feat: add option to enable worker tasks queue
[poolifier.git] / src / pools / pool.ts
1 import EventEmitter from 'node:events'
2 import type {
3 ErrorHandler,
4 ExitHandler,
5 MessageHandler,
6 OnlineHandler
7 } from './worker'
8 import type { WorkerChoiceStrategy } from './selection-strategies/selection-strategies-types'
9
10 /**
11 * Pool events emitter.
12 */
13 export class PoolEmitter extends EventEmitter {}
14
15 /**
16 * Enumeration of pool events.
17 */
18 export const PoolEvents = Object.freeze({
19 full: 'full',
20 busy: 'busy'
21 } as const)
22
23 /**
24 * Pool event.
25 */
26 export type PoolEvent = keyof typeof PoolEvents
27
28 /**
29 * Options for a poolifier pool.
30 */
31 export interface PoolOptions<Worker> {
32 /**
33 * A function that will listen for message event on each worker.
34 */
35 messageHandler?: MessageHandler<Worker>
36 /**
37 * A function that will listen for error event on each worker.
38 */
39 errorHandler?: ErrorHandler<Worker>
40 /**
41 * A function that will listen for online event on each worker.
42 */
43 onlineHandler?: OnlineHandler<Worker>
44 /**
45 * A function that will listen for exit event on each worker.
46 */
47 exitHandler?: ExitHandler<Worker>
48 /**
49 * The worker choice strategy to use in this pool.
50 */
51 workerChoiceStrategy?: WorkerChoiceStrategy
52 /**
53 * Pool events emission.
54 *
55 * @defaultValue true
56 */
57 enableEvents?: boolean
58 /**
59 * Pool worker tasks queue.
60 *
61 * @experimental
62 * @defaultValue false
63 */
64 enableTasksQueue?: boolean
65 }
66
67 /**
68 * Contract definition for a poolifier pool.
69 *
70 * @typeParam Data - Type of data sent to the worker. This can only be serializable data.
71 * @typeParam Response - Type of response of execution. This can only be serializable data.
72 */
73 export interface IPool<Data = unknown, Response = unknown> {
74 /**
75 * Emitter on which events can be listened to.
76 *
77 * Events that can currently be listened to:
78 *
79 * - `'full'`: Emitted when the pool is dynamic and full.
80 * - `'busy'`: Emitted when the pool is busy.
81 */
82 readonly emitter?: PoolEmitter
83 /**
84 * Performs the task specified in the constructor with the data parameter.
85 *
86 * @param data - The input for the specified task. This can only be serializable data.
87 * @returns Promise that will be resolved when the task is successfully completed.
88 */
89 execute: (data: Data) => Promise<Response>
90 /**
91 * Shutdowns every current worker in this pool.
92 */
93 destroy: () => Promise<void>
94 /**
95 * Sets the worker choice strategy in this pool.
96 *
97 * @param workerChoiceStrategy - The worker choice strategy.
98 */
99 setWorkerChoiceStrategy: (workerChoiceStrategy: WorkerChoiceStrategy) => void
100 }