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, | |
4e38fd21 | 21 | TaskFunctionOperationResult, |
b6b32453 | 22 | TaskFunctions, |
82ea6492 JB |
23 | TaskSyncFunction |
24 | } from './task-functions' | |
9a38f99e JB |
25 | import { |
26 | checkTaskFunctionName, | |
27 | checkValidTaskFunctionEntry, | |
28 | checkValidWorkerOptions | |
29 | } from './utils' | |
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 | |
c97c7edb | 59 | > extends AsyncResource { |
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 JB |
74 | */ |
75 | protected statistics!: WorkerStatistics | |
729c563d | 76 | /** |
b0a4db63 | 77 | * Handler id of the `activeInterval` worker activity check. |
729c563d | 78 | */ |
b0a4db63 | 79 | protected activeInterval?: NodeJS.Timeout |
c97c7edb | 80 | /** |
729c563d | 81 | * Constructs a new poolifier worker. |
c97c7edb | 82 | * |
38e795c1 JB |
83 | * @param type - The type of async event. |
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 ( | |
90 | type: string, | |
c2ade475 | 91 | protected readonly isMain: boolean, |
6c0c538c | 92 | private readonly mainWorker: MainWorker, |
82ea6492 | 93 | taskFunctions: TaskFunction<Data, Response> | TaskFunctions<Data, Response>, |
d38d0e30 | 94 | protected opts: WorkerOptions = DEFAULT_WORKER_OPTIONS |
c97c7edb S |
95 | ) { |
96 | super(type) | |
9d2d0da1 JB |
97 | if (this.isMain == null) { |
98 | throw new Error('isMain parameter is mandatory') | |
99 | } | |
a86b6df1 | 100 | this.checkTaskFunctions(taskFunctions) |
9d2d0da1 | 101 | this.checkWorkerOptions(this.opts) |
1f68cede | 102 | if (!this.isMain) { |
0cb6edc2 | 103 | // Should be once() but Node.js on windows has a bug that prevents it from working |
e2898b4f | 104 | this.getMainWorker().on('message', this.handleReadyMessage.bind(this)) |
c97c7edb S |
105 | } |
106 | } | |
107 | ||
41aa7dcd | 108 | private checkWorkerOptions (opts: WorkerOptions): void { |
9a38f99e | 109 | checkValidWorkerOptions(opts) |
d38d0e30 | 110 | this.opts = { ...DEFAULT_WORKER_OPTIONS, ...opts } |
41aa7dcd JB |
111 | } |
112 | ||
113 | /** | |
c20084b6 | 114 | * Checks if the `taskFunctions` parameter is passed to the constructor and valid. |
41aa7dcd | 115 | * |
82888165 | 116 | * @param taskFunctions - The task function(s) parameter that should be checked. |
41aa7dcd | 117 | */ |
a86b6df1 | 118 | private checkTaskFunctions ( |
82ea6492 | 119 | taskFunctions: TaskFunction<Data, Response> | TaskFunctions<Data, Response> |
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 | } | |
968a2e8c JB |
283 | this.taskFunctions.set( |
284 | DEFAULT_TASK_NAME, | |
82ea6492 | 285 | this.taskFunctions.get(name) as TaskFunction<Data, Response> |
968a2e8c | 286 | ) |
9eae3c69 | 287 | this.sendTaskFunctionNamesToMainWorker() |
6703b9f4 JB |
288 | return { status: true } |
289 | } catch (error) { | |
290 | return { status: false, error: error as Error } | |
968a2e8c JB |
291 | } |
292 | } | |
293 | ||
a038b517 JB |
294 | /** |
295 | * Handles the ready message sent by the main worker. | |
296 | * | |
297 | * @param message - The ready message. | |
298 | */ | |
299 | protected abstract handleReadyMessage (message: MessageValue<Data>): void | |
300 | ||
aee46736 JB |
301 | /** |
302 | * Worker message listener. | |
303 | * | |
6b813701 | 304 | * @param message - The received message. |
aee46736 | 305 | */ |
85aeb3f3 | 306 | protected messageListener (message: MessageValue<Data>): void { |
9e746eec | 307 | this.checkMessageWorkerId(message) |
310de0aa JB |
308 | if (message.statistics != null) { |
309 | // Statistics message received | |
310 | this.statistics = message.statistics | |
311 | } else if (message.checkActive != null) { | |
312 | // Check active message received | |
313 | message.checkActive ? this.startCheckActive() : this.stopCheckActive() | |
6703b9f4 JB |
314 | } else if (message.taskFunctionOperation != null) { |
315 | // Task function operation message received | |
316 | this.handleTaskFunctionOperationMessage(message) | |
310de0aa JB |
317 | } else if (message.taskId != null && message.data != null) { |
318 | // Task message received | |
319 | this.run(message) | |
320 | } else if (message.kill === true) { | |
321 | // Kill message received | |
322 | this.handleKillMessage(message) | |
cf597bc5 JB |
323 | } |
324 | } | |
325 | ||
6703b9f4 JB |
326 | protected handleTaskFunctionOperationMessage ( |
327 | message: MessageValue<Data> | |
328 | ): void { | |
9eae3c69 | 329 | const { taskFunctionOperation, taskFunctionName, taskFunction } = message |
4e38fd21 | 330 | let response!: TaskFunctionOperationResult |
d2dd5ef5 JB |
331 | switch (taskFunctionOperation) { |
332 | case 'add': | |
333 | response = this.addTaskFunction( | |
334 | taskFunctionName as string, | |
335 | // eslint-disable-next-line @typescript-eslint/no-implied-eval, no-new-func | |
336 | new Function(`return ${taskFunction as string}`)() as TaskFunction< | |
337 | Data, | |
338 | Response | |
339 | > | |
340 | ) | |
341 | break | |
342 | case 'remove': | |
343 | response = this.removeTaskFunction(taskFunctionName as string) | |
344 | break | |
345 | case 'default': | |
346 | response = this.setDefaultTaskFunction(taskFunctionName as string) | |
347 | break | |
348 | default: | |
349 | response = { status: false, error: new Error('Unknown task operation') } | |
350 | break | |
6703b9f4 JB |
351 | } |
352 | this.sendToMainWorker({ | |
353 | taskFunctionOperation, | |
354 | taskFunctionOperationStatus: response.status, | |
adee6053 JB |
355 | taskFunctionName, |
356 | ...(!response.status && | |
357 | response?.error != null && { | |
358 | workerError: { | |
359 | name: taskFunctionName as string, | |
360 | message: this.handleError(response.error as Error | string) | |
361 | } | |
362 | }) | |
6703b9f4 JB |
363 | }) |
364 | } | |
365 | ||
984dc9c8 JB |
366 | /** |
367 | * Handles a kill message sent by the main worker. | |
368 | * | |
369 | * @param message - The kill message. | |
370 | */ | |
97cf8c0d | 371 | protected handleKillMessage (_message: MessageValue<Data>): void { |
29d8b961 | 372 | this.stopCheckActive() |
07588f30 | 373 | if (isAsyncFunction(this.opts.killHandler)) { |
041dc05b | 374 | (this.opts.killHandler?.() as Promise<void>) |
1e3214b6 | 375 | .then(() => { |
895b5341 | 376 | this.sendToMainWorker({ kill: 'success' }) |
fefd3cef | 377 | return undefined |
1e3214b6 JB |
378 | }) |
379 | .catch(() => { | |
895b5341 | 380 | this.sendToMainWorker({ kill: 'failure' }) |
1e3214b6 JB |
381 | }) |
382 | .finally(() => { | |
383 | this.emitDestroy() | |
384 | }) | |
07588f30 JB |
385 | .catch(EMPTY_FUNCTION) |
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 JB |
393 | } finally { |
394 | this.emitDestroy() | |
395 | } | |
07588f30 | 396 | } |
984dc9c8 JB |
397 | } |
398 | ||
9e746eec JB |
399 | /** |
400 | * Check if the message worker id is set and matches the worker id. | |
401 | * | |
402 | * @param message - The message to check. | |
403 | * @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. | |
404 | */ | |
405 | private checkMessageWorkerId (message: MessageValue<Data>): void { | |
406 | if (message.workerId == null) { | |
407 | throw new Error('Message worker id is not set') | |
408 | } else if (message.workerId != null && message.workerId !== this.id) { | |
409 | throw new Error( | |
410 | `Message worker id ${message.workerId} does not match the worker id ${this.id}` | |
411 | ) | |
412 | } | |
413 | } | |
414 | ||
48487131 | 415 | /** |
b0a4db63 | 416 | * Starts the worker check active interval. |
48487131 | 417 | */ |
b0a4db63 | 418 | private startCheckActive (): void { |
75d3401a | 419 | this.lastTaskTimestamp = performance.now() |
b0a4db63 JB |
420 | this.activeInterval = setInterval( |
421 | this.checkActive.bind(this), | |
75d3401a | 422 | (this.opts.maxInactiveTime ?? DEFAULT_MAX_INACTIVE_TIME) / 2 |
984dc9c8 | 423 | ) |
75d3401a JB |
424 | } |
425 | ||
48487131 | 426 | /** |
b0a4db63 | 427 | * Stops the worker check active interval. |
48487131 | 428 | */ |
b0a4db63 | 429 | private stopCheckActive (): void { |
c3f498b5 JB |
430 | if (this.activeInterval != null) { |
431 | clearInterval(this.activeInterval) | |
432 | delete this.activeInterval | |
433 | } | |
48487131 JB |
434 | } |
435 | ||
436 | /** | |
437 | * Checks if the worker should be terminated, because its living too long. | |
438 | */ | |
b0a4db63 | 439 | private checkActive (): void { |
48487131 JB |
440 | if ( |
441 | performance.now() - this.lastTaskTimestamp > | |
442 | (this.opts.maxInactiveTime ?? DEFAULT_MAX_INACTIVE_TIME) | |
443 | ) { | |
895b5341 | 444 | this.sendToMainWorker({ kill: this.opts.killBehavior }) |
48487131 JB |
445 | } |
446 | } | |
447 | ||
729c563d S |
448 | /** |
449 | * Returns the main worker. | |
838898f1 S |
450 | * |
451 | * @returns Reference to the main worker. | |
155bb3de | 452 | * @throws {@link https://nodejs.org/api/errors.html#class-error} If the main worker is not set. |
729c563d | 453 | */ |
838898f1 | 454 | protected getMainWorker (): MainWorker { |
78cea37e | 455 | if (this.mainWorker == null) { |
e102732c | 456 | throw new Error('Main worker not set') |
838898f1 S |
457 | } |
458 | return this.mainWorker | |
459 | } | |
c97c7edb | 460 | |
729c563d | 461 | /** |
aa9eede8 | 462 | * Sends a message to main worker. |
729c563d | 463 | * |
38e795c1 | 464 | * @param message - The response message. |
729c563d | 465 | */ |
82f36766 JB |
466 | protected abstract sendToMainWorker ( |
467 | message: MessageValue<Response, Data> | |
468 | ): void | |
c97c7edb | 469 | |
90d7d101 | 470 | /** |
e81c38f2 | 471 | * Sends task function names to the main worker. |
90d7d101 | 472 | */ |
e81c38f2 | 473 | protected sendTaskFunctionNamesToMainWorker (): void { |
90d7d101 | 474 | this.sendToMainWorker({ |
895b5341 | 475 | taskFunctionNames: this.listTaskFunctionNames() |
90d7d101 JB |
476 | }) |
477 | } | |
478 | ||
729c563d | 479 | /** |
8accb8d5 | 480 | * Handles an error and convert it to a string so it can be sent back to the main worker. |
729c563d | 481 | * |
6703b9f4 | 482 | * @param error - The error raised by the worker. |
ab80dc46 | 483 | * @returns The error message. |
729c563d | 484 | */ |
6703b9f4 JB |
485 | protected handleError (error: Error | string): string { |
486 | return error instanceof Error ? error.message : error | |
c97c7edb S |
487 | } |
488 | ||
5c4d16da JB |
489 | /** |
490 | * Runs the given task. | |
491 | * | |
492 | * @param task - The task to execute. | |
5c4d16da JB |
493 | */ |
494 | protected run (task: Task<Data>): void { | |
9d2d0da1 JB |
495 | const { name, taskId, data } = task |
496 | const fn = this.taskFunctions.get(name ?? DEFAULT_TASK_NAME) | |
497 | if (fn == null) { | |
498 | this.sendToMainWorker({ | |
6703b9f4 | 499 | workerError: { |
9d2d0da1 JB |
500 | name: name as string, |
501 | message: `Task function '${name as string}' not found`, | |
502 | data | |
503 | }, | |
9d2d0da1 JB |
504 | taskId |
505 | }) | |
506 | return | |
507 | } | |
5c4d16da JB |
508 | if (isAsyncFunction(fn)) { |
509 | this.runInAsyncScope(this.runAsync.bind(this), this, fn, task) | |
510 | } else { | |
511 | this.runInAsyncScope(this.runSync.bind(this), this, fn, task) | |
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 | */ |
70a4f5ea | 521 | protected runSync ( |
82ea6492 | 522 | fn: TaskSyncFunction<Data, Response>, |
5c4d16da | 523 | task: Task<Data> |
c97c7edb | 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: { |
0628755c | 538 | name: name as string, |
6703b9f4 | 539 | message: this.handleError(error as Error | string), |
310de0aa | 540 | data |
82f36766 | 541 | }, |
310de0aa | 542 | taskId |
91ee39ed | 543 | }) |
6e9d10db | 544 | } finally { |
c3f498b5 | 545 | this.updateLastTaskTimestamp() |
c97c7edb S |
546 | } |
547 | } | |
548 | ||
729c563d | 549 | /** |
4dd93fcf | 550 | * Runs the given task function asynchronously. |
729c563d | 551 | * |
5c4d16da JB |
552 | * @param fn - Task function that will be executed. |
553 | * @param task - Input data for the task function. | |
729c563d | 554 | */ |
c97c7edb | 555 | protected runAsync ( |
82ea6492 | 556 | fn: TaskAsyncFunction<Data, Response>, |
5c4d16da | 557 | task: Task<Data> |
c97c7edb | 558 | ): void { |
310de0aa JB |
559 | const { name, taskId, data } = task |
560 | let taskPerformance = this.beginTaskPerformance(name) | |
561 | fn(data) | |
041dc05b | 562 | .then(res => { |
d715b7bc | 563 | taskPerformance = this.endTaskPerformance(taskPerformance) |
3fafb1b2 JB |
564 | this.sendToMainWorker({ |
565 | data: res, | |
d715b7bc | 566 | taskPerformance, |
310de0aa | 567 | taskId |
3fafb1b2 | 568 | }) |
04714ef7 | 569 | return undefined |
c97c7edb | 570 | }) |
6703b9f4 | 571 | .catch(error => { |
91ee39ed | 572 | this.sendToMainWorker({ |
6703b9f4 | 573 | workerError: { |
0628755c | 574 | name: name as string, |
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 { |
8a970421 | 588 | this.checkStatistics() |
62c15a68 | 589 | return { |
ff128cc9 | 590 | name: name ?? DEFAULT_TASK_NAME, |
1c6fe997 | 591 | timestamp: performance.now(), |
b6b32453 | 592 | ...(this.statistics.elu && { elu: performance.eventLoopUtilization() }) |
62c15a68 JB |
593 | } |
594 | } | |
595 | ||
d9d31201 JB |
596 | private endTaskPerformance ( |
597 | taskPerformance: TaskPerformance | |
598 | ): TaskPerformance { | |
8a970421 | 599 | this.checkStatistics() |
62c15a68 JB |
600 | return { |
601 | ...taskPerformance, | |
b6b32453 JB |
602 | ...(this.statistics.runTime && { |
603 | runTime: performance.now() - taskPerformance.timestamp | |
604 | }), | |
605 | ...(this.statistics.elu && { | |
62c15a68 | 606 | elu: performance.eventLoopUtilization(taskPerformance.elu) |
b6b32453 | 607 | }) |
62c15a68 JB |
608 | } |
609 | } | |
8a970421 JB |
610 | |
611 | private checkStatistics (): void { | |
612 | if (this.statistics == null) { | |
613 | throw new Error('Performance statistics computation requirements not set') | |
614 | } | |
615 | } | |
c3f498b5 JB |
616 | |
617 | private updateLastTaskTimestamp (): void { | |
29d8b961 | 618 | if (this.activeInterval != null) { |
c3f498b5 JB |
619 | this.lastTaskTimestamp = performance.now() |
620 | } | |
621 | } | |
c97c7edb | 622 | } |