"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const axios_1 = __importDefault(require("axios"));
const Util = __importStar(require("../util"));
const logger_1 = __importDefault(require("../logger"));
const requestUtil = __importStar(require("./request_util"));
const DEFAULT_SNOWFLAKE_RETRY_CONFIG = {
    maxRetries: 7,
    sleepBase: 1,
    sleepCap: 16,
    includeRetryReason: false,
};
const axios = axios_1.default.create();
axios.interceptors.request.use((config) => {
    if (!config.useSnowflakeRetryMiddleware) {
        return config;
    }
    config.__snowflakeRetryConfig ??= {
        ...DEFAULT_SNOWFLAKE_RETRY_CONFIG,
        ...config.snowflakeRetryConfig,
    };
    config.__snowflakeRetryState ??= {
        startTime: Date.now(),
        numRetries: 0,
        currentSleepTime: 1,
    };
    return config;
});
axios.interceptors.response.use((response) => response, async (err) => {
    const config = err.config ? err.config : null;
    if (!config?.useSnowflakeRetryMiddleware) {
        return Promise.reject(err);
    }
    const isRetryable = err.response
        ? Util.isRetryableHttpError({ statusCode: err.response.status }, false)
        : err.code !== 'ERR_CANCELED'; // Network errors are retryable, but not client-canceled requests
    if (!isRetryable) {
        return Promise.reject(err);
    }
    const retryConfig = config.__snowflakeRetryConfig;
    const retryState = config.__snowflakeRetryState;
    if (retryState.numRetries < retryConfig.maxRetries) {
        const sleepTime = Util.nextSleepTime(retryConfig.sleepBase, retryConfig.sleepCap, retryState.currentSleepTime);
        retryState.currentSleepTime = sleepTime;
        retryState.numRetries++;
        // Apply tracking parameters to the url
        const url = new URL(config.url ?? '', config.baseURL);
        url.searchParams.set('clientStartTime', retryState.startTime.toString());
        url.searchParams.set('retryCount', retryState.numRetries.toString());
        if (retryConfig.includeRetryReason) {
            url.searchParams.set('retryReason', (err.response?.status ?? 0).toString());
        }
        config.url = url.toString();
        (0, logger_1.default)().debug('useSnowflakeRetryMiddleware: Retrying request%s - error=%s, attempt=%s, delay=%ss', requestUtil.describeRequestFromOptions(config), err.message, retryState.numRetries, sleepTime);
        await Util.sleep(sleepTime * 1000);
        return axios.request(config);
    }
    else {
        return Promise.reject(err);
    }
});
exports.default = axios;
//# sourceMappingURL=axios_instance.js.map