poolifier 4.4.4 → 5.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { TransferListItem, MessagePort, WorkerOptions as WorkerOptions$1, MessageChannel, Worker as Worker$1 } from 'node:worker_threads';
1
+ import { Transferable, MessagePort, MessageChannel, WorkerOptions as WorkerOptions$1, Worker as Worker$1 } from 'node:worker_threads';
2
2
  import { EventEmitter, EventEmitterAsyncResource } from 'node:events';
3
3
  import { AsyncResource } from 'node:async_hooks';
4
4
  import { EventLoopUtilization } from 'node:perf_hooks';
@@ -9,21 +9,16 @@ import { ClusterSettings, Worker } from 'node:cluster';
9
9
  * @internal
10
10
  */
11
11
  declare class CircularBuffer {
12
+ size: number;
12
13
  private readonly items;
13
14
  private readonly maxArrayIdx;
14
15
  private readIdx;
15
16
  private writeIdx;
16
- size: number;
17
17
  /**
18
18
  * @param size - Buffer size. @defaultValue defaultBufferSize
19
19
  * @returns CircularBuffer.
20
20
  */
21
21
  constructor(size?: number);
22
- /**
23
- * Checks the buffer size.
24
- * @param size - Buffer size.
25
- */
26
- private checkSize;
27
22
  /**
28
23
  * Checks whether the buffer is empty.
29
24
  * @returns Whether the buffer is empty.
@@ -49,6 +44,11 @@ declare class CircularBuffer {
49
44
  * @returns Numbers' array.
50
45
  */
51
46
  toArray(): number[];
47
+ /**
48
+ * Checks the buffer size.
49
+ * @param size - Buffer size.
50
+ */
51
+ private checkSize;
52
52
  }
53
53
 
54
54
  /**
@@ -76,47 +76,60 @@ declare const Measurements: Readonly<{
76
76
  waitTime: 'waitTime';
77
77
  }>;
78
78
  /**
79
- * Measurement.
80
- */
81
- type Measurement = keyof typeof Measurements;
82
- /**
83
- * Measurement options.
79
+ * Worker choice strategy interface.
80
+ * @internal
84
81
  */
85
- interface MeasurementOptions {
82
+ interface IWorkerChoiceStrategy {
86
83
  /**
87
- * Set measurement median.
84
+ * Chooses a worker node in the pool and returns its key.
85
+ * If no worker nodes are not eligible, `undefined` is returned.
86
+ * If `undefined` is returned, the caller retry.
87
+ * @returns The worker node key or `undefined`.
88
88
  */
89
- readonly median: boolean;
90
- }
91
- /**
92
- * Worker choice strategy options.
93
- */
94
- interface WorkerChoiceStrategyOptions {
89
+ readonly choose: () => number | undefined;
95
90
  /**
96
- * Event loop utilization options.
97
- * @defaultValue \{ median: false \}
91
+ * Removes the worker node key from strategy internals.
92
+ * @param workerNodeKey - The worker node key.
93
+ * @returns `true` if the worker node key is removed, `false` otherwise.
98
94
  */
99
- readonly elu?: MeasurementOptions;
95
+ readonly remove: (workerNodeKey: number) => boolean;
100
96
  /**
101
- * Measurement to use in worker choice strategy supporting it.
97
+ * Resets strategy internals.
98
+ * @returns `true` if the reset is successful, `false` otherwise.
102
99
  */
103
- readonly measurement?: Measurement;
100
+ readonly reset: () => boolean;
104
101
  /**
105
- * Runtime options.
106
- * @defaultValue \{ median: false \}
102
+ * Sets the worker choice strategy options.
103
+ * @param opts - The worker choice strategy options.
107
104
  */
108
- readonly runTime?: MeasurementOptions;
105
+ readonly setOptions: (opts: undefined | WorkerChoiceStrategyOptions) => void;
109
106
  /**
110
- * Wait time options.
111
- * @defaultValue \{ median: false \}
107
+ * Strategy policy.
112
108
  */
113
- readonly waitTime?: MeasurementOptions;
109
+ readonly strategyPolicy: StrategyPolicy;
114
110
  /**
115
- * Worker weights to use for weighted round robin worker selection strategies.
116
- * A weight is tasks maximum execution time in milliseconds for a worker node.
117
- * @defaultValue Weights computed automatically given the CPU performance.
111
+ * Tasks statistics requirements.
118
112
  */
119
- weights?: Record<number, number>;
113
+ readonly taskStatisticsRequirements: TaskStatisticsRequirements;
114
+ /**
115
+ * Updates the worker node key strategy internals.
116
+ * This is called after a task has been executed on a worker node.
117
+ * @returns `true` if the update is successful, `false` otherwise.
118
+ */
119
+ readonly update: (workerNodeKey: number) => boolean;
120
+ }
121
+ /**
122
+ * Measurement.
123
+ */
124
+ type Measurement = keyof typeof Measurements;
125
+ /**
126
+ * Measurement options.
127
+ */
128
+ interface MeasurementOptions {
129
+ /**
130
+ * Set measurement median.
131
+ */
132
+ readonly median: boolean;
120
133
  }
121
134
  /**
122
135
  * Measurement statistics requirements.
@@ -136,24 +149,6 @@ interface MeasurementStatisticsRequirements {
136
149
  */
137
150
  median: boolean;
138
151
  }
139
- /**
140
- * Pool worker node worker usage statistics requirements.
141
- * @internal
142
- */
143
- interface TaskStatisticsRequirements {
144
- /**
145
- * Tasks event loop utilization requirements.
146
- */
147
- readonly elu: MeasurementStatisticsRequirements;
148
- /**
149
- * Tasks runtime requirements.
150
- */
151
- readonly runTime: MeasurementStatisticsRequirements;
152
- /**
153
- * Tasks wait time requirements.
154
- */
155
- readonly waitTime: MeasurementStatisticsRequirements;
156
- }
157
152
  /**
158
153
  * Strategy policy.
159
154
  * @internal
@@ -169,47 +164,52 @@ interface StrategyPolicy {
169
164
  readonly dynamicWorkerUsage: boolean;
170
165
  }
171
166
  /**
172
- * Worker choice strategy interface.
167
+ * Pool worker node worker usage statistics requirements.
173
168
  * @internal
174
169
  */
175
- interface IWorkerChoiceStrategy {
170
+ interface TaskStatisticsRequirements {
176
171
  /**
177
- * Chooses a worker node in the pool and returns its key.
178
- * If no worker nodes are not eligible, `undefined` is returned.
179
- * If `undefined` is returned, the caller retry.
180
- * @returns The worker node key or `undefined`.
172
+ * Tasks event loop utilization requirements.
181
173
  */
182
- readonly choose: () => number | undefined;
174
+ readonly elu: MeasurementStatisticsRequirements;
183
175
  /**
184
- * Removes the worker node key from strategy internals.
185
- * @param workerNodeKey - The worker node key.
186
- * @returns `true` if the worker node key is removed, `false` otherwise.
176
+ * Tasks runtime requirements.
187
177
  */
188
- readonly remove: (workerNodeKey: number) => boolean;
178
+ readonly runTime: MeasurementStatisticsRequirements;
189
179
  /**
190
- * Resets strategy internals.
191
- * @returns `true` if the reset is successful, `false` otherwise.
180
+ * Tasks wait time requirements.
192
181
  */
193
- readonly reset: () => boolean;
182
+ readonly waitTime: MeasurementStatisticsRequirements;
183
+ }
184
+ /**
185
+ * Worker choice strategy options.
186
+ */
187
+ interface WorkerChoiceStrategyOptions {
194
188
  /**
195
- * Sets the worker choice strategy options.
196
- * @param opts - The worker choice strategy options.
189
+ * Event loop utilization options.
190
+ * @defaultValue \{ median: false \}
197
191
  */
198
- readonly setOptions: (opts: undefined | WorkerChoiceStrategyOptions) => void;
192
+ readonly elu?: MeasurementOptions;
199
193
  /**
200
- * Strategy policy.
194
+ * Measurement to use in worker choice strategy supporting it.
201
195
  */
202
- readonly strategyPolicy: StrategyPolicy;
196
+ readonly measurement?: Measurement;
203
197
  /**
204
- * Tasks statistics requirements.
198
+ * Runtime options.
199
+ * @defaultValue \{ median: false \}
205
200
  */
206
- readonly taskStatisticsRequirements: TaskStatisticsRequirements;
201
+ readonly runTime?: MeasurementOptions;
207
202
  /**
208
- * Updates the worker node key strategy internals.
209
- * This is called after a task has been executed on a worker node.
210
- * @returns `true` if the update is successful, `false` otherwise.
203
+ * Wait time options.
204
+ * @defaultValue \{ median: false \}
211
205
  */
212
- readonly update: (workerNodeKey: number) => boolean;
206
+ readonly waitTime?: MeasurementOptions;
207
+ /**
208
+ * Worker weights to use for weighted round robin worker selection strategies.
209
+ * A weight is tasks maximum execution time in milliseconds for a worker node.
210
+ * @defaultValue Weights computed automatically given the CPU performance.
211
+ */
212
+ weights?: Record<number, number>;
213
213
  }
214
214
 
215
215
  /**
@@ -261,83 +261,99 @@ interface WorkerOptions {
261
261
  }
262
262
 
263
263
  /**
264
- * Worker error.
265
- * @typeParam Data - Type of data sent to the worker triggering an error. This can only be structured-cloneable data.
264
+ * Message object that is passed between main worker and worker.
265
+ * @typeParam Data - Type of data sent to the worker or execution response. This can only be structured-cloneable data.
266
+ * @typeParam ErrorData - Type of data sent to the worker triggering an error. This can only be structured-cloneable data.
267
+ * @internal
266
268
  */
267
- interface WorkerError<Data = unknown> {
269
+ interface MessageValue<Data = unknown, ErrorData = unknown> extends Task<Data> {
268
270
  /**
269
- * Data triggering the error.
271
+ * Whether the worker starts or stops its activity check.
270
272
  */
271
- readonly data?: Data;
273
+ readonly checkActive?: boolean;
272
274
  /**
273
- * Error object.
275
+ * Kill code.
274
276
  */
275
- readonly error?: Error;
277
+ readonly kill?: 'failure' | 'success' | KillBehavior | true;
276
278
  /**
277
- * Error message.
279
+ * Message port.
278
280
  */
279
- readonly message: string;
281
+ readonly port?: MessagePort;
280
282
  /**
281
- * Task function name triggering the error.
283
+ * Whether the worker is ready or not.
282
284
  */
283
- readonly name?: string;
285
+ readonly ready?: boolean;
284
286
  /**
285
- * Error stack trace.
287
+ * Whether the worker computes the given statistics or not.
286
288
  */
287
- readonly stack?: string;
288
- }
289
- /**
290
- * Task performance.
291
- * @internal
292
- */
293
- interface TaskPerformance {
289
+ readonly statistics?: WorkerStatistics;
294
290
  /**
295
- * Task event loop utilization.
291
+ * Task function serialized to string.
296
292
  */
297
- readonly elu?: EventLoopUtilization;
293
+ readonly taskFunction?: string;
298
294
  /**
299
- * Task name.
295
+ * Task function operation:
296
+ * - `'add'` - Add a task function.
297
+ * - `'remove'` - Remove a task function.
298
+ * - `'default'` - Set a task function as default.
300
299
  */
301
- readonly name: string;
300
+ readonly taskFunctionOperation?: 'add' | 'default' | 'remove';
302
301
  /**
303
- * Task runtime.
302
+ * Whether the task function operation is successful or not.
304
303
  */
305
- readonly runTime?: number;
304
+ readonly taskFunctionOperationStatus?: boolean;
306
305
  /**
307
- * Task performance timestamp.
306
+ * Task function properties.
308
307
  */
309
- readonly timestamp: number;
308
+ readonly taskFunctionProperties?: TaskFunctionProperties;
309
+ /**
310
+ * Task functions properties.
311
+ */
312
+ readonly taskFunctionsProperties?: TaskFunctionProperties[];
313
+ /**
314
+ * Task operation:
315
+ * - `'abort'` - Abort a task.
316
+ */
317
+ readonly taskOperation?: 'abort';
318
+ /**
319
+ * Task performance.
320
+ */
321
+ readonly taskPerformance?: TaskPerformance;
322
+ /**
323
+ * Worker error.
324
+ */
325
+ readonly workerError?: WorkerError<ErrorData>;
326
+ /**
327
+ * Worker id.
328
+ */
329
+ readonly workerId?: number;
310
330
  }
311
331
  /**
312
- * Worker task performance statistics computation settings.
332
+ * An object holding the task execution response promise resolve/reject callbacks.
333
+ * @typeParam Response - Type of execution response. This can only be structured-cloneable data.
313
334
  * @internal
314
335
  */
315
- interface WorkerStatistics {
336
+ interface PromiseResponseWrapper<Response = unknown> {
316
337
  /**
317
- * Whether the worker computes the task event loop utilization (ELU) or not.
338
+ * The task abort signal.
318
339
  */
319
- readonly elu: boolean;
340
+ readonly abortSignal?: AbortSignal;
320
341
  /**
321
- * Whether the worker computes the task runtime or not.
342
+ * The asynchronous resource used to track the task execution.
322
343
  */
323
- readonly runTime: boolean;
324
- }
325
- /**
326
- * Task function properties.
327
- */
328
- interface TaskFunctionProperties {
344
+ readonly asyncResource?: AsyncResource;
329
345
  /**
330
- * Task function name.
346
+ * Reject callback to reject the promise.
331
347
  */
332
- readonly name: string;
348
+ readonly reject: (reason?: unknown) => void;
333
349
  /**
334
- * Task function priority. Lower values have higher priority.
350
+ * Resolve callback to fulfill the promise.
335
351
  */
336
- readonly priority?: number;
352
+ readonly resolve: (value: PromiseLike<Response> | Response) => void;
337
353
  /**
338
- * Task function worker choice strategy.
354
+ * The worker node key executing the task.
339
355
  */
340
- readonly strategy?: WorkerChoiceStrategy;
356
+ readonly workerNodeKey: number;
341
357
  }
342
358
  /**
343
359
  * Message object that is passed as a task between main worker and worker.
@@ -345,6 +361,10 @@ interface TaskFunctionProperties {
345
361
  * @internal
346
362
  */
347
363
  interface Task<Data = unknown> {
364
+ /**
365
+ * Whether the task is abortable or not.
366
+ */
367
+ readonly abortable?: boolean;
348
368
  /**
349
369
  * Task input data that will be passed to the worker.
350
370
  */
@@ -373,93 +393,90 @@ interface Task<Data = unknown> {
373
393
  /**
374
394
  * Array of transferable objects.
375
395
  */
376
- readonly transferList?: readonly TransferListItem[];
396
+ readonly transferList?: readonly Transferable[];
377
397
  }
378
398
  /**
379
- * Message object that is passed between main worker and worker.
380
- * @typeParam Data - Type of data sent to the worker or execution response. This can only be structured-cloneable data.
381
- * @typeParam ErrorData - Type of data sent to the worker triggering an error. This can only be structured-cloneable data.
382
- * @internal
399
+ * Task function properties.
383
400
  */
384
- interface MessageValue<Data = unknown, ErrorData = unknown> extends Task<Data> {
401
+ interface TaskFunctionProperties {
385
402
  /**
386
- * Whether the worker starts or stops its activity check.
403
+ * Task function name.
387
404
  */
388
- readonly checkActive?: boolean;
405
+ readonly name: string;
389
406
  /**
390
- * Kill code.
407
+ * Task function priority. Lower values have higher priority.
391
408
  */
392
- readonly kill?: 'failure' | 'success' | KillBehavior | true;
409
+ readonly priority?: number;
393
410
  /**
394
- * Message port.
411
+ * Task function worker choice strategy.
395
412
  */
396
- readonly port?: MessagePort;
413
+ readonly strategy?: WorkerChoiceStrategy;
414
+ }
415
+ /**
416
+ * Task performance.
417
+ * @internal
418
+ */
419
+ interface TaskPerformance {
397
420
  /**
398
- * Whether the worker is ready or not.
421
+ * Task event loop utilization.
399
422
  */
400
- readonly ready?: boolean;
423
+ readonly elu?: EventLoopUtilization;
401
424
  /**
402
- * Whether the worker computes the given statistics or not.
425
+ * Task name.
403
426
  */
404
- readonly statistics?: WorkerStatistics;
427
+ readonly name: string;
405
428
  /**
406
- * Task function serialized to string.
429
+ * Task runtime.
407
430
  */
408
- readonly taskFunction?: string;
431
+ readonly runTime?: number;
409
432
  /**
410
- * Task function operation:
411
- * - `'add'` - Add a task function.
412
- * - `'remove'` - Remove a task function.
413
- * - `'default'` - Set a task function as default.
433
+ * Task performance timestamp.
414
434
  */
415
- readonly taskFunctionOperation?: 'add' | 'default' | 'remove';
435
+ readonly timestamp: number;
436
+ }
437
+ /**
438
+ * Worker error.
439
+ * @typeParam Data - Type of data sent to the worker triggering an error. This can only be structured-cloneable data.
440
+ */
441
+ interface WorkerError<Data = unknown> {
416
442
  /**
417
- * Whether the task function operation is successful or not.
443
+ * Whether the error is an abort error or not.
418
444
  */
419
- readonly taskFunctionOperationStatus?: boolean;
445
+ readonly aborted: boolean;
420
446
  /**
421
- * Task function properties.
447
+ * Data triggering the error.
422
448
  */
423
- readonly taskFunctionProperties?: TaskFunctionProperties;
449
+ readonly data?: Data;
424
450
  /**
425
- * Task functions properties.
451
+ * Error object.
426
452
  */
427
- readonly taskFunctionsProperties?: TaskFunctionProperties[];
453
+ readonly error?: Error;
428
454
  /**
429
- * Task performance.
455
+ * Error message.
430
456
  */
431
- readonly taskPerformance?: TaskPerformance;
457
+ readonly message: string;
432
458
  /**
433
- * Worker error.
459
+ * Task function name triggering the error.
434
460
  */
435
- readonly workerError?: WorkerError<ErrorData>;
461
+ readonly name?: string;
436
462
  /**
437
- * Worker id.
463
+ * Error stack trace.
438
464
  */
439
- readonly workerId?: number;
465
+ readonly stack?: string;
440
466
  }
441
467
  /**
442
- * An object holding the task execution response promise resolve/reject callbacks.
443
- * @typeParam Response - Type of execution response. This can only be structured-cloneable data.
468
+ * Worker task performance statistics computation settings.
444
469
  * @internal
445
470
  */
446
- interface PromiseResponseWrapper<Response = unknown> {
447
- /**
448
- * The asynchronous resource used to track the task execution.
449
- */
450
- readonly asyncResource?: AsyncResource;
451
- /**
452
- * Reject callback to reject the promise.
453
- */
454
- readonly reject: (reason?: unknown) => void;
471
+ interface WorkerStatistics {
455
472
  /**
456
- * Resolve callback to fulfill the promise.
473
+ * Whether the worker computes the task event loop utilization (ELU) or not.
457
474
  */
458
- readonly resolve: (value: PromiseLike<Response> | Response) => void;
475
+ readonly elu: boolean;
459
476
  /**
460
- * The worker node key executing the task.
477
+ * Whether the worker computes the task runtime or not.
461
478
  */
462
- readonly workerNodeKey: number;
479
+ readonly runTime: boolean;
463
480
  }
464
481
  /**
465
482
  * Remove readonly modifier from all properties of T.
@@ -470,14 +487,6 @@ type Writable<T> = {
470
487
  -readonly [P in keyof T]: T[P];
471
488
  };
472
489
 
473
- /**
474
- * Task synchronous function that can be executed.
475
- * @param data - Data sent to the worker.
476
- * @returns Execution response.
477
- * @typeParam Data - Type of data sent to the worker. This can only be structured-cloneable data.
478
- * @typeParam Response - Type of execution response. This can only be structured-cloneable data.
479
- */
480
- type TaskSyncFunction<Data = unknown, Response = unknown> = (data?: Data) => Response;
481
490
  /**
482
491
  * Task asynchronous function that can be executed.
483
492
  * This function must return a promise.
@@ -513,6 +522,13 @@ interface TaskFunctionObject<Data = unknown, Response = unknown> {
513
522
  */
514
523
  taskFunction: TaskFunction<Data, Response>;
515
524
  }
525
+ /**
526
+ * Task function operation result.
527
+ */
528
+ interface TaskFunctionOperationResult {
529
+ error?: Error;
530
+ status: boolean;
531
+ }
516
532
  /**
517
533
  * Tasks functions that can be executed.
518
534
  * The key is the name of the task function or task function object.
@@ -522,38 +538,119 @@ interface TaskFunctionObject<Data = unknown, Response = unknown> {
522
538
  */
523
539
  type TaskFunctions<Data = unknown, Response = unknown> = Record<string, TaskFunction<Data, Response> | TaskFunctionObject<Data, Response>>;
524
540
  /**
525
- * Task function operation result.
541
+ * Task synchronous function that can be executed.
542
+ * @param data - Data sent to the worker.
543
+ * @returns Execution response.
544
+ * @typeParam Data - Type of data sent to the worker. This can only be structured-cloneable data.
545
+ * @typeParam Response - Type of execution response. This can only be structured-cloneable data.
526
546
  */
527
- interface TaskFunctionOperationResult {
528
- error?: Error;
529
- status: boolean;
530
- }
547
+ type TaskSyncFunction<Data = unknown, Response = unknown> = (data?: Data) => Response;
531
548
 
532
549
  /**
533
- * Callback invoked when the worker has started successfully.
534
- * @typeParam Worker - Type of worker.
550
+ * Priority queue.
551
+ * @typeParam T - Type of priority queue data.
552
+ * @internal
535
553
  */
536
- type OnlineHandler<Worker extends IWorker> = (this: Worker) => void;
554
+ declare class PriorityQueue<T> {
555
+ /** The priority queue maximum size. */
556
+ maxSize: number;
557
+ /**
558
+ * The number of filled prioritized buckets.
559
+ * @returns The number of filled prioritized buckets.
560
+ */
561
+ get buckets(): number;
562
+ /**
563
+ * Whether priority is enabled.
564
+ * @returns Whether priority is enabled.
565
+ */
566
+ get enablePriority(): boolean;
567
+ /**
568
+ * Enables/disables priority.
569
+ * @param enablePriority - Whether to enable priority.
570
+ */
571
+ set enablePriority(enablePriority: boolean);
572
+ /**
573
+ * The priority queue size.
574
+ * @returns The priority queue size.
575
+ */
576
+ get size(): number;
577
+ private readonly bucketSize;
578
+ private head;
579
+ private priorityEnabled;
580
+ private tail;
581
+ /**
582
+ * Constructs a priority queue.
583
+ * @param bucketSize - Prioritized bucket size. @defaultValue defaultBucketSize
584
+ * @param enablePriority - Whether to enable priority. @defaultValue false
585
+ * @returns PriorityQueue.
586
+ */
587
+ constructor(bucketSize?: number, enablePriority?: boolean);
588
+ /**
589
+ * Clears the priority queue.
590
+ */
591
+ clear(): void;
592
+ /**
593
+ * Deletes the given data from the priority queue.
594
+ * @param data - Data to delete.
595
+ * @returns `true` if the data was deleted, `false` otherwise.
596
+ */
597
+ delete(data: T): boolean;
598
+ /**
599
+ * Dequeue data from the priority queue.
600
+ * @param bucket - The prioritized bucket to dequeue from.
601
+ * @returns The dequeued data or `undefined` if the priority queue is empty.
602
+ */
603
+ dequeue(bucket?: number): T | undefined;
604
+ /**
605
+ * Enqueue data into the priority queue.
606
+ * @param data - Data to enqueue.
607
+ * @param priority - Priority of the data. Lower values have higher priority.
608
+ * @returns The new size of the priority queue.
609
+ */
610
+ enqueue(data: T, priority?: number): number;
611
+ /**
612
+ * Returns an iterator for the priority queue.
613
+ * @returns An iterator for the priority queue.
614
+ * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols
615
+ */
616
+ [Symbol.iterator](): Iterator<T>;
617
+ private getPriorityQueueNode;
618
+ }
619
+
537
620
  /**
538
- * Callback invoked if the worker has received a message.
621
+ * Callback invoked if the worker raised an error.
539
622
  * @typeParam Worker - Type of worker.
540
623
  */
541
- type MessageHandler<Worker extends IWorker> = (this: Worker, message: unknown) => void;
624
+ type ErrorHandler<Worker extends IWorker> = (this: Worker, error: Error) => void;
542
625
  /**
543
- * Callback invoked if the worker raised an error.
626
+ * Worker event handler.
544
627
  * @typeParam Worker - Type of worker.
545
628
  */
546
- type ErrorHandler<Worker extends IWorker> = (this: Worker, error: Error) => void;
629
+ type EventHandler<Worker extends IWorker> = ErrorHandler<Worker> | ExitHandler<Worker> | MessageHandler<Worker> | OnlineHandler<Worker>;
547
630
  /**
548
631
  * Callback invoked when the worker exits successfully.
549
632
  * @typeParam Worker - Type of worker.
550
633
  */
551
634
  type ExitHandler<Worker extends IWorker> = (this: Worker, exitCode: number) => void;
552
635
  /**
553
- * Worker event handler.
636
+ * Callback invoked if the worker has received a message.
554
637
  * @typeParam Worker - Type of worker.
555
638
  */
556
- type EventHandler<Worker extends IWorker> = ErrorHandler<Worker> | ExitHandler<Worker> | MessageHandler<Worker> | OnlineHandler<Worker>;
639
+ type MessageHandler<Worker extends IWorker> = (this: Worker, message: unknown) => void;
640
+ /**
641
+ * Callback invoked when the worker has started successfully.
642
+ * @typeParam Worker - Type of worker.
643
+ */
644
+ type OnlineHandler<Worker extends IWorker> = (this: Worker) => void;
645
+ /**
646
+ * Event loop utilization measurement statistics.
647
+ * @internal
648
+ */
649
+ interface EventLoopUtilizationMeasurementStatistics {
650
+ readonly active: MeasurementStatistics;
651
+ readonly idle: MeasurementStatistics;
652
+ utilization?: number;
653
+ }
557
654
  /**
558
655
  * Measurement statistics.
559
656
  * @internal
@@ -584,15 +681,6 @@ interface MeasurementStatistics {
584
681
  */
585
682
  minimum?: number;
586
683
  }
587
- /**
588
- * Event loop utilization measurement statistics.
589
- * @internal
590
- */
591
- interface EventLoopUtilizationMeasurementStatistics {
592
- readonly active: MeasurementStatistics;
593
- readonly idle: MeasurementStatistics;
594
- utilization?: number;
595
- }
596
684
  /**
597
685
  * Task statistics.
598
686
  * @internal
@@ -635,115 +723,31 @@ declare const WorkerTypes: Readonly<{
635
723
  thread: 'thread';
636
724
  }>;
637
725
  /**
638
- * Worker type.
639
- */
640
- type WorkerType = keyof typeof WorkerTypes;
641
- /**
642
- * Worker information.
643
- * @internal
726
+ * Worker interface.
644
727
  */
645
- interface WorkerInfo {
728
+ interface IWorker extends EventEmitter {
646
729
  /**
647
- * Back pressure flag.
648
- * This flag is set to `true` when worker node tasks queue is back pressured.
730
+ * Cluster worker disconnect.
649
731
  */
650
- backPressure: boolean;
732
+ readonly disconnect?: () => void;
651
733
  /**
652
- * Back pressure stealing flag.
653
- * This flag is set to `true` when worker node is stealing one task from another back pressured worker node.
734
+ * Cluster worker id.
654
735
  */
655
- backPressureStealing: boolean;
736
+ readonly id?: number;
656
737
  /**
657
- * Continuous stealing flag.
658
- * This flag is set to `true` when worker node is continuously stealing tasks from other worker nodes.
738
+ * Cluster worker kill.
659
739
  */
660
- continuousStealing: boolean;
740
+ readonly kill?: (signal?: string) => void;
661
741
  /**
662
- * Dynamic flag.
742
+ * Registers an event handler.
743
+ * @param event - The event.
744
+ * @param handler - The event handler.
663
745
  */
664
- dynamic: boolean;
746
+ readonly on: (event: string, handler: EventHandler<this>) => this;
665
747
  /**
666
- * Worker id.
667
- */
668
- readonly id: number | undefined;
669
- /**
670
- * Ready flag.
671
- */
672
- ready: boolean;
673
- /**
674
- * Stealing flag.
675
- * This flag is set to `true` when worker node is stealing one task from another worker node.
676
- */
677
- stealing: boolean;
678
- /**
679
- * Stolen flag.
680
- * This flag is set to `true` when worker node has one task stolen from another worker node.
681
- */
682
- stolen: boolean;
683
- /**
684
- * Task functions properties.
685
- */
686
- taskFunctionsProperties?: TaskFunctionProperties[];
687
- /**
688
- * Worker type.
689
- */
690
- readonly type: WorkerType;
691
- }
692
- /**
693
- * Worker usage statistics.
694
- * @internal
695
- */
696
- interface WorkerUsage {
697
- /**
698
- * Tasks event loop utilization statistics.
699
- */
700
- readonly elu: EventLoopUtilizationMeasurementStatistics;
701
- /**
702
- * Tasks runtime statistics.
703
- */
704
- readonly runTime: MeasurementStatistics;
705
- /**
706
- * Tasks statistics.
707
- */
708
- readonly tasks: TaskStatistics;
709
- /**
710
- * Tasks wait time statistics.
711
- */
712
- readonly waitTime: MeasurementStatistics;
713
- }
714
- /**
715
- * Worker choice strategy data.
716
- * @internal
717
- */
718
- interface StrategyData {
719
- virtualTaskEndTimestamp?: number;
720
- }
721
- /**
722
- * Worker interface.
723
- */
724
- interface IWorker extends EventEmitter {
725
- /**
726
- * Cluster worker disconnect.
727
- */
728
- readonly disconnect?: () => void;
729
- /**
730
- * Cluster worker id.
731
- */
732
- readonly id?: number;
733
- /**
734
- * Cluster worker kill.
735
- */
736
- readonly kill?: (signal?: string) => void;
737
- /**
738
- * Registers an event handler.
739
- * @param event - The event.
740
- * @param handler - The event handler.
741
- */
742
- readonly on: (event: string, handler: EventHandler<this>) => this;
743
- /**
744
- * Registers once an event handler.
745
- * @param event - The event.
746
- * @param handler - The event handler.
748
+ * Registers once an event handler.
749
+ * @param event - The event.
750
+ * @param handler - The event handler.
747
751
  */
748
752
  readonly once: (event: string, handler: EventHandler<this>) => this;
749
753
  /**
@@ -762,17 +766,6 @@ interface IWorker extends EventEmitter {
762
766
  */
763
767
  readonly unref?: () => void;
764
768
  }
765
- /**
766
- * Worker node options.
767
- * @internal
768
- */
769
- interface WorkerNodeOptions {
770
- env?: Record<string, unknown>;
771
- tasksQueueBackPressureSize: number | undefined;
772
- tasksQueueBucketSize: number | undefined;
773
- tasksQueuePriority: boolean | undefined;
774
- workerOptions?: WorkerOptions$1;
775
- }
776
769
  /**
777
770
  * Worker node interface.
778
771
  * @typeParam Worker - Type of worker.
@@ -784,6 +777,12 @@ interface IWorkerNode<Worker extends IWorker, Data = unknown> extends EventEmitt
784
777
  * Clears tasks queue.
785
778
  */
786
779
  readonly clearTasksQueue: () => void;
780
+ /**
781
+ * Deletes a task from the tasks queue.
782
+ * @param task - The task to delete.
783
+ * @returns `true` if the task was deleted, `false` otherwise.
784
+ */
785
+ readonly deleteTask: (task: Task<Data>) => boolean;
787
786
  /**
788
787
  * Deletes task function worker usage statistics.
789
788
  * @param name - The task function name.
@@ -843,6 +842,10 @@ interface IWorkerNode<Worker extends IWorker, Data = unknown> extends EventEmitt
843
842
  * This is used to store data that are specific to the worker choice strategy.
844
843
  */
845
844
  strategyData?: StrategyData;
845
+ /**
846
+ * Tasks queue.
847
+ */
848
+ readonly tasksQueue: PriorityQueue<Task<Data>>;
846
849
  /**
847
850
  * Tasks queue back pressure size.
848
851
  * This is the number of tasks that can be enqueued before the worker node has back pressure.
@@ -866,14 +869,115 @@ interface IWorkerNode<Worker extends IWorker, Data = unknown> extends EventEmitt
866
869
  */
867
870
  readonly worker: Worker;
868
871
  }
872
+ /**
873
+ * Worker choice strategy data.
874
+ * @internal
875
+ */
876
+ interface StrategyData {
877
+ virtualTaskEndTimestamp?: number;
878
+ }
879
+ /**
880
+ * Worker information.
881
+ * @internal
882
+ */
883
+ interface WorkerInfo {
884
+ /**
885
+ * Back pressure flag.
886
+ * This flag is set to `true` when worker node tasks queue is back pressured.
887
+ */
888
+ backPressure: boolean;
889
+ /**
890
+ * Back pressure stealing flag.
891
+ * This flag is set to `true` when worker node is stealing one task from another back pressured worker node.
892
+ */
893
+ backPressureStealing: boolean;
894
+ /**
895
+ * Continuous stealing flag.
896
+ * This flag is set to `true` when worker node is continuously stealing tasks from other worker nodes.
897
+ */
898
+ continuousStealing: boolean;
899
+ /**
900
+ * Dynamic flag.
901
+ */
902
+ dynamic: boolean;
903
+ /**
904
+ * Worker id.
905
+ */
906
+ readonly id: number | undefined;
907
+ /**
908
+ * Queued task abortion flag.
909
+ * This flag is set to `true` when worker node is aborting a queued task.
910
+ */
911
+ queuedTaskAbortion: boolean;
912
+ /**
913
+ * Ready flag.
914
+ */
915
+ ready: boolean;
916
+ /**
917
+ * Stealing flag.
918
+ * This flag is set to `true` when worker node is stealing one task from another worker node.
919
+ */
920
+ stealing: boolean;
921
+ /**
922
+ * Stolen flag.
923
+ * This flag is set to `true` when worker node has one task stolen from another worker node.
924
+ */
925
+ stolen: boolean;
926
+ /**
927
+ * Task functions properties.
928
+ */
929
+ taskFunctionsProperties?: TaskFunctionProperties[];
930
+ /**
931
+ * Worker type.
932
+ */
933
+ readonly type: WorkerType;
934
+ }
869
935
  /**
870
936
  * Worker node event detail.
871
937
  * @internal
872
938
  */
873
939
  interface WorkerNodeEventDetail {
940
+ taskId?: `${string}-${string}-${string}-${string}-${string}`;
874
941
  workerId?: number;
875
942
  workerNodeKey?: number;
876
943
  }
944
+ /**
945
+ * Worker node options.
946
+ * @internal
947
+ */
948
+ interface WorkerNodeOptions {
949
+ env?: Record<string, unknown>;
950
+ tasksQueueBackPressureSize: number | undefined;
951
+ tasksQueueBucketSize: number | undefined;
952
+ tasksQueuePriority: boolean | undefined;
953
+ workerOptions?: WorkerOptions$1;
954
+ }
955
+ /**
956
+ * Worker type.
957
+ */
958
+ type WorkerType = keyof typeof WorkerTypes;
959
+ /**
960
+ * Worker usage statistics.
961
+ * @internal
962
+ */
963
+ interface WorkerUsage {
964
+ /**
965
+ * Tasks event loop utilization statistics.
966
+ */
967
+ readonly elu: EventLoopUtilizationMeasurementStatistics;
968
+ /**
969
+ * Tasks runtime statistics.
970
+ */
971
+ readonly runTime: MeasurementStatistics;
972
+ /**
973
+ * Tasks statistics.
974
+ */
975
+ readonly tasks: TaskStatistics;
976
+ /**
977
+ * Tasks wait time statistics.
978
+ */
979
+ readonly waitTime: MeasurementStatistics;
980
+ }
877
981
 
878
982
  /**
879
983
  * Enumeration of pool types.
@@ -902,6 +1006,124 @@ declare const PoolEvents: Readonly<{
902
1006
  ready: 'ready';
903
1007
  taskError: 'taskError';
904
1008
  }>;
1009
+ /**
1010
+ * Contract definition for a poolifier pool.
1011
+ * @typeParam Worker - Type of worker which manages this pool.
1012
+ * @typeParam Data - Type of data sent to the worker. This can only be structured-cloneable data.
1013
+ * @typeParam Response - Type of execution response. This can only be structured-cloneable data.
1014
+ */
1015
+ interface IPool<Worker extends IWorker, Data = unknown, Response = unknown> {
1016
+ /**
1017
+ * Adds a task function to this pool.
1018
+ * If a task function with the same name already exists, it will be overwritten.
1019
+ * @param name - The name of the task function.
1020
+ * @param fn - The task function.
1021
+ * @returns `true` if the task function was added, `false` otherwise.
1022
+ * @throws {@link https://nodejs.org/api/errors.html#class-typeerror} If the `name` parameter is not a string or an empty string.
1023
+ * @throws {@link https://nodejs.org/api/errors.html#class-typeerror} If the `fn` parameter is not a function or task function object.
1024
+ */
1025
+ readonly addTaskFunction: (name: string, fn: TaskFunction<Data, Response> | TaskFunctionObject<Data, Response>) => Promise<boolean>;
1026
+ /**
1027
+ * Terminates all workers in this pool.
1028
+ */
1029
+ readonly destroy: () => Promise<void>;
1030
+ /**
1031
+ * Pool event emitter integrated with async resource.
1032
+ * The async tracking tooling identifier is `poolifier:<PoolType>-<WorkerType>-pool`.
1033
+ *
1034
+ * Events that can currently be listened to:
1035
+ *
1036
+ * - `'ready'`: Emitted when the number of workers created in the pool has reached the minimum size expected and are ready. If the pool is dynamic with a minimum number of workers set to zero, this event is emitted when the pool is started.
1037
+ * - `'busy'`: Emitted when the number of workers created in the pool has reached the maximum size expected and are executing concurrently their tasks quota.
1038
+ * - `'busyEnd'`: Emitted when the number of workers created in the pool has reached the maximum size expected and are no longer executing concurrently their tasks quota.
1039
+ * - `'full'`: Emitted when the pool is dynamic and the number of workers created has reached the maximum size expected.
1040
+ * - `'fullEnd'`: Emitted when the pool is dynamic and the number of workers created has no longer reached the maximum size expected.
1041
+ * - `'empty'`: Emitted when the pool is dynamic with a minimum number of workers set to zero and the number of workers has reached the minimum size expected.
1042
+ * - `'destroy'`: Emitted when the pool is destroyed.
1043
+ * - `'error'`: Emitted when an uncaught error occurs.
1044
+ * - `'taskError'`: Emitted when an error occurs while executing a task.
1045
+ * - `'backPressure'`: Emitted when the number of workers created in the pool has reached the maximum size expected and are back pressured (i.e. their tasks queue is full: queue size \>= maximum queue size).
1046
+ * - `'backPressureEnd'`: Emitted when the number of workers created in the pool has reached the maximum size expected and are no longer back pressured (i.e. their tasks queue is no longer full: queue size \< maximum queue size).
1047
+ */
1048
+ readonly emitter?: EventEmitterAsyncResource;
1049
+ /**
1050
+ * Enables/disables the worker node tasks queue in this pool.
1051
+ * @param enable - Whether to enable or disable the worker node tasks queue.
1052
+ * @param tasksQueueOptions - The worker node tasks queue options.
1053
+ */
1054
+ readonly enableTasksQueue: (enable: boolean, tasksQueueOptions?: TasksQueueOptions) => void;
1055
+ /**
1056
+ * Executes the specified function in the worker constructor with the task data input parameter.
1057
+ * @param data - The optional task input data for the specified task function. This can only be structured-cloneable data.
1058
+ * @param name - The optional name of the task function to execute. If not specified, the default task function will be executed.
1059
+ * @param abortSignal - The optional AbortSignal to abort the task.
1060
+ * @param transferList - The optional array of transferable objects to transfer ownership of. Ownership of the transferred objects is given to the chosen pool's worker_threads worker and they should not be used in the main thread afterwards.
1061
+ * @returns Promise with a task function response that will be fulfilled when the task is completed.
1062
+ */
1063
+ readonly execute: (data?: Data, name?: string, abortSignal?: AbortSignal, transferList?: readonly Transferable[]) => Promise<Response>;
1064
+ /**
1065
+ * Whether the specified task function exists in this pool.
1066
+ * @param name - The name of the task function.
1067
+ * @returns `true` if the task function exists, `false` otherwise.
1068
+ */
1069
+ readonly hasTaskFunction: (name: string) => boolean;
1070
+ /**
1071
+ * Pool information.
1072
+ */
1073
+ readonly info: PoolInfo;
1074
+ /**
1075
+ * Lists the properties of task functions available in this pool.
1076
+ * @returns The properties of task functions available in this pool.
1077
+ */
1078
+ readonly listTaskFunctionsProperties: () => TaskFunctionProperties[];
1079
+ /**
1080
+ * Executes the specified function in the worker constructor with the tasks data iterable input parameter.
1081
+ * @param data - The tasks iterable input data for the specified task function. This can only be an iterable of structured-cloneable data.
1082
+ * @param name - The optional name of the task function to execute. If not specified, the default task function will be executed.
1083
+ * @param abortSignals - The optional iterable of AbortSignal to abort the tasks iterable.
1084
+ * @param transferList - The optional array of transferable objects to transfer ownership of. Ownership of the transferred objects is given to the chosen pool's worker_threads worker and they should not be used in the main thread afterwards.
1085
+ * @returns Promise with an array of task function responses that will be fulfilled when the tasks are completed.
1086
+ */
1087
+ readonly mapExecute: (data: Iterable<Data>, name?: string, abortSignals?: Iterable<AbortSignal>, transferList?: readonly Transferable[]) => Promise<Response[]>;
1088
+ /**
1089
+ * Removes a task function from this pool.
1090
+ * @param name - The name of the task function.
1091
+ * @returns `true` if the task function was removed, `false` otherwise.
1092
+ */
1093
+ readonly removeTaskFunction: (name: string) => Promise<boolean>;
1094
+ /**
1095
+ * Sets the default task function in this pool.
1096
+ * @param name - The name of the task function.
1097
+ * @returns `true` if the default task function was set, `false` otherwise.
1098
+ */
1099
+ readonly setDefaultTaskFunction: (name: string) => Promise<boolean>;
1100
+ /**
1101
+ * Sets the worker node tasks queue options in this pool.
1102
+ * @param tasksQueueOptions - The worker node tasks queue options.
1103
+ */
1104
+ readonly setTasksQueueOptions: (tasksQueueOptions: TasksQueueOptions) => void;
1105
+ /**
1106
+ * Sets the default worker choice strategy in this pool.
1107
+ * @param workerChoiceStrategy - The default worker choice strategy.
1108
+ * @param workerChoiceStrategyOptions - The worker choice strategy options.
1109
+ */
1110
+ readonly setWorkerChoiceStrategy: (workerChoiceStrategy: WorkerChoiceStrategy, workerChoiceStrategyOptions?: WorkerChoiceStrategyOptions) => void;
1111
+ /**
1112
+ * Sets the worker choice strategy options in this pool.
1113
+ * @param workerChoiceStrategyOptions - The worker choice strategy options.
1114
+ * @returns `true` if the worker choice strategy options were set, `false` otherwise.
1115
+ */
1116
+ readonly setWorkerChoiceStrategyOptions: (workerChoiceStrategyOptions: WorkerChoiceStrategyOptions) => boolean;
1117
+ /**
1118
+ * Starts the minimum number of workers in this pool.
1119
+ */
1120
+ readonly start: () => void;
1121
+ /**
1122
+ * Pool worker nodes.
1123
+ * @internal
1124
+ */
1125
+ readonly workerNodes: IWorkerNode<Worker, Data>[];
1126
+ }
905
1127
  /**
906
1128
  * Pool event.
907
1129
  */
@@ -971,41 +1193,6 @@ interface PoolInfo {
971
1193
  /** Pool total worker nodes. */
972
1194
  readonly workerNodes: number;
973
1195
  }
974
- /**
975
- * Worker node tasks queue options.
976
- */
977
- interface TasksQueueOptions {
978
- /**
979
- * Maximum number of tasks that can be executed concurrently on a worker node.
980
- * @defaultValue 1
981
- */
982
- readonly concurrency?: number;
983
- /**
984
- * Maximum tasks queue size per worker node flagging it as back pressured.
985
- * @defaultValue (pool maximum size)^2
986
- */
987
- readonly size?: number;
988
- /**
989
- * Queued tasks finished timeout in milliseconds at worker node termination.
990
- * @defaultValue 2000
991
- */
992
- readonly tasksFinishedTimeout?: number;
993
- /**
994
- * Whether to enable tasks stealing under back pressure.
995
- * @defaultValue true
996
- */
997
- readonly tasksStealingOnBackPressure?: boolean;
998
- /**
999
- * Ratio of worker nodes that can steal tasks from another worker node.
1000
- * @defaultValue 0.6
1001
- */
1002
- readonly tasksStealingRatio?: number;
1003
- /**
1004
- * Whether to enable task stealing on idle.
1005
- * @defaultValue true
1006
- */
1007
- readonly taskStealing?: boolean;
1008
- }
1009
1196
  /**
1010
1197
  * Options for a poolifier pool.
1011
1198
  * @typeParam Worker - Type of worker.
@@ -1080,120 +1267,39 @@ interface PoolOptions<Worker extends IWorker> {
1080
1267
  workerOptions?: WorkerOptions$1;
1081
1268
  }
1082
1269
  /**
1083
- * Contract definition for a poolifier pool.
1084
- * @typeParam Worker - Type of worker which manages this pool.
1085
- * @typeParam Data - Type of data sent to the worker. This can only be structured-cloneable data.
1086
- * @typeParam Response - Type of execution response. This can only be structured-cloneable data.
1270
+ * Worker node tasks queue options.
1087
1271
  */
1088
- interface IPool<Worker extends IWorker, Data = unknown, Response = unknown> {
1089
- /**
1090
- * Adds a task function to this pool.
1091
- * If a task function with the same name already exists, it will be overwritten.
1092
- * @param name - The name of the task function.
1093
- * @param fn - The task function.
1094
- * @returns `true` if the task function was added, `false` otherwise.
1095
- * @throws {@link https://nodejs.org/api/errors.html#class-typeerror} If the `name` parameter is not a string or an empty string.
1096
- * @throws {@link https://nodejs.org/api/errors.html#class-typeerror} If the `fn` parameter is not a function or task function object.
1097
- */
1098
- readonly addTaskFunction: (name: string, fn: TaskFunction<Data, Response> | TaskFunctionObject<Data, Response>) => Promise<boolean>;
1099
- /**
1100
- * Terminates all workers in this pool.
1101
- */
1102
- readonly destroy: () => Promise<void>;
1103
- /**
1104
- * Pool event emitter integrated with async resource.
1105
- * The async tracking tooling identifier is `poolifier:<PoolType>-<WorkerType>-pool`.
1106
- *
1107
- * Events that can currently be listened to:
1108
- *
1109
- * - `'ready'`: Emitted when the number of workers created in the pool has reached the minimum size expected and are ready. If the pool is dynamic with a minimum number of workers set to zero, this event is emitted when the pool is started.
1110
- * - `'busy'`: Emitted when the number of workers created in the pool has reached the maximum size expected and are executing concurrently their tasks quota.
1111
- * - `'busyEnd'`: Emitted when the number of workers created in the pool has reached the maximum size expected and are no longer executing concurrently their tasks quota.
1112
- * - `'full'`: Emitted when the pool is dynamic and the number of workers created has reached the maximum size expected.
1113
- * - `'fullEnd'`: Emitted when the pool is dynamic and the number of workers created has no longer reached the maximum size expected.
1114
- * - `'empty'`: Emitted when the pool is dynamic with a minimum number of workers set to zero and the number of workers has reached the minimum size expected.
1115
- * - `'destroy'`: Emitted when the pool is destroyed.
1116
- * - `'error'`: Emitted when an uncaught error occurs.
1117
- * - `'taskError'`: Emitted when an error occurs while executing a task.
1118
- * - `'backPressure'`: Emitted when the number of workers created in the pool has reached the maximum size expected and are back pressured (i.e. their tasks queue is full: queue size \>= maximum queue size).
1119
- * - `'backPressureEnd'`: Emitted when the number of workers created in the pool has reached the maximum size expected and are no longer back pressured (i.e. their tasks queue is no longer full: queue size \< maximum queue size).
1120
- */
1121
- readonly emitter?: EventEmitterAsyncResource;
1122
- /**
1123
- * Enables/disables the worker node tasks queue in this pool.
1124
- * @param enable - Whether to enable or disable the worker node tasks queue.
1125
- * @param tasksQueueOptions - The worker node tasks queue options.
1126
- */
1127
- readonly enableTasksQueue: (enable: boolean, tasksQueueOptions?: TasksQueueOptions) => void;
1128
- /**
1129
- * Executes the specified function in the worker constructor with the task data input parameter.
1130
- * @param data - The optional task input data for the specified task function. This can only be structured-cloneable data.
1131
- * @param name - The optional name of the task function to execute. If not specified, the default task function will be executed.
1132
- * @param transferList - An optional array of transferable objects to transfer ownership of. Ownership of the transferred objects is given to the chosen pool's worker_threads worker and they should not be used in the main thread afterwards.
1133
- * @returns Promise with a task function response that will be fulfilled when the task is completed.
1134
- */
1135
- readonly execute: (data?: Data, name?: string, transferList?: readonly TransferListItem[]) => Promise<Response>;
1136
- /**
1137
- * Whether the specified task function exists in this pool.
1138
- * @param name - The name of the task function.
1139
- * @returns `true` if the task function exists, `false` otherwise.
1140
- */
1141
- readonly hasTaskFunction: (name: string) => boolean;
1142
- /**
1143
- * Pool information.
1144
- */
1145
- readonly info: PoolInfo;
1146
- /**
1147
- * Lists the properties of task functions available in this pool.
1148
- * @returns The properties of task functions available in this pool.
1149
- */
1150
- readonly listTaskFunctionsProperties: () => TaskFunctionProperties[];
1151
- /**
1152
- * Executes the specified function in the worker constructor with the tasks data iterable input parameter.
1153
- * @param data - The tasks iterable input data for the specified task function. This can only be an iterable of structured-cloneable data.
1154
- * @param name - The optional name of the task function to execute. If not specified, the default task function will be executed.
1155
- * @param transferList - An optional array of transferable objects to transfer ownership of. Ownership of the transferred objects is given to the chosen pool's worker_threads worker and they should not be used in the main thread afterwards.
1156
- * @returns Promise with an array of task function responses that will be fulfilled when the tasks are completed.
1157
- */
1158
- readonly mapExecute: (data: Iterable<Data>, name?: string, transferList?: readonly TransferListItem[]) => Promise<Response[]>;
1159
- /**
1160
- * Removes a task function from this pool.
1161
- * @param name - The name of the task function.
1162
- * @returns `true` if the task function was removed, `false` otherwise.
1163
- */
1164
- readonly removeTaskFunction: (name: string) => Promise<boolean>;
1272
+ interface TasksQueueOptions {
1165
1273
  /**
1166
- * Sets the default task function in this pool.
1167
- * @param name - The name of the task function.
1168
- * @returns `true` if the default task function was set, `false` otherwise.
1274
+ * Maximum number of tasks that can be executed concurrently on a worker node.
1275
+ * @defaultValue 1
1169
1276
  */
1170
- readonly setDefaultTaskFunction: (name: string) => Promise<boolean>;
1277
+ readonly concurrency?: number;
1171
1278
  /**
1172
- * Sets the worker node tasks queue options in this pool.
1173
- * @param tasksQueueOptions - The worker node tasks queue options.
1279
+ * Maximum tasks queue size per worker node flagging it as back pressured.
1280
+ * @defaultValue (pool maximum size)^2
1174
1281
  */
1175
- readonly setTasksQueueOptions: (tasksQueueOptions: TasksQueueOptions) => void;
1282
+ readonly size?: number;
1176
1283
  /**
1177
- * Sets the default worker choice strategy in this pool.
1178
- * @param workerChoiceStrategy - The default worker choice strategy.
1179
- * @param workerChoiceStrategyOptions - The worker choice strategy options.
1284
+ * Queued tasks finished timeout in milliseconds at worker node termination.
1285
+ * @defaultValue 2000
1180
1286
  */
1181
- readonly setWorkerChoiceStrategy: (workerChoiceStrategy: WorkerChoiceStrategy, workerChoiceStrategyOptions?: WorkerChoiceStrategyOptions) => void;
1287
+ readonly tasksFinishedTimeout?: number;
1182
1288
  /**
1183
- * Sets the worker choice strategy options in this pool.
1184
- * @param workerChoiceStrategyOptions - The worker choice strategy options.
1185
- * @returns `true` if the worker choice strategy options were set, `false` otherwise.
1289
+ * Whether to enable tasks stealing under back pressure.
1290
+ * @defaultValue true
1186
1291
  */
1187
- readonly setWorkerChoiceStrategyOptions: (workerChoiceStrategyOptions: WorkerChoiceStrategyOptions) => boolean;
1292
+ readonly tasksStealingOnBackPressure?: boolean;
1188
1293
  /**
1189
- * Starts the minimum number of workers in this pool.
1294
+ * Ratio of worker nodes that can steal tasks from another worker node.
1295
+ * @defaultValue 0.6
1190
1296
  */
1191
- readonly start: () => void;
1297
+ readonly tasksStealingRatio?: number;
1192
1298
  /**
1193
- * Pool worker nodes.
1194
- * @internal
1299
+ * Whether to enable task stealing on idle.
1300
+ * @defaultValue true
1195
1301
  */
1196
- readonly workerNodes: IWorkerNode<Worker, Data>[];
1302
+ readonly taskStealing?: boolean;
1197
1303
  }
1198
1304
 
1199
1305
  /**
@@ -1205,6 +1311,10 @@ interface IPool<Worker extends IWorker, Data = unknown, Response = unknown> {
1205
1311
  */
1206
1312
  declare class WorkerChoiceStrategiesContext<Worker extends IWorker, Data = unknown, Response = unknown> {
1207
1313
  private readonly pool;
1314
+ /**
1315
+ * The number of worker choice strategies execution retries.
1316
+ */
1317
+ retriesCount: number;
1208
1318
  /**
1209
1319
  * The default worker choice strategy in the context.
1210
1320
  */
@@ -1225,10 +1335,6 @@ declare class WorkerChoiceStrategiesContext<Worker extends IWorker, Data = unkno
1225
1335
  * The active worker choice strategies in the context task statistics requirements.
1226
1336
  */
1227
1337
  private workerChoiceStrategiesTaskStatisticsRequirements;
1228
- /**
1229
- * The number of worker choice strategies execution retries.
1230
- */
1231
- retriesCount: number;
1232
1338
  /**
1233
1339
  * Worker choice strategies context constructor.
1234
1340
  * @param pool - The pool instance.
@@ -1236,27 +1342,6 @@ declare class WorkerChoiceStrategiesContext<Worker extends IWorker, Data = unkno
1236
1342
  * @param opts - The worker choice strategy options.
1237
1343
  */
1238
1344
  constructor(pool: IPool<Worker, Data, Response>, workerChoiceStrategies?: WorkerChoiceStrategy[], opts?: WorkerChoiceStrategyOptions);
1239
- /**
1240
- * Adds a worker choice strategy to the context.
1241
- * @param workerChoiceStrategy - The worker choice strategy to add.
1242
- * @param pool - The pool instance.
1243
- * @param opts - The worker choice strategy options.
1244
- * @returns The worker choice strategies.
1245
- */
1246
- private addWorkerChoiceStrategy;
1247
- /**
1248
- * Executes the given worker choice strategy.
1249
- * @param workerChoiceStrategy - The worker choice strategy.
1250
- * @returns The key of the worker node.
1251
- * @throws {@link https://nodejs.org/api/errors.html#class-error} If after computed retries the worker node key is null or undefined.
1252
- */
1253
- private executeStrategy;
1254
- /**
1255
- * Removes a worker choice strategy from the context.
1256
- * @param workerChoiceStrategy - The worker choice strategy to remove.
1257
- * @returns `true` if the worker choice strategy is removed, `false` otherwise.
1258
- */
1259
- private removeWorkerChoiceStrategy;
1260
1345
  /**
1261
1346
  * Executes the given worker choice strategy in the context algorithm.
1262
1347
  * @param workerChoiceStrategy - The worker choice strategy algorithm to execute. @defaultValue this.defaultWorkerChoiceStrategy
@@ -1303,6 +1388,27 @@ declare class WorkerChoiceStrategiesContext<Worker extends IWorker, Data = unkno
1303
1388
  * @returns `true` if the update is successful, `false` otherwise.
1304
1389
  */
1305
1390
  update(workerNodeKey: number): boolean;
1391
+ /**
1392
+ * Adds a worker choice strategy to the context.
1393
+ * @param workerChoiceStrategy - The worker choice strategy to add.
1394
+ * @param pool - The pool instance.
1395
+ * @param opts - The worker choice strategy options.
1396
+ * @returns The worker choice strategies.
1397
+ */
1398
+ private addWorkerChoiceStrategy;
1399
+ /**
1400
+ * Executes the given worker choice strategy.
1401
+ * @param workerChoiceStrategy - The worker choice strategy.
1402
+ * @returns The key of the worker node.
1403
+ * @throws {@link https://nodejs.org/api/errors.html#class-error} If after computed retries the worker node key is null or undefined.
1404
+ */
1405
+ private executeStrategy;
1406
+ /**
1407
+ * Removes a worker choice strategy from the context.
1408
+ * @param workerChoiceStrategy - The worker choice strategy to remove.
1409
+ * @returns `true` if the worker choice strategy is removed, `false` otherwise.
1410
+ */
1411
+ private removeWorkerChoiceStrategy;
1306
1412
  }
1307
1413
 
1308
1414
  /**
@@ -1316,6 +1422,12 @@ declare abstract class AbstractPool<Worker extends IWorker, Data = unknown, Resp
1316
1422
  protected readonly filePath: string;
1317
1423
  protected readonly opts: PoolOptions<Worker>;
1318
1424
  protected readonly maximumNumberOfWorkers?: number | undefined;
1425
+ /** @inheritDoc */
1426
+ emitter?: EventEmitterAsyncResource;
1427
+ /** @inheritDoc */
1428
+ readonly workerNodes: IWorkerNode<Worker, Data>[];
1429
+ /** @inheritDoc */
1430
+ get info(): PoolInfo;
1319
1431
  /**
1320
1432
  * The task execution response promise map:
1321
1433
  * - `key`: The message id of each submitted task.
@@ -1329,50 +1441,37 @@ declare abstract class AbstractPool<Worker extends IWorker, Data = unknown, Resp
1329
1441
  */
1330
1442
  protected workerChoiceStrategiesContext?: WorkerChoiceStrategiesContext<Worker, Data, Response>;
1331
1443
  /**
1332
- * This method is the message listener registered on each worker.
1333
- * @param message - The message received from the worker.
1334
- */
1335
- protected readonly workerMessageListener: (message: MessageValue<Response>) => void;
1336
- /**
1337
- * Whether the pool back pressure event has been emitted or not.
1444
+ * Whether the pool is back pressured or not.
1445
+ * @returns The pool back pressure boolean status.
1338
1446
  */
1339
- private backPressureEventEmitted;
1447
+ protected abstract get backPressure(): boolean;
1340
1448
  /**
1341
- * Whether the pool busy event has been emitted or not.
1449
+ * Whether the pool is busy or not.
1450
+ * @returns The pool busyness boolean status.
1342
1451
  */
1343
- private busyEventEmitted;
1452
+ protected abstract get busy(): boolean;
1344
1453
  /**
1345
- * Whether the pool is destroying or not.
1454
+ * The pool type.
1455
+ *
1456
+ * If it is `'dynamic'`, it provides the `max` property.
1346
1457
  */
1347
- private destroying;
1458
+ protected abstract get type(): PoolType;
1348
1459
  /**
1349
- * Gets task function worker choice strategy, if any.
1350
- * @param name - The task function name.
1351
- * @returns The task function worker choice strategy if the task function worker choice strategy is defined, `undefined` otherwise.
1460
+ * The worker type.
1352
1461
  */
1353
- private readonly getTaskFunctionWorkerChoiceStrategy;
1462
+ protected abstract get worker(): WorkerType;
1354
1463
  /**
1355
- * Gets the worker choice strategies registered in this pool.
1356
- * @returns The worker choice strategies.
1464
+ * Whether the pool back pressure event has been emitted or not.
1357
1465
  */
1358
- private readonly getWorkerChoiceStrategies;
1466
+ private backPressureEventEmitted;
1359
1467
  /**
1360
- * Gets worker node task function priority, if any.
1361
- * @param workerNodeKey - The worker node key.
1362
- * @param name - The task function name.
1363
- * @returns The worker node task function priority if the worker node task function priority is defined, `undefined` otherwise.
1468
+ * Whether the pool busy event has been emitted or not.
1364
1469
  */
1365
- private readonly getWorkerNodeTaskFunctionPriority;
1470
+ private busyEventEmitted;
1366
1471
  /**
1367
- * Gets worker node task function worker choice strategy, if any.
1368
- * @param workerNodeKey - The worker node key.
1369
- * @param name - The task function name.
1370
- * @returns The worker node task function worker choice strategy if the worker node task function worker choice strategy is defined, `undefined` otherwise.
1472
+ * Whether the pool is destroying or not.
1371
1473
  */
1372
- private readonly getWorkerNodeTaskFunctionWorkerChoiceStrategy;
1373
- private readonly handleWorkerNodeBackPressureEvent;
1374
- private readonly handleWorkerNodeIdleEvent;
1375
- private readonly isStealingRatioReached;
1474
+ private destroying;
1376
1475
  /**
1377
1476
  * Whether the pool ready event has been emitted or not.
1378
1477
  */
@@ -1393,18 +1492,22 @@ declare abstract class AbstractPool<Worker extends IWorker, Data = unknown, Resp
1393
1492
  * The start timestamp of the pool.
1394
1493
  */
1395
1494
  private startTimestamp?;
1396
- private readonly stealTask;
1397
1495
  /**
1398
1496
  * The task functions added at runtime map:
1399
1497
  * - `key`: The task function name.
1400
1498
  * - `value`: The task function object.
1401
1499
  */
1402
1500
  private readonly taskFunctions;
1403
- private readonly workerNodeStealTask;
1404
- /** @inheritDoc */
1405
- emitter?: EventEmitterAsyncResource;
1406
- /** @inheritDoc */
1407
- readonly workerNodes: IWorkerNode<Worker, Data>[];
1501
+ /**
1502
+ * Whether the pool is ready or not.
1503
+ * @returns The pool readiness boolean status.
1504
+ */
1505
+ private get ready();
1506
+ /**
1507
+ * The approximate pool utilization.
1508
+ * @returns The pool utilization.
1509
+ */
1510
+ private get utilization();
1408
1511
  /**
1409
1512
  * Constructs a new poolifier pool.
1410
1513
  * @param minimumNumberOfWorkers - Minimum number of workers that this pool manages.
@@ -1413,6 +1516,32 @@ declare abstract class AbstractPool<Worker extends IWorker, Data = unknown, Resp
1413
1516
  * @param maximumNumberOfWorkers - Maximum number of workers that this pool manages.
1414
1517
  */
1415
1518
  constructor(minimumNumberOfWorkers: number, filePath: string, opts: PoolOptions<Worker>, maximumNumberOfWorkers?: number | undefined);
1519
+ /** @inheritDoc */
1520
+ addTaskFunction(name: string, fn: TaskFunction<Data, Response> | TaskFunctionObject<Data, Response>): Promise<boolean>;
1521
+ /** @inheritDoc */
1522
+ destroy(): Promise<void>;
1523
+ /** @inheritDoc */
1524
+ enableTasksQueue(enable: boolean, tasksQueueOptions?: TasksQueueOptions): void;
1525
+ /** @inheritDoc */
1526
+ execute(data?: Data, name?: string, abortSignal?: AbortSignal, transferList?: readonly Transferable[]): Promise<Response>;
1527
+ /** @inheritDoc */
1528
+ hasTaskFunction(name: string): boolean;
1529
+ /** @inheritDoc */
1530
+ listTaskFunctionsProperties(): TaskFunctionProperties[];
1531
+ /** @inheritDoc */
1532
+ mapExecute(data: Iterable<Data>, name?: string, abortSignals?: Iterable<AbortSignal>, transferList?: readonly Transferable[]): Promise<Response[]>;
1533
+ /** @inheritDoc */
1534
+ removeTaskFunction(name: string): Promise<boolean>;
1535
+ /** @inheritDoc */
1536
+ setDefaultTaskFunction(name: string): Promise<boolean>;
1537
+ /** @inheritDoc */
1538
+ setTasksQueueOptions(tasksQueueOptions: TasksQueueOptions | undefined): void;
1539
+ /** @inheritDoc */
1540
+ setWorkerChoiceStrategy(workerChoiceStrategy: WorkerChoiceStrategy, workerChoiceStrategyOptions?: WorkerChoiceStrategyOptions): void;
1541
+ /** @inheritDoc */
1542
+ setWorkerChoiceStrategyOptions(workerChoiceStrategyOptions: undefined | WorkerChoiceStrategyOptions): boolean;
1543
+ /** @inheritdoc */
1544
+ start(): void;
1416
1545
  /**
1417
1546
  * Hook executed after the worker task execution.
1418
1547
  * Can be overridden.
@@ -1508,7 +1637,7 @@ declare abstract class AbstractPool<Worker extends IWorker, Data = unknown, Resp
1508
1637
  * @param message - The message.
1509
1638
  * @param transferList - The optional array of transferable objects.
1510
1639
  */
1511
- protected abstract sendToWorker(workerNodeKey: number, message: MessageValue<Data>, transferList?: readonly TransferListItem[]): void;
1640
+ protected abstract sendToWorker(workerNodeKey: number, message: MessageValue<Data>, transferList?: readonly Transferable[]): void;
1512
1641
  /**
1513
1642
  * Setup hook to execute code before worker nodes are created in the abstract constructor.
1514
1643
  * Can be overridden.
@@ -1519,6 +1648,12 @@ declare abstract class AbstractPool<Worker extends IWorker, Data = unknown, Resp
1519
1648
  * @returns Whether to create a dynamic worker or not.
1520
1649
  */
1521
1650
  protected abstract shallCreateDynamicWorker(): boolean;
1651
+ /**
1652
+ * This method is the message listener registered on each worker.
1653
+ * @param message - The message received from the worker.
1654
+ */
1655
+ protected readonly workerMessageListener: (message: MessageValue<Response>) => void;
1656
+ private readonly abortTask;
1522
1657
  /**
1523
1658
  * Adds the given worker node in the pool worker nodes.
1524
1659
  * @param workerNode - The worker node.
@@ -1563,16 +1698,44 @@ declare abstract class AbstractPool<Worker extends IWorker, Data = unknown, Resp
1563
1698
  */
1564
1699
  private executeTask;
1565
1700
  private flushTasksQueues;
1701
+ private readonly getAbortError;
1702
+ /**
1703
+ * Gets task function worker choice strategy, if any.
1704
+ * @param name - The task function name.
1705
+ * @returns The task function worker choice strategy if the task function worker choice strategy is defined, `undefined` otherwise.
1706
+ */
1707
+ private readonly getTaskFunctionWorkerChoiceStrategy;
1566
1708
  private getTasksQueuePriority;
1709
+ /**
1710
+ * Gets the worker choice strategies registered in this pool.
1711
+ * @returns The worker choice strategies.
1712
+ */
1713
+ private readonly getWorkerChoiceStrategies;
1567
1714
  /**
1568
1715
  * Gets the worker node key given its worker id.
1569
1716
  * @param workerId - The worker id.
1570
1717
  * @returns The worker node key if the worker id is found in the pool worker nodes, `-1` otherwise.
1571
1718
  */
1572
1719
  private getWorkerNodeKeyByWorkerId;
1720
+ /**
1721
+ * Gets worker node task function priority, if any.
1722
+ * @param workerNodeKey - The worker node key.
1723
+ * @param name - The task function name.
1724
+ * @returns The worker node task function priority if the worker node task function priority is defined, `undefined` otherwise.
1725
+ */
1726
+ private readonly getWorkerNodeTaskFunctionPriority;
1727
+ /**
1728
+ * Gets worker node task function worker choice strategy, if any.
1729
+ * @param workerNodeKey - The worker node key.
1730
+ * @param name - The task function name.
1731
+ * @returns The worker node task function worker choice strategy if the worker node task function worker choice strategy is defined, `undefined` otherwise.
1732
+ */
1733
+ private readonly getWorkerNodeTaskFunctionWorkerChoiceStrategy;
1573
1734
  private handleTask;
1574
1735
  private handleTaskExecutionResponse;
1575
- private handleWorkerError;
1736
+ private readonly handleWorkerError;
1737
+ private readonly handleWorkerNodeBackPressureEvent;
1738
+ private readonly handleWorkerNodeIdleEvent;
1576
1739
  private handleWorkerReadyResponse;
1577
1740
  private initEventEmitter;
1578
1741
  /**
@@ -1581,6 +1744,7 @@ declare abstract class AbstractPool<Worker extends IWorker, Data = unknown, Resp
1581
1744
  */
1582
1745
  private initWorkerNodeUsage;
1583
1746
  private internalExecute;
1747
+ private readonly isStealingRatioReached;
1584
1748
  private isWorkerNodeBackPressured;
1585
1749
  private isWorkerNodeBusy;
1586
1750
  private isWorkerNodeIdle;
@@ -1616,69 +1780,13 @@ declare abstract class AbstractPool<Worker extends IWorker, Data = unknown, Resp
1616
1780
  * @param initWorkerNodeUsage - Whether to initialize the worker node usage or not. @defaultValue false
1617
1781
  */
1618
1782
  private startMinimumNumberOfWorkers;
1783
+ private readonly stealTask;
1619
1784
  private tasksQueueSize;
1620
1785
  private unsetTasksStealingOnBackPressure;
1621
1786
  private unsetTaskStealing;
1622
1787
  private updateTaskSequentiallyStolenStatisticsWorkerUsage;
1623
1788
  private updateTaskStolenStatisticsWorkerUsage;
1624
- /** @inheritDoc */
1625
- addTaskFunction(name: string, fn: TaskFunction<Data, Response> | TaskFunctionObject<Data, Response>): Promise<boolean>;
1626
- /** @inheritDoc */
1627
- destroy(): Promise<void>;
1628
- /** @inheritDoc */
1629
- enableTasksQueue(enable: boolean, tasksQueueOptions?: TasksQueueOptions): void;
1630
- /** @inheritDoc */
1631
- execute(data?: Data, name?: string, transferList?: readonly TransferListItem[]): Promise<Response>;
1632
- /** @inheritDoc */
1633
- hasTaskFunction(name: string): boolean;
1634
- /** @inheritDoc */
1635
- listTaskFunctionsProperties(): TaskFunctionProperties[];
1636
- /** @inheritDoc */
1637
- mapExecute(data: Iterable<Data>, name?: string, transferList?: readonly TransferListItem[]): Promise<Response[]>;
1638
- /** @inheritDoc */
1639
- removeTaskFunction(name: string): Promise<boolean>;
1640
- /** @inheritDoc */
1641
- setDefaultTaskFunction(name: string): Promise<boolean>;
1642
- /** @inheritDoc */
1643
- setTasksQueueOptions(tasksQueueOptions: TasksQueueOptions | undefined): void;
1644
- /** @inheritDoc */
1645
- setWorkerChoiceStrategy(workerChoiceStrategy: WorkerChoiceStrategy, workerChoiceStrategyOptions?: WorkerChoiceStrategyOptions): void;
1646
- /** @inheritDoc */
1647
- setWorkerChoiceStrategyOptions(workerChoiceStrategyOptions: undefined | WorkerChoiceStrategyOptions): boolean;
1648
- /** @inheritdoc */
1649
- start(): void;
1650
- /**
1651
- * Whether the pool is back pressured or not.
1652
- * @returns The pool back pressure boolean status.
1653
- */
1654
- protected abstract get backPressure(): boolean;
1655
- /**
1656
- * Whether the pool is busy or not.
1657
- * @returns The pool busyness boolean status.
1658
- */
1659
- protected abstract get busy(): boolean;
1660
- /** @inheritDoc */
1661
- get info(): PoolInfo;
1662
- /**
1663
- * Whether the pool is ready or not.
1664
- * @returns The pool readiness boolean status.
1665
- */
1666
- private get ready();
1667
- /**
1668
- * The pool type.
1669
- *
1670
- * If it is `'dynamic'`, it provides the `max` property.
1671
- */
1672
- protected abstract get type(): PoolType;
1673
- /**
1674
- * The approximate pool utilization.
1675
- * @returns The pool utilization.
1676
- */
1677
- private get utilization();
1678
- /**
1679
- * The worker type.
1680
- */
1681
- protected abstract get worker(): WorkerType;
1789
+ private readonly workerNodeStealTask;
1682
1790
  }
1683
1791
 
1684
1792
  /**
@@ -1693,6 +1801,14 @@ type ClusterPoolOptions = PoolOptions<Worker>;
1693
1801
  * @since 2.0.0
1694
1802
  */
1695
1803
  declare class FixedClusterPool<Data = unknown, Response = unknown> extends AbstractPool<Worker, Data, Response> {
1804
+ /** @inheritDoc */
1805
+ protected get backPressure(): boolean;
1806
+ /** @inheritDoc */
1807
+ protected get busy(): boolean;
1808
+ /** @inheritDoc */
1809
+ protected get type(): PoolType;
1810
+ /** @inheritDoc */
1811
+ protected get worker(): WorkerType;
1696
1812
  /**
1697
1813
  * Constructs a new poolifier fixed cluster pool.
1698
1814
  * @param numberOfWorkers - Number of workers for this pool.
@@ -1720,15 +1836,7 @@ declare class FixedClusterPool<Data = unknown, Response = unknown> extends Abstr
1720
1836
  /** @inheritDoc */
1721
1837
  protected setupHook(): void;
1722
1838
  /** @inheritDoc */
1723
- protected shallCreateDynamicWorker(): boolean;
1724
- /** @inheritDoc */
1725
- protected get backPressure(): boolean;
1726
- /** @inheritDoc */
1727
- protected get busy(): boolean;
1728
- /** @inheritDoc */
1729
- protected get type(): PoolType;
1730
- /** @inheritDoc */
1731
- protected get worker(): WorkerType;
1839
+ protected shallCreateDynamicWorker(): boolean;
1732
1840
  }
1733
1841
 
1734
1842
  /**
@@ -1742,6 +1850,12 @@ declare class FixedClusterPool<Data = unknown, Response = unknown> extends Abstr
1742
1850
  * @since 2.0.0
1743
1851
  */
1744
1852
  declare class DynamicClusterPool<Data = unknown, Response = unknown> extends FixedClusterPool<Data, Response> {
1853
+ /** @inheritDoc */
1854
+ protected get backPressure(): boolean;
1855
+ /** @inheritDoc */
1856
+ protected get busy(): boolean;
1857
+ /** @inheritDoc */
1858
+ protected get type(): PoolType;
1745
1859
  /**
1746
1860
  * Whether the pool empty event has been emitted or not
1747
1861
  */
@@ -1750,6 +1864,16 @@ declare class DynamicClusterPool<Data = unknown, Response = unknown> extends Fix
1750
1864
  * Whether the pool full event has been emitted or not.
1751
1865
  */
1752
1866
  private fullEventEmitted;
1867
+ /**
1868
+ * Whether the pool is empty or not.
1869
+ * @returns The pool emptiness boolean status.
1870
+ */
1871
+ private get empty();
1872
+ /**
1873
+ * Whether the pool is full or not.
1874
+ * @returns The pool fullness boolean status.
1875
+ */
1876
+ private get full();
1753
1877
  /**
1754
1878
  * Constructs a new poolifier dynamic cluster pool.
1755
1879
  * @param min - Minimum number of workers which are always active.
@@ -1764,22 +1888,6 @@ declare class DynamicClusterPool<Data = unknown, Response = unknown> extends Fix
1764
1888
  protected checkAndEmitDynamicWorkerDestructionEvents(): void;
1765
1889
  /** @inheritDoc */
1766
1890
  protected shallCreateDynamicWorker(): boolean;
1767
- /** @inheritDoc */
1768
- protected get backPressure(): boolean;
1769
- /** @inheritDoc */
1770
- protected get busy(): boolean;
1771
- /**
1772
- * Whether the pool is empty or not.
1773
- * @returns The pool emptiness boolean status.
1774
- */
1775
- private get empty();
1776
- /**
1777
- * Whether the pool is full or not.
1778
- * @returns The pool fullness boolean status.
1779
- */
1780
- private get full();
1781
- /** @inheritDoc */
1782
- protected get type(): PoolType;
1783
1891
  }
1784
1892
 
1785
1893
  /**
@@ -1794,6 +1902,14 @@ type ThreadPoolOptions = PoolOptions<Worker$1>;
1794
1902
  * @since 0.0.1
1795
1903
  */
1796
1904
  declare class FixedThreadPool<Data = unknown, Response = unknown> extends AbstractPool<Worker$1, Data, Response> {
1905
+ /** @inheritDoc */
1906
+ protected get backPressure(): boolean;
1907
+ /** @inheritDoc */
1908
+ protected get busy(): boolean;
1909
+ /** @inheritDoc */
1910
+ protected get type(): PoolType;
1911
+ /** @inheritDoc */
1912
+ protected get worker(): WorkerType;
1797
1913
  /**
1798
1914
  * Constructs a new poolifier fixed thread pool.
1799
1915
  * @param numberOfThreads - Number of threads for this pool.
@@ -1817,17 +1933,9 @@ declare class FixedThreadPool<Data = unknown, Response = unknown> extends Abstra
1817
1933
  /** @inheritDoc */
1818
1934
  protected sendStartupMessageToWorker(workerNodeKey: number): void;
1819
1935
  /** @inheritDoc */
1820
- protected sendToWorker(workerNodeKey: number, message: MessageValue<Data>, transferList?: readonly TransferListItem[]): void;
1936
+ protected sendToWorker(workerNodeKey: number, message: MessageValue<Data>, transferList?: readonly Transferable[]): void;
1821
1937
  /** @inheritDoc */
1822
1938
  protected shallCreateDynamicWorker(): boolean;
1823
- /** @inheritDoc */
1824
- protected get backPressure(): boolean;
1825
- /** @inheritDoc */
1826
- protected get busy(): boolean;
1827
- /** @inheritDoc */
1828
- protected get type(): PoolType;
1829
- /** @inheritDoc */
1830
- protected get worker(): WorkerType;
1831
1939
  }
1832
1940
 
1833
1941
  /**
@@ -1841,6 +1949,12 @@ declare class FixedThreadPool<Data = unknown, Response = unknown> extends Abstra
1841
1949
  * @since 0.0.1
1842
1950
  */
1843
1951
  declare class DynamicThreadPool<Data = unknown, Response = unknown> extends FixedThreadPool<Data, Response> {
1952
+ /** @inheritDoc */
1953
+ protected get backPressure(): boolean;
1954
+ /** @inheritDoc */
1955
+ protected get busy(): boolean;
1956
+ /** @inheritDoc */
1957
+ protected get type(): PoolType;
1844
1958
  /**
1845
1959
  * Whether the pool empty event has been emitted or not
1846
1960
  */
@@ -1849,6 +1963,16 @@ declare class DynamicThreadPool<Data = unknown, Response = unknown> extends Fixe
1849
1963
  * Whether the pool full event has been emitted or not.
1850
1964
  */
1851
1965
  private fullEventEmitted;
1966
+ /**
1967
+ * Whether the pool is empty or not.
1968
+ * @returns The pool emptiness boolean status.
1969
+ */
1970
+ private get empty();
1971
+ /**
1972
+ * Whether the pool is full or not.
1973
+ * @returns The pool fullness boolean status.
1974
+ */
1975
+ private get full();
1852
1976
  /**
1853
1977
  * Constructs a new poolifier dynamic thread pool.
1854
1978
  * @param min - Minimum number of threads which are always active.
@@ -1863,87 +1987,6 @@ declare class DynamicThreadPool<Data = unknown, Response = unknown> extends Fixe
1863
1987
  protected checkAndEmitDynamicWorkerDestructionEvents(): void;
1864
1988
  /** @inheritDoc */
1865
1989
  protected shallCreateDynamicWorker(): boolean;
1866
- /** @inheritDoc */
1867
- protected get backPressure(): boolean;
1868
- /** @inheritDoc */
1869
- protected get busy(): boolean;
1870
- /**
1871
- * Whether the pool is empty or not.
1872
- * @returns The pool emptiness boolean status.
1873
- */
1874
- private get empty();
1875
- /**
1876
- * Whether the pool is full or not.
1877
- * @returns The pool fullness boolean status.
1878
- */
1879
- private get full();
1880
- /** @inheritDoc */
1881
- protected get type(): PoolType;
1882
- }
1883
-
1884
- /**
1885
- * Priority queue.
1886
- * @typeParam T - Type of priority queue data.
1887
- * @internal
1888
- */
1889
- declare class PriorityQueue<T> {
1890
- private readonly bucketSize;
1891
- private head;
1892
- private priorityEnabled;
1893
- private tail;
1894
- /** The priority queue maximum size. */
1895
- maxSize: number;
1896
- /**
1897
- * Constructs a priority queue.
1898
- * @param bucketSize - Prioritized bucket size. @defaultValue defaultBucketSize
1899
- * @param enablePriority - Whether to enable priority. @defaultValue false
1900
- * @returns PriorityQueue.
1901
- */
1902
- constructor(bucketSize?: number, enablePriority?: boolean);
1903
- private getPriorityQueueNode;
1904
- /**
1905
- * Clears the priority queue.
1906
- */
1907
- clear(): void;
1908
- /**
1909
- * Dequeue data from the priority queue.
1910
- * @param bucket - The prioritized bucket to dequeue from.
1911
- * @returns The dequeued data or `undefined` if the priority queue is empty.
1912
- */
1913
- dequeue(bucket?: number): T | undefined;
1914
- /**
1915
- * Enqueue data into the priority queue.
1916
- * @param data - Data to enqueue.
1917
- * @param priority - Priority of the data. Lower values have higher priority.
1918
- * @returns The new size of the priority queue.
1919
- */
1920
- enqueue(data: T, priority?: number): number;
1921
- /**
1922
- * Returns an iterator for the priority queue.
1923
- * @returns An iterator for the priority queue.
1924
- * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols
1925
- */
1926
- [Symbol.iterator](): Iterator<T>;
1927
- /**
1928
- * The number of filled prioritized buckets.
1929
- * @returns The number of filled prioritized buckets.
1930
- */
1931
- get buckets(): number;
1932
- /**
1933
- * Whether priority is enabled.
1934
- * @returns Whether priority is enabled.
1935
- */
1936
- get enablePriority(): boolean;
1937
- /**
1938
- * Enables/disables priority.
1939
- * @param enablePriority - Whether to enable priority.
1940
- */
1941
- set enablePriority(enablePriority: boolean);
1942
- /**
1943
- * The priority queue size.
1944
- * @returns The priority queue size.
1945
- */
1946
- get size(): number;
1947
1990
  }
1948
1991
 
1949
1992
  /**
@@ -1973,6 +2016,12 @@ interface IFixedQueue<T> {
1973
2016
  * Clears the fixed queue.
1974
2017
  */
1975
2018
  clear: () => void;
2019
+ /**
2020
+ * Deletes the given data from the fixed priority queue.
2021
+ * @param data - Data to delete.
2022
+ * @returns `true` if the data was deleted, `false` otherwise.
2023
+ */
2024
+ delete: (data: T) => boolean;
1976
2025
  /**
1977
2026
  * Dequeue data from the fixed queue.
1978
2027
  * @returns The dequeued data or `undefined` if the fixed queue is empty.
@@ -2021,7 +2070,7 @@ declare const availableParallelism: () => number;
2021
2070
  * @typeParam Data - Type of data this worker receives from pool's execution. This can only be structured-cloneable data.
2022
2071
  * @typeParam Response - Type of response the worker sends back to the main worker. This can only be structured-cloneable data.
2023
2072
  */
2024
- declare abstract class AbstractWorker<MainWorker extends MessagePort | Worker, Data = unknown, Response = unknown> {
2073
+ declare abstract class AbstractWorker<MainWorker extends MessagePort | Worker, Data = unknown, Response = unknown> extends EventEmitter {
2025
2074
  protected readonly isMain: boolean | undefined;
2026
2075
  private readonly mainWorker;
2027
2076
  protected opts: WorkerOptions;
@@ -2032,32 +2081,19 @@ declare abstract class AbstractWorker<MainWorker extends MessagePort | Worker, D
2032
2081
  /**
2033
2082
  * Worker id.
2034
2083
  */
2035
- protected abstract id: number;
2084
+ protected abstract readonly id: number;
2036
2085
  /**
2037
2086
  * Timestamp of the last task processed by this worker.
2038
2087
  */
2039
2088
  protected lastTaskTimestamp: number;
2040
- /**
2041
- * Runs the given task.
2042
- * @param task - The task to execute.
2043
- */
2044
- protected readonly run: (task: Task<Data>) => void;
2045
- /**
2046
- * Runs the given task function asynchronously.
2047
- * @param fn - Task function that will be executed.
2048
- * @param task - Input data for the task function.
2049
- */
2050
- protected readonly runAsync: (fn: TaskAsyncFunction<Data, Response>, task: Task<Data>) => void;
2051
- /**
2052
- * Runs the given task function synchronously.
2053
- * @param fn - Task function that will be executed.
2054
- * @param task - Input data for the task function.
2055
- */
2056
- protected readonly runSync: (fn: TaskSyncFunction<Data, Response>, task: Task<Data>) => void;
2057
2089
  /**
2058
2090
  * Performance statistics computation requirements.
2059
2091
  */
2060
2092
  protected statistics?: WorkerStatistics;
2093
+ /**
2094
+ * Task abort functions processed by the worker when task operation 'abort' is received.
2095
+ */
2096
+ protected taskAbortFunctions: Map<`${string}-${string}-${string}-${string}-${string}`, () => void>;
2061
2097
  /**
2062
2098
  * Task function object(s) processed by the worker when the pool's `execute` method is invoked.
2063
2099
  */
@@ -2070,6 +2106,37 @@ declare abstract class AbstractWorker<MainWorker extends MessagePort | Worker, D
2070
2106
  * @param opts - Options for the worker.
2071
2107
  */
2072
2108
  constructor(isMain: boolean | undefined, mainWorker: MainWorker | null | undefined, taskFunctions: TaskFunction<Data, Response> | TaskFunctions<Data, Response>, opts?: WorkerOptions);
2109
+ /**
2110
+ * Adds a task function to the worker.
2111
+ * If a task function with the same name already exists, it is replaced.
2112
+ * @param name - The name of the task function to add.
2113
+ * @param fn - The task function to add.
2114
+ * @returns Whether the task function was added or not.
2115
+ */
2116
+ addTaskFunction(name: string, fn: TaskFunction<Data, Response> | TaskFunctionObject<Data, Response>): TaskFunctionOperationResult;
2117
+ /**
2118
+ * Checks if the worker has a task function with the given name.
2119
+ * @param name - The name of the task function to check.
2120
+ * @returns Whether the worker has a task function with the given name or not.
2121
+ */
2122
+ hasTaskFunction(name: string): TaskFunctionOperationResult;
2123
+ /**
2124
+ * Lists the properties of the worker's task functions.
2125
+ * @returns The properties of the worker's task functions.
2126
+ */
2127
+ listTaskFunctionsProperties(): TaskFunctionProperties[];
2128
+ /**
2129
+ * Removes a task function from the worker.
2130
+ * @param name - The name of the task function to remove.
2131
+ * @returns Whether the task function existed and was removed or not.
2132
+ */
2133
+ removeTaskFunction(name: string): TaskFunctionOperationResult;
2134
+ /**
2135
+ * Sets the default task function to use in the worker.
2136
+ * @param name - The name of the task function to use as default task function.
2137
+ * @returns Whether the default task function was set or not.
2138
+ */
2139
+ setDefaultTaskFunction(name: string): TaskFunctionOperationResult;
2073
2140
  /**
2074
2141
  * Returns the main worker.
2075
2142
  * @returns Reference to the main worker.
@@ -2082,6 +2149,7 @@ declare abstract class AbstractWorker<MainWorker extends MessagePort | Worker, D
2082
2149
  * @returns The worker error object.
2083
2150
  */
2084
2151
  protected abstract handleError(error: Error): {
2152
+ aborted: boolean;
2085
2153
  error?: Error;
2086
2154
  message: string;
2087
2155
  stack?: string;
@@ -2102,6 +2170,23 @@ declare abstract class AbstractWorker<MainWorker extends MessagePort | Worker, D
2102
2170
  * @param message - The received message.
2103
2171
  */
2104
2172
  protected messageListener(message: MessageValue<Data>): void;
2173
+ /**
2174
+ * Runs the given task.
2175
+ * @param task - The task to execute.
2176
+ */
2177
+ protected readonly run: (task: Task<Data>) => void;
2178
+ /**
2179
+ * Runs the given task function asynchronously.
2180
+ * @param fn - Task function that will be executed.
2181
+ * @param task - Input data for the task function.
2182
+ */
2183
+ protected readonly runAsync: (fn: TaskAsyncFunction<Data, Response>, task: Task<Data>) => void;
2184
+ /**
2185
+ * Runs the given task function synchronously.
2186
+ * @param fn - Task function that will be executed.
2187
+ * @param task - Input data for the task function.
2188
+ */
2189
+ protected readonly runSync: (fn: TaskSyncFunction<Data, Response>, task: Task<Data>) => void;
2105
2190
  /**
2106
2191
  * Sends task functions properties to the main worker.
2107
2192
  */
@@ -2129,6 +2214,14 @@ declare abstract class AbstractWorker<MainWorker extends MessagePort | Worker, D
2129
2214
  private checkTaskFunctions;
2130
2215
  private checkWorkerOptions;
2131
2216
  private endTaskPerformance;
2217
+ /**
2218
+ * Gets abortable task function.
2219
+ * An abortable promise is built to permit the task to be aborted.
2220
+ * @param name - The name of the task.
2221
+ * @param taskId - The task id.
2222
+ * @returns The abortable task function.
2223
+ */
2224
+ private getAbortableTaskFunction;
2132
2225
  /**
2133
2226
  * Starts the worker check active interval.
2134
2227
  */
@@ -2138,37 +2231,6 @@ declare abstract class AbstractWorker<MainWorker extends MessagePort | Worker, D
2138
2231
  */
2139
2232
  private stopCheckActive;
2140
2233
  private updateLastTaskTimestamp;
2141
- /**
2142
- * Adds a task function to the worker.
2143
- * If a task function with the same name already exists, it is replaced.
2144
- * @param name - The name of the task function to add.
2145
- * @param fn - The task function to add.
2146
- * @returns Whether the task function was added or not.
2147
- */
2148
- addTaskFunction(name: string, fn: TaskFunction<Data, Response> | TaskFunctionObject<Data, Response>): TaskFunctionOperationResult;
2149
- /**
2150
- * Checks if the worker has a task function with the given name.
2151
- * @param name - The name of the task function to check.
2152
- * @returns Whether the worker has a task function with the given name or not.
2153
- */
2154
- hasTaskFunction(name: string): TaskFunctionOperationResult;
2155
- /**
2156
- * Lists the properties of the worker's task functions.
2157
- * @returns The properties of the worker's task functions.
2158
- */
2159
- listTaskFunctionsProperties(): TaskFunctionProperties[];
2160
- /**
2161
- * Removes a task function from the worker.
2162
- * @param name - The name of the task function to remove.
2163
- * @returns Whether the task function existed and was removed or not.
2164
- */
2165
- removeTaskFunction(name: string): TaskFunctionOperationResult;
2166
- /**
2167
- * Sets the default task function to use in the worker.
2168
- * @param name - The name of the task function to use as default task function.
2169
- * @returns Whether the default task function was set or not.
2170
- */
2171
- setDefaultTaskFunction(name: string): TaskFunctionOperationResult;
2172
2234
  }
2173
2235
 
2174
2236
  /**
@@ -2186,7 +2248,7 @@ declare abstract class AbstractWorker<MainWorker extends MessagePort | Worker, D
2186
2248
  */
2187
2249
  declare class ClusterWorker<Data = unknown, Response = unknown> extends AbstractWorker<Worker, Data, Response> {
2188
2250
  /** @inheritDoc */
2189
- protected readonly sendToMainWorker: (message: MessageValue<Response>) => void;
2251
+ protected get id(): number;
2190
2252
  /**
2191
2253
  * Constructs a new poolifier cluster worker.
2192
2254
  * @param taskFunctions - Task function(s) processed by the worker when the pool's `execute` method is invoked.
@@ -2197,13 +2259,14 @@ declare class ClusterWorker<Data = unknown, Response = unknown> extends Abstract
2197
2259
  * @inheritDoc
2198
2260
  */
2199
2261
  protected handleError(error: Error): {
2262
+ aborted: boolean;
2200
2263
  message: string;
2201
2264
  stack?: string;
2202
2265
  };
2203
2266
  /** @inheritDoc */
2204
2267
  protected handleReadyMessage(message: MessageValue<Data>): void;
2205
2268
  /** @inheritDoc */
2206
- protected get id(): number;
2269
+ protected readonly sendToMainWorker: (message: MessageValue<Response>) => void;
2207
2270
  }
2208
2271
 
2209
2272
  /**
@@ -2221,7 +2284,7 @@ declare class ClusterWorker<Data = unknown, Response = unknown> extends Abstract
2221
2284
  */
2222
2285
  declare class ThreadWorker<Data = unknown, Response = unknown> extends AbstractWorker<MessagePort, Data, Response> {
2223
2286
  /** @inheritDoc */
2224
- protected readonly sendToMainWorker: (message: MessageValue<Response>) => void;
2287
+ protected get id(): number;
2225
2288
  /**
2226
2289
  * Message port used to communicate with the main worker.
2227
2290
  */
@@ -2236,6 +2299,7 @@ declare class ThreadWorker<Data = unknown, Response = unknown> extends AbstractW
2236
2299
  * @inheritDoc
2237
2300
  */
2238
2301
  protected handleError(error: Error): {
2302
+ aborted: boolean;
2239
2303
  error: Error;
2240
2304
  message: string;
2241
2305
  stack?: string;
@@ -2245,7 +2309,8 @@ declare class ThreadWorker<Data = unknown, Response = unknown> extends AbstractW
2245
2309
  /** @inheritDoc */
2246
2310
  protected handleReadyMessage(message: MessageValue<Data>): void;
2247
2311
  /** @inheritDoc */
2248
- protected get id(): number;
2312
+ protected readonly sendToMainWorker: (message: MessageValue<Response>) => void;
2249
2313
  }
2250
2314
 
2251
- export { AbstractPool, AbstractWorker, CircularBuffer, type ClusterPoolOptions, ClusterWorker, DynamicClusterPool, DynamicThreadPool, type ErrorHandler, type EventHandler, type EventLoopUtilizationMeasurementStatistics, type ExitHandler, FixedClusterPool, type FixedQueueNode, FixedThreadPool, type IFixedQueue, type IPool, type IWorker, type IWorkerChoiceStrategy, type IWorkerNode, type KillBehavior, KillBehaviors, type KillHandler, type Measurement, type MeasurementOptions, type MeasurementStatistics, type MeasurementStatisticsRequirements, Measurements, type MessageHandler, type MessageValue, type OnlineHandler, type PoolEvent, PoolEvents, type PoolInfo, type PoolOptions, type PoolType, PoolTypes, PriorityQueue, type PromiseResponseWrapper, type StrategyData, type StrategyPolicy, type Task, type TaskAsyncFunction, type TaskFunction, type TaskFunctionObject, type TaskFunctionOperationResult, type TaskFunctionProperties, type TaskFunctions, type TaskPerformance, type TaskStatistics, type TaskStatisticsRequirements, type TaskSyncFunction, type TasksQueueOptions, type ThreadPoolOptions, ThreadWorker, WorkerChoiceStrategies, WorkerChoiceStrategiesContext, type WorkerChoiceStrategy, type WorkerChoiceStrategyOptions, type WorkerError, type WorkerInfo, type WorkerNodeEventDetail, type WorkerNodeOptions, type WorkerOptions, type WorkerStatistics, type WorkerType, WorkerTypes, type WorkerUsage, type Writable, availableParallelism };
2315
+ export { AbstractPool, AbstractWorker, CircularBuffer, ClusterWorker, DynamicClusterPool, DynamicThreadPool, FixedClusterPool, FixedThreadPool, KillBehaviors, Measurements, PoolEvents, PoolTypes, PriorityQueue, ThreadWorker, WorkerChoiceStrategies, WorkerChoiceStrategiesContext, WorkerTypes, availableParallelism };
2316
+ export type { ClusterPoolOptions, ErrorHandler, EventHandler, EventLoopUtilizationMeasurementStatistics, ExitHandler, FixedQueueNode, IFixedQueue, IPool, IWorker, IWorkerChoiceStrategy, IWorkerNode, KillBehavior, KillHandler, Measurement, MeasurementOptions, MeasurementStatistics, MeasurementStatisticsRequirements, MessageHandler, MessageValue, OnlineHandler, PoolEvent, PoolInfo, PoolOptions, PoolType, PromiseResponseWrapper, StrategyData, StrategyPolicy, Task, TaskAsyncFunction, TaskFunction, TaskFunctionObject, TaskFunctionOperationResult, TaskFunctionProperties, TaskFunctions, TaskPerformance, TaskStatistics, TaskStatisticsRequirements, TaskSyncFunction, TasksQueueOptions, ThreadPoolOptions, WorkerChoiceStrategy, WorkerChoiceStrategyOptions, WorkerError, WorkerInfo, WorkerNodeEventDetail, WorkerNodeOptions, WorkerOptions, WorkerStatistics, WorkerType, WorkerUsage, Writable };