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