crates/edge/sdk/src/cache/descriptor.rs 8.3 KiB 262 lines Raw
1 //! Bounded descriptor I/O for cache payloads.2 //!3 //! A codec never trusts a descriptor. Before a restore the length and CRC32C4 //! must match what the core reserved; after a save the codec must report the5 //! exact bytes it wrote. These helpers do that without mapping, without a path,6 //! and without a staging directory.7 8 use std::fs::File;9 use std::io::{self, Read, Seek, SeekFrom, Write};10 11 use inf3r_crc32c::Crc32c;12 13 use super::{CacheFile, CacheWrite};14 15 const BUFFER: usize = 1024 * 1024;16 17 /// Verifies a restored entry against its length and CRC32C, then rewinds it.18 ///19 /// The descriptor is the only input: no path, no hash, and no metadata from20 /// the client is trusted. A mismatch is a cold erase, never a best-effort21 /// restore.22 pub fn verify_file(file: &CacheFile) -> io::Result<()> {23     let mut source = File::from(file.file.try_clone()?);24     source.seek(SeekFrom::Start(0))?;25     let mut crc = Crc32c::new();26     let mut bytes = 0u64;27     let mut buffer = [0u8; BUFFER];28     loop {29         let read = source.read(&mut buffer)?;30         if read == 0 {31             break;32         }33         crc.update(&buffer[..read]);34         bytes += read as u64;35     }36     source.seek(SeekFrom::Start(0))?;37     if bytes != file.bytes || crc.finish() != file.crc32c {38         return Err(io::Error::other(39             "the cache entry failed its length or CRC32C check",40         ));41     }42     Ok(())43 }44 45 /// Measures what an engine wrote into a granted descriptor and rewinds it.46 ///47 /// The byte count is checked against the reservation before the caller may48 /// commit it. A too-large write is refused; it never becomes a partial entry.49 pub fn measure_write(write: &CacheWrite) -> io::Result<(u64, u32)> {50     let mut file = File::from(write.file.try_clone()?);51     file.seek(SeekFrom::Start(0))?;52     let mut crc = Crc32c::new();53     let mut bytes = 0u64;54     let mut buffer = [0u8; BUFFER];55     loop {56         let read = file.read(&mut buffer)?;57         if read == 0 {58             break;59         }60         crc.update(&buffer[..read]);61         bytes += read as u64;62         if bytes > write.max_bytes {63             return Err(io::Error::other(format!(64                 "the engine wrote more than the entry limit of {}",65                 write.max_bytes66             )));67         }68     }69     file.sync_all()?;70     file.seek(SeekFrom::Start(0))?;71     Ok((bytes, crc.finish()))72 }73 74 /// Copies a verified entry into a sink, then leaves the descriptor at zero.75 ///76 /// This is the compatibility path for an engine that wants a path instead of a77 /// descriptor. The sink is the codec's private staging file, not a cache tier.78 pub fn copy_in(file: &CacheFile, target: &mut impl Write) -> io::Result<()> {79     let mut source = File::from(file.file.try_clone()?);80     source.seek(SeekFrom::Start(0))?;81     let mut crc = Crc32c::new();82     let mut bytes = 0u64;83     let mut buffer = [0u8; BUFFER];84     loop {85         let read = source.read(&mut buffer)?;86         if read == 0 {87             break;88         }89         target.write_all(&buffer[..read])?;90         crc.update(&buffer[..read]);91         bytes += read as u64;92     }93     source.seek(SeekFrom::Start(0))?;94     if bytes != file.bytes || crc.finish() != file.crc32c {95         return Err(io::Error::other(96             "the cache entry failed its length or CRC32C check",97         ));98     }99     Ok(())100 }101 102 /// Copies an engine's staging file into a granted descriptor.103 ///104 /// This is the compatibility path for an engine that writes a path. The105 /// returned count is checked against the reservation before commit.106 pub fn copy_out(write: &CacheWrite, source: &mut impl Read) -> io::Result<(u64, u32)> {107     let mut target = File::from(write.file.try_clone()?);108     target.seek(SeekFrom::Start(0))?;109     target.set_len(0)?;110     let mut crc = Crc32c::new();111     let mut buffer = [0u8; BUFFER];112     let mut bytes = 0u64;113     loop {114         let read = source.read(&mut buffer)?;115         if read == 0 {116             break;117         }118         target.write_all(&buffer[..read])?;119         crc.update(&buffer[..read]);120         bytes += read as u64;121         if bytes > write.max_bytes {122             return Err(io::Error::other(format!(123                 "the engine wrote more than the entry limit of {}",124                 write.max_bytes125             )));126         }127     }128     target.sync_all()?;129     target.seek(SeekFrom::Start(0))?;130     Ok((bytes, crc.finish()))131 }132 133 #[cfg(test)]134 mod tests {135     use super::*;136     use std::fs::{self, OpenOptions};137     use std::os::unix::fs::PermissionsExt;138     use std::path::PathBuf;139     use std::sync::atomic::{AtomicU64, Ordering};140 141     static NEXT: AtomicU64 = AtomicU64::new(0);142 143     struct TempDir(PathBuf);144 145     impl TempDir {146         fn new() -> TempDir {147             let path = std::env::temp_dir().join(format!(148                 "inf3r-sdk-descriptor-{}-{}",149                 std::process::id(),150                 NEXT.fetch_add(1, Ordering::SeqCst)151             ));152             fs::create_dir_all(&path).unwrap();153             fs::set_permissions(&path, fs::Permissions::from_mode(0o700)).unwrap();154             TempDir(path)155         }156     }157 158     impl Drop for TempDir {159         fn drop(&mut self) {160             let _ = fs::remove_dir_all(&self.0);161         }162     }163 164     fn read_file(path: &std::path::Path) -> CacheFile {165         let bytes = fs::read(path).unwrap();166         let file = File::open(path).unwrap();167         CacheFile {168             key: [1; 32],169             lease_id: 1,170             bytes: bytes.len() as u64,171             crc32c: inf3r_crc32c::crc32c(&bytes),172             token_count: 1,173             tier: "test".into(),174             file: file.into(),175         }176     }177 178     fn write_file(path: &std::path::Path, bytes: &[u8]) -> CacheWrite {179         let file = OpenOptions::new()180             .read(true)181             .write(true)182             .create(true)183             .truncate(true)184             .open(path)185             .unwrap();186         file.try_clone().unwrap().write_all(bytes).unwrap();187         CacheWrite {188             lease_id: 1,189             max_bytes: 1024,190             tier: "test".into(),191             file: file.into(),192         }193     }194 195     #[test]196     fn a_verified_entry_rewinds_and_a_corrupt_one_is_refused() {197         let temp = TempDir::new();198         let path = temp.0.join("entry.bin");199         fs::write(&path, b"slot bytes").unwrap();200         let file = read_file(&path);201         verify_file(&file).unwrap();202         let mut copy = File::from(file.file.try_clone().unwrap());203         let mut bytes = Vec::new();204         copy.read_to_end(&mut bytes).unwrap();205         assert_eq!(bytes, b"slot bytes");206 207         let mut corrupt = read_file(&path);208         corrupt.crc32c ^= 1;209         assert!(verify_file(&corrupt).is_err());210         let mut short = read_file(&path);211         short.bytes += 1;212         assert!(verify_file(&short).is_err());213     }214 215     #[test]216     fn a_write_is_measured_and_bounded() {217         let temp = TempDir::new();218         let path = temp.0.join("write.bin");219         let write = write_file(&path, b"slot bytes");220         let (bytes, crc) = measure_write(&write).unwrap();221         assert_eq!(bytes, 10);222         assert_eq!(crc, inf3r_crc32c::crc32c(b"slot bytes"));223 224         let path = temp.0.join("large.bin");225         let write = write_file(&path, b"too large");226         let write = CacheWrite {227             max_bytes: 4,228             ..write229         };230         assert!(measure_write(&write).is_err());231     }232 233     #[test]234     fn copy_in_verifies_while_it_copies() {235         let temp = TempDir::new();236         let source = temp.0.join("source.bin");237         fs::write(&source, b"slot bytes").unwrap();238         let hit = read_file(&source);239         let mut target = Vec::new();240         copy_in(&hit, &mut target).unwrap();241         assert_eq!(target, b"slot bytes");242 243         let mut corrupt = read_file(&source);244         corrupt.bytes += 1;245         let mut target = Vec::new();246         assert!(copy_in(&corrupt, &mut target).is_err());247     }248 249     #[test]250     fn copy_out_measures_and_rewinds_the_descriptor() {251         let temp = TempDir::new();252         let path = temp.0.join("write.bin");253         let write = write_file(&path, b"");254         let (bytes, crc) = copy_out(&write, &mut &b"slot bytes"[..]).unwrap();255         assert_eq!(bytes, 10);256         assert_eq!(crc, inf3r_crc32c::crc32c(b"slot bytes"));257         let mut target = File::from(write.file.try_clone().unwrap());258         let mut got = Vec::new();259         target.read_to_end(&mut got).unwrap();260         assert_eq!(got, b"slot bytes");261     }262 }