1 import type { EventEmitterAsyncResource
} from
'node:events'
3 import { FixedThreadPool
, type PoolInfo
} from
'poolifier'
5 import { WorkerAbstract
} from
'./WorkerAbstract.js'
6 import type { WorkerData
, WorkerOptions
} from
'./WorkerTypes.js'
7 import { randomizeDelay
, sleep
} from
'./WorkerUtils.js'
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
{
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 await 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 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
58 this.workerOptions
.elementStartDelay
! > 0 &&
59 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
60 (await sleep(randomizeDelay(this.workerOptions
.elementStartDelay
!)))