poolifier 2.3.7 → 2.3.9

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.
Files changed (27) hide show
  1. package/lib/index.d.ts +14 -881
  2. package/lib/index.js +1 -1
  3. package/lib/index.mjs +1 -0
  4. package/lib/pools/abstract-pool.d.ts +219 -0
  5. package/lib/pools/cluster/dynamic.d.ts +30 -0
  6. package/lib/pools/cluster/fixed.d.ts +64 -0
  7. package/lib/pools/pool-internal.d.ts +85 -0
  8. package/lib/pools/pool-worker.d.ts +35 -0
  9. package/lib/pools/pool.d.ts +73 -0
  10. package/lib/pools/selection-strategies/abstract-worker-choice-strategy.d.ts +27 -0
  11. package/lib/pools/selection-strategies/dynamic-pool-worker-choice-strategy.d.ts +27 -0
  12. package/lib/pools/selection-strategies/fair-share-worker-choice-strategy.d.ts +29 -0
  13. package/lib/pools/selection-strategies/less-recently-used-worker-choice-strategy.d.ts +15 -0
  14. package/lib/pools/selection-strategies/round-robin-worker-choice-strategy.d.ts +19 -0
  15. package/lib/pools/selection-strategies/selection-strategies-types.d.ts +55 -0
  16. package/lib/pools/selection-strategies/selection-strategies-utils.d.ts +11 -0
  17. package/lib/pools/selection-strategies/weighted-round-robin-worker-choice-strategy.d.ts +43 -0
  18. package/lib/pools/selection-strategies/worker-choice-strategy-context.d.ts +48 -0
  19. package/lib/pools/thread/dynamic.d.ts +31 -0
  20. package/lib/pools/thread/fixed.d.ts +48 -0
  21. package/lib/utility-types.d.ts +63 -0
  22. package/lib/utils.d.ts +4 -0
  23. package/lib/worker/abstract-worker.d.ts +86 -0
  24. package/lib/worker/cluster-worker.d.ts +32 -0
  25. package/lib/worker/thread-worker.d.ts +30 -0
  26. package/lib/worker/worker-options.d.ts +61 -0
  27. package/package.json +52 -35
package/lib/index.d.ts CHANGED
@@ -1,881 +1,14 @@
1
- /// <reference types="node" />
2
- import EventEmitter from "events";
3
- import { ClusterSettings, Worker } from "cluster";
4
- import { Worker as ClusterWorker } from "cluster";
5
- import { MessagePort, MessageChannel } from "worker_threads";
6
- import { Worker as Worker$0 } from "worker_threads";
7
- import { AsyncResource } from "async_hooks";
8
- /**
9
- * Callback invoked if the worker has received a message.
10
- */
11
- type MessageHandler<Worker> = (this: Worker, m: unknown) => void;
12
- /**
13
- * Callback invoked if the worker raised an error.
14
- */
15
- type ErrorHandler<Worker> = (this: Worker, e: Error) => void;
16
- /**
17
- * Callback invoked when the worker has started successfully.
18
- */
19
- type OnlineHandler<Worker> = (this: Worker) => void;
20
- /**
21
- * Callback invoked when the worker exits successfully.
22
- */
23
- type ExitHandler<Worker> = (this: Worker, code: number) => void;
24
- /**
25
- * Interface that describes the minimum required implementation of listener events for a pool worker.
26
- */
27
- interface IPoolWorker {
28
- /**
29
- * Register an event listener.
30
- *
31
- * @param event The event.
32
- * @param handler The event listener.
33
- */
34
- on: ((event: "message", handler: MessageHandler<this>) => void) & ((event: "error", handler: ErrorHandler<this>) => void) & ((event: "online", handler: OnlineHandler<this>) => void) & ((event: "exit", handler: ExitHandler<this>) => void);
35
- /**
36
- * Register a listener to the exit event that will only performed once.
37
- *
38
- * @param event `'exit'`.
39
- * @param handler The exit handler.
40
- */
41
- once: (event: "exit", handler: ExitHandler<this>) => void;
42
- }
43
- /**
44
- * Enumeration of worker choice strategies.
45
- */
46
- declare const WorkerChoiceStrategies: Readonly<{
47
- readonly ROUND_ROBIN: "ROUND_ROBIN";
48
- readonly LESS_RECENTLY_USED: "LESS_RECENTLY_USED";
49
- readonly FAIR_SHARE: "FAIR_SHARE";
50
- readonly WEIGHTED_ROUND_ROBIN: "WEIGHTED_ROUND_ROBIN";
51
- }>;
52
- /**
53
- * Worker choice strategy.
54
- */
55
- type WorkerChoiceStrategy = keyof typeof WorkerChoiceStrategies;
56
- /**
57
- * Pool tasks usage statistics requirements.
58
- */
59
- interface RequiredStatistics {
60
- runTime: boolean;
61
- }
62
- /**
63
- * Worker choice strategy interface.
64
- *
65
- * @template Worker Type of worker which manages the strategy.
66
- */
67
- interface IWorkerChoiceStrategy<Worker extends IPoolWorker> {
68
- /**
69
- * Is the pool attached to the strategy dynamic?.
70
- */
71
- readonly isDynamicPool: boolean;
72
- /**
73
- * Required pool tasks usage statistics.
74
- */
75
- readonly requiredStatistics: RequiredStatistics;
76
- /**
77
- * Resets strategy internals (counters, statistics, etc.).
78
- */
79
- reset: () => boolean;
80
- /**
81
- * Chooses a worker in the pool.
82
- */
83
- choose: () => Worker;
84
- }
85
- /**
86
- * Pool events emitter.
87
- */
88
- declare class PoolEmitter extends EventEmitter {
89
- }
90
- /**
91
- * Options for a poolifier pool.
92
- */
93
- interface PoolOptions<Worker> {
94
- /**
95
- * A function that will listen for message event on each worker.
96
- */
97
- messageHandler?: MessageHandler<Worker>;
98
- /**
99
- * A function that will listen for error event on each worker.
100
- */
101
- errorHandler?: ErrorHandler<Worker>;
102
- /**
103
- * A function that will listen for online event on each worker.
104
- */
105
- onlineHandler?: OnlineHandler<Worker>;
106
- /**
107
- * A function that will listen for exit event on each worker.
108
- */
109
- exitHandler?: ExitHandler<Worker>;
110
- /**
111
- * The worker choice strategy to use in this pool.
112
- */
113
- workerChoiceStrategy?: WorkerChoiceStrategy;
114
- /**
115
- * Pool events emission.
116
- *
117
- * @default true
118
- */
119
- enableEvents?: boolean;
120
- }
121
- /**
122
- * Contract definition for a poolifier pool.
123
- *
124
- * @template Data Type of data sent to the worker. This can only be serializable data.
125
- * @template Response Type of response of execution. This can only be serializable data.
126
- */
127
- interface IPool<Data = unknown, Response = unknown> {
128
- /**
129
- * Emitter on which events can be listened to.
130
- *
131
- * Events that can currently be listened to:
132
- *
133
- * - `'busy'`
134
- */
135
- readonly emitter?: PoolEmitter;
136
- /**
137
- * Performs the task specified in the constructor with the data parameter.
138
- *
139
- * @param data The input for the specified task. This can only be serializable data.
140
- * @returns Promise that will be resolved when the task is successfully completed.
141
- */
142
- execute: (data: Data) => Promise<Response>;
143
- /**
144
- * Shutdowns every current worker in this pool.
145
- */
146
- destroy: () => Promise<void>;
147
- /**
148
- * Sets the worker choice strategy in this pool.
149
- *
150
- * @param workerChoiceStrategy The worker choice strategy.
151
- */
152
- setWorkerChoiceStrategy: (workerChoiceStrategy: WorkerChoiceStrategy) => void;
153
- }
154
- /**
155
- * Internal pool types.
156
- */
157
- declare enum PoolType {
158
- FIXED = "fixed",
159
- DYNAMIC = "dynamic"
160
- }
161
- /**
162
- * Internal tasks usage statistics.
163
- */
164
- interface TasksUsage {
165
- run: number;
166
- running: number;
167
- runTime: number;
168
- avgRunTime: number;
169
- }
170
- /**
171
- * Internal contract definition for a poolifier pool.
172
- *
173
- * @template Worker Type of worker which manages this pool.
174
- * @template Data Type of data sent to the worker.
175
- * @template Response Type of response of execution.
176
- */
177
- interface IPoolInternal<Worker extends IPoolWorker, Data = unknown, Response = unknown> extends IPool<Data, Response> {
178
- /**
179
- * List of currently available workers.
180
- */
181
- readonly workers: Worker[];
182
- /**
183
- * The workers tasks usage map.
184
- *
185
- * `key`: The `Worker`
186
- * `value`: Worker tasks usage statistics.
187
- */
188
- readonly workersTasksUsage: Map<Worker, TasksUsage>;
189
- /**
190
- * Pool type.
191
- *
192
- * If it is `'dynamic'`, it provides the `max` property.
193
- */
194
- readonly type: PoolType;
195
- /**
196
- * Whether the pool is busy or not.
197
- *
198
- * The pool busyness boolean status.
199
- */
200
- readonly busy: boolean;
201
- /**
202
- * Number of tasks currently concurrently running.
203
- */
204
- readonly numberOfRunningTasks: number;
205
- /**
206
- * Finds a free worker based on the number of tasks the worker has applied.
207
- *
208
- * If a worker is found with `0` running tasks, it is detected as free and returned.
209
- *
210
- * If no free worker is found, `false` is returned.
211
- *
212
- * @returns A free worker if there is one, otherwise `false`.
213
- */
214
- findFreeWorker: () => Worker | false;
215
- /**
216
- * Gets worker index.
217
- *
218
- * @param worker The worker.
219
- * @returns The worker index.
220
- */
221
- getWorkerIndex: (worker: Worker) => number;
222
- /**
223
- * Gets worker running tasks.
224
- *
225
- * @param worker The worker.
226
- * @returns The number of tasks currently running on the worker.
227
- */
228
- getWorkerRunningTasks: (worker: Worker) => number | undefined;
229
- /**
230
- * Gets worker average tasks runtime.
231
- *
232
- * @param worker The worker.
233
- * @returns The average tasks runtime on the worker.
234
- */
235
- getWorkerAverageTasksRunTime: (worker: Worker) => number | undefined;
236
- }
237
- /**
238
- * Enumeration of kill behaviors.
239
- */
240
- declare const KillBehaviors: Readonly<{
241
- readonly SOFT: "SOFT";
242
- readonly HARD: "HARD";
243
- }>;
244
- /**
245
- * Kill behavior.
246
- */
247
- type KillBehavior = keyof typeof KillBehaviors;
248
- /**
249
- * Options for workers.
250
- */
251
- interface WorkerOptions {
252
- /**
253
- * Maximum waiting time in milliseconds for tasks.
254
- *
255
- * After this time, newly created workers will be terminated.
256
- * The last active time of your worker unit will be updated when a task is submitted to a worker or when a worker terminate a task.
257
- *
258
- * - If `killBehavior` is set to `KillBehaviors.HARD` this value represents also the timeout for the tasks that you submit to the pool,
259
- * when this timeout expires your tasks is interrupted and the worker is killed if is not part of the minimum size of the pool.
260
- * - If `killBehavior` is set to `KillBehaviors.SOFT` your tasks have no timeout and your workers will not be terminated until your task is completed.
261
- *
262
- * @default 60000 ms
263
- */
264
- maxInactiveTime?: number;
265
- /**
266
- * Whether your worker will perform asynchronous or not.
267
- *
268
- * @default false
269
- */
270
- async?: boolean;
271
- /**
272
- * `killBehavior` dictates if your async unit (worker/process) will be deleted in case that a task is active on it.
273
- *
274
- * - SOFT: If `currentTime - lastActiveTime` is greater than `maxInactiveTime` but a task is still running, then the worker **won't** be deleted.
275
- * - HARD: If `lastActiveTime` is greater than `maxInactiveTime` but a task is still running, then the worker will be deleted.
276
- *
277
- * This option only apply to the newly created workers.
278
- *
279
- * @default KillBehaviors.SOFT
280
- */
281
- killBehavior?: KillBehavior;
282
- }
283
- /**
284
- * Make all properties in T non-readonly.
285
- */
286
- type Draft<T> = {
287
- -readonly [P in keyof T]?: T[P];
288
- };
289
- /**
290
- * Message object that is passed between worker and main worker.
291
- */
292
- interface MessageValue<Data = unknown, MainWorker extends ClusterWorker | MessagePort | unknown = unknown> {
293
- /**
294
- * Input data that will be passed to the worker.
295
- */
296
- readonly data?: Data;
297
- /**
298
- * Id of the message.
299
- */
300
- readonly id?: number;
301
- /**
302
- * Kill code.
303
- */
304
- readonly kill?: KillBehavior | 1;
305
- /**
306
- * Error.
307
- */
308
- readonly error?: string;
309
- /**
310
- * Task runtime.
311
- */
312
- readonly taskRunTime?: number;
313
- /**
314
- * Reference to main worker.
315
- *
316
- * Only for internal use.
317
- */
318
- readonly parent?: MainWorker;
319
- }
320
- /**
321
- * An object holding the worker that will be used to resolve/rejects the promise later on.
322
- *
323
- * @template Worker Type of worker.
324
- * @template Response Type of response of execution. This can only be serializable data.
325
- */
326
- interface PromiseWorkerResponseWrapper<Worker extends IPoolWorker, Response = unknown> {
327
- /**
328
- * Resolve callback to fulfill the promise.
329
- */
330
- readonly resolve: (value: Response) => void;
331
- /**
332
- * Reject callback to reject the promise.
333
- */
334
- readonly reject: (reason?: string) => void;
335
- /**
336
- * The worker that has the assigned task.
337
- */
338
- readonly worker: Worker;
339
- }
340
- /**
341
- * The worker choice strategy context.
342
- *
343
- * @template Worker Type of worker.
344
- * @template Data Type of data sent to the worker. This can only be serializable data.
345
- * @template Response Type of response of execution. This can only be serializable data.
346
- */
347
- declare class WorkerChoiceStrategyContext<Worker extends IPoolWorker, Data, Response> {
348
- private readonly pool;
349
- private readonly createDynamicallyWorkerCallback;
350
- private workerChoiceStrategy;
351
- /**
352
- * Worker choice strategy context constructor.
353
- *
354
- * @param pool The pool instance.
355
- * @param createDynamicallyWorkerCallback The worker creation callback for dynamic pool.
356
- * @param workerChoiceStrategy The worker choice strategy.
357
- */
358
- constructor(pool: IPoolInternal<Worker, Data, Response>, createDynamicallyWorkerCallback: () => Worker, workerChoiceStrategy?: WorkerChoiceStrategy);
359
- /**
360
- * Gets the worker choice strategy instance specific to the pool type.
361
- *
362
- * @param workerChoiceStrategy The worker choice strategy.
363
- * @returns The worker choice strategy instance for the pool type.
364
- */
365
- private getPoolWorkerChoiceStrategy;
366
- /**
367
- * Gets the worker choice strategy used in the context.
368
- *
369
- * @returns The worker choice strategy.
370
- */
371
- getWorkerChoiceStrategy(): IWorkerChoiceStrategy<Worker>;
372
- /**
373
- * Sets the worker choice strategy to use in the context.
374
- *
375
- * @param workerChoiceStrategy The worker choice strategy to set.
376
- */
377
- setWorkerChoiceStrategy(workerChoiceStrategy: WorkerChoiceStrategy): void;
378
- /**
379
- * Chooses a worker with the underlying selection strategy.
380
- *
381
- * @returns The chosen one.
382
- */
383
- execute(): Worker;
384
- }
385
- /**
386
- * Base class that implements some shared logic for all poolifier pools.
387
- *
388
- * @template Worker Type of worker which manages this pool.
389
- * @template Data Type of data sent to the worker. This can only be serializable data.
390
- * @template Response Type of response of execution. This can only be serializable data.
391
- */
392
- declare abstract class AbstractPool<Worker extends IPoolWorker, Data = unknown, Response = unknown> implements IPoolInternal<Worker, Data, Response> {
393
- readonly numberOfWorkers: number;
394
- readonly filePath: string;
395
- readonly opts: PoolOptions<Worker>;
396
- /** @inheritDoc */
397
- readonly workers: Worker[];
398
- /** @inheritDoc */
399
- readonly workersTasksUsage: Map<Worker, TasksUsage>;
400
- /** @inheritDoc */
401
- readonly emitter?: PoolEmitter;
402
- /**
403
- * The promise map.
404
- *
405
- * - `key`: This is the message Id of each submitted task.
406
- * - `value`: An object that contains the worker, the resolve function and the reject function.
407
- *
408
- * When we receive a message from the worker we get a map entry and resolve/reject the promise based on the message.
409
- */
410
- protected promiseMap: Map<number, PromiseWorkerResponseWrapper<Worker, Response>>;
411
- /**
412
- * Id of the next message.
413
- */
414
- protected nextMessageId: number;
415
- /**
416
- * Worker choice strategy instance implementing the worker choice algorithm.
417
- *
418
- * Default to a strategy implementing a round robin algorithm.
419
- */
420
- protected workerChoiceStrategyContext: WorkerChoiceStrategyContext<Worker, Data, Response>;
421
- /**
422
- * Constructs a new poolifier pool.
423
- *
424
- * @param numberOfWorkers Number of workers that this pool should manage.
425
- * @param filePath Path to the worker-file.
426
- * @param opts Options for the pool.
427
- */
428
- constructor(numberOfWorkers: number, filePath: string, opts: PoolOptions<Worker>);
429
- private checkFilePath;
430
- private checkNumberOfWorkers;
431
- private checkPoolOptions;
432
- /** @inheritDoc */
433
- abstract get type(): PoolType;
434
- /** @inheritDoc */
435
- get numberOfRunningTasks(): number;
436
- /** @inheritDoc */
437
- getWorkerIndex(worker: Worker): number;
438
- /** @inheritDoc */
439
- getWorkerRunningTasks(worker: Worker): number | undefined;
440
- /** @inheritDoc */
441
- getWorkerAverageTasksRunTime(worker: Worker): number | undefined;
442
- /** @inheritDoc */
443
- setWorkerChoiceStrategy(workerChoiceStrategy: WorkerChoiceStrategy): void;
444
- /** @inheritDoc */
445
- abstract get busy(): boolean;
446
- protected internalGetBusyStatus(): boolean;
447
- /** @inheritDoc */
448
- findFreeWorker(): Worker | false;
449
- /** @inheritDoc */
450
- execute(data: Data): Promise<Response>;
451
- /** @inheritDoc */
452
- destroy(): Promise<void>;
453
- /**
454
- * Shutdowns given worker.
455
- *
456
- * @param worker A worker within `workers`.
457
- */
458
- protected abstract destroyWorker(worker: Worker): void | Promise<void>;
459
- /**
460
- * Setup hook that can be overridden by a Poolifier pool implementation
461
- * to run code before workers are created in the abstract constructor.
462
- */
463
- protected setupHook(): void;
464
- /**
465
- * Should return whether the worker is the main worker or not.
466
- */
467
- protected abstract isMain(): boolean;
468
- /**
469
- * Hook executed before the worker task promise resolution.
470
- * Can be overridden.
471
- *
472
- * @param worker The worker.
473
- */
474
- protected beforePromiseWorkerResponseHook(worker: Worker): void;
475
- /**
476
- * Hook executed after the worker task promise resolution.
477
- * Can be overridden.
478
- *
479
- * @param message The received message.
480
- * @param promise The Promise response.
481
- */
482
- protected afterPromiseWorkerResponseHook(message: MessageValue<Response>, promise: PromiseWorkerResponseWrapper<Worker, Response>): void;
483
- /**
484
- * Removes the given worker from the pool.
485
- *
486
- * @param worker The worker that will be removed.
487
- */
488
- protected removeWorker(worker: Worker): void;
489
- /**
490
- * Chooses a worker for the next task.
491
- *
492
- * The default implementation uses a round robin algorithm to distribute the load.
493
- *
494
- * @returns Worker.
495
- */
496
- protected chooseWorker(): Worker;
497
- /**
498
- * Sends a message to the given worker.
499
- *
500
- * @param worker The worker which should receive the message.
501
- * @param message The message.
502
- */
503
- protected abstract sendToWorker(worker: Worker, message: MessageValue<Data>): void;
504
- /**
505
- * Registers a listener callback on a given worker.
506
- *
507
- * @param worker The worker which should register a listener.
508
- * @param listener The message listener callback.
509
- */
510
- protected abstract registerWorkerMessageListener<Message extends Data | Response>(worker: Worker, listener: (message: MessageValue<Message>) => void): void;
511
- /**
512
- * Returns a newly created worker.
513
- */
514
- protected abstract createWorker(): Worker;
515
- /**
516
- * Function that can be hooked up when a worker has been newly created and moved to the workers registry.
517
- *
518
- * Can be used to update the `maxListeners` or binding the `main-worker`<->`worker` connection if not bind by default.
519
- *
520
- * @param worker The newly created worker.
521
- */
522
- protected abstract afterWorkerSetup(worker: Worker): void;
523
- /**
524
- * Creates a new worker for this pool and sets it up completely.
525
- *
526
- * @returns New, completely set up worker.
527
- */
528
- protected createAndSetupWorker(): Worker;
529
- /**
530
- * This function is the listener registered for each worker.
531
- *
532
- * @returns The listener function to execute when a message is received from a worker.
533
- */
534
- protected workerListener(): (message: MessageValue<Response>) => void;
535
- private internalExecute;
536
- private checkAndEmitBusy;
537
- /**
538
- * Increases the number of tasks that the given worker has applied.
539
- *
540
- * @param worker Worker which running tasks is increased.
541
- */
542
- private increaseWorkerRunningTasks;
543
- /**
544
- * Decreases the number of tasks that the given worker has applied.
545
- *
546
- * @param worker Worker which running tasks is decreased.
547
- */
548
- private decreaseWorkerRunningTasks;
549
- /**
550
- * Steps the number of tasks that the given worker has applied.
551
- *
552
- * @param worker Worker which running tasks are stepped.
553
- * @param step Number of running tasks step.
554
- */
555
- private stepWorkerRunningTasks;
556
- /**
557
- * Steps the number of tasks that the given worker has run.
558
- *
559
- * @param worker Worker which has run tasks.
560
- * @param step Number of run tasks step.
561
- */
562
- private stepWorkerRunTasks;
563
- /**
564
- * Updates tasks runtime for the given worker.
565
- *
566
- * @param worker Worker which run the task.
567
- * @param taskRunTime Worker task runtime.
568
- */
569
- private updateWorkerTasksRunTime;
570
- /**
571
- * Checks if the given worker is registered in the workers tasks usage map.
572
- *
573
- * @param worker Worker to check.
574
- * @returns `true` if the worker is registered in the workers tasks usage map. `false` otherwise.
575
- */
576
- private checkWorkerTasksUsage;
577
- /**
578
- * Initializes tasks usage statistics.
579
- *
580
- * @param worker The worker.
581
- */
582
- private initWorkerTasksUsage;
583
- /**
584
- * Removes worker tasks usage statistics.
585
- *
586
- * @param worker The worker.
587
- */
588
- private removeWorkerTasksUsage;
589
- /**
590
- * Resets worker tasks usage statistics.
591
- *
592
- * @param worker The worker.
593
- */
594
- private resetWorkerTasksUsage;
595
- }
596
- /**
597
- * Options for a poolifier cluster pool.
598
- */
599
- interface ClusterPoolOptions extends PoolOptions<Worker> {
600
- /**
601
- * Key/value pairs to add to worker process environment.
602
- *
603
- * @see https://nodejs.org/api/cluster.html#cluster_cluster_fork_env
604
- */
605
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
606
- env?: any;
607
- /**
608
- * Cluster settings.
609
- *
610
- * @see https://nodejs.org/api/cluster.html#cluster_cluster_settings
611
- */
612
- settings?: ClusterSettings;
613
- }
614
- /**
615
- * A cluster pool with a fixed number of workers.
616
- *
617
- * It is possible to perform tasks in sync or asynchronous mode as you prefer.
618
- *
619
- * This pool selects the workers in a round robin fashion.
620
- *
621
- * @template Data Type of data sent to the worker. This can only be serializable data.
622
- * @template Response Type of response of execution. This can only be serializable data.
623
- * @author [Christopher Quadflieg](https://github.com/Shinigami92)
624
- * @since 2.0.0
625
- */
626
- declare class FixedClusterPool<Data = unknown, Response = unknown> extends AbstractPool<Worker, Data, Response> {
627
- readonly opts: ClusterPoolOptions;
628
- /**
629
- * Constructs a new poolifier fixed cluster pool.
630
- *
631
- * @param numberOfWorkers Number of workers for this pool.
632
- * @param filePath Path to an implementation of a `ClusterWorker` file, which can be relative or absolute.
633
- * @param opts Options for this fixed cluster pool.
634
- */
635
- constructor(numberOfWorkers: number, filePath: string, opts?: ClusterPoolOptions);
636
- /** @inheritDoc */
637
- protected setupHook(): void;
638
- /** @inheritDoc */
639
- protected isMain(): boolean;
640
- /** @inheritDoc */
641
- destroyWorker(worker: Worker): void;
642
- /** @inheritDoc */
643
- protected sendToWorker(worker: Worker, message: MessageValue<Data>): void;
644
- /** @inheritDoc */
645
- registerWorkerMessageListener<Message extends Data | Response>(worker: Worker, listener: (message: MessageValue<Message>) => void): void;
646
- /** @inheritDoc */
647
- protected createWorker(): Worker;
648
- /** @inheritDoc */
649
- protected afterWorkerSetup(worker: Worker): void;
650
- /** @inheritDoc */
651
- get type(): PoolType;
652
- /** @inheritDoc */
653
- get busy(): boolean;
654
- }
655
- /**
656
- * A cluster pool with a dynamic number of workers, but a guaranteed minimum number of workers.
657
- *
658
- * This cluster pool creates new workers when the others are busy, up to the maximum number of workers.
659
- * When the maximum number of workers is reached, an event is emitted. If you want to listen to this event, use the pool's `emitter`.
660
- *
661
- * @template Data Type of data sent to the worker. This can only be serializable data.
662
- * @template Response Type of response of execution. This can only be serializable data.
663
- * @author [Christopher Quadflieg](https://github.com/Shinigami92)
664
- * @since 2.0.0
665
- */
666
- declare class DynamicClusterPool<Data = unknown, Response = unknown> extends FixedClusterPool<Data, Response> {
667
- protected readonly max: number;
668
- /**
669
- * Constructs a new poolifier dynamic cluster pool.
670
- *
671
- * @param min Minimum number of workers which are always active.
672
- * @param max Maximum number of workers that can be created by this pool.
673
- * @param filePath Path to an implementation of a `ClusterWorker` file, which can be relative or absolute.
674
- * @param opts Options for this dynamic cluster pool.
675
- */
676
- constructor(min: number, max: number, filePath: string, opts?: ClusterPoolOptions);
677
- /** @inheritDoc */
678
- get type(): PoolType;
679
- /** @inheritDoc */
680
- get busy(): boolean;
681
- }
682
- /**
683
- * A thread worker with message channels for communication between main thread and thread worker.
684
- */
685
- type ThreadWorkerWithMessageChannel = Worker$0 & Draft<MessageChannel>;
686
- /**
687
- * A thread pool with a fixed number of threads.
688
- *
689
- * It is possible to perform tasks in sync or asynchronous mode as you prefer.
690
- *
691
- * This pool selects the threads in a round robin fashion.
692
- *
693
- * @template Data Type of data sent to the worker. This can only be serializable data.
694
- * @template Response Type of response of execution. This can only be serializable data.
695
- * @author [Alessandro Pio Ardizio](https://github.com/pioardi)
696
- * @since 0.0.1
697
- */
698
- declare class FixedThreadPool<Data = unknown, Response = unknown> extends AbstractPool<ThreadWorkerWithMessageChannel, Data, Response> {
699
- /**
700
- * Constructs a new poolifier fixed thread pool.
701
- *
702
- * @param numberOfThreads Number of threads for this pool.
703
- * @param filePath Path to an implementation of a `ThreadWorker` file, which can be relative or absolute.
704
- * @param opts Options for this fixed thread pool.
705
- */
706
- constructor(numberOfThreads: number, filePath: string, opts?: PoolOptions<ThreadWorkerWithMessageChannel>);
707
- /** @inheritDoc */
708
- protected isMain(): boolean;
709
- /** @inheritDoc */
710
- destroyWorker(worker: ThreadWorkerWithMessageChannel): Promise<void>;
711
- /** @inheritDoc */
712
- protected sendToWorker(worker: ThreadWorkerWithMessageChannel, message: MessageValue<Data>): void;
713
- /** @inheritDoc */
714
- registerWorkerMessageListener<Message extends Data | Response>(messageChannel: ThreadWorkerWithMessageChannel, listener: (message: MessageValue<Message>) => void): void;
715
- /** @inheritDoc */
716
- protected createWorker(): ThreadWorkerWithMessageChannel;
717
- /** @inheritDoc */
718
- protected afterWorkerSetup(worker: ThreadWorkerWithMessageChannel): void;
719
- /** @inheritDoc */
720
- get type(): PoolType;
721
- /** @inheritDoc */
722
- get busy(): boolean;
723
- }
724
- /**
725
- * A thread pool with a dynamic number of threads, but a guaranteed minimum number of threads.
726
- *
727
- * This thread pool creates new threads when the others are busy, up to the maximum number of threads.
728
- * When the maximum number of threads is reached, an event is emitted. If you want to listen to this event, use the pool's `emitter`.
729
- *
730
- * @template Data Type of data sent to the worker. This can only be serializable data.
731
- * @template Response Type of response of execution. This can only be serializable data.
732
- * @author [Alessandro Pio Ardizio](https://github.com/pioardi)
733
- * @since 0.0.1
734
- */
735
- declare class DynamicThreadPool<Data = unknown, Response = unknown> extends FixedThreadPool<Data, Response> {
736
- protected readonly max: number;
737
- /**
738
- * Constructs a new poolifier dynamic thread pool.
739
- *
740
- * @param min Minimum number of threads which are always active.
741
- * @param max Maximum number of threads that can be created by this pool.
742
- * @param filePath Path to an implementation of a `ThreadWorker` file, which can be relative or absolute.
743
- * @param opts Options for this dynamic thread pool.
744
- */
745
- constructor(min: number, max: number, filePath: string, opts?: PoolOptions<ThreadWorkerWithMessageChannel>);
746
- /** @inheritDoc */
747
- get type(): PoolType;
748
- /** @inheritDoc */
749
- get busy(): boolean;
750
- }
751
- /**
752
- * Base class that implements some shared logic for all poolifier workers.
753
- *
754
- * @template MainWorker Type of main worker.
755
- * @template Data Type of data this worker receives from pool's execution. This can only be serializable data.
756
- * @template Response Type of response the worker sends back to the main worker. This can only be serializable data.
757
- */
758
- declare abstract class AbstractWorker<MainWorker extends Worker | MessagePort, Data = unknown, Response = unknown> extends AsyncResource {
759
- protected mainWorker: MainWorker | undefined | null;
760
- /**
761
- * Timestamp of the last task processed by this worker.
762
- */
763
- protected lastTaskTimestamp: number;
764
- /**
765
- * Handler Id of the `aliveInterval` worker alive check.
766
- */
767
- protected readonly aliveInterval?: NodeJS.Timeout;
768
- /**
769
- * Options for the worker.
770
- */
771
- readonly opts: WorkerOptions;
772
- /**
773
- * Constructs a new poolifier worker.
774
- *
775
- * @param type The type of async event.
776
- * @param isMain Whether this is the main worker or not.
777
- * @param fn Function processed by the worker when the pool's `execution` function is invoked.
778
- * @param mainWorker Reference to main worker.
779
- * @param opts Options for the worker.
780
- */
781
- constructor(type: string, isMain: boolean, fn: (data: Data) => Response, mainWorker: MainWorker | undefined | null, opts?: WorkerOptions);
782
- protected messageListener(value: MessageValue<Data, MainWorker>, fn: (data: Data) => Response): void;
783
- private checkWorkerOptions;
784
- /**
785
- * Checks if the `fn` parameter is passed to the constructor.
786
- *
787
- * @param fn The function that should be defined.
788
- */
789
- private checkFunctionInput;
790
- /**
791
- * Returns the main worker.
792
- *
793
- * @returns Reference to the main worker.
794
- */
795
- protected getMainWorker(): MainWorker;
796
- /**
797
- * Sends a message to the main worker.
798
- *
799
- * @param message The response message.
800
- */
801
- protected abstract sendToMainWorker(message: MessageValue<Response>): void;
802
- /**
803
- * Checks if the worker should be terminated, because its living too long.
804
- */
805
- protected checkAlive(): void;
806
- /**
807
- * Handles an error and convert it to a string so it can be sent back to the main worker.
808
- *
809
- * @param e The error raised by the worker.
810
- * @returns Message of the error.
811
- */
812
- protected handleError(e: Error | string): string;
813
- /**
814
- * Runs the given function synchronously.
815
- *
816
- * @param fn Function that will be executed.
817
- * @param value Input data for the given function.
818
- */
819
- protected run(fn: (data?: Data) => Response, value: MessageValue<Data>): void;
820
- /**
821
- * Runs the given function asynchronously.
822
- *
823
- * @param fn Function that will be executed.
824
- * @param value Input data for the given function.
825
- */
826
- protected runAsync(fn: (data?: Data) => Promise<Response>, value: MessageValue<Data>): void;
827
- }
828
- /**
829
- * A cluster worker used by a poolifier `ClusterPool`.
830
- *
831
- * When this worker is inactive for more than the given `maxInactiveTime`,
832
- * it will send a termination request to its main worker.
833
- *
834
- * If you use a `DynamicClusterPool` the extra workers that were created will be terminated,
835
- * but the minimum number of workers will be guaranteed.
836
- *
837
- * @template Data Type of data this worker receives from pool's execution. This can only be serializable data.
838
- * @template Response Type of response the worker sends back to the main worker. This can only be serializable data.
839
- * @author [Christopher Quadflieg](https://github.com/Shinigami92)
840
- * @since 2.0.0
841
- */
842
- declare class ClusterWorker$0<Data = unknown, Response = unknown> extends AbstractWorker<Worker, Data, Response> {
843
- /**
844
- * Constructs a new poolifier cluster worker.
845
- *
846
- * @param fn Function processed by the worker when the pool's `execution` function is invoked.
847
- * @param opts Options for the worker.
848
- */
849
- constructor(fn: (data: Data) => Response, opts?: WorkerOptions);
850
- /** @inheritDoc */
851
- protected sendToMainWorker(message: MessageValue<Response>): void;
852
- /** @inheritDoc */
853
- protected handleError(e: Error | string): string;
854
- }
855
- /**
856
- * A thread worker used by a poolifier `ThreadPool`.
857
- *
858
- * When this worker is inactive for more than the given `maxInactiveTime`,
859
- * it will send a termination request to its main thread.
860
- *
861
- * If you use a `DynamicThreadPool` the extra workers that were created will be terminated,
862
- * but the minimum number of workers will be guaranteed.
863
- *
864
- * @template Data Type of data this worker receives from pool's execution. This can only be serializable data.
865
- * @template Response Type of response the worker sends back to the main thread. This can only be serializable data.
866
- * @author [Alessandro Pio Ardizio](https://github.com/pioardi)
867
- * @since 0.0.1
868
- */
869
- declare class ThreadWorker<Data = unknown, Response = unknown> extends AbstractWorker<MessagePort, Data, Response> {
870
- /**
871
- * Constructs a new poolifier thread worker.
872
- *
873
- * @param fn Function processed by the worker when the pool's `execution` function is invoked.
874
- * @param opts Options for the worker.
875
- */
876
- constructor(fn: (data: Data) => Response, opts?: WorkerOptions);
877
- /** @inheritDoc */
878
- protected sendToMainWorker(message: MessageValue<Response>): void;
879
- }
880
- export { DynamicClusterPool, FixedClusterPool, WorkerChoiceStrategies, DynamicThreadPool, FixedThreadPool, ClusterWorker$0 as ClusterWorker, ThreadWorker, KillBehaviors };
881
- export type { ClusterPoolOptions, IPool, PoolEmitter, PoolOptions, ErrorHandler, ExitHandler, MessageHandler, OnlineHandler, WorkerChoiceStrategy, ThreadWorkerWithMessageChannel, KillBehavior, WorkerOptions };
1
+ export { DynamicClusterPool } from './pools/cluster/dynamic';
2
+ export { FixedClusterPool } from './pools/cluster/fixed';
3
+ export type { ClusterPoolOptions } from './pools/cluster/fixed';
4
+ export type { IPool, PoolEmitter, PoolOptions } from './pools/pool';
5
+ export type { ErrorHandler, ExitHandler, MessageHandler, OnlineHandler } from './pools/pool-worker';
6
+ export { WorkerChoiceStrategies } from './pools/selection-strategies/selection-strategies-types';
7
+ export type { WorkerChoiceStrategy } from './pools/selection-strategies/selection-strategies-types';
8
+ export { DynamicThreadPool } from './pools/thread/dynamic';
9
+ export { FixedThreadPool } from './pools/thread/fixed';
10
+ export type { ThreadWorkerWithMessageChannel } from './pools/thread/fixed';
11
+ export { ClusterWorker } from './worker/cluster-worker';
12
+ export { ThreadWorker } from './worker/thread-worker';
13
+ export { KillBehaviors } from './worker/worker-options';
14
+ export type { KillBehavior, WorkerOptions } from './worker/worker-options';