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