peerpigeon 0.0.8 → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +34 -0
- package/examples/browser/index.html +104 -16
- package/examples/browser/ui.js +381 -0
- package/examples/debug-configuration.js +171 -0
- package/examples/node/storage-spaces-test.js +329 -0
- package/examples/node/storage-test.js +141 -6
- package/index.js +3 -0
- package/package.json +13 -8
- package/server/index.js +12 -12
- package/src/CleanupManager.js +20 -18
- package/src/ConnectionManager.js +407 -102
- package/src/CryptoManager.js +28 -26
- package/src/DebugLogger.js +211 -0
- package/src/DistributedStorageManager.js +490 -102
- package/src/EnvironmentDetector.js +3 -1
- package/src/EventEmitter.js +1 -0
- package/src/EvictionManager.js +26 -24
- package/src/GossipManager.js +69 -33
- package/src/LexicalStorageInterface.js +332 -0
- package/src/MediaManager.js +12 -10
- package/src/MeshOptimizer.js +30 -28
- package/src/PeerConnection.js +621 -159
- package/src/PeerDiscovery.js +19 -17
- package/src/PeerPigeonMesh.js +241 -33
- package/src/SignalingClient.js +59 -44
- package/src/SignalingHandler.js +280 -51
- package/src/StorageManager.js +7 -5
- package/src/TimerUtils.js +1 -0
- package/src/WebDHT.js +125 -123
- package/websocket-server/server.js +31 -103
|
@@ -0,0 +1,332 @@
|
|
|
1
|
+
import { EventEmitter } from './EventEmitter.js';
|
|
2
|
+
import DebugLogger from './DebugLogger.js';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Lexical Storage Interface - GUN-like chaining API for DistributedStorageManager
|
|
6
|
+
*
|
|
7
|
+
* Usage:
|
|
8
|
+
* const user = storage.get('users').get('alice');
|
|
9
|
+
* await user.put({name: 'Alice', age: 30});
|
|
10
|
+
* const name = await user.get('name').val();
|
|
11
|
+
*
|
|
12
|
+
* user.get('friends').set({bob: true, charlie: true});
|
|
13
|
+
* user.get('friends').map().on((friend, key) => console.log(key, friend));
|
|
14
|
+
*/
|
|
15
|
+
export class LexicalStorageInterface extends EventEmitter {
|
|
16
|
+
constructor(distributedStorage, path = []) {
|
|
17
|
+
super();
|
|
18
|
+
this.debug = DebugLogger.create('LexicalStorageInterface');
|
|
19
|
+
this.storage = distributedStorage;
|
|
20
|
+
this.path = path.slice(); // Create a copy of the path
|
|
21
|
+
this.subscriptions = new Map();
|
|
22
|
+
this._isMap = false;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Navigate to a key (creates a new interface instance)
|
|
27
|
+
* @param {string} key - The key to navigate to
|
|
28
|
+
* @returns {LexicalStorageInterface} New interface for the key
|
|
29
|
+
*/
|
|
30
|
+
get(key) {
|
|
31
|
+
const newInterface = new LexicalStorageInterface(this.storage, [...this.path, key]);
|
|
32
|
+
return newInterface;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Store data at the current path
|
|
37
|
+
* @param {any} value - Value to store
|
|
38
|
+
* @param {Object} options - Storage options
|
|
39
|
+
* @returns {Promise<LexicalStorageInterface>} This interface for chaining
|
|
40
|
+
*/
|
|
41
|
+
async put(value, options = {}) {
|
|
42
|
+
const fullKey = this.path.join(':');
|
|
43
|
+
|
|
44
|
+
if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
|
|
45
|
+
// For objects, store each property as a separate key
|
|
46
|
+
const promises = Object.entries(value).map(([prop, val]) => {
|
|
47
|
+
const propKey = `${fullKey}:${prop}`;
|
|
48
|
+
return this.storage.store(propKey, val, options);
|
|
49
|
+
});
|
|
50
|
+
await Promise.all(promises);
|
|
51
|
+
|
|
52
|
+
// Also store the object structure for reference
|
|
53
|
+
await this.storage.store(fullKey, { _keys: Object.keys(value), _type: 'object' }, options);
|
|
54
|
+
} else {
|
|
55
|
+
// For primitives, store directly
|
|
56
|
+
await this.storage.store(fullKey, value, options);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
// Emit change event
|
|
60
|
+
this.emit('put', { key: fullKey, value });
|
|
61
|
+
|
|
62
|
+
return this;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Retrieve the current value
|
|
67
|
+
* @param {Object} options - Retrieval options
|
|
68
|
+
* @returns {Promise<any>} The stored value
|
|
69
|
+
*/
|
|
70
|
+
async val(options = {}) {
|
|
71
|
+
const fullKey = this.path.join(':');
|
|
72
|
+
const value = await this.storage.retrieve(fullKey, options);
|
|
73
|
+
|
|
74
|
+
// If it's an object structure, reconstruct it
|
|
75
|
+
if (value && typeof value === 'object' && value._keys && value._type === 'object') {
|
|
76
|
+
const reconstructed = {};
|
|
77
|
+
const promises = value._keys.map(async (key) => {
|
|
78
|
+
const keyValue = await this.storage.retrieve(`${fullKey}:${key}`, options);
|
|
79
|
+
reconstructed[key] = keyValue;
|
|
80
|
+
});
|
|
81
|
+
await Promise.all(promises);
|
|
82
|
+
return reconstructed;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
return value;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Set multiple key-value pairs (like GUN's set)
|
|
90
|
+
* @param {Object} obj - Object with key-value pairs to set
|
|
91
|
+
* @param {Object} options - Storage options
|
|
92
|
+
* @returns {Promise<LexicalStorageInterface>} This interface for chaining
|
|
93
|
+
*/
|
|
94
|
+
async set(obj, options = {}) {
|
|
95
|
+
const fullKey = this.path.join(':');
|
|
96
|
+
|
|
97
|
+
// Store each entry with a unique ID
|
|
98
|
+
const promises = Object.entries(obj).map(([key, value]) => {
|
|
99
|
+
const setKey = `${fullKey}:${key}`;
|
|
100
|
+
return this.storage.store(setKey, value, options);
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
await Promise.all(promises);
|
|
104
|
+
|
|
105
|
+
// Update the set index
|
|
106
|
+
const existingSet = await this.storage.retrieve(`${fullKey}:_set`) || {};
|
|
107
|
+
const updatedSet = { ...existingSet, ...obj };
|
|
108
|
+
await this.storage.store(`${fullKey}:_set`, updatedSet, options);
|
|
109
|
+
|
|
110
|
+
// Emit set event
|
|
111
|
+
this.emit('set', { key: fullKey, values: obj });
|
|
112
|
+
|
|
113
|
+
return this;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* Map over a set (like GUN's map)
|
|
118
|
+
* @returns {LexicalStorageInterface} New interface for mapping
|
|
119
|
+
*/
|
|
120
|
+
map() {
|
|
121
|
+
const mapInterface = new LexicalStorageInterface(this.storage, this.path);
|
|
122
|
+
mapInterface._isMap = true;
|
|
123
|
+
return mapInterface;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* Subscribe to changes (like GUN's on)
|
|
128
|
+
* @param {Function} callback - Callback for changes
|
|
129
|
+
* @returns {Function} Unsubscribe function
|
|
130
|
+
*/
|
|
131
|
+
on(callback) {
|
|
132
|
+
const fullKey = this.path.join(':');
|
|
133
|
+
|
|
134
|
+
if (this._isMap) {
|
|
135
|
+
// For maps, listen to set changes
|
|
136
|
+
const setKey = `${fullKey}:_set`;
|
|
137
|
+
|
|
138
|
+
const handleChange = async () => {
|
|
139
|
+
const setData = await this.storage.retrieve(setKey);
|
|
140
|
+
if (setData) {
|
|
141
|
+
Object.entries(setData).forEach(([key, value]) => {
|
|
142
|
+
callback(value, key);
|
|
143
|
+
});
|
|
144
|
+
}
|
|
145
|
+
};
|
|
146
|
+
|
|
147
|
+
// Subscribe to the set key using storage's subscription mechanism
|
|
148
|
+
if (this.storage.subscribe) {
|
|
149
|
+
this.storage.subscribe(setKey).then(() => {
|
|
150
|
+
this.storage.on('dataUpdated', (event) => {
|
|
151
|
+
if (event.key === setKey) {
|
|
152
|
+
handleChange();
|
|
153
|
+
}
|
|
154
|
+
});
|
|
155
|
+
});
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
// Initial call
|
|
159
|
+
handleChange();
|
|
160
|
+
|
|
161
|
+
return () => {
|
|
162
|
+
if (this.storage.unsubscribe) {
|
|
163
|
+
this.storage.unsubscribe(setKey);
|
|
164
|
+
}
|
|
165
|
+
};
|
|
166
|
+
} else {
|
|
167
|
+
// For regular keys, listen to direct changes
|
|
168
|
+
if (this.storage.subscribe) {
|
|
169
|
+
this.storage.subscribe(fullKey).then((currentValue) => {
|
|
170
|
+
callback(currentValue, fullKey);
|
|
171
|
+
});
|
|
172
|
+
|
|
173
|
+
this.storage.on('dataUpdated', (event) => {
|
|
174
|
+
if (event.key === fullKey) {
|
|
175
|
+
this.storage.retrieve(fullKey).then(value => {
|
|
176
|
+
callback(value, fullKey);
|
|
177
|
+
});
|
|
178
|
+
}
|
|
179
|
+
});
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
return () => {
|
|
183
|
+
if (this.storage.unsubscribe) {
|
|
184
|
+
this.storage.unsubscribe(fullKey);
|
|
185
|
+
}
|
|
186
|
+
};
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/**
|
|
191
|
+
* Once - listen for a single change
|
|
192
|
+
* @param {Function} callback - Callback for the change
|
|
193
|
+
* @returns {Promise} Promise that resolves with the value
|
|
194
|
+
*/
|
|
195
|
+
async once(callback) {
|
|
196
|
+
return new Promise((resolve) => {
|
|
197
|
+
const unsubscribe = this.on((value, key) => {
|
|
198
|
+
if (callback) callback(value, key);
|
|
199
|
+
unsubscribe();
|
|
200
|
+
resolve(value);
|
|
201
|
+
});
|
|
202
|
+
});
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/**
|
|
206
|
+
* Delete the current path
|
|
207
|
+
* @returns {Promise<boolean>} Success status
|
|
208
|
+
*/
|
|
209
|
+
async delete() {
|
|
210
|
+
const fullKey = this.path.join(':');
|
|
211
|
+
|
|
212
|
+
// If it's an object, delete all its properties first
|
|
213
|
+
const value = await this.storage.retrieve(fullKey);
|
|
214
|
+
if (value && typeof value === 'object' && value._keys && value._type === 'object') {
|
|
215
|
+
const deletePromises = value._keys.map(key => {
|
|
216
|
+
const propKey = `${fullKey}:${key}`;
|
|
217
|
+
return this.storage.delete(propKey);
|
|
218
|
+
});
|
|
219
|
+
await Promise.all(deletePromises);
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
const result = await this.storage.delete(fullKey);
|
|
223
|
+
|
|
224
|
+
// Emit delete event
|
|
225
|
+
this.emit('delete', { key: fullKey });
|
|
226
|
+
|
|
227
|
+
return result;
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
/**
|
|
231
|
+
* Update with merge semantics
|
|
232
|
+
* @param {any} value - Value to merge
|
|
233
|
+
* @param {Object} options - Update options
|
|
234
|
+
* @returns {Promise<LexicalStorageInterface>} This interface for chaining
|
|
235
|
+
*/
|
|
236
|
+
async update(value, options = {}) {
|
|
237
|
+
const fullKey = this.path.join(':');
|
|
238
|
+
const currentValue = await this.storage.retrieve(fullKey);
|
|
239
|
+
|
|
240
|
+
let mergedValue;
|
|
241
|
+
if (typeof value === 'object' && value !== null && !Array.isArray(value) &&
|
|
242
|
+
typeof currentValue === 'object' && currentValue !== null && !Array.isArray(currentValue)) {
|
|
243
|
+
// Handle object reconstruction first
|
|
244
|
+
if (currentValue._keys && currentValue._type === 'object') {
|
|
245
|
+
const reconstructed = {};
|
|
246
|
+
const promises = currentValue._keys.map(async (key) => {
|
|
247
|
+
const keyValue = await this.storage.retrieve(`${fullKey}:${key}`, options);
|
|
248
|
+
reconstructed[key] = keyValue;
|
|
249
|
+
});
|
|
250
|
+
await Promise.all(promises);
|
|
251
|
+
mergedValue = { ...reconstructed, ...value };
|
|
252
|
+
} else {
|
|
253
|
+
mergedValue = { ...currentValue, ...value };
|
|
254
|
+
}
|
|
255
|
+
} else {
|
|
256
|
+
mergedValue = value;
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
// Use put instead of update to ensure proper object decomposition
|
|
260
|
+
await this.put(mergedValue, options);
|
|
261
|
+
|
|
262
|
+
// Emit update event
|
|
263
|
+
this.emit('update', { key: fullKey, value: mergedValue });
|
|
264
|
+
|
|
265
|
+
return this;
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/**
|
|
269
|
+
* Create a proxied interface that allows property access
|
|
270
|
+
* @returns {Proxy} Proxied interface
|
|
271
|
+
*/
|
|
272
|
+
proxy() {
|
|
273
|
+
return new Proxy(this, {
|
|
274
|
+
get(target, prop) {
|
|
275
|
+
// If it's a method, return it bound
|
|
276
|
+
if (typeof target[prop] === 'function') {
|
|
277
|
+
return target[prop].bind(target);
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
// If it's a property access, create a new get() call
|
|
281
|
+
if (typeof prop === 'string' && !prop.startsWith('_') && prop !== 'constructor') {
|
|
282
|
+
return target.get(prop).proxy();
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
return target[prop];
|
|
286
|
+
}
|
|
287
|
+
});
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
/**
|
|
291
|
+
* Get the current path as a string
|
|
292
|
+
* @returns {string} The path
|
|
293
|
+
*/
|
|
294
|
+
getPath() {
|
|
295
|
+
return this.path.join(':');
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
/**
|
|
299
|
+
* Check if a value exists at the current path
|
|
300
|
+
* @returns {Promise<boolean>} Whether the value exists
|
|
301
|
+
*/
|
|
302
|
+
async exists() {
|
|
303
|
+
const fullKey = this.path.join(':');
|
|
304
|
+
const value = await this.storage.retrieve(fullKey);
|
|
305
|
+
return value !== null && value !== undefined;
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
/**
|
|
309
|
+
* Get all keys under the current path (for object-like structures)
|
|
310
|
+
* @returns {Promise<string[]>} Array of keys
|
|
311
|
+
*/
|
|
312
|
+
async keys() {
|
|
313
|
+
const fullKey = this.path.join(':');
|
|
314
|
+
const value = await this.storage.retrieve(fullKey);
|
|
315
|
+
|
|
316
|
+
if (value && typeof value === 'object' && value._keys && value._type === 'object') {
|
|
317
|
+
return value._keys;
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
return [];
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
/**
|
|
325
|
+
* Create a lexical interface for the distributed storage
|
|
326
|
+
* @param {DistributedStorageManager} distributedStorage
|
|
327
|
+
* @returns {Proxy} Proxied lexical interface
|
|
328
|
+
*/
|
|
329
|
+
export function createLexicalInterface(distributedStorage) {
|
|
330
|
+
const lexicalInterface = new LexicalStorageInterface(distributedStorage);
|
|
331
|
+
return lexicalInterface.proxy();
|
|
332
|
+
}
|
package/src/MediaManager.js
CHANGED
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
import { EventEmitter } from './EventEmitter.js';
|
|
2
2
|
import { environmentDetector } from './EnvironmentDetector.js';
|
|
3
|
+
import DebugLogger from './DebugLogger.js';
|
|
3
4
|
|
|
4
5
|
export class MediaManager extends EventEmitter {
|
|
5
6
|
constructor() {
|
|
6
7
|
super();
|
|
8
|
+
this.debug = DebugLogger.create('MediaManager');
|
|
7
9
|
this.localStream = null;
|
|
8
10
|
this.isVideoEnabled = false;
|
|
9
11
|
this.isAudioEnabled = false;
|
|
@@ -33,7 +35,7 @@ export class MediaManager extends EventEmitter {
|
|
|
33
35
|
async init() {
|
|
34
36
|
// Check if media APIs are available
|
|
35
37
|
if (!environmentDetector.hasGetUserMedia) {
|
|
36
|
-
|
|
38
|
+
this.debug.warn('getUserMedia not available in this environment');
|
|
37
39
|
this.emit('error', { type: 'init', error: new Error('getUserMedia not supported') });
|
|
38
40
|
return false;
|
|
39
41
|
}
|
|
@@ -43,7 +45,7 @@ export class MediaManager extends EventEmitter {
|
|
|
43
45
|
await this.enumerateDevices();
|
|
44
46
|
return true;
|
|
45
47
|
} catch (error) {
|
|
46
|
-
|
|
48
|
+
this.debug.error('Failed to initialize media manager:', error);
|
|
47
49
|
this.emit('error', { type: 'init', error });
|
|
48
50
|
return false;
|
|
49
51
|
}
|
|
@@ -57,7 +59,7 @@ export class MediaManager extends EventEmitter {
|
|
|
57
59
|
if ((!environmentDetector.isBrowser && !environmentDetector.isNativeScript) ||
|
|
58
60
|
typeof navigator === 'undefined' ||
|
|
59
61
|
typeof navigator.mediaDevices === 'undefined') {
|
|
60
|
-
|
|
62
|
+
this.debug.warn('Media device enumeration not available in this environment');
|
|
61
63
|
return;
|
|
62
64
|
}
|
|
63
65
|
|
|
@@ -71,7 +73,7 @@ export class MediaManager extends EventEmitter {
|
|
|
71
73
|
this.emit('devicesUpdated', this.devices);
|
|
72
74
|
return this.devices;
|
|
73
75
|
} catch (error) {
|
|
74
|
-
|
|
76
|
+
this.debug.error('Failed to enumerate devices:', error);
|
|
75
77
|
this.emit('error', { type: 'enumerate', error });
|
|
76
78
|
throw error;
|
|
77
79
|
}
|
|
@@ -116,7 +118,7 @@ export class MediaManager extends EventEmitter {
|
|
|
116
118
|
// Mark stream as local origin to prevent confusion with remote streams
|
|
117
119
|
this.markStreamAsLocal(this.localStream);
|
|
118
120
|
|
|
119
|
-
|
|
121
|
+
this.debug.log('Local media stream started:', {
|
|
120
122
|
video: this.isVideoEnabled,
|
|
121
123
|
audio: this.isAudioEnabled,
|
|
122
124
|
tracks: this.localStream.getTracks().map(track => ({
|
|
@@ -134,7 +136,7 @@ export class MediaManager extends EventEmitter {
|
|
|
134
136
|
|
|
135
137
|
return this.localStream;
|
|
136
138
|
} catch (error) {
|
|
137
|
-
|
|
139
|
+
this.debug.error('Failed to start local media stream:', error);
|
|
138
140
|
this.emit('error', { type: 'getUserMedia', error });
|
|
139
141
|
throw error;
|
|
140
142
|
}
|
|
@@ -145,7 +147,7 @@ export class MediaManager extends EventEmitter {
|
|
|
145
147
|
*/
|
|
146
148
|
stopLocalStream() {
|
|
147
149
|
if (this.localStream) {
|
|
148
|
-
|
|
150
|
+
this.debug.log('Stopping local media stream');
|
|
149
151
|
this.localStream.getTracks().forEach(track => {
|
|
150
152
|
track.stop();
|
|
151
153
|
});
|
|
@@ -237,7 +239,7 @@ export class MediaManager extends EventEmitter {
|
|
|
237
239
|
|
|
238
240
|
return permissions;
|
|
239
241
|
} catch (error) {
|
|
240
|
-
|
|
242
|
+
this.debug.warn('Could not check media permissions:', error);
|
|
241
243
|
return {};
|
|
242
244
|
}
|
|
243
245
|
}
|
|
@@ -256,9 +258,9 @@ export class MediaManager extends EventEmitter {
|
|
|
256
258
|
configurable: false
|
|
257
259
|
});
|
|
258
260
|
|
|
259
|
-
|
|
261
|
+
this.debug.log(`🔒 Stream ${stream.id} marked as local origin in MediaManager`);
|
|
260
262
|
} catch (error) {
|
|
261
|
-
|
|
263
|
+
this.debug.warn('Could not mark stream as local origin:', error);
|
|
262
264
|
}
|
|
263
265
|
}
|
|
264
266
|
}
|
package/src/MeshOptimizer.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { EventEmitter } from './EventEmitter.js';
|
|
2
|
+
import DebugLogger from './DebugLogger.js';
|
|
2
3
|
|
|
3
4
|
/**
|
|
4
5
|
* Manages mesh optimization, connection strategies, and peer discovery optimization
|
|
@@ -6,6 +7,7 @@ import { EventEmitter } from './EventEmitter.js';
|
|
|
6
7
|
export class MeshOptimizer extends EventEmitter {
|
|
7
8
|
constructor(mesh, connectionManager, evictionManager) {
|
|
8
9
|
super();
|
|
10
|
+
this.debug = DebugLogger.create('MeshOptimizer');
|
|
9
11
|
this.mesh = mesh;
|
|
10
12
|
this.connectionManager = connectionManager;
|
|
11
13
|
this.evictionManager = evictionManager;
|
|
@@ -23,7 +25,7 @@ export class MeshOptimizer extends EventEmitter {
|
|
|
23
25
|
const belowMinimum = currentConnected < this.mesh.minPeers;
|
|
24
26
|
|
|
25
27
|
if (hasNoConnections && unconnectedPeers.length > 0) {
|
|
26
|
-
|
|
28
|
+
this.debug.log(`Peer has no connections but found ${unconnectedPeers.length} unconnected peers - forcing connection attempt`);
|
|
27
29
|
// Force connection to the closest peer by XOR distance
|
|
28
30
|
const sortedByDistance = unconnectedPeers.sort((a, b) => {
|
|
29
31
|
const distA = this.calculateXorDistance(this.mesh.peerId, a);
|
|
@@ -32,13 +34,13 @@ export class MeshOptimizer extends EventEmitter {
|
|
|
32
34
|
});
|
|
33
35
|
|
|
34
36
|
const targetPeer = sortedByDistance[0];
|
|
35
|
-
|
|
37
|
+
this.debug.log(`Forcing connection to closest peer: ${targetPeer.substring(0, 8)}... (no connections, mesh connectivity required)`);
|
|
36
38
|
this.connectionManager.connectToPeer(targetPeer);
|
|
37
39
|
return;
|
|
38
40
|
}
|
|
39
41
|
|
|
40
42
|
if (belowMinimum && unconnectedPeers.length > 0) {
|
|
41
|
-
|
|
43
|
+
this.debug.log(`Below minimum peers (${currentConnected}/${this.mesh.minPeers}) - connecting to additional peers`);
|
|
42
44
|
const needed = Math.min(this.mesh.minPeers - currentConnected, unconnectedPeers.length);
|
|
43
45
|
|
|
44
46
|
// Sort by XOR distance and connect to closest peers
|
|
@@ -50,7 +52,7 @@ export class MeshOptimizer extends EventEmitter {
|
|
|
50
52
|
|
|
51
53
|
for (let i = 0; i < needed; i++) {
|
|
52
54
|
const targetPeer = sortedByDistance[i];
|
|
53
|
-
|
|
55
|
+
this.debug.log(`Connecting to reach minimum: ${targetPeer.substring(0, 8)}...`);
|
|
54
56
|
this.connectionManager.connectToPeer(targetPeer);
|
|
55
57
|
}
|
|
56
58
|
return;
|
|
@@ -60,14 +62,14 @@ export class MeshOptimizer extends EventEmitter {
|
|
|
60
62
|
if (this.mesh.maxPeers <= 3) {
|
|
61
63
|
// For small meshes, always try to reach max capacity
|
|
62
64
|
if (currentConnected >= this.mesh.maxPeers) {
|
|
63
|
-
|
|
65
|
+
this.debug.log(`Skipping optimization - already at max capacity ${currentConnected}/${this.mesh.maxPeers}`);
|
|
64
66
|
return;
|
|
65
67
|
}
|
|
66
68
|
} else {
|
|
67
69
|
// For larger meshes, only optimize if below 70% capacity
|
|
68
70
|
const targetThreshold = Math.floor(this.mesh.maxPeers * 0.7);
|
|
69
71
|
if (currentConnected >= targetThreshold) {
|
|
70
|
-
|
|
72
|
+
this.debug.log(`Skipping optimization - ${currentConnected}/${this.mesh.maxPeers} peers connected (threshold: ${targetThreshold})`);
|
|
71
73
|
return;
|
|
72
74
|
}
|
|
73
75
|
}
|
|
@@ -75,21 +77,21 @@ export class MeshOptimizer extends EventEmitter {
|
|
|
75
77
|
const availableSlots = this.mesh.maxPeers - currentConnected;
|
|
76
78
|
const peersToConnect = unconnectedPeers.slice(0, Math.min(availableSlots, 1)); // Only connect to 1 peer at a time
|
|
77
79
|
|
|
78
|
-
|
|
80
|
+
this.debug.log(`Optimizing connections carefully: ${availableSlots} slots available, connecting to ${peersToConnect.length} peer(s)`);
|
|
79
81
|
|
|
80
82
|
peersToConnect.forEach((peerId, _index) => {
|
|
81
83
|
if (this.mesh.peerDiscovery.shouldInitiateConnection(peerId)) {
|
|
82
|
-
|
|
84
|
+
this.debug.log(`Initiating immediate connection to ${peerId.substring(0, 8)}... in optimization`);
|
|
83
85
|
// Double-check conditions before connecting
|
|
84
86
|
if (this.connectionManager.canAcceptMorePeers() &&
|
|
85
87
|
!this.connectionManager.hasPeer(peerId) &&
|
|
86
88
|
!this.mesh.peerDiscovery.isAttemptingConnection(peerId)) {
|
|
87
89
|
this.connectionManager.connectToPeer(peerId);
|
|
88
90
|
} else {
|
|
89
|
-
|
|
91
|
+
this.debug.log(`Skipping connection to ${peerId.substring(0, 8)}... - conditions changed`);
|
|
90
92
|
}
|
|
91
93
|
} else {
|
|
92
|
-
|
|
94
|
+
this.debug.log(`Not initiating connection to ${peerId.substring(0, 8)}... (should not initiate)`);
|
|
93
95
|
}
|
|
94
96
|
});
|
|
95
97
|
}
|
|
@@ -110,17 +112,17 @@ export class MeshOptimizer extends EventEmitter {
|
|
|
110
112
|
const discoveredPeers = this.mesh.getDiscoveredPeers();
|
|
111
113
|
let connectionAttempts = 0;
|
|
112
114
|
|
|
113
|
-
|
|
115
|
+
this.debug.log(`Forcing connections to ${discoveredPeers.length} discovered peers...`);
|
|
114
116
|
|
|
115
117
|
discoveredPeers.forEach(peer => {
|
|
116
118
|
if (!this.connectionManager.hasPeer(peer.peerId) && this.connectionManager.canAcceptMorePeers()) {
|
|
117
|
-
|
|
119
|
+
this.debug.log(`Force connecting to ${peer.peerId.substring(0, 8)}...`);
|
|
118
120
|
this.connectionManager.connectToPeer(peer.peerId);
|
|
119
121
|
connectionAttempts++;
|
|
120
122
|
}
|
|
121
123
|
});
|
|
122
124
|
|
|
123
|
-
|
|
125
|
+
this.debug.log(`Initiated ${connectionAttempts} forced connection attempts`);
|
|
124
126
|
return connectionAttempts;
|
|
125
127
|
}
|
|
126
128
|
|
|
@@ -130,39 +132,39 @@ export class MeshOptimizer extends EventEmitter {
|
|
|
130
132
|
const discoveredPeers = this.mesh.getDiscoveredPeers();
|
|
131
133
|
const totalPeers = this.connectionManager.peers.size;
|
|
132
134
|
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
135
|
+
this.debug.log('=== CONNECTIVITY DEBUG ===');
|
|
136
|
+
this.debug.log(`My Peer ID: ${this.mesh.peerId}`);
|
|
137
|
+
this.debug.log(`Connected Peers: ${connectedPeers}/${this.mesh.maxPeers}`);
|
|
138
|
+
this.debug.log(`Total Peer Objects: ${totalPeers}`);
|
|
139
|
+
this.debug.log(`Discovered Peers: ${discoveredPeers.length}`);
|
|
138
140
|
|
|
139
|
-
|
|
141
|
+
this.debug.log('\nPeer Details:');
|
|
140
142
|
this.connectionManager.peers.forEach((peerConnection, peerId) => {
|
|
141
143
|
const status = peerConnection.getStatus();
|
|
142
144
|
const dataChannelReady = peerConnection.dataChannelReady;
|
|
143
145
|
const connectionState = peerConnection.connection?.connectionState || 'unknown';
|
|
144
146
|
const dataChannelState = peerConnection.dataChannel?.readyState || 'unknown';
|
|
145
147
|
|
|
146
|
-
|
|
148
|
+
this.debug.log(` ${peerId.substring(0, 8)}... - Status: ${status}, WebRTC: ${connectionState}, DataChannel: ${dataChannelState}, Ready: ${dataChannelReady}`);
|
|
147
149
|
});
|
|
148
150
|
|
|
149
|
-
|
|
151
|
+
this.debug.log('\nDiscovered Peers:');
|
|
150
152
|
discoveredPeers.forEach(peer => {
|
|
151
153
|
const shouldInitiate = this.mesh.peerId < peer.peerId;
|
|
152
154
|
const isConnected = this.connectionManager.hasPeer(peer.peerId);
|
|
153
|
-
|
|
155
|
+
this.debug.log(` ${peer.peerId.substring(0, 8)}... - ShouldInitiate: ${shouldInitiate}, IsConnected: ${isConnected}`);
|
|
154
156
|
});
|
|
155
157
|
|
|
156
|
-
|
|
158
|
+
this.debug.log('\nConnection Attempts:');
|
|
157
159
|
this.connectionManager.connectionAttempts.forEach((attempts, peerId) => {
|
|
158
|
-
|
|
160
|
+
this.debug.log(` ${peerId.substring(0, 8)}... - Attempts: ${attempts}/${this.connectionManager.maxConnectionAttempts}`);
|
|
159
161
|
});
|
|
160
162
|
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
163
|
+
this.debug.log('\nEviction Status:');
|
|
164
|
+
this.debug.log(` Eviction Strategy: ${this.mesh.evictionStrategy ? 'enabled' : 'disabled'}`);
|
|
165
|
+
this.debug.log(` XOR Routing: ${this.mesh.xorRouting ? 'enabled' : 'disabled'}`);
|
|
164
166
|
|
|
165
|
-
|
|
167
|
+
this.debug.log('=== END DEBUG ===\n');
|
|
166
168
|
|
|
167
169
|
return {
|
|
168
170
|
connectedPeers,
|