Commit | Line | Data |
---|---|---|
66a7748d | 1 | import type { EventEmitterAsyncResource } from 'node:events' |
2b59e7f7 | 2 | |
66a7748d | 3 | import { FixedThreadPool, type PoolInfo } from 'poolifier' |
8114d10e | 4 | |
66a7748d JB |
5 | import { WorkerAbstract } from './WorkerAbstract.js' |
6 | import type { WorkerData, WorkerOptions } from './WorkerTypes.js' | |
7 | import { randomizeDelay, sleep } from './WorkerUtils.js' | |
a4624c96 | 8 | |
1d8f226b | 9 | export class WorkerFixedPool extends WorkerAbstract<WorkerData> { |
66a7748d | 10 | private readonly pool: FixedThreadPool<WorkerData> |
a4624c96 JB |
11 | |
12 | /** | |
1d8f226b | 13 | * Creates a new `WorkerFixedPool`. |
a4624c96 | 14 | * |
0e4fa348 JB |
15 | * @param workerScript - |
16 | * @param workerOptions - | |
a4624c96 | 17 | */ |
66a7748d JB |
18 | constructor (workerScript: string, workerOptions: WorkerOptions) { |
19 | super(workerScript, workerOptions) | |
e7aeea18 JB |
20 | this.pool = new FixedThreadPool( |
21 | this.workerOptions.poolMaxSize, | |
22 | this.workerScript, | |
66a7748d JB |
23 | this.workerOptions.poolOptions |
24 | ) | |
a4624c96 JB |
25 | } |
26 | ||
66a7748d JB |
27 | get info (): PoolInfo { |
28 | return this.pool.info | |
b779c0f8 JB |
29 | } |
30 | ||
66a7748d JB |
31 | get size (): number { |
32 | return this.pool.info.workerNodes | |
a4624c96 JB |
33 | } |
34 | ||
66a7748d JB |
35 | get maxElementsPerWorker (): number | undefined { |
36 | return undefined | |
a4624c96 JB |
37 | } |
38 | ||
66a7748d | 39 | get emitter (): EventEmitterAsyncResource | undefined { |
5199f9fd | 40 | return this.pool.emitter |
962a8159 JB |
41 | } |
42 | ||
8baf3f8f | 43 | /** @inheritDoc */ |
66a7748d | 44 | public async start (): Promise<void> { |
81797102 JB |
45 | // This is intentional |
46 | } | |
a4624c96 | 47 | |
8baf3f8f | 48 | /** @inheritDoc */ |
66a7748d JB |
49 | public async stop (): Promise<void> { |
50 | await this.pool.destroy() | |
ded13d97 JB |
51 | } |
52 | ||
8baf3f8f | 53 | /** @inheritDoc */ |
66a7748d JB |
54 | public async addElement (elementData: WorkerData): Promise<void> { |
55 | await this.pool.execute(elementData) | |
4bfd80fa | 56 | // Start element sequentially to optimize memory at startup |
66a7748d | 57 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion |
e1d9a0f4 | 58 | this.workerOptions.elementStartDelay! > 0 && |
66a7748d JB |
59 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion |
60 | (await sleep(randomizeDelay(this.workerOptions.elementStartDelay!))) | |
a4624c96 JB |
61 | } |
62 | } |