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