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