agentmux_srv_core/backend/slug_migration/
running.rs1use std::path::Path;
11
12use rusqlite::Connection;
13use serde_json::Value;
14
15use super::home::{fold, open_ro, place, Home, Install};
16use super::plan::Def;
17use crate::backend::reactive::registry::{pid_alive, AgentEntry};
18use crate::backend::rpc_types::ForkSlugRunning;
19use agentmux_common::slug::{agent_route_name, file_stem};
20
21pub(super) fn registration(dir: &Path, name: &str) -> Option<AgentEntry> {
23 let entry: AgentEntry = serde_json::from_slice(&std::fs::read(dir.join(format!("{}.json", file_stem(name)))).ok()?).ok()?;
24 entry.srv_alive().then_some(entry)
25}
26
27pub(super) fn shared_entries(home: &Home, name: &str) -> Vec<AgentEntry> {
29 let dir = home.reactive().join(file_stem(name));
30 let Ok(files) = std::fs::read_dir(dir) else { return Vec::new() };
31 files
32 .flatten()
33 .filter(|f| f.path().extension().and_then(|e| e.to_str()) == Some("json"))
34 .filter_map(|f| serde_json::from_slice::<AgentEntry>(&std::fs::read(f.path()).ok()?).ok())
35 .filter(AgentEntry::srv_alive)
36 .collect()
37}
38
39pub(super) fn block_agent(conn: &Connection, block_id: &str) -> Option<String> {
42 if block_id.is_empty() {
43 return None;
44 }
45 let data: Vec<u8> = conn.query_row("SELECT data FROM db_block WHERE oid = ?1", [block_id], |r| r.get(0)).ok()?;
46 let block: Value = serde_json::from_slice(&data).ok()?;
47 let meta = block.get("meta")?;
48 ["agentId", "agent:id"].iter().find_map(|k| meta.get(*k).and_then(Value::as_str).filter(|s| !s.is_empty()).map(str::to_string))
49}
50
51fn names_of(def: &Def) -> Vec<String> {
54 let mut names = vec![fold(&def.slug), fold(&agent_route_name(&def.name))];
55 names.extend(def.former.iter().map(|f| fold(f)));
56 names.sort();
57 names.dedup();
58 names.retain(|n| !n.is_empty());
59 names
60}
61
62pub(super) fn running(home: &Home, installs: &[Install], def: &Def) -> Result<Vec<ForkSlugRunning>, String> {
66 let mut out = Vec::new();
67 if let Some(lease) = live_lease(home, &def.uid) {
68 out.push(lease);
69 }
70 let names = names_of(def);
71 for name in &names {
72 for e in shared_entries(home, name) {
73 if e.uid.is_empty() || e.uid == def.uid {
74 out.push(ForkSlugRunning { block_id: e.block_id, channel: e.channel, how: format!("registered as {name}") });
75 }
76 }
77 }
78 for install in installs {
79 for version in &install.versions {
80 let mut conn: Option<Connection> = None;
81 for name in &names {
82 let Some(e) = registration(&version.registrations(), name) else { continue };
83 if conn.is_none() {
84 conn = Some(open_ro(&version.objects_db())?);
85 }
86 let owner = conn.as_ref().and_then(|c| block_agent(c, &e.block_id));
87 if owner.is_none() || owner.as_deref() == Some(def.uid.as_str()) {
88 out.push(ForkSlugRunning {
89 block_id: e.block_id,
90 channel: place(install, version),
91 how: format!("registered as {name}"),
92 });
93 }
94 }
95 }
96 }
97 let mut seen = std::collections::HashSet::new();
98 out.retain(|r| seen.insert((r.block_id.clone(), r.channel.clone(), r.how.clone())));
99 Ok(out)
100}
101
102fn live_lease(home: &Home, uid: &str) -> Option<ForkSlugRunning> {
107 let path = home.leases().join(format!("{uid}.lease.json"));
108 let bytes = std::fs::read(&path).ok()?;
109 let ttl = crate::registry::LEASE_TTL_MS as i64;
110 let now = agentmux_common::time::now_ms();
111 let Ok(lease) = serde_json::from_slice::<Value>(&bytes) else {
112 let age = std::fs::metadata(&path).and_then(|m| m.modified()).ok()?.elapsed().ok()?.as_millis() as i64;
113 return (age <= ttl).then(|| ForkSlugRunning { block_id: String::new(), channel: String::new(), how: "an unreadable lease".into() });
114 };
115 let num = |k: &str| lease.get(k).and_then(Value::as_i64).unwrap_or(0);
116 let text = |k: &str| lease.get(k).and_then(Value::as_str).unwrap_or_default().to_string();
117 if now - num("renewed_at_ms") > ttl {
118 return None;
119 }
120 let host = text("hostname");
121 let this_host = whoami::fallible::hostname().unwrap_or_default().trim().to_lowercase();
122 let pid = num("pid") as u32;
123 if !host.is_empty() && host == this_host && pid != 0 && !pid_alive(pid) {
124 return None;
125 }
126 Some(ForkSlugRunning { block_id: text("block_id"), channel: text("channel"), how: "holds its lease".into() })
127}