|
| 1 | +import Worktank from 'worktank'; |
| 2 | +import os from 'node:os'; |
| 3 | +import process from 'node:process'; |
| 4 | +import type { Span } from '../trace'; |
| 5 | + |
| 6 | +const pool = new Worktank({ |
| 7 | + name: 'process-phishing-domains', |
| 8 | + size: Math.max(2, Math.max(1, ('availableParallelism' in os ? os.availableParallelism() : (os as typeof import('node:os')).cpus().length) - 1)), |
| 9 | + 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 |
| 10 | + warmup: true, |
| 11 | + 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 |
| 12 | + env: {}, |
| 13 | + methods: { |
| 14 | + // eslint-disable-next-line object-shorthand -- workertank |
| 15 | + compareAndWriteFile: async function ( |
| 16 | + linesA: string[], filePath: string, |
| 17 | + importMetaUrl: string |
| 18 | + ): Promise<void> { |
| 19 | + const { default: module } = await import('node:module'); |
| 20 | + const __require = module.createRequire(importMetaUrl); |
| 21 | + |
| 22 | + const fs = __require('fs') as typeof import('fs'); |
| 23 | + const { readFileByLine } = __require('./fetch-text-by-line') as typeof import('./fetch-text-by-line'); |
| 24 | + const { fileEqual } = __require('./create-file') as typeof import('./create-file'); |
| 25 | + const path = __require('node:path') as typeof import('node:path'); |
| 26 | + const { fastStringArrayJoin } = __require('foxts/fast-string-array-join') as typeof import('foxts/fast-string-array-join'); |
| 27 | + const picocolors = __require('picocolors') as typeof import('picocolors'); |
| 28 | + |
| 29 | + let isEqual = false; |
| 30 | + if (fs.existsSync(filePath)) { |
| 31 | + isEqual = await fileEqual(linesA, readFileByLine(filePath)); |
| 32 | + } else { |
| 33 | + console.log(`${filePath} does not exists, writing...`); |
| 34 | + isEqual = false; |
| 35 | + } |
| 36 | + |
| 37 | + if (isEqual) { |
| 38 | + console.log(picocolors.gray(picocolors.dim(`same content, bail out writing: ${filePath}`))); |
| 39 | + return; |
| 40 | + } |
| 41 | + |
| 42 | + const dir = path.dirname(filePath); |
| 43 | + if (!fs.existsSync(dir)) { |
| 44 | + fs.mkdirSync(dir, { recursive: true }); |
| 45 | + } |
| 46 | + fs.writeFileSync(filePath, fastStringArrayJoin(linesA, '\n') + '\n', { encoding: 'utf-8' }); |
| 47 | + } |
| 48 | + } |
| 49 | +}); |
| 50 | + |
| 51 | +export function compareAndWriteFileInWorker(span: Span, linesA: string[], filePath: string) { |
| 52 | + return span.traceChildAsync(`compare and write ${filePath}`, () => pool.exec('compareAndWriteFile', [linesA, filePath, import.meta.url])); |
| 53 | +} |
| 54 | + |
| 55 | +process.on('beforeExit', () => pool.terminate()); |
0 commit comments