@zero-server/grpc 0.9.0 → 0.9.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,378 @@
1
+ /**
2
+ * @module grpc/balancer
3
+ * @description Client-side load balancing for gRPC.
4
+ * Distributes requests across multiple backend addresses using
5
+ * pick-first (with failover) or round-robin policies.
6
+ *
7
+ * Manages subchannels (HTTP/2 connections) per backend with
8
+ * automatic reconnection, exponential backoff, and health awareness.
9
+ *
10
+ * @example
11
+ * const { GrpcClient, parseProto } = require('@zero-server/sdk');
12
+ * const schema = parseProto(protoSource);
13
+ *
14
+ * const client = new GrpcClient({
15
+ * addresses: ['backend-1:50051', 'backend-2:50051', 'backend-3:50051'],
16
+ * loadBalancing: 'round-robin',
17
+ * }, schema, 'Greeter');
18
+ *
19
+ * const reply = await client.call('SayHello', { name: 'World' });
20
+ */
21
+
22
+ const http2 = require('http2');
23
+ const { EventEmitter } = require('events');
24
+ const log = require('../debug')('zero:grpc:balancer');
25
+
26
+ // -- Subchannel States -----------------------------------------
27
+
28
+ /**
29
+ * Connection state machine per subchannel.
30
+ * @enum {string}
31
+ */
32
+ const SubchannelState = {
33
+ IDLE: 'IDLE',
34
+ CONNECTING: 'CONNECTING',
35
+ READY: 'READY',
36
+ TRANSIENT_FAILURE: 'TRANSIENT_FAILURE',
37
+ SHUTDOWN: 'SHUTDOWN',
38
+ };
39
+
40
+ // -- Subchannel ------------------------------------------------
41
+
42
+ /**
43
+ * Represents a persistent HTTP/2 connection to a single backend.
44
+ *
45
+ * @class
46
+ * @private
47
+ */
48
+ class Subchannel extends EventEmitter
49
+ {
50
+ /**
51
+ * @param {string} address - Backend address (host:port or full URL).
52
+ * @param {object} [connectOpts] - HTTP/2 connection options (TLS, etc.).
53
+ */
54
+ constructor(address, connectOpts = {})
55
+ {
56
+ super();
57
+
58
+ /** @type {string} */
59
+ this.address = address;
60
+
61
+ /** @type {string} */
62
+ this.state = SubchannelState.IDLE;
63
+
64
+ /** @private */
65
+ this._connectOpts = connectOpts;
66
+
67
+ /** @private @type {import('http2').ClientHttp2Session|null} */
68
+ this._session = null;
69
+
70
+ /** @private */
71
+ this._backoff = 1000; // exponential backoff starting at 1s
72
+ this._maxBackoff = 30000;
73
+ this._reconnectTimer = null;
74
+
75
+ /** @private */
76
+ this._shutdown = false;
77
+
78
+ /** @private */
79
+ this._healthy = true;
80
+ }
81
+
82
+ /**
83
+ * Connect to the backend.
84
+ * @returns {import('http2').ClientHttp2Session|null}
85
+ */
86
+ connect()
87
+ {
88
+ if (this._shutdown) return null;
89
+ if (this._session && !this._session.closed && !this._session.destroyed)
90
+ return this._session;
91
+
92
+ this._setState(SubchannelState.CONNECTING);
93
+
94
+ try
95
+ {
96
+ // Normalize address to URL
97
+ const url = this.address.includes('://') ? this.address : `http://${this.address}`;
98
+ this._session = http2.connect(url, this._connectOpts);
99
+
100
+ this._session.on('connect', () =>
101
+ {
102
+ this._backoff = 1000; // reset backoff on successful connect
103
+ this._setState(SubchannelState.READY);
104
+ this._healthy = true;
105
+ });
106
+
107
+ this._session.on('error', (err) =>
108
+ {
109
+ log.warn('subchannel %s error: %s', this.address, err.message);
110
+ this._healthy = false;
111
+ this._setState(SubchannelState.TRANSIENT_FAILURE);
112
+ this._scheduleReconnect();
113
+ });
114
+
115
+ this._session.on('close', () =>
116
+ {
117
+ this._session = null;
118
+ if (!this._shutdown)
119
+ {
120
+ this._setState(SubchannelState.IDLE);
121
+ this._scheduleReconnect();
122
+ }
123
+ });
124
+
125
+ this._session.on('goaway', () =>
126
+ {
127
+ log.info('subchannel %s received GOAWAY', this.address);
128
+ this._healthy = false;
129
+ this._setState(SubchannelState.IDLE);
130
+ });
131
+
132
+ return this._session;
133
+ }
134
+ catch (err)
135
+ {
136
+ log.error('subchannel %s connect error: %s', this.address, err.message);
137
+ this._setState(SubchannelState.TRANSIENT_FAILURE);
138
+ this._scheduleReconnect();
139
+ return null;
140
+ }
141
+ }
142
+
143
+ /**
144
+ * Get the session, connecting if needed.
145
+ * @returns {import('http2').ClientHttp2Session|null}
146
+ */
147
+ getSession()
148
+ {
149
+ if (this._session && !this._session.closed && !this._session.destroyed)
150
+ return this._session;
151
+ return this.connect();
152
+ }
153
+
154
+ /**
155
+ * Whether this subchannel is ready to serve requests.
156
+ * @returns {boolean}
157
+ */
158
+ get isReady()
159
+ {
160
+ return this.state === SubchannelState.READY &&
161
+ this._session && !this._session.closed && !this._session.destroyed;
162
+ }
163
+
164
+ /**
165
+ * Whether this subchannel is considered healthy.
166
+ * @returns {boolean}
167
+ */
168
+ get isHealthy()
169
+ {
170
+ return this._healthy && this.isReady;
171
+ }
172
+
173
+ /**
174
+ * Schedule a reconnection with exponential backoff.
175
+ * @private
176
+ */
177
+ _scheduleReconnect()
178
+ {
179
+ if (this._shutdown || this._reconnectTimer) return;
180
+
181
+ this._reconnectTimer = setTimeout(() =>
182
+ {
183
+ this._reconnectTimer = null;
184
+ if (!this._shutdown) this.connect();
185
+ }, this._backoff);
186
+ if (this._reconnectTimer.unref) this._reconnectTimer.unref();
187
+
188
+ this._backoff = Math.min(this._backoff * 2, this._maxBackoff);
189
+ }
190
+
191
+ /**
192
+ * Update state and emit event.
193
+ * @private
194
+ */
195
+ _setState(state)
196
+ {
197
+ const prev = this.state;
198
+ this.state = state;
199
+ if (prev !== state)
200
+ {
201
+ log.debug('subchannel %s: %s → %s', this.address, prev, state);
202
+ this.emit('stateChange', state, prev);
203
+ }
204
+ }
205
+
206
+ /**
207
+ * Shut down this subchannel.
208
+ */
209
+ shutdown()
210
+ {
211
+ this._shutdown = true;
212
+ this._setState(SubchannelState.SHUTDOWN);
213
+ if (this._reconnectTimer)
214
+ {
215
+ clearTimeout(this._reconnectTimer);
216
+ this._reconnectTimer = null;
217
+ }
218
+ if (this._session)
219
+ {
220
+ try { this._session.close(); }
221
+ catch (_) { /* ignore */ }
222
+ this._session = null;
223
+ }
224
+ }
225
+ }
226
+
227
+ // -- Load Balancing Policies -----------------------------------
228
+
229
+ /**
230
+ * Pick-first policy: use the first ready subchannel, failover to next.
231
+ * @private
232
+ * @param {Subchannel[]} subchannels
233
+ * @returns {Subchannel|null}
234
+ */
235
+ function pickFirst(subchannels)
236
+ {
237
+ // First, try the first ready subchannel
238
+ for (const sc of subchannels)
239
+ {
240
+ if (sc.isHealthy) return sc;
241
+ }
242
+ // Fallback: try any that's ready even if not "healthy"
243
+ for (const sc of subchannels)
244
+ {
245
+ if (sc.isReady) return sc;
246
+ }
247
+ // Connect the first idle one
248
+ for (const sc of subchannels)
249
+ {
250
+ if (sc.state === SubchannelState.IDLE)
251
+ {
252
+ sc.connect();
253
+ return sc;
254
+ }
255
+ }
256
+ return subchannels[0] || null;
257
+ }
258
+
259
+ /**
260
+ * Round-robin policy: distribute requests across all ready subchannels.
261
+ * @private
262
+ */
263
+ class RoundRobinPicker
264
+ {
265
+ constructor()
266
+ {
267
+ /** @private */
268
+ this._index = 0;
269
+ }
270
+
271
+ /**
272
+ * Pick the next subchannel.
273
+ * @param {Subchannel[]} subchannels
274
+ * @returns {Subchannel|null}
275
+ */
276
+ pick(subchannels)
277
+ {
278
+ const ready = subchannels.filter(sc => sc.isHealthy);
279
+ if (ready.length === 0)
280
+ {
281
+ // Fallback to any ready
282
+ const anyReady = subchannels.filter(sc => sc.isReady);
283
+ if (anyReady.length > 0)
284
+ {
285
+ this._index = (this._index + 1) % anyReady.length;
286
+ return anyReady[this._index];
287
+ }
288
+ // Try to connect idle ones
289
+ for (const sc of subchannels)
290
+ {
291
+ if (sc.state === SubchannelState.IDLE) sc.connect();
292
+ }
293
+ return subchannels[0] || null;
294
+ }
295
+
296
+ this._index = (this._index + 1) % ready.length;
297
+ return ready[this._index];
298
+ }
299
+ }
300
+
301
+ // -- Balancer --------------------------------------------------
302
+
303
+ /**
304
+ * Load-balanced wrapper that manages multiple subchannels and
305
+ * exposes a `pickSubchannel()` method for the GrpcClient to use.
306
+ *
307
+ * @class
308
+ */
309
+ class LoadBalancer extends EventEmitter
310
+ {
311
+ /**
312
+ * @param {string[]} addresses - Backend addresses.
313
+ * @param {object} [opts] - Options.
314
+ * @param {string} [opts.policy='pick-first'] - 'pick-first' or 'round-robin'.
315
+ * @param {object} [opts.connectOpts] - HTTP/2 connection options.
316
+ */
317
+ constructor(addresses, opts = {})
318
+ {
319
+ super();
320
+
321
+ /** @type {Subchannel[]} */
322
+ this.subchannels = addresses.map(addr => new Subchannel(addr, opts.connectOpts || {}));
323
+
324
+ /** @private */
325
+ this._policy = opts.policy || 'pick-first';
326
+
327
+ /** @private */
328
+ this._rrPicker = this._policy === 'round-robin' ? new RoundRobinPicker() : null;
329
+
330
+ // Start connecting to all subchannels for round-robin
331
+ if (this._policy === 'round-robin')
332
+ {
333
+ for (const sc of this.subchannels) sc.connect();
334
+ }
335
+ else
336
+ {
337
+ // Pick-first: connect only to the first
338
+ if (this.subchannels.length > 0) this.subchannels[0].connect();
339
+ }
340
+ }
341
+
342
+ /**
343
+ * Pick a subchannel for the next request.
344
+ * @returns {Subchannel|null}
345
+ */
346
+ pick()
347
+ {
348
+ if (this._rrPicker)
349
+ return this._rrPicker.pick(this.subchannels);
350
+ return pickFirst(this.subchannels);
351
+ }
352
+
353
+ /**
354
+ * Get an HTTP/2 session from the selected subchannel.
355
+ * @returns {import('http2').ClientHttp2Session|null}
356
+ */
357
+ getSession()
358
+ {
359
+ const sc = this.pick();
360
+ if (!sc) return null;
361
+ return sc.getSession();
362
+ }
363
+
364
+ /**
365
+ * Shut down all subchannels.
366
+ */
367
+ shutdown()
368
+ {
369
+ for (const sc of this.subchannels) sc.shutdown();
370
+ }
371
+ }
372
+
373
+ module.exports = {
374
+ LoadBalancer,
375
+ Subchannel,
376
+ SubchannelState,
377
+ RoundRobinPicker,
378
+ };