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 |
c97c7edb S |
32 | |
33 | /** | |
729c563d | 34 | * Constructs a new poolifier worker. |
c97c7edb S |
35 | * |
36 | * @param type The type of async event. | |
729c563d S |
37 | * @param isMain Whether this is the main worker or not. |
38 | * @param fn Function processed by the worker when the pool's `execution` function is invoked. | |
838898f1 | 39 | * @param mainWorker Reference to main worker. |
729c563d | 40 | * @param opts Options for the worker. |
c97c7edb S |
41 | */ |
42 | public constructor ( | |
43 | type: string, | |
44 | isMain: boolean, | |
45 | fn: (data: Data) => Response, | |
c365b2d3 | 46 | protected mainWorker: MainWorker | null, |
4c35177b | 47 | public readonly opts: WorkerOptions = { |
e088a00c JB |
48 | /** |
49 | * The kill behavior option on this Worker or its default value. | |
50 | */ | |
1a81f8af | 51 | killBehavior: DEFAULT_KILL_BEHAVIOR, |
e088a00c JB |
52 | /** |
53 | * The maximum time to keep this worker alive while idle. | |
54 | * The pool automatically checks and terminates this worker when the time expires. | |
55 | */ | |
1a81f8af | 56 | maxInactiveTime: DEFAULT_MAX_INACTIVE_TIME |
4c35177b | 57 | } |
c97c7edb S |
58 | ) { |
59 | super(type) | |
c510fea7 | 60 | this.checkFunctionInput(fn) |
e088a00c JB |
61 | this.checkWorkerOptions(this.opts) |
62 | this.lastTaskTimestamp = Date.now() | |
838898f1 | 63 | // Keep the worker active |
c97c7edb | 64 | if (!isMain) { |
e088a00c | 65 | this.aliveInterval = setInterval( |
c97c7edb | 66 | this.checkAlive.bind(this), |
e088a00c | 67 | (this.opts.maxInactiveTime ?? DEFAULT_MAX_INACTIVE_TIME) / 2 |
c97c7edb S |
68 | ) |
69 | this.checkAlive.bind(this)() | |
70 | } | |
838898f1 S |
71 | |
72 | this.mainWorker?.on('message', (value: MessageValue<Data, MainWorker>) => { | |
73 | if (value?.data && value.id) { | |
74 | // Here you will receive messages | |
e088a00c | 75 | if (this.opts.async) { |
838898f1 S |
76 | this.runInAsyncScope(this.runAsync.bind(this), this, fn, value) |
77 | } else { | |
78 | this.runInAsyncScope(this.run.bind(this), this, fn, value) | |
79 | } | |
80 | } else if (value.parent) { | |
81 | // Save a reference of the main worker to communicate with it | |
82 | // This will be received once | |
83 | this.mainWorker = value.parent | |
84 | } else if (value.kill) { | |
85 | // Here is time to kill this worker, just clearing the interval | |
e088a00c | 86 | if (this.aliveInterval) clearInterval(this.aliveInterval) |
838898f1 S |
87 | this.emitDestroy() |
88 | } | |
89 | }) | |
c97c7edb S |
90 | } |
91 | ||
e088a00c JB |
92 | private checkWorkerOptions (opts: WorkerOptions) { |
93 | this.opts.killBehavior = opts.killBehavior ?? DEFAULT_KILL_BEHAVIOR | |
94 | this.opts.maxInactiveTime = | |
95 | opts.maxInactiveTime ?? DEFAULT_MAX_INACTIVE_TIME | |
96 | /** | |
97 | * Whether the worker is working asynchronously or not. | |
98 | */ | |
99 | this.opts.async = !!opts.async | |
100 | } | |
101 | ||
c510fea7 APA |
102 | /** |
103 | * Check if the `fn` parameter is passed to the constructor. | |
104 | * | |
105 | * @param fn The function that should be defined. | |
106 | */ | |
a35560ba | 107 | private checkFunctionInput (fn: (data: Data) => Response): void { |
c510fea7 APA |
108 | if (!fn) throw new Error('fn parameter is mandatory') |
109 | } | |
110 | ||
729c563d S |
111 | /** |
112 | * Returns the main worker. | |
838898f1 S |
113 | * |
114 | * @returns Reference to the main worker. | |
729c563d | 115 | */ |
838898f1 S |
116 | protected getMainWorker (): MainWorker { |
117 | if (!this.mainWorker) { | |
118 | throw new Error('Main worker was not set') | |
119 | } | |
120 | return this.mainWorker | |
121 | } | |
c97c7edb | 122 | |
729c563d S |
123 | /** |
124 | * Send a message to the main worker. | |
125 | * | |
126 | * @param message The response message. | |
127 | */ | |
c97c7edb S |
128 | protected abstract sendToMainWorker (message: MessageValue<Response>): void |
129 | ||
729c563d S |
130 | /** |
131 | * Check to see if the worker should be terminated, because its living too long. | |
132 | */ | |
c97c7edb | 133 | protected checkAlive (): void { |
e088a00c JB |
134 | if ( |
135 | Date.now() - this.lastTaskTimestamp > | |
136 | (this.opts.maxInactiveTime ?? DEFAULT_MAX_INACTIVE_TIME) | |
137 | ) { | |
138 | this.sendToMainWorker({ kill: this.opts.killBehavior }) | |
c97c7edb S |
139 | } |
140 | } | |
141 | ||
729c563d S |
142 | /** |
143 | * Handle an error and convert it to a string so it can be sent back to the main worker. | |
144 | * | |
145 | * @param e The error raised by the worker. | |
50eceb07 | 146 | * @returns Message of the error. |
729c563d | 147 | */ |
c97c7edb | 148 | protected handleError (e: Error | string): string { |
4a34343d | 149 | return e as string |
c97c7edb S |
150 | } |
151 | ||
729c563d S |
152 | /** |
153 | * Run the given function synchronously. | |
154 | * | |
155 | * @param fn Function that will be executed. | |
156 | * @param value Input data for the given function. | |
157 | */ | |
c97c7edb S |
158 | protected run ( |
159 | fn: (data?: Data) => Response, | |
160 | value: MessageValue<Data> | |
161 | ): void { | |
162 | try { | |
163 | const res = fn(value.data) | |
164 | this.sendToMainWorker({ data: res, id: value.id }) | |
c97c7edb | 165 | } catch (e) { |
0a23f635 | 166 | const err = this.handleError(e as Error) |
c97c7edb | 167 | this.sendToMainWorker({ error: err, id: value.id }) |
6e9d10db | 168 | } finally { |
e088a00c | 169 | this.lastTaskTimestamp = Date.now() |
c97c7edb S |
170 | } |
171 | } | |
172 | ||
729c563d S |
173 | /** |
174 | * Run the given function asynchronously. | |
175 | * | |
176 | * @param fn Function that will be executed. | |
177 | * @param value Input data for the given function. | |
178 | */ | |
c97c7edb S |
179 | protected runAsync ( |
180 | fn: (data?: Data) => Promise<Response>, | |
181 | value: MessageValue<Data> | |
182 | ): void { | |
183 | fn(value.data) | |
184 | .then(res => { | |
185 | this.sendToMainWorker({ data: res, id: value.id }) | |
c97c7edb S |
186 | return null |
187 | }) | |
188 | .catch(e => { | |
189 | const err = this.handleError(e) | |
190 | this.sendToMainWorker({ error: err, id: value.id }) | |
6e9d10db JB |
191 | }) |
192 | .finally(() => { | |
e088a00c | 193 | this.lastTaskTimestamp = Date.now() |
c97c7edb | 194 | }) |
6e9d10db | 195 | .catch(EMPTY_FUNCTION) |
c97c7edb S |
196 | } |
197 | } |