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