peerpigeon 0.0.5 → 0.0.7

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.
@@ -4,178 +4,177 @@ import { EventEmitter } from './EventEmitter.js';
4
4
  * Manages mesh optimization, connection strategies, and peer discovery optimization
5
5
  */
6
6
  export class MeshOptimizer extends EventEmitter {
7
- constructor(mesh, connectionManager, evictionManager) {
8
- super();
9
- this.mesh = mesh;
10
- this.connectionManager = connectionManager;
11
- this.evictionManager = evictionManager;
12
- }
7
+ constructor(mesh, connectionManager, evictionManager) {
8
+ super();
9
+ this.mesh = mesh;
10
+ this.connectionManager = connectionManager;
11
+ this.evictionManager = evictionManager;
12
+ }
13
13
 
14
- handleOptimizeConnections(unconnectedPeers) {
15
- if (!this.mesh.autoDiscovery) return;
16
-
17
- // For small mesh sizes, optimize if under capacity. For larger meshes, only optimize if significantly under capacity.
18
- const currentConnected = this.connectionManager.getConnectedPeerCount();
19
-
20
- // CRITICAL FIX: If we have no connections and there are available peers, we should connect
21
- // This handles the case where a peer with a small ID needs to connect to maintain mesh connectivity
22
- const hasNoConnections = currentConnected === 0;
23
- const hasMinPeersRequirement = this.mesh.minPeers > 0;
24
- const belowMinimum = currentConnected < this.mesh.minPeers;
25
-
26
- if (hasNoConnections && unconnectedPeers.length > 0) {
27
- console.log(`Peer has no connections but found ${unconnectedPeers.length} unconnected peers - forcing connection attempt`);
28
- // Force connection to the closest peer by XOR distance
29
- const sortedByDistance = unconnectedPeers.sort((a, b) => {
30
- const distA = this.calculateXorDistance(this.mesh.peerId, a);
31
- const distB = this.calculateXorDistance(this.mesh.peerId, b);
32
- return distA < distB ? -1 : 1;
33
- });
34
-
35
- const targetPeer = sortedByDistance[0];
36
- console.log(`Forcing connection to closest peer: ${targetPeer.substring(0, 8)}... (no connections, mesh connectivity required)`);
37
- this.connectionManager.connectToPeer(targetPeer);
38
- return;
39
- }
40
-
41
- if (belowMinimum && unconnectedPeers.length > 0) {
42
- console.log(`Below minimum peers (${currentConnected}/${this.mesh.minPeers}) - connecting to additional peers`);
43
- const needed = Math.min(this.mesh.minPeers - currentConnected, unconnectedPeers.length);
44
-
45
- // Sort by XOR distance and connect to closest peers
46
- const sortedByDistance = unconnectedPeers.sort((a, b) => {
47
- const distA = this.calculateXorDistance(this.mesh.peerId, a);
48
- const distB = this.calculateXorDistance(this.mesh.peerId, b);
49
- return distA < distB ? -1 : 1;
50
- });
51
-
52
- for (let i = 0; i < needed; i++) {
53
- const targetPeer = sortedByDistance[i];
54
- console.log(`Connecting to reach minimum: ${targetPeer.substring(0, 8)}...`);
55
- this.connectionManager.connectToPeer(targetPeer);
56
- }
57
- return;
58
- }
59
-
60
- // Normal optimization logic
61
- if (this.mesh.maxPeers <= 3) {
62
- // For small meshes, always try to reach max capacity
63
- if (currentConnected >= this.mesh.maxPeers) {
64
- console.log(`Skipping optimization - already at max capacity ${currentConnected}/${this.mesh.maxPeers}`);
65
- return;
66
- }
67
- } else {
68
- // For larger meshes, only optimize if below 70% capacity
69
- const targetThreshold = Math.floor(this.mesh.maxPeers * 0.7);
70
- if (currentConnected >= targetThreshold) {
71
- console.log(`Skipping optimization - ${currentConnected}/${this.mesh.maxPeers} peers connected (threshold: ${targetThreshold})`);
72
- return;
73
- }
74
- }
75
-
76
- const availableSlots = this.mesh.maxPeers - currentConnected;
77
- const peersToConnect = unconnectedPeers.slice(0, Math.min(availableSlots, 1)); // Only connect to 1 peer at a time
78
-
79
- console.log(`Optimizing connections carefully: ${availableSlots} slots available, connecting to ${peersToConnect.length} peer(s)`);
80
-
81
- peersToConnect.forEach((peerId, index) => {
82
- if (this.mesh.peerDiscovery.shouldInitiateConnection(peerId)) {
83
- console.log(`Initiating immediate connection to ${peerId.substring(0, 8)}... in optimization`);
84
- // Double-check conditions before connecting
85
- if (this.connectionManager.canAcceptMorePeers() &&
86
- !this.connectionManager.hasPeer(peerId) &&
87
- !this.mesh.peerDiscovery.isAttemptingConnection(peerId)) {
88
- this.connectionManager.connectToPeer(peerId);
89
- } else {
90
- console.log(`Skipping connection to ${peerId.substring(0, 8)}... - conditions changed`);
91
- }
92
- } else {
93
- console.log(`Not initiating connection to ${peerId.substring(0, 8)}... (should not initiate)`);
94
- }
95
- });
14
+ handleOptimizeConnections(unconnectedPeers) {
15
+ if (!this.mesh.autoDiscovery) return;
16
+
17
+ // For small mesh sizes, optimize if under capacity. For larger meshes, only optimize if significantly under capacity.
18
+ const currentConnected = this.connectionManager.getConnectedPeerCount();
19
+
20
+ // CRITICAL FIX: If we have no connections and there are available peers, we should connect
21
+ // This handles the case where a peer with a small ID needs to connect to maintain mesh connectivity
22
+ const hasNoConnections = currentConnected === 0;
23
+ const belowMinimum = currentConnected < this.mesh.minPeers;
24
+
25
+ if (hasNoConnections && unconnectedPeers.length > 0) {
26
+ console.log(`Peer has no connections but found ${unconnectedPeers.length} unconnected peers - forcing connection attempt`);
27
+ // Force connection to the closest peer by XOR distance
28
+ const sortedByDistance = unconnectedPeers.sort((a, b) => {
29
+ const distA = this.calculateXorDistance(this.mesh.peerId, a);
30
+ const distB = this.calculateXorDistance(this.mesh.peerId, b);
31
+ return distA < distB ? -1 : 1;
32
+ });
33
+
34
+ const targetPeer = sortedByDistance[0];
35
+ console.log(`Forcing connection to closest peer: ${targetPeer.substring(0, 8)}... (no connections, mesh connectivity required)`);
36
+ this.connectionManager.connectToPeer(targetPeer);
37
+ return;
96
38
  }
97
39
 
98
- calculateXorDistance(peerId1, peerId2) {
99
- let distance = 0n;
100
- for (let i = 0; i < Math.min(peerId1.length, peerId2.length); i += 2) {
101
- const byte1 = parseInt(peerId1.substr(i, 2), 16);
102
- const byte2 = parseInt(peerId2.substr(i, 2), 16);
103
- const xor = byte1 ^ byte2;
104
- distance = (distance << 8n) | BigInt(xor);
105
- }
106
- return distance;
40
+ if (belowMinimum && unconnectedPeers.length > 0) {
41
+ console.log(`Below minimum peers (${currentConnected}/${this.mesh.minPeers}) - connecting to additional peers`);
42
+ const needed = Math.min(this.mesh.minPeers - currentConnected, unconnectedPeers.length);
43
+
44
+ // Sort by XOR distance and connect to closest peers
45
+ const sortedByDistance = unconnectedPeers.sort((a, b) => {
46
+ const distA = this.calculateXorDistance(this.mesh.peerId, a);
47
+ const distB = this.calculateXorDistance(this.mesh.peerId, b);
48
+ return distA < distB ? -1 : 1;
49
+ });
50
+
51
+ for (let i = 0; i < needed; i++) {
52
+ const targetPeer = sortedByDistance[i];
53
+ console.log(`Connecting to reach minimum: ${targetPeer.substring(0, 8)}...`);
54
+ this.connectionManager.connectToPeer(targetPeer);
55
+ }
56
+ return;
107
57
  }
108
58
 
109
- // Method to force connection attempts to all discovered peers
110
- forceConnectToAllPeers() {
111
- const discoveredPeers = this.mesh.getDiscoveredPeers();
112
- let connectionAttempts = 0;
113
-
114
- console.log(`Forcing connections to ${discoveredPeers.length} discovered peers...`);
115
-
116
- discoveredPeers.forEach(peer => {
117
- if (!this.connectionManager.hasPeer(peer.peerId) && this.connectionManager.canAcceptMorePeers()) {
118
- console.log(`Force connecting to ${peer.peerId.substring(0, 8)}...`);
119
- this.connectionManager.connectToPeer(peer.peerId);
120
- connectionAttempts++;
121
- }
122
- });
123
-
124
- console.log(`Initiated ${connectionAttempts} forced connection attempts`);
125
- return connectionAttempts;
59
+ // Normal optimization logic
60
+ if (this.mesh.maxPeers <= 3) {
61
+ // For small meshes, always try to reach max capacity
62
+ if (currentConnected >= this.mesh.maxPeers) {
63
+ console.log(`Skipping optimization - already at max capacity ${currentConnected}/${this.mesh.maxPeers}`);
64
+ return;
65
+ }
66
+ } else {
67
+ // For larger meshes, only optimize if below 70% capacity
68
+ const targetThreshold = Math.floor(this.mesh.maxPeers * 0.7);
69
+ if (currentConnected >= targetThreshold) {
70
+ console.log(`Skipping optimization - ${currentConnected}/${this.mesh.maxPeers} peers connected (threshold: ${targetThreshold})`);
71
+ return;
72
+ }
126
73
  }
127
74
 
128
- // Debug method to help diagnose connectivity issues
129
- debugConnectivity() {
130
- const connectedPeers = this.connectionManager.getConnectedPeerCount();
131
- const discoveredPeers = this.mesh.getDiscoveredPeers();
132
- const totalPeers = this.connectionManager.peers.size;
133
-
134
- console.log('=== CONNECTIVITY DEBUG ===');
135
- console.log(`My Peer ID: ${this.mesh.peerId}`);
136
- console.log(`Connected Peers: ${connectedPeers}/${this.mesh.maxPeers}`);
137
- console.log(`Total Peer Objects: ${totalPeers}`);
138
- console.log(`Discovered Peers: ${discoveredPeers.length}`);
139
-
140
- console.log('\nPeer Details:');
141
- this.connectionManager.peers.forEach((peerConnection, peerId) => {
142
- const status = peerConnection.getStatus();
143
- const dataChannelReady = peerConnection.dataChannelReady;
144
- const connectionState = peerConnection.connection?.connectionState || 'unknown';
145
- const dataChannelState = peerConnection.dataChannel?.readyState || 'unknown';
146
-
147
- console.log(` ${peerId.substring(0, 8)}... - Status: ${status}, WebRTC: ${connectionState}, DataChannel: ${dataChannelState}, Ready: ${dataChannelReady}`);
148
- });
149
-
150
- console.log('\nDiscovered Peers:');
151
- discoveredPeers.forEach(peer => {
152
- const shouldInitiate = this.mesh.peerId < peer.peerId;
153
- const isConnected = this.connectionManager.hasPeer(peer.peerId);
154
- console.log(` ${peer.peerId.substring(0, 8)}... - ShouldInitiate: ${shouldInitiate}, IsConnected: ${isConnected}`);
155
- });
156
-
157
- console.log('\nConnection Attempts:');
158
- this.connectionManager.connectionAttempts.forEach((attempts, peerId) => {
159
- console.log(` ${peerId.substring(0, 8)}... - Attempts: ${attempts}/${this.connectionManager.maxConnectionAttempts}`);
160
- });
161
-
162
- console.log('\nEviction Status:');
163
- console.log(` Eviction Strategy: ${this.mesh.evictionStrategy ? 'enabled' : 'disabled'}`);
164
- console.log(` XOR Routing: ${this.mesh.xorRouting ? 'enabled' : 'disabled'}`);
165
-
166
- console.log('=== END DEBUG ===\n');
167
-
168
- return {
169
- connectedPeers,
170
- totalPeers,
171
- discoveredPeers: discoveredPeers.length,
172
- evictionEnabled: this.mesh.evictionStrategy,
173
- xorRouting: this.mesh.xorRouting,
174
- peerStatuses: Array.from(this.connectionManager.peers.entries()).map(([peerId, conn]) => ({
175
- peerId: peerId.substring(0, 8),
176
- status: conn.getStatus(),
177
- dataChannelReady: conn.dataChannelReady
178
- }))
179
- };
75
+ const availableSlots = this.mesh.maxPeers - currentConnected;
76
+ const peersToConnect = unconnectedPeers.slice(0, Math.min(availableSlots, 1)); // Only connect to 1 peer at a time
77
+
78
+ console.log(`Optimizing connections carefully: ${availableSlots} slots available, connecting to ${peersToConnect.length} peer(s)`);
79
+
80
+ peersToConnect.forEach((peerId, _index) => {
81
+ if (this.mesh.peerDiscovery.shouldInitiateConnection(peerId)) {
82
+ console.log(`Initiating immediate connection to ${peerId.substring(0, 8)}... in optimization`);
83
+ // Double-check conditions before connecting
84
+ if (this.connectionManager.canAcceptMorePeers() &&
85
+ !this.connectionManager.hasPeer(peerId) &&
86
+ !this.mesh.peerDiscovery.isAttemptingConnection(peerId)) {
87
+ this.connectionManager.connectToPeer(peerId);
88
+ } else {
89
+ console.log(`Skipping connection to ${peerId.substring(0, 8)}... - conditions changed`);
90
+ }
91
+ } else {
92
+ console.log(`Not initiating connection to ${peerId.substring(0, 8)}... (should not initiate)`);
93
+ }
94
+ });
95
+ }
96
+
97
+ calculateXorDistance(peerId1, peerId2) {
98
+ let distance = 0n;
99
+ for (let i = 0; i < Math.min(peerId1.length, peerId2.length); i += 2) {
100
+ const byte1 = parseInt(peerId1.substr(i, 2), 16);
101
+ const byte2 = parseInt(peerId2.substr(i, 2), 16);
102
+ const xor = byte1 ^ byte2;
103
+ distance = (distance << 8n) | BigInt(xor);
180
104
  }
105
+ return distance;
106
+ }
107
+
108
+ // Method to force connection attempts to all discovered peers
109
+ forceConnectToAllPeers() {
110
+ const discoveredPeers = this.mesh.getDiscoveredPeers();
111
+ let connectionAttempts = 0;
112
+
113
+ console.log(`Forcing connections to ${discoveredPeers.length} discovered peers...`);
114
+
115
+ discoveredPeers.forEach(peer => {
116
+ if (!this.connectionManager.hasPeer(peer.peerId) && this.connectionManager.canAcceptMorePeers()) {
117
+ console.log(`Force connecting to ${peer.peerId.substring(0, 8)}...`);
118
+ this.connectionManager.connectToPeer(peer.peerId);
119
+ connectionAttempts++;
120
+ }
121
+ });
122
+
123
+ console.log(`Initiated ${connectionAttempts} forced connection attempts`);
124
+ return connectionAttempts;
125
+ }
126
+
127
+ // Debug method to help diagnose connectivity issues
128
+ debugConnectivity() {
129
+ const connectedPeers = this.connectionManager.getConnectedPeerCount();
130
+ const discoveredPeers = this.mesh.getDiscoveredPeers();
131
+ const totalPeers = this.connectionManager.peers.size;
132
+
133
+ console.log('=== CONNECTIVITY DEBUG ===');
134
+ console.log(`My Peer ID: ${this.mesh.peerId}`);
135
+ console.log(`Connected Peers: ${connectedPeers}/${this.mesh.maxPeers}`);
136
+ console.log(`Total Peer Objects: ${totalPeers}`);
137
+ console.log(`Discovered Peers: ${discoveredPeers.length}`);
138
+
139
+ console.log('\nPeer Details:');
140
+ this.connectionManager.peers.forEach((peerConnection, peerId) => {
141
+ const status = peerConnection.getStatus();
142
+ const dataChannelReady = peerConnection.dataChannelReady;
143
+ const connectionState = peerConnection.connection?.connectionState || 'unknown';
144
+ const dataChannelState = peerConnection.dataChannel?.readyState || 'unknown';
145
+
146
+ console.log(` ${peerId.substring(0, 8)}... - Status: ${status}, WebRTC: ${connectionState}, DataChannel: ${dataChannelState}, Ready: ${dataChannelReady}`);
147
+ });
148
+
149
+ console.log('\nDiscovered Peers:');
150
+ discoveredPeers.forEach(peer => {
151
+ const shouldInitiate = this.mesh.peerId < peer.peerId;
152
+ const isConnected = this.connectionManager.hasPeer(peer.peerId);
153
+ console.log(` ${peer.peerId.substring(0, 8)}... - ShouldInitiate: ${shouldInitiate}, IsConnected: ${isConnected}`);
154
+ });
155
+
156
+ console.log('\nConnection Attempts:');
157
+ this.connectionManager.connectionAttempts.forEach((attempts, peerId) => {
158
+ console.log(` ${peerId.substring(0, 8)}... - Attempts: ${attempts}/${this.connectionManager.maxConnectionAttempts}`);
159
+ });
160
+
161
+ console.log('\nEviction Status:');
162
+ console.log(` Eviction Strategy: ${this.mesh.evictionStrategy ? 'enabled' : 'disabled'}`);
163
+ console.log(` XOR Routing: ${this.mesh.xorRouting ? 'enabled' : 'disabled'}`);
164
+
165
+ console.log('=== END DEBUG ===\n');
166
+
167
+ return {
168
+ connectedPeers,
169
+ totalPeers,
170
+ discoveredPeers: discoveredPeers.length,
171
+ evictionEnabled: this.mesh.evictionStrategy,
172
+ xorRouting: this.mesh.xorRouting,
173
+ peerStatuses: Array.from(this.connectionManager.peers.entries()).map(([peerId, conn]) => ({
174
+ peerId: peerId.substring(0, 8),
175
+ status: conn.getStatus(),
176
+ dataChannelReady: conn.dataChannelReady
177
+ }))
178
+ };
179
+ }
181
180
  }