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/SignalingHandler.js
CHANGED
|
@@ -5,325 +5,325 @@ import { PeerConnection } from './PeerConnection.js';
|
|
|
5
5
|
* Handles WebRTC signaling messages (offers, answers, ICE candidates)
|
|
6
6
|
*/
|
|
7
7
|
export class SignalingHandler extends EventEmitter {
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
8
|
+
constructor(mesh, connectionManager) {
|
|
9
|
+
super();
|
|
10
|
+
this.mesh = mesh;
|
|
11
|
+
this.connectionManager = connectionManager;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
async handleSignalingMessage(message) {
|
|
15
|
+
const { type, data, fromPeerId, targetPeerId } = message;
|
|
16
|
+
|
|
17
|
+
if (fromPeerId === this.mesh.peerId) return;
|
|
18
|
+
if (targetPeerId && targetPeerId !== this.mesh.peerId) return;
|
|
19
|
+
|
|
20
|
+
// Ignore cleanup messages - they are handled by the server, not as peer signaling
|
|
21
|
+
if (type === 'cleanup' || type === 'cleanup-all') {
|
|
22
|
+
console.log('Ignoring cleanup message:', { type, fromPeerId });
|
|
23
|
+
return;
|
|
12
24
|
}
|
|
13
25
|
|
|
14
|
-
|
|
15
|
-
|
|
26
|
+
// Ignore ping messages - they are for keepalive, not peer signaling
|
|
27
|
+
if (type === 'ping' || type === 'pong') {
|
|
28
|
+
return;
|
|
29
|
+
}
|
|
16
30
|
|
|
17
|
-
|
|
18
|
-
if (targetPeerId && targetPeerId !== this.mesh.peerId) return;
|
|
31
|
+
console.log('Processing signaling message:', { type, fromPeerId, targetPeerId });
|
|
19
32
|
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
return;
|
|
33
|
+
switch (type) {
|
|
34
|
+
case 'announce':
|
|
35
|
+
this.handlePeerAnnouncement(fromPeerId);
|
|
36
|
+
break;
|
|
37
|
+
case 'peer-discovered':
|
|
38
|
+
// Handle peer discovery messages from the signaling server
|
|
39
|
+
if (data && data.peerId) {
|
|
40
|
+
this.handlePeerAnnouncement(data.peerId);
|
|
29
41
|
}
|
|
42
|
+
break;
|
|
43
|
+
case 'goodbye':
|
|
44
|
+
this.handlePeerGoodbye(fromPeerId);
|
|
45
|
+
break;
|
|
46
|
+
case 'offer':
|
|
47
|
+
await this.handleOffer(data, fromPeerId);
|
|
48
|
+
break;
|
|
49
|
+
case 'answer':
|
|
50
|
+
await this.handleAnswer(data, fromPeerId);
|
|
51
|
+
break;
|
|
52
|
+
case 'ice-candidate':
|
|
53
|
+
await this.connectionManager.handleIceCandidate(data, fromPeerId);
|
|
54
|
+
break;
|
|
55
|
+
case 'connection-rejected':
|
|
56
|
+
this.handleConnectionRejected(data, fromPeerId);
|
|
57
|
+
break;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
30
60
|
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
break;
|
|
37
|
-
case 'peer-discovered':
|
|
38
|
-
// Handle peer discovery messages from the signaling server
|
|
39
|
-
if (data && data.peerId) {
|
|
40
|
-
this.handlePeerAnnouncement(data.peerId);
|
|
41
|
-
}
|
|
42
|
-
break;
|
|
43
|
-
case 'goodbye':
|
|
44
|
-
this.handlePeerGoodbye(fromPeerId);
|
|
45
|
-
break;
|
|
46
|
-
case 'offer':
|
|
47
|
-
await this.handleOffer(data, fromPeerId);
|
|
48
|
-
break;
|
|
49
|
-
case 'answer':
|
|
50
|
-
await this.handleAnswer(data, fromPeerId);
|
|
51
|
-
break;
|
|
52
|
-
case 'ice-candidate':
|
|
53
|
-
await this.connectionManager.handleIceCandidate(data, fromPeerId);
|
|
54
|
-
break;
|
|
55
|
-
case 'connection-rejected':
|
|
56
|
-
this.handleConnectionRejected(data, fromPeerId);
|
|
57
|
-
break;
|
|
58
|
-
}
|
|
61
|
+
handlePeerAnnouncement(fromPeerId) {
|
|
62
|
+
// Prevent duplicate announcements - only announce if we haven't seen this peer before
|
|
63
|
+
if (this.mesh.peerDiscovery.hasPeer(fromPeerId)) {
|
|
64
|
+
console.log(`Peer ${fromPeerId.substring(0, 8)}... already known, skipping announcement`);
|
|
65
|
+
return;
|
|
59
66
|
}
|
|
60
67
|
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
68
|
+
this.mesh.emit('statusChanged', { type: 'info', message: `Peer ${fromPeerId.substring(0, 8)}... announced` });
|
|
69
|
+
console.log(`Adding discovered peer: ${fromPeerId.substring(0, 8)}... to PeerDiscovery`);
|
|
70
|
+
console.log(`Current peer count: ${this.connectionManager.getConnectedPeerCount()}/${this.mesh.maxPeers}`);
|
|
71
|
+
console.log(`All discovered peers: ${Array.from(this.mesh.peerDiscovery.discoveredPeers.keys()).map(p => p.substring(0, 8)).join(', ')}`);
|
|
72
|
+
this.mesh.peerDiscovery.addDiscoveredPeer(fromPeerId);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
handlePeerGoodbye(fromPeerId) {
|
|
76
|
+
this.mesh.emit('statusChanged', { type: 'info', message: `Peer ${fromPeerId.substring(0, 8)}... left the network` });
|
|
77
|
+
this.mesh.peerDiscovery.removeDiscoveredPeer(fromPeerId);
|
|
78
|
+
this.connectionManager.disconnectPeer(fromPeerId, 'left network');
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
async handleOffer(offer, fromPeerId) {
|
|
82
|
+
console.log('Handling offer from', fromPeerId);
|
|
83
|
+
|
|
84
|
+
// If we already have a connection or are connecting, handle gracefully
|
|
85
|
+
if (this.connectionManager.hasPeer(fromPeerId)) {
|
|
86
|
+
const existingPeer = this.connectionManager.getPeer(fromPeerId);
|
|
87
|
+
const existingStatus = existingPeer.getStatus();
|
|
88
|
+
|
|
89
|
+
// If connection is already established and working, don't interfere
|
|
90
|
+
if (existingStatus === 'connected') {
|
|
91
|
+
console.log(`Connection already established with ${fromPeerId}, ignoring duplicate offer`);
|
|
92
|
+
return;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// ABSOLUTE RULE: Lexicographically larger peer ID always initiates
|
|
96
|
+
// If we're receiving an offer but we should be the initiator, there's a race condition
|
|
97
|
+
const weShouldInitiate = this.mesh.peerId > fromPeerId;
|
|
98
|
+
|
|
99
|
+
if (weShouldInitiate && existingPeer.isInitiator) {
|
|
100
|
+
console.log(`Race condition detected! We should initiate (${this.mesh.peerId.substring(0, 8)}... > ${fromPeerId.substring(0, 8)}...) but received offer. Ignoring.`);
|
|
101
|
+
return;
|
|
102
|
+
} else if (!weShouldInitiate && existingPeer.isInitiator) {
|
|
103
|
+
console.log(`We're incorrectly initiating to ${fromPeerId.substring(0, 8)}..., backing down for their offer`);
|
|
104
|
+
// Cleanup our outgoing attempt and accept the incoming offer
|
|
105
|
+
if (existingStatus === 'connecting' || existingStatus === 'new') {
|
|
106
|
+
console.log(`Cleaning up our outgoing connection attempt to ${fromPeerId.substring(0, 8)}...`);
|
|
107
|
+
this.connectionManager.cleanupRaceCondition(fromPeerId);
|
|
108
|
+
} else {
|
|
109
|
+
console.log('Connection in progress, not cleaning up');
|
|
110
|
+
return;
|
|
66
111
|
}
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
console.log(`All discovered peers: ${Array.from(this.mesh.peerDiscovery.discoveredPeers.keys()).map(p => p.substring(0, 8)).join(', ')}`);
|
|
72
|
-
this.mesh.peerDiscovery.addDiscoveredPeer(fromPeerId);
|
|
112
|
+
} else {
|
|
113
|
+
console.log('Already processing incoming connection from', fromPeerId);
|
|
114
|
+
return;
|
|
115
|
+
}
|
|
73
116
|
}
|
|
74
117
|
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
118
|
+
// Check if we're already attempting to connect to this peer
|
|
119
|
+
if (this.connectionManager.connectionAttempts.has(fromPeerId)) {
|
|
120
|
+
console.log('Already attempting connection to', fromPeerId, 'accepting incoming offer');
|
|
121
|
+
this.connectionManager.connectionAttempts.delete(fromPeerId);
|
|
79
122
|
}
|
|
80
123
|
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
// ABSOLUTE RULE: Lexicographically larger peer ID always initiates
|
|
96
|
-
// If we're receiving an offer but we should be the initiator, there's a race condition
|
|
97
|
-
const weShouldInitiate = this.mesh.peerId > fromPeerId;
|
|
98
|
-
|
|
99
|
-
if (weShouldInitiate && existingPeer.isInitiator) {
|
|
100
|
-
console.log(`Race condition detected! We should initiate (${this.mesh.peerId.substring(0, 8)}... > ${fromPeerId.substring(0, 8)}...) but received offer. Ignoring.`);
|
|
101
|
-
return;
|
|
102
|
-
} else if (!weShouldInitiate && existingPeer.isInitiator) {
|
|
103
|
-
console.log(`We're incorrectly initiating to ${fromPeerId.substring(0, 8)}..., backing down for their offer`);
|
|
104
|
-
// Cleanup our outgoing attempt and accept the incoming offer
|
|
105
|
-
if (existingStatus === 'connecting' || existingStatus === 'new') {
|
|
106
|
-
console.log(`Cleaning up our outgoing connection attempt to ${fromPeerId.substring(0, 8)}...`);
|
|
107
|
-
this.connectionManager.cleanupRaceCondition(fromPeerId);
|
|
108
|
-
} else {
|
|
109
|
-
console.log('Connection in progress, not cleaning up');
|
|
110
|
-
return;
|
|
111
|
-
}
|
|
112
|
-
} else {
|
|
113
|
-
console.log('Already processing incoming connection from', fromPeerId);
|
|
114
|
-
return;
|
|
115
|
-
}
|
|
116
|
-
}
|
|
117
|
-
|
|
118
|
-
// Check if we're already attempting to connect to this peer
|
|
119
|
-
if (this.connectionManager.connectionAttempts.has(fromPeerId)) {
|
|
120
|
-
console.log('Already attempting connection to', fromPeerId, 'accepting incoming offer');
|
|
121
|
-
this.connectionManager.connectionAttempts.delete(fromPeerId);
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
// CRITICAL: Check capacity again right before accepting to prevent race conditions
|
|
125
|
-
const currentCount = this.connectionManager.getConnectedPeerCount();
|
|
126
|
-
const totalPeerCount = this.connectionManager.peers.size;
|
|
127
|
-
let canAccept = this.mesh.canAcceptMorePeers();
|
|
128
|
-
let evictPeerId = null;
|
|
129
|
-
|
|
130
|
-
console.log(`Capacity check for ${fromPeerId.substring(0, 8)}...: ${currentCount}/${this.mesh.maxPeers} connected, ${totalPeerCount} total peers, canAccept: ${canAccept}`);
|
|
131
|
-
|
|
132
|
-
if (!canAccept) {
|
|
133
|
-
console.log(`At capacity (${currentCount}/${this.mesh.maxPeers} connected, ${totalPeerCount} total) - checking eviction and cleanup options`);
|
|
134
|
-
|
|
135
|
-
// First try: Check if we should evict a peer for this new connection
|
|
136
|
-
if (this.mesh.evictionStrategy) {
|
|
137
|
-
evictPeerId = this.mesh.evictionManager.shouldEvictForPeer(fromPeerId);
|
|
138
|
-
if (evictPeerId) {
|
|
139
|
-
console.log(`Will evict ${evictPeerId.substring(0, 8)}... for incoming connection from ${fromPeerId.substring(0, 8)}...`);
|
|
140
|
-
canAccept = true; // We can accept because we'll evict
|
|
141
|
-
} else {
|
|
142
|
-
console.log(`No suitable peer found for eviction for ${fromPeerId.substring(0, 8)}...`);
|
|
143
|
-
}
|
|
144
|
-
} else {
|
|
145
|
-
console.log(`Eviction strategy disabled - cannot evict for ${fromPeerId.substring(0, 8)}...`);
|
|
146
|
-
}
|
|
147
|
-
|
|
148
|
-
// Second try: Clean up stale peers to make room
|
|
149
|
-
if (!canAccept) {
|
|
150
|
-
const stalePeerCount = this.connectionManager.getStalePeerCount();
|
|
151
|
-
if (stalePeerCount > 0) {
|
|
152
|
-
console.log(`No eviction candidate, attempting to clean up ${stalePeerCount} stale peer(s) to make room for ${fromPeerId.substring(0, 8)}...`);
|
|
153
|
-
this.connectionManager.cleanupStalePeers();
|
|
154
|
-
canAccept = this.mesh.canAcceptMorePeers();
|
|
155
|
-
if (canAccept) {
|
|
156
|
-
console.log(`Successfully made room after cleanup for ${fromPeerId.substring(0, 8)}...`);
|
|
157
|
-
}
|
|
158
|
-
}
|
|
159
|
-
}
|
|
160
|
-
|
|
161
|
-
// Final rejection if no options worked
|
|
162
|
-
if (!canAccept) {
|
|
163
|
-
const reason = `max_peers_reached (${currentCount}/${this.mesh.maxPeers} connected, ${this.connectionManager.peers.size} total, no eviction candidate)`;
|
|
164
|
-
console.log(`Rejecting offer from ${fromPeerId.substring(0, 8)}...: ${reason}`);
|
|
165
|
-
|
|
166
|
-
try {
|
|
167
|
-
await this.mesh.signalingClient.sendSignalingMessage({
|
|
168
|
-
type: 'connection-rejected',
|
|
169
|
-
data: {
|
|
170
|
-
reason: 'max_peers_reached',
|
|
171
|
-
details: reason,
|
|
172
|
-
currentCount: currentCount,
|
|
173
|
-
maxPeers: this.mesh.maxPeers
|
|
174
|
-
},
|
|
175
|
-
targetPeerId: fromPeerId
|
|
176
|
-
});
|
|
177
|
-
console.log(`Sent connection rejection to ${fromPeerId.substring(0, 8)}...`);
|
|
178
|
-
} catch (error) {
|
|
179
|
-
console.error('Failed to send connection rejection:', error);
|
|
180
|
-
}
|
|
181
|
-
return;
|
|
182
|
-
}
|
|
183
|
-
}
|
|
184
|
-
|
|
185
|
-
// Perform eviction if we determined one was needed
|
|
124
|
+
// CRITICAL: Check capacity again right before accepting to prevent race conditions
|
|
125
|
+
const currentCount = this.connectionManager.getConnectedPeerCount();
|
|
126
|
+
const totalPeerCount = this.connectionManager.peers.size;
|
|
127
|
+
let canAccept = this.mesh.canAcceptMorePeers();
|
|
128
|
+
let evictPeerId = null;
|
|
129
|
+
|
|
130
|
+
console.log(`Capacity check for ${fromPeerId.substring(0, 8)}...: ${currentCount}/${this.mesh.maxPeers} connected, ${totalPeerCount} total peers, canAccept: ${canAccept}`);
|
|
131
|
+
|
|
132
|
+
if (!canAccept) {
|
|
133
|
+
console.log(`At capacity (${currentCount}/${this.mesh.maxPeers} connected, ${totalPeerCount} total) - checking eviction and cleanup options`);
|
|
134
|
+
|
|
135
|
+
// First try: Check if we should evict a peer for this new connection
|
|
136
|
+
if (this.mesh.evictionStrategy) {
|
|
137
|
+
evictPeerId = this.mesh.evictionManager.shouldEvictForPeer(fromPeerId);
|
|
186
138
|
if (evictPeerId) {
|
|
187
|
-
|
|
188
|
-
|
|
139
|
+
console.log(`Will evict ${evictPeerId.substring(0, 8)}... for incoming connection from ${fromPeerId.substring(0, 8)}...`);
|
|
140
|
+
canAccept = true; // We can accept because we'll evict
|
|
141
|
+
} else {
|
|
142
|
+
console.log(`No suitable peer found for eviction for ${fromPeerId.substring(0, 8)}...`);
|
|
189
143
|
}
|
|
144
|
+
} else {
|
|
145
|
+
console.log(`Eviction strategy disabled - cannot evict for ${fromPeerId.substring(0, 8)}...`);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
// Second try: Clean up stale peers to make room
|
|
149
|
+
if (!canAccept) {
|
|
150
|
+
const stalePeerCount = this.connectionManager.getStalePeerCount();
|
|
151
|
+
if (stalePeerCount > 0) {
|
|
152
|
+
console.log(`No eviction candidate, attempting to clean up ${stalePeerCount} stale peer(s) to make room for ${fromPeerId.substring(0, 8)}...`);
|
|
153
|
+
this.connectionManager.cleanupStalePeers();
|
|
154
|
+
canAccept = this.mesh.canAcceptMorePeers();
|
|
155
|
+
if (canAccept) {
|
|
156
|
+
console.log(`Successfully made room after cleanup for ${fromPeerId.substring(0, 8)}...`);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
// Final rejection if no options worked
|
|
162
|
+
if (!canAccept) {
|
|
163
|
+
const reason = `max_peers_reached (${currentCount}/${this.mesh.maxPeers} connected, ${this.connectionManager.peers.size} total, no eviction candidate)`;
|
|
164
|
+
console.log(`Rejecting offer from ${fromPeerId.substring(0, 8)}...: ${reason}`);
|
|
165
|
+
|
|
190
166
|
try {
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
}
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
const peerConnection = new PeerConnection(fromPeerId, false, options);
|
|
203
|
-
|
|
204
|
-
// Set up event handlers BEFORE creating connection to catch all events
|
|
205
|
-
this.connectionManager.setupPeerConnectionHandlers(peerConnection);
|
|
206
|
-
this.connectionManager.peers.set(fromPeerId, peerConnection);
|
|
207
|
-
|
|
208
|
-
await peerConnection.createConnection();
|
|
209
|
-
|
|
210
|
-
console.log(`Processing offer from ${fromPeerId.substring(0, 8)}...`, {
|
|
211
|
-
type: offer.type,
|
|
212
|
-
sdpLength: offer.sdp?.length || 0,
|
|
213
|
-
hasAudio: offer.sdp?.includes('m=audio') || false,
|
|
214
|
-
hasVideo: offer.sdp?.includes('m=video') || false
|
|
215
|
-
});
|
|
216
|
-
|
|
217
|
-
// Handle the offer using PeerConnection's method
|
|
218
|
-
const answer = await peerConnection.handleOffer(offer);
|
|
219
|
-
|
|
220
|
-
console.log(`Answer created for ${fromPeerId.substring(0, 8)}...`, {
|
|
221
|
-
type: answer.type,
|
|
222
|
-
sdpLength: answer.sdp?.length || 0,
|
|
223
|
-
hasAudio: answer.sdp?.includes('m=audio') || false,
|
|
224
|
-
hasVideo: answer.sdp?.includes('m=video') || false
|
|
225
|
-
});
|
|
226
|
-
|
|
227
|
-
console.log('Sending answer to', fromPeerId);
|
|
228
|
-
|
|
229
|
-
// Send answer via signaling
|
|
230
|
-
await this.mesh.signalingClient.sendSignalingMessage({
|
|
231
|
-
type: 'answer',
|
|
232
|
-
data: answer,
|
|
233
|
-
targetPeerId: fromPeerId
|
|
234
|
-
});
|
|
235
|
-
|
|
236
|
-
this.mesh.emit('statusChanged', { type: 'info', message: `Answer sent to ${fromPeerId.substring(0, 8)}...` });
|
|
237
|
-
// Clear connection attempt since we're now processing the connection
|
|
238
|
-
this.mesh.peerDiscovery.clearConnectionAttempt(fromPeerId);
|
|
167
|
+
await this.mesh.signalingClient.sendSignalingMessage({
|
|
168
|
+
type: 'connection-rejected',
|
|
169
|
+
data: {
|
|
170
|
+
reason: 'max_peers_reached',
|
|
171
|
+
details: reason,
|
|
172
|
+
currentCount,
|
|
173
|
+
maxPeers: this.mesh.maxPeers
|
|
174
|
+
},
|
|
175
|
+
targetPeerId: fromPeerId
|
|
176
|
+
});
|
|
177
|
+
console.log(`Sent connection rejection to ${fromPeerId.substring(0, 8)}...`);
|
|
239
178
|
} catch (error) {
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
// If it's a state error, handle gracefully
|
|
243
|
-
if (error.message.includes('state:')) {
|
|
244
|
-
console.log(`Offer ignored for ${fromPeerId.substring(0, 8)}... - connection state issue (likely race condition)`);
|
|
245
|
-
this.mesh.emit('statusChanged', { type: 'info', message: `Offer skipped for ${fromPeerId.substring(0, 8)}... (connection state conflict)` });
|
|
246
|
-
} else {
|
|
247
|
-
this.mesh.emit('statusChanged', { type: 'error', message: `Failed to handle offer from ${fromPeerId.substring(0, 8)}...: ${error.message}` });
|
|
248
|
-
this.connectionManager.cleanupFailedConnection(fromPeerId);
|
|
249
|
-
}
|
|
179
|
+
console.error('Failed to send connection rejection:', error);
|
|
250
180
|
}
|
|
181
|
+
return;
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
// Perform eviction if we determined one was needed
|
|
186
|
+
if (evictPeerId) {
|
|
187
|
+
this.mesh.emit('statusChanged', { type: 'info', message: `Evicting ${evictPeerId.substring(0, 8)}... for incoming connection from ${fromPeerId.substring(0, 8)}...` });
|
|
188
|
+
await this.mesh.evictionManager.evictPeer(evictPeerId, 'incoming closer peer');
|
|
251
189
|
}
|
|
190
|
+
try {
|
|
191
|
+
// Get current media stream if available
|
|
192
|
+
const localStream = this.mesh.mediaManager.localStream;
|
|
193
|
+
const hasMedia = localStream !== null;
|
|
194
|
+
const options = {
|
|
195
|
+
localStream,
|
|
196
|
+
enableAudio: hasMedia && localStream.getAudioTracks().length > 0,
|
|
197
|
+
enableVideo: hasMedia && localStream.getVideoTracks().length > 0
|
|
198
|
+
};
|
|
252
199
|
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
200
|
+
console.log(`Creating answer connection for ${fromPeerId.substring(0, 8)}... (with media: ${hasMedia})`);
|
|
201
|
+
|
|
202
|
+
const peerConnection = new PeerConnection(fromPeerId, false, options);
|
|
203
|
+
|
|
204
|
+
// Set up event handlers BEFORE creating connection to catch all events
|
|
205
|
+
this.connectionManager.setupPeerConnectionHandlers(peerConnection);
|
|
206
|
+
this.connectionManager.peers.set(fromPeerId, peerConnection);
|
|
207
|
+
|
|
208
|
+
await peerConnection.createConnection();
|
|
209
|
+
|
|
210
|
+
console.log(`Processing offer from ${fromPeerId.substring(0, 8)}...`, {
|
|
211
|
+
type: offer.type,
|
|
212
|
+
sdpLength: offer.sdp?.length || 0,
|
|
213
|
+
hasAudio: offer.sdp?.includes('m=audio') || false,
|
|
214
|
+
hasVideo: offer.sdp?.includes('m=video') || false
|
|
215
|
+
});
|
|
216
|
+
|
|
217
|
+
// Handle the offer using PeerConnection's method
|
|
218
|
+
const answer = await peerConnection.handleOffer(offer);
|
|
219
|
+
|
|
220
|
+
console.log(`Answer created for ${fromPeerId.substring(0, 8)}...`, {
|
|
221
|
+
type: answer.type,
|
|
222
|
+
sdpLength: answer.sdp?.length || 0,
|
|
223
|
+
hasAudio: answer.sdp?.includes('m=audio') || false,
|
|
224
|
+
hasVideo: answer.sdp?.includes('m=video') || false
|
|
225
|
+
});
|
|
226
|
+
|
|
227
|
+
console.log('Sending answer to', fromPeerId);
|
|
228
|
+
|
|
229
|
+
// Send answer via signaling
|
|
230
|
+
await this.mesh.signalingClient.sendSignalingMessage({
|
|
231
|
+
type: 'answer',
|
|
232
|
+
data: answer,
|
|
233
|
+
targetPeerId: fromPeerId
|
|
234
|
+
});
|
|
235
|
+
|
|
236
|
+
this.mesh.emit('statusChanged', { type: 'info', message: `Answer sent to ${fromPeerId.substring(0, 8)}...` });
|
|
237
|
+
// Clear connection attempt since we're now processing the connection
|
|
238
|
+
this.mesh.peerDiscovery.clearConnectionAttempt(fromPeerId);
|
|
239
|
+
} catch (error) {
|
|
240
|
+
console.error('Failed to handle offer from', fromPeerId, ':', error);
|
|
241
|
+
|
|
242
|
+
// If it's a state error, handle gracefully
|
|
243
|
+
if (error.message.includes('state:')) {
|
|
244
|
+
console.log(`Offer ignored for ${fromPeerId.substring(0, 8)}... - connection state issue (likely race condition)`);
|
|
245
|
+
this.mesh.emit('statusChanged', { type: 'info', message: `Offer skipped for ${fromPeerId.substring(0, 8)}... (connection state conflict)` });
|
|
246
|
+
} else {
|
|
247
|
+
this.mesh.emit('statusChanged', { type: 'error', message: `Failed to handle offer from ${fromPeerId.substring(0, 8)}...: ${error.message}` });
|
|
248
|
+
this.connectionManager.cleanupFailedConnection(fromPeerId);
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
async handleAnswer(answer, fromPeerId) {
|
|
254
|
+
console.log('Handling answer from', fromPeerId);
|
|
255
|
+
|
|
256
|
+
const peerConnection = this.connectionManager.getPeer(fromPeerId);
|
|
257
|
+
if (peerConnection) {
|
|
258
|
+
try {
|
|
259
|
+
await peerConnection.handleAnswer(answer);
|
|
260
|
+
this.mesh.emit('statusChanged', { type: 'info', message: `Answer processed from ${fromPeerId.substring(0, 8)}...` });
|
|
261
|
+
} catch (error) {
|
|
262
|
+
console.error('Failed to handle answer:', error);
|
|
263
|
+
|
|
264
|
+
// If it's a state error (connection already stable), don't treat as failure
|
|
265
|
+
if (error.message.includes('state:') || error.message.includes('stable')) {
|
|
266
|
+
console.log(`Answer ignored for ${fromPeerId.substring(0, 8)}... - connection state issue (likely race condition resolved)`);
|
|
267
|
+
this.mesh.emit('statusChanged', { type: 'info', message: `Answer skipped for ${fromPeerId.substring(0, 8)}... (connection already stable)` });
|
|
272
268
|
} else {
|
|
273
|
-
|
|
269
|
+
this.mesh.emit('statusChanged', { type: 'error', message: `Failed to handle answer from ${fromPeerId.substring(0, 8)}...: ${error.message}` });
|
|
274
270
|
}
|
|
271
|
+
}
|
|
272
|
+
} else {
|
|
273
|
+
console.log('No peer connection found for answer from', fromPeerId);
|
|
275
274
|
}
|
|
275
|
+
}
|
|
276
276
|
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
!this.connectionManager.hasPeer(peer.peerId) &&
|
|
277
|
+
handleConnectionRejected(data, fromPeerId) {
|
|
278
|
+
console.log(`Connection rejected by ${fromPeerId.substring(0, 8)}...: ${data.reason} (${data.details})`);
|
|
279
|
+
this.mesh.emit('statusChanged', {
|
|
280
|
+
type: 'info',
|
|
281
|
+
message: `Connection rejected by ${fromPeerId.substring(0, 8)}... (${data.reason})`
|
|
282
|
+
});
|
|
283
|
+
|
|
284
|
+
// Clean up any pending connection attempt
|
|
285
|
+
this.connectionManager.connectionAttempts.delete(fromPeerId);
|
|
286
|
+
|
|
287
|
+
// Remove the peer connection if it exists and is not connected
|
|
288
|
+
const peerConnection = this.connectionManager.getPeer(fromPeerId);
|
|
289
|
+
if (peerConnection && peerConnection.getStatus() !== 'connected') {
|
|
290
|
+
peerConnection.close();
|
|
291
|
+
this.connectionManager.peers.delete(fromPeerId);
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
// Clear any discovery connection attempt tracking
|
|
295
|
+
this.mesh.peerDiscovery.clearConnectionAttempt(fromPeerId);
|
|
296
|
+
|
|
297
|
+
// If we have no connections, immediately try other peers more aggressively
|
|
298
|
+
const connectedCount = this.connectionManager.getConnectedPeerCount();
|
|
299
|
+
if (connectedCount === 0) {
|
|
300
|
+
console.log(`Connection rejected and peer is isolated (${connectedCount} connections) - trying alternative peers immediately`);
|
|
301
|
+
|
|
302
|
+
// Immediately try to connect to other discovered peers
|
|
303
|
+
const discoveredPeers = Array.from(this.mesh.peerDiscovery.getDiscoveredPeers());
|
|
304
|
+
const availablePeers = discoveredPeers.filter(peer =>
|
|
305
|
+
peer.peerId !== fromPeerId &&
|
|
306
|
+
!this.connectionManager.hasPeer(peer.peerId) &&
|
|
307
307
|
!this.mesh.peerDiscovery.isAttemptingConnection(peer.peerId)
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
}
|
|
308
|
+
);
|
|
309
|
+
|
|
310
|
+
if (availablePeers.length > 0) {
|
|
311
|
+
// Sort by XOR distance and try the closest available peer
|
|
312
|
+
const sortedByDistance = availablePeers.sort((a, b) => {
|
|
313
|
+
const distA = this.mesh.peerDiscovery.calculateXorDistance(this.mesh.peerId, a.peerId);
|
|
314
|
+
const distB = this.mesh.peerDiscovery.calculateXorDistance(this.mesh.peerId, b.peerId);
|
|
315
|
+
return distA < distB ? -1 : 1;
|
|
316
|
+
});
|
|
317
|
+
|
|
318
|
+
const nextPeer = sortedByDistance[0];
|
|
319
|
+
console.log(`Immediately attempting connection to next closest peer: ${nextPeer.peerId.substring(0, 8)}...`);
|
|
320
|
+
this.connectionManager.connectToPeer(nextPeer.peerId);
|
|
321
|
+
}
|
|
322
|
+
} else {
|
|
323
|
+
// Regular mesh optimization for non-isolated peers
|
|
324
|
+
setTimeout(() => {
|
|
325
|
+
this.mesh.peerDiscovery.optimizeMeshConnections(this.connectionManager.peers);
|
|
326
|
+
}, 1000);
|
|
328
327
|
}
|
|
328
|
+
}
|
|
329
329
|
}
|