docs: comment cleanup
[poolifier.git] / src / pools / pool.ts
CommitLineData
fc3e6586 1import EventEmitter from 'node:events'
bdaf31cd
JB
2import type {
3 ErrorHandler,
4 ExitHandler,
5 MessageHandler,
6 OnlineHandler
f06e48d8 7} from './worker'
bdaf31cd
JB
8import type { WorkerChoiceStrategy } from './selection-strategies/selection-strategies-types'
9
b4904890
JB
10/**
11 * Pool events emitter.
12 */
13export class PoolEmitter extends EventEmitter {}
14
aee46736
JB
15/**
16 * Enumeration of pool events.
17 */
18export const PoolEvents = Object.freeze({
19 full: 'full',
20 busy: 'busy'
21} as const)
22
23/**
24 * Pool event.
25 */
26export type PoolEvent = keyof typeof PoolEvents
27
bdaf31cd
JB
28/**
29 * Options for a poolifier pool.
30 */
31export 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 /**
46e857ca 49 * The worker choice strategy to use in this pool.
bdaf31cd
JB
50 */
51 workerChoiceStrategy?: WorkerChoiceStrategy
52 /**
53 * Pool events emission.
54 *
38e795c1 55 * @defaultValue true
bdaf31cd
JB
56 */
57 enableEvents?: boolean
58}
a35560ba 59
729c563d
S
60/**
61 * Contract definition for a poolifier pool.
62 *
38e795c1
JB
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.
729c563d 65 */
d3c8a1a8 66export interface IPool<Data = unknown, Response = unknown> {
b4904890
JB
67 /**
68 * Emitter on which events can be listened to.
69 *
70 * Events that can currently be listened to:
71 *
164d950a
JB
72 * - `'full'`: Emitted when the pool is dynamic and full.
73 * - `'busy'`: Emitted when the pool is busy.
b4904890
JB
74 */
75 readonly emitter?: PoolEmitter
729c563d 76 /**
bdede008 77 * Performs the task specified in the constructor with the data parameter.
729c563d 78 *
38e795c1 79 * @param data - The input for the specified task. This can only be serializable data.
729c563d
S
80 * @returns Promise that will be resolved when the task is successfully completed.
81 */
78cea37e 82 execute: (data: Data) => Promise<Response>
280c2a77 83 /**
675bb809 84 * Shutdowns every current worker in this pool.
280c2a77 85 */
78cea37e 86 destroy: () => Promise<void>
a35560ba 87 /**
bdede008 88 * Sets the worker choice strategy in this pool.
a35560ba 89 *
38e795c1 90 * @param workerChoiceStrategy - The worker choice strategy.
a35560ba 91 */
78cea37e 92 setWorkerChoiceStrategy: (workerChoiceStrategy: WorkerChoiceStrategy) => void
c97c7edb 93}