peerpigeon 0.0.4 → 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.
@@ -5,321 +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
- constructor(mesh, connectionManager) {
9
- super();
10
- this.mesh = mesh;
11
- this.connectionManager = connectionManager;
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
- async handleSignalingMessage(message) {
15
- const { type, data, fromPeerId, targetPeerId } = message;
26
+ // Ignore ping messages - they are for keepalive, not peer signaling
27
+ if (type === 'ping' || type === 'pong') {
28
+ return;
29
+ }
16
30
 
17
- if (fromPeerId === this.mesh.peerId) return;
18
- if (targetPeerId && targetPeerId !== this.mesh.peerId) return;
31
+ console.log('Processing signaling message:', { type, fromPeerId, targetPeerId });
19
32
 
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;
24
- }
25
-
26
- // Ignore ping messages - they are for keepalive, not peer signaling
27
- if (type === 'ping' || type === 'pong') {
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
- console.log('Processing signaling message:', { type, fromPeerId, targetPeerId });
32
-
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);
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
- 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;
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
- 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);
112
+ } else {
113
+ console.log('Already processing incoming connection from', fromPeerId);
114
+ return;
115
+ }
73
116
  }
74
117
 
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');
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
- 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;
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
- 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');
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
- // Get current media stream if available
192
- const localStream = this.mesh.mediaManager.localStream;
193
- const hasMedia = localStream !== null;
194
- const options = { localStream };
195
-
196
- console.log(`Creating answer connection for ${fromPeerId.substring(0, 8)}... (with media: ${hasMedia})`);
197
-
198
- const peerConnection = new PeerConnection(fromPeerId, false, options);
199
-
200
- // Set up event handlers BEFORE creating connection to catch all events
201
- this.connectionManager.setupPeerConnectionHandlers(peerConnection);
202
- this.connectionManager.peers.set(fromPeerId, peerConnection);
203
-
204
- await peerConnection.createConnection();
205
-
206
- console.log(`Processing offer from ${fromPeerId.substring(0, 8)}...`, {
207
- type: offer.type,
208
- sdpLength: offer.sdp?.length || 0,
209
- hasAudio: offer.sdp?.includes('m=audio') || false,
210
- hasVideo: offer.sdp?.includes('m=video') || false
211
- });
212
-
213
- // Handle the offer using PeerConnection's method
214
- const answer = await peerConnection.handleOffer(offer);
215
-
216
- console.log(`Answer created for ${fromPeerId.substring(0, 8)}...`, {
217
- type: answer.type,
218
- sdpLength: answer.sdp?.length || 0,
219
- hasAudio: answer.sdp?.includes('m=audio') || false,
220
- hasVideo: answer.sdp?.includes('m=video') || false
221
- });
222
-
223
- console.log('Sending answer to', fromPeerId);
224
-
225
- // Send answer via signaling
226
- await this.mesh.signalingClient.sendSignalingMessage({
227
- type: 'answer',
228
- data: answer,
229
- targetPeerId: fromPeerId
230
- });
231
-
232
- this.mesh.emit('statusChanged', { type: 'info', message: `Answer sent to ${fromPeerId.substring(0, 8)}...` });
233
- // Clear connection attempt since we're now processing the connection
234
- 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)}...`);
235
178
  } catch (error) {
236
- console.error('Failed to handle offer from', fromPeerId, ':', error);
237
-
238
- // If it's a state error, handle gracefully
239
- if (error.message.includes('state:')) {
240
- console.log(`Offer ignored for ${fromPeerId.substring(0, 8)}... - connection state issue (likely race condition)`);
241
- this.mesh.emit('statusChanged', { type: 'info', message: `Offer skipped for ${fromPeerId.substring(0, 8)}... (connection state conflict)` });
242
- } else {
243
- this.mesh.emit('statusChanged', { type: 'error', message: `Failed to handle offer from ${fromPeerId.substring(0, 8)}...: ${error.message}` });
244
- this.connectionManager.cleanupFailedConnection(fromPeerId);
245
- }
179
+ console.error('Failed to send connection rejection:', error);
246
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');
247
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
+ };
248
199
 
249
- async handleAnswer(answer, fromPeerId) {
250
- console.log('Handling answer from', fromPeerId);
251
-
252
- const peerConnection = this.connectionManager.getPeer(fromPeerId);
253
- if (peerConnection) {
254
- try {
255
- await peerConnection.handleAnswer(answer);
256
- this.mesh.emit('statusChanged', { type: 'info', message: `Answer processed from ${fromPeerId.substring(0, 8)}...` });
257
- } catch (error) {
258
- console.error('Failed to handle answer:', error);
259
-
260
- // If it's a state error (connection already stable), don't treat as failure
261
- if (error.message.includes('state:') || error.message.includes('stable')) {
262
- console.log(`Answer ignored for ${fromPeerId.substring(0, 8)}... - connection state issue (likely race condition resolved)`);
263
- this.mesh.emit('statusChanged', { type: 'info', message: `Answer skipped for ${fromPeerId.substring(0, 8)}... (connection already stable)` });
264
- } else {
265
- this.mesh.emit('statusChanged', { type: 'error', message: `Failed to handle answer from ${fromPeerId.substring(0, 8)}...: ${error.message}` });
266
- }
267
- }
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)` });
268
268
  } else {
269
- console.log('No peer connection found for answer from', fromPeerId);
269
+ this.mesh.emit('statusChanged', { type: 'error', message: `Failed to handle answer from ${fromPeerId.substring(0, 8)}...: ${error.message}` });
270
270
  }
271
+ }
272
+ } else {
273
+ console.log('No peer connection found for answer from', fromPeerId);
271
274
  }
275
+ }
272
276
 
273
- handleConnectionRejected(data, fromPeerId) {
274
- console.log(`Connection rejected by ${fromPeerId.substring(0, 8)}...: ${data.reason} (${data.details})`);
275
- this.mesh.emit('statusChanged', {
276
- type: 'info',
277
- message: `Connection rejected by ${fromPeerId.substring(0, 8)}... (${data.reason})`
278
- });
279
-
280
- // Clean up any pending connection attempt
281
- this.connectionManager.connectionAttempts.delete(fromPeerId);
282
-
283
- // Remove the peer connection if it exists and is not connected
284
- const peerConnection = this.connectionManager.getPeer(fromPeerId);
285
- if (peerConnection && peerConnection.getStatus() !== 'connected') {
286
- peerConnection.close();
287
- this.connectionManager.peers.delete(fromPeerId);
288
- }
289
-
290
- // Clear any discovery connection attempt tracking
291
- this.mesh.peerDiscovery.clearConnectionAttempt(fromPeerId);
292
-
293
- // If we have no connections, immediately try other peers more aggressively
294
- const connectedCount = this.connectionManager.getConnectedPeerCount();
295
- if (connectedCount === 0) {
296
- console.log(`Connection rejected and peer is isolated (${connectedCount} connections) - trying alternative peers immediately`);
297
-
298
- // Immediately try to connect to other discovered peers
299
- const discoveredPeers = Array.from(this.mesh.peerDiscovery.getDiscoveredPeers());
300
- const availablePeers = discoveredPeers.filter(peer =>
301
- peer.peerId !== fromPeerId &&
302
- !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) &&
303
307
  !this.mesh.peerDiscovery.isAttemptingConnection(peer.peerId)
304
- );
305
-
306
- if (availablePeers.length > 0) {
307
- // Sort by XOR distance and try the closest available peer
308
- const sortedByDistance = availablePeers.sort((a, b) => {
309
- const distA = this.mesh.peerDiscovery.calculateXorDistance(this.mesh.peerId, a.peerId);
310
- const distB = this.mesh.peerDiscovery.calculateXorDistance(this.mesh.peerId, b.peerId);
311
- return distA < distB ? -1 : 1;
312
- });
313
-
314
- const nextPeer = sortedByDistance[0];
315
- console.log(`Immediately attempting connection to next closest peer: ${nextPeer.peerId.substring(0, 8)}...`);
316
- this.connectionManager.connectToPeer(nextPeer.peerId);
317
- }
318
- } else {
319
- // Regular mesh optimization for non-isolated peers
320
- setTimeout(() => {
321
- this.mesh.peerDiscovery.optimizeMeshConnections(this.connectionManager.peers);
322
- }, 1000);
323
- }
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);
324
327
  }
328
+ }
325
329
  }