peerpigeon 1.1.0 → 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.
@@ -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
  }
@@ -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() {
@@ -419,6 +426,8 @@ export class PeerPigeonMesh extends EventEmitter {
419
426
  maxPeers: this.maxPeers
420
427
  });
421
428
  this.setupDiscoveryHandlers();
429
+ // Start connectivity enforcement loop once discovery is ready
430
+ this.startConnectivityEnforcement();
422
431
 
423
432
  // Initialize crypto manager if enabled
424
433
  if (this.cryptoManager) {
@@ -458,6 +467,13 @@ export class PeerPigeonMesh extends EventEmitter {
458
467
  this.emit('statusChanged', { type: 'connected' });
459
468
  });
460
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.
461
477
  this.signalingClient.addEventListener('disconnected', () => {
462
478
  this.connected = false;
463
479
  this.polling = false;
@@ -558,7 +574,11 @@ export class PeerPigeonMesh extends EventEmitter {
558
574
  }
559
575
 
560
576
  if (this.peerDiscovery) {
561
- 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;
562
582
  }
563
583
 
564
584
  this.connectionManager.disconnectAllPeers();
@@ -572,6 +592,44 @@ export class PeerPigeonMesh extends EventEmitter {
572
592
  this.emit('statusChanged', { type: 'disconnected' });
573
593
  }
574
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
+
575
633
  // Configuration methods
576
634
  setMaxPeers(maxPeers) {
577
635
  this.maxPeers = Math.max(1, Math.min(50, maxPeers));
@@ -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
- this.emit('disconnected');
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
- this.emit('statusChanged', { type: 'warning', message: 'WebSocket connection lost - reconnecting...' });
210
- if (!this.isReconnecting) {
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
- this.isReconnecting = false;
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
  }