peerpigeon 1.0.9 → 1.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +10 -2
- package/dist/peerpigeon-browser.js +147 -26
- package/dist/peerpigeon-browser.js.map +2 -2
- package/docs/CLOUD_DEPLOYMENT.md +132 -0
- package/docs/HUB_P2P_MESH.md +358 -0
- package/examples/browser/app.js +52 -4
- package/package.json +6 -1
- package/server/index.js +662 -79
- package/src/ConnectionManager.js +84 -19
- package/src/GossipManager.js +12 -1
- package/src/PeerDiscovery.js +29 -2
- package/src/PeerPigeonMesh.js +69 -8
- package/src/SignalingClient.js +25 -11
package/src/ConnectionManager.js
CHANGED
|
@@ -79,8 +79,15 @@ export class ConnectionManager extends EventEmitter {
|
|
|
79
79
|
// Only become initiator if our peer ID is lexicographically greater than target's
|
|
80
80
|
const shouldBeInitiator = this.mesh.peerId > targetPeerId;
|
|
81
81
|
if (!shouldBeInitiator) {
|
|
82
|
-
|
|
83
|
-
|
|
82
|
+
// Allow override for low connectivity peers below connectivityFloor
|
|
83
|
+
const connectedCount = this.getConnectedPeerCount();
|
|
84
|
+
const floor = this.mesh.connectivityFloor || 0;
|
|
85
|
+
if (connectedCount < floor) {
|
|
86
|
+
this.debug.log(`🔄 INITIATOR OVERRIDE: Forcing initiation to ${targetPeerId.substring(0,8)}... (connected ${connectedCount} < floor ${floor})`);
|
|
87
|
+
} else {
|
|
88
|
+
this.debug.log(`🔄 INITIATOR LOGIC: Not becoming initiator for ${targetPeerId.substring(0, 8)}... (our ID smaller, connected ${connectedCount} >= floor ${floor})`);
|
|
89
|
+
return; // Let the other peer initiate
|
|
90
|
+
}
|
|
84
91
|
}
|
|
85
92
|
|
|
86
93
|
this.debug.log(`🔄 INITIATOR LOGIC: Becoming initiator for ${targetPeerId.substring(0, 8)}... (our ID: ${this.mesh.peerId.substring(0, 8)}... is greater)`);
|
|
@@ -161,11 +168,61 @@ export class ConnectionManager extends EventEmitter {
|
|
|
161
168
|
this.mesh.emit('statusChanged', { type: 'info', message: `Offer sent to ${targetPeerId.substring(0, 8)}...` });
|
|
162
169
|
} catch (error) {
|
|
163
170
|
this.debug.error('Failed to connect to peer:', error);
|
|
164
|
-
|
|
171
|
+
|
|
172
|
+
// Check if this was due to a connection timeout (createOffer/setLocalDescription timeout)
|
|
173
|
+
// These are expected and normal in a partial mesh when peers are at capacity
|
|
174
|
+
const isConnectionTimeout = error.message?.includes('timeout');
|
|
175
|
+
|
|
176
|
+
if (!isConnectionTimeout) {
|
|
177
|
+
// Only emit error for non-timeout failures
|
|
178
|
+
this.mesh.emit('statusChanged', {
|
|
179
|
+
type: 'error',
|
|
180
|
+
message: `Failed to connect to ${targetPeerId.substring(0, 8)}...: ${error.message}`
|
|
181
|
+
});
|
|
182
|
+
}
|
|
183
|
+
// Note: connection timeouts are logged to debug but not emitted as errors
|
|
184
|
+
|
|
165
185
|
this.cleanupFailedConnection(targetPeerId);
|
|
166
186
|
}
|
|
167
187
|
}
|
|
168
188
|
|
|
189
|
+
/**
|
|
190
|
+
* Force connection attempt ignoring standard initiator lexicographic rule (used for connectivity floor).
|
|
191
|
+
*/
|
|
192
|
+
async connectToPeerOverride(targetPeerId) {
|
|
193
|
+
// Skip if already connected
|
|
194
|
+
if (this.peers.has(targetPeerId)) return;
|
|
195
|
+
|
|
196
|
+
const connectedCount = this.getConnectedPeerCount();
|
|
197
|
+
const floor = this.mesh.connectivityFloor || 0;
|
|
198
|
+
if (connectedCount >= floor) return; // Only override if below floor
|
|
199
|
+
|
|
200
|
+
// Don't skip if attempting - override takes precedence when below floor
|
|
201
|
+
this.debug.log(`⚡ OVERRIDE CONNECT: initiating to ${targetPeerId.substring(0,8)}... (connected ${connectedCount} < floor ${floor})`);
|
|
202
|
+
|
|
203
|
+
// Clear any existing attempt record to allow override
|
|
204
|
+
this.mesh.peerDiscovery.clearConnectionAttempt(targetPeerId);
|
|
205
|
+
|
|
206
|
+
// Temporarily treat as initiator regardless of lexicographic order
|
|
207
|
+
const options = {
|
|
208
|
+
localStream: null,
|
|
209
|
+
enableAudio: true,
|
|
210
|
+
enableVideo: true
|
|
211
|
+
};
|
|
212
|
+
const peerConnection = new PeerConnection(targetPeerId, true, options);
|
|
213
|
+
this.setupPeerConnectionHandlers(peerConnection);
|
|
214
|
+
this.peers.set(targetPeerId, peerConnection);
|
|
215
|
+
try {
|
|
216
|
+
await peerConnection.createConnection();
|
|
217
|
+
const offer = await peerConnection.createOffer();
|
|
218
|
+
await this.mesh.sendSignalingMessage({ type: 'offer', data: offer }, targetPeerId);
|
|
219
|
+
} catch (e) {
|
|
220
|
+
this.debug.warn(`Override connection failed to ${targetPeerId.substring(0,8)}...: ${e.message}`);
|
|
221
|
+
this.mesh.peerDiscovery.removeDiscoveredPeer(targetPeerId);
|
|
222
|
+
this.peers.delete(targetPeerId);
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
|
|
169
226
|
cleanupFailedConnection(peerId) {
|
|
170
227
|
this.debug.log(`Cleaning up failed connection for ${peerId.substring(0, 8)}...`);
|
|
171
228
|
|
|
@@ -243,6 +300,8 @@ export class ConnectionManager extends EventEmitter {
|
|
|
243
300
|
this.mesh.peerDiscovery.clearConnectionAttempt(event.peerId);
|
|
244
301
|
this.mesh.peerDiscovery.updateDiscoveryTimestamp(event.peerId);
|
|
245
302
|
|
|
303
|
+
// (Rollback) Removed adaptive gossip resend hook
|
|
304
|
+
|
|
246
305
|
this.emit('peersUpdated');
|
|
247
306
|
});
|
|
248
307
|
|
|
@@ -428,25 +487,24 @@ export class ConnectionManager extends EventEmitter {
|
|
|
428
487
|
}
|
|
429
488
|
|
|
430
489
|
canAcceptMorePeers() {
|
|
431
|
-
// Count connected peers
|
|
490
|
+
// Count connected peers for capacity check
|
|
432
491
|
const connectedCount = this.getConnectedPeerCount();
|
|
433
|
-
|
|
434
|
-
// If we have room for connected peers, always accept
|
|
435
|
-
if (connectedCount < this.mesh.maxPeers) {
|
|
436
|
-
return true;
|
|
437
|
-
}
|
|
438
|
-
|
|
439
|
-
// If at max connected peers, check if we have stale peers we can evict
|
|
440
|
-
const stalePeerCount = this.getStalePeerCount();
|
|
441
492
|
const totalPeerCount = this.peers.size;
|
|
442
|
-
|
|
443
|
-
//
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
493
|
+
|
|
494
|
+
// STRICT: Don't accept if we're at or over maxPeers
|
|
495
|
+
// Remove the "+1 overhead" logic that was causing overshoot
|
|
496
|
+
if (connectedCount >= this.mesh.maxPeers) {
|
|
497
|
+
this.debug.log(`At or over capacity: ${connectedCount}/${this.mesh.maxPeers} connected, rejecting new connections`);
|
|
498
|
+
return false;
|
|
447
499
|
}
|
|
448
|
-
|
|
449
|
-
//
|
|
500
|
+
|
|
501
|
+
// Also check total peer count (including connecting) to prevent race conditions
|
|
502
|
+
if (totalPeerCount >= this.mesh.maxPeers) {
|
|
503
|
+
this.debug.log(`Total peer count at capacity: ${totalPeerCount}/${this.mesh.maxPeers}, rejecting new connections`);
|
|
504
|
+
return false;
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
return true;
|
|
450
508
|
this.debug.log(`Cannot accept more peers: ${connectedCount}/${this.mesh.maxPeers} connected, ${totalPeerCount} total peers in Map`);
|
|
451
509
|
return false;
|
|
452
510
|
}
|
|
@@ -760,6 +818,13 @@ export class ConnectionManager extends EventEmitter {
|
|
|
760
818
|
return;
|
|
761
819
|
}
|
|
762
820
|
|
|
821
|
+
// Emit generic messageReceived event for all messages (used by hub server)
|
|
822
|
+
this.mesh.emit('messageReceived', {
|
|
823
|
+
from: fromPeerId,
|
|
824
|
+
data: message,
|
|
825
|
+
timestamp: Date.now()
|
|
826
|
+
});
|
|
827
|
+
|
|
763
828
|
// Handle binary messages first
|
|
764
829
|
if (message.type === 'binary' && message.data instanceof Uint8Array) {
|
|
765
830
|
this.debug.log(`📦 Received binary message (${message.size} bytes) from ${fromPeerId.substring(0, 8)}...`);
|
package/src/GossipManager.js
CHANGED
|
@@ -21,11 +21,14 @@ export class GossipManager extends EventEmitter {
|
|
|
21
21
|
this.processedKeyExchanges = new Map(); // "peerId:keyType" -> timestamp
|
|
22
22
|
|
|
23
23
|
// Configuration
|
|
24
|
-
|
|
24
|
+
// Increased TTL further to improve reliability across multi-hub partial meshes
|
|
25
|
+
this.maxTTL = 40; // allow deeper multi-hop propagation before expiry
|
|
25
26
|
this.messageExpiryTime = 5 * 60 * 1000; // 5 minutes
|
|
26
27
|
this.cleanupInterval = 60 * 1000; // 1 minute
|
|
27
28
|
this.cleanupTimer = null; // Track cleanup timer for proper cleanup
|
|
28
29
|
|
|
30
|
+
// (Rollback) Remove adaptive resend structures - rely on pure gossip
|
|
31
|
+
|
|
29
32
|
this.startCleanupTimer();
|
|
30
33
|
}
|
|
31
34
|
|
|
@@ -71,6 +74,8 @@ export class GossipManager extends EventEmitter {
|
|
|
71
74
|
});
|
|
72
75
|
this.messageHistory.set(messageId, message);
|
|
73
76
|
|
|
77
|
+
// (Rollback) No adaptive resend tracking
|
|
78
|
+
|
|
74
79
|
// Send to all connected peers
|
|
75
80
|
this.propagateMessage(message);
|
|
76
81
|
|
|
@@ -88,6 +93,12 @@ export class GossipManager extends EventEmitter {
|
|
|
88
93
|
return messageId;
|
|
89
94
|
}
|
|
90
95
|
|
|
96
|
+
/**
|
|
97
|
+
* Attempt adaptive resend of recent broadcasts to peers that connected
|
|
98
|
+
* after initial propagation window.
|
|
99
|
+
*/
|
|
100
|
+
// (Rollback) attemptAdaptiveResends removed
|
|
101
|
+
|
|
91
102
|
/**
|
|
92
103
|
* Send a direct message to a specific peer using gossip routing (DM)
|
|
93
104
|
* @param {string} targetPeerId - The destination peer's ID
|
package/src/PeerDiscovery.js
CHANGED
|
@@ -23,6 +23,9 @@ export class PeerDiscovery extends EventEmitter {
|
|
|
23
23
|
}
|
|
24
24
|
|
|
25
25
|
stop() {
|
|
26
|
+
// Only stop the cleanup interval, DO NOT clear discovered peers
|
|
27
|
+
// Discovered peers should persist even when signaling server connection is lost
|
|
28
|
+
// because the WebRTC connections remain active
|
|
26
29
|
if (this.cleanupInterval) {
|
|
27
30
|
clearInterval(this.cleanupInterval);
|
|
28
31
|
this.cleanupInterval = null;
|
|
@@ -33,6 +36,14 @@ export class PeerDiscovery extends EventEmitter {
|
|
|
33
36
|
this.meshOptimizationTimeout = null;
|
|
34
37
|
}
|
|
35
38
|
|
|
39
|
+
// DO NOT CLEAR: this.discoveredPeers
|
|
40
|
+
// DO NOT CLEAR: this.connectionAttempts
|
|
41
|
+
// These should persist so we don't try to reconnect to already-connected peers
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// Full cleanup method for deliberate disconnects
|
|
45
|
+
cleanup() {
|
|
46
|
+
this.stop();
|
|
36
47
|
this.discoveredPeers.clear();
|
|
37
48
|
this.connectionAttempts.clear();
|
|
38
49
|
}
|
|
@@ -51,13 +62,29 @@ export class PeerDiscovery extends EventEmitter {
|
|
|
51
62
|
this.debug.log(`Discovered peer ${peerId.substring(0, 8)}...`);
|
|
52
63
|
|
|
53
64
|
// Only auto-connect if we should initiate to this peer and we're not already trying
|
|
54
|
-
|
|
65
|
+
const shouldInitiate = this.shouldInitiateConnection(peerId);
|
|
66
|
+
const alreadyAttempting = this.connectionAttempts.has(peerId);
|
|
67
|
+
|
|
68
|
+
this.debug.log(`🔍 Connection decision for ${peerId.substring(0, 8)}...: autoDiscovery=${this.autoDiscovery}, shouldInitiate=${shouldInitiate}, alreadyAttempting=${alreadyAttempting}`);
|
|
69
|
+
|
|
70
|
+
if (this.autoDiscovery && shouldInitiate && !alreadyAttempting) {
|
|
55
71
|
this.debug.log(`Considering connection to ${peerId.substring(0, 8)}...`);
|
|
56
72
|
|
|
57
73
|
const canAccept = this.canAcceptMorePeers();
|
|
74
|
+
this.debug.log(`Can accept more peers: ${canAccept}`);
|
|
58
75
|
if (canAccept) {
|
|
59
|
-
this.debug.log(
|
|
76
|
+
this.debug.log(`🚀 Connecting to ${peerId.substring(0, 8)}...`);
|
|
60
77
|
this.emit('connectToPeer', { peerId });
|
|
78
|
+
} else {
|
|
79
|
+
this.debug.log(`❌ Cannot accept more peers (at capacity)`);
|
|
80
|
+
}
|
|
81
|
+
} else {
|
|
82
|
+
if (!this.autoDiscovery) {
|
|
83
|
+
this.debug.log(`❌ Auto-discovery disabled, not connecting to ${peerId.substring(0, 8)}...`);
|
|
84
|
+
} else if (!shouldInitiate) {
|
|
85
|
+
this.debug.log(`⏸️ Not initiating to ${peerId.substring(0, 8)}... (they should initiate to us)`);
|
|
86
|
+
} else if (alreadyAttempting) {
|
|
87
|
+
this.debug.log(`⏸️ Already attempting connection to ${peerId.substring(0, 8)}...`);
|
|
61
88
|
}
|
|
62
89
|
}
|
|
63
90
|
|
package/src/PeerPigeonMesh.js
CHANGED
|
@@ -37,6 +37,10 @@ export class PeerPigeonMesh extends EventEmitter {
|
|
|
37
37
|
// Configuration - Optional features enabled by default (opt-out)
|
|
38
38
|
this.maxPeers = options.maxPeers !== undefined ? options.maxPeers : 3;
|
|
39
39
|
this.minPeers = options.minPeers !== undefined ? options.minPeers : 2;
|
|
40
|
+
// Connectivity floor: ensure each peer obtains at least this many connections for robust gossip
|
|
41
|
+
// Default to 3 across browsers (capped by maxPeers) for consistent propagation
|
|
42
|
+
const defaultFloor = Math.min(3, this.maxPeers ?? 3);
|
|
43
|
+
this.connectivityFloor = options.connectivityFloor !== undefined ? options.connectivityFloor : defaultFloor;
|
|
40
44
|
this.autoConnect = options.autoConnect !== false; // Default to true, can be disabled by setting to false
|
|
41
45
|
this.autoDiscovery = options.autoDiscovery !== false;
|
|
42
46
|
this.evictionStrategy = options.evictionStrategy !== false;
|
|
@@ -85,6 +89,9 @@ export class PeerPigeonMesh extends EventEmitter {
|
|
|
85
89
|
|
|
86
90
|
// Load saved signaling URL immediately
|
|
87
91
|
this.storageManager.loadSignalingUrlFromStorage();
|
|
92
|
+
|
|
93
|
+
// Connectivity enforcement timer handle
|
|
94
|
+
this._connectivityEnforcementTimer = null;
|
|
88
95
|
}
|
|
89
96
|
|
|
90
97
|
setupManagerEventHandlers() {
|
|
@@ -334,17 +341,18 @@ export class PeerPigeonMesh extends EventEmitter {
|
|
|
334
341
|
this.debug.warn('PigeonRTC initialization failed:', error.message);
|
|
335
342
|
}
|
|
336
343
|
|
|
337
|
-
// Request media permissions for localhost WebRTC to work
|
|
338
|
-
//
|
|
344
|
+
// Request media permissions for localhost WebRTC to work unless explicitly disabled
|
|
345
|
+
// Added DISABLE_LOCALHOST_MEDIA_REQUEST override for automated/headless test environments
|
|
339
346
|
if (environmentDetector.isBrowser) {
|
|
340
347
|
try {
|
|
348
|
+
const disableLocalhostMedia = typeof window !== 'undefined' && window.DISABLE_LOCALHOST_MEDIA_REQUEST;
|
|
341
349
|
const isLocalhost = window.location.hostname === 'localhost' ||
|
|
342
350
|
window.location.hostname === '127.0.0.1' ||
|
|
343
351
|
window.location.hostname === '';
|
|
344
|
-
|
|
345
|
-
if (isLocalhost && navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
|
|
346
|
-
this.debug.log('🎤 Requesting media permissions for localhost WebRTC...');
|
|
347
|
-
|
|
352
|
+
|
|
353
|
+
if (!disableLocalhostMedia && isLocalhost && navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
|
|
354
|
+
this.debug.log('🎤 Requesting media permissions for localhost WebRTC (not disabled)...');
|
|
355
|
+
|
|
348
356
|
// Request minimal audio permission (no video to reduce intrusiveness)
|
|
349
357
|
const stream = await navigator.mediaDevices.getUserMedia({
|
|
350
358
|
audio: true,
|
|
@@ -353,12 +361,14 @@ export class PeerPigeonMesh extends EventEmitter {
|
|
|
353
361
|
this.debug.warn('Media permission denied - connections may fail on localhost:', err.message);
|
|
354
362
|
return null;
|
|
355
363
|
});
|
|
356
|
-
|
|
364
|
+
|
|
357
365
|
// Immediately stop all tracks - we only needed the permission
|
|
358
366
|
if (stream) {
|
|
359
367
|
stream.getTracks().forEach(track => track.stop());
|
|
360
368
|
this.debug.log('✅ Media permissions granted - localhost connections will work');
|
|
361
369
|
}
|
|
370
|
+
} else if (disableLocalhostMedia) {
|
|
371
|
+
this.debug.log('🚫 Skipping localhost media permission request (DISABLE_LOCALHOST_MEDIA_REQUEST flag set)');
|
|
362
372
|
}
|
|
363
373
|
} catch (error) {
|
|
364
374
|
this.debug.warn('Could not request media permissions:', error.message);
|
|
@@ -416,6 +426,8 @@ export class PeerPigeonMesh extends EventEmitter {
|
|
|
416
426
|
maxPeers: this.maxPeers
|
|
417
427
|
});
|
|
418
428
|
this.setupDiscoveryHandlers();
|
|
429
|
+
// Start connectivity enforcement loop once discovery is ready
|
|
430
|
+
this.startConnectivityEnforcement();
|
|
419
431
|
|
|
420
432
|
// Initialize crypto manager if enabled
|
|
421
433
|
if (this.cryptoManager) {
|
|
@@ -455,6 +467,13 @@ export class PeerPigeonMesh extends EventEmitter {
|
|
|
455
467
|
this.emit('statusChanged', { type: 'connected' });
|
|
456
468
|
});
|
|
457
469
|
|
|
470
|
+
// IMPORTANT: When the WebSocket signaling connection is lost, we do NOT disconnect peers!
|
|
471
|
+
// WebRTC connections are peer-to-peer and remain active even without the signaling server.
|
|
472
|
+
// Peers can continue to communicate directly through their existing WebRTC data channels.
|
|
473
|
+
// The signaling server is only needed for:
|
|
474
|
+
// 1. Initial peer discovery and connection negotiation
|
|
475
|
+
// 2. Discovering new peers that join the network
|
|
476
|
+
// Once peers are connected via WebRTC, they are independent of the signaling server.
|
|
458
477
|
this.signalingClient.addEventListener('disconnected', () => {
|
|
459
478
|
this.connected = false;
|
|
460
479
|
this.polling = false;
|
|
@@ -555,7 +574,11 @@ export class PeerPigeonMesh extends EventEmitter {
|
|
|
555
574
|
}
|
|
556
575
|
|
|
557
576
|
if (this.peerDiscovery) {
|
|
558
|
-
this.peerDiscovery.stop()
|
|
577
|
+
this.peerDiscovery.cleanup(); // Use cleanup() instead of stop() for full cleanup
|
|
578
|
+
}
|
|
579
|
+
if (this._connectivityEnforcementTimer) {
|
|
580
|
+
clearInterval(this._connectivityEnforcementTimer);
|
|
581
|
+
this._connectivityEnforcementTimer = null;
|
|
559
582
|
}
|
|
560
583
|
|
|
561
584
|
this.connectionManager.disconnectAllPeers();
|
|
@@ -569,6 +592,44 @@ export class PeerPigeonMesh extends EventEmitter {
|
|
|
569
592
|
this.emit('statusChanged', { type: 'disconnected' });
|
|
570
593
|
}
|
|
571
594
|
|
|
595
|
+
/**
|
|
596
|
+
* Periodically attempt extra connections for under-connected peers until reaching connectivityFloor.
|
|
597
|
+
*/
|
|
598
|
+
startConnectivityEnforcement() {
|
|
599
|
+
if (this._connectivityEnforcementTimer) return;
|
|
600
|
+
const intervalMs = 4000; // Slower enforcement to avoid connection storms
|
|
601
|
+
this._connectivityEnforcementTimer = setInterval(() => {
|
|
602
|
+
if (!this.connected || !this.peerDiscovery) return;
|
|
603
|
+
const connectedCount = this.connectionManager.getConnectedPeerCount();
|
|
604
|
+
if (connectedCount >= this.connectivityFloor) return; // met floor
|
|
605
|
+
|
|
606
|
+
// Gather candidate peer IDs
|
|
607
|
+
const discovered = this.peerDiscovery.getDiscoveredPeers().map(p => p.peerId);
|
|
608
|
+
const notConnected = discovered.filter(pid =>
|
|
609
|
+
!this.connectionManager.hasPeer(pid) &&
|
|
610
|
+
!this.peerDiscovery.isAttemptingConnection(pid)
|
|
611
|
+
);
|
|
612
|
+
if (notConnected.length === 0) return;
|
|
613
|
+
|
|
614
|
+
// Prioritize by XOR distance for diversity and stability
|
|
615
|
+
const prioritized = notConnected.sort((a, b) => {
|
|
616
|
+
const distA = this.peerDiscovery.calculateXorDistance(this.peerId, a);
|
|
617
|
+
const distB = this.peerDiscovery.calculateXorDistance(this.peerId, b);
|
|
618
|
+
return distA < distB ? -1 : 1;
|
|
619
|
+
});
|
|
620
|
+
|
|
621
|
+
// Conservative: attempt exactly what's needed, one at a time
|
|
622
|
+
const needed = this.connectivityFloor - connectedCount;
|
|
623
|
+
const attemptLimit = Math.min(prioritized.length, Math.max(1, needed));
|
|
624
|
+
const batch = prioritized.slice(0, attemptLimit);
|
|
625
|
+
batch.forEach(pid => {
|
|
626
|
+
this.debug.log(`🔧 CONNECTIVITY FLOOR (${connectedCount}/${this.connectivityFloor}) attempting extra connection to ${pid.substring(0,8)}...`);
|
|
627
|
+
// Use normal connect, but with initiator override below floor
|
|
628
|
+
this.connectionManager.connectToPeer(pid);
|
|
629
|
+
});
|
|
630
|
+
}, intervalMs);
|
|
631
|
+
}
|
|
632
|
+
|
|
572
633
|
// Configuration methods
|
|
573
634
|
setMaxPeers(maxPeers) {
|
|
574
635
|
this.maxPeers = Math.max(1, Math.min(50, maxPeers));
|
package/src/SignalingClient.js
CHANGED
|
@@ -196,20 +196,22 @@ export class SignalingClient extends EventEmitter {
|
|
|
196
196
|
|
|
197
197
|
this.websocket.onclose = (event) => {
|
|
198
198
|
clearTimeout(connectTimeout);
|
|
199
|
+
const wasConnected = this.connected; // Track if we were connected
|
|
199
200
|
this.connected = false;
|
|
200
201
|
this.connectionPromise = null;
|
|
202
|
+
this.isReconnecting = false; // Always reset this flag
|
|
201
203
|
|
|
202
204
|
this.debug.log('WebSocket closed:', event.code, event.reason);
|
|
203
205
|
|
|
204
|
-
// Always emit disconnected event
|
|
205
|
-
|
|
206
|
+
// Always emit disconnected event (but only if we were actually connected)
|
|
207
|
+
if (wasConnected) {
|
|
208
|
+
this.emit('disconnected');
|
|
209
|
+
}
|
|
206
210
|
|
|
207
211
|
// Attempt reconnection unless this was a deliberate disconnect
|
|
208
212
|
if (!this.deliberateDisconnect) {
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
this.attemptReconnect();
|
|
212
|
-
}
|
|
213
|
+
// Always attempt reconnect when connection is lost (whether it was a new disconnect or a failed reconnection)
|
|
214
|
+
this.attemptReconnect();
|
|
213
215
|
} else {
|
|
214
216
|
// Reset the flag for future connections
|
|
215
217
|
this.deliberateDisconnect = false;
|
|
@@ -265,6 +267,14 @@ export class SignalingClient extends EventEmitter {
|
|
|
265
267
|
// If we have healthy peers, use much longer delays to avoid disrupting the mesh
|
|
266
268
|
const baseExtendedDelay = hasHealthyPeers ? 600000 : this.maxReconnectDelay * 2; // 10 min vs 2x normal
|
|
267
269
|
const extendedDelay = Math.min(baseExtendedDelay, 600000); // Max 10 minutes
|
|
270
|
+
this.emit('statusChanged', {
|
|
271
|
+
type: 'reconnecting',
|
|
272
|
+
message: `Max attempts reached. Retrying in ${Math.round(extendedDelay/1000)}s...`,
|
|
273
|
+
delay: extendedDelay,
|
|
274
|
+
attempt: this.reconnectAttempts,
|
|
275
|
+
maxAttempts: this.maxReconnectAttempts,
|
|
276
|
+
extendedBackoff: true
|
|
277
|
+
});
|
|
268
278
|
this.reconnectTimeout = setTimeout(() => {
|
|
269
279
|
this.reconnectAttempts = Math.floor(this.maxReconnectAttempts / 2); // Reset to half max
|
|
270
280
|
this.attemptReconnect();
|
|
@@ -281,6 +291,13 @@ export class SignalingClient extends EventEmitter {
|
|
|
281
291
|
const delay = Math.min(baseDelay * delayMultiplier, hasHealthyPeers ? 300000 : this.maxReconnectDelay);
|
|
282
292
|
|
|
283
293
|
this.debug.log(`Reconnecting in ${delay}ms (attempt ${this.reconnectAttempts}/${this.maxReconnectAttempts}, healthy peers: ${hasHealthyPeers})`);
|
|
294
|
+
this.emit('statusChanged', {
|
|
295
|
+
type: 'reconnecting',
|
|
296
|
+
message: `Reconnecting in ${Math.round(delay/1000)}s (attempt ${this.reconnectAttempts}/${this.maxReconnectAttempts})`,
|
|
297
|
+
delay,
|
|
298
|
+
attempt: this.reconnectAttempts,
|
|
299
|
+
maxAttempts: this.maxReconnectAttempts
|
|
300
|
+
});
|
|
284
301
|
|
|
285
302
|
this.reconnectTimeout = setTimeout(async () => {
|
|
286
303
|
if (!this.connected && this.signalingUrl) {
|
|
@@ -288,12 +305,9 @@ export class SignalingClient extends EventEmitter {
|
|
|
288
305
|
await this.connect(this.signalingUrl);
|
|
289
306
|
this.emit('statusChanged', { type: 'info', message: 'WebSocket reconnected successfully' });
|
|
290
307
|
} catch (error) {
|
|
291
|
-
this.debug.error('Reconnection failed:', error);
|
|
292
|
-
|
|
293
|
-
this.attemptReconnect();
|
|
308
|
+
this.debug.error('Reconnection attempt failed:', error);
|
|
309
|
+
// onclose will handle the next reconnection attempt
|
|
294
310
|
}
|
|
295
|
-
} else {
|
|
296
|
-
this.isReconnecting = false;
|
|
297
311
|
}
|
|
298
312
|
}, delay);
|
|
299
313
|
}
|