fetch-retry.ts 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  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. Dispatcher,
  10. Response,
  11. RequestInit,
  12. RequestInfo
  13. } from 'undici';
  14. import { BetterSqlite3CacheStore } from 'undici-cache-store-better-sqlite3';
  15. export type UndiciResponseData<T = unknown> = Dispatcher.ResponseData<T>;
  16. import { inspect } from 'node:util';
  17. import path from 'node:path';
  18. import fs from 'node:fs';
  19. import { CACHE_DIR } from '../constants/dir';
  20. import { isAbortErrorLike } from 'foxts/abort-error';
  21. import { isErrorLikeObject } from 'foxts/extract-error-message';
  22. if (!fs.existsSync(CACHE_DIR)) {
  23. fs.mkdirSync(CACHE_DIR, { recursive: true });
  24. }
  25. const agent = new Agent({
  26. allowH2: false
  27. }).compose(
  28. interceptors.dns({
  29. // disable IPv6
  30. dualStack: false,
  31. affinity: 4
  32. // TODO: proper cacheable-lookup, or even DoH
  33. }),
  34. interceptors.retry({
  35. maxRetries: 5,
  36. minTimeout: 500, // The initial retry delay in milliseconds
  37. maxTimeout: 10 * 1000, // The maximum retry delay in milliseconds
  38. // Undici still uses `statusCodes` as the first gate for HTTP response retries.
  39. // Our custom `retry()` callback only runs after a response status is admitted here,
  40. // so we must list our status codes here before we can read it in our retry callback.
  41. statusCodes: [404, 429, 500, 502, 503, 504],
  42. // TODO: this part of code is only for allow more errors to be retried by default
  43. // This should be removed once https://github.com/nodejs/undici/issues/3728 is implemented
  44. retry(err, { state, opts }, cb) {
  45. const errorCode = 'code' in err ? (err as NodeJS.ErrnoException).code : undefined;
  46. Object.defineProperty(err, '_url', {
  47. value: opts.method + ' ' + opts.origin?.toString() + opts.path
  48. });
  49. // Any code that is not a Undici's originated and allowed to retry
  50. if (
  51. errorCode === 'ERR_UNESCAPED_CHARACTERS'
  52. || errorCode === 'UND_ERR_DESTROYED'
  53. || err.message === 'Request path contains unescaped characters'
  54. || err.name === 'AbortError'
  55. ) {
  56. return cb(err);
  57. }
  58. const statusCode = 'statusCode' in err && typeof err.statusCode === 'number' ? err.statusCode : null;
  59. // bail out if the status code matches one of the following
  60. if (
  61. statusCode != null
  62. && (
  63. statusCode === 401 // Unauthorized, should check credentials instead of retrying
  64. || statusCode === 403 // Forbidden, should check permissions instead of retrying
  65. // || statusCode === 404 // Not Found, should check URL instead of retrying
  66. || statusCode === 405 // Method Not Allowed, should check method instead of retrying
  67. )
  68. ) {
  69. return cb(err);
  70. }
  71. const origin = opts.origin?.toString();
  72. if (statusCode === 404) {
  73. if (origin?.includes('cdn.jsdelivr.net')) {
  74. // continue retry anyway, jsDelivr has recently broken and return HTTP 404 for bad origin
  75. } else {
  76. return cb(err);
  77. }
  78. }
  79. // if (errorCode === 'UND_ERR_REQ_RETRY') {
  80. // return cb(err);
  81. // }
  82. const {
  83. maxRetries = 5,
  84. minTimeout = 500,
  85. maxTimeout = 10 * 1000,
  86. timeoutFactor = 2,
  87. methods = ['GET', 'HEAD', 'OPTIONS', 'PUT', 'DELETE', 'TRACE']
  88. } = opts.retryOptions || {};
  89. // If we reached the max number of retries
  90. if (state.counter > maxRetries) {
  91. return cb(err);
  92. }
  93. // If a set of method are provided and the current method is not in the list
  94. if (Array.isArray(methods) && !methods.includes(opts.method)) {
  95. return cb(err);
  96. }
  97. const headers = ('headers' in err && typeof err.headers === 'object') ? err.headers : undefined;
  98. const retryAfterHeader = (headers as Record<string, string> | null | undefined)?.['retry-after'];
  99. let retryAfter = -1;
  100. if (retryAfterHeader) {
  101. retryAfter = Number(retryAfterHeader);
  102. retryAfter = Number.isNaN(retryAfter)
  103. ? calculateRetryAfterHeader(retryAfterHeader)
  104. : retryAfter * 1e3; // Retry-After is in seconds
  105. }
  106. const retryTimeout = retryAfter > 0
  107. ? Math.min(retryAfter, maxTimeout)
  108. : Math.min(minTimeout * (timeoutFactor ** (state.counter - 1)), maxTimeout);
  109. console.log('[fetch retry]', 'schedule retry', { statusCode, retryTimeout, errorCode, url: opts.origin });
  110. // eslint-disable-next-line sukka/prefer-timer-id -- won't leak
  111. setTimeout(() => cb(null), retryTimeout);
  112. }
  113. // errorCodes: ['UND_ERR_HEADERS_TIMEOUT', 'ECONNRESET', 'ECONNREFUSED', 'ENOTFOUND', 'ENETDOWN', 'ENETUNREACH', 'EHOSTDOWN', 'EHOSTUNREACH', 'EPIPE', 'ETIMEDOUT']
  114. }),
  115. interceptors.redirect({
  116. maxRedirections: 5
  117. }),
  118. interceptors.cache({
  119. store: new BetterSqlite3CacheStore({
  120. loose: true,
  121. location: path.join(CACHE_DIR, 'undici-better-sqlite3-cache-store.db'),
  122. maxCount: 128,
  123. maxEntrySize: 1024 * 1024 * 100 // 100 MiB
  124. }),
  125. cacheByDefault: 600 // 10 minutes
  126. })
  127. );
  128. function calculateRetryAfterHeader(retryAfter: string) {
  129. const current = Date.now();
  130. return new Date(retryAfter).getTime() - current;
  131. }
  132. export class ResponseError<T extends UndiciResponseData | Response> extends Error {
  133. readonly code: number;
  134. readonly statusCode: number;
  135. readonly url: string;
  136. constructor(public readonly res: T, public readonly info: RequestInfo, ...args: any[]) {
  137. const statusCode = 'statusCode' in res ? res.statusCode : res.status;
  138. super('HTTP ' + statusCode + ' ' + args.map(_ => inspect(_)).join(' '));
  139. this.url = typeof info === 'string'
  140. ? info
  141. : ('url' in info
  142. ? info.url
  143. : info.href);
  144. // eslint-disable-next-line sukka/unicorn/custom-error-definition -- deliberatly use previous name
  145. this.name = this.constructor.name;
  146. this.res = res;
  147. this.code = statusCode;
  148. this.statusCode = statusCode;
  149. }
  150. }
  151. export const defaultRequestInit = {
  152. headers: {
  153. 'User-Agent': 'node-fetch'
  154. }
  155. };
  156. export async function $$fetch(url: RequestInfo, init: RequestInit = defaultRequestInit) {
  157. init.dispatcher = agent;
  158. try {
  159. const res = await undici.fetch(url, init);
  160. if (res.status >= 400) {
  161. throw new ResponseError(res, url);
  162. }
  163. if ((res.status < 200 || res.status > 299) && res.status !== 304) {
  164. throw new ResponseError(res, url);
  165. }
  166. return res;
  167. } catch (err: unknown) {
  168. if (isAbortErrorLike(err)) {
  169. console.log(picocolors.gray('[fetch abort]'), url);
  170. } else {
  171. console.log(picocolors.gray('[fetch fail]'), url, err);
  172. }
  173. throw err;
  174. }
  175. }
  176. export { $$fetch as '~fetch' };
  177. /**
  178. * dohdec constructs its own `Request` object for its `hooks` from `globalThis.Request`
  179. *
  180. * But we are using `undici.fetch` instead of `globalThis.fetch`, hence the version
  181. * mismatch.
  182. *
  183. * undici, on the other hand, use `instanceof Request` internally for narrowing, resulting
  184. * in it treats foreign `Request` objects as `URL` and try to parse them as URLs, causing
  185. * `TypeError: Failed to construct 'URL': [object Request]`
  186. *
  187. * See also https://github.com/nodejs/undici/issues/2155
  188. *
  189. * We already know that dohdec will only pass one `Request` object to `fetch` because
  190. * of its internal `hooks`:
  191. *
  192. * https://github.com/hildjj/dohdec/blob/d2f763db62d46f505d109be12bc697224cd42f93/pkg/dohdec/lib/doh.js#L291
  193. */
  194. export async function fetchForDoH(input: RequestInfo, _init?: RequestInit) {
  195. if (typeof input === 'object' && 'url' in input) {
  196. // Read body as ArrayBuffer before re-wrapping. The original body is a ReadableStream
  197. // from a foreign context (different undici instance / Node.js globals). Passing it
  198. // directly to new UndiciRequest fails undici's instanceof ReadableStream check and
  199. // silently drops the body. ArrayBuffer is a plain value with no cross-context issues,
  200. // and also allows the retry interceptor to re-send the body on retries.
  201. const body = input.body === null ? null : await input.arrayBuffer();
  202. input = new UndiciRequest(input.url, {
  203. method: input.method,
  204. mode: input.mode,
  205. credentials: input.credentials,
  206. cache: input.cache,
  207. redirect: input.redirect,
  208. integrity: input.integrity,
  209. keepalive: input.keepalive,
  210. signal: input.signal,
  211. headers: input.headers,
  212. body,
  213. referrer: '',
  214. referrerPolicy: 'no-referrer',
  215. dispatcher: agent
  216. });
  217. }
  218. // DoH servers may return a valid DNS wire format body with a non-200 status
  219. // (e.g. 503 with a DNS SERVFAIL). Let the DoH client parse the body and decide
  220. // — never throw on HTTP status here.
  221. return undici.fetch(input);
  222. }
  223. /** @deprecated -- undici.requests doesn't support gzip/br/deflate, and has difficulty w/ undidi cache */
  224. export async function requestWithLog(url: string, opt?: Parameters<typeof undici.request>[1]) {
  225. opt ??= {};
  226. opt.dispatcher = agent;
  227. try {
  228. const res = await undici.request(url, opt);
  229. if (res.statusCode >= 400) {
  230. throw new ResponseError(res, url);
  231. }
  232. if ((res.statusCode < 200 || res.statusCode > 299) && res.statusCode !== 304) {
  233. throw new ResponseError(res, url);
  234. }
  235. return res;
  236. } catch (err: unknown) {
  237. if (isAbortErrorLike(err)) {
  238. console.log(picocolors.gray('[fetch abort]'), url);
  239. } else {
  240. console.log(picocolors.gray('[fetch fail]'), url, { name: isErrorLikeObject(err) ? err.name : undefined }, err);
  241. }
  242. throw err;
  243. }
  244. }