Commit | Line | Data |
---|---|---|
fc3e6586 JB |
1 | import { AsyncResource } from 'node:async_hooks' |
2 | import type { Worker } from 'node:cluster' | |
3 | import type { MessagePort } from 'node:worker_threads' | |
62c15a68 | 4 | import { type EventLoopUtilization, performance } from 'node:perf_hooks' |
b6b32453 | 5 | import type { MessageValue, WorkerStatistics } from '../utility-types' |
0d80593b | 6 | import { EMPTY_FUNCTION, isPlainObject } from '../utils' |
241f23c2 JB |
7 | import { |
8 | type KillBehavior, | |
9 | KillBehaviors, | |
10 | type WorkerOptions | |
11 | } from './worker-options' | |
b6b32453 JB |
12 | import type { |
13 | TaskFunctions, | |
14 | WorkerAsyncFunction, | |
15 | WorkerFunction, | |
16 | WorkerSyncFunction | |
17 | } from './worker-functions' | |
4c35177b | 18 | |
ec8fd331 | 19 | const DEFAULT_FUNCTION_NAME = 'default' |
978aad6f | 20 | const DEFAULT_MAX_INACTIVE_TIME = 60000 |
1a81f8af | 21 | const DEFAULT_KILL_BEHAVIOR: KillBehavior = KillBehaviors.SOFT |
c97c7edb | 22 | |
b6b32453 JB |
23 | /** |
24 | * Task performance. | |
25 | */ | |
62c15a68 JB |
26 | interface 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 | 40 | export 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 { | |
d9d31201 | 229 | const taskPerformance = this.beginTaskPerformance(message) |
aee46736 | 230 | const res = fn(message.data) |
d9d31201 JB |
231 | const { runTime, waitTime, elu } = |
232 | this.endTaskPerformance(taskPerformance) | |
3fafb1b2 JB |
233 | this.sendToMainWorker({ |
234 | data: res, | |
09a6305f | 235 | runTime, |
91ee39ed | 236 | waitTime, |
62c15a68 | 237 | elu, |
91ee39ed | 238 | id: message.id |
3fafb1b2 | 239 | }) |
c97c7edb | 240 | } catch (e) { |
0a23f635 | 241 | const err = this.handleError(e as Error) |
91ee39ed JB |
242 | this.sendToMainWorker({ |
243 | error: err, | |
244 | errorData: message.data, | |
245 | id: message.id | |
246 | }) | |
6e9d10db | 247 | } finally { |
3fafb1b2 | 248 | !this.isMain && (this.lastTaskTimestamp = performance.now()) |
c97c7edb S |
249 | } |
250 | } | |
251 | ||
729c563d | 252 | /** |
8accb8d5 | 253 | * Runs the given function asynchronously. |
729c563d | 254 | * |
38e795c1 | 255 | * @param fn - Function that will be executed. |
aee46736 | 256 | * @param message - Input data for the given function. |
729c563d | 257 | */ |
c97c7edb | 258 | protected runAsync ( |
48ef9107 | 259 | fn: WorkerAsyncFunction<Data, Response>, |
aee46736 | 260 | message: MessageValue<Data> |
c97c7edb | 261 | ): void { |
d9d31201 | 262 | const taskPerformance = this.beginTaskPerformance(message) |
aee46736 | 263 | fn(message.data) |
c97c7edb | 264 | .then(res => { |
62c15a68 | 265 | const { runTime, waitTime, elu } = |
d9d31201 | 266 | this.endTaskPerformance(taskPerformance) |
3fafb1b2 JB |
267 | this.sendToMainWorker({ |
268 | data: res, | |
09a6305f | 269 | runTime, |
91ee39ed | 270 | waitTime, |
62c15a68 | 271 | elu, |
91ee39ed | 272 | id: message.id |
3fafb1b2 | 273 | }) |
c97c7edb S |
274 | return null |
275 | }) | |
276 | .catch(e => { | |
f3636726 | 277 | const err = this.handleError(e as Error) |
91ee39ed JB |
278 | this.sendToMainWorker({ |
279 | error: err, | |
280 | errorData: message.data, | |
281 | id: message.id | |
282 | }) | |
6e9d10db JB |
283 | }) |
284 | .finally(() => { | |
3fafb1b2 | 285 | !this.isMain && (this.lastTaskTimestamp = performance.now()) |
c97c7edb | 286 | }) |
6e9d10db | 287 | .catch(EMPTY_FUNCTION) |
c97c7edb | 288 | } |
ec8fd331 | 289 | |
82888165 JB |
290 | /** |
291 | * Gets the task function in the given scope. | |
292 | * | |
293 | * @param name - Name of the function that will be returned. | |
294 | */ | |
ec8fd331 JB |
295 | private getTaskFunction (name?: string): WorkerFunction<Data, Response> { |
296 | name = name ?? DEFAULT_FUNCTION_NAME | |
297 | const fn = this.taskFunctions.get(name) | |
298 | if (fn == null) { | |
ace229a1 | 299 | throw new Error(`Task function '${name}' not found`) |
ec8fd331 JB |
300 | } |
301 | return fn | |
302 | } | |
62c15a68 | 303 | |
d9d31201 | 304 | private beginTaskPerformance (message: MessageValue<Data>): TaskPerformance { |
62c15a68 JB |
305 | const timestamp = performance.now() |
306 | return { | |
307 | timestamp, | |
b6b32453 JB |
308 | ...(this.statistics.waitTime && { |
309 | waitTime: timestamp - (message.timestamp ?? timestamp) | |
310 | }), | |
311 | ...(this.statistics.elu && { elu: performance.eventLoopUtilization() }) | |
62c15a68 JB |
312 | } |
313 | } | |
314 | ||
d9d31201 JB |
315 | private endTaskPerformance ( |
316 | taskPerformance: TaskPerformance | |
317 | ): TaskPerformance { | |
62c15a68 JB |
318 | return { |
319 | ...taskPerformance, | |
b6b32453 JB |
320 | ...(this.statistics.runTime && { |
321 | runTime: performance.now() - taskPerformance.timestamp | |
322 | }), | |
323 | ...(this.statistics.elu && { | |
62c15a68 | 324 | elu: performance.eventLoopUtilization(taskPerformance.elu) |
b6b32453 | 325 | }) |
62c15a68 JB |
326 | } |
327 | } | |
c97c7edb | 328 | } |