@elastic.io/component-commons-library
Version:
Library for most common component development cases
99 lines (98 loc) • 4.98 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getFacelessRetriesCount = exports.axiosReqWithRetryOnServerError = exports.getErrMsg = exports.exponentialSleep = exports.sleep = exports.exponentialDelay = exports.getRetryOptions = exports.API_REQUEST_TIMEOUT = exports.API_RETRIES_COUNT = void 0;
const axios_1 = __importDefault(require("axios"));
const logger_1 = require("../logger/logger");
exports.API_RETRIES_COUNT = {
minValue: 0,
defaultValue: 3,
maxValue: 5
};
const ENV_API_RETRIES_COUNT = process.env.API_RETRIES_COUNT ? parseInt(process.env.API_RETRIES_COUNT, 10) : exports.API_RETRIES_COUNT.defaultValue;
exports.API_REQUEST_TIMEOUT = {
minValue: 500,
defaultValue: 15000,
maxValue: 120000
};
/**
* if values are higher or lower the limit - they'll be overwritten.
* returns valid values for RetryOptions
*/
const getRetryOptions = () => {
const ENV_API_REQUEST_TIMEOUT = process.env.API_REQUEST_TIMEOUT ? parseInt(process.env.API_REQUEST_TIMEOUT, 10) : exports.API_REQUEST_TIMEOUT.defaultValue;
return {
retriesCount: (ENV_API_RETRIES_COUNT > exports.API_RETRIES_COUNT.maxValue || ENV_API_RETRIES_COUNT < exports.API_RETRIES_COUNT.minValue)
? exports.API_RETRIES_COUNT.defaultValue
: ENV_API_RETRIES_COUNT,
requestTimeout: (ENV_API_REQUEST_TIMEOUT > exports.API_REQUEST_TIMEOUT.maxValue || ENV_API_REQUEST_TIMEOUT < exports.API_REQUEST_TIMEOUT.minValue)
? exports.API_REQUEST_TIMEOUT.defaultValue
: ENV_API_REQUEST_TIMEOUT
};
};
exports.getRetryOptions = getRetryOptions;
const exponentialDelay = (currentRetries) => {
const maxBackoff = 15000;
const delay = (2 ** currentRetries) * 100;
const randomSum = delay * 0.2 * Math.random(); // 0-20% of the delay
return Math.min(delay + randomSum, maxBackoff);
};
exports.exponentialDelay = exponentialDelay;
const sleep = async (ms) => new Promise((resolve) => {
setTimeout(resolve, ms);
});
exports.sleep = sleep;
const exponentialSleep = async (currentRetries) => (0, exports.sleep)((0, exports.exponentialDelay)(currentRetries));
exports.exponentialSleep = exponentialSleep;
const getErrMsg = (errResponse) => {
const statusText = (errResponse === null || errResponse === void 0 ? void 0 : errResponse.statusText) || 'unknown';
const status = (errResponse === null || errResponse === void 0 ? void 0 : errResponse.status) || 'unknown';
const data = (errResponse === null || errResponse === void 0 ? void 0 : errResponse.data) || 'no body found';
return `Got error "${statusText}", status - "${status}", body: ${JSON.stringify(data)}`;
};
exports.getErrMsg = getErrMsg;
const axiosReqWithRetryOnServerError = async function (options, axiosInstance = axios_1.default, logger = (0, logger_1.getLogger)()) {
var _a;
const { retriesCount, requestTimeout } = (0, exports.getRetryOptions)();
let response;
let currentRetry = 0;
let error;
const loggerInstance = (this === null || this === void 0 ? void 0 : this.logger) || logger;
while (currentRetry < retriesCount) {
try {
response = await axiosInstance.request({
...options,
timeout: requestTimeout,
validateStatus: (status) => { var _a; return (status >= 200 && status < 300) || (status === 404 && ((_a = this === null || this === void 0 ? void 0 : this.cfg) === null || _a === void 0 ? void 0 : _a.doNotThrow404)); }
});
return response;
}
catch (err) {
loggerInstance.error(err.response ? (0, exports.getErrMsg)(err.response) : err.message);
error = err;
if (((_a = err.response) === null || _a === void 0 ? void 0 : _a.status) < 500) {
throw error;
}
loggerInstance.info(`URL: "${options.url}", method: ${options.method}, Error message: "${err.message}"`);
loggerInstance.info(`Request failed, retrying(${1 + currentRetry})`);
await (0, exports.exponentialSleep)(currentRetry);
currentRetry++;
}
}
throw error;
};
exports.axiosReqWithRetryOnServerError = axiosReqWithRetryOnServerError;
const getFacelessRetriesCount = () => {
const FACELESS_RETRIES_COUNT = {
minValue: 0,
defaultValue: 3,
maxValue: 5,
};
const ENV_FACELESS_RETRIES_COUNT = process.env.FACELESS_RETRIES_COUNT ? parseInt(process.env.FACELESS_RETRIES_COUNT, 10) : FACELESS_RETRIES_COUNT.defaultValue;
return (ENV_FACELESS_RETRIES_COUNT > FACELESS_RETRIES_COUNT.maxValue || ENV_FACELESS_RETRIES_COUNT < FACELESS_RETRIES_COUNT.minValue)
? FACELESS_RETRIES_COUNT.defaultValue
: ENV_FACELESS_RETRIES_COUNT;
};
exports.getFacelessRetriesCount = getFacelessRetriesCount;