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