diff --git a/lib/config.ts b/lib/config.ts index 03f2c9efaac9fb..fda6dd0369522c 100644 --- a/lib/config.ts +++ b/lib/config.ts @@ -39,8 +39,8 @@ export type Config = { port?: string; auth?: string; url_regex: string; + strategy: 'on_retry' | 'all'; }; - proxyStrategy: string; pacUri?: string; pacScript?: string; accessKey?: string; @@ -399,8 +399,8 @@ const calculateValue = () => { port: envs.PROXY_PORT, auth: envs.PROXY_AUTH, url_regex: envs.PROXY_URL_REGEX || '.*', + strategy: envs.PROXY_STRATEGY || 'all', // all / on_retry }, - proxyStrategy: envs.PROXY_STRATEGY || 'all', // all / on_retry pacUri: envs.PAC_URI, pacScript: envs.PAC_SCRIPT, // access control diff --git a/lib/routes/test/index.ts b/lib/routes/test/index.ts index 8cba7553c45850..789a991b65670c 100644 --- a/lib/routes/test/index.ts +++ b/lib/routes/test/index.ts @@ -23,7 +23,7 @@ async function handler(ctx) { if (ctx.req.param('id') === 'httperror') { await got({ method: 'get', - url: 'https://httpbingo.org/status/404', + url: 'https://httpbingo.org/status/429', }); } if (ctx.req.param('id') === 'config-not-found-error') { diff --git a/lib/utils/ofetch.ts b/lib/utils/ofetch.ts index a90aa18112e5de..979f21cc2db976 100644 --- a/lib/utils/ofetch.ts +++ b/lib/utils/ofetch.ts @@ -6,6 +6,15 @@ const rofetch = createFetch().create({ retry: config.requestRetry, retryDelay: 1000, // timeout: config.requestTimeout, + onResponseError({ request, options }) { + if (options.retry) { + logger.warn(`Request ${request} remaining retry attempts: ${options.retry}`); + if (!options.headers) { + options.headers = {}; + } + options.headers['x-retry'] = options.retry; + } + }, onRequestError({ request, error }) { logger.error(`Request ${request} fail: ${error}`); }, diff --git a/lib/utils/request-rewriter/fetch.ts b/lib/utils/request-rewriter/fetch.ts index b113b26e3dfccd..491cf299df0ca0 100644 --- a/lib/utils/request-rewriter/fetch.ts +++ b/lib/utils/request-rewriter/fetch.ts @@ -40,8 +40,14 @@ const wrappedFetch: typeof undici.fetch = async (input: RequestInfo, init?: Requ } } + let isRetry = false; + if (request.headers.get('x-retry')) { + isRetry = true; + request.headers.delete('x-retry'); + } + // proxy - if (!options.dispatcher && proxy.dispatcher) { + if (!options.dispatcher && proxy.dispatcher && (proxy.proxyObj.strategy !== 'on_retry' || isRetry)) { const proxyRegex = new RegExp(proxy.proxyObj.url_regex); let urlHandler; try {