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