fix: fix default worker data value
[poolifier.git] / src / pools / pool.ts
1 import EventEmitter from 'events'
2 import type {
3 ErrorHandler,
4 ExitHandler,
5 MessageHandler,
6 OnlineHandler
7 } from './pool-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 * Options for a poolifier pool.
17 */
18 export interface PoolOptions<Worker> {
19 /**
20 * A function that will listen for message event on each worker.
21 */
22 messageHandler?: MessageHandler<Worker>
23 /**
24 * A function that will listen for error event on each worker.
25 */
26 errorHandler?: ErrorHandler<Worker>
27 /**
28 * A function that will listen for online event on each worker.
29 */
30 onlineHandler?: OnlineHandler<Worker>
31 /**
32 * A function that will listen for exit event on each worker.
33 */
34 exitHandler?: ExitHandler<Worker>
35 /**
36 * The worker choice strategy to use in this pool.
37 */
38 workerChoiceStrategy?: WorkerChoiceStrategy
39 /**
40 * Pool events emission.
41 *
42 * @defaultValue true
43 */
44 enableEvents?: boolean
45 }
46
47 /**
48 * Contract definition for a poolifier pool.
49 *
50 * @typeParam Data - Type of data sent to the worker. This can only be serializable data.
51 * @typeParam Response - Type of response of execution. This can only be serializable data.
52 */
53 export interface IPool<Data = unknown, Response = unknown> {
54 /**
55 * Emitter on which events can be listened to.
56 *
57 * Events that can currently be listened to:
58 *
59 * - `'busy'`
60 */
61 readonly emitter?: PoolEmitter
62 /**
63 * Performs the task specified in the constructor with the data parameter.
64 *
65 * @param data - The input for the specified task. This can only be serializable data.
66 * @returns Promise that will be resolved when the task is successfully completed.
67 */
68 execute: (data: Data) => Promise<Response>
69 /**
70 * Shutdowns every current worker in this pool.
71 */
72 destroy: () => Promise<void>
73 /**
74 * Sets the worker choice strategy in this pool.
75 *
76 * @param workerChoiceStrategy - The worker choice strategy.
77 */
78 setWorkerChoiceStrategy: (workerChoiceStrategy: WorkerChoiceStrategy) => void
79 }