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