Commit | Line | Data |
---|---|---|
01f4001e | 1 | import type { Worker } from 'node:worker_threads'; |
0e4fa348 JB |
2 | |
3 | import { type ErrorHandler, type ExitHandler, FixedThreadPool } from 'poolifier'; | |
8114d10e | 4 | |
268a74bb JB |
5 | import { WorkerAbstract } from './WorkerAbstract'; |
6 | import type { WorkerData, WorkerOptions } from './WorkerTypes'; | |
789871d6 | 7 | import { defaultErrorHandler, defaultExitHandler, sleep } from './WorkerUtils'; |
a4624c96 | 8 | |
268a74bb | 9 | export class WorkerStaticPool extends WorkerAbstract<WorkerData> { |
f2bf9948 | 10 | private readonly pool: FixedThreadPool<WorkerData>; |
a4624c96 JB |
11 | |
12 | /** | |
13 | * Create a new `WorkerStaticPool`. | |
14 | * | |
0e4fa348 JB |
15 | * @param workerScript - |
16 | * @param workerOptions - | |
a4624c96 | 17 | */ |
4d7227e6 JB |
18 | constructor(workerScript: string, workerOptions?: WorkerOptions) { |
19 | super(workerScript, workerOptions); | |
0e4fa348 | 20 | this.workerOptions.poolOptions.errorHandler = ( |
789871d6 | 21 | this.workerOptions?.poolOptions?.errorHandler ?? defaultErrorHandler |
0e4fa348 JB |
22 | ).bind(this) as ErrorHandler<Worker>; |
23 | this.workerOptions.poolOptions.exitHandler = ( | |
789871d6 | 24 | this.workerOptions?.poolOptions?.exitHandler ?? defaultExitHandler |
0e4fa348 JB |
25 | ).bind(this) as ExitHandler<Worker>; |
26 | this.workerOptions.poolOptions.messageHandler.bind(this); | |
e7aeea18 JB |
27 | this.pool = new FixedThreadPool( |
28 | this.workerOptions.poolMaxSize, | |
29 | this.workerScript, | |
30 | this.workerOptions.poolOptions | |
31 | ); | |
a4624c96 JB |
32 | } |
33 | ||
34 | get size(): number { | |
4597fdc5 | 35 | return this.pool.workerNodes.length; |
a4624c96 JB |
36 | } |
37 | ||
72092cfc JB |
38 | get maxElementsPerWorker(): number | undefined { |
39 | return undefined; | |
a4624c96 JB |
40 | } |
41 | ||
42 | /** | |
43 | * | |
81797102 | 44 | * @returns |
a4624c96 JB |
45 | * @public |
46 | */ | |
81797102 JB |
47 | public async start(): Promise<void> { |
48 | // This is intentional | |
49 | } | |
a4624c96 | 50 | |
ded13d97 JB |
51 | /** |
52 | * | |
81797102 | 53 | * @returns |
ded13d97 JB |
54 | * @public |
55 | */ | |
56 | public async stop(): Promise<void> { | |
57 | return this.pool.destroy(); | |
58 | } | |
59 | ||
a4624c96 JB |
60 | /** |
61 | * | |
0e4fa348 | 62 | * @param elementData - |
81797102 | 63 | * @returns |
a4624c96 JB |
64 | * @public |
65 | */ | |
c3ee95af | 66 | public async addElement(elementData: WorkerData): Promise<void> { |
a4624c96 | 67 | await this.pool.execute(elementData); |
4bfd80fa | 68 | // Start element sequentially to optimize memory at startup |
789871d6 | 69 | this.workerOptions.elementStartDelay > 0 && (await sleep(this.workerOptions.elementStartDelay)); |
a4624c96 JB |
70 | } |
71 | } |