fetch-retry.ts 6.6 KB

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