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 | |
9 | } from '../utility-types' | |
ff128cc9 JB |
10 | import { |
11 | DEFAULT_TASK_NAME, | |
12 | EMPTY_FUNCTION, | |
13 | isAsyncFunction, | |
14 | isPlainObject | |
15 | } from '../utils' | |
d38d0e30 | 16 | import { KillBehaviors, type WorkerOptions } from './worker-options' |
b6b32453 | 17 | import type { |
82ea6492 JB |
18 | TaskAsyncFunction, |
19 | TaskFunction, | |
4e38fd21 | 20 | TaskFunctionOperationResult, |
b6b32453 | 21 | TaskFunctions, |
82ea6492 JB |
22 | TaskSyncFunction |
23 | } from './task-functions' | |
9a38f99e JB |
24 | import { |
25 | checkTaskFunctionName, | |
26 | checkValidTaskFunctionEntry, | |
27 | checkValidWorkerOptions | |
28 | } from './utils' | |
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 | } | |
968a2e8c JB |
280 | this.taskFunctions.set( |
281 | DEFAULT_TASK_NAME, | |
82ea6492 | 282 | this.taskFunctions.get(name) as TaskFunction<Data, Response> |
968a2e8c | 283 | ) |
9eae3c69 | 284 | this.sendTaskFunctionNamesToMainWorker() |
6703b9f4 JB |
285 | return { status: true } |
286 | } catch (error) { | |
287 | return { status: false, error: error as Error } | |
968a2e8c JB |
288 | } |
289 | } | |
290 | ||
a038b517 JB |
291 | /** |
292 | * Handles the ready message sent by the main worker. | |
293 | * | |
294 | * @param message - The ready message. | |
295 | */ | |
296 | protected abstract handleReadyMessage (message: MessageValue<Data>): void | |
297 | ||
aee46736 JB |
298 | /** |
299 | * Worker message listener. | |
300 | * | |
6b813701 | 301 | * @param message - The received message. |
aee46736 | 302 | */ |
85aeb3f3 | 303 | protected messageListener (message: MessageValue<Data>): void { |
9e746eec | 304 | this.checkMessageWorkerId(message) |
310de0aa JB |
305 | if (message.statistics != null) { |
306 | // Statistics message received | |
307 | this.statistics = message.statistics | |
308 | } else if (message.checkActive != null) { | |
309 | // Check active message received | |
310 | message.checkActive ? this.startCheckActive() : this.stopCheckActive() | |
6703b9f4 JB |
311 | } else if (message.taskFunctionOperation != null) { |
312 | // Task function operation message received | |
313 | this.handleTaskFunctionOperationMessage(message) | |
310de0aa JB |
314 | } else if (message.taskId != null && message.data != null) { |
315 | // Task message received | |
316 | this.run(message) | |
317 | } else if (message.kill === true) { | |
318 | // Kill message received | |
319 | this.handleKillMessage(message) | |
cf597bc5 JB |
320 | } |
321 | } | |
322 | ||
6703b9f4 JB |
323 | protected handleTaskFunctionOperationMessage ( |
324 | message: MessageValue<Data> | |
325 | ): void { | |
9eae3c69 | 326 | const { taskFunctionOperation, taskFunctionName, taskFunction } = message |
4e38fd21 | 327 | let response!: TaskFunctionOperationResult |
d2dd5ef5 JB |
328 | switch (taskFunctionOperation) { |
329 | case 'add': | |
330 | response = this.addTaskFunction( | |
331 | taskFunctionName as string, | |
332 | // eslint-disable-next-line @typescript-eslint/no-implied-eval, no-new-func | |
333 | new Function(`return ${taskFunction as string}`)() as TaskFunction< | |
334 | Data, | |
335 | Response | |
336 | > | |
337 | ) | |
338 | break | |
339 | case 'remove': | |
340 | response = this.removeTaskFunction(taskFunctionName as string) | |
341 | break | |
342 | case 'default': | |
343 | response = this.setDefaultTaskFunction(taskFunctionName as string) | |
344 | break | |
345 | default: | |
346 | response = { status: false, error: new Error('Unknown task operation') } | |
347 | break | |
6703b9f4 JB |
348 | } |
349 | this.sendToMainWorker({ | |
350 | taskFunctionOperation, | |
351 | taskFunctionOperationStatus: response.status, | |
adee6053 JB |
352 | taskFunctionName, |
353 | ...(!response.status && | |
354 | response?.error != null && { | |
355 | workerError: { | |
356 | name: taskFunctionName as string, | |
357 | message: this.handleError(response.error as Error | string) | |
358 | } | |
359 | }) | |
6703b9f4 JB |
360 | }) |
361 | } | |
362 | ||
984dc9c8 JB |
363 | /** |
364 | * Handles a kill message sent by the main worker. | |
365 | * | |
366 | * @param message - The kill message. | |
367 | */ | |
97cf8c0d | 368 | protected handleKillMessage (_message: MessageValue<Data>): void { |
29d8b961 | 369 | this.stopCheckActive() |
07588f30 | 370 | if (isAsyncFunction(this.opts.killHandler)) { |
041dc05b | 371 | (this.opts.killHandler?.() as Promise<void>) |
1e3214b6 | 372 | .then(() => { |
895b5341 | 373 | this.sendToMainWorker({ kill: 'success' }) |
fefd3cef | 374 | return undefined |
1e3214b6 JB |
375 | }) |
376 | .catch(() => { | |
895b5341 | 377 | this.sendToMainWorker({ kill: 'failure' }) |
1e3214b6 | 378 | }) |
07588f30 | 379 | } else { |
1e3214b6 JB |
380 | try { |
381 | // eslint-disable-next-line @typescript-eslint/no-invalid-void-type | |
382 | this.opts.killHandler?.() as void | |
895b5341 | 383 | this.sendToMainWorker({ kill: 'success' }) |
7c8ac84e | 384 | } catch { |
895b5341 | 385 | this.sendToMainWorker({ kill: 'failure' }) |
1e3214b6 | 386 | } |
07588f30 | 387 | } |
984dc9c8 JB |
388 | } |
389 | ||
9e746eec JB |
390 | /** |
391 | * Check if the message worker id is set and matches the worker id. | |
392 | * | |
393 | * @param message - The message to check. | |
394 | * @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. | |
395 | */ | |
396 | private checkMessageWorkerId (message: MessageValue<Data>): void { | |
397 | if (message.workerId == null) { | |
398 | throw new Error('Message worker id is not set') | |
8e5a7cf9 | 399 | } else if (message.workerId !== this.id) { |
9e746eec JB |
400 | throw new Error( |
401 | `Message worker id ${message.workerId} does not match the worker id ${this.id}` | |
402 | ) | |
403 | } | |
404 | } | |
405 | ||
48487131 | 406 | /** |
b0a4db63 | 407 | * Starts the worker check active interval. |
48487131 | 408 | */ |
b0a4db63 | 409 | private startCheckActive (): void { |
75d3401a | 410 | this.lastTaskTimestamp = performance.now() |
b0a4db63 JB |
411 | this.activeInterval = setInterval( |
412 | this.checkActive.bind(this), | |
75d3401a | 413 | (this.opts.maxInactiveTime ?? DEFAULT_MAX_INACTIVE_TIME) / 2 |
984dc9c8 | 414 | ) |
75d3401a JB |
415 | } |
416 | ||
48487131 | 417 | /** |
b0a4db63 | 418 | * Stops the worker check active interval. |
48487131 | 419 | */ |
b0a4db63 | 420 | private stopCheckActive (): void { |
c3f498b5 JB |
421 | if (this.activeInterval != null) { |
422 | clearInterval(this.activeInterval) | |
423 | delete this.activeInterval | |
424 | } | |
48487131 JB |
425 | } |
426 | ||
427 | /** | |
428 | * Checks if the worker should be terminated, because its living too long. | |
429 | */ | |
b0a4db63 | 430 | private checkActive (): void { |
48487131 JB |
431 | if ( |
432 | performance.now() - this.lastTaskTimestamp > | |
433 | (this.opts.maxInactiveTime ?? DEFAULT_MAX_INACTIVE_TIME) | |
434 | ) { | |
895b5341 | 435 | this.sendToMainWorker({ kill: this.opts.killBehavior }) |
48487131 JB |
436 | } |
437 | } | |
438 | ||
729c563d S |
439 | /** |
440 | * Returns the main worker. | |
838898f1 S |
441 | * |
442 | * @returns Reference to the main worker. | |
155bb3de | 443 | * @throws {@link https://nodejs.org/api/errors.html#class-error} If the main worker is not set. |
729c563d | 444 | */ |
838898f1 | 445 | protected getMainWorker (): MainWorker { |
78cea37e | 446 | if (this.mainWorker == null) { |
e102732c | 447 | throw new Error('Main worker not set') |
838898f1 S |
448 | } |
449 | return this.mainWorker | |
450 | } | |
c97c7edb | 451 | |
729c563d | 452 | /** |
aa9eede8 | 453 | * Sends a message to main worker. |
729c563d | 454 | * |
38e795c1 | 455 | * @param message - The response message. |
729c563d | 456 | */ |
82f36766 JB |
457 | protected abstract sendToMainWorker ( |
458 | message: MessageValue<Response, Data> | |
459 | ): void | |
c97c7edb | 460 | |
90d7d101 | 461 | /** |
e81c38f2 | 462 | * Sends task function names to the main worker. |
90d7d101 | 463 | */ |
e81c38f2 | 464 | protected sendTaskFunctionNamesToMainWorker (): void { |
90d7d101 | 465 | this.sendToMainWorker({ |
895b5341 | 466 | taskFunctionNames: this.listTaskFunctionNames() |
90d7d101 JB |
467 | }) |
468 | } | |
469 | ||
729c563d | 470 | /** |
8accb8d5 | 471 | * Handles an error and convert it to a string so it can be sent back to the main worker. |
729c563d | 472 | * |
6703b9f4 | 473 | * @param error - The error raised by the worker. |
ab80dc46 | 474 | * @returns The error message. |
729c563d | 475 | */ |
6703b9f4 JB |
476 | protected handleError (error: Error | string): string { |
477 | return error instanceof Error ? error.message : error | |
c97c7edb S |
478 | } |
479 | ||
5c4d16da JB |
480 | /** |
481 | * Runs the given task. | |
482 | * | |
483 | * @param task - The task to execute. | |
5c4d16da | 484 | */ |
803f948f | 485 | protected readonly run = (task: Task<Data>): void => { |
9d2d0da1 | 486 | const { name, taskId, data } = task |
c878a240 JB |
487 | const taskFunctionName = name ?? DEFAULT_TASK_NAME |
488 | if (!this.taskFunctions.has(taskFunctionName)) { | |
9d2d0da1 | 489 | this.sendToMainWorker({ |
6703b9f4 | 490 | workerError: { |
9d2d0da1 JB |
491 | name: name as string, |
492 | message: `Task function '${name as string}' not found`, | |
493 | data | |
494 | }, | |
9d2d0da1 JB |
495 | taskId |
496 | }) | |
497 | return | |
498 | } | |
c878a240 | 499 | const fn = this.taskFunctions.get(taskFunctionName) |
5c4d16da | 500 | if (isAsyncFunction(fn)) { |
69b70a7e | 501 | this.runAsync(fn as TaskAsyncFunction<Data, Response>, task) |
5c4d16da | 502 | } else { |
69b70a7e | 503 | this.runSync(fn as TaskSyncFunction<Data, Response>, task) |
5c4d16da JB |
504 | } |
505 | } | |
506 | ||
729c563d | 507 | /** |
4dd93fcf | 508 | * Runs the given task function synchronously. |
729c563d | 509 | * |
5c4d16da JB |
510 | * @param fn - Task function that will be executed. |
511 | * @param task - Input data for the task function. | |
729c563d | 512 | */ |
803f948f | 513 | protected readonly runSync = ( |
82ea6492 | 514 | fn: TaskSyncFunction<Data, Response>, |
5c4d16da | 515 | task: Task<Data> |
803f948f | 516 | ): void => { |
310de0aa | 517 | const { name, taskId, data } = task |
c97c7edb | 518 | try { |
310de0aa JB |
519 | let taskPerformance = this.beginTaskPerformance(name) |
520 | const res = fn(data) | |
d715b7bc | 521 | taskPerformance = this.endTaskPerformance(taskPerformance) |
3fafb1b2 JB |
522 | this.sendToMainWorker({ |
523 | data: res, | |
d715b7bc | 524 | taskPerformance, |
310de0aa | 525 | taskId |
3fafb1b2 | 526 | }) |
6703b9f4 | 527 | } catch (error) { |
91ee39ed | 528 | this.sendToMainWorker({ |
6703b9f4 | 529 | workerError: { |
0628755c | 530 | name: name as string, |
6703b9f4 | 531 | message: this.handleError(error as Error | string), |
310de0aa | 532 | data |
82f36766 | 533 | }, |
310de0aa | 534 | taskId |
91ee39ed | 535 | }) |
6e9d10db | 536 | } finally { |
c3f498b5 | 537 | this.updateLastTaskTimestamp() |
c97c7edb S |
538 | } |
539 | } | |
540 | ||
729c563d | 541 | /** |
4dd93fcf | 542 | * Runs the given task function asynchronously. |
729c563d | 543 | * |
5c4d16da JB |
544 | * @param fn - Task function that will be executed. |
545 | * @param task - Input data for the task function. | |
729c563d | 546 | */ |
803f948f | 547 | protected readonly runAsync = ( |
82ea6492 | 548 | fn: TaskAsyncFunction<Data, Response>, |
5c4d16da | 549 | task: Task<Data> |
803f948f | 550 | ): void => { |
310de0aa JB |
551 | const { name, taskId, data } = task |
552 | let taskPerformance = this.beginTaskPerformance(name) | |
553 | fn(data) | |
041dc05b | 554 | .then(res => { |
d715b7bc | 555 | taskPerformance = this.endTaskPerformance(taskPerformance) |
3fafb1b2 JB |
556 | this.sendToMainWorker({ |
557 | data: res, | |
d715b7bc | 558 | taskPerformance, |
310de0aa | 559 | taskId |
3fafb1b2 | 560 | }) |
04714ef7 | 561 | return undefined |
c97c7edb | 562 | }) |
6703b9f4 | 563 | .catch(error => { |
91ee39ed | 564 | this.sendToMainWorker({ |
6703b9f4 | 565 | workerError: { |
0628755c | 566 | name: name as string, |
6703b9f4 | 567 | message: this.handleError(error as Error | string), |
310de0aa | 568 | data |
82f36766 | 569 | }, |
310de0aa | 570 | taskId |
91ee39ed | 571 | }) |
6e9d10db JB |
572 | }) |
573 | .finally(() => { | |
c3f498b5 | 574 | this.updateLastTaskTimestamp() |
c97c7edb | 575 | }) |
6e9d10db | 576 | .catch(EMPTY_FUNCTION) |
c97c7edb | 577 | } |
ec8fd331 | 578 | |
197b4aa5 | 579 | private beginTaskPerformance (name?: string): TaskPerformance { |
8a970421 | 580 | this.checkStatistics() |
62c15a68 | 581 | return { |
ff128cc9 | 582 | name: name ?? DEFAULT_TASK_NAME, |
1c6fe997 | 583 | timestamp: performance.now(), |
b6b32453 | 584 | ...(this.statistics.elu && { elu: performance.eventLoopUtilization() }) |
62c15a68 JB |
585 | } |
586 | } | |
587 | ||
d9d31201 JB |
588 | private endTaskPerformance ( |
589 | taskPerformance: TaskPerformance | |
590 | ): TaskPerformance { | |
8a970421 | 591 | this.checkStatistics() |
62c15a68 JB |
592 | return { |
593 | ...taskPerformance, | |
b6b32453 JB |
594 | ...(this.statistics.runTime && { |
595 | runTime: performance.now() - taskPerformance.timestamp | |
596 | }), | |
597 | ...(this.statistics.elu && { | |
62c15a68 | 598 | elu: performance.eventLoopUtilization(taskPerformance.elu) |
b6b32453 | 599 | }) |
62c15a68 JB |
600 | } |
601 | } | |
8a970421 JB |
602 | |
603 | private checkStatistics (): void { | |
604 | if (this.statistics == null) { | |
605 | throw new Error('Performance statistics computation requirements not set') | |
606 | } | |
607 | } | |
c3f498b5 JB |
608 | |
609 | private updateLastTaskTimestamp (): void { | |
29d8b961 | 610 | if (this.activeInterval != null) { |
c3f498b5 JB |
611 | this.lastTaskTimestamp = performance.now() |
612 | } | |
613 | } | |
c97c7edb | 614 | } |