agentmux_srv_core/backend/slug_migration/
home.rs1use std::path::{Path, PathBuf};
9
10use rusqlite::{Connection, OpenFlags};
11
12#[derive(Debug, Clone)]
14pub struct Home {
15 pub root: PathBuf,
16 pub shared: PathBuf,
18 pub bashwrap_dir: PathBuf,
22}
23
24impl Home {
25 pub fn at(root: &Path) -> Home {
27 Home {
28 root: root.to_path_buf(),
29 shared: root.join("shared"),
30 bashwrap_dir: root.join("state").join("bashwrap-cwd"),
31 }
32 }
33
34 pub fn from_env() -> Result<Home, String> {
37 if let Some(over) = std::env::var_os("AGENTMUX_HOME_OVERRIDE").filter(|s| !s.is_empty()) {
38 return Ok(Home::at(Path::new(&over)));
39 }
40 let root = crate::srv_info::agentmux_root().ok_or("the AgentMux root can't be resolved")?;
41 let mut home = Home::at(&root);
42 if let Some(shared) = crate::registry::resolve_global_shared_root() {
43 home.shared = shared;
44 }
45 if let Some(user) = dirs::home_dir() {
46 home.bashwrap_dir = user.join(".agentmux").join("state").join("bashwrap-cwd");
47 }
48 Ok(home)
49 }
50
51 pub fn definitions(&self) -> PathBuf {
52 self.shared.join("agents").join("definitions")
53 }
54 pub fn reactive(&self) -> PathBuf {
55 self.shared.join("agents").join("reactive")
56 }
57 pub fn leases(&self) -> PathBuf {
58 self.shared.join("agents").join("registry").join("leases")
59 }
60 pub fn lock_file(&self) -> PathBuf {
61 self.shared.join("locks").join("slug-migration.lock")
62 }
63 pub fn backups(&self) -> PathBuf {
64 self.shared.join("backups")
65 }
66
67 pub fn host_stores(&self, installs: &[Install]) -> Vec<PathBuf> {
71 let mut out: Vec<PathBuf> = ["store.db", "identity-store.db"].iter().map(|f| self.shared.join(f)).collect();
72 out.extend(installs.iter().map(|i| i.dir.join("identity-store.db")));
73 out.retain(|p| p.is_file());
74 out
75 }
76
77 pub fn installs(&self) -> Result<Vec<Install>, String> {
83 let mut out = Vec::new();
84 for ch in list_dirs(&self.root.join("channels"))? {
85 let name = format!("channels/{}", file_name(&ch));
86 let mut versions = Vec::new();
87 if has_objects_db(&ch.join("data")) {
88 versions.push(VersionData { label: String::new(), data: ch.join("data") });
89 }
90 for v in list_dirs(&ch.join("versions"))? {
91 if has_objects_db(&v.join("data")) {
92 versions.push(VersionData { label: file_name(&v), data: v.join("data") });
93 }
94 }
95 out.push(Install { name, dir: ch, versions });
96 }
97 for branch in list_dirs(&self.root.join("dev"))? {
98 if has_objects_db(&branch.join("data")) {
99 let name = format!("dev/{}", file_name(&branch));
100 out.push(Install { name, versions: vec![VersionData { label: String::new(), data: branch.join("data") }], dir: branch });
101 continue;
102 }
103 for clone in list_dirs(&branch)? {
104 if has_objects_db(&clone.join("data")) {
105 let name = format!("dev/{}/{}", file_name(&branch), file_name(&clone));
106 out.push(Install { name, versions: vec![VersionData { label: String::new(), data: clone.join("data") }], dir: clone });
107 }
108 }
109 }
110 Ok(out)
111 }
112}
113
114#[derive(Debug, Clone)]
116pub struct Install {
117 pub name: String,
118 pub dir: PathBuf,
119 pub versions: Vec<VersionData>,
120}
121
122impl Install {
123 pub fn config_dir(&self) -> PathBuf {
125 self.dir.join("config")
126 }
127 pub fn wan_db(&self) -> Option<PathBuf> {
129 Some(self.dir.join("wan-identity").join("wan.db")).filter(|p| p.is_file())
130 }
131}
132
133#[derive(Debug, Clone)]
135pub struct VersionData {
136 pub label: String,
138 pub data: PathBuf,
139}
140
141impl VersionData {
142 pub fn objects_db(&self) -> PathBuf {
143 self.data.join("db").join("objects.db")
144 }
145 pub fn registrations(&self) -> PathBuf {
147 self.data.join("agents")
148 }
149 pub fn srv_lock(&self) -> PathBuf {
151 self.data.join(crate::backend::base::SRV_DATA_LOCK_FILE)
152 }
153 pub fn stamp(&self) -> PathBuf {
155 self.data.join(super::stamp::STAMP_FILE)
156 }
157}
158
159pub fn place(install: &Install, version: &VersionData) -> String {
161 if version.label.is_empty() {
162 install.name.clone()
163 } else {
164 format!("{}@{}", install.name, version.label)
165 }
166}
167
168fn has_objects_db(data: &Path) -> bool {
169 data.join("db").join("objects.db").is_file()
170}
171
172fn file_name(p: &Path) -> String {
173 p.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default()
174}
175
176fn list_dirs(dir: &Path) -> Result<Vec<PathBuf>, String> {
178 let entries = match std::fs::read_dir(dir) {
179 Ok(e) => e,
180 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
181 Err(e) => return Err(format!("{} can't be listed: {e}", dir.display())),
182 };
183 let mut out = Vec::new();
184 for entry in entries {
185 let path = entry.map_err(|e| format!("{} can't be listed: {e}", dir.display()))?.path();
186 if path.is_dir() {
187 out.push(path);
188 }
189 }
190 out.sort();
191 Ok(out)
192}
193
194pub fn open_ro(path: &Path) -> Result<Connection, String> {
197 let conn = Connection::open_with_flags(path, OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_NO_MUTEX)
198 .map_err(|e| format!("open {}: {e}", path.display()))?;
199 conn.busy_timeout(std::time::Duration::from_secs(5)).map_err(|e| e.to_string())?;
200 Ok(conn)
201}
202
203pub fn open_rw(path: &Path) -> Result<Connection, String> {
207 let conn = Connection::open_with_flags(path, OpenFlags::SQLITE_OPEN_READ_WRITE | OpenFlags::SQLITE_OPEN_NO_MUTEX)
208 .map_err(|e| format!("open {}: {e}", path.display()))?;
209 conn.busy_timeout(std::time::Duration::from_secs(5)).map_err(|e| e.to_string())?;
210 Ok(conn)
211}
212
213pub fn table_exists(conn: &Connection, table: &str) -> bool {
214 conn.query_row("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?1", [table], |_| Ok(()))
215 .is_ok()
216}
217
218pub fn has_agent_slugs(conn: &Connection) -> bool {
221 has_column(conn, "db_agents", "slug")
222}
223
224pub fn has_column(conn: &Connection, table: &str, column: &str) -> bool {
225 let Ok(mut stmt) = conn.prepare(&format!("PRAGMA table_info({table})")) else { return false };
226 let Ok(rows) = stmt.query_map([], |r| r.get::<_, String>(1)) else { return false };
227 let columns: Vec<String> = rows.flatten().collect();
228 columns.iter().any(|c| c == column)
229}
230
231pub fn in_tx<T>(conn: &Connection, f: impl FnOnce(&Connection) -> Result<T, String>) -> Result<T, String> {
234 conn.execute_batch("BEGIN IMMEDIATE").map_err(|e| e.to_string())?;
235 match f(conn) {
236 Ok(v) => {
237 conn.execute_batch("COMMIT").map_err(|e| e.to_string())?;
238 Ok(v)
239 }
240 Err(e) => {
241 let _ = conn.execute_batch("ROLLBACK");
242 Err(e)
243 }
244 }
245}
246
247pub fn write_file(path: &Path, bytes: &[u8]) -> Result<(), String> {
256 use std::io::Write as _;
257 let dir = path.parent().ok_or("no parent directory")?;
258 std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?;
259 let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("file");
260 let tmp = path.with_file_name(format!(".{name}.{}.slug-migration", uuid::Uuid::new_v4()));
261 let err = |e: std::io::Error| format!("{}: {e}", tmp.display());
262 #[cfg(unix)]
263 let keep = (name != ".mcp.json").then(|| std::fs::metadata(path).ok().map(|m| m.permissions())).flatten();
264 let mut opts = std::fs::OpenOptions::new();
265 opts.write(true).create_new(true);
266 #[cfg(unix)]
267 {
268 use std::os::unix::fs::OpenOptionsExt as _;
269 opts.mode(0o600);
270 }
271 let written = (|| {
272 let mut f = opts.open(&tmp).map_err(err)?;
273 #[cfg(unix)]
274 if let Some(perms) = keep {
275 f.set_permissions(perms).map_err(err)?;
276 }
277 f.write_all(bytes).map_err(err)?;
278 f.sync_all().map_err(err)
279 })();
280 let result = written.and_then(|()| {
281 crate::backend::workdir_fs::rename_with_retry(&tmp, path).map_err(|e| format!("{}: {e}", path.display()))
282 });
283 if result.is_err() {
284 let _ = std::fs::remove_file(&tmp);
285 }
286 result
287}
288
289pub fn owner_only(path: &Path) -> Result<(), String> {
292 #[cfg(unix)]
293 {
294 use std::os::unix::fs::PermissionsExt as _;
295 let mode = if path.is_dir() { 0o700 } else { 0o600 };
296 std::fs::set_permissions(path, std::fs::Permissions::from_mode(mode)).map_err(|e| format!("{}: {e}", path.display()))?;
297 }
298 #[cfg(not(unix))]
299 let _ = path;
300 Ok(())
301}
302
303pub fn fold(name: &str) -> String {
305 name.trim().to_lowercase()
306}