feat: internal messaging strict worker id checking
[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()
21f710aa 151 } else if (message.statistics != null && message.workerId === this.id) {
75d3401a
JB
152 // Statistics message received
153 this.statistics = message.statistics
21f710aa 154 } else if (message.checkAlive != null && message.workerId === this.id) {
48487131
JB
155 // Check alive message received
156 message.checkAlive ? this.startCheckAlive() : this.stopCheckAlive()
21f710aa
JB
157 } else if (
158 message.id != null &&
159 message.data != null &&
160 message.workerId === this.id
161 ) {
aee46736 162 // Task message received
c7c04698 163 const fn = this.getTaskFunction(message.name)
49d1b48c 164 if (isAsyncFunction(fn)) {
aee46736 165 this.runInAsyncScope(this.runAsync.bind(this), this, fn, message)
cf597bc5 166 } else {
70a4f5ea 167 this.runInAsyncScope(this.runSync.bind(this), this, fn, message)
cf597bc5 168 }
21f710aa 169 } else if (message.kill === true && message.workerId === this.id) {
aee46736 170 // Kill message received
48487131 171 this.stopCheckAlive()
cf597bc5
JB
172 this.emitDestroy()
173 }
174 }
175
2431bdb4
JB
176 /**
177 * Notifies the main worker that this worker is ready to process tasks.
178 */
179 protected workerReady (): void {
180 !this.isMain && this.sendToMainWorker({ ready: true, workerId: this.id })
181 }
182
48487131
JB
183 /**
184 * Starts the worker alive check interval.
185 */
75d3401a
JB
186 private startCheckAlive (): void {
187 this.lastTaskTimestamp = performance.now()
188 this.aliveInterval = setInterval(
189 this.checkAlive.bind(this),
190 (this.opts.maxInactiveTime ?? DEFAULT_MAX_INACTIVE_TIME) / 2
191 )
192 this.checkAlive.bind(this)()
193 }
194
48487131
JB
195 /**
196 * Stops the worker alive check interval.
197 */
198 private stopCheckAlive (): void {
199 this.aliveInterval != null && clearInterval(this.aliveInterval)
200 }
201
202 /**
203 * Checks if the worker should be terminated, because its living too long.
204 */
205 private checkAlive (): void {
206 if (
207 performance.now() - this.lastTaskTimestamp >
208 (this.opts.maxInactiveTime ?? DEFAULT_MAX_INACTIVE_TIME)
209 ) {
21f710aa 210 this.sendToMainWorker({ kill: this.opts.killBehavior, workerId: this.id })
48487131
JB
211 }
212 }
213
729c563d
S
214 /**
215 * Returns the main worker.
838898f1
S
216 *
217 * @returns Reference to the main worker.
729c563d 218 */
838898f1 219 protected getMainWorker (): MainWorker {
78cea37e 220 if (this.mainWorker == null) {
e102732c 221 throw new Error('Main worker not set')
838898f1
S
222 }
223 return this.mainWorker
224 }
c97c7edb 225
729c563d 226 /**
8accb8d5 227 * Sends a message to the main worker.
729c563d 228 *
38e795c1 229 * @param message - The response message.
729c563d 230 */
82f36766
JB
231 protected abstract sendToMainWorker (
232 message: MessageValue<Response, Data>
233 ): void
c97c7edb 234
729c563d 235 /**
8accb8d5 236 * Handles an error and convert it to a string so it can be sent back to the main worker.
729c563d 237 *
38e795c1 238 * @param e - The error raised by the worker.
ab80dc46 239 * @returns The error message.
729c563d 240 */
c97c7edb 241 protected handleError (e: Error | string): string {
985d0e79 242 return e instanceof Error ? e.message : e
c97c7edb
S
243 }
244
729c563d 245 /**
8accb8d5 246 * Runs the given function synchronously.
729c563d 247 *
38e795c1 248 * @param fn - Function that will be executed.
aee46736 249 * @param message - Input data for the given function.
729c563d 250 */
70a4f5ea 251 protected runSync (
48ef9107 252 fn: WorkerSyncFunction<Data, Response>,
aee46736 253 message: MessageValue<Data>
c97c7edb
S
254 ): void {
255 try {
1c6fe997 256 let taskPerformance = this.beginTaskPerformance()
aee46736 257 const res = fn(message.data)
d715b7bc 258 taskPerformance = this.endTaskPerformance(taskPerformance)
3fafb1b2
JB
259 this.sendToMainWorker({
260 data: res,
d715b7bc 261 taskPerformance,
f59e1027 262 workerId: this.id,
91ee39ed 263 id: message.id
3fafb1b2 264 })
c97c7edb 265 } catch (e) {
985d0e79 266 const errorMessage = this.handleError(e as Error | string)
91ee39ed 267 this.sendToMainWorker({
82f36766 268 taskError: {
985d0e79 269 message: errorMessage,
82f36766
JB
270 data: message.data
271 },
21f710aa 272 workerId: this.id,
91ee39ed
JB
273 id: message.id
274 })
6e9d10db 275 } finally {
75d3401a
JB
276 if (!this.isMain && this.aliveInterval != null) {
277 this.lastTaskTimestamp = performance.now()
278 }
c97c7edb
S
279 }
280 }
281
729c563d 282 /**
8accb8d5 283 * Runs the given function asynchronously.
729c563d 284 *
38e795c1 285 * @param fn - Function that will be executed.
aee46736 286 * @param message - Input data for the given function.
729c563d 287 */
c97c7edb 288 protected runAsync (
48ef9107 289 fn: WorkerAsyncFunction<Data, Response>,
aee46736 290 message: MessageValue<Data>
c97c7edb 291 ): void {
1c6fe997 292 let taskPerformance = this.beginTaskPerformance()
aee46736 293 fn(message.data)
c97c7edb 294 .then(res => {
d715b7bc 295 taskPerformance = this.endTaskPerformance(taskPerformance)
3fafb1b2
JB
296 this.sendToMainWorker({
297 data: res,
d715b7bc 298 taskPerformance,
f59e1027 299 workerId: this.id,
91ee39ed 300 id: message.id
3fafb1b2 301 })
c97c7edb
S
302 return null
303 })
304 .catch(e => {
985d0e79 305 const errorMessage = this.handleError(e as Error | string)
91ee39ed 306 this.sendToMainWorker({
82f36766 307 taskError: {
985d0e79 308 message: errorMessage,
82f36766
JB
309 data: message.data
310 },
21f710aa 311 workerId: this.id,
91ee39ed
JB
312 id: message.id
313 })
6e9d10db
JB
314 })
315 .finally(() => {
75d3401a
JB
316 if (!this.isMain && this.aliveInterval != null) {
317 this.lastTaskTimestamp = performance.now()
318 }
c97c7edb 319 })
6e9d10db 320 .catch(EMPTY_FUNCTION)
c97c7edb 321 }
ec8fd331 322
82888165
JB
323 /**
324 * Gets the task function in the given scope.
325 *
326 * @param name - Name of the function that will be returned.
327 */
ec8fd331
JB
328 private getTaskFunction (name?: string): WorkerFunction<Data, Response> {
329 name = name ?? DEFAULT_FUNCTION_NAME
330 const fn = this.taskFunctions.get(name)
331 if (fn == null) {
ace229a1 332 throw new Error(`Task function '${name}' not found`)
ec8fd331
JB
333 }
334 return fn
335 }
62c15a68 336
1c6fe997 337 private beginTaskPerformance (): TaskPerformance {
8a970421 338 this.checkStatistics()
62c15a68 339 return {
1c6fe997 340 timestamp: performance.now(),
b6b32453 341 ...(this.statistics.elu && { elu: performance.eventLoopUtilization() })
62c15a68
JB
342 }
343 }
344
d9d31201
JB
345 private endTaskPerformance (
346 taskPerformance: TaskPerformance
347 ): TaskPerformance {
8a970421 348 this.checkStatistics()
62c15a68
JB
349 return {
350 ...taskPerformance,
b6b32453
JB
351 ...(this.statistics.runTime && {
352 runTime: performance.now() - taskPerformance.timestamp
353 }),
354 ...(this.statistics.elu && {
62c15a68 355 elu: performance.eventLoopUtilization(taskPerformance.elu)
b6b32453 356 })
62c15a68
JB
357 }
358 }
8a970421
JB
359
360 private checkStatistics (): void {
361 if (this.statistics == null) {
362 throw new Error('Performance statistics computation requirements not set')
363 }
364 }
c97c7edb 365}