@johnhenry/browsermesh-core 0.0.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.
- package/LICENSE +21 -0
- package/README.md +42 -0
- package/package.json +32 -0
- package/src/acl.mjs +530 -0
- package/src/capabilities.mjs +852 -0
- package/src/compat.mjs +29 -0
- package/src/group-keys.mjs +610 -0
- package/src/handshake.mjs +760 -0
- package/src/hardening.mjs +1183 -0
- package/src/identity-base.mjs +491 -0
- package/src/identity-tools.mjs +383 -0
- package/src/identity-wallet.mjs +505 -0
- package/src/identity.mjs +1349 -0
- package/src/index.mjs +15 -0
- package/src/keyring.mjs +741 -0
- package/src/peer-tools.mjs +959 -0
- package/src/peer.mjs +391 -0
- package/src/silent-catch.mjs +55 -0
- package/src/trust.mjs +425 -0
|
@@ -0,0 +1,1183 @@
|
|
|
1
|
+
import { silentCatch } from './silent-catch.mjs'
|
|
2
|
+
/**
|
|
3
|
+
// STATUS: EXPERIMENTAL — production hardening for BrowserMesh transports
|
|
4
|
+
* clawser-mesh-hardening.js -- Production Hardening Layer.
|
|
5
|
+
*
|
|
6
|
+
* Additive hardening primitives that compose with existing MeshTransport
|
|
7
|
+
* and MeshTransportNegotiator without breaking backward compatibility.
|
|
8
|
+
*
|
|
9
|
+
* Features:
|
|
10
|
+
* 1. RetryWithBackoff — exponential backoff + circuit breaker
|
|
11
|
+
* 2. TransportHealthCheck — ping/pong liveness probes
|
|
12
|
+
* 3. ConnectionPool — per-peer pooling with idle eviction
|
|
13
|
+
* 4. TransportMetrics — per-transport byte/message/error/latency counters
|
|
14
|
+
* 5. TransportFailover — graceful degradation across transport types
|
|
15
|
+
*
|
|
16
|
+
* Run tests:
|
|
17
|
+
* node --import ./web/test/_setup-globals.mjs --test web/test/clawser-mesh-hardening.test.mjs
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
// ---------------------------------------------------------------------------
|
|
21
|
+
// 1. RetryWithBackoff — exponential backoff with circuit breaker
|
|
22
|
+
// ---------------------------------------------------------------------------
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Circuit breaker states.
|
|
26
|
+
* @type {readonly string[]}
|
|
27
|
+
*/
|
|
28
|
+
export const CIRCUIT_STATES = Object.freeze(['closed', 'open', 'half-open']);
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Wraps an async operation with exponential backoff retry and circuit breaker.
|
|
32
|
+
*
|
|
33
|
+
* Circuit breaker transitions:
|
|
34
|
+
* closed -> open (after maxRetries consecutive failures)
|
|
35
|
+
* open -> half-open (after resetTimeoutMs elapses)
|
|
36
|
+
* half-open -> closed (on next success)
|
|
37
|
+
* half-open -> open (on next failure)
|
|
38
|
+
*
|
|
39
|
+
* @example
|
|
40
|
+
* const retry = new RetryWithBackoff({ maxRetries: 5 });
|
|
41
|
+
* const transport = await retry.execute(() => negotiator.negotiate(endpoints));
|
|
42
|
+
*/
|
|
43
|
+
export class RetryWithBackoff {
|
|
44
|
+
/** @type {number} */
|
|
45
|
+
#maxRetries;
|
|
46
|
+
|
|
47
|
+
/** @type {number} */
|
|
48
|
+
#baseDelayMs;
|
|
49
|
+
|
|
50
|
+
/** @type {number} */
|
|
51
|
+
#maxDelayMs;
|
|
52
|
+
|
|
53
|
+
/** @type {number} */
|
|
54
|
+
#jitterFactor;
|
|
55
|
+
|
|
56
|
+
/** @type {number} */
|
|
57
|
+
#resetTimeoutMs;
|
|
58
|
+
|
|
59
|
+
/** @type {string} */
|
|
60
|
+
#circuitState = 'closed';
|
|
61
|
+
|
|
62
|
+
/** @type {number} */
|
|
63
|
+
#failureCount = 0;
|
|
64
|
+
|
|
65
|
+
/** @type {number} */
|
|
66
|
+
#lastFailureTime = 0;
|
|
67
|
+
|
|
68
|
+
/** @type {number} */
|
|
69
|
+
#successCount = 0;
|
|
70
|
+
|
|
71
|
+
/** @type {Function} */
|
|
72
|
+
#nowFn;
|
|
73
|
+
|
|
74
|
+
/** @type {Function} */
|
|
75
|
+
#sleepFn;
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* @param {object} [opts]
|
|
79
|
+
* @param {number} [opts.maxRetries=5] - Maximum retry attempts before circuit opens
|
|
80
|
+
* @param {number} [opts.baseDelayMs=1000] - Initial backoff delay
|
|
81
|
+
* @param {number} [opts.maxDelayMs=30000] - Maximum backoff delay cap
|
|
82
|
+
* @param {number} [opts.jitterFactor=0.2] - Random jitter factor (0-1)
|
|
83
|
+
* @param {number} [opts.resetTimeoutMs=60000] - Time before circuit transitions open -> half-open
|
|
84
|
+
* @param {Function} [opts.nowFn=Date.now] - Clock function (for testing)
|
|
85
|
+
* @param {Function} [opts.sleepFn] - Sleep function (for testing)
|
|
86
|
+
*/
|
|
87
|
+
constructor(opts = {}) {
|
|
88
|
+
this.#maxRetries = opts.maxRetries ?? 5;
|
|
89
|
+
this.#baseDelayMs = opts.baseDelayMs ?? 1000;
|
|
90
|
+
this.#maxDelayMs = opts.maxDelayMs ?? 30000;
|
|
91
|
+
this.#jitterFactor = opts.jitterFactor ?? 0.2;
|
|
92
|
+
this.#resetTimeoutMs = opts.resetTimeoutMs ?? 60000;
|
|
93
|
+
this.#nowFn = opts.nowFn ?? Date.now;
|
|
94
|
+
this.#sleepFn = opts.sleepFn ?? ((ms) => new Promise(r => setTimeout(r, ms)));
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** Current circuit breaker state. */
|
|
98
|
+
get circuitState() {
|
|
99
|
+
return this.#circuitState;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** Number of consecutive failures. */
|
|
103
|
+
get failureCount() {
|
|
104
|
+
return this.#failureCount;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** Number of consecutive successes since last failure. */
|
|
108
|
+
get successCount() {
|
|
109
|
+
return this.#successCount;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* Execute an async operation with retry and circuit breaker logic.
|
|
114
|
+
*
|
|
115
|
+
* @template T
|
|
116
|
+
* @param {() => Promise<T>} fn - The async operation to execute
|
|
117
|
+
* @returns {Promise<T>}
|
|
118
|
+
* @throws {Error} When circuit is open or all retries exhausted
|
|
119
|
+
*/
|
|
120
|
+
async execute(fn) {
|
|
121
|
+
// Check circuit breaker state
|
|
122
|
+
if (this.#circuitState === 'open') {
|
|
123
|
+
const elapsed = this.#nowFn() - this.#lastFailureTime;
|
|
124
|
+
if (elapsed < this.#resetTimeoutMs) {
|
|
125
|
+
throw new Error(`Circuit breaker is open (resets in ${this.#resetTimeoutMs - elapsed}ms)`);
|
|
126
|
+
}
|
|
127
|
+
// Transition to half-open — allow one attempt
|
|
128
|
+
this.#circuitState = 'half-open';
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
const errors = [];
|
|
132
|
+
const maxAttempts = this.#circuitState === 'half-open' ? 1 : this.#maxRetries;
|
|
133
|
+
|
|
134
|
+
for (let attempt = 0; attempt < maxAttempts; attempt++) {
|
|
135
|
+
if (attempt > 0) {
|
|
136
|
+
const delay = this.#calculateDelay(attempt);
|
|
137
|
+
await this.#sleepFn(delay);
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
try {
|
|
141
|
+
const result = await fn();
|
|
142
|
+
// Success — reset failure tracking, close circuit if half-open
|
|
143
|
+
this.#failureCount = 0;
|
|
144
|
+
this.#successCount++;
|
|
145
|
+
if (this.#circuitState === 'half-open') {
|
|
146
|
+
this.#circuitState = 'closed';
|
|
147
|
+
}
|
|
148
|
+
return result;
|
|
149
|
+
} catch (err) {
|
|
150
|
+
errors.push({ attempt: attempt + 1, error: err.message });
|
|
151
|
+
this.#failureCount++;
|
|
152
|
+
this.#successCount = 0;
|
|
153
|
+
this.#lastFailureTime = this.#nowFn();
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
// All attempts exhausted — check if circuit should open
|
|
158
|
+
if (this.#failureCount >= this.#maxRetries) {
|
|
159
|
+
this.#circuitState = 'open';
|
|
160
|
+
}
|
|
161
|
+
const msg = this.#circuitState === 'open'
|
|
162
|
+
? `Circuit breaker opened after ${this.#failureCount} failures`
|
|
163
|
+
: `All ${maxAttempts} retries exhausted`;
|
|
164
|
+
const error = new Error(`${msg}: ${JSON.stringify(errors)}`);
|
|
165
|
+
error.attempts = errors;
|
|
166
|
+
throw error;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* Manually reset the circuit breaker to closed state.
|
|
171
|
+
*/
|
|
172
|
+
reset() {
|
|
173
|
+
this.#circuitState = 'closed';
|
|
174
|
+
this.#failureCount = 0;
|
|
175
|
+
this.#successCount = 0;
|
|
176
|
+
this.#lastFailureTime = 0;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* Serialize state for inspection.
|
|
181
|
+
* @returns {object}
|
|
182
|
+
*/
|
|
183
|
+
toJSON() {
|
|
184
|
+
return {
|
|
185
|
+
circuitState: this.#circuitState,
|
|
186
|
+
failureCount: this.#failureCount,
|
|
187
|
+
successCount: this.#successCount,
|
|
188
|
+
maxRetries: this.#maxRetries,
|
|
189
|
+
lastFailureTime: this.#lastFailureTime,
|
|
190
|
+
};
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
// -- Internal ---------------------------------------------------------------
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* Calculate delay for a given attempt using exponential backoff + jitter.
|
|
197
|
+
* @param {number} attempt - Zero-based attempt index
|
|
198
|
+
* @returns {number} Delay in ms
|
|
199
|
+
*/
|
|
200
|
+
#calculateDelay(attempt) {
|
|
201
|
+
const exponential = this.#baseDelayMs * Math.pow(2, attempt - 1);
|
|
202
|
+
const capped = Math.min(exponential, this.#maxDelayMs);
|
|
203
|
+
const jitter = capped * this.#jitterFactor * (Math.random() * 2 - 1);
|
|
204
|
+
return Math.max(0, Math.floor(capped + jitter));
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
// ---------------------------------------------------------------------------
|
|
210
|
+
// 2. TransportHealthCheck — ping/pong liveness probes
|
|
211
|
+
// ---------------------------------------------------------------------------
|
|
212
|
+
|
|
213
|
+
/**
|
|
214
|
+
* Health status values for a transport.
|
|
215
|
+
* @type {readonly string[]}
|
|
216
|
+
*/
|
|
217
|
+
export const TRANSPORT_HEALTH_STATUSES = Object.freeze(['healthy', 'degraded', 'unhealthy']);
|
|
218
|
+
|
|
219
|
+
/**
|
|
220
|
+
* Monitors transport liveness via periodic ping/pong probes.
|
|
221
|
+
*
|
|
222
|
+
* Sends a ping at `intervalMs`. If a pong is not received within
|
|
223
|
+
* `timeoutMs`, the probe counts as missed. After `maxMissed` consecutive
|
|
224
|
+
* misses the transport is marked unhealthy.
|
|
225
|
+
*
|
|
226
|
+
* @example
|
|
227
|
+
* const check = new TransportHealthCheck({ transport, pingFn, pongEvent: 'message' });
|
|
228
|
+
* check.start();
|
|
229
|
+
* check.on('unhealthy', () => console.log('transport down'));
|
|
230
|
+
*/
|
|
231
|
+
export class TransportHealthCheck {
|
|
232
|
+
/** @type {object} */
|
|
233
|
+
#transport;
|
|
234
|
+
|
|
235
|
+
/** @type {Function} */
|
|
236
|
+
#pingFn;
|
|
237
|
+
|
|
238
|
+
/** @type {number} */
|
|
239
|
+
#intervalMs;
|
|
240
|
+
|
|
241
|
+
/** @type {number} */
|
|
242
|
+
#timeoutMs;
|
|
243
|
+
|
|
244
|
+
/** @type {number} */
|
|
245
|
+
#maxMissed;
|
|
246
|
+
|
|
247
|
+
/** @type {number} */
|
|
248
|
+
#missedCount = 0;
|
|
249
|
+
|
|
250
|
+
/** @type {string} */
|
|
251
|
+
#status = 'healthy';
|
|
252
|
+
|
|
253
|
+
/** @type {number} */
|
|
254
|
+
#lastPongTime = 0;
|
|
255
|
+
|
|
256
|
+
/** @type {number} */
|
|
257
|
+
#totalPings = 0;
|
|
258
|
+
|
|
259
|
+
/** @type {number} */
|
|
260
|
+
#totalPongs = 0;
|
|
261
|
+
|
|
262
|
+
/** @type {*} */
|
|
263
|
+
#intervalTimer = null;
|
|
264
|
+
|
|
265
|
+
/** @type {*} */
|
|
266
|
+
#timeoutTimer = null;
|
|
267
|
+
|
|
268
|
+
/** @type {boolean} */
|
|
269
|
+
#waitingForPong = false;
|
|
270
|
+
|
|
271
|
+
/** @type {Map<string, Set<Function>>} */
|
|
272
|
+
#listeners = new Map();
|
|
273
|
+
|
|
274
|
+
/** @type {Function} */
|
|
275
|
+
#nowFn;
|
|
276
|
+
|
|
277
|
+
/**
|
|
278
|
+
* @param {object} opts
|
|
279
|
+
* @param {object} opts.transport - Transport instance to monitor
|
|
280
|
+
* @param {Function} opts.pingFn - Function to send a ping (receives transport)
|
|
281
|
+
* @param {number} [opts.intervalMs=10000] - Ping interval
|
|
282
|
+
* @param {number} [opts.timeoutMs=5000] - Max wait for pong response
|
|
283
|
+
* @param {number} [opts.maxMissed=3] - Consecutive misses before unhealthy
|
|
284
|
+
* @param {Function} [opts.nowFn=Date.now]
|
|
285
|
+
*/
|
|
286
|
+
constructor(opts) {
|
|
287
|
+
if (!opts.transport) throw new Error('transport is required');
|
|
288
|
+
if (!opts.pingFn || typeof opts.pingFn !== 'function') throw new Error('pingFn is required');
|
|
289
|
+
this.#transport = opts.transport;
|
|
290
|
+
this.#pingFn = opts.pingFn;
|
|
291
|
+
this.#intervalMs = opts.intervalMs ?? 10000;
|
|
292
|
+
this.#timeoutMs = opts.timeoutMs ?? 5000;
|
|
293
|
+
this.#maxMissed = opts.maxMissed ?? 3;
|
|
294
|
+
this.#nowFn = opts.nowFn ?? Date.now;
|
|
295
|
+
this.#lastPongTime = this.#nowFn();
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
/** Current health status. */
|
|
299
|
+
get status() {
|
|
300
|
+
return this.#status;
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
/** Number of consecutive missed pongs. */
|
|
304
|
+
get missedCount() {
|
|
305
|
+
return this.#missedCount;
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
/** Total pings sent. */
|
|
309
|
+
get totalPings() {
|
|
310
|
+
return this.#totalPings;
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
/** Total pongs received. */
|
|
314
|
+
get totalPongs() {
|
|
315
|
+
return this.#totalPongs;
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
/** Timestamp of last pong. */
|
|
319
|
+
get lastPongTime() {
|
|
320
|
+
return this.#lastPongTime;
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
/** The transport being monitored. */
|
|
324
|
+
get transport() {
|
|
325
|
+
return this.#transport;
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
/**
|
|
329
|
+
* Start periodic health checks.
|
|
330
|
+
*/
|
|
331
|
+
start() {
|
|
332
|
+
this.stop();
|
|
333
|
+
this.#intervalTimer = setInterval(() => this.#sendPing(), this.#intervalMs);
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
/**
|
|
337
|
+
* Stop periodic health checks.
|
|
338
|
+
*/
|
|
339
|
+
stop() {
|
|
340
|
+
if (this.#intervalTimer !== null) {
|
|
341
|
+
clearInterval(this.#intervalTimer);
|
|
342
|
+
this.#intervalTimer = null;
|
|
343
|
+
}
|
|
344
|
+
if (this.#timeoutTimer !== null) {
|
|
345
|
+
clearTimeout(this.#timeoutTimer);
|
|
346
|
+
this.#timeoutTimer = null;
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
/**
|
|
351
|
+
* Record a pong response. Call this externally when a pong arrives.
|
|
352
|
+
*/
|
|
353
|
+
recordPong() {
|
|
354
|
+
this.#totalPongs++;
|
|
355
|
+
this.#lastPongTime = this.#nowFn();
|
|
356
|
+
this.#missedCount = 0;
|
|
357
|
+
this.#waitingForPong = false;
|
|
358
|
+
|
|
359
|
+
if (this.#timeoutTimer !== null) {
|
|
360
|
+
clearTimeout(this.#timeoutTimer);
|
|
361
|
+
this.#timeoutTimer = null;
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
const oldStatus = this.#status;
|
|
365
|
+
this.#status = 'healthy';
|
|
366
|
+
if (oldStatus !== 'healthy') {
|
|
367
|
+
this.#emit('healthy', { transport: this.#transport });
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
/**
|
|
372
|
+
* Register a listener for a health event.
|
|
373
|
+
* Events: 'healthy', 'degraded', 'unhealthy', 'ping', 'pong-timeout'
|
|
374
|
+
*
|
|
375
|
+
* @param {string} event
|
|
376
|
+
* @param {Function} cb
|
|
377
|
+
*/
|
|
378
|
+
on(event, cb) {
|
|
379
|
+
if (!this.#listeners.has(event)) {
|
|
380
|
+
this.#listeners.set(event, new Set());
|
|
381
|
+
}
|
|
382
|
+
this.#listeners.get(event).add(cb);
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
/**
|
|
386
|
+
* Remove a listener.
|
|
387
|
+
* @param {string} event
|
|
388
|
+
* @param {Function} cb
|
|
389
|
+
*/
|
|
390
|
+
off(event, cb) {
|
|
391
|
+
const set = this.#listeners.get(event);
|
|
392
|
+
if (set) set.delete(cb);
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
/**
|
|
396
|
+
* Serialize state for inspection.
|
|
397
|
+
* @returns {object}
|
|
398
|
+
*/
|
|
399
|
+
toJSON() {
|
|
400
|
+
return {
|
|
401
|
+
status: this.#status,
|
|
402
|
+
missedCount: this.#missedCount,
|
|
403
|
+
totalPings: this.#totalPings,
|
|
404
|
+
totalPongs: this.#totalPongs,
|
|
405
|
+
lastPongTime: this.#lastPongTime,
|
|
406
|
+
};
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
// -- Internal ---------------------------------------------------------------
|
|
410
|
+
|
|
411
|
+
/** Send a ping and start a pong timeout. */
|
|
412
|
+
#sendPing() {
|
|
413
|
+
if (this.#waitingForPong) {
|
|
414
|
+
// Previous ping still pending — count as missed
|
|
415
|
+
this.#onPongTimeout();
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
this.#totalPings++;
|
|
419
|
+
this.#waitingForPong = true;
|
|
420
|
+
|
|
421
|
+
try {
|
|
422
|
+
this.#pingFn(this.#transport);
|
|
423
|
+
} catch {
|
|
424
|
+
this.#onPongTimeout();
|
|
425
|
+
return;
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
this.#emit('ping', { transport: this.#transport });
|
|
429
|
+
this.#timeoutTimer = setTimeout(() => this.#onPongTimeout(), this.#timeoutMs);
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
/** Handle a pong timeout. */
|
|
433
|
+
#onPongTimeout() {
|
|
434
|
+
this.#waitingForPong = false;
|
|
435
|
+
if (this.#timeoutTimer !== null) {
|
|
436
|
+
clearTimeout(this.#timeoutTimer);
|
|
437
|
+
this.#timeoutTimer = null;
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
this.#missedCount++;
|
|
441
|
+
this.#emit('pong-timeout', { transport: this.#transport, missedCount: this.#missedCount });
|
|
442
|
+
|
|
443
|
+
const oldStatus = this.#status;
|
|
444
|
+
if (this.#missedCount >= this.#maxMissed) {
|
|
445
|
+
this.#status = 'unhealthy';
|
|
446
|
+
if (oldStatus !== 'unhealthy') {
|
|
447
|
+
this.#emit('unhealthy', { transport: this.#transport, missedCount: this.#missedCount });
|
|
448
|
+
}
|
|
449
|
+
} else if (this.#missedCount >= 1) {
|
|
450
|
+
this.#status = 'degraded';
|
|
451
|
+
if (oldStatus !== 'degraded' && oldStatus !== 'unhealthy') {
|
|
452
|
+
this.#emit('degraded', { transport: this.#transport, missedCount: this.#missedCount });
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
/**
|
|
458
|
+
* Emit an event to all registered listeners, swallowing errors.
|
|
459
|
+
* @param {string} event
|
|
460
|
+
* @param {*} data
|
|
461
|
+
*/
|
|
462
|
+
#emit(event, data) {
|
|
463
|
+
const set = this.#listeners.get(event);
|
|
464
|
+
if (!set) return;
|
|
465
|
+
for (const cb of [...set]) {
|
|
466
|
+
try { cb(data); } catch (e) { silentCatch('clawser-mesh-hardening', 'swallow', e) }
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
// ---------------------------------------------------------------------------
|
|
472
|
+
// 3. ConnectionPool — per-peer connection pooling with idle eviction
|
|
473
|
+
// ---------------------------------------------------------------------------
|
|
474
|
+
|
|
475
|
+
/**
|
|
476
|
+
* Manages a pool of transport connections per peer with configurable
|
|
477
|
+
* limits and idle eviction.
|
|
478
|
+
*
|
|
479
|
+
* @example
|
|
480
|
+
* const pool = new ConnectionPool({ maxPerPeer: 3, idleTimeoutMs: 60000 });
|
|
481
|
+
* pool.add('peer-abc', transport);
|
|
482
|
+
* const conn = pool.acquire('peer-abc');
|
|
483
|
+
*/
|
|
484
|
+
export class ConnectionPool {
|
|
485
|
+
/** @type {number} */
|
|
486
|
+
#maxPerPeer;
|
|
487
|
+
|
|
488
|
+
/** @type {number} */
|
|
489
|
+
#idleTimeoutMs;
|
|
490
|
+
|
|
491
|
+
/** @type {Map<string, Array<{ transport: object, lastUsed: number, acquired: boolean }>>} */
|
|
492
|
+
#pools = new Map();
|
|
493
|
+
|
|
494
|
+
/** @type {*} */
|
|
495
|
+
#evictionTimer = null;
|
|
496
|
+
|
|
497
|
+
/** @type {number} */
|
|
498
|
+
#evictionIntervalMs;
|
|
499
|
+
|
|
500
|
+
/** @type {Function} */
|
|
501
|
+
#nowFn;
|
|
502
|
+
|
|
503
|
+
/**
|
|
504
|
+
* @param {object} [opts]
|
|
505
|
+
* @param {number} [opts.maxPerPeer=3] - Maximum connections per peer
|
|
506
|
+
* @param {number} [opts.idleTimeoutMs=60000] - Evict connections idle longer than this
|
|
507
|
+
* @param {number} [opts.evictionIntervalMs=30000] - How often to run idle eviction
|
|
508
|
+
* @param {Function} [opts.nowFn=Date.now]
|
|
509
|
+
*/
|
|
510
|
+
constructor(opts = {}) {
|
|
511
|
+
this.#maxPerPeer = opts.maxPerPeer ?? 3;
|
|
512
|
+
this.#idleTimeoutMs = opts.idleTimeoutMs ?? 60000;
|
|
513
|
+
this.#evictionIntervalMs = opts.evictionIntervalMs ?? 30000;
|
|
514
|
+
this.#nowFn = opts.nowFn ?? Date.now;
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
/** Maximum connections allowed per peer. */
|
|
518
|
+
get maxPerPeer() {
|
|
519
|
+
return this.#maxPerPeer;
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
/** Total connections across all peers. */
|
|
523
|
+
get totalConnections() {
|
|
524
|
+
let count = 0;
|
|
525
|
+
for (const entries of this.#pools.values()) {
|
|
526
|
+
count += entries.length;
|
|
527
|
+
}
|
|
528
|
+
return count;
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
/** Number of peers with at least one connection. */
|
|
532
|
+
get peerCount() {
|
|
533
|
+
return this.#pools.size;
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
/**
|
|
537
|
+
* Add a transport to the pool for a given peer.
|
|
538
|
+
* If the pool for that peer is at capacity, the oldest idle connection
|
|
539
|
+
* is evicted. Returns false if pool is full and no idle connections exist.
|
|
540
|
+
*
|
|
541
|
+
* @param {string} peerId
|
|
542
|
+
* @param {object} transport
|
|
543
|
+
* @returns {boolean} true if added successfully
|
|
544
|
+
*/
|
|
545
|
+
add(peerId, transport) {
|
|
546
|
+
if (!this.#pools.has(peerId)) {
|
|
547
|
+
this.#pools.set(peerId, []);
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
const entries = this.#pools.get(peerId);
|
|
551
|
+
|
|
552
|
+
if (entries.length >= this.#maxPerPeer) {
|
|
553
|
+
// Try to evict an idle (non-acquired) entry
|
|
554
|
+
const idleIdx = entries.findIndex(e => !e.acquired);
|
|
555
|
+
if (idleIdx === -1) return false;
|
|
556
|
+
|
|
557
|
+
const evicted = entries.splice(idleIdx, 1)[0];
|
|
558
|
+
if (typeof evicted.transport.close === 'function') {
|
|
559
|
+
try { evicted.transport.close(); } catch (e) { silentCatch('clawser-mesh-hardening', 'evicted.transport.close', e) }
|
|
560
|
+
}
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
entries.push({
|
|
564
|
+
transport,
|
|
565
|
+
lastUsed: this.#nowFn(),
|
|
566
|
+
acquired: false,
|
|
567
|
+
});
|
|
568
|
+
|
|
569
|
+
return true;
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
/**
|
|
573
|
+
* Acquire an idle connection for a peer. Marks it as acquired.
|
|
574
|
+
* Returns null if no idle connections exist.
|
|
575
|
+
*
|
|
576
|
+
* @param {string} peerId
|
|
577
|
+
* @returns {object|null} The transport, or null
|
|
578
|
+
*/
|
|
579
|
+
acquire(peerId) {
|
|
580
|
+
const entries = this.#pools.get(peerId);
|
|
581
|
+
if (!entries) return null;
|
|
582
|
+
|
|
583
|
+
const entry = entries.find(e => !e.acquired);
|
|
584
|
+
if (!entry) return null;
|
|
585
|
+
|
|
586
|
+
entry.acquired = true;
|
|
587
|
+
entry.lastUsed = this.#nowFn();
|
|
588
|
+
return entry.transport;
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
/**
|
|
592
|
+
* Release a previously acquired connection back to the pool.
|
|
593
|
+
*
|
|
594
|
+
* @param {string} peerId
|
|
595
|
+
* @param {object} transport
|
|
596
|
+
* @returns {boolean} true if found and released
|
|
597
|
+
*/
|
|
598
|
+
release(peerId, transport) {
|
|
599
|
+
const entries = this.#pools.get(peerId);
|
|
600
|
+
if (!entries) return false;
|
|
601
|
+
|
|
602
|
+
const entry = entries.find(e => e.transport === transport);
|
|
603
|
+
if (!entry) return false;
|
|
604
|
+
|
|
605
|
+
entry.acquired = false;
|
|
606
|
+
entry.lastUsed = this.#nowFn();
|
|
607
|
+
return true;
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
/**
|
|
611
|
+
* Remove a specific transport from the pool.
|
|
612
|
+
*
|
|
613
|
+
* @param {string} peerId
|
|
614
|
+
* @param {object} transport
|
|
615
|
+
* @returns {boolean} true if found and removed
|
|
616
|
+
*/
|
|
617
|
+
remove(peerId, transport) {
|
|
618
|
+
const entries = this.#pools.get(peerId);
|
|
619
|
+
if (!entries) return false;
|
|
620
|
+
|
|
621
|
+
const idx = entries.findIndex(e => e.transport === transport);
|
|
622
|
+
if (idx === -1) return false;
|
|
623
|
+
|
|
624
|
+
entries.splice(idx, 1);
|
|
625
|
+
if (entries.length === 0) {
|
|
626
|
+
this.#pools.delete(peerId);
|
|
627
|
+
}
|
|
628
|
+
return true;
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
/**
|
|
632
|
+
* Get count of connections for a specific peer.
|
|
633
|
+
*
|
|
634
|
+
* @param {string} peerId
|
|
635
|
+
* @returns {number}
|
|
636
|
+
*/
|
|
637
|
+
countFor(peerId) {
|
|
638
|
+
const entries = this.#pools.get(peerId);
|
|
639
|
+
return entries ? entries.length : 0;
|
|
640
|
+
}
|
|
641
|
+
|
|
642
|
+
/**
|
|
643
|
+
* Get count of idle (non-acquired) connections for a peer.
|
|
644
|
+
*
|
|
645
|
+
* @param {string} peerId
|
|
646
|
+
* @returns {number}
|
|
647
|
+
*/
|
|
648
|
+
idleCountFor(peerId) {
|
|
649
|
+
const entries = this.#pools.get(peerId);
|
|
650
|
+
if (!entries) return 0;
|
|
651
|
+
return entries.filter(e => !e.acquired).length;
|
|
652
|
+
}
|
|
653
|
+
|
|
654
|
+
/**
|
|
655
|
+
* Start periodic idle eviction.
|
|
656
|
+
*/
|
|
657
|
+
startEviction() {
|
|
658
|
+
this.stopEviction();
|
|
659
|
+
this.#evictionTimer = setInterval(() => this.evictIdle(), this.#evictionIntervalMs);
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
/**
|
|
663
|
+
* Stop periodic idle eviction.
|
|
664
|
+
*/
|
|
665
|
+
stopEviction() {
|
|
666
|
+
if (this.#evictionTimer !== null) {
|
|
667
|
+
clearInterval(this.#evictionTimer);
|
|
668
|
+
this.#evictionTimer = null;
|
|
669
|
+
}
|
|
670
|
+
}
|
|
671
|
+
|
|
672
|
+
/**
|
|
673
|
+
* Evict all idle connections that have been unused longer than idleTimeoutMs.
|
|
674
|
+
* Returns the number of evicted connections.
|
|
675
|
+
*
|
|
676
|
+
* @returns {number}
|
|
677
|
+
*/
|
|
678
|
+
evictIdle() {
|
|
679
|
+
const now = this.#nowFn();
|
|
680
|
+
let evicted = 0;
|
|
681
|
+
|
|
682
|
+
for (const [peerId, entries] of this.#pools) {
|
|
683
|
+
for (let i = entries.length - 1; i >= 0; i--) {
|
|
684
|
+
const entry = entries[i];
|
|
685
|
+
if (!entry.acquired && (now - entry.lastUsed) > this.#idleTimeoutMs) {
|
|
686
|
+
if (typeof entry.transport.close === 'function') {
|
|
687
|
+
try { entry.transport.close(); } catch (e) { silentCatch('clawser-mesh-hardening', 'entry.transport.close', e) }
|
|
688
|
+
}
|
|
689
|
+
entries.splice(i, 1);
|
|
690
|
+
evicted++;
|
|
691
|
+
}
|
|
692
|
+
}
|
|
693
|
+
if (entries.length === 0) {
|
|
694
|
+
this.#pools.delete(peerId);
|
|
695
|
+
}
|
|
696
|
+
}
|
|
697
|
+
|
|
698
|
+
return evicted;
|
|
699
|
+
}
|
|
700
|
+
|
|
701
|
+
/**
|
|
702
|
+
* Drain all connections, closing each transport.
|
|
703
|
+
*/
|
|
704
|
+
drainAll() {
|
|
705
|
+
for (const [, entries] of this.#pools) {
|
|
706
|
+
for (const entry of entries) {
|
|
707
|
+
if (typeof entry.transport.close === 'function') {
|
|
708
|
+
try { entry.transport.close(); } catch (e) { silentCatch('clawser-mesh-hardening', 'entry.transport.close', e) }
|
|
709
|
+
}
|
|
710
|
+
}
|
|
711
|
+
}
|
|
712
|
+
this.#pools.clear();
|
|
713
|
+
this.stopEviction();
|
|
714
|
+
}
|
|
715
|
+
|
|
716
|
+
/**
|
|
717
|
+
* Serialize state for inspection.
|
|
718
|
+
* @returns {object}
|
|
719
|
+
*/
|
|
720
|
+
toJSON() {
|
|
721
|
+
const pools = {};
|
|
722
|
+
for (const [peerId, entries] of this.#pools) {
|
|
723
|
+
pools[peerId] = entries.map(e => ({
|
|
724
|
+
acquired: e.acquired,
|
|
725
|
+
lastUsed: e.lastUsed,
|
|
726
|
+
transportType: e.transport.type ?? 'unknown',
|
|
727
|
+
}));
|
|
728
|
+
}
|
|
729
|
+
return {
|
|
730
|
+
maxPerPeer: this.#maxPerPeer,
|
|
731
|
+
idleTimeoutMs: this.#idleTimeoutMs,
|
|
732
|
+
totalConnections: this.totalConnections,
|
|
733
|
+
peerCount: this.peerCount,
|
|
734
|
+
pools,
|
|
735
|
+
};
|
|
736
|
+
}
|
|
737
|
+
}
|
|
738
|
+
|
|
739
|
+
// ---------------------------------------------------------------------------
|
|
740
|
+
// 4. TransportMetrics — per-transport counters and latency tracking
|
|
741
|
+
// ---------------------------------------------------------------------------
|
|
742
|
+
|
|
743
|
+
/**
|
|
744
|
+
* Tracks per-transport metrics: bytes sent/received, message counts,
|
|
745
|
+
* error counts, and latency measurements.
|
|
746
|
+
*
|
|
747
|
+
* @example
|
|
748
|
+
* const metrics = new TransportMetrics('wsh-ws');
|
|
749
|
+
* metrics.recordSend(128);
|
|
750
|
+
* metrics.recordReceive(256);
|
|
751
|
+
* metrics.recordLatency(42);
|
|
752
|
+
* console.log(metrics.toJSON());
|
|
753
|
+
*/
|
|
754
|
+
export class TransportMetrics {
|
|
755
|
+
/** @type {string} */
|
|
756
|
+
#transportId;
|
|
757
|
+
|
|
758
|
+
/** @type {number} */
|
|
759
|
+
#bytesSent = 0;
|
|
760
|
+
|
|
761
|
+
/** @type {number} */
|
|
762
|
+
#bytesReceived = 0;
|
|
763
|
+
|
|
764
|
+
/** @type {number} */
|
|
765
|
+
#messagesSent = 0;
|
|
766
|
+
|
|
767
|
+
/** @type {number} */
|
|
768
|
+
#messagesReceived = 0;
|
|
769
|
+
|
|
770
|
+
/** @type {number} */
|
|
771
|
+
#errors = 0;
|
|
772
|
+
|
|
773
|
+
/** @type {number[]} */
|
|
774
|
+
#latencySamples = [];
|
|
775
|
+
|
|
776
|
+
/** @type {number} */
|
|
777
|
+
#maxLatencySamples;
|
|
778
|
+
|
|
779
|
+
/** @type {number} */
|
|
780
|
+
#createdAt;
|
|
781
|
+
|
|
782
|
+
/** @type {Function} */
|
|
783
|
+
#nowFn;
|
|
784
|
+
|
|
785
|
+
/**
|
|
786
|
+
* @param {string} transportId - Identifier for this transport instance
|
|
787
|
+
* @param {object} [opts]
|
|
788
|
+
* @param {number} [opts.maxLatencySamples=100] - Rolling window size for latency
|
|
789
|
+
* @param {Function} [opts.nowFn=Date.now]
|
|
790
|
+
*/
|
|
791
|
+
constructor(transportId, opts = {}) {
|
|
792
|
+
if (!transportId) throw new Error('transportId is required');
|
|
793
|
+
this.#transportId = transportId;
|
|
794
|
+
this.#maxLatencySamples = opts.maxLatencySamples ?? 100;
|
|
795
|
+
this.#nowFn = opts.nowFn ?? Date.now;
|
|
796
|
+
this.#createdAt = this.#nowFn();
|
|
797
|
+
}
|
|
798
|
+
|
|
799
|
+
/** Transport identifier. */
|
|
800
|
+
get transportId() {
|
|
801
|
+
return this.#transportId;
|
|
802
|
+
}
|
|
803
|
+
|
|
804
|
+
/** Total bytes sent. */
|
|
805
|
+
get bytesSent() {
|
|
806
|
+
return this.#bytesSent;
|
|
807
|
+
}
|
|
808
|
+
|
|
809
|
+
/** Total bytes received. */
|
|
810
|
+
get bytesReceived() {
|
|
811
|
+
return this.#bytesReceived;
|
|
812
|
+
}
|
|
813
|
+
|
|
814
|
+
/** Total messages sent. */
|
|
815
|
+
get messagesSent() {
|
|
816
|
+
return this.#messagesSent;
|
|
817
|
+
}
|
|
818
|
+
|
|
819
|
+
/** Total messages received. */
|
|
820
|
+
get messagesReceived() {
|
|
821
|
+
return this.#messagesReceived;
|
|
822
|
+
}
|
|
823
|
+
|
|
824
|
+
/** Total error count. */
|
|
825
|
+
get errors() {
|
|
826
|
+
return this.#errors;
|
|
827
|
+
}
|
|
828
|
+
|
|
829
|
+
/**
|
|
830
|
+
* Record a send operation.
|
|
831
|
+
* @param {number} bytes - Byte length of the message
|
|
832
|
+
*/
|
|
833
|
+
recordSend(bytes) {
|
|
834
|
+
this.#messagesSent++;
|
|
835
|
+
this.#bytesSent += bytes;
|
|
836
|
+
}
|
|
837
|
+
|
|
838
|
+
/**
|
|
839
|
+
* Record a receive operation.
|
|
840
|
+
* @param {number} bytes - Byte length of the message
|
|
841
|
+
*/
|
|
842
|
+
recordReceive(bytes) {
|
|
843
|
+
this.#messagesReceived++;
|
|
844
|
+
this.#bytesReceived += bytes;
|
|
845
|
+
}
|
|
846
|
+
|
|
847
|
+
/**
|
|
848
|
+
* Record an error.
|
|
849
|
+
*/
|
|
850
|
+
recordError() {
|
|
851
|
+
this.#errors++;
|
|
852
|
+
}
|
|
853
|
+
|
|
854
|
+
/**
|
|
855
|
+
* Record a latency sample.
|
|
856
|
+
* @param {number} ms - Latency in milliseconds
|
|
857
|
+
*/
|
|
858
|
+
recordLatency(ms) {
|
|
859
|
+
this.#latencySamples.push(ms);
|
|
860
|
+
if (this.#latencySamples.length > this.#maxLatencySamples) {
|
|
861
|
+
this.#latencySamples.shift();
|
|
862
|
+
}
|
|
863
|
+
}
|
|
864
|
+
|
|
865
|
+
/**
|
|
866
|
+
* Get latency statistics from the rolling window.
|
|
867
|
+
* @returns {{ min: number, max: number, avg: number, p50: number, p95: number, p99: number, count: number }}
|
|
868
|
+
*/
|
|
869
|
+
getLatencyStats() {
|
|
870
|
+
const samples = this.#latencySamples;
|
|
871
|
+
if (samples.length === 0) {
|
|
872
|
+
return { min: 0, max: 0, avg: 0, p50: 0, p95: 0, p99: 0, count: 0 };
|
|
873
|
+
}
|
|
874
|
+
|
|
875
|
+
const sorted = [...samples].sort((a, b) => a - b);
|
|
876
|
+
const sum = sorted.reduce((a, b) => a + b, 0);
|
|
877
|
+
|
|
878
|
+
return {
|
|
879
|
+
min: sorted[0],
|
|
880
|
+
max: sorted[sorted.length - 1],
|
|
881
|
+
avg: Math.round(sum / sorted.length),
|
|
882
|
+
p50: sorted[Math.floor(sorted.length * 0.5)],
|
|
883
|
+
p95: sorted[Math.floor(sorted.length * 0.95)],
|
|
884
|
+
p99: sorted[Math.floor(sorted.length * 0.99)],
|
|
885
|
+
count: sorted.length,
|
|
886
|
+
};
|
|
887
|
+
}
|
|
888
|
+
|
|
889
|
+
/**
|
|
890
|
+
* Reset all counters to zero.
|
|
891
|
+
*/
|
|
892
|
+
reset() {
|
|
893
|
+
this.#bytesSent = 0;
|
|
894
|
+
this.#bytesReceived = 0;
|
|
895
|
+
this.#messagesSent = 0;
|
|
896
|
+
this.#messagesReceived = 0;
|
|
897
|
+
this.#errors = 0;
|
|
898
|
+
this.#latencySamples = [];
|
|
899
|
+
}
|
|
900
|
+
|
|
901
|
+
/**
|
|
902
|
+
* Serialize all metrics.
|
|
903
|
+
* @returns {object}
|
|
904
|
+
*/
|
|
905
|
+
toJSON() {
|
|
906
|
+
return {
|
|
907
|
+
transportId: this.#transportId,
|
|
908
|
+
bytesSent: this.#bytesSent,
|
|
909
|
+
bytesReceived: this.#bytesReceived,
|
|
910
|
+
messagesSent: this.#messagesSent,
|
|
911
|
+
messagesReceived: this.#messagesReceived,
|
|
912
|
+
errors: this.#errors,
|
|
913
|
+
latency: this.getLatencyStats(),
|
|
914
|
+
uptimeMs: this.#nowFn() - this.#createdAt,
|
|
915
|
+
};
|
|
916
|
+
}
|
|
917
|
+
}
|
|
918
|
+
|
|
919
|
+
/**
|
|
920
|
+
* Registry that manages TransportMetrics instances keyed by transport ID.
|
|
921
|
+
*
|
|
922
|
+
* @example
|
|
923
|
+
* const registry = new MetricsRegistry();
|
|
924
|
+
* registry.getOrCreate('ws-peer-abc').recordSend(128);
|
|
925
|
+
*/
|
|
926
|
+
export class MetricsRegistry {
|
|
927
|
+
/** @type {Map<string, TransportMetrics>} */
|
|
928
|
+
#metrics = new Map();
|
|
929
|
+
|
|
930
|
+
/**
|
|
931
|
+
* Get or create metrics for a transport ID.
|
|
932
|
+
* @param {string} transportId
|
|
933
|
+
* @returns {TransportMetrics}
|
|
934
|
+
*/
|
|
935
|
+
getOrCreate(transportId) {
|
|
936
|
+
if (!this.#metrics.has(transportId)) {
|
|
937
|
+
this.#metrics.set(transportId, new TransportMetrics(transportId));
|
|
938
|
+
}
|
|
939
|
+
return this.#metrics.get(transportId);
|
|
940
|
+
}
|
|
941
|
+
|
|
942
|
+
/**
|
|
943
|
+
* Get metrics for a transport ID, or null if not tracked.
|
|
944
|
+
* @param {string} transportId
|
|
945
|
+
* @returns {TransportMetrics|null}
|
|
946
|
+
*/
|
|
947
|
+
get(transportId) {
|
|
948
|
+
return this.#metrics.get(transportId) ?? null;
|
|
949
|
+
}
|
|
950
|
+
|
|
951
|
+
/**
|
|
952
|
+
* Remove metrics for a transport.
|
|
953
|
+
* @param {string} transportId
|
|
954
|
+
* @returns {boolean}
|
|
955
|
+
*/
|
|
956
|
+
remove(transportId) {
|
|
957
|
+
return this.#metrics.delete(transportId);
|
|
958
|
+
}
|
|
959
|
+
|
|
960
|
+
/** Number of tracked transports. */
|
|
961
|
+
get size() {
|
|
962
|
+
return this.#metrics.size;
|
|
963
|
+
}
|
|
964
|
+
|
|
965
|
+
/**
|
|
966
|
+
* Serialize all metrics.
|
|
967
|
+
* @returns {object}
|
|
968
|
+
*/
|
|
969
|
+
toJSON() {
|
|
970
|
+
const result = {};
|
|
971
|
+
for (const [id, m] of this.#metrics) {
|
|
972
|
+
result[id] = m.toJSON();
|
|
973
|
+
}
|
|
974
|
+
return result;
|
|
975
|
+
}
|
|
976
|
+
}
|
|
977
|
+
|
|
978
|
+
// ---------------------------------------------------------------------------
|
|
979
|
+
// 5. TransportFailover — graceful degradation across transport types
|
|
980
|
+
// ---------------------------------------------------------------------------
|
|
981
|
+
|
|
982
|
+
/**
|
|
983
|
+
* Wraps a MeshTransportNegotiator to provide transparent failover
|
|
984
|
+
* when the active transport becomes unhealthy. Monitors the active
|
|
985
|
+
* transport and automatically falls back to the next available type.
|
|
986
|
+
*
|
|
987
|
+
* @example
|
|
988
|
+
* const failover = new TransportFailover({
|
|
989
|
+
* negotiator,
|
|
990
|
+
* endpoints: { webrtc: 'rtc://p', 'wsh-ws': 'ws://p' },
|
|
991
|
+
* healthCheckOpts: { intervalMs: 5000 },
|
|
992
|
+
* });
|
|
993
|
+
* const transport = await failover.connect();
|
|
994
|
+
*/
|
|
995
|
+
export class TransportFailover {
|
|
996
|
+
/** @type {object} */
|
|
997
|
+
#negotiator;
|
|
998
|
+
|
|
999
|
+
/** @type {object} */
|
|
1000
|
+
#endpoints;
|
|
1001
|
+
|
|
1002
|
+
/** @type {object} */
|
|
1003
|
+
#auth;
|
|
1004
|
+
|
|
1005
|
+
/** @type {object} */
|
|
1006
|
+
#activeTransport = null;
|
|
1007
|
+
|
|
1008
|
+
/** @type {string[]} */
|
|
1009
|
+
#failedTypes = [];
|
|
1010
|
+
|
|
1011
|
+
/** @type {boolean} */
|
|
1012
|
+
#failingOver = false;
|
|
1013
|
+
|
|
1014
|
+
/** @type {Map<string, Set<Function>>} */
|
|
1015
|
+
#listeners = new Map();
|
|
1016
|
+
|
|
1017
|
+
/** @type {RetryWithBackoff|null} */
|
|
1018
|
+
#retry;
|
|
1019
|
+
|
|
1020
|
+
/**
|
|
1021
|
+
* @param {object} opts
|
|
1022
|
+
* @param {object} opts.negotiator - MeshTransportNegotiator instance
|
|
1023
|
+
* @param {object} opts.endpoints - Map of type -> endpoint string
|
|
1024
|
+
* @param {object} [opts.auth] - Auth credentials
|
|
1025
|
+
* @param {RetryWithBackoff} [opts.retry] - Retry instance for connection attempts
|
|
1026
|
+
*/
|
|
1027
|
+
constructor(opts) {
|
|
1028
|
+
if (!opts.negotiator) throw new Error('negotiator is required');
|
|
1029
|
+
if (!opts.endpoints) throw new Error('endpoints is required');
|
|
1030
|
+
this.#negotiator = opts.negotiator;
|
|
1031
|
+
this.#endpoints = { ...opts.endpoints };
|
|
1032
|
+
this.#auth = opts.auth ?? null;
|
|
1033
|
+
this.#retry = opts.retry ?? null;
|
|
1034
|
+
}
|
|
1035
|
+
|
|
1036
|
+
/** Currently active transport, or null. */
|
|
1037
|
+
get activeTransport() {
|
|
1038
|
+
return this.#activeTransport;
|
|
1039
|
+
}
|
|
1040
|
+
|
|
1041
|
+
/** Transport types that have failed and been excluded. */
|
|
1042
|
+
get failedTypes() {
|
|
1043
|
+
return [...this.#failedTypes];
|
|
1044
|
+
}
|
|
1045
|
+
|
|
1046
|
+
/** Whether a failover is currently in progress. */
|
|
1047
|
+
get failingOver() {
|
|
1048
|
+
return this.#failingOver;
|
|
1049
|
+
}
|
|
1050
|
+
|
|
1051
|
+
/**
|
|
1052
|
+
* Establish an initial connection using the negotiator.
|
|
1053
|
+
*
|
|
1054
|
+
* @returns {Promise<object>} The connected transport
|
|
1055
|
+
*/
|
|
1056
|
+
async connect() {
|
|
1057
|
+
const negotiate = () => this.#negotiator.negotiate(this.#endpoints, this.#auth);
|
|
1058
|
+
const transport = this.#retry
|
|
1059
|
+
? await this.#retry.execute(negotiate)
|
|
1060
|
+
: await negotiate();
|
|
1061
|
+
|
|
1062
|
+
this.#activeTransport = transport;
|
|
1063
|
+
this.#emit('connected', { transport });
|
|
1064
|
+
return transport;
|
|
1065
|
+
}
|
|
1066
|
+
|
|
1067
|
+
/**
|
|
1068
|
+
* Trigger a failover: mark the current transport type as failed,
|
|
1069
|
+
* close it, and negotiate a new connection excluding failed types.
|
|
1070
|
+
*
|
|
1071
|
+
* @param {string} [reason='unknown'] - Reason for failover
|
|
1072
|
+
* @returns {Promise<object>} The new transport
|
|
1073
|
+
* @throws {Error} If no transports are available
|
|
1074
|
+
*/
|
|
1075
|
+
async failover(reason = 'unknown') {
|
|
1076
|
+
if (this.#failingOver) {
|
|
1077
|
+
throw new Error('Failover already in progress');
|
|
1078
|
+
}
|
|
1079
|
+
|
|
1080
|
+
this.#failingOver = true;
|
|
1081
|
+
this.#emit('failover-start', { reason, previousType: this.#activeTransport?.type });
|
|
1082
|
+
|
|
1083
|
+
try {
|
|
1084
|
+
// Mark current transport type as failed
|
|
1085
|
+
if (this.#activeTransport) {
|
|
1086
|
+
const failedType = this.#activeTransport.type;
|
|
1087
|
+
if (!this.#failedTypes.includes(failedType)) {
|
|
1088
|
+
this.#failedTypes.push(failedType);
|
|
1089
|
+
}
|
|
1090
|
+
// Close the old transport
|
|
1091
|
+
if (typeof this.#activeTransport.close === 'function') {
|
|
1092
|
+
try { this.#activeTransport.close(); } catch (e) { silentCatch('clawser-mesh-hardening', 'this', e) }
|
|
1093
|
+
}
|
|
1094
|
+
this.#activeTransport = null;
|
|
1095
|
+
}
|
|
1096
|
+
|
|
1097
|
+
// Build filtered endpoints excluding failed types
|
|
1098
|
+
const filteredEndpoints = {};
|
|
1099
|
+
for (const [type, ep] of Object.entries(this.#endpoints)) {
|
|
1100
|
+
if (!this.#failedTypes.includes(type)) {
|
|
1101
|
+
filteredEndpoints[type] = ep;
|
|
1102
|
+
}
|
|
1103
|
+
}
|
|
1104
|
+
|
|
1105
|
+
if (Object.keys(filteredEndpoints).length === 0) {
|
|
1106
|
+
throw new Error(`No transports available (all failed: ${this.#failedTypes.join(', ')})`);
|
|
1107
|
+
}
|
|
1108
|
+
|
|
1109
|
+
const negotiate = () => this.#negotiator.negotiate(filteredEndpoints, this.#auth);
|
|
1110
|
+
const transport = this.#retry
|
|
1111
|
+
? await this.#retry.execute(negotiate)
|
|
1112
|
+
: await negotiate();
|
|
1113
|
+
|
|
1114
|
+
this.#activeTransport = transport;
|
|
1115
|
+
this.#emit('failover-complete', { transport, reason });
|
|
1116
|
+
return transport;
|
|
1117
|
+
} catch (err) {
|
|
1118
|
+
this.#emit('failover-failed', { reason, error: err.message });
|
|
1119
|
+
throw err;
|
|
1120
|
+
} finally {
|
|
1121
|
+
this.#failingOver = false;
|
|
1122
|
+
}
|
|
1123
|
+
}
|
|
1124
|
+
|
|
1125
|
+
/**
|
|
1126
|
+
* Reset the list of failed transport types, allowing them to be
|
|
1127
|
+
* retried on the next failover.
|
|
1128
|
+
*/
|
|
1129
|
+
resetFailedTypes() {
|
|
1130
|
+
this.#failedTypes = [];
|
|
1131
|
+
}
|
|
1132
|
+
|
|
1133
|
+
/**
|
|
1134
|
+
* Register a listener for a failover event.
|
|
1135
|
+
* Events: 'connected', 'failover-start', 'failover-complete', 'failover-failed'
|
|
1136
|
+
*
|
|
1137
|
+
* @param {string} event
|
|
1138
|
+
* @param {Function} cb
|
|
1139
|
+
*/
|
|
1140
|
+
on(event, cb) {
|
|
1141
|
+
if (!this.#listeners.has(event)) {
|
|
1142
|
+
this.#listeners.set(event, new Set());
|
|
1143
|
+
}
|
|
1144
|
+
this.#listeners.get(event).add(cb);
|
|
1145
|
+
}
|
|
1146
|
+
|
|
1147
|
+
/**
|
|
1148
|
+
* Remove a listener.
|
|
1149
|
+
* @param {string} event
|
|
1150
|
+
* @param {Function} cb
|
|
1151
|
+
*/
|
|
1152
|
+
off(event, cb) {
|
|
1153
|
+
const set = this.#listeners.get(event);
|
|
1154
|
+
if (set) set.delete(cb);
|
|
1155
|
+
}
|
|
1156
|
+
|
|
1157
|
+
/**
|
|
1158
|
+
* Serialize state for inspection.
|
|
1159
|
+
* @returns {object}
|
|
1160
|
+
*/
|
|
1161
|
+
toJSON() {
|
|
1162
|
+
return {
|
|
1163
|
+
activeTransportType: this.#activeTransport?.type ?? null,
|
|
1164
|
+
failedTypes: [...this.#failedTypes],
|
|
1165
|
+
failingOver: this.#failingOver,
|
|
1166
|
+
};
|
|
1167
|
+
}
|
|
1168
|
+
|
|
1169
|
+
// -- Internal ---------------------------------------------------------------
|
|
1170
|
+
|
|
1171
|
+
/**
|
|
1172
|
+
* Emit an event to all registered listeners, swallowing errors.
|
|
1173
|
+
* @param {string} event
|
|
1174
|
+
* @param {*} data
|
|
1175
|
+
*/
|
|
1176
|
+
#emit(event, data) {
|
|
1177
|
+
const set = this.#listeners.get(event);
|
|
1178
|
+
if (!set) return;
|
|
1179
|
+
for (const cb of [...set]) {
|
|
1180
|
+
try { cb(data); } catch (e) { silentCatch('clawser-mesh-hardening', 'swallow', e) }
|
|
1181
|
+
}
|
|
1182
|
+
}
|
|
1183
|
+
}
|