feat: add pool and worker readyness tracking infrastructure
[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'
49d1b48c 10import { EMPTY_FUNCTION, isAsyncFunction, isPlainObject } from '../utils'
241f23c2
JB
11import {
12 type KillBehavior,
13 KillBehaviors,
14 type WorkerOptions
15} from './worker-options'
b6b32453
JB
16import type {
17 TaskFunctions,
18 WorkerAsyncFunction,
19 WorkerFunction,
20 WorkerSyncFunction
21} from './worker-functions'
4c35177b 22
ec8fd331 23const DEFAULT_FUNCTION_NAME = 'default'
978aad6f 24const DEFAULT_MAX_INACTIVE_TIME = 60000
1a81f8af 25const DEFAULT_KILL_BEHAVIOR: KillBehavior = KillBehaviors.SOFT
c97c7edb 26
729c563d 27/**
ea7a90d3 28 * Base class that implements some shared logic for all poolifier workers.
729c563d 29 *
38e795c1 30 * @typeParam MainWorker - Type of main worker.
e102732c
JB
31 * @typeParam Data - Type of data this worker receives from pool's execution. This can only be structured-cloneable data.
32 * @typeParam Response - Type of response the worker sends back to the main worker. This can only be structured-cloneable data.
729c563d 33 */
c97c7edb 34export abstract class AbstractWorker<
6677a3d3 35 MainWorker extends Worker | MessagePort,
d3c8a1a8
S
36 Data = unknown,
37 Response = unknown
c97c7edb 38> extends AsyncResource {
f59e1027 39 /**
83fa0a36 40 * Worker id.
f59e1027
JB
41 */
42 protected abstract id: number
a86b6df1
JB
43 /**
44 * Task function(s) processed by the worker when the pool's `execution` function is invoked.
45 */
46 protected taskFunctions!: Map<string, WorkerFunction<Data, Response>>
729c563d
S
47 /**
48 * Timestamp of the last task processed by this worker.
49 */
a9d9ea34 50 protected lastTaskTimestamp!: number
b6b32453 51 /**
8a970421 52 * Performance statistics computation requirements.
b6b32453
JB
53 */
54 protected statistics!: WorkerStatistics
729c563d 55 /**
aee46736 56 * Handler id of the `aliveInterval` worker alive check.
729c563d 57 */
75d3401a 58 protected aliveInterval?: NodeJS.Timeout
c97c7edb 59 /**
729c563d 60 * Constructs a new poolifier worker.
c97c7edb 61 *
38e795c1
JB
62 * @param type - The type of async event.
63 * @param isMain - Whether this is the main worker or not.
82888165 64 * @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
65 * @param mainWorker - Reference to main worker.
66 * @param opts - Options for the worker.
c97c7edb
S
67 */
68 public constructor (
69 type: string,
c2ade475 70 protected readonly isMain: boolean,
a86b6df1
JB
71 taskFunctions:
72 | WorkerFunction<Data, Response>
73 | TaskFunctions<Data, Response>,
448ad581 74 protected readonly mainWorker: MainWorker,
d99ba5a8 75 protected readonly opts: WorkerOptions = {
e088a00c 76 /**
aee46736 77 * The kill behavior option on this worker or its default value.
e088a00c 78 */
1a81f8af 79 killBehavior: DEFAULT_KILL_BEHAVIOR,
e088a00c
JB
80 /**
81 * The maximum time to keep this worker alive while idle.
82 * The pool automatically checks and terminates this worker when the time expires.
83 */
1a81f8af 84 maxInactiveTime: DEFAULT_MAX_INACTIVE_TIME
4c35177b 85 }
c97c7edb
S
86 ) {
87 super(type)
e088a00c 88 this.checkWorkerOptions(this.opts)
a86b6df1 89 this.checkTaskFunctions(taskFunctions)
1f68cede 90 if (!this.isMain) {
3749facb 91 this.mainWorker?.on('message', this.messageListener.bind(this))
c97c7edb
S
92 }
93 }
94
41aa7dcd
JB
95 private checkWorkerOptions (opts: WorkerOptions): void {
96 this.opts.killBehavior = opts.killBehavior ?? DEFAULT_KILL_BEHAVIOR
97 this.opts.maxInactiveTime =
98 opts.maxInactiveTime ?? DEFAULT_MAX_INACTIVE_TIME
571227f4 99 delete this.opts.async
41aa7dcd
JB
100 }
101
102 /**
a86b6df1 103 * Checks if the `taskFunctions` parameter is passed to the constructor.
41aa7dcd 104 *
82888165 105 * @param taskFunctions - The task function(s) parameter that should be checked.
41aa7dcd 106 */
a86b6df1
JB
107 private checkTaskFunctions (
108 taskFunctions:
109 | WorkerFunction<Data, Response>
110 | TaskFunctions<Data, Response>
111 ): void {
ec8fd331
JB
112 if (taskFunctions == null) {
113 throw new Error('taskFunctions parameter is mandatory')
114 }
a86b6df1 115 this.taskFunctions = new Map<string, WorkerFunction<Data, Response>>()
0d80593b
JB
116 if (typeof taskFunctions === 'function') {
117 this.taskFunctions.set(DEFAULT_FUNCTION_NAME, taskFunctions.bind(this))
118 } else if (isPlainObject(taskFunctions)) {
82888165 119 let firstEntry = true
a86b6df1
JB
120 for (const [name, fn] of Object.entries(taskFunctions)) {
121 if (typeof fn !== 'function') {
0d80593b 122 throw new TypeError(
a86b6df1
JB
123 'A taskFunctions parameter object value is not a function'
124 )
125 }
126 this.taskFunctions.set(name, fn.bind(this))
82888165
JB
127 if (firstEntry) {
128 this.taskFunctions.set(DEFAULT_FUNCTION_NAME, fn.bind(this))
129 firstEntry = false
130 }
a86b6df1 131 }
630f0acf
JB
132 if (firstEntry) {
133 throw new Error('taskFunctions parameter object is empty')
134 }
a86b6df1 135 } else {
f34fdabe
JB
136 throw new TypeError(
137 'taskFunctions parameter is not a function or a plain object'
138 )
41aa7dcd
JB
139 }
140 }
141
aee46736
JB
142 /**
143 * Worker message listener.
144 *
145 * @param message - Message received.
aee46736 146 */
6677a3d3 147 protected messageListener (message: MessageValue<Data, Data>): void {
2431bdb4
JB
148 if (message.ready != null && message.workerId === this.id) {
149 // Startup message received
150 this.workerReady()
151 } else if (message.statistics != null) {
75d3401a
JB
152 // Statistics message received
153 this.statistics = message.statistics
48487131
JB
154 } else if (message.checkAlive != null) {
155 // Check alive message received
156 message.checkAlive ? this.startCheckAlive() : this.stopCheckAlive()
75d3401a 157 } else if (message.id != null && message.data != null) {
aee46736 158 // Task message received
c7c04698 159 const fn = this.getTaskFunction(message.name)
49d1b48c 160 if (isAsyncFunction(fn)) {
aee46736 161 this.runInAsyncScope(this.runAsync.bind(this), this, fn, message)
cf597bc5 162 } else {
70a4f5ea 163 this.runInAsyncScope(this.runSync.bind(this), this, fn, message)
cf597bc5 164 }
48487131 165 } else if (message.kill === true) {
aee46736 166 // Kill message received
48487131 167 this.stopCheckAlive()
cf597bc5
JB
168 this.emitDestroy()
169 }
170 }
171
2431bdb4
JB
172 /**
173 * Notifies the main worker that this worker is ready to process tasks.
174 */
175 protected workerReady (): void {
176 !this.isMain && this.sendToMainWorker({ ready: true, workerId: this.id })
177 }
178
48487131
JB
179 /**
180 * Starts the worker alive check interval.
181 */
75d3401a
JB
182 private startCheckAlive (): void {
183 this.lastTaskTimestamp = performance.now()
184 this.aliveInterval = setInterval(
185 this.checkAlive.bind(this),
186 (this.opts.maxInactiveTime ?? DEFAULT_MAX_INACTIVE_TIME) / 2
187 )
188 this.checkAlive.bind(this)()
189 }
190
48487131
JB
191 /**
192 * Stops the worker alive check interval.
193 */
194 private stopCheckAlive (): void {
195 this.aliveInterval != null && clearInterval(this.aliveInterval)
196 }
197
198 /**
199 * Checks if the worker should be terminated, because its living too long.
200 */
201 private checkAlive (): void {
202 if (
203 performance.now() - this.lastTaskTimestamp >
204 (this.opts.maxInactiveTime ?? DEFAULT_MAX_INACTIVE_TIME)
205 ) {
206 this.sendToMainWorker({ kill: this.opts.killBehavior })
207 }
208 }
209
729c563d
S
210 /**
211 * Returns the main worker.
838898f1
S
212 *
213 * @returns Reference to the main worker.
729c563d 214 */
838898f1 215 protected getMainWorker (): MainWorker {
78cea37e 216 if (this.mainWorker == null) {
e102732c 217 throw new Error('Main worker not set')
838898f1
S
218 }
219 return this.mainWorker
220 }
c97c7edb 221
729c563d 222 /**
8accb8d5 223 * Sends a message to the main worker.
729c563d 224 *
38e795c1 225 * @param message - The response message.
729c563d 226 */
82f36766
JB
227 protected abstract sendToMainWorker (
228 message: MessageValue<Response, Data>
229 ): void
c97c7edb 230
729c563d 231 /**
8accb8d5 232 * Handles an error and convert it to a string so it can be sent back to the main worker.
729c563d 233 *
38e795c1 234 * @param e - The error raised by the worker.
ab80dc46 235 * @returns The error message.
729c563d 236 */
c97c7edb 237 protected handleError (e: Error | string): string {
985d0e79 238 return e instanceof Error ? e.message : e
c97c7edb
S
239 }
240
729c563d 241 /**
8accb8d5 242 * Runs the given function synchronously.
729c563d 243 *
38e795c1 244 * @param fn - Function that will be executed.
aee46736 245 * @param message - Input data for the given function.
729c563d 246 */
70a4f5ea 247 protected runSync (
48ef9107 248 fn: WorkerSyncFunction<Data, Response>,
aee46736 249 message: MessageValue<Data>
c97c7edb
S
250 ): void {
251 try {
1c6fe997 252 let taskPerformance = this.beginTaskPerformance()
aee46736 253 const res = fn(message.data)
d715b7bc 254 taskPerformance = this.endTaskPerformance(taskPerformance)
3fafb1b2
JB
255 this.sendToMainWorker({
256 data: res,
d715b7bc 257 taskPerformance,
f59e1027 258 workerId: this.id,
91ee39ed 259 id: message.id
3fafb1b2 260 })
c97c7edb 261 } catch (e) {
985d0e79 262 const errorMessage = this.handleError(e as Error | string)
91ee39ed 263 this.sendToMainWorker({
82f36766 264 taskError: {
7ae6fb74 265 workerId: this.id,
985d0e79 266 message: errorMessage,
82f36766
JB
267 data: message.data
268 },
91ee39ed
JB
269 id: message.id
270 })
6e9d10db 271 } finally {
75d3401a
JB
272 if (!this.isMain && this.aliveInterval != null) {
273 this.lastTaskTimestamp = performance.now()
274 }
c97c7edb
S
275 }
276 }
277
729c563d 278 /**
8accb8d5 279 * Runs the given function asynchronously.
729c563d 280 *
38e795c1 281 * @param fn - Function that will be executed.
aee46736 282 * @param message - Input data for the given function.
729c563d 283 */
c97c7edb 284 protected runAsync (
48ef9107 285 fn: WorkerAsyncFunction<Data, Response>,
aee46736 286 message: MessageValue<Data>
c97c7edb 287 ): void {
1c6fe997 288 let taskPerformance = this.beginTaskPerformance()
aee46736 289 fn(message.data)
c97c7edb 290 .then(res => {
d715b7bc 291 taskPerformance = this.endTaskPerformance(taskPerformance)
3fafb1b2
JB
292 this.sendToMainWorker({
293 data: res,
d715b7bc 294 taskPerformance,
f59e1027 295 workerId: this.id,
91ee39ed 296 id: message.id
3fafb1b2 297 })
c97c7edb
S
298 return null
299 })
300 .catch(e => {
985d0e79 301 const errorMessage = this.handleError(e as Error | string)
91ee39ed 302 this.sendToMainWorker({
82f36766 303 taskError: {
7ae6fb74 304 workerId: this.id,
985d0e79 305 message: errorMessage,
82f36766
JB
306 data: message.data
307 },
91ee39ed
JB
308 id: message.id
309 })
6e9d10db
JB
310 })
311 .finally(() => {
75d3401a
JB
312 if (!this.isMain && this.aliveInterval != null) {
313 this.lastTaskTimestamp = performance.now()
314 }
c97c7edb 315 })
6e9d10db 316 .catch(EMPTY_FUNCTION)
c97c7edb 317 }
ec8fd331 318
82888165
JB
319 /**
320 * Gets the task function in the given scope.
321 *
322 * @param name - Name of the function that will be returned.
323 */
ec8fd331
JB
324 private getTaskFunction (name?: string): WorkerFunction<Data, Response> {
325 name = name ?? DEFAULT_FUNCTION_NAME
326 const fn = this.taskFunctions.get(name)
327 if (fn == null) {
ace229a1 328 throw new Error(`Task function '${name}' not found`)
ec8fd331
JB
329 }
330 return fn
331 }
62c15a68 332
1c6fe997 333 private beginTaskPerformance (): TaskPerformance {
8a970421 334 this.checkStatistics()
62c15a68 335 return {
1c6fe997 336 timestamp: performance.now(),
b6b32453 337 ...(this.statistics.elu && { elu: performance.eventLoopUtilization() })
62c15a68
JB
338 }
339 }
340
d9d31201
JB
341 private endTaskPerformance (
342 taskPerformance: TaskPerformance
343 ): TaskPerformance {
8a970421 344 this.checkStatistics()
62c15a68
JB
345 return {
346 ...taskPerformance,
b6b32453
JB
347 ...(this.statistics.runTime && {
348 runTime: performance.now() - taskPerformance.timestamp
349 }),
350 ...(this.statistics.elu && {
62c15a68 351 elu: performance.eventLoopUtilization(taskPerformance.elu)
b6b32453 352 })
62c15a68
JB
353 }
354 }
8a970421
JB
355
356 private checkStatistics (): void {
357 if (this.statistics == null) {
358 throw new Error('Performance statistics computation requirements not set')
359 }
360 }
c97c7edb 361}