peat-mesh 0.8.1

Peat mesh networking library with CRDT sync, transport security, and topology management
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
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
//! Transport abstraction for mesh topology connections
//!
//! This module provides backend-agnostic types and traits for establishing
//! P2P connections in the mesh network. It enables `TopologyManager` and
//! related components to work with any transport backend.
//!
//! ## Core Types
//!
//! - **NodeId**: Mesh network node identifier
//! - **MeshTransport**: Connection establishment and management trait
//! - **MeshConnection**: Active connection to a peer trait
//! - **PeerEvent**: Connection lifecycle events

use async_trait::async_trait;
use std::error::Error as StdError;
use std::fmt;
use std::time::Instant;
use tokio::sync::mpsc;

// Submodules moved from peat-protocol (ADR-049 Phase 2)
pub mod bypass;
pub mod capabilities;
pub mod health;
pub mod manager;
pub mod reconnection;

#[cfg(feature = "lite-bridge")]
pub mod lite;
#[cfg(feature = "lite-bridge")]
pub mod lite_ota;

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

// Re-exports from submodules
pub use bypass::{
    BypassChannelConfig, BypassCollectionConfig, BypassError, BypassHeader, BypassMessage,
    BypassMetrics, BypassMetricsSnapshot, BypassTarget, BypassTransport, MessageEncoding,
    UdpBypassChannel, UdpConfig,
};
pub use capabilities::{
    ConfigurableTransport, DistanceSource, MessagePriority, MessageRequirements, PaceLevel,
    PeerDistance, RangeMode, RangeModeConfig, Transport, TransportCapabilities, TransportId,
    TransportInstance, TransportMode, TransportPolicy, TransportType,
};
pub use health::{HealthMonitor, HeartbeatConfig};
pub use manager::{
    CollectionRouteConfig, CollectionRouteTable, CollectionTransportRoute, RouteDecision,
    TransportManager, TransportManagerConfig,
};

#[cfg(feature = "lite-bridge")]
pub use lite::{
    CrdtType, LiteCapabilities, LiteCapabilitiesExt, LiteDocumentBridge, LiteMeshTransport,
    LiteMessage, LitePeerState, LiteSyncMode, LiteTransportConfig, MessageType as LiteMessageType,
    OrSetElement, QueryRequest, FULL_CRDT,
};

#[cfg(feature = "lite-bridge")]
pub use lite_ota::{FirmwareImage, OtaSender, OtaStatusInfo};

#[cfg(feature = "bluetooth")]
pub use btle::PeatBleTransport;

// =============================================================================
// Node Identity
// =============================================================================

/// Node identifier in the mesh network
///
/// Uniquely identifies a node in the mesh. This is separate from
/// backend-specific IDs (e.g., Iroh's EndpointId, Ditto's peer ID).
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct NodeId(String);

impl NodeId {
    /// Create a new node ID from a string
    pub fn new(id: String) -> Self {
        Self(id)
    }

    /// Get the node ID as a string slice
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl fmt::Display for NodeId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl From<String> for NodeId {
    fn from(id: String) -> Self {
        Self(id)
    }
}

impl From<&str> for NodeId {
    fn from(id: &str) -> Self {
        Self(id.to_string())
    }
}

// =============================================================================
// Peer Events
// =============================================================================

/// Peer connection lifecycle events
///
/// Applications can subscribe to these events to react to peer state changes.
#[derive(Debug, Clone)]
pub enum PeerEvent {
    /// New peer connected successfully
    Connected {
        /// The peer's node ID
        peer_id: NodeId,
        /// When the connection was established
        connected_at: Instant,
    },

    /// Peer disconnected
    Disconnected {
        /// The peer's node ID
        peer_id: NodeId,
        /// Reason for disconnection (if known)
        reason: DisconnectReason,
        /// How long the connection was active
        connection_duration: std::time::Duration,
    },

    /// Connection quality degraded
    Degraded {
        /// The peer's node ID
        peer_id: NodeId,
        /// Current health metrics
        health: ConnectionHealth,
    },

    /// Attempting to reconnect to a peer
    Reconnecting {
        /// The peer's node ID
        peer_id: NodeId,
        /// Current attempt number (1-indexed)
        attempt: u32,
        /// Maximum attempts configured (None = infinite)
        max_attempts: Option<u32>,
    },

    /// Reconnection attempt failed
    ReconnectFailed {
        /// The peer's node ID
        peer_id: NodeId,
        /// Current attempt number
        attempt: u32,
        /// Error message
        error: String,
        /// Whether more retries will be attempted
        will_retry: bool,
    },
}

/// Reason for peer disconnection
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DisconnectReason {
    /// Remote peer initiated close
    RemoteClosed,
    /// Connection timed out
    Timeout,
    /// Network error occurred
    NetworkError(String),
    /// Local side requested disconnect
    LocalClosed,
    /// Connection was idle too long
    IdleTimeout,
    /// Application-level error
    ApplicationError(String),
    /// Unknown reason
    Unknown,
}

impl fmt::Display for DisconnectReason {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            DisconnectReason::RemoteClosed => write!(f, "remote closed"),
            DisconnectReason::Timeout => write!(f, "timeout"),
            DisconnectReason::NetworkError(e) => write!(f, "network error: {}", e),
            DisconnectReason::LocalClosed => write!(f, "local closed"),
            DisconnectReason::IdleTimeout => write!(f, "idle timeout"),
            DisconnectReason::ApplicationError(e) => write!(f, "application error: {}", e),
            DisconnectReason::Unknown => write!(f, "unknown"),
        }
    }
}

/// Connection health metrics
#[derive(Debug, Clone)]
pub struct ConnectionHealth {
    /// Round-trip time in milliseconds (smoothed average)
    pub rtt_ms: u32,
    /// RTT variance in milliseconds
    pub rtt_variance_ms: u32,
    /// Estimated packet loss percentage (0-100)
    pub packet_loss_percent: u8,
    /// Current connection state
    pub state: ConnectionState,
    /// Last successful communication
    pub last_activity: Instant,
}

impl Default for ConnectionHealth {
    fn default() -> Self {
        Self {
            rtt_ms: 0,
            rtt_variance_ms: 0,
            packet_loss_percent: 0,
            state: ConnectionState::Healthy,
            last_activity: Instant::now(),
        }
    }
}

/// Connection state for health monitoring
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ConnectionState {
    /// Connection is healthy
    Healthy,
    /// Connection is degraded (high latency/loss)
    Degraded,
    /// Connection is suspected dead (missed heartbeats)
    Suspect,
    /// Connection confirmed dead
    Dead,
}

impl fmt::Display for ConnectionState {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ConnectionState::Healthy => write!(f, "healthy"),
            ConnectionState::Degraded => write!(f, "degraded"),
            ConnectionState::Suspect => write!(f, "suspect"),
            ConnectionState::Dead => write!(f, "dead"),
        }
    }
}

// =============================================================================
// Error Types
// =============================================================================

/// Error type for mesh transport operations
#[derive(Debug)]
pub enum TransportError {
    /// Connection failed to establish
    ConnectionFailed(String),
    /// Peer not found or unreachable
    PeerNotFound(String),
    /// Connection already exists
    AlreadyConnected(String),
    /// Transport not started
    NotStarted,
    /// Generic transport error
    Other(Box<dyn StdError + Send + Sync>),
}

impl fmt::Display for TransportError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            TransportError::ConnectionFailed(msg) => write!(f, "Connection failed: {}", msg),
            TransportError::PeerNotFound(msg) => write!(f, "Peer not found: {}", msg),
            TransportError::AlreadyConnected(msg) => write!(f, "Already connected: {}", msg),
            TransportError::NotStarted => write!(f, "Transport not started"),
            TransportError::Other(err) => write!(f, "Transport error: {}", err),
        }
    }
}

impl StdError for TransportError {
    fn source(&self) -> Option<&(dyn StdError + 'static)> {
        match self {
            TransportError::Other(err) => Some(err.as_ref()),
            _ => None,
        }
    }
}

/// Result type alias for transport operations
pub type Result<T> = std::result::Result<T, TransportError>;

/// Channel capacity for peer events
pub const PEER_EVENT_CHANNEL_CAPACITY: usize = 256;

/// Type alias for peer event receiver
pub type PeerEventReceiver = mpsc::Receiver<PeerEvent>;

/// Type alias for peer event sender
pub type PeerEventSender = mpsc::Sender<PeerEvent>;

// =============================================================================
// Transport Traits
// =============================================================================

/// Transport abstraction for mesh topology connections
///
/// This trait defines the connection management operations needed by
/// `TopologyManager` to establish parent-child relationships in the mesh.
#[async_trait]
pub trait MeshTransport: Send + Sync {
    /// Start the transport layer
    async fn start(&self) -> Result<()>;

    /// Stop the transport layer
    async fn stop(&self) -> Result<()>;

    /// Connect to a peer by node ID
    async fn connect(&self, peer_id: &NodeId) -> Result<Box<dyn MeshConnection>>;

    /// Disconnect from a peer
    async fn disconnect(&self, peer_id: &NodeId) -> Result<()>;

    /// Get an existing connection to a peer
    fn get_connection(&self, peer_id: &NodeId) -> Option<Box<dyn MeshConnection>>;

    /// Get the number of connected peers
    fn peer_count(&self) -> usize;

    /// Get list of connected peer IDs
    fn connected_peers(&self) -> Vec<NodeId>;

    /// Check if connected to a specific peer
    fn is_connected(&self, peer_id: &NodeId) -> bool {
        self.get_connection(peer_id).is_some()
    }

    /// Send data to a connected peer.
    ///
    /// Returns the number of bytes sent.
    async fn send_to(&self, peer_id: &NodeId, data: &[u8]) -> Result<usize> {
        let _ = (peer_id, data);
        Err(TransportError::ConnectionFailed(
            "send not implemented".into(),
        ))
    }

    /// Subscribe to peer connection events
    fn subscribe_peer_events(&self) -> PeerEventReceiver;

    /// Get connection health for a specific peer
    fn get_peer_health(&self, peer_id: &NodeId) -> Option<ConnectionHealth> {
        self.get_connection(peer_id)
            .map(|_| ConnectionHealth::default())
    }
}

/// Active connection to a mesh peer
///
/// This trait abstracts over backend-specific connection types.
pub trait MeshConnection: Send + Sync {
    /// Get the remote peer's node ID
    fn peer_id(&self) -> &NodeId;

    /// Check if connection is still alive
    fn is_alive(&self) -> bool;

    /// Get the time when this connection was established
    fn connected_at(&self) -> Instant;

    /// Get the disconnect reason if the connection is closed
    fn disconnect_reason(&self) -> Option<DisconnectReason> {
        if self.is_alive() {
            None
        } else {
            Some(DisconnectReason::Unknown)
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::HashSet;

    #[test]
    fn test_node_id_creation() {
        let id = NodeId::new("node-123".to_string());
        assert_eq!(id.as_str(), "node-123");
        assert_eq!(id.to_string(), "node-123");
    }

    #[test]
    fn test_node_id_from_string() {
        let id: NodeId = "node-456".into();
        assert_eq!(id.as_str(), "node-456");
    }

    #[test]
    fn test_node_id_from_str() {
        let id: NodeId = NodeId::from("node-789");
        assert_eq!(id.as_str(), "node-789");
    }

    #[test]
    fn test_node_id_equality() {
        let id1 = NodeId::new("node-123".to_string());
        let id2 = NodeId::new("node-123".to_string());
        let id3 = NodeId::new("node-456".to_string());

        assert_eq!(id1, id2);
        assert_ne!(id1, id3);
    }

    #[test]
    fn test_node_id_hash() {
        let mut set = HashSet::new();
        set.insert(NodeId::new("a".into()));
        set.insert(NodeId::new("a".into()));
        set.insert(NodeId::new("b".into()));
        assert_eq!(set.len(), 2);
    }

    #[test]
    fn test_node_id_display() {
        let id = NodeId::new("display-me".into());
        assert_eq!(format!("{}", id), "display-me");
    }

    // --- DisconnectReason ---

    #[test]
    fn test_disconnect_reason_display() {
        assert_eq!(DisconnectReason::RemoteClosed.to_string(), "remote closed");
        assert_eq!(DisconnectReason::Timeout.to_string(), "timeout");
        assert_eq!(
            DisconnectReason::NetworkError("reset".into()).to_string(),
            "network error: reset"
        );
        assert_eq!(DisconnectReason::LocalClosed.to_string(), "local closed");
        assert_eq!(DisconnectReason::IdleTimeout.to_string(), "idle timeout");
        assert_eq!(
            DisconnectReason::ApplicationError("bug".into()).to_string(),
            "application error: bug"
        );
        assert_eq!(DisconnectReason::Unknown.to_string(), "unknown");
    }

    #[test]
    fn test_disconnect_reason_equality() {
        assert_eq!(DisconnectReason::Timeout, DisconnectReason::Timeout);
        assert_ne!(DisconnectReason::Timeout, DisconnectReason::Unknown);
        assert_eq!(
            DisconnectReason::NetworkError("x".into()),
            DisconnectReason::NetworkError("x".into()),
        );
    }

    // --- ConnectionState ---

    #[test]
    fn test_connection_state_display() {
        assert_eq!(ConnectionState::Healthy.to_string(), "healthy");
        assert_eq!(ConnectionState::Degraded.to_string(), "degraded");
        assert_eq!(ConnectionState::Suspect.to_string(), "suspect");
        assert_eq!(ConnectionState::Dead.to_string(), "dead");
    }

    #[test]
    fn test_connection_state_equality() {
        assert_eq!(ConnectionState::Healthy, ConnectionState::Healthy);
        assert_ne!(ConnectionState::Healthy, ConnectionState::Dead);
    }

    // --- ConnectionHealth ---

    #[test]
    fn test_connection_health_default() {
        let h = ConnectionHealth::default();
        assert_eq!(h.rtt_ms, 0);
        assert_eq!(h.rtt_variance_ms, 0);
        assert_eq!(h.packet_loss_percent, 0);
        assert_eq!(h.state, ConnectionState::Healthy);
    }

    // --- TransportError ---

    #[test]
    fn test_transport_error_display() {
        assert_eq!(
            TransportError::ConnectionFailed("timeout".into()).to_string(),
            "Connection failed: timeout"
        );
        assert_eq!(
            TransportError::PeerNotFound("node-123".into()).to_string(),
            "Peer not found: node-123"
        );
        assert_eq!(
            TransportError::AlreadyConnected("node-1".into()).to_string(),
            "Already connected: node-1"
        );
        assert_eq!(
            TransportError::NotStarted.to_string(),
            "Transport not started"
        );
    }

    #[test]
    fn test_transport_error_other() {
        let inner = std::io::Error::new(std::io::ErrorKind::Other, "boom");
        let err = TransportError::Other(Box::new(inner));
        assert!(err.to_string().contains("boom"));
    }

    #[test]
    fn test_transport_error_source() {
        use std::error::Error;

        let err = TransportError::NotStarted;
        assert!(err.source().is_none());

        let inner = std::io::Error::new(std::io::ErrorKind::Other, "boom");
        let err = TransportError::Other(Box::new(inner));
        assert!(err.source().is_some());
    }

    // --- PeerEvent construction ---

    #[test]
    fn test_peer_event_connected() {
        let evt = PeerEvent::Connected {
            peer_id: NodeId::new("p1".into()),
            connected_at: Instant::now(),
        };
        if let PeerEvent::Connected { peer_id, .. } = evt {
            assert_eq!(peer_id.as_str(), "p1");
        }
    }

    #[test]
    fn test_peer_event_disconnected() {
        let evt = PeerEvent::Disconnected {
            peer_id: NodeId::new("p1".into()),
            reason: DisconnectReason::Timeout,
            connection_duration: std::time::Duration::from_secs(60),
        };
        if let PeerEvent::Disconnected {
            reason,
            connection_duration,
            ..
        } = evt
        {
            assert_eq!(reason, DisconnectReason::Timeout);
            assert_eq!(connection_duration.as_secs(), 60);
        }
    }

    #[test]
    fn test_peer_event_degraded() {
        let evt = PeerEvent::Degraded {
            peer_id: NodeId::new("p1".into()),
            health: ConnectionHealth::default(),
        };
        if let PeerEvent::Degraded { health, .. } = evt {
            assert_eq!(health.state, ConnectionState::Healthy);
        }
    }

    #[test]
    fn test_peer_event_reconnecting() {
        let evt = PeerEvent::Reconnecting {
            peer_id: NodeId::new("p1".into()),
            attempt: 3,
            max_attempts: Some(5),
        };
        if let PeerEvent::Reconnecting {
            attempt,
            max_attempts,
            ..
        } = evt
        {
            assert_eq!(attempt, 3);
            assert_eq!(max_attempts, Some(5));
        }
    }

    #[test]
    fn test_peer_event_reconnect_failed() {
        let evt = PeerEvent::ReconnectFailed {
            peer_id: NodeId::new("p1".into()),
            attempt: 5,
            error: "timeout".into(),
            will_retry: false,
        };
        if let PeerEvent::ReconnectFailed {
            will_retry, error, ..
        } = evt
        {
            assert!(!will_retry);
            assert_eq!(error, "timeout");
        }
    }

    // --- Trait default implementations ---

    struct TestConnection {
        pid: NodeId,
        alive: bool,
    }

    impl MeshConnection for TestConnection {
        fn peer_id(&self) -> &NodeId {
            &self.pid
        }
        fn is_alive(&self) -> bool {
            self.alive
        }
        fn connected_at(&self) -> Instant {
            Instant::now()
        }
    }

    #[test]
    fn test_mesh_connection_disconnect_reason_alive() {
        let conn = TestConnection {
            pid: NodeId::new("p".into()),
            alive: true,
        };
        assert!(conn.disconnect_reason().is_none());
    }

    #[test]
    fn test_mesh_connection_disconnect_reason_dead() {
        let conn = TestConnection {
            pid: NodeId::new("p".into()),
            alive: false,
        };
        assert_eq!(conn.disconnect_reason(), Some(DisconnectReason::Unknown));
    }

    // --- MeshTransport::send_to default ---

    struct MinimalTransport;

    #[async_trait::async_trait]
    impl MeshTransport for MinimalTransport {
        async fn start(&self) -> Result<()> {
            Ok(())
        }
        async fn stop(&self) -> Result<()> {
            Ok(())
        }
        async fn connect(&self, _: &NodeId) -> Result<Box<dyn MeshConnection>> {
            Err(TransportError::NotStarted)
        }
        async fn disconnect(&self, _: &NodeId) -> Result<()> {
            Ok(())
        }
        fn get_connection(&self, _: &NodeId) -> Option<Box<dyn MeshConnection>> {
            None
        }
        fn peer_count(&self) -> usize {
            0
        }
        fn connected_peers(&self) -> Vec<NodeId> {
            vec![]
        }
        fn subscribe_peer_events(&self) -> PeerEventReceiver {
            let (_tx, rx) = tokio::sync::mpsc::channel(1);
            rx
        }
    }

    #[tokio::test]
    async fn test_send_to_default_returns_error() {
        let transport = MinimalTransport;
        let peer = NodeId::new("peer-1".into());
        let result = transport.send_to(&peer, b"hello").await;
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(
            matches!(err, TransportError::ConnectionFailed(msg) if msg.contains("send not implemented"))
        );
    }
}