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