fetch-retry.ts 7.5 KB

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