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