peerpigeon 1.0.8 â 1.0.9
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 +30 -77
- package/dist/peerpigeon-browser.js.map +3 -3
- package/package.json +1 -1
- package/server/index.js +38 -238
- package/src/ConnectionManager.js +8 -38
- package/src/PeerConnection.js +7 -12
- package/src/PeerDiscovery.js +18 -33
- package/src/SignalingHandler.js +5 -18
- package/docs/PEER_DISCOVERY_FIXES.md +0 -140
package/package.json
CHANGED
package/server/index.js
CHANGED
|
@@ -40,8 +40,6 @@ 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
|
|
45
43
|
this.isRunning = false;
|
|
46
44
|
this.cleanupTimer = null;
|
|
47
45
|
this.startTime = null;
|
|
@@ -101,36 +99,11 @@ export class PeerPigeonServer extends EventEmitter {
|
|
|
101
99
|
/**
|
|
102
100
|
* Get all connected hubs
|
|
103
101
|
*/
|
|
104
|
-
/**
|
|
105
|
-
* Get all connected hubs (directly connected via WebSocket)
|
|
106
|
-
*/
|
|
107
102
|
getConnectedHubs(excludePeerId = null) {
|
|
108
103
|
const hubList = [];
|
|
109
104
|
for (const [peerId, hubInfo] of this.hubs) {
|
|
110
105
|
if (peerId !== excludePeerId && this.connections.has(peerId)) {
|
|
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
|
-
});
|
|
106
|
+
hubList.push({ peerId, ...hubInfo });
|
|
134
107
|
}
|
|
135
108
|
}
|
|
136
109
|
return hubList;
|
|
@@ -246,7 +219,7 @@ export class PeerPigeonServer extends EventEmitter {
|
|
|
246
219
|
res.end(JSON.stringify({
|
|
247
220
|
timestamp: new Date().toISOString(),
|
|
248
221
|
totalHubs: this.hubs.size,
|
|
249
|
-
hubs: this.
|
|
222
|
+
hubs: this.getConnectedHubs()
|
|
250
223
|
}));
|
|
251
224
|
return;
|
|
252
225
|
}
|
|
@@ -425,17 +398,18 @@ export class PeerPigeonServer extends EventEmitter {
|
|
|
425
398
|
return;
|
|
426
399
|
}
|
|
427
400
|
|
|
428
|
-
//
|
|
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
|
|
401
|
+
// If no bootstrap hubs specified, try default port 3000
|
|
435
402
|
let bootstrapUris = this.bootstrapHubs;
|
|
436
403
|
if (!bootstrapUris || bootstrapUris.length === 0) {
|
|
437
|
-
|
|
438
|
-
|
|
404
|
+
// Don't connect to ourselves
|
|
405
|
+
const defaultPort = 3000;
|
|
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
|
+
}
|
|
439
413
|
}
|
|
440
414
|
|
|
441
415
|
console.log(`đ Connecting to ${bootstrapUris.length} bootstrap hub(s)...`);
|
|
@@ -510,19 +484,7 @@ export class PeerPigeonServer extends EventEmitter {
|
|
|
510
484
|
|
|
511
485
|
this.emit('bootstrapDisconnected', { uri, code, reason });
|
|
512
486
|
|
|
513
|
-
//
|
|
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
|
|
487
|
+
// Attempt to reconnect
|
|
526
488
|
if (this.isRunning && attemptNumber < this.maxReconnectAttempts) {
|
|
527
489
|
connectionInfo.reconnectTimer = setTimeout(() => {
|
|
528
490
|
console.log(`đ Reconnecting to ${uri}...`);
|
|
@@ -537,22 +499,7 @@ export class PeerPigeonServer extends EventEmitter {
|
|
|
537
499
|
ws.on('error', (error) => {
|
|
538
500
|
console.error(`â WebSocket error for ${uri}:`, error.message);
|
|
539
501
|
|
|
540
|
-
//
|
|
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
|
|
502
|
+
// Only reject on first attempt, otherwise we'll retry
|
|
556
503
|
if (attemptNumber === 0) {
|
|
557
504
|
this.bootstrapConnections.delete(uri);
|
|
558
505
|
reject(error);
|
|
@@ -574,7 +521,6 @@ export class PeerPigeonServer extends EventEmitter {
|
|
|
574
521
|
type: 'announce',
|
|
575
522
|
networkName: this.hubMeshNamespace,
|
|
576
523
|
data: {
|
|
577
|
-
peerId: this.hubPeerId, // CRITICAL: Include hub's peerId so it can be properly registered
|
|
578
524
|
isHub: true,
|
|
579
525
|
port: this.port,
|
|
580
526
|
host: this.host,
|
|
@@ -584,7 +530,7 @@ export class PeerPigeonServer extends EventEmitter {
|
|
|
584
530
|
};
|
|
585
531
|
|
|
586
532
|
ws.send(JSON.stringify(announcement));
|
|
587
|
-
console.log(`đĸ Announced
|
|
533
|
+
console.log(`đĸ Announced to bootstrap hub on ${this.hubMeshNamespace}`);
|
|
588
534
|
|
|
589
535
|
// Announce all existing local peers to the bootstrap hub
|
|
590
536
|
this.announceLocalPeersToHub(ws);
|
|
@@ -718,66 +664,30 @@ export class PeerPigeonServer extends EventEmitter {
|
|
|
718
664
|
|
|
719
665
|
case 'peer-discovered':
|
|
720
666
|
if (data?.isHub) {
|
|
721
|
-
|
|
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 });
|
|
667
|
+
console.log(`đĸ Discovered hub via bootstrap: ${data.peerId?.substring(0, 8)}...`);
|
|
668
|
+
this.emit('hubDiscovered', { peerId: data.peerId, via: uri, data });
|
|
746
669
|
} else if (data?.peerId) {
|
|
747
|
-
// Regular peer discovered on another hub - notify our local
|
|
670
|
+
// Regular peer discovered on another hub - notify our local peers in same network
|
|
748
671
|
const discoveredPeerId = data.peerId;
|
|
749
672
|
const discoveredNetwork = networkName || 'global';
|
|
750
673
|
|
|
751
674
|
console.log(`đĨ Peer ${discoveredPeerId.substring(0, 8)}... discovered on another hub (network: ${discoveredNetwork})`);
|
|
752
675
|
|
|
753
|
-
// Forward to all our local
|
|
754
|
-
const
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
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
|
-
}
|
|
676
|
+
// Forward to all our local peers in the same network
|
|
677
|
+
const localPeers = this.getActivePeers(null, discoveredNetwork);
|
|
678
|
+
localPeers.forEach(localPeerId => {
|
|
679
|
+
const localConnection = this.connections.get(localPeerId);
|
|
680
|
+
if (localConnection) {
|
|
681
|
+
this.sendToConnection(localConnection, {
|
|
682
|
+
type: 'peer-discovered',
|
|
683
|
+
data,
|
|
684
|
+
networkName: discoveredNetwork,
|
|
685
|
+
fromPeerId: 'system',
|
|
686
|
+
targetPeerId: localPeerId,
|
|
687
|
+
timestamp: Date.now()
|
|
688
|
+
});
|
|
776
689
|
}
|
|
777
|
-
|
|
778
|
-
} else {
|
|
779
|
-
console.log(`âšī¸ No local peers in network '${discoveredNetwork}' to forward to`);
|
|
780
|
-
}
|
|
690
|
+
});
|
|
781
691
|
}
|
|
782
692
|
break;
|
|
783
693
|
|
|
@@ -1044,11 +954,8 @@ export class PeerPigeonServer extends EventEmitter {
|
|
|
1044
954
|
}
|
|
1045
955
|
this.networkPeers.get(peerNetworkName).add(peerId);
|
|
1046
956
|
|
|
1047
|
-
// If this is a hub, broadcast
|
|
1048
|
-
|
|
1049
|
-
const isNewAnnouncement = peerInfo && !peerInfo.broadcastedToHubs;
|
|
1050
|
-
|
|
1051
|
-
if (this.isHub && isNewAnnouncement) {
|
|
957
|
+
// If this is a hub, broadcast this peer to ALL other connected hubs (both bootstrap and incoming)
|
|
958
|
+
if (this.isHub && !isHub) {
|
|
1052
959
|
const connectedHubs = [];
|
|
1053
960
|
|
|
1054
961
|
// 1. Add outgoing bootstrap connections
|
|
@@ -1071,13 +978,12 @@ export class PeerPigeonServer extends EventEmitter {
|
|
|
1071
978
|
}
|
|
1072
979
|
|
|
1073
980
|
if (connectedHubs.length > 0) {
|
|
1074
|
-
|
|
1075
|
-
console.log(`đĄ Broadcasting ${peerType} ${peerId.substring(0, 8)}... (network: ${peerNetworkName}) to ${connectedHubs.length} connected hub(s)`);
|
|
981
|
+
console.log(`đĄ Broadcasting peer ${peerId.substring(0, 8)}... to ${connectedHubs.length} connected hub(s)`);
|
|
1076
982
|
const peerAnnouncement = {
|
|
1077
983
|
type: 'peer-discovered',
|
|
1078
984
|
data: {
|
|
1079
985
|
peerId,
|
|
1080
|
-
isHub,
|
|
986
|
+
isHub: false,
|
|
1081
987
|
...message.data
|
|
1082
988
|
},
|
|
1083
989
|
networkName: peerNetworkName,
|
|
@@ -1085,25 +991,17 @@ export class PeerPigeonServer extends EventEmitter {
|
|
|
1085
991
|
timestamp: Date.now()
|
|
1086
992
|
};
|
|
1087
993
|
|
|
1088
|
-
// Mark as broadcasted to prevent re-broadcasting
|
|
1089
|
-
peerInfo.broadcastedToHubs = true;
|
|
1090
|
-
|
|
1091
994
|
for (const hub of connectedHubs) {
|
|
1092
995
|
try {
|
|
1093
996
|
if (hub.type === 'bootstrap') {
|
|
1094
|
-
console.log(` â Sending to bootstrap hub: ${hub.id}`);
|
|
1095
997
|
hub.ws.send(JSON.stringify(peerAnnouncement));
|
|
1096
998
|
} else {
|
|
1097
|
-
console.log(` â Sending to incoming hub: ${hub.id.substring(0, 8)}...`);
|
|
1098
999
|
this.sendToConnection(hub.ws, peerAnnouncement);
|
|
1099
1000
|
}
|
|
1100
1001
|
} catch (error) {
|
|
1101
1002
|
console.error(`â Error broadcasting to hub ${hub.id}:`, error.message);
|
|
1102
1003
|
}
|
|
1103
1004
|
}
|
|
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`);
|
|
1107
1005
|
}
|
|
1108
1006
|
}
|
|
1109
1007
|
|
|
@@ -1208,22 +1106,8 @@ export class PeerPigeonServer extends EventEmitter {
|
|
|
1208
1106
|
this.sendToConnection(targetConnection, responseMessage);
|
|
1209
1107
|
} else {
|
|
1210
1108
|
// 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
|
-
|
|
1222
1109
|
console.log(`đ Target peer ${targetPeerId.substring(0, 8)}... NOT LOCAL, relaying to other hubs (network: ${networkName})`);
|
|
1223
1110
|
|
|
1224
|
-
// Mark as relayed BEFORE relaying to prevent loops
|
|
1225
|
-
this.relayedSignaling.set(signalingKey, now);
|
|
1226
|
-
|
|
1227
1111
|
let relayed = false;
|
|
1228
1112
|
|
|
1229
1113
|
// First try relaying through bootstrap hubs (if we're not the bootstrap)
|
|
@@ -1298,10 +1182,9 @@ export class PeerPigeonServer extends EventEmitter {
|
|
|
1298
1182
|
return;
|
|
1299
1183
|
}
|
|
1300
1184
|
|
|
1301
|
-
// Check if sender is a hub
|
|
1302
|
-
const isFromBootstrap = fromHubPeerId === 'bootstrap' || message.fromPeerId === 'system';
|
|
1185
|
+
// Check if sender is a hub
|
|
1303
1186
|
const senderPeerData = this.peerData.get(fromHubPeerId);
|
|
1304
|
-
const isFromHub =
|
|
1187
|
+
const isFromHub = senderPeerData?.isHub || senderPeerData?.networkName === this.hubMeshNamespace;
|
|
1305
1188
|
|
|
1306
1189
|
if (!isFromHub) {
|
|
1307
1190
|
console.log(`â ī¸ Received peer-discovered from non-hub peer ${fromHubPeerId.substring(0, 8)}... - ignoring`);
|
|
@@ -1310,65 +1193,6 @@ export class PeerPigeonServer extends EventEmitter {
|
|
|
1310
1193
|
|
|
1311
1194
|
console.log(`đ Received peer discovery from hub ${fromHubPeerId.substring(0, 8)}... - Peer ${discoveredPeerId.substring(0, 8)}... in network '${networkName}'`);
|
|
1312
1195
|
|
|
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
|
-
|
|
1372
1196
|
// Forward to all local CLIENT peers in the same network (exclude hubs)
|
|
1373
1197
|
const localPeers = this.networkPeers.get(networkName);
|
|
1374
1198
|
if (localPeers && localPeers.size > 0) {
|
|
@@ -1557,30 +1381,6 @@ export class PeerPigeonServer extends EventEmitter {
|
|
|
1557
1381
|
if (cleanedUp > 0) {
|
|
1558
1382
|
console.log(`đ§š Periodic cleanup: removed ${cleanedUp} stale connections, ${this.connections.size} active across ${this.networkPeers.size} networks`);
|
|
1559
1383
|
}
|
|
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
|
-
}
|
|
1584
1384
|
}
|
|
1585
1385
|
|
|
1586
1386
|
/**
|
package/src/ConnectionManager.js
CHANGED
|
@@ -65,37 +65,14 @@ export class ConnectionManager extends EventEmitter {
|
|
|
65
65
|
|
|
66
66
|
// Enhanced duplicate connection prevention
|
|
67
67
|
if (this.peers.has(targetPeerId)) {
|
|
68
|
-
|
|
69
|
-
|
|
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
|
-
}
|
|
68
|
+
this.debug.log(`Already connected to ${targetPeerId.substring(0, 8)}...`);
|
|
69
|
+
return;
|
|
87
70
|
}
|
|
88
71
|
|
|
89
72
|
// Check if we're already attempting through PeerDiscovery
|
|
90
73
|
if (this.mesh.peerDiscovery.isAttemptingConnection(targetPeerId)) {
|
|
91
|
-
|
|
92
|
-
|
|
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);
|
|
74
|
+
this.debug.log(`Already attempting connection to ${targetPeerId.substring(0, 8)}... via PeerDiscovery`);
|
|
75
|
+
return;
|
|
99
76
|
}
|
|
100
77
|
|
|
101
78
|
// INITIATOR LOGIC: Use deterministic peer ID comparison to prevent race conditions
|
|
@@ -125,22 +102,15 @@ export class ConnectionManager extends EventEmitter {
|
|
|
125
102
|
|
|
126
103
|
if (now - lastAttempt < retryDelay) {
|
|
127
104
|
const remaining = retryDelay - (now - lastAttempt);
|
|
128
|
-
this.debug.log(`Connection to ${targetPeerId.substring(0, 8)}... on cooldown (${Math.round(remaining)}
|
|
105
|
+
this.debug.log(`Connection to ${targetPeerId.substring(0, 8)}... on cooldown (${Math.round(remaining / 1000)}s remaining, isolated: ${connectedCount === 0})`);
|
|
129
106
|
return;
|
|
130
107
|
}
|
|
131
108
|
}
|
|
132
109
|
|
|
133
|
-
// Check connection attempt count
|
|
134
|
-
|
|
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)}...`);
|
|
110
|
+
// Check connection attempt count
|
|
111
|
+
if (attempts >= this.maxConnectionAttempts) {
|
|
139
112
|
this.mesh.emit('statusChanged', { type: 'warning', message: `Max connection attempts reached for ${targetPeerId.substring(0, 8)}...` });
|
|
140
|
-
|
|
141
|
-
this.connectionAttempts.delete(targetPeerId);
|
|
142
|
-
this.lastConnectionAttempt.delete(targetPeerId);
|
|
143
|
-
this.mesh.peerDiscovery.clearConnectionAttempt(targetPeerId);
|
|
113
|
+
this.mesh.peerDiscovery.removeDiscoveredPeer(targetPeerId);
|
|
144
114
|
return;
|
|
145
115
|
}
|
|
146
116
|
|
package/src/PeerConnection.js
CHANGED
|
@@ -270,32 +270,27 @@ export class PeerConnection extends EventEmitter {
|
|
|
270
270
|
if (this.connection &&
|
|
271
271
|
this.connection.iceConnectionState === 'disconnected' &&
|
|
272
272
|
!this.isClosing) {
|
|
273
|
-
//
|
|
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
|
|
273
|
+
// Check if signaling is available before attempting ICE restart
|
|
276
274
|
const hasSignaling = this.mesh && this.mesh.signalingClient && this.mesh.signalingClient.isConnected();
|
|
277
275
|
const hasMeshConnectivity = this.mesh && this.mesh.connected && this.mesh.connectionManager.getConnectedPeerCount() > 0;
|
|
278
276
|
|
|
279
277
|
if (hasSignaling || hasMeshConnectivity) {
|
|
280
|
-
this.debug.log(
|
|
278
|
+
this.debug.log(`â ICE remained disconnected for ${this.peerId}, attempting restart (signaling: ${hasSignaling}, mesh: ${hasMeshConnectivity})`);
|
|
281
279
|
try {
|
|
282
280
|
this.restartIceViaSignaling().catch(error => {
|
|
283
281
|
this.debug.error('Failed to restart ICE after disconnection:', error);
|
|
284
|
-
|
|
285
|
-
this.debug.log(`Will wait for ICE to reach "failed" state before disconnecting ${this.peerId}`);
|
|
282
|
+
this.emit('disconnected', { peerId: this.peerId, reason: 'ICE disconnected' });
|
|
286
283
|
});
|
|
287
284
|
} catch (error) {
|
|
288
285
|
this.debug.error('Failed to restart ICE after disconnection:', error);
|
|
289
|
-
|
|
290
|
-
this.debug.log(`Will wait for ICE to reach "failed" state before disconnecting ${this.peerId}`);
|
|
286
|
+
this.emit('disconnected', { peerId: this.peerId, reason: 'ICE disconnected' });
|
|
291
287
|
}
|
|
292
288
|
} else {
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
this.debug.log(`â ī¸ ICE disconnected for ${this.peerId} without signaling - waiting for ICE state to resolve naturally`);
|
|
289
|
+
this.debug.log(`â ICE remained disconnected for ${this.peerId}, disconnecting`);
|
|
290
|
+
this.emit('disconnected', { peerId: this.peerId, reason: 'ICE disconnected' });
|
|
296
291
|
}
|
|
297
292
|
}
|
|
298
|
-
}, 5000); //
|
|
293
|
+
}, 5000); // Faster ICE reconnection - 5 seconds
|
|
299
294
|
}
|
|
300
295
|
};
|
|
301
296
|
|
package/src/PeerDiscovery.js
CHANGED
|
@@ -38,46 +38,27 @@ export class PeerDiscovery extends EventEmitter {
|
|
|
38
38
|
}
|
|
39
39
|
|
|
40
40
|
addDiscoveredPeer(peerId) {
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
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 });
|
|
41
|
+
// Skip if we already know about this peer (prevent duplicate processing)
|
|
42
|
+
if (this.discoveredPeers.has(peerId)) {
|
|
43
|
+
// Update timestamp but don't emit events or trigger connections
|
|
44
|
+
this.discoveredPeers.set(peerId, Date.now());
|
|
45
|
+
return;
|
|
61
46
|
}
|
|
62
47
|
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
48
|
+
this.discoveredPeers.set(peerId, Date.now());
|
|
49
|
+
this.emit('peerDiscovered', { peerId });
|
|
50
|
+
|
|
51
|
+
this.debug.log(`Discovered peer ${peerId.substring(0, 8)}...`);
|
|
52
|
+
|
|
53
|
+
// Only auto-connect if we should initiate to this peer and we're not already trying
|
|
54
|
+
if (this.autoDiscovery && this.shouldInitiateConnection(peerId) && !this.connectionAttempts.has(peerId)) {
|
|
55
|
+
this.debug.log(`Considering connection to ${peerId.substring(0, 8)}...`);
|
|
69
56
|
|
|
70
57
|
const canAccept = this.canAcceptMorePeers();
|
|
71
58
|
if (canAccept) {
|
|
72
|
-
this.debug.log(
|
|
59
|
+
this.debug.log(`Connecting to ${peerId.substring(0, 8)}...`);
|
|
73
60
|
this.emit('connectToPeer', { peerId });
|
|
74
|
-
} else {
|
|
75
|
-
this.debug.log(`Cannot connect to ${peerId.substring(0, 8)}... (at max peers)`);
|
|
76
61
|
}
|
|
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)`);
|
|
81
62
|
}
|
|
82
63
|
|
|
83
64
|
this.scheduleMeshOptimization();
|
|
@@ -113,6 +94,10 @@ export class PeerDiscovery extends EventEmitter {
|
|
|
113
94
|
}
|
|
114
95
|
|
|
115
96
|
shouldInitiateConnection(targetPeerId) {
|
|
97
|
+
if (this.connectionAttempts.has(targetPeerId)) {
|
|
98
|
+
return false;
|
|
99
|
+
}
|
|
100
|
+
|
|
116
101
|
// Check current connection count to handle isolation
|
|
117
102
|
this.emit('checkCapacity');
|
|
118
103
|
const currentConnectionCount = this._currentConnectionCount || 0;
|
package/src/SignalingHandler.js
CHANGED
|
@@ -100,26 +100,13 @@ export class SignalingHandler extends EventEmitter {
|
|
|
100
100
|
}
|
|
101
101
|
|
|
102
102
|
handlePeerAnnouncement(fromPeerId) {
|
|
103
|
-
//
|
|
104
|
-
if (this.
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
this.debug.log(`Peer ${fromPeerId.substring(0, 8)}... already connected (${peerStatus}), updating timestamp`);
|
|
108
|
-
this.mesh.peerDiscovery.updateDiscoveryTimestamp(fromPeerId);
|
|
109
|
-
return;
|
|
110
|
-
}
|
|
111
|
-
this.debug.log(`Peer ${fromPeerId.substring(0, 8)}... exists but not connected (${peerStatus}), allowing re-discovery`);
|
|
112
|
-
}
|
|
113
|
-
|
|
114
|
-
// Allow re-discovery to refresh timestamps and potentially retry connections
|
|
115
|
-
const wasKnown = this.mesh.peerDiscovery.hasPeer(fromPeerId);
|
|
116
|
-
if (wasKnown) {
|
|
117
|
-
this.debug.log(`Peer ${fromPeerId.substring(0, 8)}... already known, refreshing discovery`);
|
|
118
|
-
} else {
|
|
119
|
-
this.debug.log(`New peer discovered: ${fromPeerId.substring(0, 8)}...`);
|
|
103
|
+
// Prevent duplicate announcements - only announce if we haven't seen this peer before
|
|
104
|
+
if (this.mesh.peerDiscovery.hasPeer(fromPeerId)) {
|
|
105
|
+
this.debug.log(`Peer ${fromPeerId.substring(0, 8)}... already known, skipping announcement`);
|
|
106
|
+
return;
|
|
120
107
|
}
|
|
121
108
|
|
|
122
|
-
this.mesh.emit('statusChanged', { type: 'info', message: `Peer ${fromPeerId.substring(0, 8)}...
|
|
109
|
+
this.mesh.emit('statusChanged', { type: 'info', message: `Peer ${fromPeerId.substring(0, 8)}... announced` });
|
|
123
110
|
this.debug.log(`Adding discovered peer: ${fromPeerId.substring(0, 8)}... to PeerDiscovery`);
|
|
124
111
|
this.debug.log(`Current peer count: ${this.connectionManager.getConnectedPeerCount()}/${this.mesh.maxPeers}`);
|
|
125
112
|
this.debug.log(`All discovered peers: ${Array.from(this.mesh.peerDiscovery.discoveredPeers.keys()).map(p => p.substring(0, 8)).join(', ')}`);
|