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 | |
978aad6f | 15 | const DEFAULT_MAX_INACTIVE_TIME = 60000 |
1a81f8af | 16 | const DEFAULT_KILL_BEHAVIOR: KillBehavior = KillBehaviors.SOFT |
c97c7edb | 17 | |
729c563d | 18 | /** |
ea7a90d3 | 19 | * Base class that implements some shared logic for all poolifier workers. |
729c563d | 20 | * |
38e795c1 JB |
21 | * @typeParam MainWorker - Type of main worker. |
22 | * @typeParam Data - Type of data this worker receives from pool's execution. This can only be serializable data. | |
23 | * @typeParam Response - Type of response the worker sends back to the main worker. This can only be serializable data. | |
729c563d | 24 | */ |
c97c7edb | 25 | export abstract class AbstractWorker< |
838898f1 | 26 | MainWorker extends Worker | MessagePort, |
d3c8a1a8 S |
27 | Data = unknown, |
28 | Response = unknown | |
c97c7edb | 29 | > extends AsyncResource { |
a86b6df1 JB |
30 | /** |
31 | * Task function(s) processed by the worker when the pool's `execution` function is invoked. | |
32 | */ | |
33 | protected taskFunctions!: Map<string, WorkerFunction<Data, Response>> | |
729c563d S |
34 | /** |
35 | * Timestamp of the last task processed by this worker. | |
36 | */ | |
a9d9ea34 | 37 | protected lastTaskTimestamp!: number |
729c563d | 38 | /** |
aee46736 | 39 | * Handler id of the `aliveInterval` worker alive check. |
729c563d | 40 | */ |
e088a00c | 41 | protected readonly aliveInterval?: NodeJS.Timeout |
c97c7edb | 42 | /** |
729c563d | 43 | * Constructs a new poolifier worker. |
c97c7edb | 44 | * |
38e795c1 JB |
45 | * @param type - The type of async event. |
46 | * @param isMain - Whether this is the main worker or not. | |
a86b6df1 | 47 | * @param taskFunctions - Task function(s) processed by the worker when the pool's `execution` function is invoked. |
38e795c1 JB |
48 | * @param mainWorker - Reference to main worker. |
49 | * @param opts - Options for the worker. | |
c97c7edb S |
50 | */ |
51 | public constructor ( | |
52 | type: string, | |
c2ade475 | 53 | protected readonly isMain: boolean, |
a86b6df1 JB |
54 | taskFunctions: |
55 | | WorkerFunction<Data, Response> | |
56 | | TaskFunctions<Data, Response>, | |
7e0d447f | 57 | protected mainWorker: MainWorker | undefined | null, |
d99ba5a8 | 58 | protected readonly opts: WorkerOptions = { |
e088a00c | 59 | /** |
aee46736 | 60 | * The kill behavior option on this worker or its default value. |
e088a00c | 61 | */ |
1a81f8af | 62 | killBehavior: DEFAULT_KILL_BEHAVIOR, |
e088a00c JB |
63 | /** |
64 | * The maximum time to keep this worker alive while idle. | |
65 | * The pool automatically checks and terminates this worker when the time expires. | |
66 | */ | |
1a81f8af | 67 | maxInactiveTime: DEFAULT_MAX_INACTIVE_TIME |
4c35177b | 68 | } |
c97c7edb S |
69 | ) { |
70 | super(type) | |
e088a00c | 71 | this.checkWorkerOptions(this.opts) |
a86b6df1 | 72 | this.checkTaskFunctions(taskFunctions) |
7c24d88b | 73 | if (!this.isMain) { |
3fafb1b2 | 74 | this.lastTaskTimestamp = performance.now() |
e088a00c | 75 | this.aliveInterval = setInterval( |
c97c7edb | 76 | this.checkAlive.bind(this), |
e088a00c | 77 | (this.opts.maxInactiveTime ?? DEFAULT_MAX_INACTIVE_TIME) / 2 |
c97c7edb S |
78 | ) |
79 | this.checkAlive.bind(this)() | |
80 | } | |
838898f1 | 81 | |
aee46736 JB |
82 | this.mainWorker?.on( |
83 | 'message', | |
84 | (message: MessageValue<Data, MainWorker>) => { | |
a86b6df1 | 85 | this.messageListener(message) |
aee46736 JB |
86 | } |
87 | ) | |
c97c7edb S |
88 | } |
89 | ||
41aa7dcd JB |
90 | private checkWorkerOptions (opts: WorkerOptions): void { |
91 | this.opts.killBehavior = opts.killBehavior ?? DEFAULT_KILL_BEHAVIOR | |
92 | this.opts.maxInactiveTime = | |
93 | opts.maxInactiveTime ?? DEFAULT_MAX_INACTIVE_TIME | |
94 | this.opts.async = opts.async ?? false | |
95 | } | |
96 | ||
97 | /** | |
a86b6df1 | 98 | * Checks if the `taskFunctions` parameter is passed to the constructor. |
41aa7dcd | 99 | * |
a86b6df1 | 100 | * @param taskFunctions - The task function(s) that should be defined. |
41aa7dcd | 101 | */ |
a86b6df1 JB |
102 | private checkTaskFunctions ( |
103 | taskFunctions: | |
104 | | WorkerFunction<Data, Response> | |
105 | | TaskFunctions<Data, Response> | |
106 | ): void { | |
107 | if (taskFunctions == null) { throw new Error('taskFunctions parameter is mandatory') } | |
108 | if ( | |
109 | typeof taskFunctions !== 'function' && | |
110 | typeof taskFunctions !== 'object' | |
111 | ) { | |
112 | throw new Error('taskFunctions parameter is not a function or an object') | |
41aa7dcd | 113 | } |
a86b6df1 JB |
114 | if ( |
115 | typeof taskFunctions === 'object' && | |
116 | taskFunctions.constructor !== Object && | |
117 | Object.prototype.toString.call(taskFunctions) !== '[object Object]' | |
118 | ) { | |
119 | throw new Error('taskFunctions parameter is not an object literal') | |
120 | } | |
121 | this.taskFunctions = new Map<string, WorkerFunction<Data, Response>>() | |
122 | if (typeof taskFunctions !== 'function') { | |
123 | for (const [name, fn] of Object.entries(taskFunctions)) { | |
124 | if (typeof fn !== 'function') { | |
125 | throw new Error( | |
126 | 'A taskFunctions parameter object value is not a function' | |
127 | ) | |
128 | } | |
129 | this.taskFunctions.set(name, fn.bind(this)) | |
130 | } | |
131 | } else { | |
132 | this.taskFunctions.set('default', taskFunctions.bind(this)) | |
41aa7dcd JB |
133 | } |
134 | } | |
135 | ||
aee46736 JB |
136 | /** |
137 | * Worker message listener. | |
138 | * | |
139 | * @param message - Message received. | |
aee46736 | 140 | */ |
a86b6df1 | 141 | protected messageListener (message: MessageValue<Data, MainWorker>): void { |
a3f5f781 | 142 | if (message.id != null && message.data != null) { |
a86b6df1 JB |
143 | let fn: WorkerFunction<Data, Response> | undefined |
144 | if (message.name == null) { | |
145 | fn = this.taskFunctions.get('default') | |
146 | } else { | |
147 | fn = this.taskFunctions.get(message.name) | |
148 | } | |
aee46736 | 149 | // Task message received |
a86b6df1 | 150 | if (fn?.constructor.name === 'AsyncFunction') { |
aee46736 | 151 | this.runInAsyncScope(this.runAsync.bind(this), this, fn, message) |
cf597bc5 | 152 | } else { |
aee46736 | 153 | this.runInAsyncScope(this.run.bind(this), this, fn, message) |
cf597bc5 | 154 | } |
aee46736 JB |
155 | } else if (message.parent != null) { |
156 | // Main worker reference message received | |
157 | this.mainWorker = message.parent | |
158 | } else if (message.kill != null) { | |
159 | // Kill message received | |
73cff87e | 160 | this.aliveInterval != null && clearInterval(this.aliveInterval) |
cf597bc5 JB |
161 | this.emitDestroy() |
162 | } | |
163 | } | |
164 | ||
729c563d S |
165 | /** |
166 | * Returns the main worker. | |
838898f1 S |
167 | * |
168 | * @returns Reference to the main worker. | |
729c563d | 169 | */ |
838898f1 | 170 | protected getMainWorker (): MainWorker { |
78cea37e | 171 | if (this.mainWorker == null) { |
838898f1 S |
172 | throw new Error('Main worker was not set') |
173 | } | |
174 | return this.mainWorker | |
175 | } | |
c97c7edb | 176 | |
729c563d | 177 | /** |
8accb8d5 | 178 | * Sends a message to the main worker. |
729c563d | 179 | * |
38e795c1 | 180 | * @param message - The response message. |
729c563d | 181 | */ |
c97c7edb S |
182 | protected abstract sendToMainWorker (message: MessageValue<Response>): void |
183 | ||
729c563d | 184 | /** |
a05c10de | 185 | * Checks if the worker should be terminated, because its living too long. |
729c563d | 186 | */ |
c97c7edb | 187 | protected checkAlive (): void { |
e088a00c | 188 | if ( |
3fafb1b2 | 189 | performance.now() - this.lastTaskTimestamp > |
e088a00c JB |
190 | (this.opts.maxInactiveTime ?? DEFAULT_MAX_INACTIVE_TIME) |
191 | ) { | |
192 | this.sendToMainWorker({ kill: this.opts.killBehavior }) | |
c97c7edb S |
193 | } |
194 | } | |
195 | ||
729c563d | 196 | /** |
8accb8d5 | 197 | * Handles an error and convert it to a string so it can be sent back to the main worker. |
729c563d | 198 | * |
38e795c1 | 199 | * @param e - The error raised by the worker. |
50eceb07 | 200 | * @returns Message of the error. |
729c563d | 201 | */ |
c97c7edb | 202 | protected handleError (e: Error | string): string { |
4a34343d | 203 | return e as string |
c97c7edb S |
204 | } |
205 | ||
729c563d | 206 | /** |
8accb8d5 | 207 | * Runs the given function synchronously. |
729c563d | 208 | * |
38e795c1 | 209 | * @param fn - Function that will be executed. |
aee46736 | 210 | * @param message - Input data for the given function. |
729c563d | 211 | */ |
c97c7edb | 212 | protected run ( |
48ef9107 | 213 | fn: WorkerSyncFunction<Data, Response>, |
aee46736 | 214 | message: MessageValue<Data> |
c97c7edb S |
215 | ): void { |
216 | try { | |
3fafb1b2 | 217 | const startTimestamp = performance.now() |
aee46736 | 218 | const res = fn(message.data) |
3fafb1b2 JB |
219 | const runTime = performance.now() - startTimestamp |
220 | this.sendToMainWorker({ | |
221 | data: res, | |
222 | id: message.id, | |
223 | runTime | |
224 | }) | |
c97c7edb | 225 | } catch (e) { |
0a23f635 | 226 | const err = this.handleError(e as Error) |
aee46736 | 227 | this.sendToMainWorker({ error: err, id: message.id }) |
6e9d10db | 228 | } finally { |
3fafb1b2 | 229 | !this.isMain && (this.lastTaskTimestamp = performance.now()) |
c97c7edb S |
230 | } |
231 | } | |
232 | ||
729c563d | 233 | /** |
8accb8d5 | 234 | * Runs the given function asynchronously. |
729c563d | 235 | * |
38e795c1 | 236 | * @param fn - Function that will be executed. |
aee46736 | 237 | * @param message - Input data for the given function. |
729c563d | 238 | */ |
c97c7edb | 239 | protected runAsync ( |
48ef9107 | 240 | fn: WorkerAsyncFunction<Data, Response>, |
aee46736 | 241 | message: MessageValue<Data> |
c97c7edb | 242 | ): void { |
3fafb1b2 | 243 | const startTimestamp = performance.now() |
aee46736 | 244 | fn(message.data) |
c97c7edb | 245 | .then(res => { |
3fafb1b2 JB |
246 | const runTime = performance.now() - startTimestamp |
247 | this.sendToMainWorker({ | |
248 | data: res, | |
249 | id: message.id, | |
250 | runTime | |
251 | }) | |
c97c7edb S |
252 | return null |
253 | }) | |
254 | .catch(e => { | |
f3636726 | 255 | const err = this.handleError(e as Error) |
aee46736 | 256 | this.sendToMainWorker({ error: err, id: message.id }) |
6e9d10db JB |
257 | }) |
258 | .finally(() => { | |
3fafb1b2 | 259 | !this.isMain && (this.lastTaskTimestamp = performance.now()) |
c97c7edb | 260 | }) |
6e9d10db | 261 | .catch(EMPTY_FUNCTION) |
c97c7edb S |
262 | } |
263 | } |