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