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