communitas-core 0.12.4

Core business logic for Communitas - PQC collaboration with virtual disks
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
// SPDX-License-Identifier: MIT OR Apache-2.0

// Copyright (c) 2025 Saorsa Labs Limited
//
// Licensed under the AGPL-3.0 license

//! Resource Limits and Management
//!
//! Implements MESH_CAPABILITIES.md Section 8.3: Resource management and limits
//! to prevent OOM, connection exhaustion, and bandwidth saturation.

use serde::{Deserialize, Serialize};
use std::time::Duration;
use sysinfo::{System, get_current_pid};
use thiserror::Error;
use tracing::warn;

/// Resource limit errors
#[derive(Error, Debug)]
pub enum ResourceLimitError {
    #[error("Peer connection limit exceeded: {current}/{limit}")]
    PeerLimitExceeded { current: usize, limit: usize },

    #[error("Memory limit exceeded: {current}MB/{limit_mb}MB")]
    MemoryLimitExceeded { current: usize, limit_mb: usize },

    #[error("Document size too large: {size_mb}MB/{limit_mb}MB")]
    DocumentTooLarge { size_mb: usize, limit_mb: usize },

    #[error("Upload rate limit exceeded: {current:.2}Mbps/{max:.2}Mbps")]
    UploadRateExceeded { current: f64, max: f64 },

    #[error("Download rate limit exceeded: {current:.2}Mbps/{max:.2}Mbps")]
    DownloadRateExceeded { current: f64, max: f64 },

    #[error("Connection timeout: {0:?}")]
    Timeout(Duration),
}

/// Result type for resource limit operations
pub type ResourceLimitResult<T> = Result<T, ResourceLimitError>;

/// Resource limits configuration (loadable from TOML)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ResourceLimitsConfig {
    /// Maximum number of concurrent peer connections
    pub max_peer_connections: usize,

    /// Maximum number of relay connections
    pub max_relay_connections: usize,

    /// Maximum memory usage in megabytes
    pub max_memory_mb: usize,

    /// Maximum CRDT document size in megabytes
    pub crdt_document_limit_mb: usize,

    /// Connection timeout in seconds
    pub connection_timeout_secs: u64,

    /// Maximum anti-entropy sync interval in seconds
    pub anti_entropy_max_interval_secs: u64,

    /// Optional upload rate limit in Mbps
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_upload_rate_mbps: Option<u64>,

    /// Optional download rate limit in Mbps
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_download_rate_mbps: Option<u64>,
}

impl Default for ResourceLimitsConfig {
    fn default() -> Self {
        Self {
            max_peer_connections: 50,
            max_relay_connections: 3,
            max_memory_mb: 2048,
            crdt_document_limit_mb: 50,
            connection_timeout_secs: 30,
            anti_entropy_max_interval_secs: 300,
            max_upload_rate_mbps: None,
            max_download_rate_mbps: None,
        }
    }
}

/// Current resource usage snapshot
#[derive(Debug, Clone)]
pub struct ResourceUsage {
    pub peer_connections: usize,
    pub memory_mb: usize,
    pub upload_rate_mbps: f64,
    pub download_rate_mbps: f64,
}

/// Resource limits manager
///
/// Enforces resource constraints to prevent:
/// - Connection exhaustion
/// - Out-of-memory conditions
/// - Bandwidth saturation
/// - Excessive sync intervals
#[derive(Debug, Clone)]
pub struct ResourceLimits {
    pub max_peer_connections: usize,
    pub max_relay_connections: usize,
    pub max_memory_mb: usize,
    pub crdt_document_limit_mb: usize,
    pub connection_timeout: Duration,
    pub anti_entropy_max_interval: Duration,
    pub upload_rate_limit_mbps: Option<u64>,
    pub download_rate_limit_mbps: Option<u64>,
}

impl Default for ResourceLimits {
    fn default() -> Self {
        // Direct construction to avoid recursion with from_config fallback
        let config = ResourceLimitsConfig::default();
        Self {
            max_peer_connections: config.max_peer_connections,
            max_relay_connections: config.max_relay_connections,
            max_memory_mb: config.max_memory_mb,
            crdt_document_limit_mb: config.crdt_document_limit_mb,
            connection_timeout: Duration::from_secs(config.connection_timeout_secs),
            anti_entropy_max_interval: Duration::from_secs(config.anti_entropy_max_interval_secs),
            upload_rate_limit_mbps: config.max_upload_rate_mbps,
            download_rate_limit_mbps: config.max_download_rate_mbps,
        }
    }
}

impl ResourceLimits {
    /// Create resource limits from configuration with validation.
    ///
    /// Returns `Err` if the configuration is invalid (e.g., zero limits,
    /// document size exceeds memory limit).
    pub fn try_from_config(config: ResourceLimitsConfig) -> ResourceLimitResult<Self> {
        // Validate: peer connections must be positive
        if config.max_peer_connections == 0 {
            return Err(ResourceLimitError::PeerLimitExceeded {
                current: 0,
                limit: 0,
            });
        }

        // Validate: memory must be positive
        if config.max_memory_mb == 0 {
            return Err(ResourceLimitError::MemoryLimitExceeded {
                current: 0,
                limit_mb: 0,
            });
        }

        // Validate: document limit should not exceed memory limit
        if config.crdt_document_limit_mb > config.max_memory_mb {
            return Err(ResourceLimitError::MemoryLimitExceeded {
                current: config.crdt_document_limit_mb,
                limit_mb: config.max_memory_mb,
            });
        }

        Ok(Self {
            max_peer_connections: config.max_peer_connections,
            max_relay_connections: config.max_relay_connections,
            max_memory_mb: config.max_memory_mb,
            crdt_document_limit_mb: config.crdt_document_limit_mb,
            connection_timeout: Duration::from_secs(config.connection_timeout_secs),
            anti_entropy_max_interval: Duration::from_secs(config.anti_entropy_max_interval_secs),
            upload_rate_limit_mbps: config.max_upload_rate_mbps,
            download_rate_limit_mbps: config.max_download_rate_mbps,
        })
    }

    /// Create resource limits from configuration.
    ///
    /// Logs a warning and uses safe defaults if validation fails.
    /// For stricter error handling, use [`Self::try_from_config`].
    pub fn from_config(config: ResourceLimitsConfig) -> Self {
        match Self::try_from_config(config) {
            Ok(limits) => limits,
            Err(e) => {
                warn!(
                    "Invalid resource limits configuration: {}. Using safe defaults.",
                    e
                );
                Self::default()
            }
        }
    }

    /// Create low-resource preset for constrained devices
    pub fn low_resource() -> Self {
        Self::from_config(ResourceLimitsConfig {
            max_peer_connections: 20,
            max_relay_connections: 1,
            max_memory_mb: 512,
            crdt_document_limit_mb: 10,
            connection_timeout_secs: 15,
            anti_entropy_max_interval_secs: 600, // 10 min
            max_upload_rate_mbps: Some(5),
            max_download_rate_mbps: Some(20),
        })
    }

    /// Create high-performance preset for powerful devices
    pub fn high_performance() -> Self {
        Self::from_config(ResourceLimitsConfig {
            max_peer_connections: 200,
            max_relay_connections: 10,
            max_memory_mb: 8192,
            crdt_document_limit_mb: 200,
            connection_timeout_secs: 60,
            anti_entropy_max_interval_secs: 60, // 1 min
            max_upload_rate_mbps: None,
            max_download_rate_mbps: None,
        })
    }

    /// Enforce peer connection limit
    pub fn enforce_peer_limit(&self, current: usize) -> ResourceLimitResult<()> {
        if current >= self.max_peer_connections {
            Err(ResourceLimitError::PeerLimitExceeded {
                current,
                limit: self.max_peer_connections,
            })
        } else {
            Ok(())
        }
    }

    /// Enforce memory limit
    pub fn enforce_memory_limit(&self, current_mb: usize) -> ResourceLimitResult<()> {
        if current_mb > self.max_memory_mb {
            Err(ResourceLimitError::MemoryLimitExceeded {
                current: current_mb,
                limit_mb: self.max_memory_mb,
            })
        } else {
            Ok(())
        }
    }

    /// Enforce relay connection limit
    pub fn enforce_relay_limit(&self, current: usize) -> ResourceLimitResult<()> {
        if current >= self.max_relay_connections {
            Err(ResourceLimitError::PeerLimitExceeded {
                current,
                limit: self.max_relay_connections,
            })
        } else {
            Ok(())
        }
    }

    /// Enforce CRDT document size limit
    pub fn enforce_document_limit(&self, size_mb: usize) -> ResourceLimitResult<()> {
        if size_mb > self.crdt_document_limit_mb {
            Err(ResourceLimitError::DocumentTooLarge {
                size_mb,
                limit_mb: self.crdt_document_limit_mb,
            })
        } else {
            Ok(())
        }
    }

    /// Check memory usage against limit
    pub fn check_memory_usage(&self, current_mb: usize) -> ResourceLimitResult<()> {
        self.enforce_memory_limit(current_mb)
    }

    /// Enforce upload rate limit
    pub fn enforce_upload_rate(&self, current_mbps: f64) -> ResourceLimitResult<()> {
        if let Some(max) = self.upload_rate_limit_mbps {
            let max_f64 = max as f64;
            if current_mbps > max_f64 {
                return Err(ResourceLimitError::UploadRateExceeded {
                    current: current_mbps,
                    max: max_f64,
                });
            }
        }
        Ok(())
    }

    /// Enforce download rate limit
    pub fn enforce_download_rate(&self, current_mbps: f64) -> ResourceLimitResult<()> {
        if let Some(max) = self.download_rate_limit_mbps {
            let max_f64 = max as f64;
            if current_mbps > max_f64 {
                return Err(ResourceLimitError::DownloadRateExceeded {
                    current: current_mbps,
                    max: max_f64,
                });
            }
        }
        Ok(())
    }

    /// Convert upload rate limit to bytes per second
    pub fn upload_rate_bytes_per_sec(&self) -> Option<u64> {
        self.upload_rate_limit_mbps.map(|mbps| mbps * 125_000)
    }

    /// Convert download rate limit to bytes per second
    pub fn download_rate_bytes_per_sec(&self) -> Option<u64> {
        self.download_rate_limit_mbps.map(|mbps| mbps * 125_000)
    }

    /// Validate configuration for consistency
    pub fn validate(&self) -> ResourceLimitResult<()> {
        // Peer connections must be positive
        if self.max_peer_connections == 0 {
            return Err(ResourceLimitError::PeerLimitExceeded {
                current: 0,
                limit: 0,
            });
        }

        // Memory must be positive
        if self.max_memory_mb == 0 {
            return Err(ResourceLimitError::MemoryLimitExceeded {
                current: 0,
                limit_mb: 0,
            });
        }

        // Document limit should not exceed memory limit
        if self.crdt_document_limit_mb > self.max_memory_mb {
            return Err(ResourceLimitError::MemoryLimitExceeded {
                current: self.crdt_document_limit_mb,
                limit_mb: self.max_memory_mb,
            });
        }

        Ok(())
    }

    /// Check all limits against current usage
    pub fn check_all(&self, usage: &ResourceUsage) -> ResourceLimitResult<()> {
        self.enforce_peer_limit(usage.peer_connections)?;
        self.enforce_memory_limit(usage.memory_mb)?;
        self.enforce_upload_rate(usage.upload_rate_mbps)?;
        self.enforce_download_rate(usage.download_rate_mbps)?;
        Ok(())
    }

    /// Measure current usage with a provided peer count
    ///
    /// If memory monitoring is unavailable, uses max_memory_mb as a conservative
    /// fallback to prevent bypassing memory limits.
    pub fn measure_usage_with_peers(&self, peer_connections: usize) -> ResourceUsage {
        // Use max_memory_mb as conservative fallback if measurement fails
        // This prevents silently bypassing memory limits when monitoring unavailable
        let memory_mb = current_process_memory_mb().unwrap_or(self.max_memory_mb);
        ResourceUsage {
            peer_connections,
            memory_mb,
            upload_rate_mbps: 0.0,
            download_rate_mbps: 0.0,
        }
    }

    /// Get current resource usage from system
    pub fn measure_current_usage(&self) -> ResourceUsage {
        self.measure_usage_with_peers(0)
    }
}

fn current_process_memory_mb() -> Option<usize> {
    let pid = match get_current_pid() {
        Ok(pid) => pid,
        Err(e) => {
            warn!(
                "Failed to get current process ID for memory monitoring: {}",
                e
            );
            return None;
        }
    };
    let mut system = System::new();
    system.refresh_processes();
    match system.process(pid) {
        // process.memory() returns bytes, divide by 1024*1024 to get MB
        Some(process) => Some((process.memory() / (1024 * 1024)) as usize),
        None => {
            warn!("Failed to find current process in system info for memory monitoring");
            None
        }
    }
}

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

    #[test]
    fn test_config_serialization() {
        let config = ResourceLimitsConfig::default();
        let toml = toml::to_string(&config).expect("Serialize");
        let parsed: ResourceLimitsConfig = toml::from_str(&toml).expect("Deserialize");

        assert_eq!(parsed.max_peer_connections, 50);
        assert_eq!(parsed.max_memory_mb, 2048);
    }

    #[test]
    fn test_try_from_config_valid() {
        let config = ResourceLimitsConfig::default();
        let result = ResourceLimits::try_from_config(config);
        assert!(result.is_ok());
        let limits = result.unwrap();
        assert_eq!(limits.max_peer_connections, 50);
        assert_eq!(limits.max_memory_mb, 2048);
    }

    #[test]
    fn test_try_from_config_zero_peer_connections() {
        let config = ResourceLimitsConfig {
            max_peer_connections: 0,
            ..ResourceLimitsConfig::default()
        };
        let result = ResourceLimits::try_from_config(config);
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            ResourceLimitError::PeerLimitExceeded { .. }
        ));
    }

    #[test]
    fn test_try_from_config_zero_memory() {
        let config = ResourceLimitsConfig {
            max_memory_mb: 0,
            ..ResourceLimitsConfig::default()
        };
        let result = ResourceLimits::try_from_config(config);
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            ResourceLimitError::MemoryLimitExceeded { .. }
        ));
    }

    #[test]
    fn test_try_from_config_document_exceeds_memory() {
        let config = ResourceLimitsConfig {
            max_memory_mb: 100,
            crdt_document_limit_mb: 200,
            ..ResourceLimitsConfig::default()
        };
        let result = ResourceLimits::try_from_config(config);
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            ResourceLimitError::MemoryLimitExceeded { .. }
        ));
    }

    #[test]
    fn test_from_config_invalid_falls_back_to_defaults() {
        let config = ResourceLimitsConfig {
            max_peer_connections: 0,
            max_memory_mb: 0,
            ..ResourceLimitsConfig::default()
        };
        // from_config should fall back to defaults instead of panicking
        let limits = ResourceLimits::from_config(config);
        // Should have default values, not zeros
        assert_eq!(limits.max_peer_connections, 50);
        assert_eq!(limits.max_memory_mb, 2048);
    }

    #[test]
    fn test_from_config_valid_uses_provided_values() {
        let config = ResourceLimitsConfig {
            max_peer_connections: 100,
            max_memory_mb: 4096,
            ..ResourceLimitsConfig::default()
        };
        let limits = ResourceLimits::from_config(config);
        assert_eq!(limits.max_peer_connections, 100);
        assert_eq!(limits.max_memory_mb, 4096);
    }

    #[test]
    fn test_default_is_valid() {
        let limits = ResourceLimits::default();
        // Should be able to validate successfully
        assert!(limits.validate().is_ok());
        assert_eq!(limits.max_peer_connections, 50);
        assert_eq!(limits.max_memory_mb, 2048);
    }

    #[test]
    fn test_low_resource_is_valid() {
        let limits = ResourceLimits::low_resource();
        assert!(limits.validate().is_ok());
    }

    #[test]
    fn test_high_performance_is_valid() {
        let limits = ResourceLimits::high_performance();
        assert!(limits.validate().is_ok());
    }
}