peerpigeon 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 +21 -0
- package/README.md +1187 -0
- package/examples/browser/app-dht-disabled.js +42 -0
- package/examples/browser/app.js +51 -0
- package/examples/browser/assets/images/favicon.png +0 -0
- package/examples/browser/assets/images/pigeon.png +0 -0
- package/examples/browser/index-dht-disabled.html +123 -0
- package/examples/browser/index.html +340 -0
- package/examples/browser/styles.css +1288 -0
- package/examples/browser/ui-clean.js +0 -0
- package/examples/browser/ui.js +1930 -0
- package/index.js +8 -0
- package/package.json +70 -0
- package/server/index.js +515 -0
- package/src/CleanupManager.js +181 -0
- package/src/ConnectionManager.js +841 -0
- package/src/EventEmitter.js +27 -0
- package/src/EvictionManager.js +257 -0
- package/src/GossipManager.js +416 -0
- package/src/MediaManager.js +225 -0
- package/src/MeshOptimizer.js +181 -0
- package/src/PeerConnection.js +831 -0
- package/src/PeerDiscovery.js +297 -0
- package/src/PeerPigeonMesh.js +703 -0
- package/src/SignalingClient.js +536 -0
- package/src/SignalingHandler.js +325 -0
- package/src/StorageManager.js +88 -0
- package/src/TimerUtils.js +46 -0
- package/src/WebDHT.js +1099 -0
- package/websocket-server/README.md +257 -0
- package/websocket-server/memory-leak-test.js +193 -0
- package/websocket-server/node_modules/.package-lock.json +29 -0
- package/websocket-server/node_modules/ws/LICENSE +20 -0
- package/websocket-server/node_modules/ws/README.md +548 -0
- package/websocket-server/node_modules/ws/browser.js +8 -0
- package/websocket-server/node_modules/ws/index.js +13 -0
- package/websocket-server/node_modules/ws/lib/buffer-util.js +131 -0
- package/websocket-server/node_modules/ws/lib/constants.js +18 -0
- package/websocket-server/node_modules/ws/lib/event-target.js +292 -0
- package/websocket-server/node_modules/ws/lib/extension.js +203 -0
- package/websocket-server/node_modules/ws/lib/limiter.js +55 -0
- package/websocket-server/node_modules/ws/lib/permessage-deflate.js +528 -0
- package/websocket-server/node_modules/ws/lib/receiver.js +706 -0
- package/websocket-server/node_modules/ws/lib/sender.js +602 -0
- package/websocket-server/node_modules/ws/lib/stream.js +161 -0
- package/websocket-server/node_modules/ws/lib/subprotocol.js +62 -0
- package/websocket-server/node_modules/ws/lib/validation.js +152 -0
- package/websocket-server/node_modules/ws/lib/websocket-server.js +550 -0
- package/websocket-server/node_modules/ws/lib/websocket.js +1388 -0
- package/websocket-server/node_modules/ws/package.json +69 -0
- package/websocket-server/node_modules/ws/wrapper.mjs +8 -0
- package/websocket-server/package-lock.json +39 -0
- package/websocket-server/server.js +298 -0
- package/websocket-server/test.js +133 -0
|
@@ -0,0 +1,536 @@
|
|
|
1
|
+
import { EventEmitter } from './EventEmitter.js';
|
|
2
|
+
|
|
3
|
+
export class SignalingClient extends EventEmitter {
|
|
4
|
+
constructor(peerId, maxPeers = 10, mesh = null) {
|
|
5
|
+
super();
|
|
6
|
+
this.peerId = peerId;
|
|
7
|
+
this.maxPeers = maxPeers;
|
|
8
|
+
this.mesh = mesh; // Reference to the mesh for peer coordination
|
|
9
|
+
this.signalingUrl = null;
|
|
10
|
+
this.connected = false;
|
|
11
|
+
this.websocket = null;
|
|
12
|
+
this.reconnectDelay = 1000;
|
|
13
|
+
this.maxReconnectDelay = 30000;
|
|
14
|
+
this.reconnectAttempts = 0;
|
|
15
|
+
this.maxReconnectAttempts = 10; // Increased for better persistence
|
|
16
|
+
this.connectionPromise = null;
|
|
17
|
+
this.reconnectTimeout = null;
|
|
18
|
+
this.isReconnecting = false;
|
|
19
|
+
|
|
20
|
+
// Add keep-alive ping to prevent AWS WebSocket timeout (10 min idle limit)
|
|
21
|
+
this.keepAliveInterval = null;
|
|
22
|
+
this.keepAliveIntervalMs = 9 * 60 * 1000; // Ping every 9 minutes for large safety margin
|
|
23
|
+
|
|
24
|
+
// Health monitoring
|
|
25
|
+
this.lastPingTime = null;
|
|
26
|
+
this.lastPongTime = null;
|
|
27
|
+
this.pingTimeout = null;
|
|
28
|
+
this.healthCheckInterval = null;
|
|
29
|
+
this.connectionQualityTimeout = 10000; // 10 seconds to consider connection unhealthy
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
setConnectionType(type) {
|
|
33
|
+
// WebSocket-only implementation, ignore connection type setting
|
|
34
|
+
console.log(`WebSocket-only implementation - connection type setting ignored: ${type}`);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
async sendSignalingMessage(message) {
|
|
38
|
+
// Check connection health before sending
|
|
39
|
+
if (!this.isConnected()) {
|
|
40
|
+
console.log('WebSocket not connected, attempting to reconnect...');
|
|
41
|
+
if (!this.isReconnecting) {
|
|
42
|
+
this.attemptReconnect();
|
|
43
|
+
}
|
|
44
|
+
throw new Error('WebSocket not connected');
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const payload = {
|
|
48
|
+
type: message.type,
|
|
49
|
+
data: message.data,
|
|
50
|
+
maxPeers: this.maxPeers,
|
|
51
|
+
...(message.targetPeerId && { targetPeerId: message.targetPeerId })
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
try {
|
|
55
|
+
this.websocket.send(JSON.stringify(payload));
|
|
56
|
+
console.log('Sent WebSocket message:', payload.type);
|
|
57
|
+
return { success: true };
|
|
58
|
+
} catch (error) {
|
|
59
|
+
console.error('Failed to send WebSocket message:', error);
|
|
60
|
+
// Trigger reconnection on send failure
|
|
61
|
+
if (!this.isReconnecting) {
|
|
62
|
+
this.attemptReconnect();
|
|
63
|
+
}
|
|
64
|
+
throw error;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
isConnected() {
|
|
69
|
+
return this.websocket &&
|
|
70
|
+
this.websocket.readyState === WebSocket.OPEN &&
|
|
71
|
+
this.connected;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
async connect(websocketUrl) {
|
|
75
|
+
// Prevent multiple simultaneous connection attempts
|
|
76
|
+
if (this.connectionPromise) {
|
|
77
|
+
console.log('Connection already in progress, waiting for completion...');
|
|
78
|
+
return this.connectionPromise;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// Convert HTTP/HTTPS URL to WebSocket URL if needed
|
|
82
|
+
if (websocketUrl.startsWith('http://')) {
|
|
83
|
+
websocketUrl = websocketUrl.replace('http://', 'ws://');
|
|
84
|
+
} else if (websocketUrl.startsWith('https://')) {
|
|
85
|
+
websocketUrl = websocketUrl.replace('https://', 'wss://');
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// Ensure WebSocket URL format
|
|
89
|
+
if (!websocketUrl.startsWith('ws://') && !websocketUrl.startsWith('wss://')) {
|
|
90
|
+
throw new Error('Invalid WebSocket URL format');
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
this.signalingUrl = websocketUrl;
|
|
94
|
+
|
|
95
|
+
// Add peerId as query parameter
|
|
96
|
+
const url = new URL(websocketUrl);
|
|
97
|
+
url.searchParams.set('peerId', this.peerId);
|
|
98
|
+
|
|
99
|
+
this.emit('statusChanged', { type: 'connecting', message: 'Connecting to WebSocket...' });
|
|
100
|
+
|
|
101
|
+
this.connectionPromise = new Promise((resolve, reject) => {
|
|
102
|
+
try {
|
|
103
|
+
this.websocket = new WebSocket(url.toString());
|
|
104
|
+
|
|
105
|
+
const connectTimeout = setTimeout(() => {
|
|
106
|
+
if (this.websocket.readyState === WebSocket.CONNECTING) {
|
|
107
|
+
this.websocket.close();
|
|
108
|
+
reject(new Error('WebSocket connection timeout'));
|
|
109
|
+
}
|
|
110
|
+
}, 10000);
|
|
111
|
+
|
|
112
|
+
this.websocket.onopen = () => {
|
|
113
|
+
clearTimeout(connectTimeout);
|
|
114
|
+
this.connected = true;
|
|
115
|
+
this.reconnectAttempts = 0;
|
|
116
|
+
this.reconnectDelay = 1000;
|
|
117
|
+
this.isReconnecting = false;
|
|
118
|
+
this.connectionPromise = null;
|
|
119
|
+
|
|
120
|
+
console.log('WebSocket connected');
|
|
121
|
+
this.emit('statusChanged', { type: 'info', message: 'WebSocket connected' });
|
|
122
|
+
|
|
123
|
+
// Send announce message
|
|
124
|
+
this.sendSignalingMessage({
|
|
125
|
+
type: 'announce',
|
|
126
|
+
data: { peerId: this.peerId }
|
|
127
|
+
}).then(() => {
|
|
128
|
+
this.startKeepAlive();
|
|
129
|
+
// Removed health monitoring - keep-alive pings are sufficient
|
|
130
|
+
this.emit('connected');
|
|
131
|
+
resolve();
|
|
132
|
+
}).catch(error => {
|
|
133
|
+
console.error('Failed to send announce message:', error);
|
|
134
|
+
this.startKeepAlive();
|
|
135
|
+
// Removed health monitoring - keep-alive pings are sufficient
|
|
136
|
+
this.emit('connected'); // Still emit connected even if announce fails
|
|
137
|
+
resolve();
|
|
138
|
+
});
|
|
139
|
+
};
|
|
140
|
+
|
|
141
|
+
this.websocket.onmessage = (event) => {
|
|
142
|
+
try {
|
|
143
|
+
const message = JSON.parse(event.data);
|
|
144
|
+
console.log('Received WebSocket message:', message.type);
|
|
145
|
+
|
|
146
|
+
if (message.type === 'connected') {
|
|
147
|
+
// Connection confirmation from server
|
|
148
|
+
console.log('WebSocket connection confirmed by server');
|
|
149
|
+
} else if (message.type === 'pong') {
|
|
150
|
+
// Handle pong response for health monitoring
|
|
151
|
+
this.handlePong();
|
|
152
|
+
} else {
|
|
153
|
+
// Forward signaling message to mesh
|
|
154
|
+
this.emit('signalingMessage', message);
|
|
155
|
+
}
|
|
156
|
+
} catch (error) {
|
|
157
|
+
console.error('Failed to parse WebSocket message:', error);
|
|
158
|
+
}
|
|
159
|
+
};
|
|
160
|
+
|
|
161
|
+
this.websocket.onclose = (event) => {
|
|
162
|
+
clearTimeout(connectTimeout);
|
|
163
|
+
this.connected = false;
|
|
164
|
+
this.connectionPromise = null;
|
|
165
|
+
this.stopKeepAlive();
|
|
166
|
+
// Removed health monitoring stop - not using health monitoring
|
|
167
|
+
|
|
168
|
+
console.log('WebSocket closed:', event.code, event.reason);
|
|
169
|
+
|
|
170
|
+
if (event.code === 1000) {
|
|
171
|
+
// Normal closure
|
|
172
|
+
this.emit('disconnected');
|
|
173
|
+
} else {
|
|
174
|
+
// Abnormal closure - attempt reconnection
|
|
175
|
+
this.emit('statusChanged', { type: 'warning', message: 'WebSocket connection lost - reconnecting...' });
|
|
176
|
+
if (!this.isReconnecting) {
|
|
177
|
+
this.attemptReconnect();
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
};
|
|
181
|
+
|
|
182
|
+
this.websocket.onerror = (error) => {
|
|
183
|
+
clearTimeout(connectTimeout);
|
|
184
|
+
console.error('WebSocket error:', error);
|
|
185
|
+
|
|
186
|
+
if (this.websocket.readyState === WebSocket.CONNECTING) {
|
|
187
|
+
this.connectionPromise = null;
|
|
188
|
+
reject(new Error('WebSocket connection failed'));
|
|
189
|
+
} else {
|
|
190
|
+
this.emit('statusChanged', { type: 'error', message: 'WebSocket error occurred' });
|
|
191
|
+
// Trigger reconnection on error if not already reconnecting
|
|
192
|
+
if (!this.isReconnecting) {
|
|
193
|
+
this.attemptReconnect();
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
};
|
|
197
|
+
|
|
198
|
+
} catch (error) {
|
|
199
|
+
this.connectionPromise = null;
|
|
200
|
+
reject(error);
|
|
201
|
+
}
|
|
202
|
+
});
|
|
203
|
+
|
|
204
|
+
return this.connectionPromise;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
attemptReconnect() {
|
|
208
|
+
if (this.isReconnecting) {
|
|
209
|
+
console.log('Reconnection already in progress');
|
|
210
|
+
return;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
// Clear any existing reconnect timeout
|
|
214
|
+
if (this.reconnectTimeout) {
|
|
215
|
+
clearTimeout(this.reconnectTimeout);
|
|
216
|
+
this.reconnectTimeout = null;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
if (this.reconnectAttempts >= this.maxReconnectAttempts) {
|
|
220
|
+
console.log('Max reconnection attempts reached, using exponential backoff');
|
|
221
|
+
// Don't give up completely, but use longer delays
|
|
222
|
+
const extendedDelay = Math.min(this.maxReconnectDelay * 2, 300000); // Max 5 minutes
|
|
223
|
+
this.reconnectTimeout = setTimeout(() => {
|
|
224
|
+
this.reconnectAttempts = Math.floor(this.maxReconnectAttempts / 2); // Reset to half max
|
|
225
|
+
this.attemptReconnect();
|
|
226
|
+
}, extendedDelay);
|
|
227
|
+
return;
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
this.isReconnecting = true;
|
|
231
|
+
this.reconnectAttempts++;
|
|
232
|
+
const delay = Math.min(this.reconnectDelay * Math.pow(2, this.reconnectAttempts - 1), this.maxReconnectDelay);
|
|
233
|
+
|
|
234
|
+
console.log(`Reconnecting in ${delay}ms (attempt ${this.reconnectAttempts}/${this.maxReconnectAttempts})`);
|
|
235
|
+
|
|
236
|
+
this.reconnectTimeout = setTimeout(async () => {
|
|
237
|
+
if (!this.connected && this.signalingUrl) {
|
|
238
|
+
try {
|
|
239
|
+
await this.connect(this.signalingUrl);
|
|
240
|
+
this.emit('statusChanged', { type: 'info', message: 'WebSocket reconnected successfully' });
|
|
241
|
+
} catch (error) {
|
|
242
|
+
console.error('Reconnection failed:', error);
|
|
243
|
+
this.isReconnecting = false;
|
|
244
|
+
this.attemptReconnect();
|
|
245
|
+
}
|
|
246
|
+
} else {
|
|
247
|
+
this.isReconnecting = false;
|
|
248
|
+
}
|
|
249
|
+
}, delay);
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
disconnect() {
|
|
253
|
+
// Clear reconnection state
|
|
254
|
+
this.isReconnecting = false;
|
|
255
|
+
if (this.reconnectTimeout) {
|
|
256
|
+
clearTimeout(this.reconnectTimeout);
|
|
257
|
+
this.reconnectTimeout = null;
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
// The sendGoodbyeMessage is often called from an unload handler,
|
|
261
|
+
// so we don't want to make it part of the standard disconnect flow here.
|
|
262
|
+
// The CleanupManager handles sending goodbye on unload.
|
|
263
|
+
this.stopKeepAlive();
|
|
264
|
+
this.stopHealthMonitoring(); // FIX: Stop health monitoring to prevent memory leaks
|
|
265
|
+
|
|
266
|
+
this.connected = false;
|
|
267
|
+
this.connectionPromise = null;
|
|
268
|
+
|
|
269
|
+
if (this.websocket) {
|
|
270
|
+
// Clear event handlers to prevent memory leaks
|
|
271
|
+
this.websocket.onopen = null;
|
|
272
|
+
this.websocket.onmessage = null;
|
|
273
|
+
this.websocket.onclose = null;
|
|
274
|
+
this.websocket.onerror = null;
|
|
275
|
+
|
|
276
|
+
this.websocket.close(1000, 'Client disconnect');
|
|
277
|
+
this.websocket = null;
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
this.emit('disconnected');
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
sendGoodbyeMessage() {
|
|
284
|
+
if (!this.connected) return;
|
|
285
|
+
|
|
286
|
+
try {
|
|
287
|
+
console.log('Sending goodbye message');
|
|
288
|
+
|
|
289
|
+
if (this.websocket && this.websocket.readyState === WebSocket.OPEN) {
|
|
290
|
+
this.websocket.send(JSON.stringify({
|
|
291
|
+
type: 'goodbye',
|
|
292
|
+
data: {
|
|
293
|
+
peerId: this.peerId,
|
|
294
|
+
timestamp: Date.now(),
|
|
295
|
+
reason: 'peer_disconnect'
|
|
296
|
+
}
|
|
297
|
+
}));
|
|
298
|
+
}
|
|
299
|
+
} catch (error) {
|
|
300
|
+
console.error('Failed to send goodbye message:', error);
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
async sendCleanupMessage(targetPeerId) {
|
|
305
|
+
if (!this.connected) return;
|
|
306
|
+
|
|
307
|
+
try {
|
|
308
|
+
await this.sendSignalingMessage({
|
|
309
|
+
type: 'cleanup',
|
|
310
|
+
data: {
|
|
311
|
+
peerId: this.peerId,
|
|
312
|
+
targetPeerId: targetPeerId,
|
|
313
|
+
timestamp: Date.now(),
|
|
314
|
+
reason: 'peer_disconnect'
|
|
315
|
+
},
|
|
316
|
+
targetPeerId: targetPeerId
|
|
317
|
+
});
|
|
318
|
+
} catch (error) {
|
|
319
|
+
console.log(`Cleanup message failed for ${targetPeerId}:`, error.message);
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
startKeepAlive() {
|
|
324
|
+
if (this.keepAliveInterval) return;
|
|
325
|
+
|
|
326
|
+
console.log('Starting keep-alive pings every', this.keepAliveIntervalMs / 1000, 'seconds');
|
|
327
|
+
this.keepAliveInterval = window.setInterval.call(window, () => {
|
|
328
|
+
if (this.connected) {
|
|
329
|
+
// Check if this peer should send the ping
|
|
330
|
+
if (this.shouldSendKeepAlivePing()) {
|
|
331
|
+
console.log('Sending keep-alive ping (designated peer)');
|
|
332
|
+
this.sendSignalingMessage({
|
|
333
|
+
type: 'ping',
|
|
334
|
+
data: { peerId: this.peerId }
|
|
335
|
+
}).catch(error => {
|
|
336
|
+
console.error('Keep-alive ping failed:', error);
|
|
337
|
+
});
|
|
338
|
+
} else {
|
|
339
|
+
console.log('Skipping keep-alive ping (not designated peer)');
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
}, this.keepAliveIntervalMs);
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
/**
|
|
346
|
+
* Determine if this peer should send the keep-alive ping.
|
|
347
|
+
* Only one peer should send it when there are multiple peers connected.
|
|
348
|
+
* The peer with the lexicographically smallest ID becomes the designated sender.
|
|
349
|
+
*/
|
|
350
|
+
shouldSendKeepAlivePing() {
|
|
351
|
+
// If no mesh reference available, always send (fallback)
|
|
352
|
+
if (!this.mesh) {
|
|
353
|
+
return true;
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
// Get all connected peers
|
|
357
|
+
const connectedPeers = this.mesh.connectionManager.getConnectedPeers();
|
|
358
|
+
|
|
359
|
+
// If no peers connected, always send
|
|
360
|
+
if (connectedPeers.length === 0) {
|
|
361
|
+
return true;
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
// Get all peer IDs including this one
|
|
365
|
+
const allPeerIds = [this.peerId, ...connectedPeers.map(peer => peer.peerId)];
|
|
366
|
+
|
|
367
|
+
// Sort lexicographically and check if this peer is the smallest
|
|
368
|
+
allPeerIds.sort();
|
|
369
|
+
const designatedPeer = allPeerIds[0];
|
|
370
|
+
|
|
371
|
+
const isDesignated = designatedPeer === this.peerId;
|
|
372
|
+
console.log(`Keep-alive ping decision: ${isDesignated ? 'SEND' : 'SKIP'} (this: ${this.peerId.substring(0, 8)}, designated: ${designatedPeer.substring(0, 8)}, total peers: ${allPeerIds.length})`);
|
|
373
|
+
|
|
374
|
+
return isDesignated;
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
stopKeepAlive() {
|
|
378
|
+
if (this.keepAliveInterval) {
|
|
379
|
+
clearInterval(this.keepAliveInterval);
|
|
380
|
+
this.keepAliveInterval = null;
|
|
381
|
+
console.log('Stopped keep-alive pings');
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
startHealthMonitoring() {
|
|
386
|
+
if (this.healthCheckInterval) return;
|
|
387
|
+
|
|
388
|
+
console.log('Starting connection health monitoring');
|
|
389
|
+
this.healthCheckInterval = window.setInterval.call(window, () => {
|
|
390
|
+
// Check WebSocket state first
|
|
391
|
+
if (!this.websocket || this.websocket.readyState !== WebSocket.OPEN) {
|
|
392
|
+
console.warn('WebSocket is not in OPEN state:', this.websocket?.readyState);
|
|
393
|
+
this.handleUnhealthyConnection();
|
|
394
|
+
return;
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
if (this.connected) {
|
|
398
|
+
const now = Date.now();
|
|
399
|
+
|
|
400
|
+
// Only check for pong timeout if we have a pending ping
|
|
401
|
+
if (this.pingTimeout) {
|
|
402
|
+
// There's already a ping waiting for pong, don't send another
|
|
403
|
+
console.log('Ping already pending, waiting for pong...');
|
|
404
|
+
return;
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
// Check if we have an old pong that indicates connection issues
|
|
408
|
+
if (this.lastPingTime && this.lastPongTime &&
|
|
409
|
+
(this.lastPingTime > this.lastPongTime) &&
|
|
410
|
+
(now - this.lastPingTime) > this.connectionQualityTimeout) {
|
|
411
|
+
console.warn('Connection health check failed - ping timeout');
|
|
412
|
+
this.handleUnhealthyConnection();
|
|
413
|
+
return;
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
// Send health check ping
|
|
417
|
+
this.sendHealthPing();
|
|
418
|
+
} else {
|
|
419
|
+
console.warn('Connection marked as disconnected but health monitoring still running');
|
|
420
|
+
this.handleUnhealthyConnection();
|
|
421
|
+
}
|
|
422
|
+
}, 15000); // Check every 15 seconds for more responsive monitoring
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
stopHealthMonitoring() {
|
|
426
|
+
if (this.healthCheckInterval) {
|
|
427
|
+
clearInterval(this.healthCheckInterval);
|
|
428
|
+
this.healthCheckInterval = null;
|
|
429
|
+
console.log('Stopped connection health monitoring');
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
if (this.pingTimeout) {
|
|
433
|
+
clearTimeout(this.pingTimeout);
|
|
434
|
+
this.pingTimeout = null;
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
sendHealthPing() {
|
|
439
|
+
if (!this.isConnected()) return;
|
|
440
|
+
|
|
441
|
+
try {
|
|
442
|
+
this.lastPingTime = Date.now();
|
|
443
|
+
|
|
444
|
+
// Set timeout for pong response
|
|
445
|
+
if (this.pingTimeout) {
|
|
446
|
+
clearTimeout(this.pingTimeout);
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
this.pingTimeout = setTimeout(() => {
|
|
450
|
+
console.warn('Health ping timeout - connection may be unhealthy');
|
|
451
|
+
this.handleUnhealthyConnection();
|
|
452
|
+
}, this.connectionQualityTimeout);
|
|
453
|
+
|
|
454
|
+
// Send ping as a regular message (Lambda will handle it)
|
|
455
|
+
this.websocket.send(JSON.stringify({
|
|
456
|
+
type: 'ping',
|
|
457
|
+
data: { peerId: this.peerId, timestamp: this.lastPingTime }
|
|
458
|
+
}));
|
|
459
|
+
|
|
460
|
+
console.log('Sent health ping');
|
|
461
|
+
} catch (error) {
|
|
462
|
+
console.error('Failed to send health ping:', error);
|
|
463
|
+
this.handleUnhealthyConnection();
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
handlePong() {
|
|
468
|
+
this.lastPongTime = Date.now();
|
|
469
|
+
|
|
470
|
+
if (this.pingTimeout) {
|
|
471
|
+
clearTimeout(this.pingTimeout);
|
|
472
|
+
this.pingTimeout = null;
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
console.log('Received pong - connection healthy');
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
handleUnhealthyConnection() {
|
|
479
|
+
console.warn('Detected unhealthy WebSocket connection, forcing reconnection');
|
|
480
|
+
this.emit('statusChanged', { type: 'warning', message: 'Connection health degraded - reconnecting...' });
|
|
481
|
+
|
|
482
|
+
// Force close and reconnect
|
|
483
|
+
this.connected = false;
|
|
484
|
+
if (this.websocket && this.websocket.readyState === WebSocket.OPEN) {
|
|
485
|
+
this.websocket.close(3000, 'Health check failed'); // Use valid close code 3000-4999
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
if (!this.isReconnecting) {
|
|
489
|
+
this.attemptReconnect();
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
forceHealthCheck() {
|
|
494
|
+
if (!this.isConnected()) {
|
|
495
|
+
console.log('Connection not healthy, triggering reconnection');
|
|
496
|
+
if (!this.isReconnecting) {
|
|
497
|
+
this.attemptReconnect();
|
|
498
|
+
}
|
|
499
|
+
return false;
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
this.sendHealthPing();
|
|
503
|
+
return true;
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
/**
|
|
507
|
+
* Force an immediate keep-alive ping check when peer topology changes.
|
|
508
|
+
* This ensures quick takeover when the designated ping sender disconnects.
|
|
509
|
+
*/
|
|
510
|
+
triggerKeepAlivePingCheck() {
|
|
511
|
+
if (!this.connected) return;
|
|
512
|
+
|
|
513
|
+
if (this.shouldSendKeepAlivePing()) {
|
|
514
|
+
console.log('Topology changed - sending immediate keep-alive ping as new designated peer');
|
|
515
|
+
this.sendSignalingMessage({
|
|
516
|
+
type: 'ping',
|
|
517
|
+
data: { peerId: this.peerId }
|
|
518
|
+
}).catch(error => {
|
|
519
|
+
console.error('Immediate keep-alive ping failed:', error);
|
|
520
|
+
});
|
|
521
|
+
} else {
|
|
522
|
+
console.log('Topology changed - not designated for keep-alive pings');
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
getConnectionStats() {
|
|
527
|
+
return {
|
|
528
|
+
connected: this.connected,
|
|
529
|
+
isReconnecting: this.isReconnecting,
|
|
530
|
+
reconnectAttempts: this.reconnectAttempts,
|
|
531
|
+
lastPingTime: this.lastPingTime,
|
|
532
|
+
lastPongTime: this.lastPongTime,
|
|
533
|
+
websocketState: this.websocket ? this.websocket.readyState : 'not created'
|
|
534
|
+
};
|
|
535
|
+
}
|
|
536
|
+
}
|