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