build: fix eslint configuration with type checking
[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, {
3a502712 358 // eslint-disable-next-line no-new-func
31847469
JB
359 taskFunction: new Function(
360 `return ${taskFunction}`
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
JB
379 }
380 this.sendToMainWorker({
381 taskFunctionOperation,
382 taskFunctionOperationStatus: response.status,
31847469 383 taskFunctionProperties,
adee6053 384 ...(!response.status &&
c63a35a0 385 response.error != null && {
adee6053 386 workerError: {
31847469 387 name: taskFunctionProperties.name,
3a502712
JB
388 message: this.handleError(response.error as Error | string),
389 },
390 }),
6703b9f4
JB
391 })
392 }
393
984dc9c8
JB
394 /**
395 * Handles a kill message sent by the main worker.
984dc9c8
JB
396 * @param message - The kill message.
397 */
3a502712 398 protected handleKillMessage (message: MessageValue<Data>): void {
29d8b961 399 this.stopCheckActive()
07588f30 400 if (isAsyncFunction(this.opts.killHandler)) {
3a502712 401 ;(this.opts.killHandler() as Promise<void>)
1e3214b6 402 .then(() => {
895b5341 403 this.sendToMainWorker({ kill: 'success' })
fefd3cef 404 return undefined
1e3214b6
JB
405 })
406 .catch(() => {
895b5341 407 this.sendToMainWorker({ kill: 'failure' })
1e3214b6 408 })
07588f30 409 } else {
1e3214b6 410 try {
3a502712 411 this.opts.killHandler?.()
895b5341 412 this.sendToMainWorker({ kill: 'success' })
7c8ac84e 413 } catch {
895b5341 414 this.sendToMainWorker({ kill: 'failure' })
1e3214b6 415 }
07588f30 416 }
984dc9c8
JB
417 }
418
9e746eec
JB
419 /**
420 * Check if the message worker id is set and matches the worker id.
9e746eec
JB
421 * @param message - The message to check.
422 * @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.
423 */
424 private checkMessageWorkerId (message: MessageValue<Data>): void {
425 if (message.workerId == null) {
426 throw new Error('Message worker id is not set')
8e5a7cf9 427 } else if (message.workerId !== this.id) {
9e746eec
JB
428 throw new Error(
429 `Message worker id ${message.workerId} does not match the worker id ${this.id}`
430 )
431 }
432 }
433
48487131 434 /**
b0a4db63 435 * Starts the worker check active interval.
48487131 436 */
b0a4db63 437 private startCheckActive (): void {
75d3401a 438 this.lastTaskTimestamp = performance.now()
b0a4db63
JB
439 this.activeInterval = setInterval(
440 this.checkActive.bind(this),
75d3401a 441 (this.opts.maxInactiveTime ?? DEFAULT_MAX_INACTIVE_TIME) / 2
984dc9c8 442 )
75d3401a
JB
443 }
444
48487131 445 /**
b0a4db63 446 * Stops the worker check active interval.
48487131 447 */
b0a4db63 448 private stopCheckActive (): void {
c3f498b5
JB
449 if (this.activeInterval != null) {
450 clearInterval(this.activeInterval)
451 delete this.activeInterval
452 }
48487131
JB
453 }
454
455 /**
456 * Checks if the worker should be terminated, because its living too long.
457 */
b0a4db63 458 private checkActive (): void {
48487131
JB
459 if (
460 performance.now() - this.lastTaskTimestamp >
461 (this.opts.maxInactiveTime ?? DEFAULT_MAX_INACTIVE_TIME)
462 ) {
895b5341 463 this.sendToMainWorker({ kill: this.opts.killBehavior })
48487131
JB
464 }
465 }
466
729c563d
S
467 /**
468 * Returns the main worker.
838898f1 469 * @returns Reference to the main worker.
155bb3de 470 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the main worker is not set.
729c563d 471 */
838898f1 472 protected getMainWorker (): MainWorker {
78cea37e 473 if (this.mainWorker == null) {
e102732c 474 throw new Error('Main worker not set')
838898f1
S
475 }
476 return this.mainWorker
477 }
c97c7edb 478
729c563d 479 /**
aa9eede8 480 * Sends a message to main worker.
38e795c1 481 * @param message - The response message.
729c563d 482 */
82f36766
JB
483 protected abstract sendToMainWorker (
484 message: MessageValue<Response, Data>
485 ): void
c97c7edb 486
90d7d101 487 /**
31847469 488 * Sends task functions properties to the main worker.
90d7d101 489 */
31847469 490 protected sendTaskFunctionsPropertiesToMainWorker (): void {
90d7d101 491 this.sendToMainWorker({
3a502712 492 taskFunctionsProperties: this.listTaskFunctionsProperties(),
90d7d101
JB
493 })
494 }
495
729c563d 496 /**
8accb8d5 497 * Handles an error and convert it to a string so it can be sent back to the main worker.
6703b9f4 498 * @param error - The error raised by the worker.
ab80dc46 499 * @returns The error message.
729c563d 500 */
6703b9f4
JB
501 protected handleError (error: Error | string): string {
502 return error instanceof Error ? error.message : error
c97c7edb
S
503 }
504
5c4d16da
JB
505 /**
506 * Runs the given task.
5c4d16da 507 * @param task - The task to execute.
5c4d16da 508 */
803f948f 509 protected readonly run = (task: Task<Data>): void => {
9d2d0da1 510 const { name, taskId, data } = task
c878a240
JB
511 const taskFunctionName = name ?? DEFAULT_TASK_NAME
512 if (!this.taskFunctions.has(taskFunctionName)) {
9d2d0da1 513 this.sendToMainWorker({
6703b9f4 514 workerError: {
67f3f2d6
JB
515 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
516 name: name!,
c63a35a0 517 message: `Task function '${name}' not found`,
3a502712 518 data,
9d2d0da1 519 },
3a502712 520 taskId,
9d2d0da1
JB
521 })
522 return
523 }
31847469 524 const fn = this.taskFunctions.get(taskFunctionName)?.taskFunction
5c4d16da 525 if (isAsyncFunction(fn)) {
69b70a7e 526 this.runAsync(fn as TaskAsyncFunction<Data, Response>, task)
5c4d16da 527 } else {
69b70a7e 528 this.runSync(fn as TaskSyncFunction<Data, Response>, task)
5c4d16da
JB
529 }
530 }
531
729c563d 532 /**
4dd93fcf 533 * Runs the given task function synchronously.
5c4d16da
JB
534 * @param fn - Task function that will be executed.
535 * @param task - Input data for the task function.
729c563d 536 */
803f948f 537 protected readonly runSync = (
82ea6492 538 fn: TaskSyncFunction<Data, Response>,
5c4d16da 539 task: Task<Data>
803f948f 540 ): void => {
310de0aa 541 const { name, taskId, data } = task
c97c7edb 542 try {
310de0aa
JB
543 let taskPerformance = this.beginTaskPerformance(name)
544 const res = fn(data)
d715b7bc 545 taskPerformance = this.endTaskPerformance(taskPerformance)
3fafb1b2
JB
546 this.sendToMainWorker({
547 data: res,
d715b7bc 548 taskPerformance,
3a502712 549 taskId,
3fafb1b2 550 })
6703b9f4 551 } catch (error) {
91ee39ed 552 this.sendToMainWorker({
6703b9f4 553 workerError: {
67f3f2d6
JB
554 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
555 name: name!,
6703b9f4 556 message: this.handleError(error as Error | string),
3a502712 557 data,
82f36766 558 },
3a502712 559 taskId,
91ee39ed 560 })
6e9d10db 561 } finally {
c3f498b5 562 this.updateLastTaskTimestamp()
c97c7edb
S
563 }
564 }
565
729c563d 566 /**
4dd93fcf 567 * Runs the given task function asynchronously.
5c4d16da
JB
568 * @param fn - Task function that will be executed.
569 * @param task - Input data for the task function.
729c563d 570 */
803f948f 571 protected readonly runAsync = (
82ea6492 572 fn: TaskAsyncFunction<Data, Response>,
5c4d16da 573 task: Task<Data>
803f948f 574 ): void => {
310de0aa
JB
575 const { name, taskId, data } = task
576 let taskPerformance = this.beginTaskPerformance(name)
577 fn(data)
041dc05b 578 .then(res => {
d715b7bc 579 taskPerformance = this.endTaskPerformance(taskPerformance)
3fafb1b2
JB
580 this.sendToMainWorker({
581 data: res,
d715b7bc 582 taskPerformance,
3a502712 583 taskId,
3fafb1b2 584 })
04714ef7 585 return undefined
c97c7edb 586 })
07f6f7b1 587 .catch((error: unknown) => {
91ee39ed 588 this.sendToMainWorker({
6703b9f4 589 workerError: {
67f3f2d6
JB
590 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
591 name: name!,
6703b9f4 592 message: this.handleError(error as Error | string),
3a502712 593 data,
82f36766 594 },
3a502712 595 taskId,
91ee39ed 596 })
6e9d10db
JB
597 })
598 .finally(() => {
c3f498b5 599 this.updateLastTaskTimestamp()
c97c7edb 600 })
6e9d10db 601 .catch(EMPTY_FUNCTION)
c97c7edb 602 }
ec8fd331 603
197b4aa5 604 private beginTaskPerformance (name?: string): TaskPerformance {
c63a35a0
JB
605 if (this.statistics == null) {
606 throw new Error('Performance statistics computation requirements not set')
607 }
62c15a68 608 return {
ff128cc9 609 name: name ?? DEFAULT_TASK_NAME,
1c6fe997 610 timestamp: performance.now(),
c63a35a0 611 ...(this.statistics.elu && {
3a502712
JB
612 elu: performance.eventLoopUtilization(),
613 }),
62c15a68
JB
614 }
615 }
616
d9d31201
JB
617 private endTaskPerformance (
618 taskPerformance: TaskPerformance
619 ): TaskPerformance {
c63a35a0
JB
620 if (this.statistics == null) {
621 throw new Error('Performance statistics computation requirements not set')
622 }
62c15a68
JB
623 return {
624 ...taskPerformance,
b6b32453 625 ...(this.statistics.runTime && {
3a502712 626 runTime: performance.now() - taskPerformance.timestamp,
b6b32453
JB
627 }),
628 ...(this.statistics.elu && {
3a502712
JB
629 elu: performance.eventLoopUtilization(taskPerformance.elu),
630 }),
62c15a68
JB
631 }
632 }
8a970421 633
c3f498b5 634 private updateLastTaskTimestamp (): void {
29d8b961 635 if (this.activeInterval != null) {
c3f498b5
JB
636 this.lastTaskTimestamp = performance.now()
637 }
638 }
c97c7edb 639}