Skip to content

Commit c525dbe

Browse files
committed
Updated peer discovery
Signed-off-by: Robert Gogete <gogeterobert@yahoo.com>
1 parent 6fcc708 commit c525dbe

File tree

1 file changed

+128
-2
lines changed

1 file changed

+128
-2
lines changed

dig-node/src/network-manager.ts

Lines changed: 128 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,9 @@ export class NetworkManager extends EventEmitter {
111111

112112
// Set up peer discovery
113113
this.setupPeerDiscovery();
114+
115+
// Actively discover existing peers
116+
await this.discoverExistingPeers();
114117
} else {
115118
this.logger.warn('FileHost not available - file sharing will not work');
116119
}
@@ -153,13 +156,16 @@ export class NetworkManager extends EventEmitter {
153156
}
154157

155158
// Listen for peer announcements
156-
(this.gunRegistry as any).on('peerDiscovered', (capabilities: HostCapabilities) => {
159+
(this.gunRegistry as any).on('peerDiscovered', async (capabilities: HostCapabilities) => {
157160
this.logger.debug(`Discovered peer: ${capabilities.storeId}`);
158161
this.emit('peerConnected', capabilities.storeId);
159162

163+
// Query for the peer's files
164+
const files = await this.discoverPeerFiles(capabilities.storeId);
165+
160166
const announcement: PeerFileAnnouncement = {
161167
storeId: capabilities.storeId,
162-
files: [],
168+
files: files,
163169
capabilities: capabilities,
164170
timestamp: Date.now()
165171
};
@@ -177,6 +183,92 @@ export class NetworkManager extends EventEmitter {
177183
this.logger.debug('Peer discovery set up');
178184
}
179185

186+
private async discoverExistingPeers(): Promise<void> {
187+
if (!this.fileClient || !this.digNatToolsLoaded) {
188+
this.logger.debug('Cannot discover peers - FileClient not available');
189+
return;
190+
}
191+
192+
try {
193+
this.logger.debug('🔍 Discovering existing peers...');
194+
const availablePeers = await (this.fileClient as any).findAvailablePeers();
195+
196+
this.logger.info(`🌐 Found ${availablePeers.length} existing peers`);
197+
198+
for (const peerCapabilities of availablePeers) {
199+
if (peerCapabilities.storeId && peerCapabilities.storeId !== this.storeId) {
200+
this.logger.debug(`📡 Processing existing peer: ${peerCapabilities.storeId}`);
201+
202+
// Create announcement for this peer
203+
const announcement: PeerFileAnnouncement = {
204+
storeId: peerCapabilities.storeId,
205+
files: await this.discoverPeerFiles(peerCapabilities.storeId),
206+
capabilities: peerCapabilities,
207+
timestamp: Date.now()
208+
};
209+
210+
this.knownPeers.set(peerCapabilities.storeId, announcement);
211+
this.emit('peerAnnouncement', announcement);
212+
}
213+
}
214+
} catch (error) {
215+
this.logger.error('Error discovering existing peers:', error);
216+
}
217+
}
218+
219+
private async discoverPeerFiles(storeId: string): Promise<DigFileInfo[]> {
220+
if (!this.gunRegistry || !this.digNatToolsLoaded) {
221+
return [];
222+
}
223+
224+
try {
225+
this.logger.debug(`🔍 Querying files from peer: ${storeId}`);
226+
227+
return new Promise<DigFileInfo[]>((resolve) => {
228+
const timeout = globalThis.setTimeout(() => {
229+
this.logger.debug(`⏰ Timeout querying files from peer: ${storeId}`);
230+
resolve([]);
231+
}, 5000); // 5 second timeout
232+
233+
if ((this.gunRegistry as any).gun) {
234+
(this.gunRegistry as any).gun
235+
.get(this.config.gunOptions.namespace)
236+
.get('files')
237+
.get(storeId)
238+
.once((data: string | null) => {
239+
globalThis.clearTimeout(timeout);
240+
241+
if (data) {
242+
try {
243+
const fileList = JSON.parse(data);
244+
const digFiles: DigFileInfo[] = fileList.map((f: any) => ({
245+
path: f.path,
246+
hash: f.hash,
247+
size: f.size || 0
248+
}));
249+
250+
this.logger.debug(`📋 Found ${digFiles.length} files from peer ${storeId}`);
251+
resolve(digFiles);
252+
} catch (error) {
253+
this.logger.error(`Failed to parse file list from ${storeId}:`, error);
254+
resolve([]);
255+
}
256+
} else {
257+
this.logger.debug(`📋 No file list found for peer ${storeId}`);
258+
resolve([]);
259+
}
260+
});
261+
} else {
262+
globalThis.clearTimeout(timeout);
263+
resolve([]);
264+
}
265+
});
266+
} catch (error) {
267+
this.logger.error(`Error querying files from peer ${storeId}:`, error);
268+
return [];
269+
}
270+
}
271+
180272
public async announceFiles(files: DigFileInfo[]): Promise<void> {
181273
this.logger.debug(`announceFiles called with ${files.length} files`);
182274
this.logger.debug(`fileHost exists: ${!!this.fileHost}`);
@@ -209,12 +301,46 @@ export class NetworkManager extends EventEmitter {
209301
}
210302
}
211303

304+
// Also announce our file list to the Gun registry for peer discovery
305+
await this.announceFileListToRegistry(files);
306+
212307
this.logger.info(`Successfully announced ${sharedHashes.length} of ${files.length} files to network`);
213308
} catch (error) {
214309
this.logger.error('Failed to announce files:', error);
215310
}
216311
}
217312

313+
private async announceFileListToRegistry(files: DigFileInfo[]): Promise<void> {
314+
if (!this.gunRegistry || !this.digNatToolsLoaded) {
315+
return;
316+
}
317+
318+
try {
319+
this.logger.debug(`📢 Announcing ${files.length} files to Gun registry`);
320+
321+
// Store our file list in the Gun registry under our storeId
322+
const fileList = files.map(f => ({
323+
hash: f.hash,
324+
path: f.path,
325+
size: f.size || 0
326+
}));
327+
328+
// Use Gun to store our file list - this is a simple approach
329+
// In a real implementation, this might be part of the GunRegistry class
330+
if ((this.gunRegistry as any).gun) {
331+
(this.gunRegistry as any).gun
332+
.get(this.config.gunOptions.namespace)
333+
.get('files')
334+
.get(this.storeId)
335+
.put(JSON.stringify(fileList));
336+
337+
this.logger.debug(`📢 File list announced to registry for ${this.storeId}`);
338+
}
339+
} catch (error) {
340+
this.logger.error('Failed to announce file list to registry:', error);
341+
}
342+
}
343+
218344
public async getFileUrl(hash: string, storeId: string): Promise<string | null> {
219345
const peerAnnouncement = this.knownPeers.get(storeId);
220346
if (!peerAnnouncement) {

0 commit comments

Comments
 (0)