1 import type { EventEmitterAsyncResource
} from
'node:events';
3 import { FixedThreadPool
, type PoolInfo
} from
'poolifier';
5 import { WorkerAbstract
} from
'./WorkerAbstract';
6 import type { WorkerData
, WorkerOptions
} from
'./WorkerTypes';
7 import { randomizeDelay
, sleep
} from
'./WorkerUtils';
9 export class WorkerFixedPool
extends WorkerAbstract
<WorkerData
> {
10 private readonly pool
: FixedThreadPool
<WorkerData
>;
13 * Creates a new `WorkerFixedPool`.
15 * @param workerScript -
16 * @param workerOptions -
18 constructor(workerScript
: string, workerOptions
: WorkerOptions
) {
19 super(workerScript
, workerOptions
);
20 this.pool
= new FixedThreadPool(
21 this.workerOptions
.poolMaxSize
,
23 this.workerOptions
.poolOptions
,
27 get
info(): PoolInfo
{
28 return this.pool
.info
;
32 return this.pool
.info
.workerNodes
;
35 get
maxElementsPerWorker(): number | undefined {
39 get
emitter(): EventEmitterAsyncResource
| undefined {
40 return this.pool
?.emitter
;
44 public async start(): Promise
<void> {
45 // This is intentional
49 public async stop(): Promise
<void> {
50 return this.pool
.destroy();
54 public async addElement(elementData
: WorkerData
): Promise
<void> {
55 await this.pool
.execute(elementData
);
56 // Start element sequentially to optimize memory at startup
57 this.workerOptions
.elementStartDelay
! > 0 &&
58 (await sleep(randomizeDelay(this.workerOptions
.elementStartDelay
!)));