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