Commit | Line | Data |
---|---|---|
6677a3d3 | 1 | import type { Worker } from 'node:cluster' |
d715b7bc | 2 | import { performance } from 'node:perf_hooks' |
ded253e2 JB |
3 | import type { MessagePort } from 'node:worker_threads' |
4 | ||
d715b7bc JB |
5 | import type { |
6 | MessageValue, | |
5c4d16da | 7 | Task, |
31847469 | 8 | TaskFunctionProperties, |
d715b7bc JB |
9 | TaskPerformance, |
10 | WorkerStatistics | |
d35e5717 | 11 | } from '../utility-types.js' |
ff128cc9 | 12 | import { |
31847469 | 13 | buildTaskFunctionProperties, |
ff128cc9 JB |
14 | DEFAULT_TASK_NAME, |
15 | EMPTY_FUNCTION, | |
16 | isAsyncFunction, | |
17 | isPlainObject | |
d35e5717 | 18 | } from '../utils.js' |
b6b32453 | 19 | import type { |
82ea6492 JB |
20 | TaskAsyncFunction, |
21 | TaskFunction, | |
31847469 | 22 | TaskFunctionObject, |
4e38fd21 | 23 | TaskFunctionOperationResult, |
b6b32453 | 24 | TaskFunctions, |
82ea6492 | 25 | TaskSyncFunction |
d35e5717 | 26 | } from './task-functions.js' |
9a38f99e JB |
27 | import { |
28 | checkTaskFunctionName, | |
bcfb06ce | 29 | checkValidTaskFunctionObjectEntry, |
9a38f99e | 30 | checkValidWorkerOptions |
d35e5717 | 31 | } from './utils.js' |
ded253e2 | 32 | import { KillBehaviors, type WorkerOptions } from './worker-options.js' |
4c35177b | 33 | |
978aad6f | 34 | const DEFAULT_MAX_INACTIVE_TIME = 60000 |
d38d0e30 JB |
35 | const DEFAULT_WORKER_OPTIONS: WorkerOptions = { |
36 | /** | |
37 | * The kill behavior option on this worker or its default value. | |
38 | */ | |
39 | killBehavior: KillBehaviors.SOFT, | |
40 | /** | |
41 | * The maximum time to keep this worker active while idle. | |
42 | * The pool automatically checks and terminates this worker when the time expires. | |
43 | */ | |
44 | maxInactiveTime: DEFAULT_MAX_INACTIVE_TIME, | |
45 | /** | |
46 | * The function to call when the worker is killed. | |
47 | */ | |
48 | killHandler: EMPTY_FUNCTION | |
49 | } | |
c97c7edb | 50 | |
729c563d | 51 | /** |
ea7a90d3 | 52 | * Base class that implements some shared logic for all poolifier workers. |
729c563d | 53 | * |
38e795c1 | 54 | * @typeParam MainWorker - Type of main worker. |
e102732c JB |
55 | * @typeParam Data - Type of data this worker receives from pool's execution. This can only be structured-cloneable data. |
56 | * @typeParam Response - Type of response the worker sends back to the main worker. This can only be structured-cloneable data. | |
729c563d | 57 | */ |
c97c7edb | 58 | export abstract class AbstractWorker< |
6677a3d3 | 59 | MainWorker extends Worker | MessagePort, |
d3c8a1a8 S |
60 | Data = unknown, |
61 | Response = unknown | |
69b70a7e | 62 | > { |
f59e1027 | 63 | /** |
83fa0a36 | 64 | * Worker id. |
f59e1027 JB |
65 | */ |
66 | protected abstract id: number | |
a86b6df1 | 67 | /** |
31847469 | 68 | * Task function object(s) processed by the worker when the pool's `execution` function is invoked. |
a86b6df1 | 69 | */ |
31847469 | 70 | protected taskFunctions!: Map<string, TaskFunctionObject<Data, Response>> |
729c563d S |
71 | /** |
72 | * Timestamp of the last task processed by this worker. | |
73 | */ | |
a9d9ea34 | 74 | protected lastTaskTimestamp!: number |
b6b32453 | 75 | /** |
8a970421 | 76 | * Performance statistics computation requirements. |
b6b32453 | 77 | */ |
c63a35a0 | 78 | protected statistics?: WorkerStatistics |
729c563d | 79 | /** |
b0a4db63 | 80 | * Handler id of the `activeInterval` worker activity check. |
729c563d | 81 | */ |
b0a4db63 | 82 | protected activeInterval?: NodeJS.Timeout |
49890030 | 83 | |
c97c7edb | 84 | /** |
729c563d | 85 | * Constructs a new poolifier worker. |
c97c7edb | 86 | * |
38e795c1 | 87 | * @param isMain - Whether this is the main worker or not. |
38e795c1 | 88 | * @param mainWorker - Reference to main worker. |
85aeb3f3 | 89 | * @param taskFunctions - Task function(s) processed by the worker when the pool's `execution` function is invoked. The first function is the default function. |
38e795c1 | 90 | * @param opts - Options for the worker. |
c97c7edb S |
91 | */ |
92 | public constructor ( | |
c63a35a0 JB |
93 | protected readonly isMain: boolean | undefined, |
94 | private readonly mainWorker: MainWorker | undefined | null, | |
82ea6492 | 95 | taskFunctions: TaskFunction<Data, Response> | TaskFunctions<Data, Response>, |
d38d0e30 | 96 | protected opts: WorkerOptions = DEFAULT_WORKER_OPTIONS |
c97c7edb | 97 | ) { |
9d2d0da1 JB |
98 | if (this.isMain == null) { |
99 | throw new Error('isMain parameter is mandatory') | |
100 | } | |
a86b6df1 | 101 | this.checkTaskFunctions(taskFunctions) |
9d2d0da1 | 102 | this.checkWorkerOptions(this.opts) |
1f68cede | 103 | if (!this.isMain) { |
0cb6edc2 | 104 | // Should be once() but Node.js on windows has a bug that prevents it from working |
e2898b4f | 105 | this.getMainWorker().on('message', this.handleReadyMessage.bind(this)) |
c97c7edb S |
106 | } |
107 | } | |
108 | ||
41aa7dcd | 109 | private checkWorkerOptions (opts: WorkerOptions): void { |
9a38f99e | 110 | checkValidWorkerOptions(opts) |
d38d0e30 | 111 | this.opts = { ...DEFAULT_WORKER_OPTIONS, ...opts } |
41aa7dcd JB |
112 | } |
113 | ||
114 | /** | |
c20084b6 | 115 | * Checks if the `taskFunctions` parameter is passed to the constructor and valid. |
41aa7dcd | 116 | * |
82888165 | 117 | * @param taskFunctions - The task function(s) parameter that should be checked. |
41aa7dcd | 118 | */ |
a86b6df1 | 119 | private checkTaskFunctions ( |
c63a35a0 JB |
120 | taskFunctions: |
121 | | TaskFunction<Data, Response> | |
122 | | TaskFunctions<Data, Response> | |
123 | | undefined | |
a86b6df1 | 124 | ): void { |
ec8fd331 JB |
125 | if (taskFunctions == null) { |
126 | throw new Error('taskFunctions parameter is mandatory') | |
127 | } | |
31847469 | 128 | this.taskFunctions = new Map<string, TaskFunctionObject<Data, Response>>() |
0d80593b | 129 | if (typeof taskFunctions === 'function') { |
31847469 JB |
130 | const fnObj = { taskFunction: taskFunctions.bind(this) } |
131 | this.taskFunctions.set(DEFAULT_TASK_NAME, fnObj) | |
2a69b8c5 JB |
132 | this.taskFunctions.set( |
133 | typeof taskFunctions.name === 'string' && | |
efebef40 | 134 | taskFunctions.name.trim().length > 0 |
2a69b8c5 JB |
135 | ? taskFunctions.name |
136 | : 'fn1', | |
31847469 | 137 | fnObj |
2a69b8c5 | 138 | ) |
0d80593b | 139 | } else if (isPlainObject(taskFunctions)) { |
82888165 | 140 | let firstEntry = true |
31847469 JB |
141 | for (let [name, fnObj] of Object.entries(taskFunctions)) { |
142 | if (typeof fnObj === 'function') { | |
143 | fnObj = { taskFunction: fnObj } satisfies TaskFunctionObject< | |
144 | Data, | |
145 | Response | |
146 | > | |
147 | } | |
bcfb06ce | 148 | checkValidTaskFunctionObjectEntry<Data, Response>(name, fnObj) |
31847469 | 149 | fnObj.taskFunction = fnObj.taskFunction.bind(this) |
82888165 | 150 | if (firstEntry) { |
31847469 | 151 | this.taskFunctions.set(DEFAULT_TASK_NAME, fnObj) |
82888165 JB |
152 | firstEntry = false |
153 | } | |
31847469 | 154 | this.taskFunctions.set(name, fnObj) |
a86b6df1 | 155 | } |
630f0acf JB |
156 | if (firstEntry) { |
157 | throw new Error('taskFunctions parameter object is empty') | |
158 | } | |
a86b6df1 | 159 | } else { |
f34fdabe JB |
160 | throw new TypeError( |
161 | 'taskFunctions parameter is not a function or a plain object' | |
162 | ) | |
41aa7dcd JB |
163 | } |
164 | } | |
165 | ||
968a2e8c JB |
166 | /** |
167 | * Checks if the worker has a task function with the given name. | |
168 | * | |
169 | * @param name - The name of the task function to check. | |
170 | * @returns Whether the worker has a task function with the given name or not. | |
968a2e8c | 171 | */ |
4e38fd21 | 172 | public hasTaskFunction (name: string): TaskFunctionOperationResult { |
6703b9f4 | 173 | try { |
9a38f99e | 174 | checkTaskFunctionName(name) |
6703b9f4 JB |
175 | } catch (error) { |
176 | return { status: false, error: error as Error } | |
177 | } | |
178 | return { status: this.taskFunctions.has(name) } | |
968a2e8c JB |
179 | } |
180 | ||
181 | /** | |
182 | * Adds a task function to the worker. | |
183 | * If a task function with the same name already exists, it is replaced. | |
184 | * | |
185 | * @param name - The name of the task function to add. | |
186 | * @param fn - The task function to add. | |
187 | * @returns Whether the task function was added or not. | |
968a2e8c JB |
188 | */ |
189 | public addTaskFunction ( | |
190 | name: string, | |
31847469 | 191 | fn: TaskFunction<Data, Response> | TaskFunctionObject<Data, Response> |
4e38fd21 | 192 | ): TaskFunctionOperationResult { |
968a2e8c | 193 | try { |
9a38f99e | 194 | checkTaskFunctionName(name) |
6703b9f4 JB |
195 | if (name === DEFAULT_TASK_NAME) { |
196 | throw new Error( | |
197 | 'Cannot add a task function with the default reserved name' | |
198 | ) | |
199 | } | |
31847469 JB |
200 | if (typeof fn === 'function') { |
201 | fn = { taskFunction: fn } satisfies TaskFunctionObject<Data, Response> | |
6703b9f4 | 202 | } |
bcfb06ce | 203 | checkValidTaskFunctionObjectEntry<Data, Response>(name, fn) |
31847469 | 204 | fn.taskFunction = fn.taskFunction.bind(this) |
968a2e8c JB |
205 | if ( |
206 | this.taskFunctions.get(name) === | |
207 | this.taskFunctions.get(DEFAULT_TASK_NAME) | |
208 | ) { | |
31847469 | 209 | this.taskFunctions.set(DEFAULT_TASK_NAME, fn) |
968a2e8c | 210 | } |
31847469 JB |
211 | this.taskFunctions.set(name, fn) |
212 | this.sendTaskFunctionsPropertiesToMainWorker() | |
6703b9f4 JB |
213 | return { status: true } |
214 | } catch (error) { | |
215 | return { status: false, error: error as Error } | |
968a2e8c JB |
216 | } |
217 | } | |
218 | ||
219 | /** | |
220 | * Removes a task function from the worker. | |
221 | * | |
222 | * @param name - The name of the task function to remove. | |
223 | * @returns Whether the task function existed and was removed or not. | |
968a2e8c | 224 | */ |
4e38fd21 | 225 | public removeTaskFunction (name: string): TaskFunctionOperationResult { |
6703b9f4 | 226 | try { |
9a38f99e | 227 | checkTaskFunctionName(name) |
6703b9f4 JB |
228 | if (name === DEFAULT_TASK_NAME) { |
229 | throw new Error( | |
230 | 'Cannot remove the task function with the default reserved name' | |
231 | ) | |
232 | } | |
233 | if ( | |
234 | this.taskFunctions.get(name) === | |
235 | this.taskFunctions.get(DEFAULT_TASK_NAME) | |
236 | ) { | |
237 | throw new Error( | |
238 | 'Cannot remove the task function used as the default task function' | |
239 | ) | |
240 | } | |
241 | const deleteStatus = this.taskFunctions.delete(name) | |
31847469 | 242 | this.sendTaskFunctionsPropertiesToMainWorker() |
6703b9f4 JB |
243 | return { status: deleteStatus } |
244 | } catch (error) { | |
245 | return { status: false, error: error as Error } | |
968a2e8c | 246 | } |
968a2e8c JB |
247 | } |
248 | ||
249 | /** | |
31847469 | 250 | * Lists the properties of the worker's task functions. |
c50b93fb | 251 | * |
31847469 | 252 | * @returns The properties of the worker's task functions. |
c50b93fb | 253 | */ |
31847469 | 254 | public listTaskFunctionsProperties (): TaskFunctionProperties[] { |
d8a4de75 | 255 | let defaultTaskFunctionName = DEFAULT_TASK_NAME |
31847469 | 256 | for (const [name, fnObj] of this.taskFunctions) { |
b558f6b5 JB |
257 | if ( |
258 | name !== DEFAULT_TASK_NAME && | |
31847469 | 259 | fnObj === this.taskFunctions.get(DEFAULT_TASK_NAME) |
b558f6b5 JB |
260 | ) { |
261 | defaultTaskFunctionName = name | |
262 | break | |
263 | } | |
264 | } | |
31847469 JB |
265 | const taskFunctionsProperties: TaskFunctionProperties[] = [] |
266 | for (const [name, fnObj] of this.taskFunctions) { | |
267 | if (name === DEFAULT_TASK_NAME || name === defaultTaskFunctionName) { | |
268 | continue | |
269 | } | |
270 | taskFunctionsProperties.push(buildTaskFunctionProperties(name, fnObj)) | |
271 | } | |
b558f6b5 | 272 | return [ |
31847469 JB |
273 | buildTaskFunctionProperties( |
274 | DEFAULT_TASK_NAME, | |
275 | this.taskFunctions.get(DEFAULT_TASK_NAME) | |
276 | ), | |
277 | buildTaskFunctionProperties( | |
278 | defaultTaskFunctionName, | |
279 | this.taskFunctions.get(defaultTaskFunctionName) | |
280 | ), | |
281 | ...taskFunctionsProperties | |
b558f6b5 | 282 | ] |
c50b93fb JB |
283 | } |
284 | ||
285 | /** | |
286 | * Sets the default task function to use in the worker. | |
968a2e8c JB |
287 | * |
288 | * @param name - The name of the task function to use as default task function. | |
289 | * @returns Whether the default task function was set or not. | |
968a2e8c | 290 | */ |
4e38fd21 | 291 | public setDefaultTaskFunction (name: string): TaskFunctionOperationResult { |
968a2e8c | 292 | try { |
9a38f99e | 293 | checkTaskFunctionName(name) |
6703b9f4 JB |
294 | if (name === DEFAULT_TASK_NAME) { |
295 | throw new Error( | |
296 | 'Cannot set the default task function reserved name as the default task function' | |
297 | ) | |
298 | } | |
299 | if (!this.taskFunctions.has(name)) { | |
300 | throw new Error( | |
301 | 'Cannot set the default task function to a non-existing task function' | |
302 | ) | |
303 | } | |
67f3f2d6 JB |
304 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion |
305 | this.taskFunctions.set(DEFAULT_TASK_NAME, this.taskFunctions.get(name)!) | |
31847469 | 306 | this.sendTaskFunctionsPropertiesToMainWorker() |
6703b9f4 JB |
307 | return { status: true } |
308 | } catch (error) { | |
309 | return { status: false, error: error as Error } | |
968a2e8c JB |
310 | } |
311 | } | |
312 | ||
a038b517 JB |
313 | /** |
314 | * Handles the ready message sent by the main worker. | |
315 | * | |
316 | * @param message - The ready message. | |
317 | */ | |
318 | protected abstract handleReadyMessage (message: MessageValue<Data>): void | |
319 | ||
aee46736 JB |
320 | /** |
321 | * Worker message listener. | |
322 | * | |
6b813701 | 323 | * @param message - The received message. |
aee46736 | 324 | */ |
85aeb3f3 | 325 | protected messageListener (message: MessageValue<Data>): void { |
9e746eec | 326 | this.checkMessageWorkerId(message) |
310de0aa JB |
327 | if (message.statistics != null) { |
328 | // Statistics message received | |
329 | this.statistics = message.statistics | |
330 | } else if (message.checkActive != null) { | |
331 | // Check active message received | |
332 | message.checkActive ? this.startCheckActive() : this.stopCheckActive() | |
6703b9f4 JB |
333 | } else if (message.taskFunctionOperation != null) { |
334 | // Task function operation message received | |
335 | this.handleTaskFunctionOperationMessage(message) | |
310de0aa JB |
336 | } else if (message.taskId != null && message.data != null) { |
337 | // Task message received | |
338 | this.run(message) | |
339 | } else if (message.kill === true) { | |
340 | // Kill message received | |
341 | this.handleKillMessage(message) | |
cf597bc5 JB |
342 | } |
343 | } | |
344 | ||
6703b9f4 JB |
345 | protected handleTaskFunctionOperationMessage ( |
346 | message: MessageValue<Data> | |
347 | ): void { | |
31847469 JB |
348 | const { taskFunctionOperation, taskFunctionProperties, taskFunction } = |
349 | message | |
350 | if (taskFunctionProperties == null) { | |
7f0e1334 | 351 | throw new Error( |
31847469 | 352 | 'Cannot handle task function operation message without task function properties' |
7f0e1334 JB |
353 | ) |
354 | } | |
355 | let response: TaskFunctionOperationResult | |
d2dd5ef5 JB |
356 | switch (taskFunctionOperation) { |
357 | case 'add': | |
31847469 | 358 | response = this.addTaskFunction(taskFunctionProperties.name, { |
7f0e1334 | 359 | // eslint-disable-next-line @typescript-eslint/no-implied-eval, no-new-func |
31847469 JB |
360 | taskFunction: new Function( |
361 | `return ${taskFunction}` | |
362 | )() as TaskFunction<Data, Response>, | |
363 | ...(taskFunctionProperties.priority != null && { | |
364 | priority: taskFunctionProperties.priority | |
365 | }), | |
366 | ...(taskFunctionProperties.strategy != null && { | |
367 | strategy: taskFunctionProperties.strategy | |
368 | }) | |
369 | }) | |
d2dd5ef5 JB |
370 | break |
371 | case 'remove': | |
31847469 | 372 | response = this.removeTaskFunction(taskFunctionProperties.name) |
d2dd5ef5 JB |
373 | break |
374 | case 'default': | |
31847469 | 375 | response = this.setDefaultTaskFunction(taskFunctionProperties.name) |
d2dd5ef5 JB |
376 | break |
377 | default: | |
378 | response = { status: false, error: new Error('Unknown task operation') } | |
379 | break | |
6703b9f4 JB |
380 | } |
381 | this.sendToMainWorker({ | |
382 | taskFunctionOperation, | |
383 | taskFunctionOperationStatus: response.status, | |
31847469 | 384 | taskFunctionProperties, |
adee6053 | 385 | ...(!response.status && |
c63a35a0 | 386 | response.error != null && { |
adee6053 | 387 | workerError: { |
31847469 | 388 | name: taskFunctionProperties.name, |
adee6053 JB |
389 | message: this.handleError(response.error as Error | string) |
390 | } | |
391 | }) | |
6703b9f4 JB |
392 | }) |
393 | } | |
394 | ||
984dc9c8 JB |
395 | /** |
396 | * Handles a kill message sent by the main worker. | |
397 | * | |
398 | * @param message - The kill message. | |
399 | */ | |
97cf8c0d | 400 | protected handleKillMessage (_message: MessageValue<Data>): void { |
29d8b961 | 401 | this.stopCheckActive() |
07588f30 | 402 | if (isAsyncFunction(this.opts.killHandler)) { |
c63a35a0 | 403 | (this.opts.killHandler() as Promise<void>) |
1e3214b6 | 404 | .then(() => { |
895b5341 | 405 | this.sendToMainWorker({ kill: 'success' }) |
fefd3cef | 406 | return undefined |
1e3214b6 JB |
407 | }) |
408 | .catch(() => { | |
895b5341 | 409 | this.sendToMainWorker({ kill: 'failure' }) |
1e3214b6 | 410 | }) |
07588f30 | 411 | } else { |
1e3214b6 JB |
412 | try { |
413 | // eslint-disable-next-line @typescript-eslint/no-invalid-void-type | |
414 | this.opts.killHandler?.() as void | |
895b5341 | 415 | this.sendToMainWorker({ kill: 'success' }) |
7c8ac84e | 416 | } catch { |
895b5341 | 417 | this.sendToMainWorker({ kill: 'failure' }) |
1e3214b6 | 418 | } |
07588f30 | 419 | } |
984dc9c8 JB |
420 | } |
421 | ||
9e746eec JB |
422 | /** |
423 | * Check if the message worker id is set and matches the worker id. | |
424 | * | |
425 | * @param message - The message to check. | |
426 | * @throws {@link https://nodejs.org/api/errors.html#class-error} If the message worker id is not set or does not match the worker id. | |
427 | */ | |
428 | private checkMessageWorkerId (message: MessageValue<Data>): void { | |
429 | if (message.workerId == null) { | |
430 | throw new Error('Message worker id is not set') | |
8e5a7cf9 | 431 | } else if (message.workerId !== this.id) { |
9e746eec JB |
432 | throw new Error( |
433 | `Message worker id ${message.workerId} does not match the worker id ${this.id}` | |
434 | ) | |
435 | } | |
436 | } | |
437 | ||
48487131 | 438 | /** |
b0a4db63 | 439 | * Starts the worker check active interval. |
48487131 | 440 | */ |
b0a4db63 | 441 | private startCheckActive (): void { |
75d3401a | 442 | this.lastTaskTimestamp = performance.now() |
b0a4db63 JB |
443 | this.activeInterval = setInterval( |
444 | this.checkActive.bind(this), | |
75d3401a | 445 | (this.opts.maxInactiveTime ?? DEFAULT_MAX_INACTIVE_TIME) / 2 |
984dc9c8 | 446 | ) |
75d3401a JB |
447 | } |
448 | ||
48487131 | 449 | /** |
b0a4db63 | 450 | * Stops the worker check active interval. |
48487131 | 451 | */ |
b0a4db63 | 452 | private stopCheckActive (): void { |
c3f498b5 JB |
453 | if (this.activeInterval != null) { |
454 | clearInterval(this.activeInterval) | |
455 | delete this.activeInterval | |
456 | } | |
48487131 JB |
457 | } |
458 | ||
459 | /** | |
460 | * Checks if the worker should be terminated, because its living too long. | |
461 | */ | |
b0a4db63 | 462 | private checkActive (): void { |
48487131 JB |
463 | if ( |
464 | performance.now() - this.lastTaskTimestamp > | |
465 | (this.opts.maxInactiveTime ?? DEFAULT_MAX_INACTIVE_TIME) | |
466 | ) { | |
895b5341 | 467 | this.sendToMainWorker({ kill: this.opts.killBehavior }) |
48487131 JB |
468 | } |
469 | } | |
470 | ||
729c563d S |
471 | /** |
472 | * Returns the main worker. | |
838898f1 S |
473 | * |
474 | * @returns Reference to the main worker. | |
155bb3de | 475 | * @throws {@link https://nodejs.org/api/errors.html#class-error} If the main worker is not set. |
729c563d | 476 | */ |
838898f1 | 477 | protected getMainWorker (): MainWorker { |
78cea37e | 478 | if (this.mainWorker == null) { |
e102732c | 479 | throw new Error('Main worker not set') |
838898f1 S |
480 | } |
481 | return this.mainWorker | |
482 | } | |
c97c7edb | 483 | |
729c563d | 484 | /** |
aa9eede8 | 485 | * Sends a message to main worker. |
729c563d | 486 | * |
38e795c1 | 487 | * @param message - The response message. |
729c563d | 488 | */ |
82f36766 JB |
489 | protected abstract sendToMainWorker ( |
490 | message: MessageValue<Response, Data> | |
491 | ): void | |
c97c7edb | 492 | |
90d7d101 | 493 | /** |
31847469 | 494 | * Sends task functions properties to the main worker. |
90d7d101 | 495 | */ |
31847469 | 496 | protected sendTaskFunctionsPropertiesToMainWorker (): void { |
90d7d101 | 497 | this.sendToMainWorker({ |
31847469 | 498 | taskFunctionsProperties: this.listTaskFunctionsProperties() |
90d7d101 JB |
499 | }) |
500 | } | |
501 | ||
729c563d | 502 | /** |
8accb8d5 | 503 | * Handles an error and convert it to a string so it can be sent back to the main worker. |
729c563d | 504 | * |
6703b9f4 | 505 | * @param error - The error raised by the worker. |
ab80dc46 | 506 | * @returns The error message. |
729c563d | 507 | */ |
6703b9f4 JB |
508 | protected handleError (error: Error | string): string { |
509 | return error instanceof Error ? error.message : error | |
c97c7edb S |
510 | } |
511 | ||
5c4d16da JB |
512 | /** |
513 | * Runs the given task. | |
514 | * | |
515 | * @param task - The task to execute. | |
5c4d16da | 516 | */ |
803f948f | 517 | protected readonly run = (task: Task<Data>): void => { |
9d2d0da1 | 518 | const { name, taskId, data } = task |
c878a240 JB |
519 | const taskFunctionName = name ?? DEFAULT_TASK_NAME |
520 | if (!this.taskFunctions.has(taskFunctionName)) { | |
9d2d0da1 | 521 | this.sendToMainWorker({ |
6703b9f4 | 522 | workerError: { |
67f3f2d6 JB |
523 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion |
524 | name: name!, | |
c63a35a0 | 525 | message: `Task function '${name}' not found`, |
9d2d0da1 JB |
526 | data |
527 | }, | |
9d2d0da1 JB |
528 | taskId |
529 | }) | |
530 | return | |
531 | } | |
31847469 | 532 | const fn = this.taskFunctions.get(taskFunctionName)?.taskFunction |
5c4d16da | 533 | if (isAsyncFunction(fn)) { |
69b70a7e | 534 | this.runAsync(fn as TaskAsyncFunction<Data, Response>, task) |
5c4d16da | 535 | } else { |
69b70a7e | 536 | this.runSync(fn as TaskSyncFunction<Data, Response>, task) |
5c4d16da JB |
537 | } |
538 | } | |
539 | ||
729c563d | 540 | /** |
4dd93fcf | 541 | * Runs the given task function synchronously. |
729c563d | 542 | * |
5c4d16da JB |
543 | * @param fn - Task function that will be executed. |
544 | * @param task - Input data for the task function. | |
729c563d | 545 | */ |
803f948f | 546 | protected readonly runSync = ( |
82ea6492 | 547 | fn: TaskSyncFunction<Data, Response>, |
5c4d16da | 548 | task: Task<Data> |
803f948f | 549 | ): void => { |
310de0aa | 550 | const { name, taskId, data } = task |
c97c7edb | 551 | try { |
310de0aa JB |
552 | let taskPerformance = this.beginTaskPerformance(name) |
553 | const res = fn(data) | |
d715b7bc | 554 | taskPerformance = this.endTaskPerformance(taskPerformance) |
3fafb1b2 JB |
555 | this.sendToMainWorker({ |
556 | data: res, | |
d715b7bc | 557 | taskPerformance, |
310de0aa | 558 | taskId |
3fafb1b2 | 559 | }) |
6703b9f4 | 560 | } catch (error) { |
91ee39ed | 561 | this.sendToMainWorker({ |
6703b9f4 | 562 | workerError: { |
67f3f2d6 JB |
563 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion |
564 | name: name!, | |
6703b9f4 | 565 | message: this.handleError(error as Error | string), |
310de0aa | 566 | data |
82f36766 | 567 | }, |
310de0aa | 568 | taskId |
91ee39ed | 569 | }) |
6e9d10db | 570 | } finally { |
c3f498b5 | 571 | this.updateLastTaskTimestamp() |
c97c7edb S |
572 | } |
573 | } | |
574 | ||
729c563d | 575 | /** |
4dd93fcf | 576 | * Runs the given task function asynchronously. |
729c563d | 577 | * |
5c4d16da JB |
578 | * @param fn - Task function that will be executed. |
579 | * @param task - Input data for the task function. | |
729c563d | 580 | */ |
803f948f | 581 | protected readonly runAsync = ( |
82ea6492 | 582 | fn: TaskAsyncFunction<Data, Response>, |
5c4d16da | 583 | task: Task<Data> |
803f948f | 584 | ): void => { |
310de0aa JB |
585 | const { name, taskId, data } = task |
586 | let taskPerformance = this.beginTaskPerformance(name) | |
587 | fn(data) | |
041dc05b | 588 | .then(res => { |
d715b7bc | 589 | taskPerformance = this.endTaskPerformance(taskPerformance) |
3fafb1b2 JB |
590 | this.sendToMainWorker({ |
591 | data: res, | |
d715b7bc | 592 | taskPerformance, |
310de0aa | 593 | taskId |
3fafb1b2 | 594 | }) |
04714ef7 | 595 | return undefined |
c97c7edb | 596 | }) |
07f6f7b1 | 597 | .catch((error: unknown) => { |
91ee39ed | 598 | this.sendToMainWorker({ |
6703b9f4 | 599 | workerError: { |
67f3f2d6 JB |
600 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion |
601 | name: name!, | |
6703b9f4 | 602 | message: this.handleError(error as Error | string), |
310de0aa | 603 | data |
82f36766 | 604 | }, |
310de0aa | 605 | taskId |
91ee39ed | 606 | }) |
6e9d10db JB |
607 | }) |
608 | .finally(() => { | |
c3f498b5 | 609 | this.updateLastTaskTimestamp() |
c97c7edb | 610 | }) |
6e9d10db | 611 | .catch(EMPTY_FUNCTION) |
c97c7edb | 612 | } |
ec8fd331 | 613 | |
197b4aa5 | 614 | private beginTaskPerformance (name?: string): TaskPerformance { |
c63a35a0 JB |
615 | if (this.statistics == null) { |
616 | throw new Error('Performance statistics computation requirements not set') | |
617 | } | |
62c15a68 | 618 | return { |
ff128cc9 | 619 | name: name ?? DEFAULT_TASK_NAME, |
1c6fe997 | 620 | timestamp: performance.now(), |
c63a35a0 JB |
621 | ...(this.statistics.elu && { |
622 | elu: performance.eventLoopUtilization() | |
623 | }) | |
62c15a68 JB |
624 | } |
625 | } | |
626 | ||
d9d31201 JB |
627 | private endTaskPerformance ( |
628 | taskPerformance: TaskPerformance | |
629 | ): TaskPerformance { | |
c63a35a0 JB |
630 | if (this.statistics == null) { |
631 | throw new Error('Performance statistics computation requirements not set') | |
632 | } | |
62c15a68 JB |
633 | return { |
634 | ...taskPerformance, | |
b6b32453 JB |
635 | ...(this.statistics.runTime && { |
636 | runTime: performance.now() - taskPerformance.timestamp | |
637 | }), | |
638 | ...(this.statistics.elu && { | |
62c15a68 | 639 | elu: performance.eventLoopUtilization(taskPerformance.elu) |
b6b32453 | 640 | }) |
62c15a68 JB |
641 | } |
642 | } | |
8a970421 | 643 | |
c3f498b5 | 644 | private updateLastTaskTimestamp (): void { |
29d8b961 | 645 | if (this.activeInterval != null) { |
c3f498b5 JB |
646 | this.lastTaskTimestamp = performance.now() |
647 | } | |
648 | } | |
c97c7edb | 649 | } |