fetch-assets.ts 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import picocolors from 'picocolors';
  2. import { $$fetch, defaultRequestInit, ResponseError } from './fetch-retry';
  3. import { waitWithAbort } from 'foxts/wait';
  4. import { nullthrow } from 'foxts/guard';
  5. import { TextLineStream } from 'foxts/text-line-stream';
  6. import { ProcessLineStream } from './process-line';
  7. import { AdGuardFilterIgnoreUnsupportedLinesStream } from './parse-filter/filters';
  8. import { appendArrayInPlace } from 'foxts/append-array-in-place';
  9. import { newQueue } from '@henrygd/queue';
  10. import { AbortError } from 'foxts/abort-error';
  11. const reusedCustomAbortError = new AbortError();
  12. const queue = newQueue(16);
  13. export async function fetchAssets(
  14. url: string, fallbackUrls: null | undefined | string[] | readonly string[],
  15. processLine = false, allowEmpty = false, filterAdGuardUnsupportedLines = false
  16. ) {
  17. const controller = new AbortController();
  18. const createFetchFallbackPromise = async (url: string, index: number) => {
  19. if (index >= 0) {
  20. // To avoid wasting bandwidth, we will wait for a few time before downloading from the fallback URL.
  21. try {
  22. await waitWithAbort(1800 + (index + 1) * 1200, controller.signal);
  23. } catch {
  24. console.log(picocolors.gray('[fetch cancelled early]'), picocolors.gray(url));
  25. throw reusedCustomAbortError;
  26. }
  27. }
  28. if (controller.signal.aborted) {
  29. console.log(picocolors.gray('[fetch cancelled]'), picocolors.gray(url));
  30. throw reusedCustomAbortError;
  31. }
  32. if (index >= 0) {
  33. console.log(picocolors.yellowBright('[fetch fallback begin]'), picocolors.gray(url));
  34. }
  35. // we don't queue add here
  36. const res = await $$fetch(url, { signal: controller.signal, ...defaultRequestInit });
  37. let stream = nullthrow(res.body, url + ' has an empty body')
  38. .pipeThrough(new TextDecoderStream())
  39. .pipeThrough(new TextLineStream({ skipEmptyLines: processLine }));
  40. if (processLine) {
  41. stream = stream.pipeThrough(new ProcessLineStream());
  42. }
  43. if (filterAdGuardUnsupportedLines) {
  44. stream = stream.pipeThrough(new AdGuardFilterIgnoreUnsupportedLinesStream());
  45. }
  46. // we does queue during downloading
  47. const arr = await queue.add(() => Array.fromAsync(stream));
  48. if (arr.length < 1 && !allowEmpty) {
  49. throw new ResponseError(res, url, 'empty response w/o 304');
  50. }
  51. controller.abort();
  52. return arr;
  53. };
  54. const primaryPromise = createFetchFallbackPromise(url, -1);
  55. if (!fallbackUrls || fallbackUrls.length === 0) {
  56. return primaryPromise;
  57. }
  58. return Promise.any(
  59. appendArrayInPlace(
  60. [primaryPromise],
  61. fallbackUrls.map(createFetchFallbackPromise)
  62. )
  63. );
  64. }