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