agentmux_srv_core/backend/storage/
container_limits.rs1use rusqlite::{params, OptionalExtension};
14
15use super::error::StoreError;
16use super::store::Store;
17use agentmux_common::time::now_secs;
18
19const CREATE_TABLE: &str = "CREATE TABLE IF NOT EXISTS db_agent_container_limits (
20 agent_id TEXT PRIMARY KEY,
21 memory_mb TEXT NOT NULL DEFAULT '',
22 cpus TEXT NOT NULL DEFAULT '',
23 updated_at INTEGER NOT NULL DEFAULT 0
24)";
25
26impl Store {
27 pub fn container_limits_get(&self, agent_id: &str) -> Result<Option<(String, String)>, StoreError> {
29 let conn = self.conn.lock().unwrap();
30 conn.execute_batch(CREATE_TABLE)?;
31 Ok(conn
32 .query_row(
33 "SELECT memory_mb, cpus FROM db_agent_container_limits WHERE agent_id = ?1",
34 params![agent_id.to_lowercase()],
35 |row| Ok((row.get(0)?, row.get(1)?)),
36 )
37 .optional()?)
38 }
39
40 pub fn container_limits_set(&self, agent_id: &str, memory_mb: &str, cpus: &str) -> Result<(), StoreError> {
42 let conn = self.conn.lock().unwrap();
43 conn.execute_batch(CREATE_TABLE)?;
44 conn.execute(
45 "INSERT INTO db_agent_container_limits (agent_id, memory_mb, cpus, updated_at) VALUES (?1, ?2, ?3, ?4)
46 ON CONFLICT(agent_id) DO UPDATE SET memory_mb = ?2, cpus = ?3, updated_at = ?4",
47 params![agent_id.to_lowercase(), memory_mb, cpus, now_secs()],
48 )?;
49 Ok(())
50 }
51}
52
53#[cfg(test)]
54mod tests {
55 use super::*;
56
57 #[test]
58 fn an_agent_with_no_row_has_no_limits_set_and_a_set_replaces_the_row() {
59 let store = Store::open(std::path::Path::new(":memory:")).unwrap();
60 assert_eq!(store.container_limits_get("Aria").unwrap(), None);
61 store.container_limits_set("Aria", "4096", "").unwrap();
62 assert_eq!(store.container_limits_get("aria").unwrap(), Some(("4096".to_string(), String::new())), "keyed case-insensitively");
63 store.container_limits_set("aria", "0", "2").unwrap();
64 assert_eq!(store.container_limits_get("ARIA").unwrap(), Some(("0".to_string(), "2".to_string())));
65 }
66}