fetch-retry.ts 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. import picocolors from 'picocolors';
  2. import undici, {
  3. interceptors,
  4. Agent,
  5. setGlobalDispatcher
  6. } from 'undici';
  7. import type {
  8. Dispatcher,
  9. Response
  10. } from 'undici';
  11. export type UndiciResponseData<T = unknown> = Dispatcher.ResponseData<T>;
  12. import { inspect } from 'node:util';
  13. const agent = new Agent({});
  14. setGlobalDispatcher(agent.compose(
  15. interceptors.retry({
  16. maxRetries: 5,
  17. minTimeout: 500, // The initial retry delay in milliseconds
  18. maxTimeout: 10 * 1000, // The maximum retry delay in milliseconds
  19. // TODO: this part of code is only for allow more errors to be retried by default
  20. // This should be removed once https://github.com/nodejs/undici/issues/3728 is implemented
  21. retry(err, { state, opts }, cb) {
  22. const statusCode = 'statusCode' in err && typeof err.statusCode === 'number' ? err.statusCode : null;
  23. const errorCode = 'code' in err ? (err as NodeJS.ErrnoException).code : undefined;
  24. const headers = ('headers' in err && typeof err.headers === 'object') ? err.headers : undefined;
  25. const { counter } = state;
  26. // Any code that is not a Undici's originated and allowed to retry
  27. if (
  28. errorCode === 'ERR_UNESCAPED_CHARACTERS'
  29. || err.message === 'Request path contains unescaped characters'
  30. || err.name === 'AbortError'
  31. ) {
  32. return cb(err);
  33. }
  34. // if (errorCode === 'UND_ERR_REQ_RETRY') {
  35. // return cb(err);
  36. // }
  37. const { method, retryOptions = {} } = opts;
  38. const {
  39. maxRetries = 5,
  40. minTimeout = 500,
  41. maxTimeout = 10 * 1000,
  42. timeoutFactor = 2,
  43. methods = ['GET', 'HEAD', 'OPTIONS', 'PUT', 'DELETE', 'TRACE']
  44. } = retryOptions;
  45. // If we reached the max number of retries
  46. if (counter > maxRetries) {
  47. return cb(err);
  48. }
  49. // If a set of method are provided and the current method is not in the list
  50. if (Array.isArray(methods) && !methods.includes(method)) {
  51. return cb(err);
  52. }
  53. // bail out if the status code matches one of the following
  54. if (
  55. statusCode != null
  56. && (
  57. statusCode === 401 // Unauthorized, should check credentials instead of retrying
  58. || statusCode === 403 // Forbidden, should check permissions instead of retrying
  59. || statusCode === 404 // Not Found, should check URL instead of retrying
  60. || statusCode === 405 // Method Not Allowed, should check method instead of retrying
  61. )
  62. ) {
  63. return cb(err);
  64. }
  65. const retryAfterHeader = (headers as Record<string, string> | null | undefined)?.['retry-after'];
  66. let retryAfter = -1;
  67. if (retryAfterHeader) {
  68. retryAfter = Number(retryAfterHeader);
  69. retryAfter = Number.isNaN(retryAfter)
  70. ? calculateRetryAfterHeader(retryAfterHeader)
  71. : retryAfter * 1e3; // Retry-After is in seconds
  72. }
  73. const retryTimeout
  74. = retryAfter > 0
  75. ? Math.min(retryAfter, maxTimeout)
  76. : Math.min(minTimeout * (timeoutFactor ** (counter - 1)), maxTimeout);
  77. console.log('[fetch retry]', 'schedule retry', { statusCode, retryTimeout, errorCode, url: opts.origin });
  78. // eslint-disable-next-line sukka/prefer-timer-id -- won't leak
  79. setTimeout(() => cb(null), retryTimeout);
  80. }
  81. // errorCodes: ['UND_ERR_HEADERS_TIMEOUT', 'ECONNRESET', 'ECONNREFUSED', 'ENOTFOUND', 'ENETDOWN', 'ENETUNREACH', 'EHOSTDOWN', 'EHOSTUNREACH', 'EPIPE', 'ETIMEDOUT']
  82. }),
  83. interceptors.redirect({
  84. maxRedirections: 5
  85. })
  86. ));
  87. function calculateRetryAfterHeader(retryAfter: string) {
  88. const current = Date.now();
  89. return new Date(retryAfter).getTime() - current;
  90. }
  91. export class ResponseError<T extends UndiciResponseData | Response> extends Error {
  92. readonly code: number;
  93. readonly statusCode: number;
  94. constructor(public readonly res: T, public readonly url: string, ...args: any[]) {
  95. const statusCode = 'statusCode' in res ? res.statusCode : res.status;
  96. super('HTTP ' + statusCode + ' ' + args.map(_ => inspect(_)).join(' '));
  97. if ('captureStackTrace' in Error) {
  98. Error.captureStackTrace(this, ResponseError);
  99. }
  100. // eslint-disable-next-line sukka/unicorn/custom-error-definition -- deliberatly use previous name
  101. this.name = this.constructor.name;
  102. this.res = res;
  103. this.code = statusCode;
  104. this.statusCode = statusCode;
  105. }
  106. }
  107. export const defaultRequestInit = {
  108. headers: {
  109. 'User-Agent': 'curl/8.9.1 (https://github.com/SukkaW/Surge)'
  110. }
  111. };
  112. // export async function fetchWithLog(url: string, init?: RequestInit) {
  113. // try {
  114. // const res = await undici.fetch(url, init);
  115. // if (res.status >= 400) {
  116. // throw new ResponseError(res, url);
  117. // }
  118. // if (!(res.status >= 200 && res.status <= 299) && res.status !== 304) {
  119. // throw new ResponseError(res, url);
  120. // }
  121. // return res;
  122. // } catch (err: unknown) {
  123. // if (typeof err === 'object' && err !== null && 'name' in err) {
  124. // if ((
  125. // err.name === 'AbortError'
  126. // || ('digest' in err && err.digest === 'AbortError')
  127. // )) {
  128. // console.log(picocolors.gray('[fetch abort]'), url);
  129. // }
  130. // } else {
  131. // console.log(picocolors.gray('[fetch fail]'), url, { name: (err as any).name }, err);
  132. // }
  133. // throw err;
  134. // }
  135. // }
  136. export async function requestWithLog(url: string, opt?: Parameters<typeof undici.request>[1]) {
  137. try {
  138. const res = await undici.request(url, opt);
  139. if (res.statusCode >= 400) {
  140. throw new ResponseError(res, url);
  141. }
  142. if (!(res.statusCode >= 200 && res.statusCode <= 299) && res.statusCode !== 304) {
  143. throw new ResponseError(res, url);
  144. }
  145. return res;
  146. } catch (err: unknown) {
  147. if (typeof err === 'object' && err !== null && 'name' in err) {
  148. if ((
  149. err.name === 'AbortError'
  150. || ('digest' in err && err.digest === 'AbortError')
  151. )) {
  152. console.log(picocolors.gray('[fetch abort]'), url);
  153. }
  154. } else {
  155. console.log(picocolors.gray('[fetch fail]'), url, { name: (err as any).name }, err);
  156. }
  157. throw err;
  158. }
  159. }