clasp-discovery 3.3.0

Device discovery for CLASP (mDNS, UDP broadcast)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
//! Clasp Discovery
//!
//! Provides device discovery mechanisms:
//! - mDNS/Bonjour for LAN auto-discovery
//! - UDP broadcast fallback
//! - Rendezvous server for WAN discovery
//! - Manual registration

pub mod device;
pub mod error;

#[cfg(feature = "mdns")]
pub mod mdns;

#[cfg(feature = "broadcast")]
pub mod broadcast;

#[cfg(feature = "rendezvous")]
pub mod rendezvous;

pub use device::{Device, DeviceInfo};
pub use error::{DiscoveryError, Result};

#[cfg(feature = "rendezvous")]
pub use rendezvous::{DeviceRegistration, RendezvousClient, RendezvousConfig, RendezvousServer};

use std::sync::Arc;
use std::time::Duration;
use tokio::sync::mpsc;

/// Discovery event
#[derive(Debug, Clone)]
pub enum DiscoveryEvent {
    /// Device discovered
    Found(Device),
    /// Device removed/lost
    Lost(String), // Device ID
    /// Error during discovery
    Error(String),
}

/// Discovery source (where the device was discovered from)
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DiscoverySource {
    /// mDNS/Bonjour (LAN)
    Mdns,
    /// UDP broadcast (LAN)
    Broadcast,
    /// Rendezvous server (WAN)
    Rendezvous,
    /// Manually added
    Manual,
}

/// Discovery configuration
#[derive(Debug, Clone)]
pub struct DiscoveryConfig {
    /// Enable mDNS discovery
    pub mdns: bool,
    /// Enable UDP broadcast discovery
    pub broadcast: bool,
    /// Broadcast port
    pub broadcast_port: u16,
    /// Discovery timeout
    pub timeout: Duration,
    /// Rendezvous server URL for WAN discovery (e.g., "https://rendezvous.example.com")
    pub rendezvous_url: Option<String>,
    /// Rendezvous refresh interval (how often to re-register, should be < TTL)
    pub rendezvous_refresh_interval: Duration,
    /// Filter tag for rendezvous discovery
    pub rendezvous_tag: Option<String>,
}

impl Default for DiscoveryConfig {
    fn default() -> Self {
        Self {
            mdns: true,
            broadcast: true,
            broadcast_port: clasp_core::DEFAULT_DISCOVERY_PORT,
            timeout: Duration::from_secs(5),
            rendezvous_url: None,
            rendezvous_refresh_interval: Duration::from_secs(120), // 2 minutes (< 5 min default TTL)
            rendezvous_tag: None,
        }
    }
}

/// Rendezvous keepalive state
#[cfg(feature = "rendezvous")]
struct RendezvousKeepalive {
    client: rendezvous::RendezvousClient,
    registration: rendezvous::DeviceRegistration,
    device_id: parking_lot::RwLock<Option<String>>,
    refresh_interval: Duration,
}

#[cfg(feature = "rendezvous")]
impl RendezvousKeepalive {
    fn new(
        url: &str,
        registration: rendezvous::DeviceRegistration,
        refresh_interval: Duration,
    ) -> Self {
        Self {
            client: rendezvous::RendezvousClient::new(url),
            registration,
            device_id: parking_lot::RwLock::new(None),
            refresh_interval,
        }
    }

    async fn register(&self) -> Result<()> {
        let response = self
            .client
            .register(self.registration.clone())
            .await
            .map_err(|e| DiscoveryError::Other(format!("Rendezvous registration failed: {}", e)))?;

        *self.device_id.write() = Some(response.id);
        tracing::info!(
            "Registered with rendezvous server (TTL: {}s)",
            response.ttl
        );
        Ok(())
    }

    async fn refresh(&self) -> Result<bool> {
        let device_id: Option<String> = self.device_id.read().clone();
        if let Some(ref id) = device_id {
            let success = self
                .client
                .refresh(id)
                .await
                .map_err(|e| DiscoveryError::Other(format!("Rendezvous refresh failed: {}", e)))?;

            if !success {
                // Device was removed, re-register
                tracing::warn!("Rendezvous registration expired, re-registering");
                *self.device_id.write() = None;
                self.register().await?;
            }
            Ok(true)
        } else {
            // Not registered yet, register now
            self.register().await?;
            Ok(true)
        }
    }

    async fn unregister(&self) -> Result<()> {
        let device_id: Option<String> = self.device_id.write().take();
        if let Some(ref id) = device_id {
            let _ = self.client.unregister(id).await;
            tracing::info!("Unregistered from rendezvous server");
        }
        Ok(())
    }

    /// Start the keepalive loop
    fn start_keepalive(self: Arc<Self>) {
        let keepalive = Arc::clone(&self);
        tokio::spawn(async move {
            // Initial registration
            if let Err(e) = keepalive.register().await {
                tracing::error!("Initial rendezvous registration failed: {}", e);
            }

            // Refresh loop
            let mut interval = tokio::time::interval(keepalive.refresh_interval);
            loop {
                interval.tick().await;
                if let Err(e) = keepalive.refresh().await {
                    tracing::warn!("Rendezvous refresh failed: {}", e);
                }
            }
        });
    }
}

/// Discover Clasp devices
pub struct Discovery {
    config: DiscoveryConfig,
    devices: std::collections::HashMap<String, Device>,
    #[cfg(feature = "rendezvous")]
    rendezvous_keepalive: Option<Arc<RendezvousKeepalive>>,
}

impl Discovery {
    pub fn new() -> Self {
        Self {
            config: DiscoveryConfig::default(),
            devices: std::collections::HashMap::new(),
            #[cfg(feature = "rendezvous")]
            rendezvous_keepalive: None,
        }
    }

    pub fn with_config(config: DiscoveryConfig) -> Self {
        Self {
            config,
            devices: std::collections::HashMap::new(),
            #[cfg(feature = "rendezvous")]
            rendezvous_keepalive: None,
        }
    }

    /// Register this device with the rendezvous server and start keepalive
    #[cfg(feature = "rendezvous")]
    pub fn register_with_rendezvous(&mut self, registration: rendezvous::DeviceRegistration) {
        if let Some(ref url) = self.config.rendezvous_url {
            let keepalive = Arc::new(RendezvousKeepalive::new(
                url,
                registration,
                self.config.rendezvous_refresh_interval,
            ));
            keepalive.clone().start_keepalive();
            self.rendezvous_keepalive = Some(keepalive);
        } else {
            tracing::warn!("Cannot register with rendezvous: no URL configured");
        }
    }

    /// Discover devices from the rendezvous server (WAN discovery)
    #[cfg(feature = "rendezvous")]
    pub async fn discover_wan(&self) -> Result<Vec<Device>> {
        let url = self
            .config
            .rendezvous_url
            .as_ref()
            .ok_or_else(|| DiscoveryError::Other("No rendezvous URL configured".to_string()))?;

        let client = rendezvous::RendezvousClient::new(url);
        let tag = self.config.rendezvous_tag.as_deref();
        let registered_devices = client
            .discover(tag)
            .await
            .map_err(|e| DiscoveryError::Other(format!("Rendezvous discovery failed: {}", e)))?;

        // Convert RegisteredDevice to Device
        let devices: Vec<Device> = registered_devices
            .into_iter()
            .map(|rd| {
                let mut meta = rd.metadata.clone();
                // Add tags to metadata
                if !rd.tags.is_empty() {
                    meta.insert("tags".to_string(), rd.tags.join(","));
                }

                let info = DeviceInfo {
                    version: clasp_core::PROTOCOL_VERSION,
                    features: rd.features,
                    bridge: false,
                    bridge_protocol: None,
                    meta,
                };

                let now = std::time::Instant::now();
                Device {
                    id: rd.id,
                    name: rd.name,
                    info,
                    endpoints: rd.endpoints,
                    discovered_at: now,
                    last_seen: now,
                }
            })
            .collect();

        Ok(devices)
    }

    /// Discover all devices using all available methods (cascade discovery)
    /// Tries: mDNS → broadcast → rendezvous
    /// Returns devices from all successful discovery methods
    pub async fn discover_all(&mut self) -> Result<Vec<Device>> {
        let (tx, mut rx) = mpsc::channel(100);
        let mut all_devices = Vec::new();
        let mut seen_ids = std::collections::HashSet::new();

        // Start LAN discovery
        #[cfg(feature = "mdns")]
        if self.config.mdns {
            let tx_clone = tx.clone();
            tokio::spawn(async move {
                if let Err(e) = mdns::discover(tx_clone).await {
                    tracing::warn!("mDNS discovery error: {}", e);
                }
            });
        }

        #[cfg(feature = "broadcast")]
        if self.config.broadcast {
            let tx_clone = tx.clone();
            let port = self.config.broadcast_port;
            tokio::spawn(async move {
                if let Err(e) = broadcast::discover(port, tx_clone).await {
                    tracing::warn!("Broadcast discovery error: {}", e);
                }
            });
        }

        // Collect LAN results with timeout
        let timeout = self.config.timeout;
        let deadline = tokio::time::Instant::now() + timeout;
        drop(tx); // Close sender so rx completes when all spawned tasks finish

        loop {
            tokio::select! {
                event = rx.recv() => {
                    match event {
                        Some(DiscoveryEvent::Found(device)) => {
                            if seen_ids.insert(device.id.clone()) {
                                self.devices.insert(device.id.clone(), device.clone());
                                all_devices.push(device);
                            }
                        }
                        Some(DiscoveryEvent::Error(e)) => {
                            tracing::warn!("Discovery error: {}", e);
                        }
                        Some(DiscoveryEvent::Lost(_)) | None => break,
                    }
                }
                _ = tokio::time::sleep_until(deadline) => {
                    tracing::debug!("LAN discovery timeout");
                    break;
                }
            }
        }

        // Try WAN discovery if configured
        #[cfg(feature = "rendezvous")]
        if self.config.rendezvous_url.is_some() {
            match self.discover_wan().await {
                Ok(wan_devices) => {
                    for device in wan_devices {
                        if seen_ids.insert(device.id.clone()) {
                            self.devices.insert(device.id.clone(), device.clone());
                            all_devices.push(device);
                        }
                    }
                }
                Err(e) => {
                    tracing::warn!("WAN discovery failed: {}", e);
                }
            }
        }

        Ok(all_devices)
    }

    /// Start discovery and return a receiver for events
    pub async fn start(&mut self) -> Result<mpsc::Receiver<DiscoveryEvent>> {
        let (tx, rx) = mpsc::channel(100);

        #[cfg(feature = "mdns")]
        if self.config.mdns {
            let tx_clone = tx.clone();
            tokio::spawn(async move {
                if let Err(e) = mdns::discover(tx_clone).await {
                    tracing::warn!("mDNS discovery error: {}", e);
                }
            });
        }

        #[cfg(feature = "broadcast")]
        if self.config.broadcast {
            let tx_clone = tx.clone();
            let port = self.config.broadcast_port;
            tokio::spawn(async move {
                if let Err(e) = broadcast::discover(port, tx_clone).await {
                    tracing::warn!("Broadcast discovery error: {}", e);
                }
            });
        }

        // Start WAN discovery if configured
        #[cfg(feature = "rendezvous")]
        if self.config.rendezvous_url.is_some() {
            let tx_clone = tx.clone();
            let config = self.config.clone();
            tokio::spawn(async move {
                let url = config.rendezvous_url.as_ref().unwrap();
                let client = rendezvous::RendezvousClient::new(url);
                let tag = config.rendezvous_tag.as_deref();

                match client.discover(tag).await {
                    Ok(devices) => {
                        for rd in devices {
                            let mut meta = rd.metadata.clone();
                            if !rd.tags.is_empty() {
                                meta.insert("tags".to_string(), rd.tags.join(","));
                            }

                            let info = DeviceInfo {
                                version: clasp_core::PROTOCOL_VERSION,
                                features: rd.features,
                                bridge: false,
                                bridge_protocol: None,
                                meta,
                            };

                            let now = std::time::Instant::now();
                            let device = Device {
                                id: rd.id,
                                name: rd.name,
                                info,
                                endpoints: rd.endpoints,
                                discovered_at: now,
                                last_seen: now,
                            };
                            let _ = tx_clone.send(DiscoveryEvent::Found(device)).await;
                        }
                    }
                    Err(e) => {
                        tracing::warn!("Rendezvous discovery error: {}", e);
                        let _ = tx_clone
                            .send(DiscoveryEvent::Error(format!(
                                "Rendezvous discovery failed: {}",
                                e
                            )))
                            .await;
                    }
                }
            });
        }

        Ok(rx)
    }

    /// Get currently known devices
    pub fn devices(&self) -> impl Iterator<Item = &Device> {
        self.devices.values()
    }

    /// Get a device by ID
    pub fn get(&self, id: &str) -> Option<&Device> {
        self.devices.get(id)
    }

    /// Manually add a device
    pub fn add(&mut self, device: Device) {
        self.devices.insert(device.id.clone(), device);
    }

    /// Remove a device
    pub fn remove(&mut self, id: &str) -> Option<Device> {
        self.devices.remove(id)
    }
}

impl Default for Discovery {
    fn default() -> Self {
        Self::new()
    }
}