Skip to main content

cortex_runtime/pool/
resource_governor.rs

1//! Resource governor — enforces memory limits on the browser pool.
2
3use std::sync::atomic::{AtomicU64, Ordering};
4use std::sync::Arc;
5
6/// Tracks and enforces resource limits for the browser pool.
7pub struct ResourceGovernor {
8    /// Current estimated memory usage in bytes.
9    memory_usage: Arc<AtomicU64>,
10    /// Maximum allowed memory in bytes.
11    memory_limit: u64,
12    /// Per-request timeout in milliseconds.
13    request_timeout_ms: u64,
14}
15
16impl ResourceGovernor {
17    /// Create a new resource governor with a memory limit in megabytes.
18    pub fn new(memory_limit_mb: u64, request_timeout_ms: u64) -> Self {
19        Self {
20            memory_usage: Arc::new(AtomicU64::new(0)),
21            memory_limit: memory_limit_mb * 1024 * 1024,
22            request_timeout_ms,
23        }
24    }
25
26    /// Check if acquiring another context would exceed the memory limit.
27    pub fn can_acquire(&self, estimated_mb: u64) -> bool {
28        let current = self.memory_usage.load(Ordering::SeqCst);
29        current + (estimated_mb * 1024 * 1024) <= self.memory_limit
30    }
31
32    /// Record memory allocation for a context.
33    pub fn record_allocation(&self, bytes: u64) {
34        self.memory_usage.fetch_add(bytes, Ordering::SeqCst);
35    }
36
37    /// Record memory deallocation when a context is released.
38    pub fn record_deallocation(&self, bytes: u64) {
39        self.memory_usage.fetch_sub(bytes, Ordering::SeqCst);
40    }
41
42    /// Current memory usage in bytes.
43    pub fn memory_usage_bytes(&self) -> u64 {
44        self.memory_usage.load(Ordering::SeqCst)
45    }
46
47    /// Current memory usage in megabytes.
48    pub fn memory_usage_mb(&self) -> f64 {
49        self.memory_usage_bytes() as f64 / (1024.0 * 1024.0)
50    }
51
52    /// Per-request timeout in milliseconds.
53    pub fn request_timeout_ms(&self) -> u64 {
54        self.request_timeout_ms
55    }
56
57    /// Memory limit in megabytes.
58    pub fn memory_limit_mb(&self) -> u64 {
59        self.memory_limit / (1024 * 1024)
60    }
61}