All files / lib/libs opensearch-lib.ts

86.36% Statements 95/110
76.31% Branches 58/76
90.47% Functions 19/21
85.98% Lines 92/107

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296                            28x                 249x 249x 249x     249x     28x                       1x                         109x 38x 38x     71x   71x 71x 85x 1x   84x         72x 72x 70x                               70x     2x 1x 1x 1x   1x 1x       71x       8x 8x 8x   1x           1x                     3x 3x     3x             3x                   3x 3x                   2x   1x 1x         29x 29x       25x               86x 86x 86x 82x 82x 25x   57x   4x             4x               26x 26x 26x 26x     26x       18x 18x   18x   18x             17x 15x 14x   1x 1x     1x 1x           8x 8x 8x 7x       1x 1x                 2x 2x 2x             1x   1x 1x         13212x 4551x 4551x   1x     8661x 465x   8260x 3520x 12611x 12611x     4740x    
import { AssumeRoleCommand, STSClient } from "@aws-sdk/client-sts";
import { defaultProvider } from "@aws-sdk/credential-provider-node";
import { Client, Connection, errors as OpensearchErrors } from "@opensearch-project/opensearch";
import * as aws4 from "aws4";
import { aws4Interceptor } from "aws4-axios";
import axios from "axios";
import { opensearch } from "shared-types";
import { Document as OSDocument, ItemResult } from "shared-types/opensearch/main";
 
import { getDomainAndNamespace } from "./utils";
 
let client: Client;
 
export async function getClient(host: string) {
  return new Client({
    ...createAwsConnector(await defaultProvider()()),
    node: host,
  });
}
 
function createAwsConnector(credentials: any) {
  class AmazonConnection extends Connection {
    buildRequestObject(params: any) {
      const request = super.buildRequestObject(params);
      request.headers = request.headers || {};
      request.headers["host"] = request.hostname ?? undefined;
      // request.headers["Content-Type"] = "application/json; charset=UTF-8"; // Ensure Content-Type header is set
 
      return aws4.sign(<any>request, credentials);
    }
  }
  return {
    Connection: AmazonConnection,
  };
}
 
export async function updateData(host: string, indexObject: any) {
  client = client || (await getClient(host));
  // Add a document to the index.
  await client.update(indexObject);
}
 
function sleep(ms: number): Promise<void> {
  return new Promise((resolve) => setTimeout(resolve, ms));
}
 
interface Document {
  id: string;
  [key: string]: any;
}
 
export async function bulkUpdateData(
  host: string,
  index: string,
  arrayOfDocuments: Document[],
): Promise<void> {
  if (arrayOfDocuments.length === 0) {
    console.log("No documents to update. Skipping bulk update operation.");
    return;
  }
 
  client = client || (await getClient(host));
 
  const body: any[] = [];
  for (const doc of arrayOfDocuments) {
    if (doc.delete) {
      body.push({ delete: { _index: index, _id: doc.id } });
    } else {
      body.push({ update: { _index: index, _id: doc.id } }, { doc: doc, doc_as_upsert: true });
    }
  }
 
  async function attemptBulkUpdate(retries: number = 5, delay: number = 1000): Promise<void> {
    try {
      const response = await client.bulk({ refresh: true, body: body });
      Iif (response.body.errors) {
        // Check for 429 status within response errors
        const hasRateLimitErrors = response.body.items.some(
          (item: any) => item.update.status === 429,
        );
 
        if (hasRateLimitErrors && retries > 0) {
          console.log(`Rate limit exceeded, retrying in ${delay}ms...`);
          await sleep(delay);
          return attemptBulkUpdate(retries - 1, delay * 2); // Exponential backoff
        }
        if (!hasRateLimitErrors) {
          // Handle or throw other errors normally
          console.error("Bulk update errors:", JSON.stringify(response.body.items, null, 2));
        }
      } else {
        console.log("Bulk update successful.");
      }
    } catch (error: any) {
      if (error.statusCode === 429 && retries > 0) {
        console.log(`Rate limit exceeded, retrying in ${delay}ms...`, error.message);
        await sleep(delay);
        return attemptBulkUpdate(retries - 1, delay * 2); // Exponential backoff
      }
      console.error("An error occurred:", error);
      throw error;
    }
  }
 
  await attemptBulkUpdate();
}
 
export async function deleteIndex(host: string, index: opensearch.Index) {
  client = client || (await getClient(host));
  try {
    await client.indices.delete({ index });
  } catch (error) {
    Iif (
      error instanceof OpensearchErrors.ResponseError &&
      error.message.includes("index_not_found_exception")
    ) {
      console.log(`Index ${index} not found.  Continuing...`);
    } else {
      throw error;
    }
  }
}
 
export async function mapRole(
  host: string,
  masterRoleToAssume: string,
  osRoleName: string,
  iamRoleName: string,
) {
  try {
    const sts = new STSClient({
      region: process.env.region,
    });
    const assumedRoleCommandData = await sts.send(
      new AssumeRoleCommand({
        RoleArn: masterRoleToAssume,
        RoleSessionName: "RoleMappingSession",
        ExternalId: "foo",
      }),
    );
    const interceptor = aws4Interceptor({
      options: {
        region: process.env.region,
      },
      credentials: {
        accessKeyId: assumedRoleCommandData?.Credentials?.AccessKeyId || "",
        secretAccessKey: assumedRoleCommandData?.Credentials?.SecretAccessKey || "",
        sessionToken: assumedRoleCommandData?.Credentials?.SessionToken,
      },
    });
    axios.interceptors.request.use(interceptor);
    const patchResponse = await axios.patch(
      `${host}/_plugins/_security/api/rolesmapping/${osRoleName}`,
      [
        {
          op: "add",
          path: "/and_backend_roles",
          value: [iamRoleName],
        },
      ],
    );
    return decodeUtf8(patchResponse.data);
  } catch (error) {
    console.error("Error making PUT request:", error);
    throw error;
  }
}
 
export async function search(host: string, index: opensearch.Index, query: any) {
  client = client || (await getClient(host));
  const response = await client.search({
    index: index,
    body: query,
  });
  return decodeUtf8(response).body;
}
 
export async function getItem(
  host: string,
  index: opensearch.Index,
  id: string,
): Promise<ItemResult | undefined> {
  try {
    client = client || (await getClient(host));
    const response = await client.get({ id, index });
    const item = decodeUtf8(response).body;
    if (item.found === false || !item._source) {
      return undefined;
    }
    return item;
  } catch (error) {
    Iif (
      (error instanceof OpensearchErrors.ResponseError && error.statusCode === 404) ||
      error.meta?.statusCode === 404
    ) {
      console.log("Error (404) retrieving in OpenSearch:", error);
      return undefined;
    }
    throw error;
  }
}
export async function getItemAndThrowAllErrors(
  host: string,
  index: opensearch.Index,
  id: string,
): Promise<ItemResult | undefined> {
  client = client || (await getClient(host));
  const response = await client.get({ id, index });
  const item = decodeUtf8(response).body;
  Iif (item.found === false || !item._source) {
    return undefined;
  }
  return item;
}
 
export async function getItems(ids: string[]): Promise<OSDocument[]> {
  try {
    const { domain, index } = getDomainAndNamespace("main");
 
    client = client || (await getClient(domain));
 
    const response = await client.mget<{ docs: ItemResult[] }>({
      index,
      body: {
        ids,
      },
    });
 
    return response.body.docs.reduce<OSDocument[]>((acc, doc) => {
      if (doc && doc.found && doc._source) {
        return acc.concat(doc._source);
      }
      console.error(`Document with ID ${doc._id} not found.`);
      return acc;
    }, []);
  } catch (e) {
    console.log({ e });
    return [];
  }
}
 
// check it exists - then create
export async function createIndex(host: string, index: opensearch.Index) {
  client = client || (await getClient(host));
  try {
    const exists = await client.indices.exists({ index });
    Eif (exists.body) return;
 
    await client.indices.create({ index });
  } catch (error) {
    console.error("Error creating index:", error);
    throw error;
  }
}
 
export async function updateFieldMapping(
  host: string,
  index: opensearch.Index,
  properties: object,
) {
  client = client || (await getClient(host));
  try {
    const response = await client.indices.putMapping({
      index: index,
      body: {
        properties,
      },
    });
 
    console.log("Field mapping updated:", response);
  } catch (error) {
    console.error("Error updating field mapping:", error);
    throw error;
  }
}
 
export function decodeUtf8(data: any): any {
  if (typeof data === "string") {
    try {
      return decodeURIComponent(escape(data));
    } catch {
      return data;
    }
  }
  if (Array.isArray(data)) {
    return data.map((item) => decodeUtf8(item));
  }
  if (typeof data === "object" && data !== null) {
    return Object.keys(data).reduce((acc, key) => {
      acc[key] = decodeUtf8(data[key]);
      return acc;
    }, {} as any);
  }
  return data;
}