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