fetch-retry.ts 6.4 KB

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