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