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