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 */
b0a4db63 81 protected activeInterval?: NodeJS.Timeout
49890030 82
c97c7edb 83 /**
729c563d 84 * Constructs a new poolifier worker.
38e795c1 85 * @param isMain - Whether this is the main worker or not.
38e795c1 86 * @param mainWorker - Reference to main worker.
85aeb3f3 87 * @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 88 * @param opts - Options for the worker.
c97c7edb
S
89 */
90 public constructor (
c63a35a0
JB
91 protected readonly isMain: boolean | undefined,
92 private readonly mainWorker: MainWorker | undefined | null,
82ea6492 93 taskFunctions: TaskFunction<Data, Response> | TaskFunctions<Data, Response>,
d38d0e30 94 protected opts: WorkerOptions = DEFAULT_WORKER_OPTIONS
c97c7edb 95 ) {
9d2d0da1
JB
96 if (this.isMain == null) {
97 throw new Error('isMain parameter is mandatory')
98 }
a86b6df1 99 this.checkTaskFunctions(taskFunctions)
9d2d0da1 100 this.checkWorkerOptions(this.opts)
1f68cede 101 if (!this.isMain) {
0cb6edc2 102 // Should be once() but Node.js on windows has a bug that prevents it from working
e2898b4f 103 this.getMainWorker().on('message', this.handleReadyMessage.bind(this))
c97c7edb
S
104 }
105 }
106
41aa7dcd 107 private checkWorkerOptions (opts: WorkerOptions): void {
9a38f99e 108 checkValidWorkerOptions(opts)
d38d0e30 109 this.opts = { ...DEFAULT_WORKER_OPTIONS, ...opts }
41aa7dcd
JB
110 }
111
112 /**
c20084b6 113 * Checks if the `taskFunctions` parameter is passed to the constructor and valid.
82888165 114 * @param taskFunctions - The task function(s) parameter that should be checked.
41aa7dcd 115 */
a86b6df1 116 private checkTaskFunctions (
c63a35a0 117 taskFunctions:
3a502712
JB
118 | TaskFunction<Data, Response>
119 | TaskFunctions<Data, Response>
120 | undefined
a86b6df1 121 ): void {
ec8fd331
JB
122 if (taskFunctions == null) {
123 throw new Error('taskFunctions parameter is mandatory')
124 }
31847469 125 this.taskFunctions = new Map<string, TaskFunctionObject<Data, Response>>()
0d80593b 126 if (typeof taskFunctions === 'function') {
31847469
JB
127 const fnObj = { taskFunction: taskFunctions.bind(this) }
128 this.taskFunctions.set(DEFAULT_TASK_NAME, fnObj)
2a69b8c5
JB
129 this.taskFunctions.set(
130 typeof taskFunctions.name === 'string' &&
efebef40 131 taskFunctions.name.trim().length > 0
2a69b8c5
JB
132 ? taskFunctions.name
133 : 'fn1',
31847469 134 fnObj
2a69b8c5 135 )
0d80593b 136 } else if (isPlainObject(taskFunctions)) {
82888165 137 let firstEntry = true
31847469
JB
138 for (let [name, fnObj] of Object.entries(taskFunctions)) {
139 if (typeof fnObj === 'function') {
140 fnObj = { taskFunction: fnObj } satisfies TaskFunctionObject<
3a502712
JB
141 Data,
142 Response
31847469
JB
143 >
144 }
bcfb06ce 145 checkValidTaskFunctionObjectEntry<Data, Response>(name, fnObj)
31847469 146 fnObj.taskFunction = fnObj.taskFunction.bind(this)
82888165 147 if (firstEntry) {
31847469 148 this.taskFunctions.set(DEFAULT_TASK_NAME, fnObj)
82888165
JB
149 firstEntry = false
150 }
31847469 151 this.taskFunctions.set(name, fnObj)
a86b6df1 152 }
630f0acf
JB
153 if (firstEntry) {
154 throw new Error('taskFunctions parameter object is empty')
155 }
a86b6df1 156 } else {
f34fdabe
JB
157 throw new TypeError(
158 'taskFunctions parameter is not a function or a plain object'
159 )
41aa7dcd
JB
160 }
161 }
162
968a2e8c
JB
163 /**
164 * Checks if the worker has a task function with the given name.
968a2e8c
JB
165 * @param name - The name of the task function to check.
166 * @returns Whether the worker has a task function with the given name or not.
968a2e8c 167 */
4e38fd21 168 public hasTaskFunction (name: string): TaskFunctionOperationResult {
6703b9f4 169 try {
9a38f99e 170 checkTaskFunctionName(name)
6703b9f4
JB
171 } catch (error) {
172 return { status: false, error: error as Error }
173 }
174 return { status: this.taskFunctions.has(name) }
968a2e8c
JB
175 }
176
177 /**
178 * Adds a task function to the worker.
179 * If a task function with the same name already exists, it is replaced.
968a2e8c
JB
180 * @param name - The name of the task function to add.
181 * @param fn - The task function to add.
182 * @returns Whether the task function was added or not.
968a2e8c
JB
183 */
184 public addTaskFunction (
185 name: string,
31847469 186 fn: TaskFunction<Data, Response> | TaskFunctionObject<Data, Response>
4e38fd21 187 ): TaskFunctionOperationResult {
968a2e8c 188 try {
9a38f99e 189 checkTaskFunctionName(name)
6703b9f4
JB
190 if (name === DEFAULT_TASK_NAME) {
191 throw new Error(
192 'Cannot add a task function with the default reserved name'
193 )
194 }
31847469
JB
195 if (typeof fn === 'function') {
196 fn = { taskFunction: fn } satisfies TaskFunctionObject<Data, Response>
6703b9f4 197 }
bcfb06ce 198 checkValidTaskFunctionObjectEntry<Data, Response>(name, fn)
31847469 199 fn.taskFunction = fn.taskFunction.bind(this)
968a2e8c
JB
200 if (
201 this.taskFunctions.get(name) ===
202 this.taskFunctions.get(DEFAULT_TASK_NAME)
203 ) {
31847469 204 this.taskFunctions.set(DEFAULT_TASK_NAME, fn)
968a2e8c 205 }
31847469
JB
206 this.taskFunctions.set(name, fn)
207 this.sendTaskFunctionsPropertiesToMainWorker()
6703b9f4
JB
208 return { status: true }
209 } catch (error) {
210 return { status: false, error: error as Error }
968a2e8c
JB
211 }
212 }
213
214 /**
215 * Removes a task function from the worker.
968a2e8c
JB
216 * @param name - The name of the task function to remove.
217 * @returns Whether the task function existed and was removed or not.
968a2e8c 218 */
4e38fd21 219 public removeTaskFunction (name: string): TaskFunctionOperationResult {
6703b9f4 220 try {
9a38f99e 221 checkTaskFunctionName(name)
6703b9f4
JB
222 if (name === DEFAULT_TASK_NAME) {
223 throw new Error(
224 'Cannot remove the task function with the default reserved name'
225 )
226 }
227 if (
228 this.taskFunctions.get(name) ===
229 this.taskFunctions.get(DEFAULT_TASK_NAME)
230 ) {
231 throw new Error(
232 'Cannot remove the task function used as the default task function'
233 )
234 }
235 const deleteStatus = this.taskFunctions.delete(name)
31847469 236 this.sendTaskFunctionsPropertiesToMainWorker()
6703b9f4
JB
237 return { status: deleteStatus }
238 } catch (error) {
239 return { status: false, error: error as Error }
968a2e8c 240 }
968a2e8c
JB
241 }
242
243 /**
31847469 244 * Lists the properties of the worker's task functions.
31847469 245 * @returns The properties of the worker's task functions.
c50b93fb 246 */
31847469 247 public listTaskFunctionsProperties (): TaskFunctionProperties[] {
d8a4de75 248 let defaultTaskFunctionName = DEFAULT_TASK_NAME
31847469 249 for (const [name, fnObj] of this.taskFunctions) {
b558f6b5
JB
250 if (
251 name !== DEFAULT_TASK_NAME &&
31847469 252 fnObj === this.taskFunctions.get(DEFAULT_TASK_NAME)
b558f6b5
JB
253 ) {
254 defaultTaskFunctionName = name
255 break
256 }
257 }
31847469
JB
258 const taskFunctionsProperties: TaskFunctionProperties[] = []
259 for (const [name, fnObj] of this.taskFunctions) {
260 if (name === DEFAULT_TASK_NAME || name === defaultTaskFunctionName) {
261 continue
262 }
263 taskFunctionsProperties.push(buildTaskFunctionProperties(name, fnObj))
264 }
b558f6b5 265 return [
31847469
JB
266 buildTaskFunctionProperties(
267 DEFAULT_TASK_NAME,
268 this.taskFunctions.get(DEFAULT_TASK_NAME)
269 ),
270 buildTaskFunctionProperties(
271 defaultTaskFunctionName,
272 this.taskFunctions.get(defaultTaskFunctionName)
273 ),
3a502712 274 ...taskFunctionsProperties,
b558f6b5 275 ]
c50b93fb
JB
276 }
277
278 /**
279 * Sets the default task function to use in the worker.
968a2e8c
JB
280 * @param name - The name of the task function to use as default task function.
281 * @returns Whether the default task function was set or not.
968a2e8c 282 */
4e38fd21 283 public setDefaultTaskFunction (name: string): TaskFunctionOperationResult {
968a2e8c 284 try {
9a38f99e 285 checkTaskFunctionName(name)
6703b9f4
JB
286 if (name === DEFAULT_TASK_NAME) {
287 throw new Error(
288 'Cannot set the default task function reserved name as the default task function'
289 )
290 }
291 if (!this.taskFunctions.has(name)) {
292 throw new Error(
293 'Cannot set the default task function to a non-existing task function'
294 )
295 }
67f3f2d6
JB
296 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
297 this.taskFunctions.set(DEFAULT_TASK_NAME, this.taskFunctions.get(name)!)
31847469 298 this.sendTaskFunctionsPropertiesToMainWorker()
6703b9f4
JB
299 return { status: true }
300 } catch (error) {
301 return { status: false, error: error as Error }
968a2e8c
JB
302 }
303 }
304
a038b517
JB
305 /**
306 * Handles the ready message sent by the main worker.
a038b517
JB
307 * @param message - The ready message.
308 */
309 protected abstract handleReadyMessage (message: MessageValue<Data>): void
310
aee46736
JB
311 /**
312 * Worker message listener.
6b813701 313 * @param message - The received message.
aee46736 314 */
85aeb3f3 315 protected messageListener (message: MessageValue<Data>): void {
9e746eec 316 this.checkMessageWorkerId(message)
43805f1d
JB
317 const {
318 statistics,
319 checkActive,
320 taskFunctionOperation,
321 taskId,
322 data,
3a502712 323 kill,
43805f1d
JB
324 } = message
325 if (statistics != null) {
310de0aa 326 // Statistics message received
43805f1d
JB
327 this.statistics = statistics
328 } else if (checkActive != null) {
310de0aa 329 // Check active message received
43805f1d
JB
330 checkActive ? this.startCheckActive() : this.stopCheckActive()
331 } else if (taskFunctionOperation != null) {
6703b9f4
JB
332 // Task function operation message received
333 this.handleTaskFunctionOperationMessage(message)
43805f1d 334 } else if (taskId != null && data != null) {
310de0aa
JB
335 // Task message received
336 this.run(message)
43805f1d 337 } else if (kill === true) {
310de0aa
JB
338 // Kill message received
339 this.handleKillMessage(message)
cf597bc5
JB
340 }
341 }
342
6703b9f4
JB
343 protected handleTaskFunctionOperationMessage (
344 message: MessageValue<Data>
345 ): void {
31847469
JB
346 const { taskFunctionOperation, taskFunctionProperties, taskFunction } =
347 message
348 if (taskFunctionProperties == null) {
7f0e1334 349 throw new Error(
31847469 350 'Cannot handle task function operation message without task function properties'
7f0e1334
JB
351 )
352 }
353 let response: TaskFunctionOperationResult
d2dd5ef5
JB
354 switch (taskFunctionOperation) {
355 case 'add':
31847469 356 response = this.addTaskFunction(taskFunctionProperties.name, {
6e5d7052 357 // eslint-disable-next-line @typescript-eslint/no-implied-eval, no-new-func
31847469 358 taskFunction: new Function(
6e5d7052
JB
359 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
360 `return ${taskFunction!}`
31847469
JB
361 )() as TaskFunction<Data, Response>,
362 ...(taskFunctionProperties.priority != null && {
3a502712 363 priority: taskFunctionProperties.priority,
31847469
JB
364 }),
365 ...(taskFunctionProperties.strategy != null && {
3a502712
JB
366 strategy: taskFunctionProperties.strategy,
367 }),
31847469 368 })
d2dd5ef5
JB
369 break
370 case 'remove':
31847469 371 response = this.removeTaskFunction(taskFunctionProperties.name)
d2dd5ef5
JB
372 break
373 case 'default':
31847469 374 response = this.setDefaultTaskFunction(taskFunctionProperties.name)
d2dd5ef5
JB
375 break
376 default:
377 response = { status: false, error: new Error('Unknown task operation') }
378 break
6703b9f4 379 }
4a537a1a 380 const { status, error } = response
6703b9f4
JB
381 this.sendToMainWorker({
382 taskFunctionOperation,
4a537a1a 383 taskFunctionOperationStatus: status,
31847469 384 taskFunctionProperties,
4a537a1a
JB
385 ...(!status &&
386 error != null && {
adee6053 387 workerError: {
31847469 388 name: taskFunctionProperties.name,
4a537a1a 389 message: this.handleError(error as Error | string),
3a502712
JB
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}