All files / lib/libs opensearch-lib.ts

87.87% Statements 116/132
71.56% Branches 73/102
91.3% Functions 21/23
87.69% Lines 114/130

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 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362                                          62x 5x 5x             4x     1x     62x 5x 5x 4x     1x       50x                 845x   845x     845x 845x   845x     845x     50x                       1x                         192x 113x 113x     79x   79x 79x 105x 1x   104x         80x 80x 78x                                   78x     2x 1x 1x 1x   1x 1x       79x       32x 32x 32x   3x           3x                     3x 3x       3x             3x                   3x 3x                   2x   1x 1x             521x 521x       506x               157x 157x 157x 151x 151x 45x   106x     6x                     6x             6x               27x 27x 27x 27x     27x       18x 18x   18x   18x             17x 15x 14x   1x 1x     1x 1x           11x 11x 11x 10x       1x 1x                 3x 3x 3x             2x   1x 1x         35532x 19922x 19922x   1x     15610x 7311x   8299x 8299x 1x   8298x 1363x 1363x 1363x 2976x   1363x   6935x 6935x 6935x 31868x 31868x      
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 type { OutgoingHttpHeaders } from "http";
import { opensearch } from "shared-types";
import { Document as OSDocument, ItemResult } from "shared-types/opensearch/main";
 
import { getDomainAndNamespace } from "./utils";
 
let client: Client;
 
type AwsSdkLogger = {
  debug: (...content: any[]) => void;
  info: (...content: any[]) => void;
  warn: (...content: any[]) => void;
  error: (...content: any[]) => void;
};
 
const isAwsSdkLogger = (logger: unknown): logger is AwsSdkLogger => {
  const candidate = logger as Partial<AwsSdkLogger> | undefined;
  if (
    candidate &&
    typeof candidate.debug === "function" &&
    typeof candidate.info === "function" &&
    typeof candidate.warn === "function" &&
    typeof candidate.error === "function"
  ) {
    return true;
  }
 
  return false;
};
 
export const getAwsSdkLogger = (): AwsSdkLogger => {
  const logger = (globalThis as { logger?: unknown }).logger;
  if (isAwsSdkLogger(logger)) {
    return logger;
  }
 
  return console;
};
 
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);
      const headers: Record<string, string | string[] | undefined> =
        request.headers && !Array.isArray(request.headers)
          ? { ...(request.headers as Record<string, string | string[] | undefined>) }
          : {};
      Eif (typeof request.hostname === "string") {
        headers.host = request.hostname;
      }
      request.headers = headers as OutgoingHttpHeaders;
      // 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.
  return 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.adminChangeType === "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) => {
          // Check both update and delete operations for rate limit errors
          const operation = item.update || item.delete;
          return operation?.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,
      logger: getAwsSdkLogger(),
    });
    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;
  }
}
 
type SearchIndex = opensearch.Index | `${opensearch.Index},${opensearch.Index}`;
 
export async function search(host: string, index: SearchIndex, 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) {
    const statusCode =
      error instanceof OpensearchErrors.ResponseError
        ? error.statusCode
        : typeof error === "object" &&
            error !== null &&
            "meta" in error &&
            typeof error.meta === "object" &&
            error.meta !== null &&
            "statusCode" in error.meta
          ? (error.meta.statusCode as number | undefined)
          : undefined;
 
    Iif (
      (error instanceof OpensearchErrors.ResponseError && error.statusCode === 404) ||
      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, seen = new WeakMap<object, unknown>()): any {
  if (typeof data === "string") {
    try {
      return decodeURIComponent(escape(data));
    } catch {
      return data;
    }
  }
  if (data === null || typeof data !== "object") {
    return data;
  }
  const cached = seen.get(data);
  if (cached) {
    return cached;
  }
  if (Array.isArray(data)) {
    const decodedItems: unknown[] = [];
    seen.set(data, decodedItems);
    data.forEach((item) => {
      decodedItems.push(decodeUtf8(item, seen));
    });
    return decodedItems;
  }
  const decodedObject: Record<string, unknown> = {};
  seen.set(data, decodedObject);
  return Object.keys(data).reduce((acc, key) => {
    acc[key] = decodeUtf8(data[key], seen);
    return acc;
  }, decodedObject);
}