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
//! Broker state trait and data types for the mesh service broker.

use serde::Serialize;
use serde_json::Value;
use tokio::sync::broadcast;

/// Information about the local mesh node.
#[derive(Debug, Clone, Serialize)]
pub struct MeshNodeInfo {
    pub node_id: String,
    pub uptime_secs: u64,
    pub version: String,
}

/// Summary of a connected peer.
#[derive(Debug, Clone, Serialize)]
pub struct PeerSummary {
    pub id: String,
    pub connected: bool,
    pub state: String,
    pub rtt_ms: Option<u64>,
}

/// Summary of the mesh topology.
#[derive(Debug, Clone, Serialize)]
pub struct TopologySummary {
    pub peer_count: usize,
    pub role: String,
    pub hierarchy_level: u32,
}

/// Response from the readiness probe endpoint.
#[derive(Debug, Clone, Serialize)]
pub struct ReadinessResponse {
    pub ready: bool,
    pub node_id: String,
    pub checks: Vec<ReadinessCheck>,
}

/// Individual readiness check result.
#[derive(Debug, Clone, Serialize)]
pub struct ReadinessCheck {
    pub name: String,
    pub ready: bool,
    pub message: Option<String>,
}

/// Events streamed over WebSocket.
#[derive(Debug, Clone, Serialize)]
#[serde(tag = "type")]
pub enum MeshEvent {
    PeerConnected {
        peer_id: String,
    },
    PeerDisconnected {
        peer_id: String,
        reason: String,
    },
    TopologyChanged {
        new_role: String,
        peer_count: usize,
    },
    SyncEvent {
        collection: String,
        doc_id: String,
        action: String,
    },
}

/// Trait that backs the broker with mesh data.
///
/// Consumers implement this trait to provide live mesh state to the HTTP/WS broker.
/// The broker holds `Arc<dyn MeshBrokerState>` (same pattern as `Arc<dyn DataStore>`
/// in peat-persistence).
#[async_trait::async_trait]
pub trait MeshBrokerState: Send + Sync + 'static {
    /// Returns information about the local node.
    fn node_info(&self) -> MeshNodeInfo;

    /// Lists all known peers.
    async fn list_peers(&self) -> Vec<PeerSummary>;

    /// Gets a specific peer by ID, if known.
    async fn get_peer(&self, id: &str) -> Option<PeerSummary>;

    /// Returns a summary of the current topology.
    fn topology(&self) -> TopologySummary;

    /// Subscribe to mesh events (for WebSocket streaming).
    fn subscribe_events(&self) -> broadcast::Receiver<MeshEvent>;

    /// Returns the readiness status of this node.
    ///
    /// Default implementation returns ready with no checks.
    /// Override to add custom readiness checks (e.g., transport connected,
    /// sync caught up, etc.).
    fn readiness(&self) -> ReadinessResponse {
        ReadinessResponse {
            ready: true,
            node_id: self.node_info().node_id,
            checks: vec![],
        }
    }

    /// Lists documents in a collection (optional — returns `None` by default).
    async fn list_documents(&self, _collection: &str) -> Option<Vec<Value>> {
        None
    }

    /// Gets a single document by collection and id (optional — returns `None` by default).
    async fn get_document(&self, _collection: &str, _id: &str) -> Option<Value> {
        None
    }
}

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

    #[test]
    fn test_mesh_node_info_serialization() {
        let info = MeshNodeInfo {
            node_id: "node-1".into(),
            uptime_secs: 3600,
            version: "0.1.0".into(),
        };
        let json: serde_json::Value = serde_json::to_value(&info).unwrap();
        assert_eq!(json["node_id"], "node-1");
        assert_eq!(json["uptime_secs"], 3600);
        assert_eq!(json["version"], "0.1.0");
    }

    #[test]
    fn test_mesh_node_info_zero_uptime() {
        let info = MeshNodeInfo {
            node_id: "fresh".into(),
            uptime_secs: 0,
            version: "0.0.0".into(),
        };
        let json: serde_json::Value = serde_json::to_value(&info).unwrap();
        assert_eq!(json["uptime_secs"], 0);
    }

    #[test]
    fn test_peer_summary_with_rtt() {
        let peer = PeerSummary {
            id: "peer-1".into(),
            connected: true,
            state: "active".into(),
            rtt_ms: Some(42),
        };
        let json: serde_json::Value = serde_json::to_value(&peer).unwrap();
        assert_eq!(json["id"], "peer-1");
        assert_eq!(json["connected"], true);
        assert_eq!(json["state"], "active");
        assert_eq!(json["rtt_ms"], 42);
    }

    #[test]
    fn test_peer_summary_without_rtt() {
        let peer = PeerSummary {
            id: "peer-2".into(),
            connected: false,
            state: "disconnected".into(),
            rtt_ms: None,
        };
        let json: serde_json::Value = serde_json::to_value(&peer).unwrap();
        assert_eq!(json["id"], "peer-2");
        assert_eq!(json["connected"], false);
        assert!(json["rtt_ms"].is_null());
    }

    #[test]
    fn test_topology_summary_serialization() {
        let topo = TopologySummary {
            peer_count: 5,
            role: "leader".into(),
            hierarchy_level: 1,
        };
        let json: serde_json::Value = serde_json::to_value(&topo).unwrap();
        assert_eq!(json["peer_count"], 5);
        assert_eq!(json["role"], "leader");
        assert_eq!(json["hierarchy_level"], 1);
    }

    #[test]
    fn test_topology_summary_standalone_node() {
        let topo = TopologySummary {
            peer_count: 0,
            role: "standalone".into(),
            hierarchy_level: 0,
        };
        let json: serde_json::Value = serde_json::to_value(&topo).unwrap();
        assert_eq!(json["peer_count"], 0);
        assert_eq!(json["role"], "standalone");
    }

    #[test]
    fn test_mesh_event_peer_connected() {
        let event = MeshEvent::PeerConnected {
            peer_id: "peer-2".into(),
        };
        let json: serde_json::Value = serde_json::to_value(&event).unwrap();
        assert_eq!(json["type"], "PeerConnected");
        assert_eq!(json["peer_id"], "peer-2");
        // Should only have type + peer_id
        assert_eq!(json.as_object().unwrap().len(), 2);
    }

    #[test]
    fn test_mesh_event_peer_disconnected() {
        let event = MeshEvent::PeerDisconnected {
            peer_id: "peer-3".into(),
            reason: "timeout".into(),
        };
        let json: serde_json::Value = serde_json::to_value(&event).unwrap();
        assert_eq!(json["type"], "PeerDisconnected");
        assert_eq!(json["peer_id"], "peer-3");
        assert_eq!(json["reason"], "timeout");
    }

    #[test]
    fn test_mesh_event_topology_changed() {
        let event = MeshEvent::TopologyChanged {
            new_role: "follower".into(),
            peer_count: 3,
        };
        let json: serde_json::Value = serde_json::to_value(&event).unwrap();
        assert_eq!(json["type"], "TopologyChanged");
        assert_eq!(json["new_role"], "follower");
        assert_eq!(json["peer_count"], 3);
    }

    #[test]
    fn test_mesh_event_sync_event() {
        let event = MeshEvent::SyncEvent {
            collection: "docs".into(),
            doc_id: "d1".into(),
            action: "insert".into(),
        };
        let json: serde_json::Value = serde_json::to_value(&event).unwrap();
        assert_eq!(json["type"], "SyncEvent");
        assert_eq!(json["collection"], "docs");
        assert_eq!(json["doc_id"], "d1");
        assert_eq!(json["action"], "insert");
    }

    #[test]
    fn test_mesh_node_info_debug_clone() {
        let info = MeshNodeInfo {
            node_id: "n1".into(),
            uptime_secs: 100,
            version: "1.0".into(),
        };
        let cloned = info.clone();
        assert_eq!(cloned.node_id, "n1");
        assert_eq!(cloned.uptime_secs, 100);
        let _ = format!("{:?}", info);
    }

    #[test]
    fn test_peer_summary_debug_clone() {
        let peer = PeerSummary {
            id: "p1".into(),
            connected: true,
            state: "active".into(),
            rtt_ms: Some(10),
        };
        let cloned = peer.clone();
        assert_eq!(cloned.id, "p1");
        assert!(cloned.connected);
        let _ = format!("{:?}", peer);
    }

    #[test]
    fn test_topology_summary_debug_clone() {
        let topo = TopologySummary {
            peer_count: 3,
            role: "leader".into(),
            hierarchy_level: 2,
        };
        let cloned = topo.clone();
        assert_eq!(cloned.peer_count, 3);
        assert_eq!(cloned.hierarchy_level, 2);
        let _ = format!("{:?}", topo);
    }

    #[test]
    fn test_mesh_event_debug_clone() {
        let event = MeshEvent::PeerConnected {
            peer_id: "p1".into(),
        };
        let cloned = event.clone();
        let _ = format!("{:?}", cloned);

        let event2 = MeshEvent::SyncEvent {
            collection: "docs".into(),
            doc_id: "d1".into(),
            action: "update".into(),
        };
        let cloned2 = event2.clone();
        let _ = format!("{:?}", cloned2);
    }

    #[test]
    fn test_mesh_event_topology_changed_clone() {
        let event = MeshEvent::TopologyChanged {
            new_role: "follower".into(),
            peer_count: 5,
        };
        let cloned = event.clone();
        let _ = format!("{:?}", cloned);
    }

    #[test]
    fn test_mesh_event_peer_disconnected_clone() {
        let event = MeshEvent::PeerDisconnected {
            peer_id: "p2".into(),
            reason: "timeout".into(),
        };
        let cloned = event.clone();
        let _ = format!("{:?}", cloned);
    }

    #[test]
    fn test_readiness_response_serialization() {
        let resp = ReadinessResponse {
            ready: true,
            node_id: "node-1".into(),
            checks: vec![ReadinessCheck {
                name: "transport".into(),
                ready: true,
                message: None,
            }],
        };
        let json: serde_json::Value = serde_json::to_value(&resp).unwrap();
        assert_eq!(json["ready"], true);
        assert_eq!(json["node_id"], "node-1");
        assert_eq!(json["checks"][0]["name"], "transport");
        assert_eq!(json["checks"][0]["ready"], true);
        assert!(json["checks"][0]["message"].is_null());
    }

    #[test]
    fn test_readiness_check_with_message() {
        let check = ReadinessCheck {
            name: "sync".into(),
            ready: false,
            message: Some("catching up".into()),
        };
        let json: serde_json::Value = serde_json::to_value(&check).unwrap();
        assert_eq!(json["name"], "sync");
        assert_eq!(json["ready"], false);
        assert_eq!(json["message"], "catching up");
    }

    #[test]
    fn test_readiness_response_debug_clone() {
        let resp = ReadinessResponse {
            ready: false,
            node_id: "n1".into(),
            checks: vec![],
        };
        let cloned = resp.clone();
        assert_eq!(cloned.ready, false);
        assert_eq!(cloned.node_id, "n1");
        let _ = format!("{:?}", resp);
    }

    /// Verify MeshBrokerState default methods return None.
    #[tokio::test]
    async fn test_default_trait_methods() {
        struct MinimalState {
            tx: broadcast::Sender<MeshEvent>,
        }

        #[async_trait::async_trait]
        impl MeshBrokerState for MinimalState {
            fn node_info(&self) -> MeshNodeInfo {
                MeshNodeInfo {
                    node_id: "n".into(),
                    uptime_secs: 0,
                    version: "0".into(),
                }
            }
            async fn list_peers(&self) -> Vec<PeerSummary> {
                vec![]
            }
            async fn get_peer(&self, _id: &str) -> Option<PeerSummary> {
                None
            }
            fn topology(&self) -> TopologySummary {
                TopologySummary {
                    peer_count: 0,
                    role: "none".into(),
                    hierarchy_level: 0,
                }
            }
            fn subscribe_events(&self) -> broadcast::Receiver<MeshEvent> {
                self.tx.subscribe()
            }
            // list_documents and get_document use defaults
        }

        let (tx, _) = broadcast::channel(1);
        let state = MinimalState { tx };

        assert!(state.list_documents("any").await.is_none());
        assert!(state.get_document("any", "id").await.is_none());
    }

    #[tokio::test]
    async fn test_trait_required_methods() {
        struct FullState {
            tx: broadcast::Sender<MeshEvent>,
        }

        #[async_trait::async_trait]
        impl MeshBrokerState for FullState {
            fn node_info(&self) -> MeshNodeInfo {
                MeshNodeInfo {
                    node_id: "full".into(),
                    uptime_secs: 42,
                    version: "1.0".into(),
                }
            }
            async fn list_peers(&self) -> Vec<PeerSummary> {
                vec![PeerSummary {
                    id: "p1".into(),
                    connected: true,
                    state: "active".into(),
                    rtt_ms: Some(10),
                }]
            }
            async fn get_peer(&self, id: &str) -> Option<PeerSummary> {
                if id == "p1" {
                    Some(PeerSummary {
                        id: "p1".into(),
                        connected: true,
                        state: "active".into(),
                        rtt_ms: Some(10),
                    })
                } else {
                    None
                }
            }
            fn topology(&self) -> TopologySummary {
                TopologySummary {
                    peer_count: 1,
                    role: "leader".into(),
                    hierarchy_level: 2,
                }
            }
            fn subscribe_events(&self) -> broadcast::Receiver<MeshEvent> {
                self.tx.subscribe()
            }
        }

        let (tx, _) = broadcast::channel(16);
        let state = FullState { tx };

        let info = state.node_info();
        assert_eq!(info.node_id, "full");
        assert_eq!(info.uptime_secs, 42);

        let peers = state.list_peers().await;
        assert_eq!(peers.len(), 1);

        let peer = state.get_peer("p1").await;
        assert!(peer.is_some());

        let no_peer = state.get_peer("missing").await;
        assert!(no_peer.is_none());

        let topo = state.topology();
        assert_eq!(topo.peer_count, 1);

        let _rx = state.subscribe_events();
    }
}