1 import { DynamicThreadPool
} from
'poolifier';
3 import type { WorkerData
, WorkerOptions
} from
'../types/Worker';
4 import Utils from
'../utils/Utils';
5 import WorkerAbstract from
'./WorkerAbstract';
6 import { WorkerUtils
} from
'./WorkerUtils';
8 export default class WorkerDynamicPool
extends WorkerAbstract
<WorkerData
> {
9 private readonly pool
: DynamicThreadPool
<WorkerData
>;
12 * Create a new `WorkerDynamicPool`.
15 * @param workerOptions
17 constructor(workerScript
: string, workerOptions
?: WorkerOptions
) {
18 super(workerScript
, workerOptions
);
19 this.workerOptions
.poolOptions
.errorHandler
=
20 this.workerOptions
?.poolOptions
?.errorHandler
?? WorkerUtils
.defaultErrorHandler
;
21 this.workerOptions
.poolOptions
.exitHandler
=
22 this.workerOptions
?.poolOptions
?.exitHandler
?? WorkerUtils
.defaultExitHandler
;
23 this.pool
= new DynamicThreadPool
<WorkerData
>(
24 this.workerOptions
.poolMinSize
,
25 this.workerOptions
.poolMaxSize
,
27 this.workerOptions
.poolOptions
32 return this.pool
.workers
.length
;
35 get
maxElementsPerWorker(): number | null {
44 public async start(): Promise
<void> {
45 // This is intentional
53 public async stop(): Promise
<void> {
54 return this.pool
.destroy();
63 public async addElement(elementData
: WorkerData
): Promise
<void> {
64 await this.pool
.execute(elementData
);
65 // Start element sequentially to optimize memory at startup
66 this.workerOptions
.elementStartDelay
> 0 &&
67 (await Utils
.sleep(this.workerOptions
.elementStartDelay
));