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