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