fetch-retry.ts 6.7 KB

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