peat-mesh 0.8.2

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
//! Configuration types for the PeatMesh facade.

use crate::topology::TopologyConfig;
use crate::transport::TransportManagerConfig;
use std::path::PathBuf;
use std::time::Duration;

/// Configuration for the Iroh networking layer.
#[derive(Debug, Clone)]
pub struct IrohConfig {
    /// Explicit bind address for the Iroh endpoint.
    /// When `None`, Iroh picks an available port automatically.
    pub bind_addr: Option<std::net::SocketAddr>,
    /// Relay server URLs for NAT traversal.
    /// Empty means use Iroh's default relay infrastructure.
    pub relay_urls: Vec<String>,
    /// Deterministic Iroh identity seed (32 bytes).
    /// When `Some`, used as `SecretKey::from_bytes()` for the Iroh endpoint,
    /// giving the node a stable, reproducible identity.
    pub secret_key: Option<[u8; 32]>,
    /// Timeout for binding the QUIC endpoint (default: 10s).
    pub bind_timeout: Duration,
    /// Timeout for graceful shutdown (default: 5s).
    pub shutdown_timeout: Duration,
    /// Timeout for blob download operations from remote peers (default: 30s).
    pub download_timeout: Duration,
}

impl Default for IrohConfig {
    fn default() -> Self {
        Self {
            bind_addr: None,
            relay_urls: Vec::new(),
            secret_key: None,
            bind_timeout: Duration::from_secs(10),
            shutdown_timeout: Duration::from_secs(5),
            download_timeout: Duration::from_secs(30),
        }
    }
}

/// Top-level configuration for PeatMesh.
///
/// Composes topology, discovery, and security settings into a single
/// configuration struct that drives the [`crate::mesh::PeatMesh`] facade.
#[derive(Debug, Clone, Default)]
pub struct MeshConfig {
    /// Node identifier. Auto-generated (UUID v4) if `None`.
    pub node_id: Option<String>,
    /// Optional path for persistent storage.
    pub storage_path: Option<PathBuf>,
    /// Topology formation configuration.
    pub topology: TopologyConfig,
    /// Peer discovery configuration.
    pub discovery: MeshDiscoveryConfig,
    /// Security configuration.
    pub security: SecurityConfig,
    /// Transport manager configuration for multi-transport selection.
    pub transport_manager: Option<TransportManagerConfig>,
    /// Iroh networking configuration.
    pub iroh: IrohConfig,
    /// Automerge CRDT compaction configuration.
    pub compaction: CompactionConfig,
}

/// Configuration for periodic Automerge document compaction.
///
/// Compaction discards CRDT revision history via `fork()`, keeping only the
/// current document state. This bounds memory growth on long-running nodes
/// at the cost of a full-state sync on the next peer exchange.
#[derive(Debug, Clone)]
pub struct CompactionConfig {
    /// Enable automatic background compaction. Default: `false`.
    pub enabled: bool,
    /// How often the compaction sweep runs. Default: 5 minutes.
    /// Clamped to a minimum of 10 seconds to prevent busy-looping.
    pub interval: Duration,
    /// Only compact documents larger than this threshold. Default: 64 KiB.
    pub size_threshold_bytes: usize,
    /// Collections to compact. When empty and compaction is enabled,
    /// auto-derives from `SyncModeRegistry` (all `LatestOnly` collections).
    /// Only `LatestOnly` collections are safe to compact — compacting
    /// `FullHistory` collections destroys change history needed for delta sync.
    pub collections: Vec<String>,
}

/// Minimum compaction interval to prevent busy-looping (10 seconds).
const MIN_COMPACTION_INTERVAL: Duration = Duration::from_secs(10);

impl CompactionConfig {
    /// Returns the effective interval, clamped to at least 10 seconds.
    pub fn effective_interval(&self) -> Duration {
        self.interval.max(MIN_COMPACTION_INTERVAL)
    }
}

impl Default for CompactionConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            interval: Duration::from_secs(300),
            size_threshold_bytes: 64 * 1024,
            collections: Vec::new(),
        }
    }
}

/// Discovery settings for mesh peer discovery.
#[derive(Debug, Clone)]
pub struct MeshDiscoveryConfig {
    /// Enable mDNS-based peer discovery.
    pub mdns_enabled: bool,
    /// Service name advertised during discovery.
    pub service_name: String,
    /// Discovery broadcast interval.
    pub interval: Duration,
}

impl Default for MeshDiscoveryConfig {
    fn default() -> Self {
        Self {
            mdns_enabled: true,
            service_name: "peat-mesh".to_string(),
            interval: Duration::from_secs(30),
        }
    }
}

/// Security settings for mesh communications.
#[derive(Debug, Clone)]
pub struct SecurityConfig {
    /// Enable encryption for mesh communications.
    pub encryption_enabled: bool,
    /// Require cryptographic peer identity verification.
    pub require_peer_verification: bool,
}

impl Default for SecurityConfig {
    fn default() -> Self {
        Self {
            encryption_enabled: true,
            require_peer_verification: false,
        }
    }
}

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

    // ── MeshConfig defaults ──────────────────────────────────────

    #[test]
    fn test_mesh_config_default_node_id_is_none() {
        let cfg = MeshConfig::default();
        assert!(cfg.node_id.is_none());
    }

    #[test]
    fn test_mesh_config_default_storage_path_is_none() {
        let cfg = MeshConfig::default();
        assert!(cfg.storage_path.is_none());
    }

    #[test]
    fn test_mesh_config_default_topology() {
        let cfg = MeshConfig::default();
        // TopologyConfig default reevaluation_interval is 30s
        assert_eq!(
            cfg.topology.reevaluation_interval,
            Some(Duration::from_secs(30))
        );
    }

    #[test]
    fn test_mesh_config_default_discovery() {
        let cfg = MeshConfig::default();
        assert!(cfg.discovery.mdns_enabled);
        assert_eq!(cfg.discovery.service_name, "peat-mesh");
    }

    #[test]
    fn test_mesh_config_default_security() {
        let cfg = MeshConfig::default();
        assert!(cfg.security.encryption_enabled);
        assert!(!cfg.security.require_peer_verification);
    }

    #[test]
    fn test_mesh_config_custom_values() {
        let cfg = MeshConfig {
            node_id: Some("custom-node".to_string()),
            storage_path: Some(PathBuf::from("/tmp/mesh")),
            discovery: MeshDiscoveryConfig {
                mdns_enabled: false,
                service_name: "my-mesh".to_string(),
                interval: Duration::from_secs(10),
            },
            security: SecurityConfig {
                encryption_enabled: false,
                require_peer_verification: true,
            },
            ..Default::default()
        };
        assert_eq!(cfg.node_id.as_deref(), Some("custom-node"));
        assert_eq!(
            cfg.storage_path.as_deref(),
            Some(std::path::Path::new("/tmp/mesh"))
        );
        assert!(!cfg.discovery.mdns_enabled);
        assert_eq!(cfg.discovery.service_name, "my-mesh");
        assert_eq!(cfg.discovery.interval, Duration::from_secs(10));
        assert!(!cfg.security.encryption_enabled);
        assert!(cfg.security.require_peer_verification);
    }

    #[test]
    fn test_mesh_config_clone() {
        let cfg = MeshConfig {
            node_id: Some("cloned".to_string()),
            ..Default::default()
        };
        let cloned = cfg.clone();
        assert_eq!(cloned.node_id, cfg.node_id);
    }

    #[test]
    fn test_mesh_config_debug() {
        let cfg = MeshConfig::default();
        let debug = format!("{:?}", cfg);
        assert!(debug.contains("MeshConfig"));
    }

    // ── MeshDiscoveryConfig defaults ─────────────────────────────

    #[test]
    fn test_discovery_config_default_mdns_enabled() {
        let cfg = MeshDiscoveryConfig::default();
        assert!(cfg.mdns_enabled);
    }

    #[test]
    fn test_discovery_config_default_service_name() {
        let cfg = MeshDiscoveryConfig::default();
        assert_eq!(cfg.service_name, "peat-mesh");
    }

    #[test]
    fn test_discovery_config_default_interval() {
        let cfg = MeshDiscoveryConfig::default();
        assert_eq!(cfg.interval, Duration::from_secs(30));
    }

    #[test]
    fn test_discovery_config_custom() {
        let cfg = MeshDiscoveryConfig {
            mdns_enabled: false,
            service_name: "custom".to_string(),
            interval: Duration::from_secs(5),
        };
        assert!(!cfg.mdns_enabled);
        assert_eq!(cfg.service_name, "custom");
        assert_eq!(cfg.interval, Duration::from_secs(5));
    }

    #[test]
    fn test_discovery_config_clone() {
        let cfg = MeshDiscoveryConfig::default();
        let cloned = cfg.clone();
        assert_eq!(cloned.service_name, cfg.service_name);
    }

    #[test]
    fn test_discovery_config_debug() {
        let cfg = MeshDiscoveryConfig::default();
        let debug = format!("{:?}", cfg);
        assert!(debug.contains("MeshDiscoveryConfig"));
    }

    // ── IrohConfig defaults ───────────────────────────────────────

    #[test]
    fn test_iroh_config_default() {
        let cfg = IrohConfig::default();
        assert!(cfg.bind_addr.is_none());
        assert!(cfg.relay_urls.is_empty());
        assert_eq!(cfg.bind_timeout, Duration::from_secs(10));
        assert_eq!(cfg.shutdown_timeout, Duration::from_secs(5));
        assert_eq!(cfg.download_timeout, Duration::from_secs(30));
    }

    #[test]
    fn test_iroh_config_custom_bind_addr() {
        let cfg = IrohConfig {
            bind_addr: Some("0.0.0.0:4433".parse().unwrap()),
            relay_urls: vec!["https://relay.example.com".to_string()],
            ..Default::default()
        };
        assert_eq!(cfg.bind_addr.unwrap().port(), 4433);
        assert_eq!(cfg.relay_urls.len(), 1);
    }

    #[test]
    fn test_iroh_config_secret_key() {
        let key = [42u8; 32];
        let cfg = IrohConfig {
            secret_key: Some(key),
            ..Default::default()
        };
        assert_eq!(cfg.secret_key.unwrap(), [42u8; 32]);
    }

    #[test]
    fn test_mesh_config_default_iroh() {
        let cfg = MeshConfig::default();
        assert!(cfg.iroh.bind_addr.is_none());
        assert!(cfg.iroh.relay_urls.is_empty());
    }

    // ── SecurityConfig defaults ──────────────────────────────────

    #[test]
    fn test_security_config_default_encryption_enabled() {
        let cfg = SecurityConfig::default();
        assert!(cfg.encryption_enabled);
    }

    #[test]
    fn test_security_config_default_peer_verification_disabled() {
        let cfg = SecurityConfig::default();
        assert!(!cfg.require_peer_verification);
    }

    #[test]
    fn test_security_config_custom() {
        let cfg = SecurityConfig {
            encryption_enabled: false,
            require_peer_verification: true,
        };
        assert!(!cfg.encryption_enabled);
        assert!(cfg.require_peer_verification);
    }

    #[test]
    fn test_security_config_clone() {
        let cfg = SecurityConfig {
            encryption_enabled: true,
            require_peer_verification: true,
        };
        let cloned = cfg.clone();
        assert_eq!(cloned.encryption_enabled, cfg.encryption_enabled);
        assert_eq!(
            cloned.require_peer_verification,
            cfg.require_peer_verification
        );
    }

    #[test]
    fn test_security_config_debug() {
        let cfg = SecurityConfig::default();
        let debug = format!("{:?}", cfg);
        assert!(debug.contains("SecurityConfig"));
    }

    // ── CompactionConfig defaults ────────────────────────────────

    #[test]
    fn test_compaction_config_default_disabled() {
        let cfg = CompactionConfig::default();
        assert!(!cfg.enabled);
    }

    #[test]
    fn test_compaction_config_default_interval() {
        let cfg = CompactionConfig::default();
        assert_eq!(cfg.interval, Duration::from_secs(300));
    }

    #[test]
    fn test_compaction_config_default_threshold() {
        let cfg = CompactionConfig::default();
        assert_eq!(cfg.size_threshold_bytes, 64 * 1024);
    }

    #[test]
    fn test_compaction_config_custom() {
        let cfg = CompactionConfig {
            enabled: true,
            interval: Duration::from_secs(60),
            size_threshold_bytes: 1024,
            collections: vec!["beacons".to_string()],
        };
        assert!(cfg.enabled);
        assert_eq!(cfg.interval, Duration::from_secs(60));
        assert_eq!(cfg.size_threshold_bytes, 1024);
        assert_eq!(cfg.collections.len(), 1);
    }

    #[test]
    fn test_compaction_config_clone() {
        let cfg = CompactionConfig {
            enabled: false,
            ..Default::default()
        };
        let cloned = cfg.clone();
        assert_eq!(cloned.enabled, cfg.enabled);
        assert_eq!(cloned.interval, cfg.interval);
    }

    #[test]
    fn test_compaction_config_debug() {
        let cfg = CompactionConfig::default();
        let debug = format!("{:?}", cfg);
        assert!(debug.contains("CompactionConfig"));
    }

    #[test]
    fn test_mesh_config_default_compaction() {
        let cfg = MeshConfig::default();
        assert!(!cfg.compaction.enabled);
        assert_eq!(cfg.compaction.interval, Duration::from_secs(300));
        assert!(cfg.compaction.collections.is_empty());
    }

    #[test]
    fn test_compaction_config_zero_interval_clamped() {
        let cfg = CompactionConfig {
            interval: Duration::from_secs(0),
            ..Default::default()
        };
        assert_eq!(cfg.effective_interval(), Duration::from_secs(10));
    }

    #[test]
    fn test_compaction_config_tiny_interval_clamped() {
        let cfg = CompactionConfig {
            interval: Duration::from_secs(3),
            ..Default::default()
        };
        assert_eq!(cfg.effective_interval(), Duration::from_secs(10));
    }

    #[test]
    fn test_compaction_config_large_interval_unchanged() {
        let cfg = CompactionConfig {
            interval: Duration::from_secs(600),
            ..Default::default()
        };
        assert_eq!(cfg.effective_interval(), Duration::from_secs(600));
    }

    #[test]
    fn test_compaction_config_exactly_min_interval() {
        let cfg = CompactionConfig {
            interval: Duration::from_secs(10),
            ..Default::default()
        };
        assert_eq!(cfg.effective_interval(), Duration::from_secs(10));
    }

    #[test]
    fn test_compaction_config_with_collections() {
        let cfg = CompactionConfig {
            enabled: true,
            collections: vec!["beacons".to_string(), "platforms".to_string()],
            ..Default::default()
        };
        assert!(cfg.enabled);
        assert_eq!(cfg.collections.len(), 2);
        assert_eq!(cfg.collections[0], "beacons");
    }
}