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' | |
a86b6df1 JB |
4 | import { |
5 | type MessageValue, | |
6 | type TaskFunctions, | |
7 | type WorkerAsyncFunction, | |
8 | type WorkerFunction, | |
9 | type WorkerSyncFunction | |
48ef9107 | 10 | } from '../utility-types' |
6e9d10db | 11 | import { EMPTY_FUNCTION } from '../utils' |
5919b303 | 12 | import type { KillBehavior, WorkerOptions } from './worker-options' |
1a81f8af | 13 | import { KillBehaviors } from './worker-options' |
4c35177b | 14 | |
ec8fd331 | 15 | const DEFAULT_FUNCTION_NAME = 'default' |
978aad6f | 16 | const DEFAULT_MAX_INACTIVE_TIME = 60000 |
1a81f8af | 17 | const 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 | 26 | export 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. | |
a86b6df1 | 48 | * @param taskFunctions - Task function(s) processed by the worker when the pool's `execution` function is invoked. |
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) |
7c24d88b | 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 | |
aee46736 JB |
83 | this.mainWorker?.on( |
84 | 'message', | |
85 | (message: MessageValue<Data, MainWorker>) => { | |
a86b6df1 | 86 | this.messageListener(message) |
aee46736 JB |
87 | } |
88 | ) | |
c97c7edb S |
89 | } |
90 | ||
41aa7dcd JB |
91 | private checkWorkerOptions (opts: WorkerOptions): void { |
92 | this.opts.killBehavior = opts.killBehavior ?? DEFAULT_KILL_BEHAVIOR | |
93 | this.opts.maxInactiveTime = | |
94 | opts.maxInactiveTime ?? DEFAULT_MAX_INACTIVE_TIME | |
95 | this.opts.async = opts.async ?? false | |
96 | } | |
97 | ||
98 | /** | |
a86b6df1 | 99 | * Checks if the `taskFunctions` parameter is passed to the constructor. |
41aa7dcd | 100 | * |
a86b6df1 | 101 | * @param taskFunctions - The task function(s) that should be defined. |
41aa7dcd | 102 | */ |
a86b6df1 JB |
103 | private checkTaskFunctions ( |
104 | taskFunctions: | |
105 | | WorkerFunction<Data, Response> | |
106 | | TaskFunctions<Data, Response> | |
107 | ): void { | |
ec8fd331 JB |
108 | if (taskFunctions == null) { |
109 | throw new Error('taskFunctions parameter is mandatory') | |
110 | } | |
a86b6df1 JB |
111 | if ( |
112 | typeof taskFunctions !== 'function' && | |
113 | typeof taskFunctions !== 'object' | |
114 | ) { | |
115 | throw new Error('taskFunctions parameter is not a function or an object') | |
41aa7dcd | 116 | } |
a86b6df1 JB |
117 | if ( |
118 | typeof taskFunctions === 'object' && | |
119 | taskFunctions.constructor !== Object && | |
120 | Object.prototype.toString.call(taskFunctions) !== '[object Object]' | |
121 | ) { | |
122 | throw new Error('taskFunctions parameter is not an object literal') | |
123 | } | |
124 | this.taskFunctions = new Map<string, WorkerFunction<Data, Response>>() | |
125 | if (typeof taskFunctions !== 'function') { | |
126 | for (const [name, fn] of Object.entries(taskFunctions)) { | |
127 | if (typeof fn !== 'function') { | |
128 | throw new Error( | |
129 | 'A taskFunctions parameter object value is not a function' | |
130 | ) | |
131 | } | |
132 | this.taskFunctions.set(name, fn.bind(this)) | |
133 | } | |
134 | } else { | |
ec8fd331 | 135 | this.taskFunctions.set(DEFAULT_FUNCTION_NAME, taskFunctions.bind(this)) |
41aa7dcd JB |
136 | } |
137 | } | |
138 | ||
aee46736 JB |
139 | /** |
140 | * Worker message listener. | |
141 | * | |
142 | * @param message - Message received. | |
aee46736 | 143 | */ |
a86b6df1 | 144 | protected messageListener (message: MessageValue<Data, MainWorker>): void { |
a3f5f781 | 145 | if (message.id != null && message.data != null) { |
aee46736 | 146 | // Task message received |
c7c04698 | 147 | const fn = this.getTaskFunction(message.name) |
a86b6df1 | 148 | if (fn?.constructor.name === 'AsyncFunction') { |
aee46736 | 149 | this.runInAsyncScope(this.runAsync.bind(this), this, fn, message) |
cf597bc5 | 150 | } else { |
aee46736 | 151 | this.runInAsyncScope(this.run.bind(this), this, fn, message) |
cf597bc5 | 152 | } |
aee46736 JB |
153 | } else if (message.parent != null) { |
154 | // Main worker reference message received | |
155 | this.mainWorker = message.parent | |
156 | } else if (message.kill != null) { | |
157 | // Kill message received | |
73cff87e | 158 | this.aliveInterval != null && clearInterval(this.aliveInterval) |
cf597bc5 JB |
159 | this.emitDestroy() |
160 | } | |
161 | } | |
162 | ||
729c563d S |
163 | /** |
164 | * Returns the main worker. | |
838898f1 S |
165 | * |
166 | * @returns Reference to the main worker. | |
729c563d | 167 | */ |
838898f1 | 168 | protected getMainWorker (): MainWorker { |
78cea37e | 169 | if (this.mainWorker == null) { |
838898f1 S |
170 | throw new Error('Main worker was not set') |
171 | } | |
172 | return this.mainWorker | |
173 | } | |
c97c7edb | 174 | |
729c563d | 175 | /** |
8accb8d5 | 176 | * Sends a message to the main worker. |
729c563d | 177 | * |
38e795c1 | 178 | * @param message - The response message. |
729c563d | 179 | */ |
c97c7edb S |
180 | protected abstract sendToMainWorker (message: MessageValue<Response>): void |
181 | ||
729c563d | 182 | /** |
a05c10de | 183 | * Checks if the worker should be terminated, because its living too long. |
729c563d | 184 | */ |
c97c7edb | 185 | protected checkAlive (): void { |
e088a00c | 186 | if ( |
3fafb1b2 | 187 | performance.now() - this.lastTaskTimestamp > |
e088a00c JB |
188 | (this.opts.maxInactiveTime ?? DEFAULT_MAX_INACTIVE_TIME) |
189 | ) { | |
190 | this.sendToMainWorker({ kill: this.opts.killBehavior }) | |
c97c7edb S |
191 | } |
192 | } | |
193 | ||
729c563d | 194 | /** |
8accb8d5 | 195 | * Handles an error and convert it to a string so it can be sent back to the main worker. |
729c563d | 196 | * |
38e795c1 | 197 | * @param e - The error raised by the worker. |
50eceb07 | 198 | * @returns Message of the error. |
729c563d | 199 | */ |
c97c7edb | 200 | protected handleError (e: Error | string): string { |
4a34343d | 201 | return e as string |
c97c7edb S |
202 | } |
203 | ||
729c563d | 204 | /** |
8accb8d5 | 205 | * Runs the given function synchronously. |
729c563d | 206 | * |
38e795c1 | 207 | * @param fn - Function that will be executed. |
aee46736 | 208 | * @param message - Input data for the given function. |
729c563d | 209 | */ |
c97c7edb | 210 | protected run ( |
48ef9107 | 211 | fn: WorkerSyncFunction<Data, Response>, |
aee46736 | 212 | message: MessageValue<Data> |
c97c7edb S |
213 | ): void { |
214 | try { | |
3fafb1b2 | 215 | const startTimestamp = performance.now() |
aee46736 | 216 | const res = fn(message.data) |
3fafb1b2 JB |
217 | const runTime = performance.now() - startTimestamp |
218 | this.sendToMainWorker({ | |
219 | data: res, | |
220 | id: message.id, | |
221 | runTime | |
222 | }) | |
c97c7edb | 223 | } catch (e) { |
0a23f635 | 224 | const err = this.handleError(e as Error) |
aee46736 | 225 | this.sendToMainWorker({ error: err, id: message.id }) |
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() |
aee46736 | 242 | fn(message.data) |
c97c7edb | 243 | .then(res => { |
3fafb1b2 JB |
244 | const runTime = performance.now() - startTimestamp |
245 | this.sendToMainWorker({ | |
246 | data: res, | |
247 | id: message.id, | |
248 | runTime | |
249 | }) | |
c97c7edb S |
250 | return null |
251 | }) | |
252 | .catch(e => { | |
f3636726 | 253 | const err = this.handleError(e as Error) |
aee46736 | 254 | this.sendToMainWorker({ error: err, id: message.id }) |
6e9d10db JB |
255 | }) |
256 | .finally(() => { | |
3fafb1b2 | 257 | !this.isMain && (this.lastTaskTimestamp = performance.now()) |
c97c7edb | 258 | }) |
6e9d10db | 259 | .catch(EMPTY_FUNCTION) |
c97c7edb | 260 | } |
ec8fd331 JB |
261 | |
262 | private getTaskFunction (name?: string): WorkerFunction<Data, Response> { | |
263 | name = name ?? DEFAULT_FUNCTION_NAME | |
264 | const fn = this.taskFunctions.get(name) | |
265 | if (fn == null) { | |
266 | throw new Error(`Task function "${name}" not found`) | |
267 | } | |
268 | return fn | |
269 | } | |
c97c7edb | 270 | } |