3bb0ac9d66ef550f254b8535d3fd23d4f369a4f6
[poolifier.git] / src / pools / worker.ts
1 import type { CircularArray } from '../circular-array'
2
3 /**
4 * Callback invoked if the worker has received a message.
5 */
6 export type MessageHandler<Worker extends IWorker> = (
7 this: Worker,
8 m: unknown
9 ) => void
10
11 /**
12 * Callback invoked if the worker raised an error.
13 */
14 export type ErrorHandler<Worker extends IWorker> = (
15 this: Worker,
16 e: Error
17 ) => void
18
19 /**
20 * Callback invoked when the worker has started successfully.
21 */
22 export type OnlineHandler<Worker extends IWorker> = (this: Worker) => void
23
24 /**
25 * Callback invoked when the worker exits successfully.
26 */
27 export type ExitHandler<Worker extends IWorker> = (
28 this: Worker,
29 code: number
30 ) => void
31
32 /**
33 * Worker task interface.
34 *
35 * @typeParam Data - Type of data sent to the worker. This can only be serializable data.
36 * @internal
37 */
38 export interface Task<Data = unknown> {
39 /**
40 * Worker task data.
41 */
42 data: Data
43 /**
44 * Task UUID.
45 */
46 id: string
47 }
48
49 /**
50 * Worker tasks usage statistics.
51 */
52 export interface TasksUsage {
53 run: number
54 running: number
55 runTime: number
56 runTimeHistory: CircularArray<number>
57 avgRunTime: number
58 medRunTime: number
59 error: number
60 }
61
62 /**
63 * Worker interface.
64 */
65 export interface IWorker {
66 /**
67 * Register an event listener.
68 *
69 * @param event - The event.
70 * @param handler - The event listener.
71 */
72 on: ((event: 'message', handler: MessageHandler<this>) => void) &
73 ((event: 'error', handler: ErrorHandler<this>) => void) &
74 ((event: 'online', handler: OnlineHandler<this>) => void) &
75 ((event: 'exit', handler: ExitHandler<this>) => void)
76 /**
77 * Register a listener to the exit event that will only performed once.
78 *
79 * @param event - `'exit'`.
80 * @param handler - The exit handler.
81 */
82 once: (event: 'exit', handler: ExitHandler<this>) => void
83 }
84
85 /**
86 * Worker node interface.
87 *
88 * @typeParam Worker - Type of worker.
89 * @typeParam Data - Type of data sent to the worker. This can only be serializable data.
90 * @internal
91 */
92 export interface WorkerNode<Worker extends IWorker, Data = unknown> {
93 /**
94 * Worker node worker.
95 */
96 worker: Worker
97 /**
98 * Worker node tasks usage statistics.
99 */
100 tasksUsage: TasksUsage
101 /**
102 * Worker node tasks queue.
103 */
104 tasksQueue: Array<Task<Data>>
105 }