peerpigeon 1.0.6 â 1.0.8
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/dist/peerpigeon-browser.js +361 -30
- package/dist/peerpigeon-browser.js.map +3 -3
- package/docs/BROADCAST_STREAMING.md +388 -0
- package/docs/PEER_DISCOVERY_FIXES.md +140 -0
- package/examples/broadcast-stream-demo.html +539 -0
- package/package.json +1 -1
- package/server/index.js +238 -38
- package/src/ConnectionManager.js +38 -8
- package/src/GossipManager.js +22 -0
- package/src/PeerConnection.js +12 -7
- package/src/PeerDiscovery.js +33 -18
- package/src/PeerPigeonMesh.js +333 -0
- package/src/SignalingHandler.js +18 -5
package/server/index.js
CHANGED
|
@@ -40,6 +40,8 @@ export class PeerPigeonServer extends EventEmitter {
|
|
|
40
40
|
this.networkPeers = new Map(); // networkName -> Set of peerIds
|
|
41
41
|
this.hubs = new Map(); // peerId -> hub info (for peers identified as hubs)
|
|
42
42
|
this.bootstrapConnections = new Map(); // bootstrapUri -> connection info
|
|
43
|
+
this.relayedDiscoveries = new Map(); // Track relayed peer discoveries to prevent loops: "peerId:networkName" -> timestamp
|
|
44
|
+
this.relayedSignaling = new Map(); // Track relayed signaling messages to prevent loops: "fromPeerId:targetPeerId:type" -> timestamp
|
|
43
45
|
this.isRunning = false;
|
|
44
46
|
this.cleanupTimer = null;
|
|
45
47
|
this.startTime = null;
|
|
@@ -99,11 +101,36 @@ export class PeerPigeonServer extends EventEmitter {
|
|
|
99
101
|
/**
|
|
100
102
|
* Get all connected hubs
|
|
101
103
|
*/
|
|
104
|
+
/**
|
|
105
|
+
* Get all connected hubs (directly connected via WebSocket)
|
|
106
|
+
*/
|
|
102
107
|
getConnectedHubs(excludePeerId = null) {
|
|
103
108
|
const hubList = [];
|
|
104
109
|
for (const [peerId, hubInfo] of this.hubs) {
|
|
105
110
|
if (peerId !== excludePeerId && this.connections.has(peerId)) {
|
|
106
|
-
hubList.push({
|
|
111
|
+
hubList.push({
|
|
112
|
+
peerId,
|
|
113
|
+
connected: true,
|
|
114
|
+
...hubInfo
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
return hubList;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Get all known hubs (both directly connected and remotely discovered)
|
|
123
|
+
*/
|
|
124
|
+
getAllKnownHubs(excludePeerId = null) {
|
|
125
|
+
const hubList = [];
|
|
126
|
+
for (const [peerId, hubInfo] of this.hubs) {
|
|
127
|
+
if (peerId !== excludePeerId) {
|
|
128
|
+
hubList.push({
|
|
129
|
+
peerId,
|
|
130
|
+
connected: this.connections.has(peerId),
|
|
131
|
+
remote: hubInfo.remote || false,
|
|
132
|
+
...hubInfo
|
|
133
|
+
});
|
|
107
134
|
}
|
|
108
135
|
}
|
|
109
136
|
return hubList;
|
|
@@ -219,7 +246,7 @@ export class PeerPigeonServer extends EventEmitter {
|
|
|
219
246
|
res.end(JSON.stringify({
|
|
220
247
|
timestamp: new Date().toISOString(),
|
|
221
248
|
totalHubs: this.hubs.size,
|
|
222
|
-
hubs: this.
|
|
249
|
+
hubs: this.getAllKnownHubs()
|
|
223
250
|
}));
|
|
224
251
|
return;
|
|
225
252
|
}
|
|
@@ -398,18 +425,17 @@ export class PeerPigeonServer extends EventEmitter {
|
|
|
398
425
|
return;
|
|
399
426
|
}
|
|
400
427
|
|
|
401
|
-
//
|
|
428
|
+
// Default Fly.io bootstrap hubs
|
|
429
|
+
const DEFAULT_FLY_HUBS = [
|
|
430
|
+
'wss://pigeonhub.fly.dev',
|
|
431
|
+
'wss://pigeonhub-c.fly.dev'
|
|
432
|
+
];
|
|
433
|
+
|
|
434
|
+
// Use provided bootstrap hubs, or default to Fly.io hubs
|
|
402
435
|
let bootstrapUris = this.bootstrapHubs;
|
|
403
436
|
if (!bootstrapUris || bootstrapUris.length === 0) {
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
if (this.port !== defaultPort) {
|
|
407
|
-
bootstrapUris = [`ws://${this.host}:${defaultPort}`];
|
|
408
|
-
console.log(`đ No bootstrap hubs specified, trying default: ws://${this.host}:${defaultPort}`);
|
|
409
|
-
} else {
|
|
410
|
-
console.log('âšī¸ No bootstrap hubs to connect to (running on default port 3000)');
|
|
411
|
-
return;
|
|
412
|
-
}
|
|
437
|
+
bootstrapUris = DEFAULT_FLY_HUBS;
|
|
438
|
+
console.log(`đ No bootstrap hubs specified, using default Fly.io hubs: ${bootstrapUris.join(', ')}`);
|
|
413
439
|
}
|
|
414
440
|
|
|
415
441
|
console.log(`đ Connecting to ${bootstrapUris.length} bootstrap hub(s)...`);
|
|
@@ -484,7 +510,19 @@ export class PeerPigeonServer extends EventEmitter {
|
|
|
484
510
|
|
|
485
511
|
this.emit('bootstrapDisconnected', { uri, code, reason });
|
|
486
512
|
|
|
487
|
-
//
|
|
513
|
+
// Don't reconnect to localhost hubs - they're likely just not running
|
|
514
|
+
const url = new URL(uri);
|
|
515
|
+
const isLocalhost = url.hostname === 'localhost' ||
|
|
516
|
+
url.hostname === '127.0.0.1' ||
|
|
517
|
+
url.hostname === '0.0.0.0';
|
|
518
|
+
|
|
519
|
+
if (isLocalhost) {
|
|
520
|
+
console.log(`âšī¸ Not reconnecting to localhost hub ${uri} - assuming it's not running`);
|
|
521
|
+
this.bootstrapConnections.delete(uri);
|
|
522
|
+
return;
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
// Attempt to reconnect for non-localhost hubs
|
|
488
526
|
if (this.isRunning && attemptNumber < this.maxReconnectAttempts) {
|
|
489
527
|
connectionInfo.reconnectTimer = setTimeout(() => {
|
|
490
528
|
console.log(`đ Reconnecting to ${uri}...`);
|
|
@@ -499,7 +537,22 @@ export class PeerPigeonServer extends EventEmitter {
|
|
|
499
537
|
ws.on('error', (error) => {
|
|
500
538
|
console.error(`â WebSocket error for ${uri}:`, error.message);
|
|
501
539
|
|
|
502
|
-
//
|
|
540
|
+
// Check if it's a localhost hub
|
|
541
|
+
const url = new URL(uri);
|
|
542
|
+
const isLocalhost = url.hostname === 'localhost' ||
|
|
543
|
+
url.hostname === '127.0.0.1' ||
|
|
544
|
+
url.hostname === '0.0.0.0';
|
|
545
|
+
|
|
546
|
+
if (isLocalhost) {
|
|
547
|
+
console.log(`âšī¸ Localhost hub ${uri} not available - skipping reconnection attempts`);
|
|
548
|
+
this.bootstrapConnections.delete(uri);
|
|
549
|
+
if (attemptNumber === 0) {
|
|
550
|
+
reject(error);
|
|
551
|
+
}
|
|
552
|
+
return;
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
// Only reject on first attempt for non-localhost, otherwise we'll retry
|
|
503
556
|
if (attemptNumber === 0) {
|
|
504
557
|
this.bootstrapConnections.delete(uri);
|
|
505
558
|
reject(error);
|
|
@@ -521,6 +574,7 @@ export class PeerPigeonServer extends EventEmitter {
|
|
|
521
574
|
type: 'announce',
|
|
522
575
|
networkName: this.hubMeshNamespace,
|
|
523
576
|
data: {
|
|
577
|
+
peerId: this.hubPeerId, // CRITICAL: Include hub's peerId so it can be properly registered
|
|
524
578
|
isHub: true,
|
|
525
579
|
port: this.port,
|
|
526
580
|
host: this.host,
|
|
@@ -530,7 +584,7 @@ export class PeerPigeonServer extends EventEmitter {
|
|
|
530
584
|
};
|
|
531
585
|
|
|
532
586
|
ws.send(JSON.stringify(announcement));
|
|
533
|
-
console.log(`đĸ Announced to bootstrap hub on ${this.hubMeshNamespace}`);
|
|
587
|
+
console.log(`đĸ Announced hub ${this.hubPeerId.substring(0, 8)}... to bootstrap hub on namespace '${this.hubMeshNamespace}'`);
|
|
534
588
|
|
|
535
589
|
// Announce all existing local peers to the bootstrap hub
|
|
536
590
|
this.announceLocalPeersToHub(ws);
|
|
@@ -664,30 +718,66 @@ export class PeerPigeonServer extends EventEmitter {
|
|
|
664
718
|
|
|
665
719
|
case 'peer-discovered':
|
|
666
720
|
if (data?.isHub) {
|
|
667
|
-
|
|
668
|
-
|
|
721
|
+
const hubPeerId = data.peerId;
|
|
722
|
+
|
|
723
|
+
// CRITICAL: Ignore our own announcements to prevent loops
|
|
724
|
+
if (hubPeerId === this.hubPeerId) {
|
|
725
|
+
console.log(`đ Ignoring self-announcement from ${uri}`);
|
|
726
|
+
break;
|
|
727
|
+
}
|
|
728
|
+
|
|
729
|
+
console.log(`đĸ Discovered hub via bootstrap: ${hubPeerId?.substring(0, 8)}...`);
|
|
730
|
+
|
|
731
|
+
// Register this remotely discovered hub (even though it's not directly connected to us)
|
|
732
|
+
// This helps with hub awareness and statistics
|
|
733
|
+
if (hubPeerId && !this.hubs.has(hubPeerId)) {
|
|
734
|
+
this.hubs.set(hubPeerId, {
|
|
735
|
+
peerId: hubPeerId,
|
|
736
|
+
registeredAt: Date.now(),
|
|
737
|
+
lastActivity: Date.now(),
|
|
738
|
+
discoveredVia: uri,
|
|
739
|
+
remote: true, // Not directly connected to us
|
|
740
|
+
...data
|
|
741
|
+
});
|
|
742
|
+
console.log(`đ Registered remote hub: ${hubPeerId.substring(0, 8)}... (${this.hubs.size} total hubs)`);
|
|
743
|
+
}
|
|
744
|
+
|
|
745
|
+
this.emit('hubDiscovered', { peerId: hubPeerId, via: uri, data });
|
|
669
746
|
} else if (data?.peerId) {
|
|
670
|
-
// Regular peer discovered on another hub - notify our local peers in same network
|
|
747
|
+
// Regular peer discovered on another hub - notify our local CLIENT peers in same network
|
|
671
748
|
const discoveredPeerId = data.peerId;
|
|
672
749
|
const discoveredNetwork = networkName || 'global';
|
|
673
750
|
|
|
674
751
|
console.log(`đĨ Peer ${discoveredPeerId.substring(0, 8)}... discovered on another hub (network: ${discoveredNetwork})`);
|
|
675
752
|
|
|
676
|
-
// Forward to all our local peers in the same network
|
|
677
|
-
const
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
753
|
+
// Forward to all our local CLIENT peers in the same network (exclude hubs)
|
|
754
|
+
const localPeersInNetwork = this.networkPeers.get(discoveredNetwork);
|
|
755
|
+
if (localPeersInNetwork && localPeersInNetwork.size > 0) {
|
|
756
|
+
let forwardedCount = 0;
|
|
757
|
+
for (const localPeerId of localPeersInNetwork) {
|
|
758
|
+
// Skip hubs - only forward to client peers
|
|
759
|
+
const localPeerData = this.peerData.get(localPeerId);
|
|
760
|
+
if (localPeerData?.isHub) {
|
|
761
|
+
continue;
|
|
762
|
+
}
|
|
763
|
+
|
|
764
|
+
const localConnection = this.connections.get(localPeerId);
|
|
765
|
+
if (localConnection && localConnection.readyState === WebSocket.OPEN) {
|
|
766
|
+
this.sendToConnection(localConnection, {
|
|
767
|
+
type: 'peer-discovered',
|
|
768
|
+
data,
|
|
769
|
+
networkName: discoveredNetwork,
|
|
770
|
+
fromPeerId: 'system',
|
|
771
|
+
targetPeerId: localPeerId,
|
|
772
|
+
timestamp: Date.now()
|
|
773
|
+
});
|
|
774
|
+
forwardedCount++;
|
|
775
|
+
}
|
|
689
776
|
}
|
|
690
|
-
|
|
777
|
+
console.log(`â
Forwarded peer-discovered to ${forwardedCount} local client peer(s) in network '${discoveredNetwork}'`);
|
|
778
|
+
} else {
|
|
779
|
+
console.log(`âšī¸ No local peers in network '${discoveredNetwork}' to forward to`);
|
|
780
|
+
}
|
|
691
781
|
}
|
|
692
782
|
break;
|
|
693
783
|
|
|
@@ -954,8 +1044,11 @@ export class PeerPigeonServer extends EventEmitter {
|
|
|
954
1044
|
}
|
|
955
1045
|
this.networkPeers.get(peerNetworkName).add(peerId);
|
|
956
1046
|
|
|
957
|
-
// If this is a hub, broadcast
|
|
958
|
-
if
|
|
1047
|
+
// If this is a hub, broadcast BOTH hubs and regular peers to ALL other connected hubs
|
|
1048
|
+
// BUT only if this is a NEW announcement (not already known)
|
|
1049
|
+
const isNewAnnouncement = peerInfo && !peerInfo.broadcastedToHubs;
|
|
1050
|
+
|
|
1051
|
+
if (this.isHub && isNewAnnouncement) {
|
|
959
1052
|
const connectedHubs = [];
|
|
960
1053
|
|
|
961
1054
|
// 1. Add outgoing bootstrap connections
|
|
@@ -978,12 +1071,13 @@ export class PeerPigeonServer extends EventEmitter {
|
|
|
978
1071
|
}
|
|
979
1072
|
|
|
980
1073
|
if (connectedHubs.length > 0) {
|
|
981
|
-
|
|
1074
|
+
const peerType = isHub ? 'hub' : 'peer';
|
|
1075
|
+
console.log(`đĄ Broadcasting ${peerType} ${peerId.substring(0, 8)}... (network: ${peerNetworkName}) to ${connectedHubs.length} connected hub(s)`);
|
|
982
1076
|
const peerAnnouncement = {
|
|
983
1077
|
type: 'peer-discovered',
|
|
984
1078
|
data: {
|
|
985
1079
|
peerId,
|
|
986
|
-
isHub
|
|
1080
|
+
isHub,
|
|
987
1081
|
...message.data
|
|
988
1082
|
},
|
|
989
1083
|
networkName: peerNetworkName,
|
|
@@ -991,17 +1085,25 @@ export class PeerPigeonServer extends EventEmitter {
|
|
|
991
1085
|
timestamp: Date.now()
|
|
992
1086
|
};
|
|
993
1087
|
|
|
1088
|
+
// Mark as broadcasted to prevent re-broadcasting
|
|
1089
|
+
peerInfo.broadcastedToHubs = true;
|
|
1090
|
+
|
|
994
1091
|
for (const hub of connectedHubs) {
|
|
995
1092
|
try {
|
|
996
1093
|
if (hub.type === 'bootstrap') {
|
|
1094
|
+
console.log(` â Sending to bootstrap hub: ${hub.id}`);
|
|
997
1095
|
hub.ws.send(JSON.stringify(peerAnnouncement));
|
|
998
1096
|
} else {
|
|
1097
|
+
console.log(` â Sending to incoming hub: ${hub.id.substring(0, 8)}...`);
|
|
999
1098
|
this.sendToConnection(hub.ws, peerAnnouncement);
|
|
1000
1099
|
}
|
|
1001
1100
|
} catch (error) {
|
|
1002
1101
|
console.error(`â Error broadcasting to hub ${hub.id}:`, error.message);
|
|
1003
1102
|
}
|
|
1004
1103
|
}
|
|
1104
|
+
} else if (!isHub) {
|
|
1105
|
+
// Log when we have no hubs to broadcast to (only for client peers, not hubs)
|
|
1106
|
+
console.log(`â ī¸ No connected hubs to broadcast peer ${peerId.substring(0, 8)}... to`);
|
|
1005
1107
|
}
|
|
1006
1108
|
}
|
|
1007
1109
|
|
|
@@ -1106,8 +1208,22 @@ export class PeerPigeonServer extends EventEmitter {
|
|
|
1106
1208
|
this.sendToConnection(targetConnection, responseMessage);
|
|
1107
1209
|
} else {
|
|
1108
1210
|
// Target peer not on this hub - relay to other hubs
|
|
1211
|
+
// CRITICAL: Check if we've already relayed this signaling message to prevent loops
|
|
1212
|
+
const signalingKey = `${peerId}:${targetPeerId}:${message.type}`;
|
|
1213
|
+
const now = Date.now();
|
|
1214
|
+
const lastRelayed = this.relayedSignaling.get(signalingKey);
|
|
1215
|
+
|
|
1216
|
+
// If we've relayed this within the last 5 seconds, skip it
|
|
1217
|
+
if (lastRelayed && (now - lastRelayed) < 5000) {
|
|
1218
|
+
console.log(`đ Skipping relay - already relayed ${message.type} from ${peerId.substring(0, 8)}... to ${targetPeerId.substring(0, 8)}... recently`);
|
|
1219
|
+
return;
|
|
1220
|
+
}
|
|
1221
|
+
|
|
1109
1222
|
console.log(`đ Target peer ${targetPeerId.substring(0, 8)}... NOT LOCAL, relaying to other hubs (network: ${networkName})`);
|
|
1110
1223
|
|
|
1224
|
+
// Mark as relayed BEFORE relaying to prevent loops
|
|
1225
|
+
this.relayedSignaling.set(signalingKey, now);
|
|
1226
|
+
|
|
1111
1227
|
let relayed = false;
|
|
1112
1228
|
|
|
1113
1229
|
// First try relaying through bootstrap hubs (if we're not the bootstrap)
|
|
@@ -1182,9 +1298,10 @@ export class PeerPigeonServer extends EventEmitter {
|
|
|
1182
1298
|
return;
|
|
1183
1299
|
}
|
|
1184
1300
|
|
|
1185
|
-
// Check if sender is a hub
|
|
1301
|
+
// Check if sender is a hub or if it's from bootstrap
|
|
1302
|
+
const isFromBootstrap = fromHubPeerId === 'bootstrap' || message.fromPeerId === 'system';
|
|
1186
1303
|
const senderPeerData = this.peerData.get(fromHubPeerId);
|
|
1187
|
-
const isFromHub = senderPeerData?.isHub || senderPeerData?.networkName === this.hubMeshNamespace;
|
|
1304
|
+
const isFromHub = isFromBootstrap || senderPeerData?.isHub || senderPeerData?.networkName === this.hubMeshNamespace;
|
|
1188
1305
|
|
|
1189
1306
|
if (!isFromHub) {
|
|
1190
1307
|
console.log(`â ī¸ Received peer-discovered from non-hub peer ${fromHubPeerId.substring(0, 8)}... - ignoring`);
|
|
@@ -1193,6 +1310,65 @@ export class PeerPigeonServer extends EventEmitter {
|
|
|
1193
1310
|
|
|
1194
1311
|
console.log(`đ Received peer discovery from hub ${fromHubPeerId.substring(0, 8)}... - Peer ${discoveredPeerId.substring(0, 8)}... in network '${networkName}'`);
|
|
1195
1312
|
|
|
1313
|
+
// CRITICAL: Check if we've already relayed this peer discovery to prevent infinite loops
|
|
1314
|
+
const discoveryKey = `${discoveredPeerId}:${networkName}`;
|
|
1315
|
+
const now = Date.now();
|
|
1316
|
+
const lastRelayed = this.relayedDiscoveries.get(discoveryKey);
|
|
1317
|
+
|
|
1318
|
+
// If we've relayed this within the last 60 seconds, skip it
|
|
1319
|
+
if (lastRelayed && (now - lastRelayed) < 60000) {
|
|
1320
|
+
console.log(`đ Skipping relay - already relayed ${discoveredPeerId.substring(0, 8)}... in network '${networkName}' recently`);
|
|
1321
|
+
} else if (this.isHub) {
|
|
1322
|
+
// Mark as relayed before relaying to prevent loops
|
|
1323
|
+
this.relayedDiscoveries.set(discoveryKey, now);
|
|
1324
|
+
|
|
1325
|
+
const relayedToHubs = [];
|
|
1326
|
+
|
|
1327
|
+
// Relay to outgoing bootstrap connections (except the one we received from)
|
|
1328
|
+
for (const [uri, connInfo] of this.bootstrapConnections) {
|
|
1329
|
+
if (connInfo.connected && connInfo.ws.readyState === WebSocket.OPEN) {
|
|
1330
|
+
try {
|
|
1331
|
+
connInfo.ws.send(JSON.stringify({
|
|
1332
|
+
type: 'peer-discovered',
|
|
1333
|
+
data: messageData,
|
|
1334
|
+
networkName,
|
|
1335
|
+
fromPeerId: 'system',
|
|
1336
|
+
timestamp: Date.now()
|
|
1337
|
+
}));
|
|
1338
|
+
relayedToHubs.push(uri);
|
|
1339
|
+
} catch (error) {
|
|
1340
|
+
console.error(`â Error relaying to bootstrap hub ${uri}:`, error.message);
|
|
1341
|
+
}
|
|
1342
|
+
}
|
|
1343
|
+
}
|
|
1344
|
+
|
|
1345
|
+
// Relay to incoming hub connections (except the sender)
|
|
1346
|
+
for (const [hubPeerId, hubInfo] of this.hubs) {
|
|
1347
|
+
if (hubPeerId === fromHubPeerId || hubPeerId === this.hubPeerId) {
|
|
1348
|
+
continue; // Skip sender and self
|
|
1349
|
+
}
|
|
1350
|
+
const hubConnection = this.connections.get(hubPeerId);
|
|
1351
|
+
if (hubConnection && hubConnection.readyState === WebSocket.OPEN) {
|
|
1352
|
+
try {
|
|
1353
|
+
this.sendToConnection(hubConnection, {
|
|
1354
|
+
type: 'peer-discovered',
|
|
1355
|
+
data: messageData,
|
|
1356
|
+
networkName,
|
|
1357
|
+
fromPeerId: 'system',
|
|
1358
|
+
timestamp: Date.now()
|
|
1359
|
+
});
|
|
1360
|
+
relayedToHubs.push(hubPeerId.substring(0, 8) + '...');
|
|
1361
|
+
} catch (error) {
|
|
1362
|
+
console.error(`â Error relaying to hub ${hubPeerId.substring(0, 8)}...:`, error.message);
|
|
1363
|
+
}
|
|
1364
|
+
}
|
|
1365
|
+
}
|
|
1366
|
+
|
|
1367
|
+
if (relayedToHubs.length > 0) {
|
|
1368
|
+
console.log(`đ Relayed peer-discovered to ${relayedToHubs.length} other hub(s): ${relayedToHubs.join(', ')}`);
|
|
1369
|
+
}
|
|
1370
|
+
}
|
|
1371
|
+
|
|
1196
1372
|
// Forward to all local CLIENT peers in the same network (exclude hubs)
|
|
1197
1373
|
const localPeers = this.networkPeers.get(networkName);
|
|
1198
1374
|
if (localPeers && localPeers.size > 0) {
|
|
@@ -1381,6 +1557,30 @@ export class PeerPigeonServer extends EventEmitter {
|
|
|
1381
1557
|
if (cleanedUp > 0) {
|
|
1382
1558
|
console.log(`đ§š Periodic cleanup: removed ${cleanedUp} stale connections, ${this.connections.size} active across ${this.networkPeers.size} networks`);
|
|
1383
1559
|
}
|
|
1560
|
+
|
|
1561
|
+
// Clean up old relay tracking entries (older than 5 minutes)
|
|
1562
|
+
const fiveMinutesAgo = Date.now() - 300000;
|
|
1563
|
+
let relayEntriesRemoved = 0;
|
|
1564
|
+
for (const [key, timestamp] of this.relayedDiscoveries) {
|
|
1565
|
+
if (timestamp < fiveMinutesAgo) {
|
|
1566
|
+
this.relayedDiscoveries.delete(key);
|
|
1567
|
+
relayEntriesRemoved++;
|
|
1568
|
+
}
|
|
1569
|
+
}
|
|
1570
|
+
|
|
1571
|
+
// Clean up old signaling relay tracking entries (older than 1 minute)
|
|
1572
|
+
const oneMinuteAgo = Date.now() - 60000;
|
|
1573
|
+
let signalingEntriesRemoved = 0;
|
|
1574
|
+
for (const [key, timestamp] of this.relayedSignaling) {
|
|
1575
|
+
if (timestamp < oneMinuteAgo) {
|
|
1576
|
+
this.relayedSignaling.delete(key);
|
|
1577
|
+
signalingEntriesRemoved++;
|
|
1578
|
+
}
|
|
1579
|
+
}
|
|
1580
|
+
|
|
1581
|
+
if (relayEntriesRemoved > 0 || signalingEntriesRemoved > 0) {
|
|
1582
|
+
console.log(`đ§š Cleaned up ${relayEntriesRemoved} relay tracking entries, ${signalingEntriesRemoved} signaling relay entries`);
|
|
1583
|
+
}
|
|
1384
1584
|
}
|
|
1385
1585
|
|
|
1386
1586
|
/**
|
package/src/ConnectionManager.js
CHANGED
|
@@ -65,14 +65,37 @@ export class ConnectionManager extends EventEmitter {
|
|
|
65
65
|
|
|
66
66
|
// Enhanced duplicate connection prevention
|
|
67
67
|
if (this.peers.has(targetPeerId)) {
|
|
68
|
-
this.
|
|
69
|
-
|
|
68
|
+
const existingPeer = this.peers.get(targetPeerId);
|
|
69
|
+
const status = existingPeer.getStatus();
|
|
70
|
+
|
|
71
|
+
// If already connected, don't retry
|
|
72
|
+
if (status === 'connected') {
|
|
73
|
+
this.debug.log(`Already connected to ${targetPeerId.substring(0, 8)}... (status: ${status})`);
|
|
74
|
+
return;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// If connecting but stuck, allow retry after timeout
|
|
78
|
+
if (status === 'connecting') {
|
|
79
|
+
const connectionAge = Date.now() - (existingPeer.createdAt || 0);
|
|
80
|
+
if (connectionAge < 10000) { // Wait 10 seconds before considering it stuck
|
|
81
|
+
this.debug.log(`Connection to ${targetPeerId.substring(0, 8)}... still in progress (${Math.round(connectionAge / 1000)}s)`);
|
|
82
|
+
return;
|
|
83
|
+
}
|
|
84
|
+
this.debug.log(`Connection to ${targetPeerId.substring(0, 8)}... appears stuck (${Math.round(connectionAge / 1000)}s), will retry`);
|
|
85
|
+
this.cleanupFailedConnection(targetPeerId);
|
|
86
|
+
}
|
|
70
87
|
}
|
|
71
88
|
|
|
72
89
|
// Check if we're already attempting through PeerDiscovery
|
|
73
90
|
if (this.mesh.peerDiscovery.isAttemptingConnection(targetPeerId)) {
|
|
74
|
-
|
|
75
|
-
|
|
91
|
+
const attemptAge = Date.now() - (this.lastConnectionAttempt.get(targetPeerId) || 0);
|
|
92
|
+
// Allow retry if attempt is old (more than 10 seconds)
|
|
93
|
+
if (attemptAge < 10000) {
|
|
94
|
+
this.debug.log(`Already attempting connection to ${targetPeerId.substring(0, 8)}... via PeerDiscovery (${Math.round(attemptAge / 1000)}s ago)`);
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
97
|
+
this.debug.log(`Old connection attempt to ${targetPeerId.substring(0, 8)}... (${Math.round(attemptAge / 1000)}s ago), allowing retry`);
|
|
98
|
+
this.mesh.peerDiscovery.clearConnectionAttempt(targetPeerId);
|
|
76
99
|
}
|
|
77
100
|
|
|
78
101
|
// INITIATOR LOGIC: Use deterministic peer ID comparison to prevent race conditions
|
|
@@ -102,15 +125,22 @@ export class ConnectionManager extends EventEmitter {
|
|
|
102
125
|
|
|
103
126
|
if (now - lastAttempt < retryDelay) {
|
|
104
127
|
const remaining = retryDelay - (now - lastAttempt);
|
|
105
|
-
this.debug.log(`Connection to ${targetPeerId.substring(0, 8)}... on cooldown (${Math.round(remaining
|
|
128
|
+
this.debug.log(`Connection to ${targetPeerId.substring(0, 8)}... on cooldown (${Math.round(remaining)}ms remaining, isolated: ${connectedCount === 0})`);
|
|
106
129
|
return;
|
|
107
130
|
}
|
|
108
131
|
}
|
|
109
132
|
|
|
110
|
-
// Check connection attempt count
|
|
111
|
-
|
|
133
|
+
// Check connection attempt count - be more lenient for isolated peers
|
|
134
|
+
const connectedCount = this.getConnectedPeerCount();
|
|
135
|
+
const maxAttempts = connectedCount === 0 ? this.maxConnectionAttempts * 2 : this.maxConnectionAttempts;
|
|
136
|
+
|
|
137
|
+
if (attempts >= maxAttempts) {
|
|
138
|
+
this.debug.log(`Max connection attempts (${maxAttempts}) reached for ${targetPeerId.substring(0, 8)}...`);
|
|
112
139
|
this.mesh.emit('statusChanged', { type: 'warning', message: `Max connection attempts reached for ${targetPeerId.substring(0, 8)}...` });
|
|
113
|
-
|
|
140
|
+
// Don't remove from discovered peers immediately - might reconnect later
|
|
141
|
+
this.connectionAttempts.delete(targetPeerId);
|
|
142
|
+
this.lastConnectionAttempt.delete(targetPeerId);
|
|
143
|
+
this.mesh.peerDiscovery.clearConnectionAttempt(targetPeerId);
|
|
114
144
|
return;
|
|
115
145
|
}
|
|
116
146
|
|
package/src/GossipManager.js
CHANGED
|
@@ -240,6 +240,28 @@ export class GossipManager extends EventEmitter {
|
|
|
240
240
|
} else if (subtype === 'mediaEvent') {
|
|
241
241
|
// Handle media streaming events
|
|
242
242
|
this.handleMediaEvent(content, originPeerId);
|
|
243
|
+
} else if (subtype === 'stream-chunk') {
|
|
244
|
+
// Handle gossip stream chunks - pass directly to mesh
|
|
245
|
+
this.emit('messageReceived', {
|
|
246
|
+
from: originPeerId,
|
|
247
|
+
message: {
|
|
248
|
+
type: 'stream-chunk',
|
|
249
|
+
...content
|
|
250
|
+
},
|
|
251
|
+
timestamp,
|
|
252
|
+
messageId
|
|
253
|
+
});
|
|
254
|
+
} else if (subtype === 'stream-control') {
|
|
255
|
+
// Handle gossip stream control messages - pass directly to mesh
|
|
256
|
+
this.emit('messageReceived', {
|
|
257
|
+
from: originPeerId,
|
|
258
|
+
message: {
|
|
259
|
+
type: 'stream-control',
|
|
260
|
+
...content
|
|
261
|
+
},
|
|
262
|
+
timestamp,
|
|
263
|
+
messageId
|
|
264
|
+
});
|
|
243
265
|
} else if (subtype === 'dm') {
|
|
244
266
|
// Direct message logic
|
|
245
267
|
if (typeof to === 'string' && typeof this.mesh.peerId === 'string' && to.trim().toLowerCase() === this.mesh.peerId.trim().toLowerCase()) {
|
package/src/PeerConnection.js
CHANGED
|
@@ -270,27 +270,32 @@ export class PeerConnection extends EventEmitter {
|
|
|
270
270
|
if (this.connection &&
|
|
271
271
|
this.connection.iceConnectionState === 'disconnected' &&
|
|
272
272
|
!this.isClosing) {
|
|
273
|
-
//
|
|
273
|
+
// ICE "disconnected" state is temporary - WebRTC connections are peer-to-peer
|
|
274
|
+
// and should persist even without signaling. Only disconnect on "failed" state.
|
|
275
|
+
// Check if we have signaling or mesh connectivity for ICE restart attempts
|
|
274
276
|
const hasSignaling = this.mesh && this.mesh.signalingClient && this.mesh.signalingClient.isConnected();
|
|
275
277
|
const hasMeshConnectivity = this.mesh && this.mesh.connected && this.mesh.connectionManager.getConnectedPeerCount() > 0;
|
|
276
278
|
|
|
277
279
|
if (hasSignaling || hasMeshConnectivity) {
|
|
278
|
-
this.debug.log(
|
|
280
|
+
this.debug.log(`â ī¸ ICE remained disconnected for ${this.peerId}, attempting restart (signaling: ${hasSignaling}, mesh: ${hasMeshConnectivity})`);
|
|
279
281
|
try {
|
|
280
282
|
this.restartIceViaSignaling().catch(error => {
|
|
281
283
|
this.debug.error('Failed to restart ICE after disconnection:', error);
|
|
282
|
-
|
|
284
|
+
// Don't disconnect on restart failure - wait for ICE to reach "failed" state naturally
|
|
285
|
+
this.debug.log(`Will wait for ICE to reach "failed" state before disconnecting ${this.peerId}`);
|
|
283
286
|
});
|
|
284
287
|
} catch (error) {
|
|
285
288
|
this.debug.error('Failed to restart ICE after disconnection:', error);
|
|
286
|
-
|
|
289
|
+
// Don't disconnect on restart failure - wait for ICE to reach "failed" state naturally
|
|
290
|
+
this.debug.log(`Will wait for ICE to reach "failed" state before disconnecting ${this.peerId}`);
|
|
287
291
|
}
|
|
288
292
|
} else {
|
|
289
|
-
|
|
290
|
-
|
|
293
|
+
// No signaling available, but WebRTC is peer-to-peer
|
|
294
|
+
// Don't disconnect unless ICE reaches "failed" state
|
|
295
|
+
this.debug.log(`â ī¸ ICE disconnected for ${this.peerId} without signaling - waiting for ICE state to resolve naturally`);
|
|
291
296
|
}
|
|
292
297
|
}
|
|
293
|
-
}, 5000); //
|
|
298
|
+
}, 5000); // Wait 5 seconds for potential ICE reconnection
|
|
294
299
|
}
|
|
295
300
|
};
|
|
296
301
|
|
package/src/PeerDiscovery.js
CHANGED
|
@@ -38,27 +38,46 @@ export class PeerDiscovery extends EventEmitter {
|
|
|
38
38
|
}
|
|
39
39
|
|
|
40
40
|
addDiscoveredPeer(peerId) {
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
41
|
+
const wasKnown = this.discoveredPeers.has(peerId);
|
|
42
|
+
const now = Date.now();
|
|
43
|
+
|
|
44
|
+
// Update or add peer with current timestamp
|
|
45
|
+
this.discoveredPeers.set(peerId, now);
|
|
46
|
+
|
|
47
|
+
if (wasKnown) {
|
|
48
|
+
this.debug.log(`Re-discovered peer ${peerId.substring(0, 8)}... (updating timestamp)`);
|
|
49
|
+
|
|
50
|
+
// Clean up stale connection attempt if it's been more than 5 seconds
|
|
51
|
+
if (this.connectionAttempts.has(peerId)) {
|
|
52
|
+
const attemptTime = this.connectionAttempts.get(peerId);
|
|
53
|
+
if (now - attemptTime > 5000) {
|
|
54
|
+
this.debug.log(`Clearing stale connection attempt for ${peerId.substring(0, 8)}...`);
|
|
55
|
+
this.connectionAttempts.delete(peerId);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
} else {
|
|
59
|
+
this.debug.log(`Discovered new peer ${peerId.substring(0, 8)}...`);
|
|
60
|
+
this.emit('peerDiscovered', { peerId });
|
|
46
61
|
}
|
|
47
62
|
|
|
48
|
-
|
|
49
|
-
this.
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
if (this.autoDiscovery && this.shouldInitiateConnection(peerId) && !this.connectionAttempts.has(peerId)) {
|
|
55
|
-
this.debug.log(`Considering connection to ${peerId.substring(0, 8)}...`);
|
|
63
|
+
// Check if we should initiate connection
|
|
64
|
+
const alreadyTrying = this.connectionAttempts.has(peerId);
|
|
65
|
+
const shouldInitiate = this.shouldInitiateConnection(peerId);
|
|
66
|
+
|
|
67
|
+
if (this.autoDiscovery && shouldInitiate && !alreadyTrying) {
|
|
68
|
+
this.debug.log(`Considering connection to ${peerId.substring(0, 8)}... (shouldInitiate: ${shouldInitiate}, alreadyTrying: ${alreadyTrying})`);
|
|
56
69
|
|
|
57
70
|
const canAccept = this.canAcceptMorePeers();
|
|
58
71
|
if (canAccept) {
|
|
59
|
-
this.debug.log(
|
|
72
|
+
this.debug.log(`đ Initiating connection to ${peerId.substring(0, 8)}...`);
|
|
60
73
|
this.emit('connectToPeer', { peerId });
|
|
74
|
+
} else {
|
|
75
|
+
this.debug.log(`Cannot connect to ${peerId.substring(0, 8)}... (at max peers)`);
|
|
61
76
|
}
|
|
77
|
+
} else if (alreadyTrying) {
|
|
78
|
+
this.debug.log(`Already attempting connection to ${peerId.substring(0, 8)}...`);
|
|
79
|
+
} else if (!shouldInitiate) {
|
|
80
|
+
this.debug.log(`Not initiating to ${peerId.substring(0, 8)}... (should wait for them to initiate)`);
|
|
62
81
|
}
|
|
63
82
|
|
|
64
83
|
this.scheduleMeshOptimization();
|
|
@@ -94,10 +113,6 @@ export class PeerDiscovery extends EventEmitter {
|
|
|
94
113
|
}
|
|
95
114
|
|
|
96
115
|
shouldInitiateConnection(targetPeerId) {
|
|
97
|
-
if (this.connectionAttempts.has(targetPeerId)) {
|
|
98
|
-
return false;
|
|
99
|
-
}
|
|
100
|
-
|
|
101
116
|
// Check current connection count to handle isolation
|
|
102
117
|
this.emit('checkCapacity');
|
|
103
118
|
const currentConnectionCount = this._currentConnectionCount || 0;
|