docs: update changelog entries
[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> = (this: Worker, m: unknown) => void
7
8 /**
9 * Callback invoked if the worker raised an error.
10 */
11 export type ErrorHandler<Worker> = (this: Worker, e: Error) => void
12
13 /**
14 * Callback invoked when the worker has started successfully.
15 */
16 export type OnlineHandler<Worker> = (this: Worker) => void
17
18 /**
19 * Callback invoked when the worker exits successfully.
20 */
21 export type ExitHandler<Worker> = (this: Worker, code: number) => void
22
23 /**
24 * Worker task interface.
25 */
26 export interface Task<Data = unknown> {
27 data: Data
28 id: string
29 }
30
31 /**
32 * Worker tasks usage statistics.
33 */
34 export interface TasksUsage {
35 run: number
36 running: number
37 runTime: number
38 runTimeHistory: CircularArray<number>
39 avgRunTime: number
40 medRunTime: number
41 error: number
42 }
43
44 /**
45 * Worker interface.
46 */
47 export interface IWorker {
48 /**
49 * Register an event listener.
50 *
51 * @param event - The event.
52 * @param handler - The event listener.
53 */
54 on: ((event: 'message', handler: MessageHandler<this>) => void) &
55 ((event: 'error', handler: ErrorHandler<this>) => void) &
56 ((event: 'online', handler: OnlineHandler<this>) => void) &
57 ((event: 'exit', handler: ExitHandler<this>) => void)
58 /**
59 * Register a listener to the exit event that will only performed once.
60 *
61 * @param event - `'exit'`.
62 * @param handler - The exit handler.
63 */
64 once: (event: 'exit', handler: ExitHandler<this>) => void
65 }
66
67 /**
68 * Worker node interface.
69 */
70 export interface WorkerNode<Worker extends IWorker, Data = unknown> {
71 worker: Worker
72 tasksUsage: TasksUsage
73 tasksQueue: Array<Task<Data>>
74 }