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