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