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.
Files changed (54) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1187 -0
  3. package/examples/browser/app-dht-disabled.js +42 -0
  4. package/examples/browser/app.js +51 -0
  5. package/examples/browser/assets/images/favicon.png +0 -0
  6. package/examples/browser/assets/images/pigeon.png +0 -0
  7. package/examples/browser/index-dht-disabled.html +123 -0
  8. package/examples/browser/index.html +340 -0
  9. package/examples/browser/styles.css +1288 -0
  10. package/examples/browser/ui-clean.js +0 -0
  11. package/examples/browser/ui.js +1930 -0
  12. package/index.js +8 -0
  13. package/package.json +70 -0
  14. package/server/index.js +515 -0
  15. package/src/CleanupManager.js +181 -0
  16. package/src/ConnectionManager.js +841 -0
  17. package/src/EventEmitter.js +27 -0
  18. package/src/EvictionManager.js +257 -0
  19. package/src/GossipManager.js +416 -0
  20. package/src/MediaManager.js +225 -0
  21. package/src/MeshOptimizer.js +181 -0
  22. package/src/PeerConnection.js +831 -0
  23. package/src/PeerDiscovery.js +297 -0
  24. package/src/PeerPigeonMesh.js +703 -0
  25. package/src/SignalingClient.js +536 -0
  26. package/src/SignalingHandler.js +325 -0
  27. package/src/StorageManager.js +88 -0
  28. package/src/TimerUtils.js +46 -0
  29. package/src/WebDHT.js +1099 -0
  30. package/websocket-server/README.md +257 -0
  31. package/websocket-server/memory-leak-test.js +193 -0
  32. package/websocket-server/node_modules/.package-lock.json +29 -0
  33. package/websocket-server/node_modules/ws/LICENSE +20 -0
  34. package/websocket-server/node_modules/ws/README.md +548 -0
  35. package/websocket-server/node_modules/ws/browser.js +8 -0
  36. package/websocket-server/node_modules/ws/index.js +13 -0
  37. package/websocket-server/node_modules/ws/lib/buffer-util.js +131 -0
  38. package/websocket-server/node_modules/ws/lib/constants.js +18 -0
  39. package/websocket-server/node_modules/ws/lib/event-target.js +292 -0
  40. package/websocket-server/node_modules/ws/lib/extension.js +203 -0
  41. package/websocket-server/node_modules/ws/lib/limiter.js +55 -0
  42. package/websocket-server/node_modules/ws/lib/permessage-deflate.js +528 -0
  43. package/websocket-server/node_modules/ws/lib/receiver.js +706 -0
  44. package/websocket-server/node_modules/ws/lib/sender.js +602 -0
  45. package/websocket-server/node_modules/ws/lib/stream.js +161 -0
  46. package/websocket-server/node_modules/ws/lib/subprotocol.js +62 -0
  47. package/websocket-server/node_modules/ws/lib/validation.js +152 -0
  48. package/websocket-server/node_modules/ws/lib/websocket-server.js +550 -0
  49. package/websocket-server/node_modules/ws/lib/websocket.js +1388 -0
  50. package/websocket-server/node_modules/ws/package.json +69 -0
  51. package/websocket-server/node_modules/ws/wrapper.mjs +8 -0
  52. package/websocket-server/package-lock.json +39 -0
  53. package/websocket-server/server.js +298 -0
  54. package/websocket-server/test.js +133 -0
@@ -0,0 +1,841 @@
1
+ import { EventEmitter } from './EventEmitter.js';
2
+ import { PeerConnection } from './PeerConnection.js';
3
+
4
+ /**
5
+ * Manages individual peer connections, timeouts, and connection attempts
6
+ */
7
+ export class ConnectionManager extends EventEmitter {
8
+ constructor(mesh) {
9
+ super();
10
+ this.mesh = mesh;
11
+ this.peers = new Map();
12
+ this.connectionAttempts = new Map();
13
+ this.connectionTimeouts = new Map();
14
+ this.pendingIceCandidates = new Map();
15
+ this.disconnectionInProgress = new Set();
16
+ this.cleanupInProgress = new Set();
17
+ this.lastConnectionAttempt = new Map(); // Track last attempt time per peer
18
+
19
+ // Configuration
20
+ this.maxConnectionAttempts = 3;
21
+ this.connectionTimeout = 30000; // Reduced to 30 seconds for faster retry
22
+ this.retryDelay = 1500; // 1.5 second cooldown between attempts to same peer
23
+
24
+ // Start periodic cleanup of stale peers
25
+ this.startPeriodicCleanup();
26
+ }
27
+
28
+ async connectToPeer(targetPeerId) {
29
+ console.log(`connectToPeer called for ${targetPeerId.substring(0, 8)}...`);
30
+
31
+ // Enhanced duplicate connection prevention
32
+ if (this.peers.has(targetPeerId)) {
33
+ console.log(`Already connected to ${targetPeerId.substring(0, 8)}...`);
34
+ return;
35
+ }
36
+
37
+ // Check if we're already in the process of connecting
38
+ if (this.connectionTimeouts.has(targetPeerId)) {
39
+ console.log(`Already connecting to ${targetPeerId.substring(0, 8)}... (connection in progress)`);
40
+ return;
41
+ }
42
+
43
+ // Check if we're already attempting through PeerDiscovery
44
+ if (this.mesh.peerDiscovery.isAttemptingConnection(targetPeerId)) {
45
+ console.log(`Already attempting connection to ${targetPeerId.substring(0, 8)}... via PeerDiscovery`);
46
+ return;
47
+ }
48
+
49
+ if (!this.mesh.canAcceptMorePeers()) {
50
+ console.log(`Cannot connect to ${targetPeerId.substring(0, 8)}... (max peers reached: ${this.mesh.maxPeers})`);
51
+ return;
52
+ }
53
+
54
+ // Check retry cooldown (only apply after first attempt)
55
+ const now = Date.now();
56
+ const attempts = this.connectionAttempts.get(targetPeerId) || 0;
57
+ if (attempts > 0) {
58
+ const lastAttempt = this.lastConnectionAttempt.get(targetPeerId) || 0;
59
+
60
+ // Use shorter delay for isolated peers to help them connect faster
61
+ const connectedCount = this.getConnectedPeerCount();
62
+ const retryDelay = connectedCount === 0 ? 500 : this.retryDelay; // 500ms for isolated peers, 1500ms otherwise
63
+
64
+ if (now - lastAttempt < retryDelay) {
65
+ const remaining = retryDelay - (now - lastAttempt);
66
+ console.log(`Connection to ${targetPeerId.substring(0, 8)}... on cooldown (${Math.round(remaining/1000)}s remaining, isolated: ${connectedCount === 0})`);
67
+ return;
68
+ }
69
+ }
70
+
71
+ // Check connection attempt count
72
+ if (attempts >= this.maxConnectionAttempts) {
73
+ this.mesh.emit('statusChanged', { type: 'warning', message: `Max connection attempts reached for ${targetPeerId.substring(0, 8)}...` });
74
+ this.mesh.peerDiscovery.removeDiscoveredPeer(targetPeerId);
75
+ return;
76
+ }
77
+
78
+ console.log(`Starting connection to ${targetPeerId.substring(0, 8)}... (attempt ${attempts + 1})`);
79
+ this.connectionAttempts.set(targetPeerId, attempts + 1);
80
+ this.lastConnectionAttempt.set(targetPeerId, now);
81
+ this.mesh.peerDiscovery.trackConnectionAttempt(targetPeerId);
82
+
83
+ // Set connection timeout - longer for media-enabled connections
84
+ const hasMedia = this.mesh.mediaManager.localStream !== null;
85
+ const timeoutDuration = hasMedia ? 45000 : 30000; // 45s for media, 30s for data-only
86
+
87
+ console.log(`Setting connection timeout for ${targetPeerId.substring(0, 8)}... - ${timeoutDuration/1000}s (media: ${hasMedia})`);
88
+
89
+ const timeoutId = setTimeout(() => {
90
+ if (this.peers.has(targetPeerId)) {
91
+ const peer = this.peers.get(targetPeerId);
92
+ const status = peer.getStatus();
93
+ const detailedStatus = peer.getDetailedStatus();
94
+ console.log(`Connection timeout check for ${targetPeerId.substring(0, 8)}... - current status: ${status}`);
95
+ console.log(`Detailed status:`, detailedStatus);
96
+
97
+ // Cleanup if not fully connected (includes 'connecting', 'new', 'failed', etc.)
98
+ if (status !== 'connected') {
99
+ this.mesh.emit('statusChanged', { type: 'warning', message: `Connection timeout for ${targetPeerId.substring(0, 8)}... (status: ${status}, media: ${hasMedia})` });
100
+ this.handleConnectionTimeout(targetPeerId);
101
+ } else {
102
+ console.log(`Connection to ${targetPeerId.substring(0, 8)}... is connected, clearing timeout`);
103
+ this.connectionTimeouts.delete(targetPeerId);
104
+ }
105
+ } else {
106
+ console.log(`Peer ${targetPeerId.substring(0, 8)}... no longer in peers Map, cleaning up timeout`);
107
+ this.connectionTimeouts.delete(targetPeerId);
108
+ }
109
+ }, timeoutDuration);
110
+
111
+ this.connectionTimeouts.set(targetPeerId, timeoutId);
112
+
113
+ try {
114
+ console.log(`Creating PeerConnection for ${targetPeerId.substring(0, 8)}...`);
115
+
116
+ // Get current media stream if available
117
+ const localStream = this.mesh.mediaManager.localStream;
118
+ const options = { localStream };
119
+
120
+ const peerConnection = new PeerConnection(targetPeerId, true, options);
121
+
122
+ // Set up event handlers BEFORE creating connection to catch all events
123
+ this.setupPeerConnectionHandlers(peerConnection);
124
+ this.peers.set(targetPeerId, peerConnection);
125
+
126
+ console.log(`Creating WebRTC connection for ${targetPeerId.substring(0, 8)}...`);
127
+ await peerConnection.createConnection();
128
+
129
+ console.log(`Creating offer for ${targetPeerId.substring(0, 8)}... (with media: ${hasMedia})`);
130
+ const offer = await peerConnection.createOffer();
131
+
132
+ console.log(`Offer created for ${targetPeerId.substring(0, 8)}...`, {
133
+ type: offer.type,
134
+ sdpLength: offer.sdp?.length || 0,
135
+ hasAudio: offer.sdp?.includes('m=audio') || false,
136
+ hasVideo: offer.sdp?.includes('m=video') || false
137
+ });
138
+
139
+ console.log(`Sending offer to ${targetPeerId.substring(0, 8)}...`);
140
+ await this.mesh.signalingClient.sendSignalingMessage({
141
+ type: 'offer',
142
+ data: offer,
143
+ targetPeerId
144
+ });
145
+
146
+ this.mesh.emit('statusChanged', { type: 'info', message: `Offer sent to ${targetPeerId.substring(0, 8)}...` });
147
+ } catch (error) {
148
+ console.error('Failed to connect to peer:', error);
149
+ this.mesh.emit('statusChanged', { type: 'error', message: `Failed to connect to ${targetPeerId.substring(0, 8)}...: ${error.message}` });
150
+ this.cleanupFailedConnection(targetPeerId);
151
+ }
152
+ }
153
+
154
+ handleConnectionTimeout(peerId) {
155
+ console.log(`Connection timeout for ${peerId.substring(0, 8)}...`);
156
+
157
+ const attempts = this.connectionAttempts.get(peerId) || 0;
158
+ if (attempts >= this.maxConnectionAttempts) {
159
+ this.mesh.emit('statusChanged', { type: 'warning', message: `Removing unresponsive peer ${peerId.substring(0, 8)}... after ${attempts} attempts` });
160
+ this.mesh.peerDiscovery.removeDiscoveredPeer(peerId);
161
+ this.connectionAttempts.delete(peerId);
162
+ } else {
163
+ this.mesh.peerDiscovery.clearConnectionAttempt(peerId);
164
+ console.log(`Will retry connection to ${peerId.substring(0, 8)}... (attempt ${attempts}/${this.maxConnectionAttempts})`);
165
+ }
166
+
167
+ // Always cleanup the failed connection and ensure it's removed from peers Map
168
+ this.cleanupFailedConnection(peerId);
169
+
170
+ // Double-check that the peer is actually removed from the UI
171
+ if (this.peers.has(peerId)) {
172
+ console.warn(`Peer ${peerId.substring(0, 8)}... still in peers Map after timeout cleanup, force removing`);
173
+ this.peers.delete(peerId);
174
+ this.emit('peersUpdated');
175
+ }
176
+ }
177
+
178
+ cleanupFailedConnection(peerId) {
179
+ console.log(`Cleaning up failed connection for ${peerId.substring(0, 8)}...`);
180
+
181
+ // Clear timeout
182
+ const timeoutId = this.connectionTimeouts.get(peerId);
183
+ if (timeoutId) {
184
+ clearTimeout(timeoutId);
185
+ this.connectionTimeouts.delete(peerId);
186
+ console.log(`Cleared timeout for ${peerId.substring(0, 8)}...`);
187
+ }
188
+
189
+ // Remove peer connection
190
+ let peerRemoved = false;
191
+ if (this.peers.has(peerId)) {
192
+ const peer = this.peers.get(peerId);
193
+ const status = peer.getStatus();
194
+ console.log(`Removing peer ${peerId.substring(0, 8)}... with status: ${status}`);
195
+
196
+ try {
197
+ if (typeof peer.markAsFailed === 'function') {
198
+ peer.markAsFailed('failed');
199
+ }
200
+ peer.close();
201
+ } catch (error) {
202
+ console.error('Error closing failed connection:', error);
203
+ }
204
+ this.peers.delete(peerId);
205
+ peerRemoved = true;
206
+ console.log(`Successfully removed peer ${peerId.substring(0, 8)}... from peers Map`);
207
+ } else {
208
+ console.log(`Peer ${peerId.substring(0, 8)}... was not in peers Map`);
209
+ }
210
+
211
+ // Clean up related data
212
+ this.mesh.peerDiscovery.clearConnectionAttempt(peerId);
213
+ this.pendingIceCandidates.delete(peerId);
214
+
215
+ // Always emit peersUpdated if we removed a peer or to force UI refresh
216
+ if (peerRemoved) {
217
+ console.log(`Emitting peersUpdated after removing ${peerId.substring(0, 8)}...`);
218
+ this.emit('peersUpdated');
219
+ }
220
+ }
221
+
222
+ cleanupRaceCondition(peerId) {
223
+ // Clear timeout
224
+ const timeoutId = this.connectionTimeouts.get(peerId);
225
+ if (timeoutId) {
226
+ clearTimeout(timeoutId);
227
+ this.connectionTimeouts.delete(peerId);
228
+ }
229
+
230
+ // Remove peer connection but preserve connection attempts
231
+ if (this.peers.has(peerId)) {
232
+ const peer = this.peers.get(peerId);
233
+ try {
234
+ peer.close();
235
+ } catch (error) {
236
+ console.error('Error closing race condition connection:', error);
237
+ }
238
+ this.peers.delete(peerId);
239
+ }
240
+
241
+ // Don't clear connection attempts or discovery data - just the active connection
242
+ this.pendingIceCandidates.delete(peerId);
243
+ this.emit('peersUpdated');
244
+ }
245
+
246
+ setupPeerConnectionHandlers(peerConnection) {
247
+ peerConnection.addEventListener('iceCandidate', async (event) => {
248
+ try {
249
+ console.log('Sending ICE candidate to', event.peerId);
250
+ await this.mesh.signalingClient.sendSignalingMessage({
251
+ type: 'ice-candidate',
252
+ data: event.candidate,
253
+ targetPeerId: event.peerId
254
+ });
255
+ } catch (error) {
256
+ console.error('Failed to send ICE candidate:', error);
257
+ }
258
+ });
259
+
260
+ peerConnection.addEventListener('connected', (event) => {
261
+ console.log(`[EVENT] Connected event received from ${event.peerId.substring(0, 8)}...`);
262
+
263
+ // Clear connection timeout on successful connection
264
+ const timeoutId = this.connectionTimeouts.get(event.peerId);
265
+ if (timeoutId) {
266
+ clearTimeout(timeoutId);
267
+ this.connectionTimeouts.delete(event.peerId);
268
+ }
269
+
270
+ // Reset connection attempts on successful connection
271
+ this.connectionAttempts.delete(event.peerId);
272
+
273
+ // Don't emit peerConnected here - wait for data channel to be ready
274
+ this.mesh.emit('statusChanged', { type: 'info', message: `WebRTC connected to ${event.peerId.substring(0, 8)}...` });
275
+ this.mesh.peerDiscovery.clearConnectionAttempt(event.peerId);
276
+ this.mesh.peerDiscovery.updateDiscoveryTimestamp(event.peerId);
277
+
278
+ this.emit('peersUpdated');
279
+ });
280
+
281
+ peerConnection.addEventListener('disconnected', (event) => {
282
+ this.mesh.emit('statusChanged', { type: 'info', message: `Disconnected from ${event.peerId.substring(0, 8)}...` });
283
+ this.handlePeerDisconnection(event.peerId, event.reason);
284
+ });
285
+
286
+ peerConnection.addEventListener('dataChannelOpen', (event) => {
287
+ console.log(`[EVENT] DataChannelOpen event received from ${event.peerId.substring(0, 8)}...`);
288
+
289
+ this.mesh.emit('statusChanged', { type: 'info', message: `Data channel ready with ${event.peerId.substring(0, 8)}...` });
290
+ this.emit('peersUpdated');
291
+ this.mesh.emit('peerConnected', { peerId: event.peerId });
292
+ });
293
+
294
+ peerConnection.addEventListener('message', (event) => {
295
+ this.handleIncomingMessage(event.message, event.peerId);
296
+ });
297
+
298
+ peerConnection.addEventListener('remoteStream', (event) => {
299
+ console.log(`[EVENT] Remote stream received from ${event.peerId.substring(0, 8)}...`);
300
+ this.emit('remoteStream', event);
301
+ });
302
+
303
+ peerConnection.addEventListener('renegotiationNeeded', async (event) => {
304
+ console.log(`🔄 Renegotiation needed for ${event.peerId.substring(0, 8)}...`);
305
+
306
+ try {
307
+ // Check connection state before attempting renegotiation
308
+ if (peerConnection.connection.signalingState !== 'stable') {
309
+ console.log(`Skipping renegotiation for ${event.peerId.substring(0, 8)}... - connection not stable (${peerConnection.connection.signalingState})`);
310
+ return;
311
+ }
312
+
313
+ // Additional check for connection state
314
+ if (peerConnection.connection.connectionState !== 'connected') {
315
+ console.log(`Skipping renegotiation for ${event.peerId.substring(0, 8)}... - not connected (${peerConnection.connection.connectionState})`);
316
+ return;
317
+ }
318
+
319
+ console.log(`🔄 Creating renegotiation offer for ${event.peerId.substring(0, 8)}...`);
320
+
321
+ // Create new offer with restartIce flag to avoid m-line issues
322
+ const offerOptions = {
323
+ iceRestart: false, // Don't restart ICE unless necessary
324
+ offerToReceiveAudio: true,
325
+ offerToReceiveVideo: true
326
+ };
327
+
328
+ const offer = await peerConnection.connection.createOffer(offerOptions);
329
+ await peerConnection.connection.setLocalDescription(offer);
330
+
331
+ // Send the new offer to the peer using the correct signaling method
332
+ await this.mesh.signalingClient.sendSignalingMessage({
333
+ type: 'offer',
334
+ data: offer,
335
+ targetPeerId: event.peerId
336
+ });
337
+
338
+ console.log(`🔄 Sent renegotiation offer to ${event.peerId.substring(0, 8)}...`);
339
+ } catch (error) {
340
+ console.error(`Failed to renegotiate with ${event.peerId}:`, error);
341
+
342
+ // If renegotiation fails due to m-line order, log but don't crash
343
+ if (error.name === 'InvalidAccessError' && error.message.includes('m-line')) {
344
+ console.log(`🔄 M-line order error detected for ${event.peerId.substring(0, 8)}... - this is expected with replaceTrack approach`);
345
+ }
346
+ }
347
+ });
348
+
349
+ // ...existing code...
350
+ }
351
+
352
+ handlePeerDisconnection(peerId, reason) {
353
+ // Prevent duplicate disconnection handling
354
+ if (this.disconnectionInProgress.has(peerId)) {
355
+ console.log(`Disconnection already in progress for ${peerId.substring(0, 8)}..., skipping duplicate`);
356
+ return;
357
+ }
358
+
359
+ console.log(`Handling peer disconnection: ${peerId.substring(0, 8)}... (${reason})`);
360
+
361
+ // Mark disconnection in progress
362
+ this.disconnectionInProgress.add(peerId);
363
+
364
+ try {
365
+ // Clear all related data
366
+ const timeoutId = this.connectionTimeouts.get(peerId);
367
+ if (timeoutId) {
368
+ clearTimeout(timeoutId);
369
+ this.connectionTimeouts.delete(peerId);
370
+ }
371
+
372
+ if (this.peers.has(peerId)) {
373
+ const peerConnection = this.peers.get(peerId);
374
+
375
+ try {
376
+ peerConnection.close();
377
+ } catch (error) {
378
+ console.error('Error closing peer connection:', error);
379
+ }
380
+
381
+ this.peers.delete(peerId);
382
+ }
383
+
384
+ this.mesh.peerDiscovery.clearConnectionAttempt(peerId);
385
+ this.pendingIceCandidates.delete(peerId);
386
+
387
+ // Clean up eviction tracking
388
+ this.mesh.evictionManager.clearEvictionTracking(peerId);
389
+
390
+ // Don't remove from discovered peers immediately - let it timeout naturally
391
+ // unless it's a goodbye or explicit removal
392
+ if (reason === 'left network' || reason === 'manually removed') {
393
+ this.mesh.peerDiscovery.removeDiscoveredPeer(peerId);
394
+ this.connectionAttempts.delete(peerId);
395
+ } else if (reason === 'connection failed' || reason === 'connection disconnected' || reason === 'ICE connection closed') {
396
+ // For connection failures, clear the attempt so we can retry later
397
+ this.connectionAttempts.delete(peerId);
398
+ console.log(`Cleared connection attempt for ${peerId.substring(0, 8)}... due to ${reason} - will retry later`);
399
+ }
400
+
401
+ this.mesh.emit('peerDisconnected', { peerId, reason });
402
+ this.emit('peersUpdated');
403
+
404
+ // Only trigger optimization if we're significantly under capacity
405
+ const connectedCount = this.getConnectedPeerCount();
406
+ const needsOptimization = connectedCount === 0; // Only optimize if completely disconnected
407
+
408
+ if (needsOptimization && this.mesh.autoDiscovery && this.mesh.peerDiscovery.getDiscoveredPeers().length > 0) {
409
+ console.log(`Completely disconnected (${connectedCount}/${this.mesh.maxPeers}), scheduling mesh optimization`);
410
+ setTimeout(() => {
411
+ // Check if we still need optimization
412
+ const currentCount = this.getConnectedPeerCount();
413
+ if (currentCount === 0) {
414
+ console.log(`Still completely disconnected (${currentCount}/${this.mesh.maxPeers}), attempting optimization`);
415
+ this.mesh.peerDiscovery.optimizeMeshConnections(this.peers);
416
+ } else {
417
+ console.log(`Connection recovered (${currentCount}/${this.mesh.maxPeers}), skipping optimization`);
418
+ }
419
+ }, 2000); // Wait 2 seconds before optimizing to allow connections to stabilize
420
+ } else {
421
+ console.log(`Peer count appropriate at ${connectedCount}/${this.mesh.maxPeers}, no optimization needed`);
422
+ }
423
+ } finally {
424
+ // Always clean up the disconnection tracking
425
+ this.disconnectionInProgress.delete(peerId);
426
+ }
427
+ }
428
+
429
+ disconnectAllPeers() {
430
+ this.peers.forEach((peerConnection, peerId) => {
431
+ peerConnection.close();
432
+ this.mesh.emit('peerDisconnected', { peerId, reason: 'mesh disconnected' });
433
+ });
434
+ }
435
+
436
+ disconnectPeer(peerId, reason) {
437
+ this.handlePeerDisconnection(peerId, reason);
438
+ }
439
+
440
+ removePeer(peerId) {
441
+ this.mesh.peerDiscovery.removeDiscoveredPeer(peerId);
442
+ this.mesh.peerDiscovery.clearConnectionAttempt(peerId);
443
+ this.connectionAttempts.delete(peerId);
444
+
445
+ // Clear timeout if exists
446
+ const timeoutId = this.connectionTimeouts.get(peerId);
447
+ if (timeoutId) {
448
+ clearTimeout(timeoutId);
449
+ this.connectionTimeouts.delete(peerId);
450
+ }
451
+
452
+ if (this.peers.has(peerId)) {
453
+ const peer = this.peers.get(peerId);
454
+ if (peer.connection) {
455
+ peer.connection.close();
456
+ }
457
+ this.peers.delete(peerId);
458
+ this.mesh.emit('peerDisconnected', { peerId, reason: 'manually removed' });
459
+ }
460
+
461
+ this.emit('peersUpdated');
462
+ }
463
+
464
+ canAcceptMorePeers() {
465
+ // Count connected peers first (these are guaranteed slots)
466
+ const connectedCount = this.getConnectedPeerCount();
467
+
468
+ // If we have room for connected peers, always accept
469
+ if (connectedCount < this.mesh.maxPeers) {
470
+ return true;
471
+ }
472
+
473
+ // If at max connected peers, check if we have stale peers we can evict
474
+ const stalePeerCount = this.getStalePeerCount();
475
+ const totalPeerCount = this.peers.size;
476
+
477
+ // Accept if we have stale peers that can be cleaned up
478
+ if (stalePeerCount > 0 && totalPeerCount >= this.mesh.maxPeers) {
479
+ console.log(`At capacity (${connectedCount}/${this.mesh.maxPeers} connected, ${totalPeerCount} total) but have ${stalePeerCount} stale peers that can be evicted`);
480
+ return true;
481
+ }
482
+
483
+ // Reject if we're at capacity with all viable peers
484
+ console.log(`Cannot accept more peers: ${connectedCount}/${this.mesh.maxPeers} connected, ${totalPeerCount} total peers in Map`);
485
+ return false;
486
+ }
487
+
488
+ /**
489
+ * Count peers that are in stale/non-viable states
490
+ */
491
+ getStalePeerCount() {
492
+ const now = Date.now();
493
+ const STALE_THRESHOLD = 45000; // 45 seconds (shorter than cleanup threshold)
494
+
495
+ return Array.from(this.peers.values()).filter(peerConnection => {
496
+ const status = peerConnection.getStatus();
497
+ const connectionAge = now - peerConnection.connectionStartTime;
498
+
499
+ return connectionAge > STALE_THRESHOLD &&
500
+ (status === 'failed' || status === 'disconnected' || status === 'closed');
501
+ }).length;
502
+ }
503
+
504
+ getConnectedPeerCount() {
505
+ return Array.from(this.peers.values()).filter(peerConnection =>
506
+ peerConnection.getStatus() === 'connected'
507
+ ).length;
508
+ }
509
+
510
+ getConnectedPeers() {
511
+ return Array.from(this.peers.values()).filter(peerConnection =>
512
+ peerConnection.getStatus() === 'connected'
513
+ );
514
+ }
515
+
516
+ getPeers() {
517
+ return Array.from(this.peers.entries()).map(([peerId, peerConnection]) => ({
518
+ peerId,
519
+ status: peerConnection.getStatus(),
520
+ isInitiator: peerConnection.isInitiator,
521
+ connectionStartTime: peerConnection.connectionStartTime
522
+ }));
523
+ }
524
+
525
+ hasPeer(peerId) {
526
+ return this.peers.has(peerId);
527
+ }
528
+
529
+ getPeer(peerId) {
530
+ return this.peers.get(peerId);
531
+ }
532
+
533
+ sendMessage(content) {
534
+ if (!content || typeof content !== 'string') {
535
+ console.error('Invalid message content:', content);
536
+ return 0;
537
+ }
538
+
539
+ // Use gossip protocol to broadcast messages throughout the mesh network
540
+ console.log(`Broadcasting message via gossip protocol: "${content}"`);
541
+ const messageId = this.mesh.gossipManager.broadcastMessage(content, 'chat');
542
+
543
+ if (messageId) {
544
+ // Return the number of directly connected peers for UI feedback
545
+ // (the message will propagate to the entire network via gossip)
546
+ const connectedCount = this.getConnectedPeerCount();
547
+ console.log(`Message broadcasted via gossip to ${connectedCount} directly connected peer(s), will propagate to entire network`);
548
+ return connectedCount;
549
+ } else {
550
+ console.error('Failed to broadcast message via gossip protocol');
551
+ return 0;
552
+ }
553
+ }
554
+
555
+ /**
556
+ * Send a message directly to a specific peer via data channel
557
+ * @param {string} peerId - The peer ID to send to
558
+ * @param {Object} message - The message object to send
559
+ * @returns {boolean} - True if message was sent successfully
560
+ */
561
+ sendDirectMessage(peerId, message) {
562
+ const peerConnection = this.peers.get(peerId);
563
+ if (!peerConnection) {
564
+ console.warn(`Cannot send direct message to ${peerId?.substring(0, 8)}: peer not connected`);
565
+ return false;
566
+ }
567
+
568
+ try {
569
+ console.log(`📤 Sending direct message to ${peerId?.substring(0, 8)}:`, message);
570
+ peerConnection.sendMessage(message);
571
+ return true;
572
+ } catch (error) {
573
+ console.error(`Failed to send direct message to ${peerId?.substring(0, 8)}:`, error);
574
+ return false;
575
+ }
576
+ }
577
+
578
+ async handleIceCandidate(candidate, fromPeerId) {
579
+ console.log('Handling ICE candidate from', fromPeerId);
580
+
581
+ const peerConnection = this.peers.get(fromPeerId);
582
+ if (peerConnection) {
583
+ try {
584
+ await peerConnection.handleIceCandidate(candidate);
585
+ } catch (error) {
586
+ console.error('Failed to add ICE candidate:', error);
587
+ }
588
+ } else {
589
+ // No peer connection exists yet - buffer the candidate for when it's created
590
+ console.log('Buffering ICE candidate for', fromPeerId, '(no peer connection yet)');
591
+ if (!this.pendingIceCandidates.has(fromPeerId)) {
592
+ this.pendingIceCandidates.set(fromPeerId, []);
593
+ }
594
+ this.pendingIceCandidates.get(fromPeerId).push(candidate);
595
+ }
596
+ }
597
+
598
+ async processPendingIceCandidates(peerId) {
599
+ const candidates = this.pendingIceCandidates.get(peerId);
600
+ if (candidates && candidates.length > 0) {
601
+ console.log(`Processing ${candidates.length} buffered ICE candidates for`, peerId);
602
+ const peerConnection = this.peers.get(peerId);
603
+
604
+ if (peerConnection) {
605
+ for (const candidate of candidates) {
606
+ try {
607
+ await peerConnection.handleIceCandidate(candidate);
608
+ } catch (error) {
609
+ console.error('Failed to add buffered ICE candidate:', error);
610
+ }
611
+ }
612
+
613
+ // Clear the buffer after processing
614
+ this.pendingIceCandidates.delete(peerId);
615
+ }
616
+ }
617
+ }
618
+
619
+ cleanup() {
620
+ // Stop periodic cleanup
621
+ this.stopPeriodicCleanup();
622
+
623
+ this.peers.clear();
624
+ this.connectionAttempts.clear();
625
+ this.connectionTimeouts.clear();
626
+ this.pendingIceCandidates.clear();
627
+ this.disconnectionInProgress.clear();
628
+ this.cleanupInProgress.clear();
629
+ this.lastConnectionAttempt.clear();
630
+ }
631
+
632
+ /**
633
+ * Start periodic cleanup of stale peer connections
634
+ */
635
+ startPeriodicCleanup() {
636
+ if (this.cleanupInterval) {
637
+ clearInterval(this.cleanupInterval);
638
+ }
639
+
640
+ // Run cleanup every 30 seconds
641
+ this.cleanupInterval = window.setInterval.call(window, () => {
642
+ this.cleanupStalePeers();
643
+ }, 30000);
644
+ }
645
+
646
+ /**
647
+ * Stop periodic cleanup
648
+ */
649
+ stopPeriodicCleanup() {
650
+ if (this.cleanupInterval) {
651
+ clearInterval(this.cleanupInterval);
652
+ this.cleanupInterval = null;
653
+ }
654
+ }
655
+
656
+ /**
657
+ * Clean up peers that are in non-viable states for too long
658
+ */
659
+ cleanupStalePeers() {
660
+ const now = Date.now();
661
+ const STALE_THRESHOLD = 60000; // 60 seconds
662
+ const DISCONNECTED_THRESHOLD = 5000; // 5 seconds for disconnected peers
663
+ const peersToCleanup = [];
664
+
665
+ this.peers.forEach((peerConnection, peerId) => {
666
+ const status = peerConnection.getStatus();
667
+ const connectionAge = now - peerConnection.connectionStartTime;
668
+
669
+ // Immediately clean up disconnected peers
670
+ if (status === 'disconnected' && connectionAge > DISCONNECTED_THRESHOLD) {
671
+ console.log(`Disconnected peer detected: ${peerId.substring(0, 8)}... (status: ${status}, age: ${Math.round(connectionAge/1000)}s)`);
672
+ peersToCleanup.push(peerId);
673
+ }
674
+ // Clean up peers that have been in non-connected states for too long
675
+ else if (connectionAge > STALE_THRESHOLD) {
676
+ if (status === 'connecting' || status === 'channel-connecting' ||
677
+ status === 'failed' || status === 'closed') {
678
+ console.log(`Stale peer detected: ${peerId.substring(0, 8)}... (status: ${status}, age: ${Math.round(connectionAge/1000)}s)`);
679
+ peersToCleanup.push(peerId);
680
+ }
681
+ }
682
+ });
683
+
684
+ if (peersToCleanup.length > 0) {
685
+ console.log(`Cleaning up ${peersToCleanup.length} stale peer(s)`);
686
+ peersToCleanup.forEach(peerId => {
687
+ this.cleanupFailedConnection(peerId);
688
+ });
689
+ }
690
+ }
691
+
692
+ /**
693
+ * Force cleanup of peers that are not in connected state (for debugging)
694
+ */
695
+ forceCleanupInvalidPeers() {
696
+ console.log('Force cleaning up peers not in connected state...');
697
+ const peersToRemove = [];
698
+
699
+ this.peers.forEach((peerConnection, peerId) => {
700
+ const status = peerConnection.getStatus();
701
+ if (status !== 'connected') {
702
+ console.log(`Found peer ${peerId.substring(0, 8)}... in invalid state: ${status}`);
703
+ peersToRemove.push(peerId);
704
+ }
705
+ });
706
+
707
+ peersToRemove.forEach(peerId => {
708
+ console.log(`Force removing peer ${peerId.substring(0, 8)}...`);
709
+ this.cleanupFailedConnection(peerId);
710
+ });
711
+
712
+ if (peersToRemove.length > 0) {
713
+ console.log(`Force cleaned up ${peersToRemove.length} invalid peers`);
714
+ this.emit('peersUpdated');
715
+ }
716
+
717
+ return peersToRemove.length;
718
+ }
719
+
720
+ /**
721
+ * Get a summary of all peer states for debugging
722
+ */
723
+ getPeerStateSummary() {
724
+ const summary = {
725
+ total: this.peers.size,
726
+ connected: 0,
727
+ connecting: 0,
728
+ channelConnecting: 0,
729
+ failed: 0,
730
+ disconnected: 0,
731
+ closed: 0,
732
+ other: 0,
733
+ stale: this.getStalePeerCount()
734
+ };
735
+
736
+ this.peers.forEach((peerConnection) => {
737
+ const status = peerConnection.getStatus();
738
+ switch (status) {
739
+ case 'connected':
740
+ summary.connected++;
741
+ break;
742
+ case 'connecting':
743
+ summary.connecting++;
744
+ break;
745
+ case 'channel-connecting':
746
+ summary.channelConnecting++;
747
+ break;
748
+ case 'failed':
749
+ summary.failed++;
750
+ break;
751
+ case 'disconnected':
752
+ summary.disconnected++;
753
+ break;
754
+ case 'closed':
755
+ summary.closed++;
756
+ break;
757
+ default:
758
+ summary.other++;
759
+ }
760
+ });
761
+
762
+ return summary;
763
+ }
764
+
765
+ getDetailedPeerStatus() {
766
+ const peerStatuses = {};
767
+ this.peers.forEach((peerConnection, peerId) => {
768
+ peerStatuses[peerId.substring(0, 8) + '...'] = {
769
+ status: peerConnection.getStatus(),
770
+ isInitiator: peerConnection.isInitiator,
771
+ dataChannelReady: peerConnection.dataChannelReady,
772
+ connectionStartTime: peerConnection.connectionStartTime,
773
+ connectionState: peerConnection.connection?.connectionState,
774
+ iceConnectionState: peerConnection.connection?.iceConnectionState
775
+ };
776
+ });
777
+ return peerStatuses;
778
+ }
779
+
780
+ // Get all peer connections
781
+ getAllConnections() {
782
+ return Array.from(this.peers.values());
783
+ }
784
+
785
+ /**
786
+ * Route incoming messages based on their type
787
+ */
788
+ handleIncomingMessage(message, fromPeerId) {
789
+ if (!message || typeof message !== 'object') {
790
+ console.warn('Received invalid message from', fromPeerId?.substring(0, 8));
791
+ return;
792
+ }
793
+
794
+ // Route based on message type
795
+ switch (message.type) {
796
+ case 'gossip':
797
+ // Gossip protocol messages
798
+ this.mesh.gossipManager.handleGossipMessage(message, fromPeerId);
799
+ break;
800
+
801
+ case 'eviction':
802
+ // Handle eviction notices
803
+ this.handleEvictionMessage(message, fromPeerId);
804
+ break;
805
+
806
+ case 'dht':
807
+ // WebDHT messages
808
+ if (this.mesh.webDHT) {
809
+ this.mesh.webDHT.handleMessage(message, fromPeerId);
810
+ }
811
+ break;
812
+
813
+ default:
814
+ // Unknown message type - try gossip as fallback for backward compatibility
815
+ console.warn(`Unknown message type '${message.type}' from ${fromPeerId?.substring(0, 8)}, trying gossip handler`);
816
+ this.mesh.gossipManager.handleGossipMessage(message, fromPeerId);
817
+ break;
818
+ }
819
+ }
820
+
821
+ /**
822
+ * Handle eviction messages
823
+ */
824
+ handleEvictionMessage(message, fromPeerId) {
825
+ console.log(`Received eviction notice from ${fromPeerId?.substring(0, 8)}: ${message.reason}`);
826
+
827
+ // Emit eviction event for UI notification
828
+ this.mesh.emit('peerEvicted', {
829
+ peerId: fromPeerId,
830
+ reason: message.reason,
831
+ initiatedByPeer: true
832
+ });
833
+
834
+ // Close the connection gracefully
835
+ const peerConnection = this.peers.get(fromPeerId);
836
+ if (peerConnection) {
837
+ peerConnection.close();
838
+ this.peers.delete(fromPeerId);
839
+ }
840
+ }
841
+ }