Skip to main content

agentmux_srv_core/backend/slug_migration/
backup.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The copy a run takes before its first write (ยง4 Phase 2, "Back up"):
5//! every database it will touch through SQLite's `VACUUM INTO`
6//! (`db_copy::copy_database`, never a raw copy of a file in WAL mode), and
7//! every other file it will change or delete as it is, each with its
8//! SHA-256 in the journal. Also the digests restore mode compares.
9
10use std::path::{Path, PathBuf};
11
12use sha2::{Digest, Sha256};
13
14use super::home::{open_ro, owner_only};
15use super::journal::{BackupEntry, Fingerprint};
16
17/// What to back up: databases and plain files, by original path.
18#[derive(Debug, Default)]
19pub struct BackupList {
20    pub databases: Vec<PathBuf>,
21    pub files: Vec<PathBuf>,
22}
23
24/// Copy every listed path into `dir` and describe each copy. A database that
25/// can't be copied fails the run before anything is written; a file that is
26/// gone by now is skipped.
27pub fn take(dir: &Path, list: &BackupList) -> Result<Vec<BackupEntry>, String> {
28    std::fs::create_dir_all(dir.join("db")).map_err(|e| format!("{}: {e}", dir.display()))?;
29    std::fs::create_dir_all(dir.join("files")).map_err(|e| format!("{}: {e}", dir.display()))?;
30    for d in [dir.to_path_buf(), dir.join("db"), dir.join("files")] {
31        owner_only(&d)?;
32    }
33    let mut out = Vec::new();
34    for (i, db) in list.databases.iter().enumerate() {
35        let name = db.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
36        let copy = format!("db/{:04}-{name}", i + 1);
37        crate::backend::storage::db_copy::copy_database(db, &dir.join(&copy))?;
38        owner_only(&dir.join(&copy))?;
39        out.push(BackupEntry { original: db.display().to_string(), sha256: file_sha256(&dir.join(&copy))?, copy, database: true });
40    }
41    for (i, file) in list.files.iter().enumerate() {
42        let Ok(bytes) = std::fs::read(file) else { continue };
43        let name = file.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
44        let copy = format!("files/{:04}-{name}", i + 1);
45        super::home::write_file(&dir.join(&copy), &bytes)?;
46        out.push(BackupEntry { original: file.display().to_string(), sha256: hex::encode(Sha256::digest(&bytes)), copy, database: false });
47    }
48    Ok(out)
49}
50
51/// The copy of `original` among `entries`, checked against its recorded
52/// checksum.
53pub fn copy_of(run_dir: &Path, entries: &[BackupEntry], original: &Path) -> Result<PathBuf, String> {
54    let want = original.display().to_string();
55    let entry = entries.iter().find(|e| e.original == want).ok_or_else(|| format!("no backup of {want}"))?;
56    let copy = run_dir.join(&entry.copy);
57    let sum = file_sha256(&copy)?;
58    if sum != entry.sha256 {
59        return Err(format!("the backup of {want} doesn't match its checksum"));
60    }
61    Ok(copy)
62}
63
64pub fn file_sha256(path: &Path) -> Result<String, String> {
65    let bytes = std::fs::read(path).map_err(|e| format!("{}: {e}", path.display()))?;
66    Ok(hex::encode(Sha256::digest(&bytes)))
67}
68
69/// A digest of a database's rows, every table, independent of row order and
70/// of how its pages sit in the file and its WAL: what changed and what
71/// didn't, where a file checksum would differ after any checkpoint.
72pub fn db_digest(path: &Path) -> Result<String, String> {
73    let conn = open_ro(path)?;
74    let mut tables: Vec<String> = {
75        let mut stmt = conn
76            .prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%'")
77            .map_err(|e| e.to_string())?;
78        let rows = stmt.query_map([], |r| r.get::<_, String>(0)).map_err(|e| e.to_string())?;
79        rows.collect::<Result<_, _>>().map_err(|e| e.to_string())?
80    };
81    tables.sort();
82    let mut all = Sha256::new();
83    for table in tables {
84        let mut stmt = conn.prepare(&format!("SELECT * FROM \"{table}\"")).map_err(|e| e.to_string())?;
85        let width = stmt.column_count();
86        let mut rows: Vec<String> = stmt
87            .query_map([], |r| {
88                let mut h = Sha256::new();
89                for i in 0..width {
90                    h.update(cell(r.get_ref(i)?).as_bytes());
91                    h.update(b"\x1f");
92                }
93                Ok(hex::encode(h.finalize()))
94            })
95            .map_err(|e| e.to_string())?
96            .collect::<Result<_, _>>()
97            .map_err(|e| e.to_string())?;
98        rows.sort();
99        all.update(table.as_bytes());
100        for row in rows {
101            all.update(row.as_bytes());
102        }
103    }
104    Ok(hex::encode(all.finalize()))
105}
106
107/// One cell, as the digest sees it. A JSON object or array (a block's
108/// `data`) counts by its content, not its bytes: a row rewritten and put back
109/// holds the same JSON, whatever order its keys were serialized in.
110fn cell(v: rusqlite::types::ValueRef<'_>) -> String {
111    use rusqlite::types::ValueRef;
112    let json = match v {
113        ValueRef::Text(b) | ValueRef::Blob(b) if matches!(b.first(), Some(b'{') | Some(b'[')) => serde_json::from_slice::<serde_json::Value>(b).ok(),
114        _ => None,
115    };
116    match json {
117        Some(j) => format!("json:{}", canonical(&j)),
118        None => format!("{v:?}"),
119    }
120}
121
122/// `v` with every object's keys sorted.
123fn canonical(v: &serde_json::Value) -> String {
124    match v {
125        serde_json::Value::Object(map) => {
126            let mut keys: Vec<&String> = map.keys().collect();
127            keys.sort();
128            let inner: Vec<String> = keys.iter().map(|k| format!("{:?}:{}", k, canonical(&map[*k]))).collect();
129            format!("{{{}}}", inner.join(","))
130        }
131        serde_json::Value::Array(items) => format!("[{}]", items.iter().map(canonical).collect::<Vec<_>>().join(",")),
132        other => other.to_string(),
133    }
134}
135
136/// What `path` is now, for restore mode.
137pub fn fingerprint(path: &Path, database: bool) -> Result<Fingerprint, String> {
138    if database {
139        return Ok(Fingerprint { path: path.display().to_string(), digest: db_digest(path)?, mtime_ms: 0 });
140    }
141    let mtime_ms = std::fs::metadata(path)
142        .and_then(|m| m.modified())
143        .ok()
144        .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
145        .map(|d| d.as_millis() as i64)
146        .unwrap_or(0);
147    let digest = if path.exists() { file_sha256(path)? } else { String::new() };
148    Ok(Fingerprint { path: path.display().to_string(), digest, mtime_ms })
149}