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