@zero-server/sdk 0.9.0

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.
Files changed (126) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +437 -0
  3. package/index.js +412 -0
  4. package/lib/app.js +1172 -0
  5. package/lib/auth/authorize.js +399 -0
  6. package/lib/auth/enrollment.js +367 -0
  7. package/lib/auth/index.js +57 -0
  8. package/lib/auth/jwt.js +731 -0
  9. package/lib/auth/oauth.js +362 -0
  10. package/lib/auth/session.js +588 -0
  11. package/lib/auth/trustedDevice.js +409 -0
  12. package/lib/auth/twoFactor.js +1150 -0
  13. package/lib/auth/webauthn.js +946 -0
  14. package/lib/body/index.js +14 -0
  15. package/lib/body/json.js +109 -0
  16. package/lib/body/multipart.js +440 -0
  17. package/lib/body/raw.js +71 -0
  18. package/lib/body/rawBuffer.js +161 -0
  19. package/lib/body/sendError.js +25 -0
  20. package/lib/body/text.js +75 -0
  21. package/lib/body/typeMatch.js +42 -0
  22. package/lib/body/urlencoded.js +235 -0
  23. package/lib/cli.js +845 -0
  24. package/lib/cluster.js +666 -0
  25. package/lib/debug.js +372 -0
  26. package/lib/env/index.js +465 -0
  27. package/lib/errors.js +683 -0
  28. package/lib/fetch/index.js +256 -0
  29. package/lib/grpc/balancer.js +378 -0
  30. package/lib/grpc/call.js +708 -0
  31. package/lib/grpc/client.js +764 -0
  32. package/lib/grpc/codec.js +1221 -0
  33. package/lib/grpc/credentials.js +398 -0
  34. package/lib/grpc/frame.js +262 -0
  35. package/lib/grpc/health.js +287 -0
  36. package/lib/grpc/index.js +121 -0
  37. package/lib/grpc/metadata.js +461 -0
  38. package/lib/grpc/proto.js +821 -0
  39. package/lib/grpc/reflection.js +590 -0
  40. package/lib/grpc/server.js +445 -0
  41. package/lib/grpc/status.js +118 -0
  42. package/lib/grpc/watch.js +173 -0
  43. package/lib/http/index.js +10 -0
  44. package/lib/http/request.js +727 -0
  45. package/lib/http/response.js +799 -0
  46. package/lib/lifecycle.js +557 -0
  47. package/lib/middleware/compress.js +230 -0
  48. package/lib/middleware/cookieParser.js +237 -0
  49. package/lib/middleware/cors.js +93 -0
  50. package/lib/middleware/csrf.js +137 -0
  51. package/lib/middleware/errorHandler.js +101 -0
  52. package/lib/middleware/helmet.js +176 -0
  53. package/lib/middleware/index.js +17 -0
  54. package/lib/middleware/logger.js +74 -0
  55. package/lib/middleware/rateLimit.js +88 -0
  56. package/lib/middleware/requestId.js +54 -0
  57. package/lib/middleware/static.js +326 -0
  58. package/lib/middleware/timeout.js +72 -0
  59. package/lib/middleware/validator.js +255 -0
  60. package/lib/observe/health.js +326 -0
  61. package/lib/observe/index.js +50 -0
  62. package/lib/observe/logger.js +359 -0
  63. package/lib/observe/metrics.js +805 -0
  64. package/lib/observe/tracing.js +592 -0
  65. package/lib/orm/adapters/json.js +290 -0
  66. package/lib/orm/adapters/memory.js +764 -0
  67. package/lib/orm/adapters/mongo.js +764 -0
  68. package/lib/orm/adapters/mysql.js +933 -0
  69. package/lib/orm/adapters/postgres.js +1144 -0
  70. package/lib/orm/adapters/redis.js +1534 -0
  71. package/lib/orm/adapters/sql-base.js +212 -0
  72. package/lib/orm/adapters/sqlite.js +858 -0
  73. package/lib/orm/audit.js +649 -0
  74. package/lib/orm/cache.js +394 -0
  75. package/lib/orm/geo.js +387 -0
  76. package/lib/orm/index.js +784 -0
  77. package/lib/orm/migrate.js +432 -0
  78. package/lib/orm/model.js +1706 -0
  79. package/lib/orm/plugin.js +375 -0
  80. package/lib/orm/procedures.js +836 -0
  81. package/lib/orm/profiler.js +233 -0
  82. package/lib/orm/query.js +1772 -0
  83. package/lib/orm/replicas.js +241 -0
  84. package/lib/orm/schema.js +307 -0
  85. package/lib/orm/search.js +380 -0
  86. package/lib/orm/seed/data/commerce.js +136 -0
  87. package/lib/orm/seed/data/internet.js +111 -0
  88. package/lib/orm/seed/data/locations.js +204 -0
  89. package/lib/orm/seed/data/names.js +338 -0
  90. package/lib/orm/seed/data/person.js +128 -0
  91. package/lib/orm/seed/data/phone.js +211 -0
  92. package/lib/orm/seed/data/words.js +134 -0
  93. package/lib/orm/seed/factory.js +178 -0
  94. package/lib/orm/seed/fake.js +1186 -0
  95. package/lib/orm/seed/index.js +18 -0
  96. package/lib/orm/seed/rng.js +71 -0
  97. package/lib/orm/seed/seeder.js +125 -0
  98. package/lib/orm/seed/unique.js +68 -0
  99. package/lib/orm/snapshot.js +366 -0
  100. package/lib/orm/tenancy.js +605 -0
  101. package/lib/orm/views.js +350 -0
  102. package/lib/router/index.js +436 -0
  103. package/lib/sse/index.js +8 -0
  104. package/lib/sse/stream.js +349 -0
  105. package/lib/ws/connection.js +451 -0
  106. package/lib/ws/handshake.js +125 -0
  107. package/lib/ws/index.js +14 -0
  108. package/lib/ws/room.js +223 -0
  109. package/package.json +73 -0
  110. package/types/app.d.ts +223 -0
  111. package/types/auth.d.ts +520 -0
  112. package/types/cluster.d.ts +75 -0
  113. package/types/env.d.ts +80 -0
  114. package/types/errors.d.ts +316 -0
  115. package/types/fetch.d.ts +43 -0
  116. package/types/grpc.d.ts +432 -0
  117. package/types/index.d.ts +384 -0
  118. package/types/lifecycle.d.ts +60 -0
  119. package/types/middleware.d.ts +320 -0
  120. package/types/observe.d.ts +304 -0
  121. package/types/orm.d.ts +1887 -0
  122. package/types/request.d.ts +109 -0
  123. package/types/response.d.ts +157 -0
  124. package/types/router.d.ts +78 -0
  125. package/types/sse.d.ts +78 -0
  126. package/types/websocket.d.ts +126 -0
@@ -0,0 +1,256 @@
1
+ /**
2
+ * @module fetch
3
+ * @description Minimal, zero-dependency server-side `fetch()` replacement.
4
+ * Supports HTTP/HTTPS, JSON/URLSearchParams/Buffer/stream bodies,
5
+ * download & upload progress callbacks, timeouts, and AbortSignal.
6
+ */
7
+ const http = require('http');
8
+ const https = require('https');
9
+ const { URL } = require('url');
10
+
11
+ const STATUS_CODES = http.STATUS_CODES;
12
+
13
+ /**
14
+ * Perform an HTTP(S) request.
15
+ *
16
+ * @param {string} url - Absolute URL to fetch.
17
+ * @param {object} [opts] - Configuration options.
18
+ * @param {string} [opts.method='GET'] - HTTP method.
19
+ * @param {object} [opts.headers] - Request headers.
20
+ * @param {string|Buffer|object|ReadableStream} [opts.body] - Request body.
21
+ * @param {number} [opts.timeout] - Request timeout in ms.
22
+ * @param {AbortSignal} [opts.signal] - Abort signal for cancellation.
23
+ * @param {import('http').Agent} [opts.agent] - Custom HTTP agent.
24
+ * @param {Function} [opts.onDownloadProgress] - `({ loaded, total }) => void` download progress callback.
25
+ * @param {Function} [opts.onUploadProgress] - `({ loaded, total }) => void` upload progress callback.
26
+ * @param {boolean} [opts.rejectUnauthorized] - Reject connections with unverified certs (default: Node default `true`). TLS option — passed to `https.request()`.
27
+ * @param {string|Buffer|Array} [opts.ca] - Override default CA certificates.
28
+ * @param {string|Buffer} [opts.cert] - Client certificate (PEM) for mutual TLS.
29
+ * @param {string|Buffer} [opts.key] - Private key (PEM) for mutual TLS.
30
+ * @param {string|Buffer} [opts.pfx] - PFX / PKCS12 bundle (alternative to cert+key).
31
+ * @param {string} [opts.passphrase] - Passphrase for the key or PFX.
32
+ * @param {string} [opts.servername] - SNI server name override.
33
+ * @param {string} [opts.ciphers] - Colon-separated cipher list.
34
+ * @param {string} [opts.secureProtocol] - SSL/TLS protocol method name.
35
+ * @param {string} [opts.minVersion] - Minimum TLS version (`'TLSv1.2'`, etc.).
36
+ * @param {string} [opts.maxVersion] - Maximum TLS version.
37
+ *
38
+ * @returns {Promise<{ status: number, statusText: string, ok: boolean, secure: boolean, url: string, headers: object, arrayBuffer: Function, text: Function, json: Function }>} Resolves with a response object containing status info, headers, and body-reading helpers (`text()`, `json()`, `arrayBuffer()`).
39
+ *
40
+ * @example
41
+ * const res = await fetch('https://api.example.com/data');
42
+ * const body = await res.json();
43
+ *
44
+ * // POST with JSON body & timeout
45
+ * const res2 = await fetch('https://api.example.com/items', {
46
+ * method: 'POST',
47
+ * body: { name: 'widget' },
48
+ * timeout: 5000,
49
+ * });
50
+ */
51
+ function miniFetch(url, opts = {})
52
+ {
53
+ return new Promise((resolve, reject) =>
54
+ {
55
+ try
56
+ {
57
+ const u = new URL(url);
58
+ const lib = u.protocol === 'https:' ? https : http;
59
+ const method = (opts.method || 'GET').toUpperCase();
60
+ const headers = Object.assign({}, opts.headers || {});
61
+
62
+ // Normalize body
63
+ let body = opts.body;
64
+ if (body && typeof body === 'object' && typeof body.toString === 'function' && body.constructor && body.constructor.name === 'URLSearchParams')
65
+ {
66
+ if (!headers['Content-Type'] && !headers['content-type']) headers['Content-Type'] = 'application/x-www-form-urlencoded';
67
+ body = body.toString();
68
+ }
69
+ else if (body && typeof body === 'object' && !Buffer.isBuffer(body) && !(body instanceof ArrayBuffer) && !(body instanceof Uint8Array) && !(body && typeof body.pipe === 'function'))
70
+ {
71
+ if (!headers['Content-Type'] && !headers['content-type']) headers['Content-Type'] = 'application/json';
72
+ body = Buffer.from(JSON.stringify(body), 'utf8');
73
+ }
74
+ else if (body instanceof ArrayBuffer)
75
+ {
76
+ body = Buffer.from(body);
77
+ }
78
+ else if (body instanceof Uint8Array && !Buffer.isBuffer(body))
79
+ {
80
+ body = Buffer.from(body);
81
+ }
82
+
83
+ // Set Content-Length for known-size bodies
84
+ if ((Buffer.isBuffer(body) || typeof body === 'string') && !headers['Content-Length'] && !headers['content-length'])
85
+ {
86
+ headers['Content-Length'] = String(Buffer.isBuffer(body) ? body.length : Buffer.byteLength(body));
87
+ }
88
+
89
+ const options = { method, headers };
90
+ if (opts.agent) options.agent = opts.agent;
91
+
92
+ // Pass through TLS options for HTTPS requests
93
+ if (lib === https)
94
+ {
95
+ const tlsKeys = [
96
+ 'rejectUnauthorized', 'ca', 'cert', 'key', 'pfx', 'passphrase',
97
+ 'servername', 'ciphers', 'secureProtocol', 'minVersion', 'maxVersion'
98
+ ];
99
+ for (const k of tlsKeys)
100
+ {
101
+ if (opts[k] !== undefined) options[k] = opts[k];
102
+ }
103
+ }
104
+
105
+ const req = lib.request(u, options, (res) =>
106
+ {
107
+ const chunks = [];
108
+ let downloaded = 0;
109
+ const total = parseInt(res.headers['content-length'] || '0', 10) || null;
110
+
111
+ res.on('data', (c) =>
112
+ {
113
+ chunks.push(c);
114
+ downloaded += c.length;
115
+ if (typeof opts.onDownloadProgress === 'function')
116
+ {
117
+ try { opts.onDownloadProgress({ loaded: downloaded, total }); } catch (e) { }
118
+ }
119
+ });
120
+
121
+ res.on('end', () =>
122
+ {
123
+ const buf = Buffer.concat(chunks);
124
+ const status = res.statusCode;
125
+ const rawHeaders = res.headers || {};
126
+ const responseHeaders = {
127
+ get(name)
128
+ {
129
+ if (!name) return undefined;
130
+ const v = rawHeaders[name.toLowerCase()];
131
+ return Array.isArray(v) ? v.join(', ') : v;
132
+ },
133
+ raw: rawHeaders,
134
+ };
135
+
136
+ resolve({
137
+ status,
138
+ statusText: STATUS_CODES[status] || '',
139
+ ok: status >= 200 && status < 300,
140
+ secure: u.protocol === 'https:',
141
+ url: u.href,
142
+ headers: responseHeaders,
143
+ arrayBuffer: () => Promise.resolve(buf),
144
+ text: () => Promise.resolve(buf.toString('utf8')),
145
+ json: () =>
146
+ {
147
+ try { return Promise.resolve(JSON.parse(buf.toString('utf8'))); }
148
+ catch (e) { return Promise.reject(e); }
149
+ },
150
+ });
151
+ });
152
+ });
153
+
154
+ req.on('error', reject);
155
+
156
+ // Timeout
157
+ if (typeof opts.timeout === 'number' && opts.timeout > 0)
158
+ {
159
+ req.setTimeout(opts.timeout, () =>
160
+ {
161
+ const err = new Error('Request timed out');
162
+ err.code = 'ETIMEOUT';
163
+ req.destroy(err);
164
+ });
165
+ }
166
+
167
+ // AbortSignal support
168
+ let abortHandler;
169
+ if (opts.signal)
170
+ {
171
+ if (opts.signal.aborted)
172
+ {
173
+ const err = new Error('Request aborted');
174
+ err.name = 'AbortError';
175
+ req.destroy(err);
176
+ return;
177
+ }
178
+ abortHandler = () =>
179
+ {
180
+ const err = new Error('Request aborted');
181
+ err.name = 'AbortError';
182
+ req.destroy(err);
183
+ };
184
+ if (typeof opts.signal.addEventListener === 'function') opts.signal.addEventListener('abort', abortHandler);
185
+ else if (typeof opts.signal.on === 'function') opts.signal.on('abort', abortHandler);
186
+ }
187
+
188
+ // Cleanup signal listener
189
+ const cleanup = () =>
190
+ {
191
+ if (opts.signal && abortHandler)
192
+ {
193
+ try
194
+ {
195
+ if (typeof opts.signal.removeEventListener === 'function') opts.signal.removeEventListener('abort', abortHandler);
196
+ else if (typeof opts.signal.off === 'function') opts.signal.off('abort', abortHandler);
197
+ }
198
+ catch (e) { }
199
+ }
200
+ };
201
+ req.on('close', cleanup);
202
+
203
+ // Write body
204
+ if (body && typeof body.pipe === 'function')
205
+ {
206
+ let uploaded = 0;
207
+ body.on('data', (chunk) =>
208
+ {
209
+ uploaded += chunk.length;
210
+ if (typeof opts.onUploadProgress === 'function')
211
+ {
212
+ try { opts.onUploadProgress({ loaded: uploaded, total: headers['Content-Length'] ? Number(headers['Content-Length']) : null }); } catch (e) { }
213
+ }
214
+ });
215
+ body.on('error', (err) => req.destroy(err));
216
+ body.pipe(req);
217
+ }
218
+ else if (Buffer.isBuffer(body) || typeof body === 'string')
219
+ {
220
+ const buf = Buffer.isBuffer(body) ? body : Buffer.from(body);
221
+ const total = buf.length;
222
+ const CHUNK = 64 * 1024;
223
+ let sent = 0;
224
+
225
+ function writeNext()
226
+ {
227
+ if (sent >= total) { req.end(); return; }
228
+ const slice = buf.slice(sent, Math.min(sent + CHUNK, total));
229
+ const ok = req.write(slice, () =>
230
+ {
231
+ sent += slice.length;
232
+ if (typeof opts.onUploadProgress === 'function')
233
+ {
234
+ try { opts.onUploadProgress({ loaded: sent, total }); } catch (e) { }
235
+ }
236
+ writeNext();
237
+ });
238
+ if (!ok) req.once('drain', writeNext);
239
+ }
240
+ writeNext();
241
+ }
242
+ else if (body == null)
243
+ {
244
+ req.end();
245
+ }
246
+ else
247
+ {
248
+ req.write(String(body));
249
+ req.end();
250
+ }
251
+ }
252
+ catch (e) { reject(e); }
253
+ });
254
+ }
255
+
256
+ module.exports = miniFetch;
@@ -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
+ };