build-internal-reverse-chn-cidr.ts 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import { task } from './trace';
  2. import { getChnCidrPromise } from './build-chn-cidr';
  3. import Worktank from 'worktank';
  4. const pool = new Worktank({
  5. name: 'build-internal-reverse-chn-cidr',
  6. size: 1,
  7. timeout: 10000, // The maximum number of milliseconds to wait for the result from the worker, if exceeded the worker is terminated and the execution promise rejects
  8. warmup: true,
  9. autoterminate: 30000, // The interval of milliseconds at which to check if the pool can be automatically terminated, to free up resources, workers will be spawned up again if needed
  10. env: {},
  11. methods: {
  12. // eslint-disable-next-line object-shorthand -- workertank
  13. getreversedCidr: async function (cidr: string[], importMetaUrl: string): Promise<void> {
  14. // TODO: createRequire is a temporary workaround for https://github.com/nodejs/node/issues/51956
  15. const { default: module } = await import('node:module');
  16. const __require = module.createRequire(importMetaUrl);
  17. const path = __require('node:path') as typeof import('node:path');
  18. const fs = __require('fs') as typeof import('fs');
  19. const { OUTPUT_INTERNAL_DIR } = __require('./constants/dir') as typeof import('./constants/dir');
  20. const { exclude, merge } = __require('fast-cidr-tools') as typeof import('fast-cidr-tools');
  21. const { RESERVED_IPV4_CIDR, NON_CN_CIDR_INCLUDED_IN_CHNROUTE } = __require('./constants/cidr') as typeof import('./constants/cidr');
  22. const { appendArrayInPlace } = __require('foxts/append-array-in-place') as typeof import('foxts/append-array-in-place');
  23. const { fastStringArrayJoin } = __require('foxts/fast-string-array-join') as typeof import('foxts/fast-string-array-join');
  24. const outputFile = path.join(OUTPUT_INTERNAL_DIR, 'reversed-chn-cidr.txt');
  25. fs.mkdirSync(OUTPUT_INTERNAL_DIR, { recursive: true });
  26. const result = merge(
  27. appendArrayInPlace(
  28. exclude(
  29. ['0.0.0.0/0'],
  30. RESERVED_IPV4_CIDR.concat(cidr),
  31. true
  32. ),
  33. // https://github.com/misakaio/chnroutes2/issues/25
  34. NON_CN_CIDR_INCLUDED_IN_CHNROUTE
  35. ),
  36. true
  37. );
  38. fs.writeFileSync(outputFile, fastStringArrayJoin(result, '\n') + '\n', { encoding: 'utf-8' });
  39. }
  40. }
  41. });
  42. export const buildInternalReverseChnCIDR = task(require.main === module, __filename)(async (span) => {
  43. const [cidr] = await span.traceChildPromise('download chnroutes2', getChnCidrPromise());
  44. return span.traceChildAsync(
  45. 'build reversed chn cidr',
  46. async () => pool.exec(
  47. 'getreversedCidr',
  48. [cidr, import.meta.url]
  49. ).finally(() => pool.terminate())
  50. );
  51. });