refactor: factor out fixed queue common code in an abstract class
[poolifier.git] / src / utility-types.ts
1 import type { AsyncResource } from 'node:async_hooks'
2 import type { EventLoopUtilization } from 'node:perf_hooks'
3 import type { MessagePort, TransferListItem } from 'node:worker_threads'
4
5 import type { WorkerChoiceStrategy } from './pools/selection-strategies/selection-strategies-types.js'
6 import type { KillBehavior } from './worker/worker-options.js'
7
8 /**
9 * Worker error.
10 * @typeParam Data - Type of data sent to the worker triggering an error. This can only be structured-cloneable data.
11 */
12 export interface WorkerError<Data = unknown> {
13 /**
14 * Task function name triggering the error.
15 */
16 readonly name: string
17 /**
18 * Error message.
19 */
20 readonly message: string
21 /**
22 * Data triggering the error.
23 */
24 readonly data?: Data
25 }
26
27 /**
28 * Task performance.
29 * @internal
30 */
31 export interface TaskPerformance {
32 /**
33 * Task name.
34 */
35 readonly name: string
36 /**
37 * Task performance timestamp.
38 */
39 readonly timestamp: number
40 /**
41 * Task runtime.
42 */
43 readonly runTime?: number
44 /**
45 * Task event loop utilization.
46 */
47 readonly elu?: EventLoopUtilization
48 }
49
50 /**
51 * Worker task performance statistics computation settings.
52 * @internal
53 */
54 export interface WorkerStatistics {
55 /**
56 * Whether the worker computes the task runtime or not.
57 */
58 readonly runTime: boolean
59 /**
60 * Whether the worker computes the task event loop utilization (ELU) or not.
61 */
62 readonly elu: boolean
63 }
64
65 /**
66 * Task function properties.
67 */
68 export interface TaskFunctionProperties {
69 /**
70 * Task function name.
71 */
72 readonly name: string
73 /**
74 * Task function priority. Lower values have higher priority.
75 */
76 readonly priority?: number
77 /**
78 * Task function worker choice strategy.
79 */
80 readonly strategy?: WorkerChoiceStrategy
81 }
82
83 /**
84 * Message object that is passed as a task between main worker and worker.
85 * @typeParam Data - Type of data sent to the worker. This can only be structured-cloneable data.
86 * @internal
87 */
88 export interface Task<Data = unknown> {
89 /**
90 * Task name.
91 */
92 readonly name?: string
93 /**
94 * Task input data that will be passed to the worker.
95 */
96 readonly data?: Data
97 /**
98 * Task priority. Lower values have higher priority.
99 * @defaultValue 0
100 */
101 readonly priority?: number
102 /**
103 * Task worker choice strategy.
104 */
105 readonly strategy?: WorkerChoiceStrategy
106 /**
107 * Array of transferable objects.
108 */
109 readonly transferList?: readonly TransferListItem[]
110 /**
111 * Timestamp.
112 */
113 readonly timestamp?: number
114 /**
115 * Task UUID.
116 */
117 readonly taskId?: `${string}-${string}-${string}-${string}-${string}`
118 }
119
120 /**
121 * Message object that is passed between main worker and worker.
122 * @typeParam Data - Type of data sent to the worker or execution response. This can only be structured-cloneable data.
123 * @typeParam ErrorData - Type of data sent to the worker triggering an error. This can only be structured-cloneable data.
124 * @internal
125 */
126 export interface MessageValue<Data = unknown, ErrorData = unknown>
127 extends Task<Data> {
128 /**
129 * Worker id.
130 */
131 readonly workerId?: number
132 /**
133 * Kill code.
134 */
135 readonly kill?: KillBehavior | true | 'success' | 'failure'
136 /**
137 * Worker error.
138 */
139 readonly workerError?: WorkerError<ErrorData>
140 /**
141 * Task performance.
142 */
143 readonly taskPerformance?: TaskPerformance
144 /**
145 * Task function operation:
146 * - `'add'` - Add a task function.
147 * - `'remove'` - Remove a task function.
148 * - `'default'` - Set a task function as default.
149 */
150 readonly taskFunctionOperation?: 'add' | 'remove' | 'default'
151 /**
152 * Whether the task function operation is successful or not.
153 */
154 readonly taskFunctionOperationStatus?: boolean
155 /**
156 * Task function properties.
157 */
158 readonly taskFunctionProperties?: TaskFunctionProperties
159 /**
160 * Task function serialized to string.
161 */
162 readonly taskFunction?: string
163 /**
164 * Task functions properties.
165 */
166 readonly taskFunctionsProperties?: TaskFunctionProperties[]
167 /**
168 * Whether the worker computes the given statistics or not.
169 */
170 readonly statistics?: WorkerStatistics
171 /**
172 * Whether the worker is ready or not.
173 */
174 readonly ready?: boolean
175 /**
176 * Whether the worker starts or stops its activity check.
177 */
178 readonly checkActive?: boolean
179 /**
180 * Message port.
181 */
182 readonly port?: MessagePort
183 }
184
185 /**
186 * An object holding the task execution response promise resolve/reject callbacks.
187 * @typeParam Response - Type of execution response. This can only be structured-cloneable data.
188 * @internal
189 */
190 export interface PromiseResponseWrapper<Response = unknown> {
191 /**
192 * Resolve callback to fulfill the promise.
193 */
194 readonly resolve: (value: Response | PromiseLike<Response>) => void
195 /**
196 * Reject callback to reject the promise.
197 */
198 readonly reject: (reason?: unknown) => void
199 /**
200 * The worker node key executing the task.
201 */
202 readonly workerNodeKey: number
203 /**
204 * The asynchronous resource used to track the task execution.
205 */
206 readonly asyncResource?: AsyncResource
207 }
208
209 /**
210 * Remove readonly modifier from all properties of T.
211 * @typeParam T - Type to remove readonly modifier.
212 * @internal
213 */
214 export type Writable<T> = { -readonly [P in keyof T]: T[P] }
215
216 /**
217 * Default queue size.
218 * @internal
219 */
220 export const defaultQueueSize = 2048
221
222 /**
223 * Fixed queue node.
224 * @typeParam T - Type of fixed queue node data.
225 * @internal
226 */
227 export interface FixedQueueNode<T> {
228 data: T
229 priority: number
230 }
231
232 /**
233 * Fixed queue.
234 * @typeParam T - Type of fixed queue data.
235 * @internal
236 */
237 export interface IFixedQueue<T> {
238 /** The fixed queue capacity. */
239 readonly capacity: number
240 /** The fixed queue size. */
241 readonly size: number
242 /** The fixed queue node array. */
243 nodeArray: FixedQueueNode<T>[]
244 /**
245 * Checks if the fixed queue is empty.
246 * @returns `true` if the fixed queue is empty, `false` otherwise.
247 */
248 empty: () => boolean
249 /**
250 * Checks if the fixed queue is full.
251 * @returns `true` if the fixed queue is full, `false` otherwise.
252 */
253 full: () => boolean
254 /**
255 * Enqueue data into the fixed queue.
256 * @param data - Data to enqueue.
257 * @param priority - Priority of the data. Lower values have higher priority.
258 * @returns The new size of the fixed queue.
259 * @throws If the fixed queue is full.
260 */
261 enqueue: (data: T, priority?: number) => number
262 /**
263 * Gets data from the fixed queue.
264 * @param index - The index of the data to get.
265 * @returns The data at the index or `undefined` if the fixed queue is empty or the index is out of bounds.
266 */
267 get: (index: number) => T | undefined
268 /**
269 * Dequeue data from the fixed queue.
270 * @returns The dequeued data or `undefined` if the fixed queue is empty.
271 */
272 dequeue: () => T | undefined
273 /**
274 * Clears the fixed queue.
275 */
276 clear: () => void
277 /**
278 * Returns an iterator for the fixed queue.
279 * @returns An iterator for the fixed queue.
280 * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols
281 */
282 [Symbol.iterator]: () => Iterator<T>
283 }
284
285 /**
286 * Default bucket size.
287 * @internal
288 */
289 export const defaultBucketSize = 2048
290
291 /**
292 * Priority queue node.
293 * @typeParam T - Type of priority queue node data.
294 * @internal
295 */
296 export interface PriorityQueueNode<T> extends IFixedQueue<T> {
297 next?: IFixedQueue<T>
298 }