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