@enclave-vm/stream 0.0.1
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 +201 -0
- package/package.json +38 -0
- package/src/crypto/aes-gcm.d.ts +115 -0
- package/src/crypto/aes-gcm.js +293 -0
- package/src/crypto/aes-gcm.js.map +1 -0
- package/src/crypto/ecdh.d.ts +70 -0
- package/src/crypto/ecdh.js +166 -0
- package/src/crypto/ecdh.js.map +1 -0
- package/src/crypto/hkdf.d.ts +44 -0
- package/src/crypto/hkdf.js +123 -0
- package/src/crypto/hkdf.js.map +1 -0
- package/src/crypto/index.d.ts +9 -0
- package/src/crypto/index.js +40 -0
- package/src/crypto/index.js.map +1 -0
- package/src/index.d.ts +15 -0
- package/src/index.js +63 -0
- package/src/index.js.map +1 -0
- package/src/ndjson.d.ts +97 -0
- package/src/ndjson.js +263 -0
- package/src/ndjson.js.map +1 -0
- package/src/reconnect.d.ts +242 -0
- package/src/reconnect.js +372 -0
- package/src/reconnect.js.map +1 -0
package/src/reconnect.js
ADDED
|
@@ -0,0 +1,372 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* @enclave-vm/stream - Reconnection State Machine
|
|
4
|
+
*
|
|
5
|
+
* Handles connection drops and automatic reconnection with exponential backoff.
|
|
6
|
+
*/
|
|
7
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
8
|
+
exports.HeartbeatMonitor = exports.EventBuffer = exports.SequenceTracker = exports.ReconnectionStateMachine = exports.DEFAULT_RECONNECTION_CONFIG = exports.ConnectionState = void 0;
|
|
9
|
+
/**
|
|
10
|
+
* Connection state.
|
|
11
|
+
*/
|
|
12
|
+
exports.ConnectionState = {
|
|
13
|
+
/** Not connected */
|
|
14
|
+
Disconnected: 'disconnected',
|
|
15
|
+
/** Attempting to connect */
|
|
16
|
+
Connecting: 'connecting',
|
|
17
|
+
/** Successfully connected */
|
|
18
|
+
Connected: 'connected',
|
|
19
|
+
/** Connection lost, will attempt reconnection */
|
|
20
|
+
Reconnecting: 'reconnecting',
|
|
21
|
+
/** Permanently failed (max retries exceeded or fatal error) */
|
|
22
|
+
Failed: 'failed',
|
|
23
|
+
/** Intentionally closed */
|
|
24
|
+
Closed: 'closed',
|
|
25
|
+
};
|
|
26
|
+
/**
|
|
27
|
+
* Default reconnection configuration.
|
|
28
|
+
*/
|
|
29
|
+
exports.DEFAULT_RECONNECTION_CONFIG = {
|
|
30
|
+
maxRetries: 5,
|
|
31
|
+
initialDelayMs: 1000,
|
|
32
|
+
maxDelayMs: 30000,
|
|
33
|
+
backoffMultiplier: 2,
|
|
34
|
+
jitter: true,
|
|
35
|
+
jitterFactor: 0.3,
|
|
36
|
+
};
|
|
37
|
+
/**
|
|
38
|
+
* Reconnection state machine.
|
|
39
|
+
* Manages connection state and handles automatic reconnection.
|
|
40
|
+
*/
|
|
41
|
+
class ReconnectionStateMachine {
|
|
42
|
+
state = exports.ConnectionState.Disconnected;
|
|
43
|
+
retryCount = 0;
|
|
44
|
+
retryTimeoutId = null;
|
|
45
|
+
config;
|
|
46
|
+
onEvent;
|
|
47
|
+
constructor(options) {
|
|
48
|
+
this.config = { ...exports.DEFAULT_RECONNECTION_CONFIG, ...options.config };
|
|
49
|
+
this.onEvent = options.onEvent;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Get current connection state.
|
|
53
|
+
*/
|
|
54
|
+
getState() {
|
|
55
|
+
return this.state;
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Get current retry count.
|
|
59
|
+
*/
|
|
60
|
+
getRetryCount() {
|
|
61
|
+
return this.retryCount;
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Transition to a new state.
|
|
65
|
+
*/
|
|
66
|
+
transition(newState) {
|
|
67
|
+
const previousState = this.state;
|
|
68
|
+
if (previousState === newState)
|
|
69
|
+
return;
|
|
70
|
+
this.state = newState;
|
|
71
|
+
this.onEvent({ type: 'state_change', state: newState, previousState });
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* Calculate backoff delay with optional jitter.
|
|
75
|
+
*/
|
|
76
|
+
calculateBackoff() {
|
|
77
|
+
const { initialDelayMs, maxDelayMs, backoffMultiplier, jitter, jitterFactor } = this.config;
|
|
78
|
+
// Exponential backoff
|
|
79
|
+
let delay = initialDelayMs * Math.pow(backoffMultiplier, this.retryCount);
|
|
80
|
+
delay = Math.min(delay, maxDelayMs);
|
|
81
|
+
// Add jitter
|
|
82
|
+
if (jitter) {
|
|
83
|
+
const jitterAmount = delay * jitterFactor;
|
|
84
|
+
delay = delay - jitterAmount + Math.random() * jitterAmount * 2;
|
|
85
|
+
}
|
|
86
|
+
return Math.round(delay);
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Start connecting.
|
|
90
|
+
*/
|
|
91
|
+
connect() {
|
|
92
|
+
if (this.state === exports.ConnectionState.Connected || this.state === exports.ConnectionState.Connecting) {
|
|
93
|
+
return;
|
|
94
|
+
}
|
|
95
|
+
this.cancelRetry();
|
|
96
|
+
this.retryCount = 0;
|
|
97
|
+
this.transition(exports.ConnectionState.Connecting);
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* Called when connection succeeds.
|
|
101
|
+
*/
|
|
102
|
+
onConnected() {
|
|
103
|
+
this.cancelRetry();
|
|
104
|
+
this.retryCount = 0;
|
|
105
|
+
this.transition(exports.ConnectionState.Connected);
|
|
106
|
+
this.onEvent({ type: 'connected' });
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* Called when connection is lost.
|
|
110
|
+
*/
|
|
111
|
+
onDisconnected(reason) {
|
|
112
|
+
this.cancelRetry();
|
|
113
|
+
// If already closed or failed, don't change state
|
|
114
|
+
if (this.state === exports.ConnectionState.Closed || this.state === exports.ConnectionState.Failed) {
|
|
115
|
+
return;
|
|
116
|
+
}
|
|
117
|
+
this.onEvent({ type: 'disconnected', reason });
|
|
118
|
+
// Check if we should attempt reconnection
|
|
119
|
+
if (this.retryCount < this.config.maxRetries) {
|
|
120
|
+
this.scheduleRetry();
|
|
121
|
+
}
|
|
122
|
+
else {
|
|
123
|
+
this.transition(exports.ConnectionState.Failed);
|
|
124
|
+
this.onEvent({ type: 'failed', reason: reason ?? 'Max retries exceeded' });
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* Called when connection fails with a fatal error.
|
|
129
|
+
*/
|
|
130
|
+
onFatalError(reason) {
|
|
131
|
+
this.cancelRetry();
|
|
132
|
+
this.transition(exports.ConnectionState.Failed);
|
|
133
|
+
this.onEvent({ type: 'failed', reason });
|
|
134
|
+
}
|
|
135
|
+
/**
|
|
136
|
+
* Schedule a reconnection attempt.
|
|
137
|
+
*/
|
|
138
|
+
scheduleRetry() {
|
|
139
|
+
this.transition(exports.ConnectionState.Reconnecting);
|
|
140
|
+
const delayMs = this.calculateBackoff();
|
|
141
|
+
const attempt = this.retryCount + 1;
|
|
142
|
+
this.onEvent({ type: 'retry_scheduled', attempt, delayMs });
|
|
143
|
+
this.retryTimeoutId = setTimeout(() => {
|
|
144
|
+
this.retryTimeoutId = null;
|
|
145
|
+
this.retryCount++;
|
|
146
|
+
this.onEvent({ type: 'retry_started', attempt });
|
|
147
|
+
this.transition(exports.ConnectionState.Connecting);
|
|
148
|
+
}, delayMs);
|
|
149
|
+
}
|
|
150
|
+
/**
|
|
151
|
+
* Cancel any pending retry.
|
|
152
|
+
*/
|
|
153
|
+
cancelRetry() {
|
|
154
|
+
if (this.retryTimeoutId !== null) {
|
|
155
|
+
clearTimeout(this.retryTimeoutId);
|
|
156
|
+
this.retryTimeoutId = null;
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
/**
|
|
160
|
+
* Intentionally close the connection.
|
|
161
|
+
*/
|
|
162
|
+
close() {
|
|
163
|
+
this.cancelRetry();
|
|
164
|
+
this.transition(exports.ConnectionState.Closed);
|
|
165
|
+
}
|
|
166
|
+
/**
|
|
167
|
+
* Reset to initial state.
|
|
168
|
+
*/
|
|
169
|
+
reset() {
|
|
170
|
+
this.cancelRetry();
|
|
171
|
+
this.retryCount = 0;
|
|
172
|
+
this.transition(exports.ConnectionState.Disconnected);
|
|
173
|
+
}
|
|
174
|
+
/**
|
|
175
|
+
* Check if reconnection is possible.
|
|
176
|
+
*/
|
|
177
|
+
canReconnect() {
|
|
178
|
+
return (this.state !== exports.ConnectionState.Failed &&
|
|
179
|
+
this.state !== exports.ConnectionState.Closed &&
|
|
180
|
+
this.retryCount < this.config.maxRetries);
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
exports.ReconnectionStateMachine = ReconnectionStateMachine;
|
|
184
|
+
/**
|
|
185
|
+
* Sequence tracker for detecting gaps and enabling replay.
|
|
186
|
+
*/
|
|
187
|
+
class SequenceTracker {
|
|
188
|
+
lastSeq = 0;
|
|
189
|
+
gaps = [];
|
|
190
|
+
maxGaps;
|
|
191
|
+
constructor(maxGaps = 100) {
|
|
192
|
+
this.maxGaps = maxGaps;
|
|
193
|
+
}
|
|
194
|
+
/**
|
|
195
|
+
* Process a received sequence number.
|
|
196
|
+
* Returns any gaps detected.
|
|
197
|
+
*/
|
|
198
|
+
receive(seq) {
|
|
199
|
+
// First event
|
|
200
|
+
if (this.lastSeq === 0) {
|
|
201
|
+
this.lastSeq = seq;
|
|
202
|
+
return { gap: false };
|
|
203
|
+
}
|
|
204
|
+
// Expected sequence
|
|
205
|
+
if (seq === this.lastSeq + 1) {
|
|
206
|
+
this.lastSeq = seq;
|
|
207
|
+
return { gap: false };
|
|
208
|
+
}
|
|
209
|
+
// Duplicate or old event
|
|
210
|
+
if (seq <= this.lastSeq) {
|
|
211
|
+
return { gap: false };
|
|
212
|
+
}
|
|
213
|
+
// Gap detected
|
|
214
|
+
const missingStart = this.lastSeq + 1;
|
|
215
|
+
const missingEnd = seq - 1;
|
|
216
|
+
// Track gap (for replay)
|
|
217
|
+
if (this.gaps.length < this.maxGaps) {
|
|
218
|
+
this.gaps.push({ start: missingStart, end: missingEnd });
|
|
219
|
+
}
|
|
220
|
+
this.lastSeq = seq;
|
|
221
|
+
return { gap: true, missingStart, missingEnd };
|
|
222
|
+
}
|
|
223
|
+
/**
|
|
224
|
+
* Get the last received sequence number.
|
|
225
|
+
*/
|
|
226
|
+
getLastSeq() {
|
|
227
|
+
return this.lastSeq;
|
|
228
|
+
}
|
|
229
|
+
/**
|
|
230
|
+
* Get all detected gaps.
|
|
231
|
+
*/
|
|
232
|
+
getGaps() {
|
|
233
|
+
return [...this.gaps];
|
|
234
|
+
}
|
|
235
|
+
/**
|
|
236
|
+
* Clear a gap after it's been filled.
|
|
237
|
+
*/
|
|
238
|
+
clearGap(start, end) {
|
|
239
|
+
const index = this.gaps.findIndex((g) => g.start === start && g.end === end);
|
|
240
|
+
if (index !== -1) {
|
|
241
|
+
this.gaps.splice(index, 1);
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
/**
|
|
245
|
+
* Check if there are pending gaps.
|
|
246
|
+
*/
|
|
247
|
+
hasGaps() {
|
|
248
|
+
return this.gaps.length > 0;
|
|
249
|
+
}
|
|
250
|
+
/**
|
|
251
|
+
* Reset the tracker.
|
|
252
|
+
*/
|
|
253
|
+
reset() {
|
|
254
|
+
this.lastSeq = 0;
|
|
255
|
+
this.gaps.length = 0;
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
exports.SequenceTracker = SequenceTracker;
|
|
259
|
+
/**
|
|
260
|
+
* Event buffer for storing events during reconnection.
|
|
261
|
+
*/
|
|
262
|
+
class EventBuffer {
|
|
263
|
+
buffer = [];
|
|
264
|
+
maxSize;
|
|
265
|
+
constructor(maxSize = 1000) {
|
|
266
|
+
this.maxSize = maxSize;
|
|
267
|
+
}
|
|
268
|
+
/**
|
|
269
|
+
* Add an event to the buffer.
|
|
270
|
+
*/
|
|
271
|
+
add(event) {
|
|
272
|
+
if (this.buffer.length >= this.maxSize) {
|
|
273
|
+
return false; // Buffer full
|
|
274
|
+
}
|
|
275
|
+
this.buffer.push(event);
|
|
276
|
+
return true;
|
|
277
|
+
}
|
|
278
|
+
/**
|
|
279
|
+
* Get all buffered events.
|
|
280
|
+
*/
|
|
281
|
+
getAll() {
|
|
282
|
+
return [...this.buffer];
|
|
283
|
+
}
|
|
284
|
+
/**
|
|
285
|
+
* Drain the buffer (get all events and clear).
|
|
286
|
+
*/
|
|
287
|
+
drain() {
|
|
288
|
+
const events = [...this.buffer];
|
|
289
|
+
this.buffer.length = 0;
|
|
290
|
+
return events;
|
|
291
|
+
}
|
|
292
|
+
/**
|
|
293
|
+
* Get buffer size.
|
|
294
|
+
*/
|
|
295
|
+
size() {
|
|
296
|
+
return this.buffer.length;
|
|
297
|
+
}
|
|
298
|
+
/**
|
|
299
|
+
* Check if buffer is full.
|
|
300
|
+
*/
|
|
301
|
+
isFull() {
|
|
302
|
+
return this.buffer.length >= this.maxSize;
|
|
303
|
+
}
|
|
304
|
+
/**
|
|
305
|
+
* Clear the buffer.
|
|
306
|
+
*/
|
|
307
|
+
clear() {
|
|
308
|
+
this.buffer.length = 0;
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
exports.EventBuffer = EventBuffer;
|
|
312
|
+
/**
|
|
313
|
+
* Heartbeat monitor for detecting stale connections.
|
|
314
|
+
*/
|
|
315
|
+
class HeartbeatMonitor {
|
|
316
|
+
lastHeartbeat = Date.now();
|
|
317
|
+
timeoutId = null;
|
|
318
|
+
timeoutMs;
|
|
319
|
+
onTimeout;
|
|
320
|
+
constructor(options) {
|
|
321
|
+
this.timeoutMs = options.timeoutMs;
|
|
322
|
+
this.onTimeout = options.onTimeout;
|
|
323
|
+
}
|
|
324
|
+
/**
|
|
325
|
+
* Start monitoring.
|
|
326
|
+
*/
|
|
327
|
+
start() {
|
|
328
|
+
this.lastHeartbeat = Date.now();
|
|
329
|
+
this.scheduleCheck();
|
|
330
|
+
}
|
|
331
|
+
/**
|
|
332
|
+
* Stop monitoring.
|
|
333
|
+
*/
|
|
334
|
+
stop() {
|
|
335
|
+
if (this.timeoutId !== null) {
|
|
336
|
+
clearTimeout(this.timeoutId);
|
|
337
|
+
this.timeoutId = null;
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
/**
|
|
341
|
+
* Reset the heartbeat timer.
|
|
342
|
+
*/
|
|
343
|
+
reset() {
|
|
344
|
+
this.lastHeartbeat = Date.now();
|
|
345
|
+
}
|
|
346
|
+
/**
|
|
347
|
+
* Called when a heartbeat is received.
|
|
348
|
+
*/
|
|
349
|
+
onHeartbeat() {
|
|
350
|
+
this.lastHeartbeat = Date.now();
|
|
351
|
+
}
|
|
352
|
+
/**
|
|
353
|
+
* Get time since last heartbeat in milliseconds.
|
|
354
|
+
*/
|
|
355
|
+
getTimeSinceLastHeartbeat() {
|
|
356
|
+
return Date.now() - this.lastHeartbeat;
|
|
357
|
+
}
|
|
358
|
+
scheduleCheck() {
|
|
359
|
+
this.timeoutId = setTimeout(() => {
|
|
360
|
+
const elapsed = Date.now() - this.lastHeartbeat;
|
|
361
|
+
if (elapsed >= this.timeoutMs) {
|
|
362
|
+
this.onTimeout();
|
|
363
|
+
}
|
|
364
|
+
else {
|
|
365
|
+
// Schedule next check
|
|
366
|
+
this.scheduleCheck();
|
|
367
|
+
}
|
|
368
|
+
}, this.timeoutMs);
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
exports.HeartbeatMonitor = HeartbeatMonitor;
|
|
372
|
+
//# sourceMappingURL=reconnect.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"reconnect.js","sourceRoot":"","sources":["../../src/reconnect.ts"],"names":[],"mappings":";AAAA;;;;GAIG;;;AAIH;;GAEG;AACU,QAAA,eAAe,GAAG;IAC7B,oBAAoB;IACpB,YAAY,EAAE,cAAc;IAC5B,4BAA4B;IAC5B,UAAU,EAAE,YAAY;IACxB,6BAA6B;IAC7B,SAAS,EAAE,WAAW;IACtB,iDAAiD;IACjD,YAAY,EAAE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,aAAa,EAAE,CAAC;YACvB,CAAC;QACH,CAAC,EAAE,IAAI,CAAC,SAAS,CAAC,CAAC;IACrB,CAAC;CACF;AA7DD,4CA6DC","sourcesContent":["/**\n * @enclave-vm/stream - Reconnection State Machine\n *\n * Handles connection drops and automatic reconnection with exponential backoff.\n */\n\nimport type { StreamEvent, EncryptedEnvelope } from '@enclave-vm/types';\n\n/**\n * Connection state.\n */\nexport const ConnectionState = {\n /** Not connected */\n Disconnected: 'disconnected',\n /** Attempting to connect */\n Connecting: 'connecting',\n /** Successfully connected */\n Connected: 'connected',\n /** Connection lost, will attempt reconnection */\n Reconnecting: 'reconnecting',\n /** Permanently failed (max retries exceeded or fatal error) */\n Failed: 'failed',\n /** Intentionally closed */\n Closed: 'closed',\n} as const;\n\nexport type ConnectionState = (typeof ConnectionState)[keyof typeof ConnectionState];\n\n/**\n * Reconnection configuration.\n */\nexport interface ReconnectionConfig {\n /** Maximum number of reconnection attempts (default: 5) */\n maxRetries: number;\n /** Initial backoff delay in milliseconds (default: 1000) */\n initialDelayMs: number;\n /** Maximum backoff delay in milliseconds (default: 30000) */\n maxDelayMs: number;\n /** Backoff multiplier (default: 2) */\n backoffMultiplier: number;\n /** Add random jitter to backoff (default: true) */\n jitter: boolean;\n /** Jitter factor (0-1, default: 0.3) */\n jitterFactor: number;\n}\n\n/**\n * Default reconnection configuration.\n */\nexport const DEFAULT_RECONNECTION_CONFIG: ReconnectionConfig = {\n maxRetries: 5,\n initialDelayMs: 1000,\n maxDelayMs: 30000,\n backoffMultiplier: 2,\n jitter: true,\n jitterFactor: 0.3,\n};\n\n/**\n * Event emitted by the reconnection state machine.\n */\nexport type ReconnectionEvent =\n | { type: 'state_change'; state: ConnectionState; previousState: ConnectionState }\n | { type: 'retry_scheduled'; attempt: number; delayMs: number }\n | { type: 'retry_started'; attempt: number }\n | { type: 'connected' }\n | { type: 'disconnected'; reason?: string }\n | { type: 'failed'; reason: string };\n\n/**\n * Reconnection state machine.\n * Manages connection state and handles automatic reconnection.\n */\nexport class ReconnectionStateMachine {\n private state: ConnectionState = ConnectionState.Disconnected;\n private retryCount = 0;\n private retryTimeoutId: ReturnType<typeof setTimeout> | null = null;\n private readonly config: ReconnectionConfig;\n private readonly onEvent: (event: ReconnectionEvent) => void;\n\n constructor(options: { config?: Partial<ReconnectionConfig>; onEvent: (event: ReconnectionEvent) => void }) {\n this.config = { ...DEFAULT_RECONNECTION_CONFIG, ...options.config };\n this.onEvent = options.onEvent;\n }\n\n /**\n * Get current connection state.\n */\n getState(): ConnectionState {\n return this.state;\n }\n\n /**\n * Get current retry count.\n */\n getRetryCount(): number {\n return this.retryCount;\n }\n\n /**\n * Transition to a new state.\n */\n private transition(newState: ConnectionState): void {\n const previousState = this.state;\n if (previousState === newState) return;\n\n this.state = newState;\n this.onEvent({ type: 'state_change', state: newState, previousState });\n }\n\n /**\n * Calculate backoff delay with optional jitter.\n */\n private calculateBackoff(): number {\n const { initialDelayMs, maxDelayMs, backoffMultiplier, jitter, jitterFactor } = this.config;\n\n // Exponential backoff\n let delay = initialDelayMs * Math.pow(backoffMultiplier, this.retryCount);\n delay = Math.min(delay, maxDelayMs);\n\n // Add jitter\n if (jitter) {\n const jitterAmount = delay * jitterFactor;\n delay = delay - jitterAmount + Math.random() * jitterAmount * 2;\n }\n\n return Math.round(delay);\n }\n\n /**\n * Start connecting.\n */\n connect(): void {\n if (this.state === ConnectionState.Connected || this.state === ConnectionState.Connecting) {\n return;\n }\n\n this.cancelRetry();\n this.retryCount = 0;\n this.transition(ConnectionState.Connecting);\n }\n\n /**\n * Called when connection succeeds.\n */\n onConnected(): void {\n this.cancelRetry();\n this.retryCount = 0;\n this.transition(ConnectionState.Connected);\n this.onEvent({ type: 'connected' });\n }\n\n /**\n * Called when connection is lost.\n */\n onDisconnected(reason?: string): void {\n this.cancelRetry();\n\n // If already closed or failed, don't change state\n if (this.state === ConnectionState.Closed || this.state === ConnectionState.Failed) {\n return;\n }\n\n this.onEvent({ type: 'disconnected', reason });\n\n // Check if we should attempt reconnection\n if (this.retryCount < this.config.maxRetries) {\n this.scheduleRetry();\n } else {\n this.transition(ConnectionState.Failed);\n this.onEvent({ type: 'failed', reason: reason ?? 'Max retries exceeded' });\n }\n }\n\n /**\n * Called when connection fails with a fatal error.\n */\n onFatalError(reason: string): void {\n this.cancelRetry();\n this.transition(ConnectionState.Failed);\n this.onEvent({ type: 'failed', reason });\n }\n\n /**\n * Schedule a reconnection attempt.\n */\n private scheduleRetry(): void {\n this.transition(ConnectionState.Reconnecting);\n\n const delayMs = this.calculateBackoff();\n const attempt = this.retryCount + 1;\n\n this.onEvent({ type: 'retry_scheduled', attempt, delayMs });\n\n this.retryTimeoutId = setTimeout(() => {\n this.retryTimeoutId = null;\n this.retryCount++;\n this.onEvent({ type: 'retry_started', attempt });\n this.transition(ConnectionState.Connecting);\n }, delayMs);\n }\n\n /**\n * Cancel any pending retry.\n */\n private cancelRetry(): void {\n if (this.retryTimeoutId !== null) {\n clearTimeout(this.retryTimeoutId);\n this.retryTimeoutId = null;\n }\n }\n\n /**\n * Intentionally close the connection.\n */\n close(): void {\n this.cancelRetry();\n this.transition(ConnectionState.Closed);\n }\n\n /**\n * Reset to initial state.\n */\n reset(): void {\n this.cancelRetry();\n this.retryCount = 0;\n this.transition(ConnectionState.Disconnected);\n }\n\n /**\n * Check if reconnection is possible.\n */\n canReconnect(): boolean {\n return (\n this.state !== ConnectionState.Failed &&\n this.state !== ConnectionState.Closed &&\n this.retryCount < this.config.maxRetries\n );\n }\n}\n\n/**\n * Sequence tracker for detecting gaps and enabling replay.\n */\nexport class SequenceTracker {\n private lastSeq = 0;\n private readonly gaps: Array<{ start: number; end: number }> = [];\n private readonly maxGaps: number;\n\n constructor(maxGaps = 100) {\n this.maxGaps = maxGaps;\n }\n\n /**\n * Process a received sequence number.\n * Returns any gaps detected.\n */\n receive(seq: number): { gap: boolean; missingStart?: number; missingEnd?: number } {\n // First event\n if (this.lastSeq === 0) {\n this.lastSeq = seq;\n return { gap: false };\n }\n\n // Expected sequence\n if (seq === this.lastSeq + 1) {\n this.lastSeq = seq;\n return { gap: false };\n }\n\n // Duplicate or old event\n if (seq <= this.lastSeq) {\n return { gap: false };\n }\n\n // Gap detected\n const missingStart = this.lastSeq + 1;\n const missingEnd = seq - 1;\n\n // Track gap (for replay)\n if (this.gaps.length < this.maxGaps) {\n this.gaps.push({ start: missingStart, end: missingEnd });\n }\n\n this.lastSeq = seq;\n return { gap: true, missingStart, missingEnd };\n }\n\n /**\n * Get the last received sequence number.\n */\n getLastSeq(): number {\n return this.lastSeq;\n }\n\n /**\n * Get all detected gaps.\n */\n getGaps(): Array<{ start: number; end: number }> {\n return [...this.gaps];\n }\n\n /**\n * Clear a gap after it's been filled.\n */\n clearGap(start: number, end: number): void {\n const index = this.gaps.findIndex((g) => g.start === start && g.end === end);\n if (index !== -1) {\n this.gaps.splice(index, 1);\n }\n }\n\n /**\n * Check if there are pending gaps.\n */\n hasGaps(): boolean {\n return this.gaps.length > 0;\n }\n\n /**\n * Reset the tracker.\n */\n reset(): void {\n this.lastSeq = 0;\n this.gaps.length = 0;\n }\n}\n\n/**\n * Event buffer for storing events during reconnection.\n */\nexport class EventBuffer {\n private readonly buffer: (StreamEvent | EncryptedEnvelope)[] = [];\n private readonly maxSize: number;\n\n constructor(maxSize = 1000) {\n this.maxSize = maxSize;\n }\n\n /**\n * Add an event to the buffer.\n */\n add(event: StreamEvent | EncryptedEnvelope): boolean {\n if (this.buffer.length >= this.maxSize) {\n return false; // Buffer full\n }\n this.buffer.push(event);\n return true;\n }\n\n /**\n * Get all buffered events.\n */\n getAll(): (StreamEvent | EncryptedEnvelope)[] {\n return [...this.buffer];\n }\n\n /**\n * Drain the buffer (get all events and clear).\n */\n drain(): (StreamEvent | EncryptedEnvelope)[] {\n const events = [...this.buffer];\n this.buffer.length = 0;\n return events;\n }\n\n /**\n * Get buffer size.\n */\n size(): number {\n return this.buffer.length;\n }\n\n /**\n * Check if buffer is full.\n */\n isFull(): boolean {\n return this.buffer.length >= this.maxSize;\n }\n\n /**\n * Clear the buffer.\n */\n clear(): void {\n this.buffer.length = 0;\n }\n}\n\n/**\n * Heartbeat monitor for detecting stale connections.\n */\nexport class HeartbeatMonitor {\n private lastHeartbeat = Date.now();\n private timeoutId: ReturnType<typeof setTimeout> | null = null;\n private readonly timeoutMs: number;\n private readonly onTimeout: () => void;\n\n constructor(options: { timeoutMs: number; onTimeout: () => void }) {\n this.timeoutMs = options.timeoutMs;\n this.onTimeout = options.onTimeout;\n }\n\n /**\n * Start monitoring.\n */\n start(): void {\n this.lastHeartbeat = Date.now();\n this.scheduleCheck();\n }\n\n /**\n * Stop monitoring.\n */\n stop(): void {\n if (this.timeoutId !== null) {\n clearTimeout(this.timeoutId);\n this.timeoutId = null;\n }\n }\n\n /**\n * Reset the heartbeat timer.\n */\n reset(): void {\n this.lastHeartbeat = Date.now();\n }\n\n /**\n * Called when a heartbeat is received.\n */\n onHeartbeat(): void {\n this.lastHeartbeat = Date.now();\n }\n\n /**\n * Get time since last heartbeat in milliseconds.\n */\n getTimeSinceLastHeartbeat(): number {\n return Date.now() - this.lastHeartbeat;\n }\n\n private scheduleCheck(): void {\n this.timeoutId = setTimeout(() => {\n const elapsed = Date.now() - this.lastHeartbeat;\n if (elapsed >= this.timeoutMs) {\n this.onTimeout();\n } else {\n // Schedule next check\n this.scheduleCheck();\n }\n }, this.timeoutMs);\n }\n}\n"]}
|