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 |
edbc15c6 | 382 | if (taskFunctionOperation === 'add') { |
6703b9f4 JB |
383 | response = this.addTaskFunction( |
384 | taskFunctionName as string, | |
385 | // eslint-disable-next-line @typescript-eslint/no-implied-eval, no-new-func | |
386 | new Function(`return ${taskFunction as string}`)() as TaskFunction< | |
387 | Data, | |
388 | Response | |
adee6053 | 389 | > |
6703b9f4 JB |
390 | ) |
391 | } else if (taskFunctionOperation === 'remove') { | |
392 | response = this.removeTaskFunction(taskFunctionName as string) | |
393 | } else if (taskFunctionOperation === 'default') { | |
394 | response = this.setDefaultTaskFunction(taskFunctionName as string) | |
395 | } | |
396 | this.sendToMainWorker({ | |
397 | taskFunctionOperation, | |
398 | taskFunctionOperationStatus: response.status, | |
adee6053 JB |
399 | taskFunctionName, |
400 | ...(!response.status && | |
401 | response?.error != null && { | |
402 | workerError: { | |
403 | name: taskFunctionName as string, | |
404 | message: this.handleError(response.error as Error | string) | |
405 | } | |
406 | }) | |
6703b9f4 JB |
407 | }) |
408 | } | |
409 | ||
984dc9c8 JB |
410 | /** |
411 | * Handles a kill message sent by the main worker. | |
412 | * | |
413 | * @param message - The kill message. | |
414 | */ | |
415 | protected handleKillMessage (message: MessageValue<Data>): void { | |
29d8b961 | 416 | this.stopCheckActive() |
07588f30 | 417 | if (isAsyncFunction(this.opts.killHandler)) { |
041dc05b | 418 | (this.opts.killHandler?.() as Promise<void>) |
1e3214b6 | 419 | .then(() => { |
895b5341 | 420 | this.sendToMainWorker({ kill: 'success' }) |
1e3214b6 JB |
421 | return null |
422 | }) | |
423 | .catch(() => { | |
895b5341 | 424 | this.sendToMainWorker({ kill: 'failure' }) |
1e3214b6 JB |
425 | }) |
426 | .finally(() => { | |
427 | this.emitDestroy() | |
428 | }) | |
07588f30 JB |
429 | .catch(EMPTY_FUNCTION) |
430 | } else { | |
1e3214b6 JB |
431 | try { |
432 | // eslint-disable-next-line @typescript-eslint/no-invalid-void-type | |
433 | this.opts.killHandler?.() as void | |
895b5341 | 434 | this.sendToMainWorker({ kill: 'success' }) |
7c8ac84e | 435 | } catch { |
895b5341 | 436 | this.sendToMainWorker({ kill: 'failure' }) |
1e3214b6 JB |
437 | } finally { |
438 | this.emitDestroy() | |
439 | } | |
07588f30 | 440 | } |
984dc9c8 JB |
441 | } |
442 | ||
9e746eec JB |
443 | /** |
444 | * Check if the message worker id is set and matches the worker id. | |
445 | * | |
446 | * @param message - The message to check. | |
447 | * @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. | |
448 | */ | |
449 | private checkMessageWorkerId (message: MessageValue<Data>): void { | |
450 | if (message.workerId == null) { | |
451 | throw new Error('Message worker id is not set') | |
452 | } else if (message.workerId != null && message.workerId !== this.id) { | |
453 | throw new Error( | |
454 | `Message worker id ${message.workerId} does not match the worker id ${this.id}` | |
455 | ) | |
456 | } | |
457 | } | |
458 | ||
48487131 | 459 | /** |
b0a4db63 | 460 | * Starts the worker check active interval. |
48487131 | 461 | */ |
b0a4db63 | 462 | private startCheckActive (): void { |
75d3401a | 463 | this.lastTaskTimestamp = performance.now() |
b0a4db63 JB |
464 | this.activeInterval = setInterval( |
465 | this.checkActive.bind(this), | |
75d3401a | 466 | (this.opts.maxInactiveTime ?? DEFAULT_MAX_INACTIVE_TIME) / 2 |
984dc9c8 | 467 | ) |
75d3401a JB |
468 | } |
469 | ||
48487131 | 470 | /** |
b0a4db63 | 471 | * Stops the worker check active interval. |
48487131 | 472 | */ |
b0a4db63 | 473 | private stopCheckActive (): void { |
c3f498b5 JB |
474 | if (this.activeInterval != null) { |
475 | clearInterval(this.activeInterval) | |
476 | delete this.activeInterval | |
477 | } | |
48487131 JB |
478 | } |
479 | ||
480 | /** | |
481 | * Checks if the worker should be terminated, because its living too long. | |
482 | */ | |
b0a4db63 | 483 | private checkActive (): void { |
48487131 JB |
484 | if ( |
485 | performance.now() - this.lastTaskTimestamp > | |
486 | (this.opts.maxInactiveTime ?? DEFAULT_MAX_INACTIVE_TIME) | |
487 | ) { | |
895b5341 | 488 | this.sendToMainWorker({ kill: this.opts.killBehavior }) |
48487131 JB |
489 | } |
490 | } | |
491 | ||
729c563d S |
492 | /** |
493 | * Returns the main worker. | |
838898f1 S |
494 | * |
495 | * @returns Reference to the main worker. | |
155bb3de | 496 | * @throws {@link https://nodejs.org/api/errors.html#class-error} If the main worker is not set. |
729c563d | 497 | */ |
838898f1 | 498 | protected getMainWorker (): MainWorker { |
78cea37e | 499 | if (this.mainWorker == null) { |
e102732c | 500 | throw new Error('Main worker not set') |
838898f1 S |
501 | } |
502 | return this.mainWorker | |
503 | } | |
c97c7edb | 504 | |
729c563d | 505 | /** |
aa9eede8 | 506 | * Sends a message to main worker. |
729c563d | 507 | * |
38e795c1 | 508 | * @param message - The response message. |
729c563d | 509 | */ |
82f36766 JB |
510 | protected abstract sendToMainWorker ( |
511 | message: MessageValue<Response, Data> | |
512 | ): void | |
c97c7edb | 513 | |
90d7d101 | 514 | /** |
e81c38f2 | 515 | * Sends task function names to the main worker. |
90d7d101 | 516 | */ |
e81c38f2 | 517 | protected sendTaskFunctionNamesToMainWorker (): void { |
90d7d101 | 518 | this.sendToMainWorker({ |
895b5341 | 519 | taskFunctionNames: this.listTaskFunctionNames() |
90d7d101 JB |
520 | }) |
521 | } | |
522 | ||
729c563d | 523 | /** |
8accb8d5 | 524 | * Handles an error and convert it to a string so it can be sent back to the main worker. |
729c563d | 525 | * |
6703b9f4 | 526 | * @param error - The error raised by the worker. |
ab80dc46 | 527 | * @returns The error message. |
729c563d | 528 | */ |
6703b9f4 JB |
529 | protected handleError (error: Error | string): string { |
530 | return error instanceof Error ? error.message : error | |
c97c7edb S |
531 | } |
532 | ||
5c4d16da JB |
533 | /** |
534 | * Runs the given task. | |
535 | * | |
536 | * @param task - The task to execute. | |
537 | * @throws {@link https://nodejs.org/api/errors.html#class-error} If the task function is not found. | |
538 | */ | |
539 | protected run (task: Task<Data>): void { | |
9d2d0da1 JB |
540 | const { name, taskId, data } = task |
541 | const fn = this.taskFunctions.get(name ?? DEFAULT_TASK_NAME) | |
542 | if (fn == null) { | |
543 | this.sendToMainWorker({ | |
6703b9f4 | 544 | workerError: { |
9d2d0da1 JB |
545 | name: name as string, |
546 | message: `Task function '${name as string}' not found`, | |
547 | data | |
548 | }, | |
9d2d0da1 JB |
549 | taskId |
550 | }) | |
551 | return | |
552 | } | |
5c4d16da JB |
553 | if (isAsyncFunction(fn)) { |
554 | this.runInAsyncScope(this.runAsync.bind(this), this, fn, task) | |
555 | } else { | |
556 | this.runInAsyncScope(this.runSync.bind(this), this, fn, task) | |
557 | } | |
558 | } | |
559 | ||
729c563d | 560 | /** |
4dd93fcf | 561 | * Runs the given task function synchronously. |
729c563d | 562 | * |
5c4d16da JB |
563 | * @param fn - Task function that will be executed. |
564 | * @param task - Input data for the task function. | |
729c563d | 565 | */ |
70a4f5ea | 566 | protected runSync ( |
82ea6492 | 567 | fn: TaskSyncFunction<Data, Response>, |
5c4d16da | 568 | task: Task<Data> |
c97c7edb | 569 | ): void { |
310de0aa | 570 | const { name, taskId, data } = task |
c97c7edb | 571 | try { |
310de0aa JB |
572 | let taskPerformance = this.beginTaskPerformance(name) |
573 | const res = fn(data) | |
d715b7bc | 574 | taskPerformance = this.endTaskPerformance(taskPerformance) |
3fafb1b2 JB |
575 | this.sendToMainWorker({ |
576 | data: res, | |
d715b7bc | 577 | taskPerformance, |
310de0aa | 578 | taskId |
3fafb1b2 | 579 | }) |
6703b9f4 | 580 | } catch (error) { |
91ee39ed | 581 | this.sendToMainWorker({ |
6703b9f4 | 582 | workerError: { |
0628755c | 583 | name: name as string, |
6703b9f4 | 584 | message: this.handleError(error as Error | string), |
310de0aa | 585 | data |
82f36766 | 586 | }, |
310de0aa | 587 | taskId |
91ee39ed | 588 | }) |
6e9d10db | 589 | } finally { |
c3f498b5 | 590 | this.updateLastTaskTimestamp() |
c97c7edb S |
591 | } |
592 | } | |
593 | ||
729c563d | 594 | /** |
4dd93fcf | 595 | * Runs the given task function asynchronously. |
729c563d | 596 | * |
5c4d16da JB |
597 | * @param fn - Task function that will be executed. |
598 | * @param task - Input data for the task function. | |
729c563d | 599 | */ |
c97c7edb | 600 | protected runAsync ( |
82ea6492 | 601 | fn: TaskAsyncFunction<Data, Response>, |
5c4d16da | 602 | task: Task<Data> |
c97c7edb | 603 | ): void { |
310de0aa JB |
604 | const { name, taskId, data } = task |
605 | let taskPerformance = this.beginTaskPerformance(name) | |
606 | fn(data) | |
041dc05b | 607 | .then(res => { |
d715b7bc | 608 | taskPerformance = this.endTaskPerformance(taskPerformance) |
3fafb1b2 JB |
609 | this.sendToMainWorker({ |
610 | data: res, | |
d715b7bc | 611 | taskPerformance, |
310de0aa | 612 | taskId |
3fafb1b2 | 613 | }) |
04714ef7 | 614 | return undefined |
c97c7edb | 615 | }) |
6703b9f4 | 616 | .catch(error => { |
91ee39ed | 617 | this.sendToMainWorker({ |
6703b9f4 | 618 | workerError: { |
0628755c | 619 | name: name as string, |
6703b9f4 | 620 | message: this.handleError(error as Error | string), |
310de0aa | 621 | data |
82f36766 | 622 | }, |
310de0aa | 623 | taskId |
91ee39ed | 624 | }) |
6e9d10db JB |
625 | }) |
626 | .finally(() => { | |
c3f498b5 | 627 | this.updateLastTaskTimestamp() |
c97c7edb | 628 | }) |
6e9d10db | 629 | .catch(EMPTY_FUNCTION) |
c97c7edb | 630 | } |
ec8fd331 | 631 | |
197b4aa5 | 632 | private beginTaskPerformance (name?: string): TaskPerformance { |
8a970421 | 633 | this.checkStatistics() |
62c15a68 | 634 | return { |
ff128cc9 | 635 | name: name ?? DEFAULT_TASK_NAME, |
1c6fe997 | 636 | timestamp: performance.now(), |
b6b32453 | 637 | ...(this.statistics.elu && { elu: performance.eventLoopUtilization() }) |
62c15a68 JB |
638 | } |
639 | } | |
640 | ||
d9d31201 JB |
641 | private endTaskPerformance ( |
642 | taskPerformance: TaskPerformance | |
643 | ): TaskPerformance { | |
8a970421 | 644 | this.checkStatistics() |
62c15a68 JB |
645 | return { |
646 | ...taskPerformance, | |
b6b32453 JB |
647 | ...(this.statistics.runTime && { |
648 | runTime: performance.now() - taskPerformance.timestamp | |
649 | }), | |
650 | ...(this.statistics.elu && { | |
62c15a68 | 651 | elu: performance.eventLoopUtilization(taskPerformance.elu) |
b6b32453 | 652 | }) |
62c15a68 JB |
653 | } |
654 | } | |
8a970421 JB |
655 | |
656 | private checkStatistics (): void { | |
657 | if (this.statistics == null) { | |
658 | throw new Error('Performance statistics computation requirements not set') | |
659 | } | |
660 | } | |
c3f498b5 JB |
661 | |
662 | private updateLastTaskTimestamp (): void { | |
29d8b961 | 663 | if (this.activeInterval != null) { |
c3f498b5 JB |
664 | this.lastTaskTimestamp = performance.now() |
665 | } | |
666 | } | |
c97c7edb | 667 | } |