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