UNPKG

@ingestkorea/client-sens

Version:

INGESTKOREA SDK Naver Cloud Platform SENS Client for Node.js.

57 lines (56 loc) 2.74 kB
"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()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.middlewareRetry = void 0; const index_js_1 = require("../models/index.js"); const constants_js_1 = require("./constants.js"); const middlewareRetry = (next) => (input, context) => __awaiter(void 0, void 0, void 0, function* () { const MAX_RETRIES = 3; const MIN_DELAY_MS = 300; const BASE_DELAY_MS = 500; const MAX_DELAY_MS = 5000; let attempts = 0; let totalRetryDelay = 0; input.request.headers = Object.assign({}, input.request.headers); while (attempts < MAX_RETRIES) { attempts++; const requestLog = `attempt=${attempts}; max=${MAX_RETRIES}; totalRetryDelay=${totalRetryDelay}`; input.request.headers[constants_js_1.INGESTKOREA_REQUEST_LOG] = requestLog; try { const { response } = yield next(input, context); response.headers[constants_js_1.INGESTKOREA_RETRY] = attempts.toString(); response.headers[constants_js_1.INGESTKOREA_RETRY_DELAY] = totalRetryDelay.toString(); return { response }; } catch (error) { if (attempts >= MAX_RETRIES) { throw new index_js_1.SensError({ code: -1, type: "SDK.REQUEST_ERROR", message: error instanceof Error ? error.message : requestLog, }); } const exp = BASE_DELAY_MS * Math.pow(2, (attempts - 1)); const capped = Math.min(MAX_DELAY_MS, exp); const baseWait = Math.max(MIN_DELAY_MS, Math.floor(capped / 2)); const jitter = Math.floor(Math.random() * (capped - baseWait)); const delay = baseWait + jitter; totalRetryDelay += delay; yield new Promise((resolve) => setTimeout(resolve, delay)); } } throw new index_js_1.SensError({ code: -1, type: "SDK.UNKNOWN_ERROR", message: "Unexpected retry loop termination", }); }); exports.middlewareRetry = middlewareRetry;