6bf84b875622ebaece3d8b4b8dae3c637593ed68
[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 delete this.opts.async
107 this.opts.killHandler = opts.killHandler ?? EMPTY_FUNCTION
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 fn !== 'function') {
141 throw new TypeError(
142 'A taskFunctions parameter object value is not a function'
143 )
144 }
145 const boundFn = fn.bind(this)
146 if (firstEntry) {
147 this.taskFunctions.set(DEFAULT_TASK_NAME, boundFn)
148 firstEntry = false
149 }
150 this.taskFunctions.set(name, boundFn)
151 }
152 if (firstEntry) {
153 throw new Error('taskFunctions parameter object is empty')
154 }
155 } else {
156 throw new TypeError(
157 'taskFunctions parameter is not a function or a plain object'
158 )
159 }
160 }
161
162 /**
163 * Checks if the worker has a task function with the given name.
164 *
165 * @param name - The name of the task function to check.
166 * @returns Whether the worker has a task function with the given name or not.
167 * @throws {@link https://nodejs.org/api/errors.html#class-typeerror} If the `name` parameter is not a string.
168 */
169 public hasTaskFunction (name: string): boolean {
170 if (typeof name !== 'string') {
171 throw new TypeError('name parameter is not a string')
172 }
173 return this.taskFunctions.has(name)
174 }
175
176 /**
177 * Adds a task function to the worker.
178 * If a task function with the same name already exists, it is replaced.
179 *
180 * @param name - The name of the task function to add.
181 * @param fn - The task function to add.
182 * @returns Whether the task function was added or not.
183 * @throws {@link https://nodejs.org/api/errors.html#class-typeerror} If the `name` parameter is not a string.
184 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the `name` parameter is the default task function reserved name.
185 * @throws {@link https://nodejs.org/api/errors.html#class-typeerror} If the `fn` parameter is not a function.
186 */
187 public addTaskFunction (
188 name: string,
189 fn: TaskFunction<Data, Response>
190 ): boolean {
191 if (typeof name !== 'string') {
192 throw new TypeError('name parameter is not a string')
193 }
194 if (name === DEFAULT_TASK_NAME) {
195 throw new Error(
196 'Cannot add a task function with the default reserved name'
197 )
198 }
199 if (typeof fn !== 'function') {
200 throw new TypeError('fn parameter is not a function')
201 }
202 try {
203 const boundFn = fn.bind(this)
204 if (
205 this.taskFunctions.get(name) ===
206 this.taskFunctions.get(DEFAULT_TASK_NAME)
207 ) {
208 this.taskFunctions.set(DEFAULT_TASK_NAME, boundFn)
209 }
210 this.taskFunctions.set(name, boundFn)
211 return true
212 } catch {
213 return false
214 }
215 }
216
217 /**
218 * Removes a task function from the worker.
219 *
220 * @param name - The name of the task function to remove.
221 * @returns Whether the task function existed and was removed or not.
222 * @throws {@link https://nodejs.org/api/errors.html#class-typeerror} If the `name` parameter is not a string.
223 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the `name` parameter is the default task function reserved name.
224 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the `name` parameter is the task function used as default task function.
225 */
226 public removeTaskFunction (name: string): boolean {
227 if (typeof name !== 'string') {
228 throw new TypeError('name parameter is not a string')
229 }
230 if (name === DEFAULT_TASK_NAME) {
231 throw new Error(
232 'Cannot remove the task function with the default reserved name'
233 )
234 }
235 if (
236 this.taskFunctions.get(name) === this.taskFunctions.get(DEFAULT_TASK_NAME)
237 ) {
238 throw new Error(
239 'Cannot remove the task function used as the default task function'
240 )
241 }
242 return this.taskFunctions.delete(name)
243 }
244
245 /**
246 * Lists the names of the worker's task functions.
247 *
248 * @returns The names of the worker's task functions.
249 */
250 public listTaskFunctions (): string[] {
251 return [...this.taskFunctions.keys()]
252 }
253
254 /**
255 * Sets the default task function to use in the worker.
256 *
257 * @param name - The name of the task function to use as default task function.
258 * @returns Whether the default task function was set or not.
259 * @throws {@link https://nodejs.org/api/errors.html#class-typeerror} If the `name` parameter is not a string.
260 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the `name` parameter is the default task function reserved name.
261 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the `name` parameter is a non-existing task function.
262 */
263 public setDefaultTaskFunction (name: string): boolean {
264 if (typeof name !== 'string') {
265 throw new TypeError('name parameter is not a string')
266 }
267 if (name === DEFAULT_TASK_NAME) {
268 throw new Error(
269 'Cannot set the default task function reserved name as the default task function'
270 )
271 }
272 if (!this.taskFunctions.has(name)) {
273 throw new Error(
274 'Cannot set the default task function to a non-existing task function'
275 )
276 }
277 try {
278 this.taskFunctions.set(
279 DEFAULT_TASK_NAME,
280 this.taskFunctions.get(name) as TaskFunction<Data, Response>
281 )
282 return true
283 } catch {
284 return false
285 }
286 }
287
288 /**
289 * Handles the ready message sent by the main worker.
290 *
291 * @param message - The ready message.
292 */
293 protected abstract handleReadyMessage (message: MessageValue<Data>): void
294
295 /**
296 * Worker message listener.
297 *
298 * @param message - The received message.
299 */
300 protected messageListener (message: MessageValue<Data>): void {
301 if (this.isMain) {
302 throw new Error('Cannot handle message to worker in main worker')
303 } else if (message.workerId != null && message.workerId !== this.id) {
304 throw new Error(
305 `Message worker id ${message.workerId} does not match the worker id ${this.id}`
306 )
307 } else if (message.workerId === this.id) {
308 if (message.statistics != null) {
309 // Statistics message received
310 this.statistics = message.statistics
311 } else if (message.checkActive != null) {
312 // Check active message received
313 message.checkActive ? this.startCheckActive() : this.stopCheckActive()
314 } else if (message.taskId != null && message.data != null) {
315 // Task message received
316 this.run(message)
317 } else if (message.kill === true) {
318 // Kill message received
319 this.handleKillMessage(message)
320 }
321 }
322 }
323
324 /**
325 * Handles a kill message sent by the main worker.
326 *
327 * @param message - The kill message.
328 */
329 protected handleKillMessage (message: MessageValue<Data>): void {
330 this.stopCheckActive()
331 if (isAsyncFunction(this.opts.killHandler)) {
332 (this.opts.killHandler?.() as Promise<void>)
333 .then(() => {
334 this.sendToMainWorker({ kill: 'success', workerId: this.id })
335 return null
336 })
337 .catch(() => {
338 this.sendToMainWorker({ kill: 'failure', workerId: this.id })
339 })
340 .finally(() => {
341 this.emitDestroy()
342 })
343 .catch(EMPTY_FUNCTION)
344 } else {
345 try {
346 // eslint-disable-next-line @typescript-eslint/no-invalid-void-type
347 this.opts.killHandler?.() as void
348 this.sendToMainWorker({ kill: 'success', workerId: this.id })
349 } catch {
350 this.sendToMainWorker({ kill: 'failure', workerId: this.id })
351 } finally {
352 this.emitDestroy()
353 }
354 }
355 }
356
357 /**
358 * Starts the worker check active interval.
359 */
360 private startCheckActive (): void {
361 this.lastTaskTimestamp = performance.now()
362 this.activeInterval = setInterval(
363 this.checkActive.bind(this),
364 (this.opts.maxInactiveTime ?? DEFAULT_MAX_INACTIVE_TIME) / 2
365 )
366 }
367
368 /**
369 * Stops the worker check active interval.
370 */
371 private stopCheckActive (): void {
372 if (this.activeInterval != null) {
373 clearInterval(this.activeInterval)
374 delete this.activeInterval
375 }
376 }
377
378 /**
379 * Checks if the worker should be terminated, because its living too long.
380 */
381 private checkActive (): void {
382 if (
383 performance.now() - this.lastTaskTimestamp >
384 (this.opts.maxInactiveTime ?? DEFAULT_MAX_INACTIVE_TIME)
385 ) {
386 this.sendToMainWorker({ kill: this.opts.killBehavior, workerId: this.id })
387 }
388 }
389
390 /**
391 * Returns the main worker.
392 *
393 * @returns Reference to the main worker.
394 */
395 protected getMainWorker (): MainWorker {
396 if (this.mainWorker == null) {
397 throw new Error('Main worker not set')
398 }
399 return this.mainWorker
400 }
401
402 /**
403 * Sends a message to main worker.
404 *
405 * @param message - The response message.
406 */
407 protected abstract sendToMainWorker (
408 message: MessageValue<Response, Data>
409 ): void
410
411 /**
412 * Handles an error and convert it to a string so it can be sent back to the main worker.
413 *
414 * @param e - The error raised by the worker.
415 * @returns The error message.
416 */
417 protected handleError (e: Error | string): string {
418 return e instanceof Error ? e.message : e
419 }
420
421 /**
422 * Runs the given task.
423 *
424 * @param task - The task to execute.
425 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the task function is not found.
426 */
427 protected run (task: Task<Data>): void {
428 const fn = this.getTaskFunction(task.name)
429 if (isAsyncFunction(fn)) {
430 this.runInAsyncScope(this.runAsync.bind(this), this, fn, task)
431 } else {
432 this.runInAsyncScope(this.runSync.bind(this), this, fn, task)
433 }
434 }
435
436 /**
437 * Runs the given task function synchronously.
438 *
439 * @param fn - Task function that will be executed.
440 * @param task - Input data for the task function.
441 */
442 protected runSync (
443 fn: TaskSyncFunction<Data, Response>,
444 task: Task<Data>
445 ): void {
446 try {
447 let taskPerformance = this.beginTaskPerformance(task.name)
448 const res = fn(task.data)
449 taskPerformance = this.endTaskPerformance(taskPerformance)
450 this.sendToMainWorker({
451 data: res,
452 taskPerformance,
453 workerId: this.id,
454 taskId: task.taskId
455 })
456 } catch (e) {
457 const errorMessage = this.handleError(e as Error | string)
458 this.sendToMainWorker({
459 taskError: {
460 name: task.name ?? DEFAULT_TASK_NAME,
461 message: errorMessage,
462 data: task.data
463 },
464 workerId: this.id,
465 taskId: task.taskId
466 })
467 } finally {
468 this.updateLastTaskTimestamp()
469 }
470 }
471
472 /**
473 * Runs the given task function asynchronously.
474 *
475 * @param fn - Task function that will be executed.
476 * @param task - Input data for the task function.
477 */
478 protected runAsync (
479 fn: TaskAsyncFunction<Data, Response>,
480 task: Task<Data>
481 ): void {
482 let taskPerformance = this.beginTaskPerformance(task.name)
483 fn(task.data)
484 .then((res) => {
485 taskPerformance = this.endTaskPerformance(taskPerformance)
486 this.sendToMainWorker({
487 data: res,
488 taskPerformance,
489 workerId: this.id,
490 taskId: task.taskId
491 })
492 return null
493 })
494 .catch((e) => {
495 const errorMessage = this.handleError(e as Error | string)
496 this.sendToMainWorker({
497 taskError: {
498 name: task.name ?? DEFAULT_TASK_NAME,
499 message: errorMessage,
500 data: task.data
501 },
502 workerId: this.id,
503 taskId: task.taskId
504 })
505 })
506 .finally(() => {
507 this.updateLastTaskTimestamp()
508 })
509 .catch(EMPTY_FUNCTION)
510 }
511
512 /**
513 * Gets the task function with the given name.
514 *
515 * @param name - Name of the task function that will be returned.
516 * @returns The task function.
517 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the task function is not found.
518 */
519 private getTaskFunction (name?: string): TaskFunction<Data, Response> {
520 name = name ?? DEFAULT_TASK_NAME
521 const fn = this.taskFunctions.get(name)
522 if (fn == null) {
523 throw new Error(`Task function '${name}' not found`)
524 }
525 return fn
526 }
527
528 private beginTaskPerformance (name?: string): TaskPerformance {
529 this.checkStatistics()
530 return {
531 name: name ?? DEFAULT_TASK_NAME,
532 timestamp: performance.now(),
533 ...(this.statistics.elu && { elu: performance.eventLoopUtilization() })
534 }
535 }
536
537 private endTaskPerformance (
538 taskPerformance: TaskPerformance
539 ): TaskPerformance {
540 this.checkStatistics()
541 return {
542 ...taskPerformance,
543 ...(this.statistics.runTime && {
544 runTime: performance.now() - taskPerformance.timestamp
545 }),
546 ...(this.statistics.elu && {
547 elu: performance.eventLoopUtilization(taskPerformance.elu)
548 })
549 }
550 }
551
552 private checkStatistics (): void {
553 if (this.statistics == null) {
554 throw new Error('Performance statistics computation requirements not set')
555 }
556 }
557
558 private updateLastTaskTimestamp (): void {
559 if (this.activeInterval != null) {
560 this.lastTaskTimestamp = performance.now()
561 }
562 }
563 }