"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const core = __importStar(require("@actions/core"));
const http_client_1 = require("@actions/http-client");
const constants_1 = require("./constants");
function isSuccessStatusCode(statusCode) {
    if (!statusCode) {
        return false;
    }
    return statusCode >= 200 && statusCode < 300;
}
exports.isSuccessStatusCode = isSuccessStatusCode;
function isServerErrorStatusCode(statusCode) {
    if (!statusCode) {
        return true;
    }
    return statusCode >= 500;
}
exports.isServerErrorStatusCode = isServerErrorStatusCode;
function isRetryableStatusCode(statusCode) {
    if (!statusCode) {
        return false;
    }
    const retryableStatusCodes = [
        http_client_1.HttpCodes.BadGateway,
        http_client_1.HttpCodes.ServiceUnavailable,
        http_client_1.HttpCodes.GatewayTimeout
    ];
    return retryableStatusCodes.includes(statusCode);
}
exports.isRetryableStatusCode = isRetryableStatusCode;
function sleep(milliseconds) {
    return __awaiter(this, void 0, void 0, function* () {
        return new Promise(resolve => setTimeout(resolve, milliseconds));
    });
}
function retry(name, method, getStatusCode, maxAttempts = constants_1.DefaultRetryAttempts, delay = constants_1.DefaultRetryDelay, onError = undefined) {
    return __awaiter(this, void 0, void 0, function* () {
        let errorMessage = '';
        let attempt = 1;
        while (attempt <= maxAttempts) {
            let response = undefined;
            let statusCode = undefined;
            let isRetryable = false;
            try {
                response = yield method();
            }
            catch (error) {
                if (onError) {
                    response = onError(error);
                }
                isRetryable = true;
                errorMessage = error.message;
            }
            if (response) {
                statusCode = getStatusCode(response);
                if (!isServerErrorStatusCode(statusCode)) {
                    return response;
                }
            }
            if (statusCode) {
                isRetryable = isRetryableStatusCode(statusCode);
                errorMessage = `Cache service responded with ${statusCode}`;
            }
            core.debug(`${name} - Attempt ${attempt} of ${maxAttempts} failed with error: ${errorMessage}`);
            if (!isRetryable) {
                core.debug(`${name} - Error is not retryable`);
                break;
            }
            yield sleep(delay);
            attempt++;
        }
        throw Error(`${name} failed: ${errorMessage}`);
    });
}
exports.retry = retry;
function retryTypedResponse(name, method, maxAttempts = constants_1.DefaultRetryAttempts, delay = constants_1.DefaultRetryDelay) {
    return __awaiter(this, void 0, void 0, function* () {
        return yield retry(name, method, (response) => response.statusCode, maxAttempts, delay, 
        // If the error object contains the statusCode property, extract it and return
        // an TypedResponse<T> so it can be processed by the retry logic.
        (error) => {
            if (error instanceof http_client_1.HttpClientError) {
                return {
                    statusCode: error.statusCode,
                    result: null,
                    headers: {},
                    error
                };
            }
            else {
                return undefined;
            }
        });
    });
}
exports.retryTypedResponse = retryTypedResponse;
function retryHttpClientResponse(name, method, maxAttempts = constants_1.DefaultRetryAttempts, delay = constants_1.DefaultRetryDelay) {
    return __awaiter(this, void 0, void 0, function* () {
        return yield retry(name, method, (response) => response.message.statusCode, maxAttempts, delay);
    });
}
exports.retryHttpClientResponse = retryHttpClientResponse;
//# sourceMappingURL=requestUtils.js.map