fetch-retry.ts 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  1. import retry from 'async-retry';
  2. import picocolors from 'picocolors';
  3. import { setTimeout } from 'node:timers/promises';
  4. import {
  5. fetch as _fetch,
  6. interceptors,
  7. EnvHttpProxyAgent,
  8. setGlobalDispatcher
  9. } from 'undici';
  10. import type { Request, Response, RequestInit } from 'undici';
  11. import CacheableLookup from 'cacheable-lookup';
  12. import type { LookupOptions as CacheableLookupOptions } from 'cacheable-lookup';
  13. const cacheableLookup = new CacheableLookup();
  14. const agent = new EnvHttpProxyAgent({
  15. allowH2: true,
  16. connect: {
  17. lookup(hostname, opt, cb) {
  18. return cacheableLookup.lookup(hostname, opt as CacheableLookupOptions, cb);
  19. }
  20. }
  21. });
  22. setGlobalDispatcher(agent.compose(
  23. interceptors.retry({
  24. maxRetries: 5,
  25. minTimeout: 10000,
  26. errorCodes: ['UND_ERR_HEADERS_TIMEOUT', 'ECONNRESET', 'ECONNREFUSED', 'ENOTFOUND', 'ENETDOWN', 'ENETUNREACH', 'EHOSTDOWN', 'EHOSTUNREACH', 'EPIPE']
  27. }),
  28. interceptors.redirect({
  29. maxRedirections: 5
  30. })
  31. ));
  32. function isClientError(err: unknown): err is NodeJS.ErrnoException {
  33. if (!err || typeof err !== 'object') return false;
  34. if ('code' in err) return err.code === 'ERR_UNESCAPED_CHARACTERS';
  35. if ('message' in err) return err.message === 'Request path contains unescaped characters';
  36. if ('name' in err) return err.name === 'AbortError';
  37. return false;
  38. }
  39. export class ResponseError extends Error {
  40. readonly res: Response;
  41. readonly code: number;
  42. readonly statusCode: number;
  43. readonly url: string;
  44. constructor(res: Response) {
  45. super(res.statusText);
  46. if ('captureStackTrace' in Error) {
  47. Error.captureStackTrace(this, ResponseError);
  48. }
  49. // eslint-disable-next-line sukka/unicorn/custom-error-definition -- deliberatly use previous name
  50. this.name = this.constructor.name;
  51. this.res = res;
  52. this.code = res.status;
  53. this.statusCode = res.status;
  54. this.url = res.url;
  55. }
  56. }
  57. interface FetchRetryOpt {
  58. minTimeout?: number,
  59. retries?: number,
  60. factor?: number,
  61. maxRetryAfter?: number,
  62. // onRetry?: (err: Error) => void,
  63. retryOnNon2xx?: boolean,
  64. retryOn404?: boolean
  65. }
  66. interface FetchWithRetry {
  67. (url: string | URL | Request, opts?: RequestInit & { retry?: FetchRetryOpt }): Promise<Response>
  68. }
  69. const DEFAULT_OPT: Required<FetchRetryOpt> = {
  70. // timeouts will be [10, 60, 360, 2160, 12960]
  71. // (before randomization is added)
  72. minTimeout: 10,
  73. retries: 5,
  74. factor: 6,
  75. maxRetryAfter: 20,
  76. retryOnNon2xx: true,
  77. retryOn404: false
  78. };
  79. function createFetchRetry(fetch: typeof _fetch): FetchWithRetry {
  80. const fetchRetry: FetchWithRetry = async (url, opts = {}) => {
  81. const retryOpts = Object.assign(
  82. DEFAULT_OPT,
  83. opts.retry
  84. );
  85. try {
  86. return await retry(async (bail) => {
  87. try {
  88. // this will be retried
  89. const res = (await fetch(url, opts));
  90. if ((res.status >= 500 && res.status < 600) || res.status === 429) {
  91. // NOTE: doesn't support http-date format
  92. const retryAfterHeader = res.headers.get('retry-after');
  93. if (retryAfterHeader) {
  94. const retryAfter = Number.parseInt(retryAfterHeader, 10);
  95. if (retryAfter) {
  96. if (retryAfter > retryOpts.maxRetryAfter) {
  97. return res;
  98. }
  99. await setTimeout(retryAfter * 1e3, undefined, { ref: false });
  100. }
  101. }
  102. throw new ResponseError(res);
  103. } else {
  104. if ((!res.ok && res.status !== 304) && retryOpts.retryOnNon2xx) {
  105. throw new ResponseError(res);
  106. }
  107. return res;
  108. }
  109. } catch (err: unknown) {
  110. if (mayBailError(err)) {
  111. return bail(err) as never;
  112. };
  113. if (err instanceof AggregateError) {
  114. for (const e of err.errors) {
  115. if (mayBailError(e)) {
  116. // bail original error
  117. return bail(err) as never;
  118. };
  119. }
  120. }
  121. console.log(picocolors.gray('[fetch fail]'), url, { name: (err as any).name }, err);
  122. // Do not retry on 404
  123. if (err instanceof ResponseError && err.res.status === 404) {
  124. return bail(err) as never;
  125. }
  126. const newErr = new Error('Fetch failed');
  127. newErr.cause = err;
  128. throw newErr;
  129. }
  130. }, retryOpts);
  131. function mayBailError(err: unknown) {
  132. if (typeof err === 'object' && err !== null && 'name' in err) {
  133. if ((
  134. err.name === 'AbortError'
  135. || ('digest' in err && err.digest === 'AbortError')
  136. )) {
  137. console.log(picocolors.gray('[fetch abort]'), url);
  138. return true;
  139. }
  140. if (err.name === 'Custom304NotModifiedError') {
  141. return true;
  142. }
  143. if (err.name === 'CustomNoETagFallbackError') {
  144. return true;
  145. }
  146. }
  147. return !!(isClientError(err));
  148. };
  149. } catch (err) {
  150. if (err instanceof ResponseError) {
  151. return err.res;
  152. }
  153. throw err;
  154. }
  155. };
  156. for (const k of Object.keys(_fetch)) {
  157. const key = k as keyof typeof _fetch;
  158. fetchRetry[key] = _fetch[key];
  159. }
  160. return fetchRetry;
  161. }
  162. export const defaultRequestInit: RequestInit = {
  163. headers: {
  164. 'User-Agent': 'curl/8.9.1 (https://github.com/SukkaW/Surge)'
  165. }
  166. };
  167. export const fetchWithRetry = createFetchRetry(_fetch as any);