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