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