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