fetch-retry.ts 6.4 KB

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