refactor: factor out task function validation
[poolifier.git] / src / worker / abstract-worker.ts
CommitLineData
fc3e6586 1import { AsyncResource } from 'node:async_hooks'
6677a3d3 2import type { Worker } from 'node:cluster'
fc3e6586 3import type { MessagePort } from 'node:worker_threads'
d715b7bc
JB
4import { performance } from 'node:perf_hooks'
5import type {
6 MessageValue,
5c4d16da 7 Task,
d715b7bc
JB
8 TaskPerformance,
9 WorkerStatistics
10} from '../utility-types'
ff128cc9
JB
11import {
12 DEFAULT_TASK_NAME,
13 EMPTY_FUNCTION,
14 isAsyncFunction,
15 isPlainObject
16} from '../utils'
d38d0e30 17import { KillBehaviors, type WorkerOptions } from './worker-options'
b6b32453 18import type {
82ea6492
JB
19 TaskAsyncFunction,
20 TaskFunction,
b6b32453 21 TaskFunctions,
82ea6492
JB
22 TaskSyncFunction
23} from './task-functions'
4c35177b 24
978aad6f 25const DEFAULT_MAX_INACTIVE_TIME = 60000
d38d0e30
JB
26const DEFAULT_WORKER_OPTIONS: WorkerOptions = {
27 /**
28 * The kill behavior option on this worker or its default value.
29 */
30 killBehavior: KillBehaviors.SOFT,
31 /**
32 * The maximum time to keep this worker active while idle.
33 * The pool automatically checks and terminates this worker when the time expires.
34 */
35 maxInactiveTime: DEFAULT_MAX_INACTIVE_TIME,
36 /**
37 * The function to call when the worker is killed.
38 */
39 killHandler: EMPTY_FUNCTION
40}
c97c7edb 41
729c563d 42/**
ea7a90d3 43 * Base class that implements some shared logic for all poolifier workers.
729c563d 44 *
38e795c1 45 * @typeParam MainWorker - Type of main worker.
e102732c
JB
46 * @typeParam Data - Type of data this worker receives from pool's execution. This can only be structured-cloneable data.
47 * @typeParam Response - Type of response the worker sends back to the main worker. This can only be structured-cloneable data.
729c563d 48 */
c97c7edb 49export abstract class AbstractWorker<
6677a3d3 50 MainWorker extends Worker | MessagePort,
d3c8a1a8
S
51 Data = unknown,
52 Response = unknown
c97c7edb 53> extends AsyncResource {
f59e1027 54 /**
83fa0a36 55 * Worker id.
f59e1027
JB
56 */
57 protected abstract id: number
a86b6df1
JB
58 /**
59 * Task function(s) processed by the worker when the pool's `execution` function is invoked.
60 */
82ea6492 61 protected taskFunctions!: Map<string, TaskFunction<Data, Response>>
729c563d
S
62 /**
63 * Timestamp of the last task processed by this worker.
64 */
a9d9ea34 65 protected lastTaskTimestamp!: number
b6b32453 66 /**
8a970421 67 * Performance statistics computation requirements.
b6b32453
JB
68 */
69 protected statistics!: WorkerStatistics
729c563d 70 /**
b0a4db63 71 * Handler id of the `activeInterval` worker activity check.
729c563d 72 */
b0a4db63 73 protected activeInterval?: NodeJS.Timeout
c97c7edb 74 /**
729c563d 75 * Constructs a new poolifier worker.
c97c7edb 76 *
38e795c1
JB
77 * @param type - The type of async event.
78 * @param isMain - Whether this is the main worker or not.
38e795c1 79 * @param mainWorker - Reference to main worker.
85aeb3f3 80 * @param taskFunctions - Task function(s) processed by the worker when the pool's `execution` function is invoked. The first function is the default function.
38e795c1 81 * @param opts - Options for the worker.
c97c7edb
S
82 */
83 public constructor (
84 type: string,
c2ade475 85 protected readonly isMain: boolean,
6c0c538c 86 private readonly mainWorker: MainWorker,
82ea6492 87 taskFunctions: TaskFunction<Data, Response> | TaskFunctions<Data, Response>,
d38d0e30 88 protected opts: WorkerOptions = DEFAULT_WORKER_OPTIONS
c97c7edb
S
89 ) {
90 super(type)
9d2d0da1
JB
91 if (this.isMain == null) {
92 throw new Error('isMain parameter is mandatory')
93 }
a86b6df1 94 this.checkTaskFunctions(taskFunctions)
9d2d0da1 95 this.checkWorkerOptions(this.opts)
1f68cede 96 if (!this.isMain) {
9d2d0da1 97 this.getMainWorker().on('message', this.handleReadyMessage.bind(this))
c97c7edb
S
98 }
99 }
100
41aa7dcd 101 private checkWorkerOptions (opts: WorkerOptions): void {
d38d0e30 102 this.opts = { ...DEFAULT_WORKER_OPTIONS, ...opts }
3c5dc3fb 103 delete this.opts.async
41aa7dcd
JB
104 }
105
0628df39
JB
106 private checkValidTaskFunction (
107 name: string,
108 fn: TaskFunction<Data, Response>
109 ): void {
110 if (typeof name !== 'string') {
111 throw new TypeError(
112 'A taskFunctions parameter object key is not a string'
113 )
114 }
115 if (typeof name === 'string' && name.trim().length === 0) {
116 throw new TypeError(
117 'A taskFunctions parameter object key is an empty string'
118 )
119 }
120 if (typeof fn !== 'function') {
121 throw new TypeError(
122 'A taskFunctions parameter object value is not a function'
123 )
124 }
125 }
126
41aa7dcd 127 /**
a86b6df1 128 * Checks if the `taskFunctions` parameter is passed to the constructor.
41aa7dcd 129 *
82888165 130 * @param taskFunctions - The task function(s) parameter that should be checked.
41aa7dcd 131 */
a86b6df1 132 private checkTaskFunctions (
82ea6492 133 taskFunctions: TaskFunction<Data, Response> | TaskFunctions<Data, Response>
a86b6df1 134 ): void {
ec8fd331
JB
135 if (taskFunctions == null) {
136 throw new Error('taskFunctions parameter is mandatory')
137 }
82ea6492 138 this.taskFunctions = new Map<string, TaskFunction<Data, Response>>()
0d80593b 139 if (typeof taskFunctions === 'function') {
2a69b8c5
JB
140 const boundFn = taskFunctions.bind(this)
141 this.taskFunctions.set(DEFAULT_TASK_NAME, boundFn)
142 this.taskFunctions.set(
143 typeof taskFunctions.name === 'string' &&
8ebe6c30 144 taskFunctions.name.trim().length > 0
2a69b8c5
JB
145 ? taskFunctions.name
146 : 'fn1',
147 boundFn
148 )
0d80593b 149 } else if (isPlainObject(taskFunctions)) {
82888165 150 let firstEntry = true
a86b6df1 151 for (const [name, fn] of Object.entries(taskFunctions)) {
0628df39 152 this.checkValidTaskFunction(name, fn)
2a69b8c5 153 const boundFn = fn.bind(this)
82888165 154 if (firstEntry) {
2a69b8c5 155 this.taskFunctions.set(DEFAULT_TASK_NAME, boundFn)
82888165
JB
156 firstEntry = false
157 }
c50b93fb 158 this.taskFunctions.set(name, boundFn)
a86b6df1 159 }
630f0acf
JB
160 if (firstEntry) {
161 throw new Error('taskFunctions parameter object is empty')
162 }
a86b6df1 163 } else {
f34fdabe
JB
164 throw new TypeError(
165 'taskFunctions parameter is not a function or a plain object'
166 )
41aa7dcd
JB
167 }
168 }
169
968a2e8c
JB
170 /**
171 * Checks if the worker has a task function with the given name.
172 *
173 * @param name - The name of the task function to check.
174 * @returns Whether the worker has a task function with the given name or not.
9e746eec 175 * @throws {@link https://nodejs.org/api/errors.html#class-typeerror} If the `name` parameter is not a string or an empty string.
968a2e8c
JB
176 */
177 public hasTaskFunction (name: string): boolean {
d5e3c4ff 178 this.checkTaskFunctionName(name)
968a2e8c
JB
179 return this.taskFunctions.has(name)
180 }
181
182 /**
183 * Adds a task function to the worker.
184 * If a task function with the same name already exists, it is replaced.
185 *
186 * @param name - The name of the task function to add.
187 * @param fn - The task function to add.
188 * @returns Whether the task function was added or not.
9e746eec 189 * @throws {@link https://nodejs.org/api/errors.html#class-typeerror} If the `name` parameter is not a string or an empty string.
13a332e6
JB
190 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the `name` parameter is the default task function reserved name.
191 * @throws {@link https://nodejs.org/api/errors.html#class-typeerror} If the `fn` parameter is not a function.
968a2e8c
JB
192 */
193 public addTaskFunction (
194 name: string,
82ea6492 195 fn: TaskFunction<Data, Response>
968a2e8c 196 ): boolean {
d5e3c4ff 197 this.checkTaskFunctionName(name)
968a2e8c
JB
198 if (name === DEFAULT_TASK_NAME) {
199 throw new Error(
200 'Cannot add a task function with the default reserved name'
201 )
202 }
203 if (typeof fn !== 'function') {
204 throw new TypeError('fn parameter is not a function')
205 }
206 try {
646d040a 207 const boundFn = fn.bind(this)
968a2e8c
JB
208 if (
209 this.taskFunctions.get(name) ===
210 this.taskFunctions.get(DEFAULT_TASK_NAME)
211 ) {
2a69b8c5 212 this.taskFunctions.set(DEFAULT_TASK_NAME, boundFn)
968a2e8c 213 }
2a69b8c5 214 this.taskFunctions.set(name, boundFn)
90d7d101 215 this.sendTaskFunctionsListToMainWorker()
968a2e8c
JB
216 return true
217 } catch {
218 return false
219 }
220 }
221
222 /**
223 * Removes a task function from the worker.
224 *
225 * @param name - The name of the task function to remove.
226 * @returns Whether the task function existed and was removed or not.
9e746eec 227 * @throws {@link https://nodejs.org/api/errors.html#class-typeerror} If the `name` parameter is not a string or an empty string.
13a332e6
JB
228 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the `name` parameter is the default task function reserved name.
229 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the `name` parameter is the task function used as default task function.
968a2e8c
JB
230 */
231 public removeTaskFunction (name: string): boolean {
d5e3c4ff 232 this.checkTaskFunctionName(name)
968a2e8c
JB
233 if (name === DEFAULT_TASK_NAME) {
234 throw new Error(
235 'Cannot remove the task function with the default reserved name'
236 )
237 }
238 if (
239 this.taskFunctions.get(name) === this.taskFunctions.get(DEFAULT_TASK_NAME)
240 ) {
241 throw new Error(
242 'Cannot remove the task function used as the default task function'
243 )
244 }
90d7d101
JB
245 const deleteStatus = this.taskFunctions.delete(name)
246 this.sendTaskFunctionsListToMainWorker()
247 return deleteStatus
968a2e8c
JB
248 }
249
250 /**
c50b93fb
JB
251 * Lists the names of the worker's task functions.
252 *
253 * @returns The names of the worker's task functions.
254 */
255 public listTaskFunctions (): string[] {
b558f6b5
JB
256 const names: string[] = [...this.taskFunctions.keys()]
257 let defaultTaskFunctionName: string = DEFAULT_TASK_NAME
258 for (const [name, fn] of this.taskFunctions) {
259 if (
260 name !== DEFAULT_TASK_NAME &&
261 fn === this.taskFunctions.get(DEFAULT_TASK_NAME)
262 ) {
263 defaultTaskFunctionName = name
264 break
265 }
266 }
267 return [
268 names[names.indexOf(DEFAULT_TASK_NAME)],
269 defaultTaskFunctionName,
270 ...names.filter(
271 (name) => name !== DEFAULT_TASK_NAME && name !== defaultTaskFunctionName
272 )
273 ]
c50b93fb
JB
274 }
275
276 /**
277 * Sets the default task function to use in the worker.
968a2e8c
JB
278 *
279 * @param name - The name of the task function to use as default task function.
280 * @returns Whether the default task function was set or not.
9e746eec 281 * @throws {@link https://nodejs.org/api/errors.html#class-typeerror} If the `name` parameter is not a string or an empty string.
13a332e6
JB
282 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the `name` parameter is the default task function reserved name.
283 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the `name` parameter is a non-existing task function.
968a2e8c
JB
284 */
285 public setDefaultTaskFunction (name: string): boolean {
d5e3c4ff 286 this.checkTaskFunctionName(name)
968a2e8c
JB
287 if (name === DEFAULT_TASK_NAME) {
288 throw new Error(
289 'Cannot set the default task function reserved name as the default task function'
290 )
291 }
292 if (!this.taskFunctions.has(name)) {
293 throw new Error(
294 'Cannot set the default task function to a non-existing task function'
295 )
296 }
297 try {
298 this.taskFunctions.set(
299 DEFAULT_TASK_NAME,
82ea6492 300 this.taskFunctions.get(name) as TaskFunction<Data, Response>
968a2e8c
JB
301 )
302 return true
303 } catch {
304 return false
305 }
306 }
307
d5e3c4ff
JB
308 private checkTaskFunctionName (name: string): void {
309 if (typeof name !== 'string') {
310 throw new TypeError('name parameter is not a string')
311 }
312 if (typeof name === 'string' && name.trim().length === 0) {
313 throw new TypeError('name parameter is an empty string')
314 }
315 }
316
a038b517
JB
317 /**
318 * Handles the ready message sent by the main worker.
319 *
320 * @param message - The ready message.
321 */
322 protected abstract handleReadyMessage (message: MessageValue<Data>): void
323
aee46736
JB
324 /**
325 * Worker message listener.
326 *
6b813701 327 * @param message - The received message.
aee46736 328 */
85aeb3f3 329 protected messageListener (message: MessageValue<Data>): void {
9e746eec 330 this.checkMessageWorkerId(message)
310de0aa
JB
331 if (message.statistics != null) {
332 // Statistics message received
333 this.statistics = message.statistics
334 } else if (message.checkActive != null) {
335 // Check active message received
336 message.checkActive ? this.startCheckActive() : this.stopCheckActive()
337 } else if (message.taskId != null && message.data != null) {
338 // Task message received
339 this.run(message)
340 } else if (message.kill === true) {
341 // Kill message received
342 this.handleKillMessage(message)
cf597bc5
JB
343 }
344 }
345
984dc9c8
JB
346 /**
347 * Handles a kill message sent by the main worker.
348 *
349 * @param message - The kill message.
350 */
351 protected handleKillMessage (message: MessageValue<Data>): void {
29d8b961 352 this.stopCheckActive()
07588f30
JB
353 if (isAsyncFunction(this.opts.killHandler)) {
354 (this.opts.killHandler?.() as Promise<void>)
1e3214b6
JB
355 .then(() => {
356 this.sendToMainWorker({ kill: 'success', workerId: this.id })
357 return null
358 })
359 .catch(() => {
360 this.sendToMainWorker({ kill: 'failure', workerId: this.id })
361 })
362 .finally(() => {
363 this.emitDestroy()
364 })
07588f30
JB
365 .catch(EMPTY_FUNCTION)
366 } else {
1e3214b6
JB
367 try {
368 // eslint-disable-next-line @typescript-eslint/no-invalid-void-type
369 this.opts.killHandler?.() as void
370 this.sendToMainWorker({ kill: 'success', workerId: this.id })
7c8ac84e 371 } catch {
1e3214b6
JB
372 this.sendToMainWorker({ kill: 'failure', workerId: this.id })
373 } finally {
374 this.emitDestroy()
375 }
07588f30 376 }
984dc9c8
JB
377 }
378
9e746eec
JB
379 /**
380 * Check if the message worker id is set and matches the worker id.
381 *
382 * @param message - The message to check.
383 * @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.
384 */
385 private checkMessageWorkerId (message: MessageValue<Data>): void {
386 if (message.workerId == null) {
387 throw new Error('Message worker id is not set')
388 } else if (message.workerId != null && message.workerId !== this.id) {
389 throw new Error(
390 `Message worker id ${message.workerId} does not match the worker id ${this.id}`
391 )
392 }
393 }
394
48487131 395 /**
b0a4db63 396 * Starts the worker check active interval.
48487131 397 */
b0a4db63 398 private startCheckActive (): void {
75d3401a 399 this.lastTaskTimestamp = performance.now()
b0a4db63
JB
400 this.activeInterval = setInterval(
401 this.checkActive.bind(this),
75d3401a 402 (this.opts.maxInactiveTime ?? DEFAULT_MAX_INACTIVE_TIME) / 2
984dc9c8 403 )
75d3401a
JB
404 }
405
48487131 406 /**
b0a4db63 407 * Stops the worker check active interval.
48487131 408 */
b0a4db63 409 private stopCheckActive (): void {
c3f498b5
JB
410 if (this.activeInterval != null) {
411 clearInterval(this.activeInterval)
412 delete this.activeInterval
413 }
48487131
JB
414 }
415
416 /**
417 * Checks if the worker should be terminated, because its living too long.
418 */
b0a4db63 419 private checkActive (): void {
48487131
JB
420 if (
421 performance.now() - this.lastTaskTimestamp >
422 (this.opts.maxInactiveTime ?? DEFAULT_MAX_INACTIVE_TIME)
423 ) {
21f710aa 424 this.sendToMainWorker({ kill: this.opts.killBehavior, workerId: this.id })
48487131
JB
425 }
426 }
427
729c563d
S
428 /**
429 * Returns the main worker.
838898f1
S
430 *
431 * @returns Reference to the main worker.
729c563d 432 */
838898f1 433 protected getMainWorker (): MainWorker {
78cea37e 434 if (this.mainWorker == null) {
e102732c 435 throw new Error('Main worker not set')
838898f1
S
436 }
437 return this.mainWorker
438 }
c97c7edb 439
729c563d 440 /**
aa9eede8 441 * Sends a message to main worker.
729c563d 442 *
38e795c1 443 * @param message - The response message.
729c563d 444 */
82f36766
JB
445 protected abstract sendToMainWorker (
446 message: MessageValue<Response, Data>
447 ): void
c97c7edb 448
90d7d101
JB
449 /**
450 * Sends the list of task function names to the main worker.
451 */
452 protected sendTaskFunctionsListToMainWorker (): void {
453 this.sendToMainWorker({
454 taskFunctions: this.listTaskFunctions(),
455 workerId: this.id
456 })
457 }
458
729c563d 459 /**
8accb8d5 460 * Handles an error and convert it to a string so it can be sent back to the main worker.
729c563d 461 *
38e795c1 462 * @param e - The error raised by the worker.
ab80dc46 463 * @returns The error message.
729c563d 464 */
c97c7edb 465 protected handleError (e: Error | string): string {
985d0e79 466 return e instanceof Error ? e.message : e
c97c7edb
S
467 }
468
5c4d16da
JB
469 /**
470 * Runs the given task.
471 *
472 * @param task - The task to execute.
473 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the task function is not found.
474 */
475 protected run (task: Task<Data>): void {
9d2d0da1
JB
476 const { name, taskId, data } = task
477 const fn = this.taskFunctions.get(name ?? DEFAULT_TASK_NAME)
478 if (fn == null) {
479 this.sendToMainWorker({
480 taskError: {
481 name: name as string,
482 message: `Task function '${name as string}' not found`,
483 data
484 },
485 workerId: this.id,
486 taskId
487 })
488 return
489 }
5c4d16da
JB
490 if (isAsyncFunction(fn)) {
491 this.runInAsyncScope(this.runAsync.bind(this), this, fn, task)
492 } else {
493 this.runInAsyncScope(this.runSync.bind(this), this, fn, task)
494 }
495 }
496
729c563d 497 /**
4dd93fcf 498 * Runs the given task function synchronously.
729c563d 499 *
5c4d16da
JB
500 * @param fn - Task function that will be executed.
501 * @param task - Input data for the task function.
729c563d 502 */
70a4f5ea 503 protected runSync (
82ea6492 504 fn: TaskSyncFunction<Data, Response>,
5c4d16da 505 task: Task<Data>
c97c7edb 506 ): void {
310de0aa 507 const { name, taskId, data } = task
c97c7edb 508 try {
310de0aa
JB
509 let taskPerformance = this.beginTaskPerformance(name)
510 const res = fn(data)
d715b7bc 511 taskPerformance = this.endTaskPerformance(taskPerformance)
3fafb1b2
JB
512 this.sendToMainWorker({
513 data: res,
d715b7bc 514 taskPerformance,
f59e1027 515 workerId: this.id,
310de0aa 516 taskId
3fafb1b2 517 })
c97c7edb 518 } catch (e) {
985d0e79 519 const errorMessage = this.handleError(e as Error | string)
91ee39ed 520 this.sendToMainWorker({
82f36766 521 taskError: {
0628755c 522 name: name as string,
985d0e79 523 message: errorMessage,
310de0aa 524 data
82f36766 525 },
21f710aa 526 workerId: this.id,
310de0aa 527 taskId
91ee39ed 528 })
6e9d10db 529 } finally {
c3f498b5 530 this.updateLastTaskTimestamp()
c97c7edb
S
531 }
532 }
533
729c563d 534 /**
4dd93fcf 535 * Runs the given task function asynchronously.
729c563d 536 *
5c4d16da
JB
537 * @param fn - Task function that will be executed.
538 * @param task - Input data for the task function.
729c563d 539 */
c97c7edb 540 protected runAsync (
82ea6492 541 fn: TaskAsyncFunction<Data, Response>,
5c4d16da 542 task: Task<Data>
c97c7edb 543 ): void {
310de0aa
JB
544 const { name, taskId, data } = task
545 let taskPerformance = this.beginTaskPerformance(name)
546 fn(data)
8ebe6c30 547 .then((res) => {
d715b7bc 548 taskPerformance = this.endTaskPerformance(taskPerformance)
3fafb1b2
JB
549 this.sendToMainWorker({
550 data: res,
d715b7bc 551 taskPerformance,
f59e1027 552 workerId: this.id,
310de0aa 553 taskId
3fafb1b2 554 })
c97c7edb
S
555 return null
556 })
8ebe6c30 557 .catch((e) => {
985d0e79 558 const errorMessage = this.handleError(e as Error | string)
91ee39ed 559 this.sendToMainWorker({
82f36766 560 taskError: {
0628755c 561 name: name as string,
985d0e79 562 message: errorMessage,
310de0aa 563 data
82f36766 564 },
21f710aa 565 workerId: this.id,
310de0aa 566 taskId
91ee39ed 567 })
6e9d10db
JB
568 })
569 .finally(() => {
c3f498b5 570 this.updateLastTaskTimestamp()
c97c7edb 571 })
6e9d10db 572 .catch(EMPTY_FUNCTION)
c97c7edb 573 }
ec8fd331 574
197b4aa5 575 private beginTaskPerformance (name?: string): TaskPerformance {
8a970421 576 this.checkStatistics()
62c15a68 577 return {
ff128cc9 578 name: name ?? DEFAULT_TASK_NAME,
1c6fe997 579 timestamp: performance.now(),
b6b32453 580 ...(this.statistics.elu && { elu: performance.eventLoopUtilization() })
62c15a68
JB
581 }
582 }
583
d9d31201
JB
584 private endTaskPerformance (
585 taskPerformance: TaskPerformance
586 ): TaskPerformance {
8a970421 587 this.checkStatistics()
62c15a68
JB
588 return {
589 ...taskPerformance,
b6b32453
JB
590 ...(this.statistics.runTime && {
591 runTime: performance.now() - taskPerformance.timestamp
592 }),
593 ...(this.statistics.elu && {
62c15a68 594 elu: performance.eventLoopUtilization(taskPerformance.elu)
b6b32453 595 })
62c15a68
JB
596 }
597 }
8a970421
JB
598
599 private checkStatistics (): void {
600 if (this.statistics == null) {
601 throw new Error('Performance statistics computation requirements not set')
602 }
603 }
c3f498b5
JB
604
605 private updateLastTaskTimestamp (): void {
29d8b961 606 if (this.activeInterval != null) {
c3f498b5
JB
607 this.lastTaskTimestamp = performance.now()
608 }
609 }
c97c7edb 610}