"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.wrapErrorIfNeeded = exports.wrapErrorAndRejectPromise = exports.retryOnError = exports.mergeAndAppendArrays = exports.EndpointDataLoadingError = void 0; var _lodash = require("lodash"); var _toolingLog = require("@kbn/tooling-log"); /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ class EndpointDataLoadingError extends Error { constructor(message, meta) { super(message); this.meta = meta; } } exports.EndpointDataLoadingError = EndpointDataLoadingError; const wrapErrorIfNeeded = error => error instanceof EndpointDataLoadingError ? error : new EndpointDataLoadingError(error.message, error); // Use it in Promise's `.catch()` as `.catch(wrapErrorAndRejectPromise)` exports.wrapErrorIfNeeded = wrapErrorIfNeeded; const wrapErrorAndRejectPromise = error => Promise.reject(wrapErrorIfNeeded(error)); exports.wrapErrorAndRejectPromise = wrapErrorAndRejectPromise; const mergeAndAppendArrays = (destinationObj, srcObj) => { const customizer = (objValue, srcValue) => { if (Array.isArray(objValue)) { return objValue.concat(srcValue); } }; return (0, _lodash.mergeWith)(destinationObj, srcObj, customizer); }; /** * Call the provided `callback` and retry that call if it fails and the error in the failure * contains one of the `errors` provided. * @param callback * @param errors * @param tryCount * @param interval * @param logger */ exports.mergeAndAppendArrays = mergeAndAppendArrays; const retryOnError = async (callback, errors, logger, tryCount = 5, interval = 10000) => { const log = logger !== null && logger !== void 0 ? logger : new _toolingLog.ToolingLog({ writeTo: { write(_) {} }, level: 'silent' }); const msg = message => `retryOnError(): ${message}`; const isRetryableError = err => { return errors.some(retryMessage => { if (typeof retryMessage === 'string') { return err.message.includes(retryMessage); } else { return retryMessage.test(err.message); } }); }; let attempt = 1; let responsePromise; while (attempt <= tryCount) { const thisAttempt = attempt; attempt++; log.info(msg(`attempt ${thisAttempt} started at: ${new Date().toISOString()}`)); try { responsePromise = callback(); // store promise so that if it fails and no more attempts, we return the last failure return await responsePromise; } catch (err) { log.info(msg(`attempt ${thisAttempt} failed with: ${err.message}`), err); // If not an error that is retryable, then end loop here and return that error; if (!isRetryableError(err)) { log.error(err); return Promise.reject(err); } } await new Promise(resolve => setTimeout(resolve, interval)); } // @ts-expect-error TS2454: Variable 'responsePromise' is used before being assigned. return responsePromise; }; exports.retryOnError = retryOnError;