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