refactor: cleanup message type namespace
[poolifier.git] / src / utility-types.ts
1 import type { Worker as ClusterWorker } from 'node:cluster'
2 import type { MessagePort } from 'node:worker_threads'
3 import type { EventLoopUtilization } from 'node:perf_hooks'
4 import type { KillBehavior } from './worker/worker-options'
5 import type { IWorker, Task } from './pools/worker'
6
7 /**
8 * Make all properties in T non-readonly.
9 *
10 * @typeParam T - Type in which properties will be non-readonly.
11 */
12 export type Draft<T> = { -readonly [P in keyof T]?: T[P] }
13
14 export interface TaskError<Data = unknown> {
15 /**
16 * Error message.
17 */
18 message: string
19 /**
20 * Data passed to the worker triggering the error.
21 */
22 data?: Data
23 }
24
25 /**
26 * Task performance.
27 */
28 export interface TaskPerformance {
29 /**
30 * Task performance timestamp.
31 */
32 timestamp: number
33 /**
34 * Task runtime.
35 */
36 runTime?: number
37 /**
38 * Task wait time.
39 */
40 waitTime?: number
41 /**
42 * Task event loop utilization.
43 */
44 elu?: EventLoopUtilization
45 }
46
47 /**
48 * Performance statistics computation.
49 */
50 export interface WorkerStatistics {
51 runTime: boolean
52 waitTime: boolean
53 elu: boolean
54 }
55
56 /**
57 * Message object that is passed between main worker and worker.
58 *
59 * @typeParam MessageData - Type of data sent to and/or from the worker. This can only be serializable data.
60 * @typeParam Data - Type of data sent to the worker. This can only be serializable data.
61 * @typeParam MainWorker - Type of main worker.
62 * @internal
63 */
64 export interface MessageValue<
65 MessageData = unknown,
66 Data = unknown,
67 MainWorker extends ClusterWorker | MessagePort = ClusterWorker | MessagePort
68 > extends Task<MessageData> {
69 /**
70 * Kill code.
71 */
72 readonly kill?: KillBehavior | 1
73 /**
74 * Task error.
75 */
76 readonly taskError?: TaskError<Data>
77 /**
78 * Task performance.
79 */
80 readonly taskPerformance?: TaskPerformance
81 /**
82 * Reference to main worker.
83 */
84 readonly parent?: MainWorker
85 /**
86 * Whether to compute the given statistics or not.
87 */
88 readonly statistics?: WorkerStatistics
89 }
90
91 /**
92 * An object holding the execution response promise resolve/reject callbacks.
93 *
94 * @typeParam Worker - Type of worker.
95 * @typeParam Response - Type of execution response. This can only be serializable data.
96 * @internal
97 */
98 export interface PromiseResponseWrapper<
99 Worker extends IWorker,
100 Response = unknown
101 > {
102 /**
103 * Resolve callback to fulfill the promise.
104 */
105 readonly resolve: (value: Response) => void
106 /**
107 * Reject callback to reject the promise.
108 */
109 readonly reject: (reason?: string) => void
110 /**
111 * The worker handling the execution.
112 */
113 readonly worker: Worker
114 }