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