gioser
⎇ f4eb7dd94404c2fadd8099c61ca11d2860bcff7a crates/ente-cas/src/lib.rs Rust · 120 siq'ikuna · 3.9 KB Ñawpa willay Pi imata llamkarqan ch'uya

Capability quotas, CAS gc, patrones burst/silence, snapshot incremental f4eb7dd94 · Sergio ·

1//! Content-addressable store. Resuelve `Payload::Wasm.module_sha256` (y en
2//! el futuro otros payloads firmados) desde el sistema de archivos con
3//! verificación de hash. Path por defecto: `$XDG_DATA_HOME/ente/cas/<hex>`.
4//!
5//! Override por env: `ENTE_CAS_ROOT`.
6
7use sha2::{Digest, Sha256};
8use std::path::PathBuf;
9use tracing::debug;
10
11pub fn cas_root() -> PathBuf {
12    if let Ok(p) = std::env::var("ENTE_CAS_ROOT") {
13        return p.into();
14    }
15    let base = if let Ok(d) = std::env::var("XDG_DATA_HOME") {
16        d
17    } else if let Ok(h) = std::env::var("HOME") {
18        format!("{h}/.local/share")
19    } else {
20        "/var/lib".into()
21    };
22    PathBuf::from(base).join("ente").join("cas")
23}
24
25pub fn sha256_of(bytes: &[u8]) -> [u8; 32] {
26    let mut hasher = Sha256::new();
27    hasher.update(bytes);
28    hasher.finalize().into()
29}
30
31pub fn hex(sha: &[u8; 32]) -> String {
32    let mut s = String::with_capacity(64);
33    for b in sha {
34        s.push_str(&format!("{:02x}", b));
35    }
36    s
37}
38
39/// Lista todos los SHAs presentes en el CAS. Cada entrada del directorio
40/// con nombre de 64 chars hex se considera un blob válido.
41pub fn list_all_shas() -> anyhow::Result<Vec<[u8; 32]>> {
42    let root = cas_root();
43    if !root.exists() { return Ok(Vec::new()); }
44    let mut out = Vec::new();
45    for entry in std::fs::read_dir(&root)? {
46        let e = entry?;
47        let name = e.file_name();
48        let s = match name.to_str() {
49            Some(s) if s.len() == 64 => s,
50            _ => continue,
51        };
52        let mut sha = [0u8; 32];
53        let mut ok = true;
54        for i in 0..32 {
55            match u8::from_str_radix(&s[i*2..i*2+2], 16) {
56                Ok(b) => sha[i] = b,
57                Err(_) => { ok = false; break; }
58            }
59        }
60        if ok { out.push(sha); }
61    }
62    Ok(out)
63}
64
65/// Garbage collector. Borra todos los blobs que no están en `reachable`.
66/// Devuelve (deleted_count, freed_bytes). El caller construye `reachable`
67/// caminando todas las raíces (audit chain head, Wasm SHAs en Cards, etc).
68///
69/// Idempotente: re-correr no hace nada si el set no cambió.
70pub fn gc(reachable: &std::collections::HashSet<[u8; 32]>) -> anyhow::Result<(usize, u64)> {
71    let root = cas_root();
72    let mut deleted = 0usize;
73    let mut freed = 0u64;
74    for sha in list_all_shas()? {
75        if reachable.contains(&sha) { continue; }
76        let path = root.join(hex(&sha));
77        if let Ok(meta) = std::fs::metadata(&path) {
78            freed += meta.len();
79        }
80        if std::fs::remove_file(&path).is_ok() {
81            deleted += 1;
82            tracing::debug!(sha = %hex(&sha), "CAS gc removed");
83        }
84    }
85    Ok((deleted, freed))
86}
87
88pub fn resolve(sha: &[u8; 32]) -> anyhow::Result<Vec<u8>> {
89    let path = cas_root().join(hex(sha));
90    let bytes = std::fs::read(&path)
91        .map_err(|e| anyhow::anyhow!("CAS read {}: {e}", path.display()))?;
92    let actual = sha256_of(&bytes);
93    if &actual != sha {
94        anyhow::bail!(
95            "CAS hash mismatch en {}: declarado={} real={}",
96            path.display(), hex(sha), hex(&actual)
97        );
98    }
99    Ok(bytes)
100}
101
102/// Almacena bytes en el CAS, devuelve su SHA. Idempotente: si el archivo ya
103/// existe con el mismo hash, no reescribe.
104pub fn store(bytes: &[u8]) -> anyhow::Result<[u8; 32]> {
105    let sha = sha256_of(bytes);
106    let root = cas_root();
107    std::fs::create_dir_all(&root)
108        .map_err(|e| anyhow::anyhow!("CAS mkdir {}: {e}", root.display()))?;
109    let path = root.join(hex(&sha));
110    if !path.exists() {
111        // Escritura atómica: crear .tmp y rename.
112        let tmp = path.with_extension("tmp");
113        std::fs::write(&tmp, bytes)
114            .map_err(|e| anyhow::anyhow!("CAS write {}: {e}", tmp.display()))?;
115        std::fs::rename(&tmp, &path)
116            .map_err(|e| anyhow::anyhow!("CAS rename {}: {e}", path.display()))?;
117        debug!(hex = %hex(&sha), len = bytes.len(), path = %path.display(), "CAS store");
118    }
119    Ok(sha)
120}