Skip to main content

rustsy_engine/
cache.rs

1use sha2::{Digest, Sha256};
2use std::{
3    fs::{self, OpenOptions},
4    io::{self, Write},
5    path::Path,
6    sync::atomic::{AtomicU64, Ordering},
7};
8
9pub type Digest256 = [u8; 32];
10
11/// Builds an action key from explicitly declared inputs and dependencies.
12/// Callers supply stable names and enumerate entries in canonical order.
13pub struct ActionKey(Sha256);
14
15impl Default for ActionKey {
16    fn default() -> Self {
17        let mut hash = Sha256::new();
18        hash.update(b"rustsy-action-v1");
19        Self(hash)
20    }
21}
22
23impl ActionKey {
24    pub fn include(&mut self, name: &[u8], value: &[u8]) {
25        for field in [name, value] {
26            self.0.update((field.len() as u64).to_le_bytes());
27            self.0.update(field);
28        }
29    }
30
31    pub fn finish(self) -> Digest256 {
32        self.0.finalize().into()
33    }
34}
35
36/// Reads a content-addressed blob and checks the bytes before exposing them.
37pub fn read_blob(directory: &Path, digest: Digest256) -> io::Result<Vec<u8>> {
38    let bytes = fs::read(directory.join(blob_name(digest)))?;
39    let actual: Digest256 = Sha256::digest(&bytes).into();
40    if actual != digest {
41        return Err(io::Error::new(
42            io::ErrorKind::InvalidData,
43            "blob digest mismatch",
44        ));
45    }
46    Ok(bytes)
47}
48
49fn blob_name(digest: Digest256) -> String {
50    digest.iter().map(|byte| format!("{byte:02x}")).collect()
51}
52
53/// Publish a complete blob on the same filesystem. A competing publisher can
54/// win only with a successfully validated blob under the same content digest.
55pub fn store_blob(directory: &Path, bytes: &[u8]) -> io::Result<Digest256> {
56    static NEXT: AtomicU64 = AtomicU64::new(0);
57    let digest = Sha256::digest(bytes).into();
58    match read_blob(directory, digest) {
59        Ok(_) => return Ok(digest),
60        Err(error) if error.kind() == io::ErrorKind::NotFound => {}
61        Err(error) => return Err(error),
62    }
63    fs::create_dir_all(directory)?;
64    let (staging, mut writer) = loop {
65        let ordinal = NEXT.fetch_add(1, Ordering::Relaxed);
66        let staging = directory.join(format!(".pending-{}-{ordinal}", std::process::id()));
67        match OpenOptions::new()
68            .write(true)
69            .create_new(true)
70            .open(&staging)
71        {
72            Ok(file) => break (staging, file),
73            Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue,
74            Err(error) => return Err(error),
75        }
76    };
77    writer.write_all(bytes)?;
78    writer.sync_all()?;
79    drop(writer);
80    match fs::hard_link(staging, directory.join(blob_name(digest))) {
81        Ok(()) => {}
82        Err(error) if error.kind() == io::ErrorKind::AlreadyExists => {
83            read_blob(directory, digest)?;
84        }
85        Err(error) => return Err(error),
86    }
87    Ok(digest)
88}
89
90#[cfg(test)]
91mod tests {
92    use super::*;
93
94    #[test]
95    fn frames_and_tool_versions_change_the_key() {
96        let key = |name: &[u8], value: &[u8]| {
97            let mut key = ActionKey::default();
98            key.include(name, value);
99            key.finish()
100        };
101        assert_ne!(key(b"ab", b"c"), key(b"a", b"bc"));
102        assert_ne!(key(b"compiler", b"1"), key(b"compiler", b"2"));
103        assert_eq!(key(b"compiler", b"2"), key(b"compiler", b"2"));
104    }
105
106    #[test]
107    fn validates_blobs_after_publish() {
108        let id = std::time::SystemTime::now()
109            .duration_since(std::time::UNIX_EPOCH)
110            .unwrap()
111            .as_nanos();
112        let directory =
113            std::env::temp_dir().join(format!("rustsy-cas-{}-{id}", std::process::id()));
114        let bytes = b"artifact";
115        let digest = store_blob(&directory, bytes).unwrap();
116        assert_eq!(store_blob(&directory, bytes).unwrap(), digest);
117        assert_eq!(&read_blob(&directory, digest).unwrap(), bytes);
118        fs::write(directory.join(blob_name([0; 32])), bytes).unwrap();
119        assert_eq!(
120            read_blob(&directory, [0; 32]).unwrap_err().kind(),
121            io::ErrorKind::InvalidData
122        );
123    }
124}