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