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