fetch-retry.ts 6.5 KB

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