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