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