Elffuss BraidHub

utopia-ia/elffuss-braid public

38b3e04f7d4a · 8.4 KiBRawPermalink
1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 UtopiaIA
3
4//! The stat cache: what each file of the working copy hashed to, and the
5//! metadata it had then, so that unchanged files are not read again.
6//!
7//! An entry is used only when the file's modification time, size, inode
8//! number and type are all still the same, and its modification time is
9//! strictly older than the time the cache's scan started, read from the
10//! workspace's own file system. A file written in the same instant as the
11//! scan, or later, may have changed without its metadata showing it, so it
12//! is hashed again.
13//!
14//! ```text
15//! [8] "braidwsc" | u32 version = 1 | u32 0
16//! sv seconds | uv nanoseconds when the scan started
17//! uv n | n × entry, paths strictly ascending
18//! [32] BLAKE3 (the derived-object context) of everything before it
19//!
20//! entry: bytes path | sv mtime seconds | uv mtime nanoseconds | uv size
21//! uv inode | u8 kind (0 file, 1 executable, 2 symlink) | [32] blob
22//! ```
23//!
24//! The cache is only a cache: if it is missing or damaged, everything is
25//! hashed again.
26
27use std::collections::HashMap;
28use std::fs;
29use std::io::Write;
30use std::path::Path;
31
32use braid_format::codec::{Reader, put_bytes, put_id, put_sv, put_uv};
33use braid_format::{DecodeError, Kind, ObjectId};
34
35use crate::error::Error;
36use crate::fsprobe::random_hex;
37use crate::safe::{Stat, StatKind};
38
39const MAGIC: &[u8; 8] = b"braidwsc";
40const VERSION: u32 = 1;
41
42/// The file the cache lives in, inside the workspace's state directory.
43pub(crate) const FILE: &str = "stat";
44
45/// What a file was when it was hashed.
46#[derive(Clone, Copy, Debug, PartialEq, Eq)]
47pub(crate) struct Entry {
48 pub mtime: (i64, u32),
49 pub size: u64,
50 pub ino: u64,
51 /// 0 regular file, 1 executable, 2 symlink.
52 pub kind: u8,
53 pub blob: ObjectId,
54}
55
56impl Entry {
57 /// The entry for a file with this metadata and blob, or `None` for
58 /// something that is not a file or a symlink.
59 pub(crate) fn new(stat: &Stat, blob: ObjectId) -> Option<Entry> {
60 Some(Entry {
61 mtime: stat.mtime,
62 size: stat.size,
63 ino: stat.ino,
64 kind: kind_code(stat)?,
65 blob,
66 })
67 }
68}
69
70fn kind_code(stat: &Stat) -> Option<u8> {
71 match stat.kind {
72 StatKind::File if stat.executable => Some(1),
73 StatKind::File => Some(0),
74 StatKind::Symlink => Some(2),
75 StatKind::Dir | StatKind::Other => None,
76 }
77}
78
79/// The cache of one workspace.
80#[derive(Clone, Debug, Default, PartialEq, Eq)]
81pub(crate) struct Cache {
82 /// When the scan that wrote it started, by the file system's clock.
83 pub time: (i64, u32),
84 pub entries: HashMap<Vec<u8>, Entry>,
85}
86
87impl Cache {
88 /// The cache in `state_dir`, or an empty one if there is none or it is
89 /// damaged.
90 pub(crate) fn load(state_dir: &Path) -> Cache {
91 fs::read(state_dir.join(FILE))
92 .ok()
93 .and_then(|bytes| decode(&bytes).ok())
94 .unwrap_or_default()
95 }
96
97 /// The blob of the file at `path`, if the cache may be trusted for a
98 /// file that now has the metadata `stat`.
99 pub(crate) fn lookup(&self, path: &[u8], stat: &Stat) -> Option<ObjectId> {
100 let entry = self.entries.get(path)?;
101 let same = entry.mtime == stat.mtime
102 && entry.size == stat.size
103 && entry.ino == stat.ino
104 && Some(entry.kind) == kind_code(stat);
105 (same && entry.mtime < self.time).then_some(entry.blob)
106 }
107
108 /// Writes the cache into `state_dir`, through a scratch file and a
109 /// rename.
110 pub(crate) fn save(&self, state_dir: &Path) -> Result<(), Error> {
111 let bytes = self.encode();
112 let scratch = state_dir.join(format!("{FILE}.tmp-{}", random_hex()));
113 let target = state_dir.join(FILE);
114 let written = fs::File::create_new(&scratch)
115 .and_then(|mut file| file.write_all(&bytes))
116 .and_then(|()| fs::rename(&scratch, &target));
117 if written.is_err() {
118 let _ = fs::remove_file(&scratch);
119 }
120 written.map_err(Error::io("write", &target))
121 }
122
123 fn encode(&self) -> Vec<u8> {
124 let mut out = Vec::with_capacity(64 + self.entries.len() * 64);
125 out.extend_from_slice(MAGIC);
126 out.extend_from_slice(&VERSION.to_le_bytes());
127 out.extend_from_slice(&0u32.to_le_bytes());
128 put_sv(&mut out, self.time.0);
129 put_uv(&mut out, u64::from(self.time.1));
130 let mut paths: Vec<&Vec<u8>> = self.entries.keys().collect();
131 paths.sort();
132 put_uv(&mut out, paths.len() as u64);
133 for path in paths {
134 let entry = &self.entries[path];
135 put_bytes(&mut out, path);
136 put_sv(&mut out, entry.mtime.0);
137 put_uv(&mut out, u64::from(entry.mtime.1));
138 put_uv(&mut out, entry.size);
139 put_uv(&mut out, entry.ino);
140 out.push(entry.kind);
141 put_id(&mut out, &entry.blob);
142 }
143 let check = ObjectId::hash(Kind::Derived, &out);
144 put_id(&mut out, &check);
145 out
146 }
147}
148
149fn decode(bytes: &[u8]) -> Result<Cache, DecodeError> {
150 let invalid = |at, what| DecodeError::Invalid { at, what };
151 if bytes.len() < 16 + ObjectId::LEN {
152 return Err(invalid(0, "stat cache length"));
153 }
154 let (body, check) = bytes.split_at(bytes.len() - ObjectId::LEN);
155 if ObjectId::hash(Kind::Derived, body).as_bytes()[..] != *check {
156 return Err(invalid(body.len(), "stat cache checksum"));
157 }
158 let mut reader = Reader::new(body);
159 if reader.take(8)? != MAGIC || reader.array::<4>()? != VERSION.to_le_bytes() {
160 return Err(invalid(0, "stat cache header"));
161 }
162 reader.array::<4>()?;
163 let seconds = reader.sv()?;
164 let nanos = u32::try_from(reader.uv()?).map_err(|_| invalid(12, "nanoseconds"))?;
165 let count = reader.count(1 + 1 + 1 + 1 + 1 + 1 + 32)?;
166 let mut entries = HashMap::with_capacity(count);
167 for _ in 0..count {
168 let path = reader.bytes()?.to_vec();
169 let at = reader.position();
170 let mtime = (
171 reader.sv()?,
172 u32::try_from(reader.uv()?).map_err(|_| invalid(at, "nanoseconds"))?,
173 );
174 let entry = Entry {
175 mtime,
176 size: reader.uv()?,
177 ino: reader.uv()?,
178 kind: reader.u8()?,
179 blob: reader.id()?,
180 };
181 entries.insert(path, entry);
182 }
183 reader.finish()?;
184 Ok(Cache {
185 time: (seconds, nanos),
186 entries,
187 })
188}
189
190#[cfg(test)]
191mod tests {
192 use super::*;
193
194 fn stat(mtime: i64) -> Stat {
195 Stat {
196 kind: StatKind::File,
197 executable: false,
198 size: 5,
199 mtime: (mtime, 7),
200 ino: 42,
201 }
202 }
203
204 #[test]
205 fn round_trip_and_damage() {
206 let dir = tempfile::tempdir().unwrap();
207 assert_eq!(Cache::load(dir.path()), Cache::default());
208 let blob = ObjectId::hash(Kind::Blob, b"hello");
209 let mut cache = Cache {
210 time: (100, 0),
211 entries: HashMap::new(),
212 };
213 cache
214 .entries
215 .insert(b"a/b".to_vec(), Entry::new(&stat(50), blob).unwrap());
216 cache.save(dir.path()).unwrap();
217 assert_eq!(Cache::load(dir.path()), cache);
218
219 let mut bytes = fs::read(dir.path().join(FILE)).unwrap();
220 bytes[20] ^= 1;
221 fs::write(dir.path().join(FILE), &bytes).unwrap();
222 assert_eq!(Cache::load(dir.path()), Cache::default());
223 }
224
225 #[test]
226 fn the_guard() {
227 let blob = ObjectId::hash(Kind::Blob, b"hello");
228 let mut cache = Cache {
229 time: (100, 0),
230 entries: HashMap::new(),
231 };
232 cache
233 .entries
234 .insert(b"old".to_vec(), Entry::new(&stat(50), blob).unwrap());
235 cache
236 .entries
237 .insert(b"racy".to_vec(), Entry::new(&stat(100), blob).unwrap());
238 assert_eq!(cache.lookup(b"old", &stat(50)), Some(blob));
239 // Modified since, or written in the same instant as the scan.
240 assert_eq!(cache.lookup(b"old", &stat(51)), None);
241 assert_eq!(cache.lookup(b"racy", &stat(100)), None);
242 // Another inode, size or kind.
243 let mut moved = stat(50);
244 moved.ino = 43;
245 assert_eq!(cache.lookup(b"old", &moved), None);
246 let mut exec = stat(50);
247 exec.executable = true;
248 assert_eq!(cache.lookup(b"old", &exec), None);
249 assert_eq!(cache.lookup(b"absent", &stat(50)), None);
250 }
251}