refactor: improve error messages
[poolifier.git] / src / utility-types.ts
1 import type { EventLoopUtilization } from 'node:perf_hooks'
2 import type { KillBehavior } from './worker/worker-options'
3 import type { IWorker, Task } from './pools/worker'
4
5 /**
6 * Task error.
7 *
8 * @typeParam Data - Type of data sent to the worker triggering an error. This can only be structured-cloneable data.
9 */
10 export interface TaskError<Data = unknown> {
11 /**
12 * Worker id.
13 */
14 workerId: number
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 event loop utilization.
39 */
40 elu?: EventLoopUtilization
41 }
42
43 /**
44 * Performance statistics computation.
45 */
46 export interface WorkerStatistics {
47 runTime: boolean
48 elu: boolean
49 }
50
51 /**
52 * Message object that is passed between main worker and worker.
53 *
54 * @typeParam Data - Type of data sent to the worker or execution response. This can only be structured-cloneable data.
55 * @typeParam ErrorData - Type of data sent to the worker triggering an error. This can only be structured-cloneable data.
56 * @internal
57 */
58 export interface MessageValue<Data = unknown, ErrorData = unknown>
59 extends Task<Data> {
60 /**
61 * Worker id.
62 */
63 readonly workerId?: number
64 /**
65 * Kill code.
66 */
67 readonly kill?: KillBehavior | 1
68 /**
69 * Task error.
70 */
71 readonly taskError?: TaskError<ErrorData>
72 /**
73 * Task performance.
74 */
75 readonly taskPerformance?: TaskPerformance
76 /**
77 * Whether the worker computes the given statistics or not.
78 */
79 readonly statistics?: WorkerStatistics
80 /**
81 * Whether the worker has started or not.
82 */
83 readonly started?: boolean
84 }
85
86 /**
87 * An object holding the execution response promise resolve/reject callbacks.
88 *
89 * @typeParam Worker - Type of worker.
90 * @typeParam Response - Type of execution response. This can only be structured-cloneable data.
91 * @internal
92 */
93 export interface PromiseResponseWrapper<
94 Worker extends IWorker,
95 Response = unknown
96 > {
97 /**
98 * Resolve callback to fulfill the promise.
99 */
100 readonly resolve: (value: Response) => void
101 /**
102 * Reject callback to reject the promise.
103 */
104 readonly reject: (reason?: string) => void
105 /**
106 * The worker handling the execution.
107 */
108 readonly worker: Worker
109 }