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