Merge pull request #1129 from poolifier/chore/use-biome
[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 if (this.isMain == null) {
92 throw new Error('isMain parameter is mandatory')
93 }
94 this.checkTaskFunctions(taskFunctions)
95 this.checkWorkerOptions(this.opts)
96 if (!this.isMain) {
97 this.getMainWorker().on('message', this.handleReadyMessage.bind(this))
98 }
99 }
100
101 private checkWorkerOptions (opts: WorkerOptions): void {
102 this.opts = { ...DEFAULT_WORKER_OPTIONS, ...opts }
103 delete this.opts.async
104 }
105
106 private checkValidTaskFunction (
107 name: string,
108 fn: TaskFunction<Data, Response>
109 ): void {
110 if (typeof name !== 'string') {
111 throw new TypeError(
112 'A taskFunctions parameter object key is not a string'
113 )
114 }
115 if (typeof name === 'string' && name.trim().length === 0) {
116 throw new TypeError(
117 'A taskFunctions parameter object key is an empty string'
118 )
119 }
120 if (typeof fn !== 'function') {
121 throw new TypeError(
122 'A taskFunctions parameter object value is not a function'
123 )
124 }
125 }
126
127 /**
128 * Checks if the `taskFunctions` parameter is passed to the constructor.
129 *
130 * @param taskFunctions - The task function(s) parameter that should be checked.
131 */
132 private checkTaskFunctions (
133 taskFunctions: TaskFunction<Data, Response> | TaskFunctions<Data, Response>
134 ): void {
135 if (taskFunctions == null) {
136 throw new Error('taskFunctions parameter is mandatory')
137 }
138 this.taskFunctions = new Map<string, TaskFunction<Data, Response>>()
139 if (typeof taskFunctions === 'function') {
140 const boundFn = taskFunctions.bind(this)
141 this.taskFunctions.set(DEFAULT_TASK_NAME, boundFn)
142 this.taskFunctions.set(
143 typeof taskFunctions.name === 'string' &&
144 taskFunctions.name.trim().length > 0
145 ? taskFunctions.name
146 : 'fn1',
147 boundFn
148 )
149 } else if (isPlainObject(taskFunctions)) {
150 let firstEntry = true
151 for (const [name, fn] of Object.entries(taskFunctions)) {
152 this.checkValidTaskFunction(name, fn)
153 const boundFn = fn.bind(this)
154 if (firstEntry) {
155 this.taskFunctions.set(DEFAULT_TASK_NAME, boundFn)
156 firstEntry = false
157 }
158 this.taskFunctions.set(name, boundFn)
159 }
160 if (firstEntry) {
161 throw new Error('taskFunctions parameter object is empty')
162 }
163 } else {
164 throw new TypeError(
165 'taskFunctions parameter is not a function or a plain object'
166 )
167 }
168 }
169
170 /**
171 * Checks if the worker has a task function with the given name.
172 *
173 * @param name - The name of the task function to check.
174 * @returns Whether the worker has a task function with the given name or not.
175 * @throws {@link https://nodejs.org/api/errors.html#class-typeerror} If the `name` parameter is not a string or an empty string.
176 */
177 public hasTaskFunction (name: string): boolean {
178 this.checkTaskFunctionName(name)
179 return this.taskFunctions.has(name)
180 }
181
182 /**
183 * Adds a task function to the worker.
184 * If a task function with the same name already exists, it is replaced.
185 *
186 * @param name - The name of the task function to add.
187 * @param fn - The task function to add.
188 * @returns Whether the task function was added or not.
189 * @throws {@link https://nodejs.org/api/errors.html#class-typeerror} If the `name` parameter is not a string or an empty string.
190 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the `name` parameter is the default task function reserved name.
191 * @throws {@link https://nodejs.org/api/errors.html#class-typeerror} If the `fn` parameter is not a function.
192 */
193 public addTaskFunction (
194 name: string,
195 fn: TaskFunction<Data, Response>
196 ): boolean {
197 this.checkTaskFunctionName(name)
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 this.checkTaskFunctionName(name)
233 if (name === DEFAULT_TASK_NAME) {
234 throw new Error(
235 'Cannot remove the task function with the default reserved name'
236 )
237 }
238 if (
239 this.taskFunctions.get(name) === this.taskFunctions.get(DEFAULT_TASK_NAME)
240 ) {
241 throw new Error(
242 'Cannot remove the task function used as the default task function'
243 )
244 }
245 const deleteStatus = this.taskFunctions.delete(name)
246 this.sendTaskFunctionsListToMainWorker()
247 return deleteStatus
248 }
249
250 /**
251 * Lists the names of the worker's task functions.
252 *
253 * @returns The names of the worker's task functions.
254 */
255 public listTaskFunctions (): string[] {
256 const names: string[] = [...this.taskFunctions.keys()]
257 let defaultTaskFunctionName: string = DEFAULT_TASK_NAME
258 for (const [name, fn] of this.taskFunctions) {
259 if (
260 name !== DEFAULT_TASK_NAME &&
261 fn === this.taskFunctions.get(DEFAULT_TASK_NAME)
262 ) {
263 defaultTaskFunctionName = name
264 break
265 }
266 }
267 return [
268 names[names.indexOf(DEFAULT_TASK_NAME)],
269 defaultTaskFunctionName,
270 ...names.filter(
271 name => name !== DEFAULT_TASK_NAME && name !== defaultTaskFunctionName
272 )
273 ]
274 }
275
276 /**
277 * Sets the default task function to use in the worker.
278 *
279 * @param name - The name of the task function to use as default task function.
280 * @returns Whether the default task function was set or not.
281 * @throws {@link https://nodejs.org/api/errors.html#class-typeerror} If the `name` parameter is not a string or an empty string.
282 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the `name` parameter is the default task function reserved name.
283 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the `name` parameter is a non-existing task function.
284 */
285 public setDefaultTaskFunction (name: string): boolean {
286 this.checkTaskFunctionName(name)
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 }
297 try {
298 this.taskFunctions.set(
299 DEFAULT_TASK_NAME,
300 this.taskFunctions.get(name) as TaskFunction<Data, Response>
301 )
302 return true
303 } catch {
304 return false
305 }
306 }
307
308 private checkTaskFunctionName (name: string): void {
309 if (typeof name !== 'string') {
310 throw new TypeError('name parameter is not a string')
311 }
312 if (typeof name === 'string' && name.trim().length === 0) {
313 throw new TypeError('name parameter is an empty string')
314 }
315 }
316
317 /**
318 * Handles the ready message sent by the main worker.
319 *
320 * @param message - The ready message.
321 */
322 protected abstract handleReadyMessage (message: MessageValue<Data>): void
323
324 /**
325 * Worker message listener.
326 *
327 * @param message - The received message.
328 */
329 protected messageListener (message: MessageValue<Data>): void {
330 this.checkMessageWorkerId(message)
331 if (message.statistics != null) {
332 // Statistics message received
333 this.statistics = message.statistics
334 } else if (message.checkActive != null) {
335 // Check active message received
336 message.checkActive ? this.startCheckActive() : this.stopCheckActive()
337 } else if (message.taskId != null && message.data != null) {
338 // Task message received
339 this.run(message)
340 } else if (message.kill === true) {
341 // Kill message received
342 this.handleKillMessage(message)
343 }
344 }
345
346 /**
347 * Handles a kill message sent by the main worker.
348 *
349 * @param message - The kill message.
350 */
351 protected handleKillMessage (message: MessageValue<Data>): void {
352 this.stopCheckActive()
353 if (isAsyncFunction(this.opts.killHandler)) {
354 (this.opts.killHandler?.() as Promise<void>)
355 .then(() => {
356 this.sendToMainWorker({ kill: 'success', workerId: this.id })
357 return null
358 })
359 .catch(() => {
360 this.sendToMainWorker({ kill: 'failure', workerId: this.id })
361 })
362 .finally(() => {
363 this.emitDestroy()
364 })
365 .catch(EMPTY_FUNCTION)
366 } else {
367 try {
368 // eslint-disable-next-line @typescript-eslint/no-invalid-void-type
369 this.opts.killHandler?.() as void
370 this.sendToMainWorker({ kill: 'success', workerId: this.id })
371 } catch {
372 this.sendToMainWorker({ kill: 'failure', workerId: this.id })
373 } finally {
374 this.emitDestroy()
375 }
376 }
377 }
378
379 /**
380 * Check if the message worker id is set and matches the worker id.
381 *
382 * @param message - The message to check.
383 * @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.
384 */
385 private checkMessageWorkerId (message: MessageValue<Data>): void {
386 if (message.workerId == null) {
387 throw new Error('Message worker id is not set')
388 } else if (message.workerId != null && message.workerId !== this.id) {
389 throw new Error(
390 `Message worker id ${message.workerId} does not match the worker id ${this.id}`
391 )
392 }
393 }
394
395 /**
396 * Starts the worker check active interval.
397 */
398 private startCheckActive (): void {
399 this.lastTaskTimestamp = performance.now()
400 this.activeInterval = setInterval(
401 this.checkActive.bind(this),
402 (this.opts.maxInactiveTime ?? DEFAULT_MAX_INACTIVE_TIME) / 2
403 )
404 }
405
406 /**
407 * Stops the worker check active interval.
408 */
409 private stopCheckActive (): void {
410 if (this.activeInterval != null) {
411 clearInterval(this.activeInterval)
412 delete this.activeInterval
413 }
414 }
415
416 /**
417 * Checks if the worker should be terminated, because its living too long.
418 */
419 private checkActive (): void {
420 if (
421 performance.now() - this.lastTaskTimestamp >
422 (this.opts.maxInactiveTime ?? DEFAULT_MAX_INACTIVE_TIME)
423 ) {
424 this.sendToMainWorker({ kill: this.opts.killBehavior, workerId: this.id })
425 }
426 }
427
428 /**
429 * Returns the main worker.
430 *
431 * @returns Reference to the main worker.
432 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the main worker is not set.
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 { name, taskId, data } = task
478 const fn = this.taskFunctions.get(name ?? DEFAULT_TASK_NAME)
479 if (fn == null) {
480 this.sendToMainWorker({
481 taskError: {
482 name: name as string,
483 message: `Task function '${name as string}' not found`,
484 data
485 },
486 workerId: this.id,
487 taskId
488 })
489 return
490 }
491 if (isAsyncFunction(fn)) {
492 this.runInAsyncScope(this.runAsync.bind(this), this, fn, task)
493 } else {
494 this.runInAsyncScope(this.runSync.bind(this), this, fn, task)
495 }
496 }
497
498 /**
499 * Runs the given task function synchronously.
500 *
501 * @param fn - Task function that will be executed.
502 * @param task - Input data for the task function.
503 */
504 protected runSync (
505 fn: TaskSyncFunction<Data, Response>,
506 task: Task<Data>
507 ): void {
508 const { name, taskId, data } = task
509 try {
510 let taskPerformance = this.beginTaskPerformance(name)
511 const res = fn(data)
512 taskPerformance = this.endTaskPerformance(taskPerformance)
513 this.sendToMainWorker({
514 data: res,
515 taskPerformance,
516 workerId: this.id,
517 taskId
518 })
519 } catch (e) {
520 const errorMessage = this.handleError(e as Error | string)
521 this.sendToMainWorker({
522 taskError: {
523 name: name as string,
524 message: errorMessage,
525 data
526 },
527 workerId: this.id,
528 taskId
529 })
530 } finally {
531 this.updateLastTaskTimestamp()
532 }
533 }
534
535 /**
536 * Runs the given task function asynchronously.
537 *
538 * @param fn - Task function that will be executed.
539 * @param task - Input data for the task function.
540 */
541 protected runAsync (
542 fn: TaskAsyncFunction<Data, Response>,
543 task: Task<Data>
544 ): void {
545 const { name, taskId, data } = task
546 let taskPerformance = this.beginTaskPerformance(name)
547 fn(data)
548 .then(res => {
549 taskPerformance = this.endTaskPerformance(taskPerformance)
550 this.sendToMainWorker({
551 data: res,
552 taskPerformance,
553 workerId: this.id,
554 taskId
555 })
556 return null
557 })
558 .catch(e => {
559 const errorMessage = this.handleError(e as Error | string)
560 this.sendToMainWorker({
561 taskError: {
562 name: name as string,
563 message: errorMessage,
564 data
565 },
566 workerId: this.id,
567 taskId
568 })
569 })
570 .finally(() => {
571 this.updateLastTaskTimestamp()
572 })
573 .catch(EMPTY_FUNCTION)
574 }
575
576 private beginTaskPerformance (name?: string): TaskPerformance {
577 this.checkStatistics()
578 return {
579 name: name ?? DEFAULT_TASK_NAME,
580 timestamp: performance.now(),
581 ...(this.statistics.elu && { elu: performance.eventLoopUtilization() })
582 }
583 }
584
585 private endTaskPerformance (
586 taskPerformance: TaskPerformance
587 ): TaskPerformance {
588 this.checkStatistics()
589 return {
590 ...taskPerformance,
591 ...(this.statistics.runTime && {
592 runTime: performance.now() - taskPerformance.timestamp
593 }),
594 ...(this.statistics.elu && {
595 elu: performance.eventLoopUtilization(taskPerformance.elu)
596 })
597 }
598 }
599
600 private checkStatistics (): void {
601 if (this.statistics == null) {
602 throw new Error('Performance statistics computation requirements not set')
603 }
604 }
605
606 private updateLastTaskTimestamp (): void {
607 if (this.activeInterval != null) {
608 this.lastTaskTimestamp = performance.now()
609 }
610 }
611 }