peerpigeon 1.0.8 → 1.1.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/README.md +10 -2
- package/dist/peerpigeon-browser.js +60 -84
- package/dist/peerpigeon-browser.js.map +3 -3
- package/docs/HUB_P2P_MESH.md +358 -0
- package/package.json +5 -1
- package/server/index.js +519 -264
- package/src/ConnectionManager.js +30 -54
- package/src/PeerConnection.js +7 -12
- package/src/PeerDiscovery.js +31 -30
- package/src/PeerPigeonMesh.js +10 -7
- package/src/SignalingHandler.js +5 -18
- package/docs/PEER_DISCOVERY_FIXES.md +0 -140
package/src/ConnectionManager.js
CHANGED
|
@@ -65,37 +65,14 @@ export class ConnectionManager extends EventEmitter {
|
|
|
65
65
|
|
|
66
66
|
// Enhanced duplicate connection prevention
|
|
67
67
|
if (this.peers.has(targetPeerId)) {
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
// If already connected, don't retry
|
|
72
|
-
if (status === 'connected') {
|
|
73
|
-
this.debug.log(`Already connected to ${targetPeerId.substring(0, 8)}... (status: ${status})`);
|
|
74
|
-
return;
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
// If connecting but stuck, allow retry after timeout
|
|
78
|
-
if (status === 'connecting') {
|
|
79
|
-
const connectionAge = Date.now() - (existingPeer.createdAt || 0);
|
|
80
|
-
if (connectionAge < 10000) { // Wait 10 seconds before considering it stuck
|
|
81
|
-
this.debug.log(`Connection to ${targetPeerId.substring(0, 8)}... still in progress (${Math.round(connectionAge / 1000)}s)`);
|
|
82
|
-
return;
|
|
83
|
-
}
|
|
84
|
-
this.debug.log(`Connection to ${targetPeerId.substring(0, 8)}... appears stuck (${Math.round(connectionAge / 1000)}s), will retry`);
|
|
85
|
-
this.cleanupFailedConnection(targetPeerId);
|
|
86
|
-
}
|
|
68
|
+
this.debug.log(`Already connected to ${targetPeerId.substring(0, 8)}...`);
|
|
69
|
+
return;
|
|
87
70
|
}
|
|
88
71
|
|
|
89
72
|
// Check if we're already attempting through PeerDiscovery
|
|
90
73
|
if (this.mesh.peerDiscovery.isAttemptingConnection(targetPeerId)) {
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
if (attemptAge < 10000) {
|
|
94
|
-
this.debug.log(`Already attempting connection to ${targetPeerId.substring(0, 8)}... via PeerDiscovery (${Math.round(attemptAge / 1000)}s ago)`);
|
|
95
|
-
return;
|
|
96
|
-
}
|
|
97
|
-
this.debug.log(`Old connection attempt to ${targetPeerId.substring(0, 8)}... (${Math.round(attemptAge / 1000)}s ago), allowing retry`);
|
|
98
|
-
this.mesh.peerDiscovery.clearConnectionAttempt(targetPeerId);
|
|
74
|
+
this.debug.log(`Already attempting connection to ${targetPeerId.substring(0, 8)}... via PeerDiscovery`);
|
|
75
|
+
return;
|
|
99
76
|
}
|
|
100
77
|
|
|
101
78
|
// INITIATOR LOGIC: Use deterministic peer ID comparison to prevent race conditions
|
|
@@ -125,22 +102,15 @@ export class ConnectionManager extends EventEmitter {
|
|
|
125
102
|
|
|
126
103
|
if (now - lastAttempt < retryDelay) {
|
|
127
104
|
const remaining = retryDelay - (now - lastAttempt);
|
|
128
|
-
this.debug.log(`Connection to ${targetPeerId.substring(0, 8)}... on cooldown (${Math.round(remaining)}
|
|
105
|
+
this.debug.log(`Connection to ${targetPeerId.substring(0, 8)}... on cooldown (${Math.round(remaining / 1000)}s remaining, isolated: ${connectedCount === 0})`);
|
|
129
106
|
return;
|
|
130
107
|
}
|
|
131
108
|
}
|
|
132
109
|
|
|
133
|
-
// Check connection attempt count
|
|
134
|
-
|
|
135
|
-
const maxAttempts = connectedCount === 0 ? this.maxConnectionAttempts * 2 : this.maxConnectionAttempts;
|
|
136
|
-
|
|
137
|
-
if (attempts >= maxAttempts) {
|
|
138
|
-
this.debug.log(`Max connection attempts (${maxAttempts}) reached for ${targetPeerId.substring(0, 8)}...`);
|
|
110
|
+
// Check connection attempt count
|
|
111
|
+
if (attempts >= this.maxConnectionAttempts) {
|
|
139
112
|
this.mesh.emit('statusChanged', { type: 'warning', message: `Max connection attempts reached for ${targetPeerId.substring(0, 8)}...` });
|
|
140
|
-
|
|
141
|
-
this.connectionAttempts.delete(targetPeerId);
|
|
142
|
-
this.lastConnectionAttempt.delete(targetPeerId);
|
|
143
|
-
this.mesh.peerDiscovery.clearConnectionAttempt(targetPeerId);
|
|
113
|
+
this.mesh.peerDiscovery.removeDiscoveredPeer(targetPeerId);
|
|
144
114
|
return;
|
|
145
115
|
}
|
|
146
116
|
|
|
@@ -458,25 +428,24 @@ export class ConnectionManager extends EventEmitter {
|
|
|
458
428
|
}
|
|
459
429
|
|
|
460
430
|
canAcceptMorePeers() {
|
|
461
|
-
// Count connected peers
|
|
431
|
+
// Count connected peers for capacity check
|
|
462
432
|
const connectedCount = this.getConnectedPeerCount();
|
|
463
|
-
|
|
464
|
-
// If we have room for connected peers, always accept
|
|
465
|
-
if (connectedCount < this.mesh.maxPeers) {
|
|
466
|
-
return true;
|
|
467
|
-
}
|
|
468
|
-
|
|
469
|
-
// If at max connected peers, check if we have stale peers we can evict
|
|
470
|
-
const stalePeerCount = this.getStalePeerCount();
|
|
471
433
|
const totalPeerCount = this.peers.size;
|
|
472
|
-
|
|
473
|
-
//
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
434
|
+
|
|
435
|
+
// STRICT: Don't accept if we're at or over maxPeers
|
|
436
|
+
// Remove the "+1 overhead" logic that was causing overshoot
|
|
437
|
+
if (connectedCount >= this.mesh.maxPeers) {
|
|
438
|
+
this.debug.log(`At or over capacity: ${connectedCount}/${this.mesh.maxPeers} connected, rejecting new connections`);
|
|
439
|
+
return false;
|
|
477
440
|
}
|
|
478
|
-
|
|
479
|
-
//
|
|
441
|
+
|
|
442
|
+
// Also check total peer count (including connecting) to prevent race conditions
|
|
443
|
+
if (totalPeerCount >= this.mesh.maxPeers) {
|
|
444
|
+
this.debug.log(`Total peer count at capacity: ${totalPeerCount}/${this.mesh.maxPeers}, rejecting new connections`);
|
|
445
|
+
return false;
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
return true;
|
|
480
449
|
this.debug.log(`Cannot accept more peers: ${connectedCount}/${this.mesh.maxPeers} connected, ${totalPeerCount} total peers in Map`);
|
|
481
450
|
return false;
|
|
482
451
|
}
|
|
@@ -790,6 +759,13 @@ export class ConnectionManager extends EventEmitter {
|
|
|
790
759
|
return;
|
|
791
760
|
}
|
|
792
761
|
|
|
762
|
+
// Emit generic messageReceived event for all messages (used by hub server)
|
|
763
|
+
this.mesh.emit('messageReceived', {
|
|
764
|
+
from: fromPeerId,
|
|
765
|
+
data: message,
|
|
766
|
+
timestamp: Date.now()
|
|
767
|
+
});
|
|
768
|
+
|
|
793
769
|
// Handle binary messages first
|
|
794
770
|
if (message.type === 'binary' && message.data instanceof Uint8Array) {
|
|
795
771
|
this.debug.log(`📦 Received binary message (${message.size} bytes) from ${fromPeerId.substring(0, 8)}...`);
|
package/src/PeerConnection.js
CHANGED
|
@@ -270,32 +270,27 @@ export class PeerConnection extends EventEmitter {
|
|
|
270
270
|
if (this.connection &&
|
|
271
271
|
this.connection.iceConnectionState === 'disconnected' &&
|
|
272
272
|
!this.isClosing) {
|
|
273
|
-
//
|
|
274
|
-
// and should persist even without signaling. Only disconnect on "failed" state.
|
|
275
|
-
// Check if we have signaling or mesh connectivity for ICE restart attempts
|
|
273
|
+
// Check if signaling is available before attempting ICE restart
|
|
276
274
|
const hasSignaling = this.mesh && this.mesh.signalingClient && this.mesh.signalingClient.isConnected();
|
|
277
275
|
const hasMeshConnectivity = this.mesh && this.mesh.connected && this.mesh.connectionManager.getConnectedPeerCount() > 0;
|
|
278
276
|
|
|
279
277
|
if (hasSignaling || hasMeshConnectivity) {
|
|
280
|
-
this.debug.log(
|
|
278
|
+
this.debug.log(`❌ ICE remained disconnected for ${this.peerId}, attempting restart (signaling: ${hasSignaling}, mesh: ${hasMeshConnectivity})`);
|
|
281
279
|
try {
|
|
282
280
|
this.restartIceViaSignaling().catch(error => {
|
|
283
281
|
this.debug.error('Failed to restart ICE after disconnection:', error);
|
|
284
|
-
|
|
285
|
-
this.debug.log(`Will wait for ICE to reach "failed" state before disconnecting ${this.peerId}`);
|
|
282
|
+
this.emit('disconnected', { peerId: this.peerId, reason: 'ICE disconnected' });
|
|
286
283
|
});
|
|
287
284
|
} catch (error) {
|
|
288
285
|
this.debug.error('Failed to restart ICE after disconnection:', error);
|
|
289
|
-
|
|
290
|
-
this.debug.log(`Will wait for ICE to reach "failed" state before disconnecting ${this.peerId}`);
|
|
286
|
+
this.emit('disconnected', { peerId: this.peerId, reason: 'ICE disconnected' });
|
|
291
287
|
}
|
|
292
288
|
} else {
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
this.debug.log(`⚠️ ICE disconnected for ${this.peerId} without signaling - waiting for ICE state to resolve naturally`);
|
|
289
|
+
this.debug.log(`❌ ICE remained disconnected for ${this.peerId}, disconnecting`);
|
|
290
|
+
this.emit('disconnected', { peerId: this.peerId, reason: 'ICE disconnected' });
|
|
296
291
|
}
|
|
297
292
|
}
|
|
298
|
-
}, 5000); //
|
|
293
|
+
}, 5000); // Faster ICE reconnection - 5 seconds
|
|
299
294
|
}
|
|
300
295
|
};
|
|
301
296
|
|
package/src/PeerDiscovery.js
CHANGED
|
@@ -38,46 +38,43 @@ export class PeerDiscovery extends EventEmitter {
|
|
|
38
38
|
}
|
|
39
39
|
|
|
40
40
|
addDiscoveredPeer(peerId) {
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
if (wasKnown) {
|
|
48
|
-
this.debug.log(`Re-discovered peer ${peerId.substring(0, 8)}... (updating timestamp)`);
|
|
49
|
-
|
|
50
|
-
// Clean up stale connection attempt if it's been more than 5 seconds
|
|
51
|
-
if (this.connectionAttempts.has(peerId)) {
|
|
52
|
-
const attemptTime = this.connectionAttempts.get(peerId);
|
|
53
|
-
if (now - attemptTime > 5000) {
|
|
54
|
-
this.debug.log(`Clearing stale connection attempt for ${peerId.substring(0, 8)}...`);
|
|
55
|
-
this.connectionAttempts.delete(peerId);
|
|
56
|
-
}
|
|
57
|
-
}
|
|
58
|
-
} else {
|
|
59
|
-
this.debug.log(`Discovered new peer ${peerId.substring(0, 8)}...`);
|
|
60
|
-
this.emit('peerDiscovered', { peerId });
|
|
41
|
+
// Skip if we already know about this peer (prevent duplicate processing)
|
|
42
|
+
if (this.discoveredPeers.has(peerId)) {
|
|
43
|
+
// Update timestamp but don't emit events or trigger connections
|
|
44
|
+
this.discoveredPeers.set(peerId, Date.now());
|
|
45
|
+
return;
|
|
61
46
|
}
|
|
62
47
|
|
|
63
|
-
|
|
64
|
-
|
|
48
|
+
this.discoveredPeers.set(peerId, Date.now());
|
|
49
|
+
this.emit('peerDiscovered', { peerId });
|
|
50
|
+
|
|
51
|
+
this.debug.log(`Discovered peer ${peerId.substring(0, 8)}...`);
|
|
52
|
+
|
|
53
|
+
// Only auto-connect if we should initiate to this peer and we're not already trying
|
|
65
54
|
const shouldInitiate = this.shouldInitiateConnection(peerId);
|
|
55
|
+
const alreadyAttempting = this.connectionAttempts.has(peerId);
|
|
56
|
+
|
|
57
|
+
this.debug.log(`🔍 Connection decision for ${peerId.substring(0, 8)}...: autoDiscovery=${this.autoDiscovery}, shouldInitiate=${shouldInitiate}, alreadyAttempting=${alreadyAttempting}`);
|
|
66
58
|
|
|
67
|
-
if (this.autoDiscovery && shouldInitiate && !
|
|
68
|
-
this.debug.log(`Considering connection to ${peerId.substring(0, 8)}
|
|
59
|
+
if (this.autoDiscovery && shouldInitiate && !alreadyAttempting) {
|
|
60
|
+
this.debug.log(`Considering connection to ${peerId.substring(0, 8)}...`);
|
|
69
61
|
|
|
70
62
|
const canAccept = this.canAcceptMorePeers();
|
|
63
|
+
this.debug.log(`Can accept more peers: ${canAccept}`);
|
|
71
64
|
if (canAccept) {
|
|
72
|
-
this.debug.log(
|
|
65
|
+
this.debug.log(`🚀 Connecting to ${peerId.substring(0, 8)}...`);
|
|
73
66
|
this.emit('connectToPeer', { peerId });
|
|
74
67
|
} else {
|
|
75
|
-
this.debug.log(
|
|
68
|
+
this.debug.log(`❌ Cannot accept more peers (at capacity)`);
|
|
69
|
+
}
|
|
70
|
+
} else {
|
|
71
|
+
if (!this.autoDiscovery) {
|
|
72
|
+
this.debug.log(`❌ Auto-discovery disabled, not connecting to ${peerId.substring(0, 8)}...`);
|
|
73
|
+
} else if (!shouldInitiate) {
|
|
74
|
+
this.debug.log(`⏸️ Not initiating to ${peerId.substring(0, 8)}... (they should initiate to us)`);
|
|
75
|
+
} else if (alreadyAttempting) {
|
|
76
|
+
this.debug.log(`⏸️ Already attempting connection to ${peerId.substring(0, 8)}...`);
|
|
76
77
|
}
|
|
77
|
-
} else if (alreadyTrying) {
|
|
78
|
-
this.debug.log(`Already attempting connection to ${peerId.substring(0, 8)}...`);
|
|
79
|
-
} else if (!shouldInitiate) {
|
|
80
|
-
this.debug.log(`Not initiating to ${peerId.substring(0, 8)}... (should wait for them to initiate)`);
|
|
81
78
|
}
|
|
82
79
|
|
|
83
80
|
this.scheduleMeshOptimization();
|
|
@@ -113,6 +110,10 @@ export class PeerDiscovery extends EventEmitter {
|
|
|
113
110
|
}
|
|
114
111
|
|
|
115
112
|
shouldInitiateConnection(targetPeerId) {
|
|
113
|
+
if (this.connectionAttempts.has(targetPeerId)) {
|
|
114
|
+
return false;
|
|
115
|
+
}
|
|
116
|
+
|
|
116
117
|
// Check current connection count to handle isolation
|
|
117
118
|
this.emit('checkCapacity');
|
|
118
119
|
const currentConnectionCount = this._currentConnectionCount || 0;
|
package/src/PeerPigeonMesh.js
CHANGED
|
@@ -334,17 +334,18 @@ export class PeerPigeonMesh extends EventEmitter {
|
|
|
334
334
|
this.debug.warn('PigeonRTC initialization failed:', error.message);
|
|
335
335
|
}
|
|
336
336
|
|
|
337
|
-
// Request media permissions for localhost WebRTC to work
|
|
338
|
-
//
|
|
337
|
+
// Request media permissions for localhost WebRTC to work unless explicitly disabled
|
|
338
|
+
// Added DISABLE_LOCALHOST_MEDIA_REQUEST override for automated/headless test environments
|
|
339
339
|
if (environmentDetector.isBrowser) {
|
|
340
340
|
try {
|
|
341
|
+
const disableLocalhostMedia = typeof window !== 'undefined' && window.DISABLE_LOCALHOST_MEDIA_REQUEST;
|
|
341
342
|
const isLocalhost = window.location.hostname === 'localhost' ||
|
|
342
343
|
window.location.hostname === '127.0.0.1' ||
|
|
343
344
|
window.location.hostname === '';
|
|
344
|
-
|
|
345
|
-
if (isLocalhost && navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
|
|
346
|
-
this.debug.log('🎤 Requesting media permissions for localhost WebRTC...');
|
|
347
|
-
|
|
345
|
+
|
|
346
|
+
if (!disableLocalhostMedia && isLocalhost && navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
|
|
347
|
+
this.debug.log('🎤 Requesting media permissions for localhost WebRTC (not disabled)...');
|
|
348
|
+
|
|
348
349
|
// Request minimal audio permission (no video to reduce intrusiveness)
|
|
349
350
|
const stream = await navigator.mediaDevices.getUserMedia({
|
|
350
351
|
audio: true,
|
|
@@ -353,12 +354,14 @@ export class PeerPigeonMesh extends EventEmitter {
|
|
|
353
354
|
this.debug.warn('Media permission denied - connections may fail on localhost:', err.message);
|
|
354
355
|
return null;
|
|
355
356
|
});
|
|
356
|
-
|
|
357
|
+
|
|
357
358
|
// Immediately stop all tracks - we only needed the permission
|
|
358
359
|
if (stream) {
|
|
359
360
|
stream.getTracks().forEach(track => track.stop());
|
|
360
361
|
this.debug.log('✅ Media permissions granted - localhost connections will work');
|
|
361
362
|
}
|
|
363
|
+
} else if (disableLocalhostMedia) {
|
|
364
|
+
this.debug.log('🚫 Skipping localhost media permission request (DISABLE_LOCALHOST_MEDIA_REQUEST flag set)');
|
|
362
365
|
}
|
|
363
366
|
} catch (error) {
|
|
364
367
|
this.debug.warn('Could not request media permissions:', error.message);
|
package/src/SignalingHandler.js
CHANGED
|
@@ -100,26 +100,13 @@ export class SignalingHandler extends EventEmitter {
|
|
|
100
100
|
}
|
|
101
101
|
|
|
102
102
|
handlePeerAnnouncement(fromPeerId) {
|
|
103
|
-
//
|
|
104
|
-
if (this.
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
this.debug.log(`Peer ${fromPeerId.substring(0, 8)}... already connected (${peerStatus}), updating timestamp`);
|
|
108
|
-
this.mesh.peerDiscovery.updateDiscoveryTimestamp(fromPeerId);
|
|
109
|
-
return;
|
|
110
|
-
}
|
|
111
|
-
this.debug.log(`Peer ${fromPeerId.substring(0, 8)}... exists but not connected (${peerStatus}), allowing re-discovery`);
|
|
112
|
-
}
|
|
113
|
-
|
|
114
|
-
// Allow re-discovery to refresh timestamps and potentially retry connections
|
|
115
|
-
const wasKnown = this.mesh.peerDiscovery.hasPeer(fromPeerId);
|
|
116
|
-
if (wasKnown) {
|
|
117
|
-
this.debug.log(`Peer ${fromPeerId.substring(0, 8)}... already known, refreshing discovery`);
|
|
118
|
-
} else {
|
|
119
|
-
this.debug.log(`New peer discovered: ${fromPeerId.substring(0, 8)}...`);
|
|
103
|
+
// Prevent duplicate announcements - only announce if we haven't seen this peer before
|
|
104
|
+
if (this.mesh.peerDiscovery.hasPeer(fromPeerId)) {
|
|
105
|
+
this.debug.log(`Peer ${fromPeerId.substring(0, 8)}... already known, skipping announcement`);
|
|
106
|
+
return;
|
|
120
107
|
}
|
|
121
108
|
|
|
122
|
-
this.mesh.emit('statusChanged', { type: 'info', message: `Peer ${fromPeerId.substring(0, 8)}...
|
|
109
|
+
this.mesh.emit('statusChanged', { type: 'info', message: `Peer ${fromPeerId.substring(0, 8)}... announced` });
|
|
123
110
|
this.debug.log(`Adding discovered peer: ${fromPeerId.substring(0, 8)}... to PeerDiscovery`);
|
|
124
111
|
this.debug.log(`Current peer count: ${this.connectionManager.getConnectedPeerCount()}/${this.mesh.maxPeers}`);
|
|
125
112
|
this.debug.log(`All discovered peers: ${Array.from(this.mesh.peerDiscovery.discoveredPeers.keys()).map(p => p.substring(0, 8)).join(', ')}`);
|
|
@@ -1,140 +0,0 @@
|
|
|
1
|
-
# Peer Discovery and Connection Fixes
|
|
2
|
-
|
|
3
|
-
**Date**: November 21, 2025
|
|
4
|
-
**Issue**: Peers sometimes do not discover each other or connect using pigeonhub
|
|
5
|
-
|
|
6
|
-
## Problems Identified
|
|
7
|
-
|
|
8
|
-
### 1. **Duplicate Peer Announcement Handling** (`SignalingHandler.js`)
|
|
9
|
-
**Problem**: The `handlePeerAnnouncement` method was completely skipping re-announcements of already known peers, even if those peers had disconnected or the connection attempt had failed.
|
|
10
|
-
|
|
11
|
-
**Impact**: If a peer announcement was missed or a connection failed, peers would never retry connecting to each other.
|
|
12
|
-
|
|
13
|
-
**Fix**: Modified to:
|
|
14
|
-
- Check if peer is already actively connected before skipping
|
|
15
|
-
- Allow re-discovery to refresh timestamps
|
|
16
|
-
- Clean up stale connection attempts after 5 seconds
|
|
17
|
-
- Log the reason for accepting or rejecting announcements
|
|
18
|
-
|
|
19
|
-
### 2. **Connection Attempt Cleanup** (`PeerDiscovery.js`)
|
|
20
|
-
**Problem**: The `addDiscoveredPeer` method was returning early for known peers without evaluating whether a connection should be attempted again.
|
|
21
|
-
|
|
22
|
-
**Impact**: Once a peer was discovered, even if connection attempts failed, no retry would occur unless the peer was completely removed from the discovered list.
|
|
23
|
-
|
|
24
|
-
**Fix**: Modified to:
|
|
25
|
-
- Always update timestamps for known peers
|
|
26
|
-
- Clean up stale connection attempts (>5 seconds old)
|
|
27
|
-
- Re-evaluate connection initiation even for known peers
|
|
28
|
-
- Add detailed logging for troubleshooting
|
|
29
|
-
|
|
30
|
-
### 3. **Strict Connection Attempt Blocking** (`PeerDiscovery.js`)
|
|
31
|
-
**Problem**: The `shouldInitiateConnection` method was checking `connectionAttempts` at the start and returning false immediately if an attempt was in progress, which could block retries indefinitely.
|
|
32
|
-
|
|
33
|
-
**Impact**: If a connection attempt got stuck or timed out, the peer would never retry because the attempt tracking wasn't being cleared.
|
|
34
|
-
|
|
35
|
-
**Fix**: Removed the early return for `connectionAttempts.has(targetPeerId)` to allow the isolation override logic to work properly.
|
|
36
|
-
|
|
37
|
-
### 4. **Connection Retry Logic** (`ConnectionManager.js`)
|
|
38
|
-
**Problem**: The `connectToPeer` method had overly strict duplicate connection prevention that didn't account for stuck or timed-out connections.
|
|
39
|
-
|
|
40
|
-
**Impact**: Connections that got stuck in "connecting" state would prevent retries, leaving peers permanently unable to connect.
|
|
41
|
-
|
|
42
|
-
**Fix**: Modified to:
|
|
43
|
-
- Check connection age before blocking retries
|
|
44
|
-
- Allow retries for stuck connections (>10 seconds)
|
|
45
|
-
- Allow retries for old connection attempts (>10 seconds)
|
|
46
|
-
- Increase max attempts for isolated peers (double the normal limit)
|
|
47
|
-
- Don't permanently remove peers after max attempts - just reset counters
|
|
48
|
-
|
|
49
|
-
### 5. **Hub Peer Forwarding** (`server/index.js`)
|
|
50
|
-
**Problem**: When hubs received peer-discovered messages from bootstrap hubs or other hubs, they weren't relaying these announcements to OTHER connected hubs, only to local client peers.
|
|
51
|
-
|
|
52
|
-
**Impact**: In a multi-hub network, peers connected to different hubs wouldn't discover each other because the peer announcements weren't being propagated across the hub mesh.
|
|
53
|
-
|
|
54
|
-
**Fix**: Modified `handlePeerDiscovered` to:
|
|
55
|
-
- Relay peer-discovered messages to other connected hubs
|
|
56
|
-
- Forward to both bootstrap connections and incoming hub connections
|
|
57
|
-
- Avoid relaying back to the sender hub
|
|
58
|
-
- Add detailed logging for hub relay operations
|
|
59
|
-
|
|
60
|
-
### 6. **Bootstrap Hub Message Handling** (`server/index.js`)
|
|
61
|
-
**Problem**: The `handleBootstrapMessage` was using `getActivePeers()` which could include hub peers when forwarding peer-discovered messages.
|
|
62
|
-
|
|
63
|
-
**Impact**: Hub peers would receive peer-discovered messages meant for client peers, causing unnecessary network traffic and potential confusion.
|
|
64
|
-
|
|
65
|
-
**Fix**: Modified to:
|
|
66
|
-
- Use `networkPeers.get(discoveredNetwork)` directly
|
|
67
|
-
- Filter out hub peers explicitly
|
|
68
|
-
- Only forward to client peers
|
|
69
|
-
- Add proper connection state checking
|
|
70
|
-
|
|
71
|
-
## Testing
|
|
72
|
-
|
|
73
|
-
Created `test/peer-discovery-test.js` to verify the fixes:
|
|
74
|
-
- Tests multiple peers connecting to a hub
|
|
75
|
-
- Verifies peer discovery announcements
|
|
76
|
-
- Confirms connection establishment
|
|
77
|
-
- Uses staggered connection timing to test various scenarios
|
|
78
|
-
- Provides detailed color-coded output for debugging
|
|
79
|
-
|
|
80
|
-
### Running the Test
|
|
81
|
-
|
|
82
|
-
```bash
|
|
83
|
-
node test/peer-discovery-test.js
|
|
84
|
-
```
|
|
85
|
-
|
|
86
|
-
## Expected Behavior After Fixes
|
|
87
|
-
|
|
88
|
-
1. **Initial Discovery**: When a peer announces itself to the hub, all other peers in the same network should receive a `peer-discovered` message within milliseconds.
|
|
89
|
-
|
|
90
|
-
2. **Connection Initiation**: The peer with the lexicographically larger peer ID should initiate the WebRTC connection automatically.
|
|
91
|
-
|
|
92
|
-
3. **Retry Mechanism**: If a connection fails or gets stuck, the system will:
|
|
93
|
-
- Clean up stale connection attempts after 5 seconds
|
|
94
|
-
- Allow re-announcements to trigger new connection attempts
|
|
95
|
-
- Retry up to 3 times (6 times for isolated peers)
|
|
96
|
-
- Use shorter retry delays (200ms for isolated peers, 500ms normally)
|
|
97
|
-
|
|
98
|
-
4. **Multi-Hub Networks**: In networks with multiple hubs:
|
|
99
|
-
- Peer announcements propagate to all hubs
|
|
100
|
-
- Peers connected to different hubs can discover each other
|
|
101
|
-
- Hub-to-hub relay ensures full network visibility
|
|
102
|
-
|
|
103
|
-
5. **Connection State Management**: The system now properly handles:
|
|
104
|
-
- Stuck connections (>10 seconds in "connecting" state)
|
|
105
|
-
- Failed connection attempts
|
|
106
|
-
- Duplicate connection prevention
|
|
107
|
-
- Re-announcements of existing peers
|
|
108
|
-
|
|
109
|
-
## Files Modified
|
|
110
|
-
|
|
111
|
-
1. `src/SignalingHandler.js` - Improved peer announcement handling
|
|
112
|
-
2. `src/PeerDiscovery.js` - Better connection attempt tracking and cleanup
|
|
113
|
-
3. `src/ConnectionManager.js` - Enhanced retry logic and stuck connection handling
|
|
114
|
-
4. `server/index.js` - Fixed hub peer forwarding and relay logic
|
|
115
|
-
|
|
116
|
-
## Migration Notes
|
|
117
|
-
|
|
118
|
-
These fixes are **backward compatible** and don't require any API changes. Existing applications using PeerPigeon will automatically benefit from the improvements.
|
|
119
|
-
|
|
120
|
-
## Debugging
|
|
121
|
-
|
|
122
|
-
To enable debug logging for troubleshooting connection issues:
|
|
123
|
-
|
|
124
|
-
```javascript
|
|
125
|
-
import { DebugLogger } from 'peerpigeon';
|
|
126
|
-
|
|
127
|
-
// Enable specific modules
|
|
128
|
-
DebugLogger.enable('PeerDiscovery');
|
|
129
|
-
DebugLogger.enable('ConnectionManager');
|
|
130
|
-
DebugLogger.enable('SignalingHandler');
|
|
131
|
-
|
|
132
|
-
// Or enable all
|
|
133
|
-
DebugLogger.enableAll();
|
|
134
|
-
```
|
|
135
|
-
|
|
136
|
-
## Related Documentation
|
|
137
|
-
|
|
138
|
-
- [HUB_SYSTEM.md](./HUB_SYSTEM.md) - Hub architecture and multi-hub networking
|
|
139
|
-
- [NETWORK_NAMESPACES.md](./NETWORK_NAMESPACES.md) - Network isolation
|
|
140
|
-
- [LOCAL_TESTING.md](./LOCAL_TESTING.md) - Testing peer connections locally
|