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