fix: fix formatting issue.
[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(
041dc05b 271 name => name !== DEFAULT_TASK_NAME && name !== defaultTaskFunctionName
b558f6b5
JB
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 353 if (isAsyncFunction(this.opts.killHandler)) {
041dc05b 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.
155bb3de 432 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the main worker is not set.
729c563d 433 */
838898f1 434 protected getMainWorker (): MainWorker {
78cea37e 435 if (this.mainWorker == null) {
e102732c 436 throw new Error('Main worker not set')
838898f1
S
437 }
438 return this.mainWorker
439 }
c97c7edb 440
729c563d 441 /**
aa9eede8 442 * Sends a message to main worker.
729c563d 443 *
38e795c1 444 * @param message - The response message.
729c563d 445 */
82f36766
JB
446 protected abstract sendToMainWorker (
447 message: MessageValue<Response, Data>
448 ): void
c97c7edb 449
90d7d101
JB
450 /**
451 * Sends the list of task function names to the main worker.
452 */
453 protected sendTaskFunctionsListToMainWorker (): void {
454 this.sendToMainWorker({
455 taskFunctions: this.listTaskFunctions(),
456 workerId: this.id
457 })
458 }
459
729c563d 460 /**
8accb8d5 461 * Handles an error and convert it to a string so it can be sent back to the main worker.
729c563d 462 *
38e795c1 463 * @param e - The error raised by the worker.
ab80dc46 464 * @returns The error message.
729c563d 465 */
c97c7edb 466 protected handleError (e: Error | string): string {
985d0e79 467 return e instanceof Error ? e.message : e
c97c7edb
S
468 }
469
5c4d16da
JB
470 /**
471 * Runs the given task.
472 *
473 * @param task - The task to execute.
474 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the task function is not found.
475 */
476 protected run (task: Task<Data>): void {
9d2d0da1
JB
477 const { name, taskId, data } = task
478 const fn = this.taskFunctions.get(name ?? DEFAULT_TASK_NAME)
479 if (fn == null) {
480 this.sendToMainWorker({
481 taskError: {
482 name: name as string,
483 message: `Task function '${name as string}' not found`,
484 data
485 },
486 workerId: this.id,
487 taskId
488 })
489 return
490 }
5c4d16da
JB
491 if (isAsyncFunction(fn)) {
492 this.runInAsyncScope(this.runAsync.bind(this), this, fn, task)
493 } else {
494 this.runInAsyncScope(this.runSync.bind(this), this, fn, task)
495 }
496 }
497
729c563d 498 /**
4dd93fcf 499 * Runs the given task function synchronously.
729c563d 500 *
5c4d16da
JB
501 * @param fn - Task function that will be executed.
502 * @param task - Input data for the task function.
729c563d 503 */
70a4f5ea 504 protected runSync (
82ea6492 505 fn: TaskSyncFunction<Data, Response>,
5c4d16da 506 task: Task<Data>
c97c7edb 507 ): void {
310de0aa 508 const { name, taskId, data } = task
c97c7edb 509 try {
310de0aa
JB
510 let taskPerformance = this.beginTaskPerformance(name)
511 const res = fn(data)
d715b7bc 512 taskPerformance = this.endTaskPerformance(taskPerformance)
3fafb1b2
JB
513 this.sendToMainWorker({
514 data: res,
d715b7bc 515 taskPerformance,
f59e1027 516 workerId: this.id,
310de0aa 517 taskId
3fafb1b2 518 })
c97c7edb 519 } catch (e) {
985d0e79 520 const errorMessage = this.handleError(e as Error | string)
91ee39ed 521 this.sendToMainWorker({
82f36766 522 taskError: {
0628755c 523 name: name as string,
985d0e79 524 message: errorMessage,
310de0aa 525 data
82f36766 526 },
21f710aa 527 workerId: this.id,
310de0aa 528 taskId
91ee39ed 529 })
6e9d10db 530 } finally {
c3f498b5 531 this.updateLastTaskTimestamp()
c97c7edb
S
532 }
533 }
534
729c563d 535 /**
4dd93fcf 536 * Runs the given task function asynchronously.
729c563d 537 *
5c4d16da
JB
538 * @param fn - Task function that will be executed.
539 * @param task - Input data for the task function.
729c563d 540 */
c97c7edb 541 protected runAsync (
82ea6492 542 fn: TaskAsyncFunction<Data, Response>,
5c4d16da 543 task: Task<Data>
c97c7edb 544 ): void {
310de0aa
JB
545 const { name, taskId, data } = task
546 let taskPerformance = this.beginTaskPerformance(name)
547 fn(data)
041dc05b 548 .then(res => {
d715b7bc 549 taskPerformance = this.endTaskPerformance(taskPerformance)
3fafb1b2
JB
550 this.sendToMainWorker({
551 data: res,
d715b7bc 552 taskPerformance,
f59e1027 553 workerId: this.id,
310de0aa 554 taskId
3fafb1b2 555 })
c97c7edb
S
556 return null
557 })
041dc05b 558 .catch(e => {
985d0e79 559 const errorMessage = this.handleError(e as Error | string)
91ee39ed 560 this.sendToMainWorker({
82f36766 561 taskError: {
0628755c 562 name: name as string,
985d0e79 563 message: errorMessage,
310de0aa 564 data
82f36766 565 },
21f710aa 566 workerId: this.id,
310de0aa 567 taskId
91ee39ed 568 })
6e9d10db
JB
569 })
570 .finally(() => {
c3f498b5 571 this.updateLastTaskTimestamp()
c97c7edb 572 })
6e9d10db 573 .catch(EMPTY_FUNCTION)
c97c7edb 574 }
ec8fd331 575
197b4aa5 576 private beginTaskPerformance (name?: string): TaskPerformance {
8a970421 577 this.checkStatistics()
62c15a68 578 return {
ff128cc9 579 name: name ?? DEFAULT_TASK_NAME,
1c6fe997 580 timestamp: performance.now(),
b6b32453 581 ...(this.statistics.elu && { elu: performance.eventLoopUtilization() })
62c15a68
JB
582 }
583 }
584
d9d31201
JB
585 private endTaskPerformance (
586 taskPerformance: TaskPerformance
587 ): TaskPerformance {
8a970421 588 this.checkStatistics()
62c15a68
JB
589 return {
590 ...taskPerformance,
b6b32453
JB
591 ...(this.statistics.runTime && {
592 runTime: performance.now() - taskPerformance.timestamp
593 }),
594 ...(this.statistics.elu && {
62c15a68 595 elu: performance.eventLoopUtilization(taskPerformance.elu)
b6b32453 596 })
62c15a68
JB
597 }
598 }
8a970421
JB
599
600 private checkStatistics (): void {
601 if (this.statistics == null) {
602 throw new Error('Performance statistics computation requirements not set')
603 }
604 }
c3f498b5
JB
605
606 private updateLastTaskTimestamp (): void {
29d8b961 607 if (this.activeInterval != null) {
c3f498b5
JB
608 this.lastTaskTimestamp = performance.now()
609 }
610 }
c97c7edb 611}