fetch-retry.ts 6.5 KB

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