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