fetch-retry.ts 6.4 KB

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