fetch-retry.ts 6.3 KB

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