peerpigeon 0.0.4 → 0.0.6

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.
@@ -1,27 +1,27 @@
1
1
  export class EventEmitter {
2
- constructor() {
3
- this.eventListeners = {};
4
- }
2
+ constructor() {
3
+ this.eventListeners = {};
4
+ }
5
5
 
6
- addEventListener(event, callback) {
7
- if (!this.eventListeners[event]) {
8
- this.eventListeners[event] = [];
9
- }
10
- this.eventListeners[event].push(callback);
6
+ addEventListener(event, callback) {
7
+ if (!this.eventListeners[event]) {
8
+ this.eventListeners[event] = [];
11
9
  }
10
+ this.eventListeners[event].push(callback);
11
+ }
12
12
 
13
- removeEventListener(event, callback) {
14
- if (this.eventListeners[event]) {
15
- const index = this.eventListeners[event].indexOf(callback);
16
- if (index > -1) {
17
- this.eventListeners[event].splice(index, 1);
18
- }
19
- }
13
+ removeEventListener(event, callback) {
14
+ if (this.eventListeners[event]) {
15
+ const index = this.eventListeners[event].indexOf(callback);
16
+ if (index > -1) {
17
+ this.eventListeners[event].splice(index, 1);
18
+ }
20
19
  }
20
+ }
21
21
 
22
- emit(event, data) {
23
- if (this.eventListeners[event]) {
24
- this.eventListeners[event].forEach(callback => callback(data));
25
- }
22
+ emit(event, data) {
23
+ if (this.eventListeners[event]) {
24
+ this.eventListeners[event].forEach(callback => callback(data));
26
25
  }
26
+ }
27
27
  }
@@ -5,253 +5,253 @@ import { EventEmitter } from './EventEmitter.js';
5
5
  * Evicts farthest peers when at capacity to maintain optimal XOR distance topology
6
6
  */
7
7
  export class EvictionManager extends EventEmitter {
8
- constructor(mesh, connectionManager) {
9
- super();
10
- this.mesh = mesh;
11
- this.connectionManager = connectionManager;
8
+ constructor(mesh, connectionManager) {
9
+ super();
10
+ this.mesh = mesh;
11
+ this.connectionManager = connectionManager;
12
+ }
13
+
14
+ shouldEvictForPeer(newPeerId) {
15
+ // Only evict for mesh topology optimization
16
+ if (!this.mesh.evictionStrategy) {
17
+ console.log('Eviction disabled - evictionStrategy is false');
18
+ return null;
12
19
  }
13
20
 
14
- shouldEvictForPeer(newPeerId) {
15
- // Only evict for mesh topology optimization
16
- if (!this.mesh.evictionStrategy) {
17
- console.log(`Eviction disabled - evictionStrategy is false`);
18
- return null;
19
- }
21
+ // Check total peer count (including connecting peers) to prevent race conditions
22
+ const totalPeerCount = this.connectionManager.peers.size;
23
+ if (totalPeerCount < this.mesh.maxPeers) {
24
+ console.log(`No eviction needed: ${totalPeerCount}/${this.mesh.maxPeers} peers`);
25
+ return null;
26
+ }
20
27
 
21
- // Check total peer count (including connecting peers) to prevent race conditions
22
- const totalPeerCount = this.connectionManager.peers.size;
23
- if (totalPeerCount < this.mesh.maxPeers) {
24
- console.log(`No eviction needed: ${totalPeerCount}/${this.mesh.maxPeers} peers`);
25
- return null;
26
- }
28
+ // Special case: if we have 0 connected peers (isolated), be very aggressive about making room
29
+ const connectedCount = this.connectionManager.getConnectedPeerCount();
30
+ if (connectedCount === 0) {
31
+ console.log(`Isolated peer scenario: finding any peer to evict for ${newPeerId.substring(0, 8)}...`);
32
+ // Find any peer to evict (even connecting ones) to make room for this connection
33
+ const anyPeerId = Array.from(this.connectionManager.peers.keys())[0];
34
+ if (anyPeerId) {
35
+ console.log(`Will evict any peer ${anyPeerId.substring(0, 8)}... to escape isolation for ${newPeerId.substring(0, 8)}...`);
36
+ return anyPeerId;
37
+ }
38
+ }
27
39
 
28
- // Special case: if we have 0 connected peers (isolated), be very aggressive about making room
29
- const connectedCount = this.connectionManager.getConnectedPeerCount();
30
- if (connectedCount === 0) {
31
- console.log(`Isolated peer scenario: finding any peer to evict for ${newPeerId.substring(0, 8)}...`);
32
- // Find any peer to evict (even connecting ones) to make room for this connection
33
- const anyPeerId = Array.from(this.connectionManager.peers.keys())[0];
34
- if (anyPeerId) {
35
- console.log(`Will evict any peer ${anyPeerId.substring(0, 8)}... to escape isolation for ${newPeerId.substring(0, 8)}...`);
36
- return anyPeerId;
37
- }
38
- }
40
+ // If XOR routing is enabled, use distance-based eviction
41
+ if (this.mesh.xorRouting) {
42
+ const newPeerDistance = this.calculateXorDistance(this.mesh.peerId, newPeerId);
43
+ const farthestPeerId = this.findFarthestPeer();
39
44
 
40
- // If XOR routing is enabled, use distance-based eviction
41
- if (this.mesh.xorRouting) {
42
- const newPeerDistance = this.calculateXorDistance(this.mesh.peerId, newPeerId);
43
- const farthestPeerId = this.findFarthestPeer();
44
-
45
- if (!farthestPeerId) {
46
- console.log(`No eviction candidate found (no peers to evict)`);
47
- return null;
48
- }
45
+ if (!farthestPeerId) {
46
+ console.log('No eviction candidate found (no peers to evict)');
47
+ return null;
48
+ }
49
49
 
50
- const farthestDistance = this.calculateXorDistance(this.mesh.peerId, farthestPeerId);
50
+ const farthestDistance = this.calculateXorDistance(this.mesh.peerId, farthestPeerId);
51
51
 
52
- console.log(`Eviction check: new peer ${newPeerId.substring(0, 8)}... (distance: ${newPeerDistance.toString(16).substring(0, 8)}) vs farthest ${farthestPeerId.substring(0, 8)}... (distance: ${farthestDistance.toString(16).substring(0, 8)})`);
52
+ console.log(`Eviction check: new peer ${newPeerId.substring(0, 8)}... (distance: ${newPeerDistance.toString(16).substring(0, 8)}) vs farthest ${farthestPeerId.substring(0, 8)}... (distance: ${farthestDistance.toString(16).substring(0, 8)})`);
53
53
 
54
- // LOOSENED RULE: If we're at max capacity, always try to evict the farthest peer
55
- // even if the new peer isn't strictly closer (helps with network connectivity)
56
- const shouldEvict = newPeerDistance < farthestDistance ||
54
+ // LOOSENED RULE: If we're at max capacity, always try to evict the farthest peer
55
+ // even if the new peer isn't strictly closer (helps with network connectivity)
56
+ const shouldEvict = newPeerDistance < farthestDistance ||
57
57
  (totalPeerCount >= this.mesh.maxPeers && connectedCount < this.mesh.minPeers);
58
58
 
59
- if (shouldEvict) {
60
- console.log(`Will evict ${farthestPeerId.substring(0, 8)}... for ${newPeerDistance < farthestDistance ? 'closer' : 'network connectivity'} peer ${newPeerId.substring(0, 8)}... (${totalPeerCount}/${this.mesh.maxPeers} peers)`);
61
- return farthestPeerId;
62
- }
63
-
64
- console.log(`Not evicting for ${newPeerId.substring(0, 8)}... - criteria not met (${totalPeerCount}/${this.mesh.maxPeers} peers)`);
65
- return null;
66
- } else {
67
- // If XOR routing is disabled, use simple FIFO eviction - evict oldest peer
68
- console.log(`XOR routing disabled - using FIFO eviction for ${newPeerId.substring(0, 8)}...`);
69
- const oldestPeerId = this.findOldestPeer();
70
- if (oldestPeerId) {
71
- console.log(`Will evict oldest peer ${oldestPeerId.substring(0, 8)}... for new peer ${newPeerId.substring(0, 8)}... (${totalPeerCount}/${this.mesh.maxPeers} peers)`);
72
- return oldestPeerId;
73
- }
74
-
75
- console.log(`No eviction candidate found (no peers to evict)`);
76
- return null;
77
- }
59
+ if (shouldEvict) {
60
+ console.log(`Will evict ${farthestPeerId.substring(0, 8)}... for ${newPeerDistance < farthestDistance ? 'closer' : 'network connectivity'} peer ${newPeerId.substring(0, 8)}... (${totalPeerCount}/${this.mesh.maxPeers} peers)`);
61
+ return farthestPeerId;
62
+ }
63
+
64
+ console.log(`Not evicting for ${newPeerId.substring(0, 8)}... - criteria not met (${totalPeerCount}/${this.mesh.maxPeers} peers)`);
65
+ return null;
66
+ } else {
67
+ // If XOR routing is disabled, use simple FIFO eviction - evict oldest peer
68
+ console.log(`XOR routing disabled - using FIFO eviction for ${newPeerId.substring(0, 8)}...`);
69
+ const oldestPeerId = this.findOldestPeer();
70
+ if (oldestPeerId) {
71
+ console.log(`Will evict oldest peer ${oldestPeerId.substring(0, 8)}... for new peer ${newPeerId.substring(0, 8)}... (${totalPeerCount}/${this.mesh.maxPeers} peers)`);
72
+ return oldestPeerId;
73
+ }
74
+
75
+ console.log('No eviction candidate found (no peers to evict)');
76
+ return null;
78
77
  }
78
+ }
79
79
 
80
- async evictPeer(peerId, reason = 'topology optimization') {
81
- const peerConnection = this.connectionManager.getPeer(peerId);
82
- if (!peerConnection) {
83
- console.log(`Cannot evict ${peerId.substring(0, 8)}... - peer not found`);
84
- return;
85
- }
86
-
87
- console.log(`Evicting ${peerId.substring(0, 8)}... (${reason})`);
88
-
89
- // Send eviction notice
90
- try {
91
- peerConnection.sendMessage({
92
- type: 'eviction',
93
- reason: reason,
94
- from: this.mesh.peerId
95
- });
96
- } catch (error) {
97
- console.log('Failed to send eviction notice:', error.message);
98
- }
99
-
100
- // Close connection and clean up
101
- peerConnection.close();
102
- this.connectionManager.peers.delete(peerId);
103
- this.mesh.peerDiscovery.clearConnectionAttempt(peerId);
104
-
105
- this.mesh.emit('peerDisconnected', { peerId, reason: `evicted: ${reason}` });
106
- this.connectionManager.emit('peersUpdated');
80
+ async evictPeer(peerId, reason = 'topology optimization') {
81
+ const peerConnection = this.connectionManager.getPeer(peerId);
82
+ if (!peerConnection) {
83
+ console.log(`Cannot evict ${peerId.substring(0, 8)}... - peer not found`);
84
+ return;
107
85
  }
108
86
 
109
- handleEvictionNotice(message, fromPeerId) {
110
- console.log(`Evicted by ${fromPeerId.substring(0, 8)}... (${message.reason})`);
111
-
112
- // Clean up the connection
113
- this.connectionManager.peers.delete(fromPeerId);
114
- this.mesh.peerDiscovery.clearConnectionAttempt(fromPeerId);
115
-
116
- this.mesh.emit('peerEvicted', { fromPeerId, reason: message.reason });
117
- this.connectionManager.emit('peersUpdated');
118
-
119
- // The evicted peer will naturally discover other peers and connect to those it's closer to
120
- // No complex reconnection logic needed - let peer discovery handle it
87
+ console.log(`Evicting ${peerId.substring(0, 8)}... (${reason})`);
88
+
89
+ // Send eviction notice
90
+ try {
91
+ peerConnection.sendMessage({
92
+ type: 'eviction',
93
+ reason,
94
+ from: this.mesh.peerId
95
+ });
96
+ } catch (error) {
97
+ console.log('Failed to send eviction notice:', error.message);
121
98
  }
122
99
 
123
- calculateXorDistance(peerId1, peerId2) {
124
- let distance = 0n;
125
- for (let i = 0; i < Math.min(peerId1.length, peerId2.length); i += 2) {
126
- const byte1 = parseInt(peerId1.substr(i, 2), 16);
127
- const byte2 = parseInt(peerId2.substr(i, 2), 16);
128
- const xor = byte1 ^ byte2;
129
- distance = (distance << 8n) | BigInt(xor);
130
- }
131
- return distance;
100
+ // Close connection and clean up
101
+ peerConnection.close();
102
+ this.connectionManager.peers.delete(peerId);
103
+ this.mesh.peerDiscovery.clearConnectionAttempt(peerId);
104
+
105
+ this.mesh.emit('peerDisconnected', { peerId, reason: `evicted: ${reason}` });
106
+ this.connectionManager.emit('peersUpdated');
107
+ }
108
+
109
+ handleEvictionNotice(message, fromPeerId) {
110
+ console.log(`Evicted by ${fromPeerId.substring(0, 8)}... (${message.reason})`);
111
+
112
+ // Clean up the connection
113
+ this.connectionManager.peers.delete(fromPeerId);
114
+ this.mesh.peerDiscovery.clearConnectionAttempt(fromPeerId);
115
+
116
+ this.mesh.emit('peerEvicted', { fromPeerId, reason: message.reason });
117
+ this.connectionManager.emit('peersUpdated');
118
+
119
+ // The evicted peer will naturally discover other peers and connect to those it's closer to
120
+ // No complex reconnection logic needed - let peer discovery handle it
121
+ }
122
+
123
+ calculateXorDistance(peerId1, peerId2) {
124
+ let distance = 0n;
125
+ for (let i = 0; i < Math.min(peerId1.length, peerId2.length); i += 2) {
126
+ const byte1 = parseInt(peerId1.substr(i, 2), 16);
127
+ const byte2 = parseInt(peerId2.substr(i, 2), 16);
128
+ const xor = byte1 ^ byte2;
129
+ distance = (distance << 8n) | BigInt(xor);
132
130
  }
131
+ return distance;
132
+ }
133
133
 
134
- findFarthestPeer() {
135
- if (this.connectionManager.peers.size === 0) {
136
- console.log(`No peers available for eviction`);
137
- return null;
138
- }
134
+ findFarthestPeer() {
135
+ if (this.connectionManager.peers.size === 0) {
136
+ console.log('No peers available for eviction');
137
+ return null;
138
+ }
139
139
 
140
- let farthestPeer = null;
141
- let maxDistance = 0n;
142
- let candidateCount = 0;
140
+ let farthestPeer = null;
141
+ let maxDistance = 0n;
142
+ let candidateCount = 0;
143
143
 
144
- this.connectionManager.peers.forEach((peerConnection, peerId) => {
145
- const status = peerConnection.getStatus();
146
- // LOOSENED: Accept more peer states as eviction candidates
147
- if (status === 'connected' ||
148
- status === 'channel-connecting' ||
144
+ this.connectionManager.peers.forEach((peerConnection, peerId) => {
145
+ const status = peerConnection.getStatus();
146
+ // LOOSENED: Accept more peer states as eviction candidates
147
+ if (status === 'connected' ||
148
+ status === 'channel-connecting' ||
149
149
  status === 'connecting' ||
150
150
  status === 'channel-open') {
151
- candidateCount++;
152
- const distance = this.calculateXorDistance(this.mesh.peerId, peerId);
153
- if (distance > maxDistance) {
154
- maxDistance = distance;
155
- farthestPeer = peerId;
156
- }
157
- }
158
- });
159
-
160
- // FALLBACK: If no candidates found with strict criteria, try ANY peer
161
- if (!farthestPeer && this.connectionManager.peers.size > 0) {
162
- console.log(`No eviction candidates with connected/connecting status, trying any peer...`);
163
- this.connectionManager.peers.forEach((peerConnection, peerId) => {
164
- candidateCount++;
165
- const distance = this.calculateXorDistance(this.mesh.peerId, peerId);
166
- if (distance > maxDistance) {
167
- maxDistance = distance;
168
- farthestPeer = peerId;
169
- }
170
- });
151
+ candidateCount++;
152
+ const distance = this.calculateXorDistance(this.mesh.peerId, peerId);
153
+ if (distance > maxDistance) {
154
+ maxDistance = distance;
155
+ farthestPeer = peerId;
171
156
  }
172
-
173
- if (farthestPeer) {
174
- console.log(`Found farthest peer for eviction: ${farthestPeer.substring(0, 8)}... (distance: ${maxDistance.toString(16).substring(0, 8)}, ${candidateCount} candidate peers)`);
175
- } else {
176
- console.log(`No peers available for eviction (${candidateCount} candidate peers)`);
157
+ }
158
+ });
159
+
160
+ // FALLBACK: If no candidates found with strict criteria, try ANY peer
161
+ if (!farthestPeer && this.connectionManager.peers.size > 0) {
162
+ console.log('No eviction candidates with connected/connecting status, trying any peer...');
163
+ this.connectionManager.peers.forEach((peerConnection, peerId) => {
164
+ candidateCount++;
165
+ const distance = this.calculateXorDistance(this.mesh.peerId, peerId);
166
+ if (distance > maxDistance) {
167
+ maxDistance = distance;
168
+ farthestPeer = peerId;
177
169
  }
170
+ });
171
+ }
178
172
 
179
- return farthestPeer;
173
+ if (farthestPeer) {
174
+ console.log(`Found farthest peer for eviction: ${farthestPeer.substring(0, 8)}... (distance: ${maxDistance.toString(16).substring(0, 8)}, ${candidateCount} candidate peers)`);
175
+ } else {
176
+ console.log(`No peers available for eviction (${candidateCount} candidate peers)`);
180
177
  }
181
178
 
182
- findOldestPeer() {
183
- if (this.connectionManager.peers.size === 0) {
184
- console.log(`No peers available for FIFO eviction`);
185
- return null;
186
- }
179
+ return farthestPeer;
180
+ }
187
181
 
188
- let oldestPeer = null;
189
- let oldestTime = Date.now();
190
- let candidateCount = 0;
182
+ findOldestPeer() {
183
+ if (this.connectionManager.peers.size === 0) {
184
+ console.log('No peers available for FIFO eviction');
185
+ return null;
186
+ }
187
+
188
+ let oldestPeer = null;
189
+ let oldestTime = Date.now();
190
+ let candidateCount = 0;
191
191
 
192
- this.connectionManager.peers.forEach((peerConnection, peerId) => {
193
- const status = peerConnection.getStatus();
194
- // LOOSENED: Accept more peer states as eviction candidates
195
- if (status === 'connected' ||
196
- status === 'channel-connecting' ||
192
+ this.connectionManager.peers.forEach((peerConnection, peerId) => {
193
+ const status = peerConnection.getStatus();
194
+ // LOOSENED: Accept more peer states as eviction candidates
195
+ if (status === 'connected' ||
196
+ status === 'channel-connecting' ||
197
197
  status === 'connecting' ||
198
198
  status === 'channel-open') {
199
- candidateCount++;
200
- const connectionTime = peerConnection.connectionStartTime || Date.now();
201
- if (connectionTime < oldestTime) {
202
- oldestTime = connectionTime;
203
- oldestPeer = peerId;
204
- }
205
- }
206
- });
207
-
208
- // FALLBACK: If no candidates found with strict criteria, try ANY peer
209
- if (!oldestPeer && this.connectionManager.peers.size > 0) {
210
- console.log(`No FIFO eviction candidates with connected/connecting status, trying any peer...`);
211
- this.connectionManager.peers.forEach((peerConnection, peerId) => {
212
- candidateCount++;
213
- const connectionTime = peerConnection.connectionStartTime || Date.now();
214
- if (connectionTime < oldestTime) {
215
- oldestTime = connectionTime;
216
- oldestPeer = peerId;
217
- }
218
- });
199
+ candidateCount++;
200
+ const connectionTime = peerConnection.connectionStartTime || Date.now();
201
+ if (connectionTime < oldestTime) {
202
+ oldestTime = connectionTime;
203
+ oldestPeer = peerId;
219
204
  }
220
-
221
- if (oldestPeer) {
222
- console.log(`Found oldest peer for eviction: ${oldestPeer.substring(0, 8)}... (connected at: ${new Date(oldestTime).toLocaleTimeString()}, ${candidateCount} candidates)`);
223
- } else {
224
- console.log(`No peers available for FIFO eviction (${candidateCount} candidates)`);
205
+ }
206
+ });
207
+
208
+ // FALLBACK: If no candidates found with strict criteria, try ANY peer
209
+ if (!oldestPeer && this.connectionManager.peers.size > 0) {
210
+ console.log('No FIFO eviction candidates with connected/connecting status, trying any peer...');
211
+ this.connectionManager.peers.forEach((peerConnection, peerId) => {
212
+ candidateCount++;
213
+ const connectionTime = peerConnection.connectionStartTime || Date.now();
214
+ if (connectionTime < oldestTime) {
215
+ oldestTime = connectionTime;
216
+ oldestPeer = peerId;
225
217
  }
226
-
227
- return oldestPeer;
218
+ });
228
219
  }
229
220
 
230
- disconnectExcessPeers() {
231
- if (this.connectionManager.peers.size <= this.mesh.maxPeers) return;
232
-
233
- const peerEntries = Array.from(this.connectionManager.peers.entries())
234
- .filter(([_, peerConnection]) => peerConnection.connectionStartTime)
235
- .sort((a, b) => a[1].connectionStartTime - b[1].connectionStartTime);
236
-
237
- const toDisconnect = peerEntries.slice(0, this.connectionManager.peers.size - this.mesh.maxPeers);
238
-
239
- toDisconnect.forEach(([peerId, peerConnection]) => {
240
- console.log(`Disconnecting ${peerId.substring(0, 8)}... (over max peers limit)`);
241
- peerConnection.close();
242
- this.connectionManager.peers.delete(peerId);
243
- this.mesh.peerDiscovery.clearConnectionAttempt(peerId);
244
- this.mesh.emit('peerDisconnected', { peerId, reason: 'over max peers limit' });
245
- });
246
-
247
- this.connectionManager.emit('peersUpdated');
221
+ if (oldestPeer) {
222
+ console.log(`Found oldest peer for eviction: ${oldestPeer.substring(0, 8)}... (connected at: ${new Date(oldestTime).toLocaleTimeString()}, ${candidateCount} candidates)`);
223
+ } else {
224
+ console.log(`No peers available for FIFO eviction (${candidateCount} candidates)`);
248
225
  }
249
226
 
250
- clearEvictionTracking(peerId) {
251
- // No eviction tracking in simplified system
252
- }
227
+ return oldestPeer;
228
+ }
253
229
 
254
- cleanup() {
255
- // Simple cleanup - no complex state to manage
256
- }
230
+ disconnectExcessPeers() {
231
+ if (this.connectionManager.peers.size <= this.mesh.maxPeers) return;
232
+
233
+ const peerEntries = Array.from(this.connectionManager.peers.entries())
234
+ .filter(([_, peerConnection]) => peerConnection.connectionStartTime)
235
+ .sort((a, b) => a[1].connectionStartTime - b[1].connectionStartTime);
236
+
237
+ const toDisconnect = peerEntries.slice(0, this.connectionManager.peers.size - this.mesh.maxPeers);
238
+
239
+ toDisconnect.forEach(([peerId, peerConnection]) => {
240
+ console.log(`Disconnecting ${peerId.substring(0, 8)}... (over max peers limit)`);
241
+ peerConnection.close();
242
+ this.connectionManager.peers.delete(peerId);
243
+ this.mesh.peerDiscovery.clearConnectionAttempt(peerId);
244
+ this.mesh.emit('peerDisconnected', { peerId, reason: 'over max peers limit' });
245
+ });
246
+
247
+ this.connectionManager.emit('peersUpdated');
248
+ }
249
+
250
+ clearEvictionTracking(_peerId) {
251
+ // No eviction tracking in simplified system
252
+ }
253
+
254
+ cleanup() {
255
+ // Simple cleanup - no complex state to manage
256
+ }
257
257
  }