60aceb786549ac0daabee8253f6c1fad890918fe
[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
60 /**
61 * Contract definition for a poolifier pool.
62 *
63 * @typeParam Data - Type of data sent to the worker. This can only be serializable data.
64 * @typeParam Response - Type of response of execution. This can only be serializable data.
65 */
66 export interface IPool<Data = unknown, Response = unknown> {
67 /**
68 * Emitter on which events can be listened to.
69 *
70 * Events that can currently be listened to:
71 *
72 * - `'full'`: Emitted when the pool is dynamic and full.
73 * - `'busy'`: Emitted when the pool is busy.
74 */
75 readonly emitter?: PoolEmitter
76 /**
77 * Performs the task specified in the constructor with the data parameter.
78 *
79 * @param data - The input for the specified task. This can only be serializable data.
80 * @returns Promise that will be resolved when the task is successfully completed.
81 */
82 execute: (data: Data) => Promise<Response>
83 /**
84 * Shutdowns every current worker in this pool.
85 */
86 destroy: () => Promise<void>
87 /**
88 * Sets the worker choice strategy in this pool.
89 *
90 * @param workerChoiceStrategy - The worker choice strategy.
91 */
92 setWorkerChoiceStrategy: (workerChoiceStrategy: WorkerChoiceStrategy) => void
93 }