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