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