@vtex/api
Version:
VTEX I/O API client
56 lines (55 loc) • 3.06 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.addExponentialBackoffResponseInterceptor = void 0;
const retry_1 = require("../../../../../utils/retry");
function fixConfig(axiosInstance, config) {
if (axiosInstance.defaults.httpAgent === config.httpAgent) {
delete config.httpAgent;
}
if (axiosInstance.defaults.httpsAgent === config.httpsAgent) {
delete config.httpsAgent;
}
}
const exponentialDelay = (initialBackoffDelay, exponentialBackoffCoefficient, retryNumber) => {
const delay = initialBackoffDelay *
Math.pow(exponentialBackoffCoefficient, retryNumber - 1);
const randomSum = delay * 0.2 * Math.random();
return delay + randomSum;
};
// A lot of this code is based on:
// https://github.com/softonic/axios-retry/blob/ffd4327f31d063522e58c525d28d4c5053d0ea7b/es/index.js#L109
const onResponseError = (http) => (error) => {
var _a, _b, _c, _d;
if (error.config == null) {
return Promise.reject(error);
}
const config = error.config;
if (config.retries == null || config.retries === 0) {
return Promise.reject(error);
}
const { initialBackoffDelay = 200, exponentialBackoffCoefficient = 2, exponentialTimeoutCoefficient, } = config;
const retryCount = config.retryCount || 0;
const shouldRetry = (0, retry_1.isAbortedOrNetworkErrorOrRouterTimeout)(error) && retryCount < config.retries;
if (shouldRetry) {
config.retryCount = retryCount + 1;
const delay = exponentialDelay(initialBackoffDelay, exponentialBackoffCoefficient, config.retryCount);
// Axios fails merging this configuration to the default configuration because it has an issue
// with circular structures: https://github.com/mzabriskie/axios/issues/370
fixConfig(http, config);
config.timeout = exponentialTimeoutCoefficient
? config.timeout * exponentialTimeoutCoefficient
: config.timeout;
config.transformRequest = [data => data];
(_b = (_a = config.tracing) === null || _a === void 0 ? void 0 : _a.rootSpan) === null || _b === void 0 ? void 0 : _b.log({ event: "setup-request-retry" /* HttpLogEvents.SETUP_REQUEST_RETRY */, ["retry-number" /* HttpRetryLogFields.RETRY_NUMBER */]: config.retryCount, ["retry-in" /* HttpRetryLogFields.RETRY_IN */]: delay });
(_d = (_c = config.tracing) === null || _c === void 0 ? void 0 : _c.rootSpan) === null || _d === void 0 ? void 0 : _d.addTags({
["http.retry.count" /* CustomHttpTags.HTTP_RETRY_COUNT */]: config.retryCount,
["http.retry.error.code" /* CustomHttpTags.HTTP_RETRY_ERROR_CODE */]: error.code,
});
return new Promise(resolve => setTimeout(() => resolve(http(config)), delay));
}
return Promise.reject(error);
};
const addExponentialBackoffResponseInterceptor = (http) => {
http.interceptors.response.use(undefined, onResponseError(http));
};
exports.addExponentialBackoffResponseInterceptor = addExponentialBackoffResponseInterceptor;