Merge branch 'master' into elu-strategy
[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 /**
15 * Task error.
16 *
17 * @typeParam Data - Type of data sent to the worker. This can only be serializable data.
18 */
19 export interface TaskError<Data = unknown> {
20 /**
21 * Error message.
22 */
23 message: string
24 /**
25 * Data passed to the worker triggering the error.
26 */
27 data?: Data
28 }
29
30 /**
31 * Task performance.
32 */
33 export interface TaskPerformance {
34 /**
35 * Task performance timestamp.
36 */
37 timestamp: number
38 /**
39 * Task runtime.
40 */
41 runTime?: number
42 /**
43 * Task wait time.
44 */
45 waitTime?: number
46 /**
47 * Task event loop utilization.
48 */
49 elu?: EventLoopUtilization
50 }
51
52 /**
53 * Performance statistics computation.
54 */
55 export interface WorkerStatistics {
56 runTime: boolean
57 waitTime: boolean
58 elu: boolean
59 }
60
61 /**
62 * Message object that is passed between main worker and worker.
63 *
64 * @typeParam MessageData - Type of data sent to and/or from the worker. This can only be serializable data.
65 * @typeParam Data - Type of data sent to the worker. This can only be serializable data.
66 * @typeParam MainWorker - Type of main worker.
67 * @internal
68 */
69 export interface MessageValue<
70 MessageData = unknown,
71 Data = unknown,
72 MainWorker extends ClusterWorker | MessagePort = ClusterWorker | MessagePort
73 > extends Task<MessageData> {
74 /**
75 * Kill code.
76 */
77 readonly kill?: KillBehavior | 1
78 /**
79 * Task error.
80 */
81 readonly taskError?: TaskError<Data>
82 /**
83 * Task performance.
84 */
85 readonly taskPerformance?: TaskPerformance
86 /**
87 * Reference to main worker.
88 */
89 readonly parent?: MainWorker
90 /**
91 * Whether to compute the given statistics or not.
92 */
93 readonly statistics?: WorkerStatistics
94 }
95
96 /**
97 * An object holding the execution response promise resolve/reject callbacks.
98 *
99 * @typeParam Worker - Type of worker.
100 * @typeParam Response - Type of execution response. This can only be serializable data.
101 * @internal
102 */
103 export interface PromiseResponseWrapper<
104 Worker extends IWorker,
105 Response = unknown
106 > {
107 /**
108 * Resolve callback to fulfill the promise.
109 */
110 readonly resolve: (value: Response) => void
111 /**
112 * Reject callback to reject the promise.
113 */
114 readonly reject: (reason?: string) => void
115 /**
116 * The worker handling the execution.
117 */
118 readonly worker: Worker
119 }