| 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; and, |
| 6 | //! for each directory, what the walk found in it and the base tree it was |
| 7 | //! compared with, so that a directory that did not change is neither listed |
| 8 | //! nor compared with its tree again. |
| 9 | //! |
| 10 | //! A file's record vouches for its blob only when the file's modification |
| 11 | //! time, size, inode number and type are all still the same, and its |
| 12 | //! modification time is strictly older than the time the cache's scan |
| 13 | //! started, read from the workspace's own file system. A file written in the |
| 14 | //! same instant as the scan, or later, may have changed without its metadata |
| 15 | //! showing it, so it is hashed again. Symlinks, and files that changed while |
| 16 | //! they were read, are recorded with their blob but never vouched for. |
| 17 | //! |
| 18 | //! A directory's record lists the entries the walk used: the files, |
| 19 | //! symlinks and gitlinks that count, and the subdirectories it went into. It |
| 20 | //! stands for the directory's listing while the directory's stamp (its |
| 21 | //! modification and status change times and its inode number) is the same, |
| 22 | //! both times strictly older than the cache's scan, under the same ignore |
| 23 | //! rules and against the same base tree: the same guard as for files, since |
| 24 | //! adding, removing or renaming an entry changes both times. |
| 25 | //! |
| 26 | //! A directory is clean when its own entries were exactly those of the base |
| 27 | //! tree it was compared with: each file, symlink and gitlink of that tree |
| 28 | //! there with the same content, each of its subdirectories there as a |
| 29 | //! directory, and nothing else counted. Its record then lists that tree's |
| 30 | //! entries, and while the base has the same tree at that path and the |
| 31 | //! directory's entries still match the record, nothing in the directory |
| 32 | //! differs from the base, and the tree is not read. |
| 33 | //! |
| 34 | //! Records have a fixed width and are sorted, so that loading the cache is |
| 35 | //! reading it: a directory is found by binary search on its path, and its |
| 36 | //! entries lie together, by name. |
| 37 | //! |
| 38 | //! ```text |
| 39 | //! [8] "braidwsc" | u32 version = 3 | u32 0 |
| 40 | //! i64 seconds | u32 nanoseconds when the scan started |
| 41 | //! u32 directories | u32 entries | u32 name bytes |
| 42 | //! directories × 96 bytes, by path, strictly ascending |
| 43 | //! entries × 72 bytes, each directory's together, by name, strictly ascending |
| 44 | //! name bytes |
| 45 | //! u32 CRC-32C of everything before it |
| 46 | //! |
| 47 | //! directory: u32 names offset | u32 path length | u32 first entry |
| 48 | //! u32 entries | [32] base tree, zero if none | u32 flags |
| 49 | //! u32 mtime nanoseconds | i64 mtime seconds | i64 ctime seconds |
| 50 | //! u32 ctime nanoseconds | u32 names length | u64 inode |
| 51 | //! u64 ignore rules |
| 52 | //! entry: u32 name offset | u32 name length | i64 mtime seconds |
| 53 | //! u32 mtime nanoseconds | u8 kind | u8 flags (1 vouches) | u16 0 |
| 54 | //! u64 size | u64 inode | [32] blob |
| 55 | //! ``` |
| 56 | //! |
| 57 | //! A directory's flags: 1 it has a base tree, 2 it is clean, 4 its stamp is |
| 58 | //! recorded, 8 it is ignored, 16 it has a `.braidignore`, 32 a `.gitignore`. |
| 59 | //! Its ignore rules are a digest of the ignore files in force for its |
| 60 | //! entries. An entry's kind is 0 for a regular file, 1 an executable, 2 a |
| 61 | //! symlink, 3 a gitlink of the base whose directory is there, 4 a |
| 62 | //! subdirectory that the base has, with its tree as the blob, and 5 a |
| 63 | //! subdirectory that the base does not have. Entries of kinds 3 to 5 have no |
| 64 | //! metadata, and of them only subdirectories of the base have a blob. |
| 65 | //! |
| 66 | //! Each directory has its own block of name bytes, its path and then its |
| 67 | //! entries' names: a directory's names offset counts from the start of the |
| 68 | //! name bytes, and its entries' name offsets from the start of its block, so |
| 69 | //! that the records of a directory that did not change are copied as they |
| 70 | //! are. The cache is only a cache: if it is missing or damaged, everything is |
| 71 | //! read again. It is written whole, through a scratch file and a rename, and |
| 72 | //! only when a scan found something its records do not say. |
| 73 | |
| 74 | use std::fs; |
| 75 | use std::io::Write; |
| 76 | use std::path::Path; |
| 77 | |
| 78 | use braid_format::ObjectId; |
| 79 | |
| 80 | use crate::error::Error; |
| 81 | use crate::fsprobe::random_hex; |
| 82 | use crate::safe::{DirStamp, Stat, StatKind}; |
| 83 | |
| 84 | const MAGIC: &[u8; 8] = b"braidwsc"; |
| 85 | const VERSION: u32 = 3; |
| 86 | |
| 87 | const HEADER_LEN: usize = 40; |
| 88 | const DIR_LEN: usize = 96; |
| 89 | const FILE_LEN: usize = 72; |
| 90 | const CHECK_LEN: usize = 4; |
| 91 | |
| 92 | const DIR_HAS_BASE: u32 = 1; |
| 93 | const DIR_CLEAN: u32 = 2; |
| 94 | const DIR_STAMPED: u32 = 4; |
| 95 | const DIR_IGNORED: u32 = 8; |
| 96 | const DIR_IGNORE_FILES: u32 = 16; |
| 97 | const FILE_VOUCHES: u8 = 1; |
| 98 | |
| 99 | /// A regular file. |
| 100 | pub(crate) const KIND_FILE: u8 = 0; |
| 101 | /// An executable file. |
| 102 | pub(crate) const KIND_EXECUTABLE: u8 = 1; |
| 103 | /// A symlink. |
| 104 | pub(crate) const KIND_SYMLINK: u8 = 2; |
| 105 | /// A gitlink of the base whose directory is there. |
| 106 | pub(crate) const KIND_GITLINK: u8 = 3; |
| 107 | /// A subdirectory that the base has: its tree is the blob. |
| 108 | pub(crate) const KIND_TREE: u8 = 4; |
| 109 | /// A subdirectory that the base does not have. |
| 110 | pub(crate) const KIND_SUBDIR: u8 = 5; |
| 111 | |
| 112 | /// The file the cache lives in, inside the workspace's state directory. |
| 113 | pub(crate) const FILE: &str = "stat"; |
| 114 | |
| 115 | const ZERO: ObjectId = ObjectId::from_bytes([0; 32]); |
| 116 | |
| 117 | /// The kind code of a file with this metadata, or `None` for something that |
| 118 | /// is not a file or a symlink. |
| 119 | pub(crate) fn kind_code(stat: &Stat) -> Option<u8> { |
| 120 | match stat.kind { |
| 121 | StatKind::File if stat.executable => Some(KIND_EXECUTABLE), |
| 122 | StatKind::File => Some(KIND_FILE), |
| 123 | StatKind::Symlink => Some(KIND_SYMLINK), |
| 124 | StatKind::Dir | StatKind::Other => None, |
| 125 | } |
| 126 | } |
| 127 | |
| 128 | /// The cache of one workspace, as loaded: the file's bytes, checked once, |
| 129 | /// read in place. |
| 130 | #[derive(Debug, Default)] |
| 131 | pub(crate) struct Cache { |
| 132 | bytes: Vec<u8>, |
| 133 | time: (i64, u32), |
| 134 | dirs: usize, |
| 135 | files: usize, |
| 136 | } |
| 137 | |
| 138 | impl Cache { |
| 139 | /// The cache in `state_dir`, or an empty one if there is none or it is |
| 140 | /// damaged. |
| 141 | pub(crate) fn load(state_dir: &Path) -> Cache { |
| 142 | fs::read(state_dir.join(FILE)) |
| 143 | .ok() |
| 144 | .and_then(Cache::decode) |
| 145 | .unwrap_or_default() |
| 146 | } |
| 147 | |
| 148 | /// When the scan that wrote it started, by the file system's clock. |
| 149 | pub(crate) fn time(&self) -> (i64, u32) { |
| 150 | self.time |
| 151 | } |
| 152 | |
| 153 | /// How many directories it records. |
| 154 | pub(crate) fn dir_count(&self) -> usize { |
| 155 | self.dirs |
| 156 | } |
| 157 | |
| 158 | /// The record of the directory at `path` (empty for the root). |
| 159 | pub(crate) fn dir(&self, path: &[u8]) -> Option<CachedDir<'_>> { |
| 160 | let (mut low, mut high) = (0, self.dirs); |
| 161 | while low < high { |
| 162 | let middle = low + (high - low) / 2; |
| 163 | let dir = CachedDir { |
| 164 | cache: self, |
| 165 | at: HEADER_LEN + middle * DIR_LEN, |
| 166 | }; |
| 167 | match dir.path().cmp(path) { |
| 168 | std::cmp::Ordering::Less => low = middle + 1, |
| 169 | std::cmp::Ordering::Greater => high = middle, |
| 170 | std::cmp::Ordering::Equal => return Some(dir), |
| 171 | } |
| 172 | } |
| 173 | None |
| 174 | } |
| 175 | |
| 176 | fn names_at(&self) -> usize { |
| 177 | HEADER_LEN + self.dirs * DIR_LEN + self.files * FILE_LEN |
| 178 | } |
| 179 | |
| 180 | /// The bytes of entry `index`'s record. |
| 181 | fn entry(&self, index: usize) -> &[u8] { |
| 182 | let at = HEADER_LEN + self.dirs * DIR_LEN + index * FILE_LEN; |
| 183 | &self.bytes[at..at + FILE_LEN] |
| 184 | } |
| 185 | |
| 186 | /// Checks the bytes of a cache file: the checksum, the header, and that |
| 187 | /// every record lies within the file. The order of records is not |
| 188 | /// checked: records out of order can only fail to be found. |
| 189 | fn decode(bytes: Vec<u8>) -> Option<Cache> { |
| 190 | if bytes.len() < HEADER_LEN + CHECK_LEN { |
| 191 | return None; |
| 192 | } |
| 193 | let (body, check) = bytes.split_at(bytes.len() - CHECK_LEN); |
| 194 | if crc32c::crc32c(body).to_le_bytes()[..] != *check { |
| 195 | return None; |
| 196 | } |
| 197 | if body[..8] != MAGIC[..] || u32_at(body, 8) != VERSION { |
| 198 | return None; |
| 199 | } |
| 200 | let time = (i64_at(body, 16), u32_at(body, 24)); |
| 201 | let dirs = u32_at(body, 28) as usize; |
| 202 | let files = u32_at(body, 32) as usize; |
| 203 | let names = u32_at(body, 36) as usize; |
| 204 | let expected = HEADER_LEN |
| 205 | .checked_add(dirs.checked_mul(DIR_LEN)?)? |
| 206 | .checked_add(files.checked_mul(FILE_LEN)?)? |
| 207 | .checked_add(names)?; |
| 208 | if expected != body.len() || time.1 >= 1_000_000_000 { |
| 209 | return None; |
| 210 | } |
| 211 | let within = |offset: u32, len: u32, limit: usize| { |
| 212 | (offset as usize) |
| 213 | .checked_add(len as usize) |
| 214 | .is_some_and(|end| end <= limit) |
| 215 | }; |
| 216 | for index in 0..dirs { |
| 217 | let at = HEADER_LEN + index * DIR_LEN; |
| 218 | let record = &body[at..at + DIR_LEN]; |
| 219 | let block = u32_at(record, 76); |
| 220 | let first = u32_at(record, 8) as usize; |
| 221 | let count = u32_at(record, 12) as usize; |
| 222 | if !within(u32_at(record, 0), block, names) |
| 223 | || u32_at(record, 4) > block |
| 224 | || first.checked_add(count)? > files |
| 225 | { |
| 226 | return None; |
| 227 | } |
| 228 | for entry in first..first + count { |
| 229 | let at = HEADER_LEN + dirs * DIR_LEN + entry * FILE_LEN; |
| 230 | let entry = &body[at..at + FILE_LEN]; |
| 231 | if !within(u32_at(entry, 0), u32_at(entry, 4), block as usize) { |
| 232 | return None; |
| 233 | } |
| 234 | } |
| 235 | } |
| 236 | Some(Cache { |
| 237 | bytes, |
| 238 | time, |
| 239 | dirs, |
| 240 | files, |
| 241 | }) |
| 242 | } |
| 243 | } |
| 244 | |
| 245 | /// The record of one directory. |
| 246 | #[derive(Clone, Copy, Debug)] |
| 247 | pub(crate) struct CachedDir<'c> { |
| 248 | cache: &'c Cache, |
| 249 | at: usize, |
| 250 | } |
| 251 | |
| 252 | impl<'c> CachedDir<'c> { |
| 253 | fn record(&self) -> &'c [u8] { |
| 254 | &self.cache.bytes[self.at..self.at + DIR_LEN] |
| 255 | } |
| 256 | |
| 257 | /// The directory's block of name bytes: its path, then its entries' |
| 258 | /// names. |
| 259 | fn block(&self) -> &'c [u8] { |
| 260 | let record = self.record(); |
| 261 | let start = self.cache.names_at() + u32_at(record, 0) as usize; |
| 262 | &self.cache.bytes[start..start + u32_at(record, 76) as usize] |
| 263 | } |
| 264 | |
| 265 | /// The directory's path. |
| 266 | pub(crate) fn path(&self) -> &'c [u8] { |
| 267 | &self.block()[..u32_at(self.record(), 4) as usize] |
| 268 | } |
| 269 | |
| 270 | fn entry(&self, index: usize) -> CachedFile<'c> { |
| 271 | let bytes = self.cache.entry(index); |
| 272 | let (offset, len) = (u32_at(bytes, 0) as usize, u32_at(bytes, 4) as usize); |
| 273 | CachedFile { |
| 274 | name: &self.block()[offset..offset + len], |
| 275 | mtime: (i64_at(bytes, 8), u32_at(bytes, 16)), |
| 276 | kind: bytes[20], |
| 277 | vouches: bytes[21] & FILE_VOUCHES != 0, |
| 278 | size: u64_at(bytes, 24), |
| 279 | ino: u64_at(bytes, 32), |
| 280 | blob: id_at(bytes, 40), |
| 281 | } |
| 282 | } |
| 283 | |
| 284 | fn flags(&self) -> u32 { |
| 285 | u32_at(self.record(), 48) |
| 286 | } |
| 287 | |
| 288 | /// The base tree the directory was compared with, if it had one. |
| 289 | pub(crate) fn base(&self) -> Option<ObjectId> { |
| 290 | (self.flags() & DIR_HAS_BASE != 0).then(|| id_at(self.record(), 16)) |
| 291 | } |
| 292 | |
| 293 | /// Whether its entries were exactly those of that tree. |
| 294 | pub(crate) fn clean(&self) -> bool { |
| 295 | self.flags() & DIR_CLEAN != 0 |
| 296 | } |
| 297 | |
| 298 | /// Its stamp when it was listed, if it was. |
| 299 | pub(crate) fn stamp(&self) -> Option<DirStamp> { |
| 300 | let record = self.record(); |
| 301 | (self.flags() & DIR_STAMPED != 0).then(|| DirStamp { |
| 302 | mtime: (i64_at(record, 56), u32_at(record, 52)), |
| 303 | ctime: (i64_at(record, 64), u32_at(record, 72)), |
| 304 | ino: u64_at(record, 80), |
| 305 | }) |
| 306 | } |
| 307 | |
| 308 | /// Whether it was ignored: only what the base had counted inside. |
| 309 | pub(crate) fn ignored(&self) -> bool { |
| 310 | self.flags() & DIR_IGNORED != 0 |
| 311 | } |
| 312 | |
| 313 | /// The digest of the ignore rules in force for its entries. |
| 314 | pub(crate) fn rules(&self) -> u64 { |
| 315 | u64_at(self.record(), 88) |
| 316 | } |
| 317 | |
| 318 | /// Which ignore files it had: bit 0 for `.braidignore`, 1 for |
| 319 | /// `.gitignore`. |
| 320 | pub(crate) fn ignore_files(&self) -> u8 { |
| 321 | ((self.flags() / DIR_IGNORE_FILES) & 3) as u8 |
| 322 | } |
| 323 | |
| 324 | fn range(&self) -> std::ops::Range<usize> { |
| 325 | let record = self.record(); |
| 326 | let first = u32_at(record, 8) as usize; |
| 327 | first..first + u32_at(record, 12) as usize |
| 328 | } |
| 329 | |
| 330 | /// The bytes of its entries' records. |
| 331 | fn entries(&self) -> &'c [u8] { |
| 332 | let range = self.range(); |
| 333 | let start = HEADER_LEN + self.cache.dirs * DIR_LEN + range.start * FILE_LEN; |
| 334 | &self.cache.bytes[start..start + range.len() * FILE_LEN] |
| 335 | } |
| 336 | |
| 337 | /// How many entries it recorded. |
| 338 | pub(crate) fn file_count(&self) -> usize { |
| 339 | self.range().len() |
| 340 | } |
| 341 | |
| 342 | /// Its entries' records, by name. |
| 343 | pub(crate) fn files(&self) -> impl Iterator<Item = CachedFile<'c>> + 'c { |
| 344 | let dir = *self; |
| 345 | self.range().map(move |index| dir.entry(index)) |
| 346 | } |
| 347 | |
| 348 | /// The record of the entry `name`. |
| 349 | pub(crate) fn file(&self, name: &[u8]) -> Option<CachedFile<'c>> { |
| 350 | let range = self.range(); |
| 351 | let (mut low, mut high) = (range.start, range.end); |
| 352 | while low < high { |
| 353 | let middle = low + (high - low) / 2; |
| 354 | let file = self.entry(middle); |
| 355 | match file.name.cmp(name) { |
| 356 | std::cmp::Ordering::Less => low = middle + 1, |
| 357 | std::cmp::Ordering::Greater => high = middle, |
| 358 | std::cmp::Ordering::Equal => return Some(file), |
| 359 | } |
| 360 | } |
| 361 | None |
| 362 | } |
| 363 | } |
| 364 | |
| 365 | /// The record of one entry of a directory. |
| 366 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 367 | pub(crate) struct CachedFile<'c> { |
| 368 | pub name: &'c [u8], |
| 369 | pub mtime: (i64, u32), |
| 370 | pub size: u64, |
| 371 | pub ino: u64, |
| 372 | pub kind: u8, |
| 373 | /// Whether the record may vouch for the file by its metadata. |
| 374 | pub vouches: bool, |
| 375 | pub blob: ObjectId, |
| 376 | } |
| 377 | |
| 378 | impl CachedFile<'_> { |
| 379 | /// The blob of the file, if this record may be trusted for a file that |
| 380 | /// now has the metadata `stat`, in a cache whose scan started at `time`. |
| 381 | pub(crate) fn vouch(&self, stat: &Stat, time: (i64, u32)) -> Option<ObjectId> { |
| 382 | let same = self.mtime == stat.mtime |
| 383 | && self.size == stat.size |
| 384 | && self.ino == stat.ino |
| 385 | && Some(self.kind) == kind_code(stat); |
| 386 | (self.vouches && same && self.mtime < time).then_some(self.blob) |
| 387 | } |
| 388 | } |
| 389 | |
| 390 | /// A directory's record, as a scan makes it. |
| 391 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 392 | pub(crate) struct DirRecord { |
| 393 | pub path: Vec<u8>, |
| 394 | pub base: Option<ObjectId>, |
| 395 | pub clean: bool, |
| 396 | /// Its stamp, taken before it was listed; `None` where the system gives |
| 397 | /// none. |
| 398 | pub stamp: Option<DirStamp>, |
| 399 | pub ignored: bool, |
| 400 | pub rules: u64, |
| 401 | /// See [`CachedDir::ignore_files`]. |
| 402 | pub ignore_files: u8, |
| 403 | /// By name, strictly ascending. |
| 404 | pub files: Vec<FileRecord>, |
| 405 | } |
| 406 | |
| 407 | impl DirRecord { |
| 408 | fn flags(&self) -> u32 { |
| 409 | let bit = |set: bool, bit: u32| if set { bit } else { 0 }; |
| 410 | bit(self.base.is_some(), DIR_HAS_BASE) |
| 411 | | bit(self.clean, DIR_CLEAN) |
| 412 | | bit(self.stamp.is_some(), DIR_STAMPED) |
| 413 | | bit(self.ignored, DIR_IGNORED) |
| 414 | | (u32::from(self.ignore_files & 3) * DIR_IGNORE_FILES) |
| 415 | } |
| 416 | |
| 417 | /// Whether `cached` says exactly the same. |
| 418 | pub(crate) fn same_as(&self, cached: &CachedDir<'_>) -> bool { |
| 419 | self.flags() == cached.flags() |
| 420 | && self.base == cached.base() |
| 421 | && self.stamp == cached.stamp() |
| 422 | && self.rules == cached.rules() |
| 423 | && self.files.len() == cached.file_count() |
| 424 | && self |
| 425 | .files |
| 426 | .iter() |
| 427 | .zip(cached.files()) |
| 428 | .all(|(new, old)| new.view() == old) |
| 429 | } |
| 430 | } |
| 431 | |
| 432 | /// A file's record, as a scan makes it. |
| 433 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 434 | pub(crate) struct FileRecord { |
| 435 | pub name: Vec<u8>, |
| 436 | pub mtime: (i64, u32), |
| 437 | pub size: u64, |
| 438 | pub ino: u64, |
| 439 | pub kind: u8, |
| 440 | pub vouches: bool, |
| 441 | pub blob: ObjectId, |
| 442 | } |
| 443 | |
| 444 | impl FileRecord { |
| 445 | /// The record of a file or symlink with this metadata and blob. |
| 446 | pub(crate) fn new(name: Vec<u8>, stat: &Stat, kind: u8, vouches: bool, blob: ObjectId) -> Self { |
| 447 | FileRecord { |
| 448 | name, |
| 449 | mtime: stat.mtime, |
| 450 | size: stat.size, |
| 451 | ino: stat.ino, |
| 452 | kind, |
| 453 | vouches, |
| 454 | blob, |
| 455 | } |
| 456 | } |
| 457 | |
| 458 | /// The record of an entry without metadata: a gitlink whose directory |
| 459 | /// is there, or a subdirectory, with the base's tree for it if any. |
| 460 | pub(crate) fn bare(name: Vec<u8>, kind: u8, blob: Option<ObjectId>) -> Self { |
| 461 | FileRecord { |
| 462 | name, |
| 463 | mtime: (0, 0), |
| 464 | size: 0, |
| 465 | ino: 0, |
| 466 | kind, |
| 467 | vouches: false, |
| 468 | blob: blob.unwrap_or(ZERO), |
| 469 | } |
| 470 | } |
| 471 | |
| 472 | fn view(&self) -> CachedFile<'_> { |
| 473 | CachedFile { |
| 474 | name: &self.name, |
| 475 | mtime: self.mtime, |
| 476 | size: self.size, |
| 477 | ino: self.ino, |
| 478 | kind: self.kind, |
| 479 | vouches: self.vouches, |
| 480 | blob: self.blob, |
| 481 | } |
| 482 | } |
| 483 | } |
| 484 | |
| 485 | /// A directory's record for the next cache. |
| 486 | #[derive(Debug)] |
| 487 | pub(crate) enum Record<'c> { |
| 488 | /// As the old cache has it. |
| 489 | Kept(CachedDir<'c>), |
| 490 | /// Made by this scan. |
| 491 | Made(DirRecord), |
| 492 | } |
| 493 | |
| 494 | impl Record<'_> { |
| 495 | /// The record as one a scan made. |
| 496 | pub(crate) fn into_made(self) -> DirRecord { |
| 497 | let dir = match self { |
| 498 | Record::Made(dir) => return dir, |
| 499 | Record::Kept(dir) => dir, |
| 500 | }; |
| 501 | DirRecord { |
| 502 | path: dir.path().to_vec(), |
| 503 | base: dir.base(), |
| 504 | clean: dir.clean(), |
| 505 | stamp: dir.stamp(), |
| 506 | ignored: dir.ignored(), |
| 507 | rules: dir.rules(), |
| 508 | ignore_files: dir.ignore_files(), |
| 509 | files: dir |
| 510 | .files() |
| 511 | .map(|file| FileRecord { |
| 512 | name: file.name.to_vec(), |
| 513 | mtime: file.mtime, |
| 514 | size: file.size, |
| 515 | ino: file.ino, |
| 516 | kind: file.kind, |
| 517 | vouches: file.vouches, |
| 518 | blob: file.blob, |
| 519 | }) |
| 520 | .collect(), |
| 521 | } |
| 522 | } |
| 523 | |
| 524 | /// The directory's path. |
| 525 | pub(crate) fn path(&self) -> &[u8] { |
| 526 | match self { |
| 527 | Record::Kept(dir) => dir.path(), |
| 528 | Record::Made(dir) => &dir.path, |
| 529 | } |
| 530 | } |
| 531 | |
| 532 | fn file_count(&self) -> usize { |
| 533 | match self { |
| 534 | Record::Kept(dir) => dir.file_count(), |
| 535 | Record::Made(dir) => dir.files.len(), |
| 536 | } |
| 537 | } |
| 538 | |
| 539 | /// The length of its block of name bytes. |
| 540 | fn block_len(&self) -> usize { |
| 541 | match self { |
| 542 | Record::Kept(dir) => dir.block().len(), |
| 543 | Record::Made(dir) => { |
| 544 | dir.path.len() + dir.files.iter().map(|file| file.name.len()).sum::<usize>() |
| 545 | } |
| 546 | } |
| 547 | } |
| 548 | } |
| 549 | |
| 550 | /// Writes a cache into `state_dir`, through a scratch file and a rename: |
| 551 | /// the scan started at `time` and made `records`, sorted by path. |
| 552 | pub(crate) fn save( |
| 553 | state_dir: &Path, |
| 554 | time: (i64, u32), |
| 555 | records: &[Record<'_>], |
| 556 | ) -> Result<(), Error> { |
| 557 | let target = state_dir.join(FILE); |
| 558 | // A cache too large for its offsets is not kept: the next scan reads |
| 559 | // what it must. |
| 560 | let Some(bytes) = encode(time, records) else { |
| 561 | let _ = fs::remove_file(&target); |
| 562 | return Ok(()); |
| 563 | }; |
| 564 | let scratch = state_dir.join(format!("{FILE}.tmp-{}", random_hex())); |
| 565 | let written = fs::File::create_new(&scratch) |
| 566 | .and_then(|mut file| file.write_all(&bytes)) |
| 567 | .and_then(|()| fs::rename(&scratch, &target)); |
| 568 | if written.is_err() { |
| 569 | let _ = fs::remove_file(&scratch); |
| 570 | } |
| 571 | written.map_err(Error::io("write", &target)) |
| 572 | } |
| 573 | |
| 574 | fn encode(time: (i64, u32), records: &[Record<'_>]) -> Option<Vec<u8>> { |
| 575 | let files: usize = records.iter().map(Record::file_count).sum(); |
| 576 | let names: usize = records.iter().map(Record::block_len).sum(); |
| 577 | let small = |n: usize| u32::try_from(n).ok(); |
| 578 | let (dir_count, file_count, name_bytes) = (small(records.len())?, small(files)?, small(names)?); |
| 579 | |
| 580 | let mut out = Vec::with_capacity( |
| 581 | HEADER_LEN + records.len() * DIR_LEN + files * FILE_LEN + names + CHECK_LEN, |
| 582 | ); |
| 583 | out.extend_from_slice(MAGIC); |
| 584 | out.extend_from_slice(&VERSION.to_le_bytes()); |
| 585 | out.extend_from_slice(&0u32.to_le_bytes()); |
| 586 | out.extend_from_slice(&time.0.to_le_bytes()); |
| 587 | out.extend_from_slice(&time.1.to_le_bytes()); |
| 588 | out.extend_from_slice(&dir_count.to_le_bytes()); |
| 589 | out.extend_from_slice(&file_count.to_le_bytes()); |
| 590 | out.extend_from_slice(&name_bytes.to_le_bytes()); |
| 591 | |
| 592 | // Offsets fit: the name bytes add up to no more than `u32::MAX`. |
| 593 | let mut name_table: Vec<u8> = Vec::with_capacity(names); |
| 594 | let mut file_table: Vec<u8> = Vec::with_capacity(files * FILE_LEN); |
| 595 | let mut first = 0u32; |
| 596 | for record in records { |
| 597 | let block_at = name_table.len() as u32; |
| 598 | let count = record.file_count() as u32; |
| 599 | match record { |
| 600 | Record::Kept(dir) => { |
| 601 | // As it was, but for where its entries and names now lie. |
| 602 | let mut bytes = dir.record().to_vec(); |
| 603 | bytes[0..4].copy_from_slice(&block_at.to_le_bytes()); |
| 604 | bytes[8..12].copy_from_slice(&first.to_le_bytes()); |
| 605 | out.extend_from_slice(&bytes); |
| 606 | name_table.extend_from_slice(dir.block()); |
| 607 | file_table.extend_from_slice(dir.entries()); |
| 608 | } |
| 609 | Record::Made(dir) => { |
| 610 | let block_len = record.block_len() as u32; |
| 611 | out.extend_from_slice(&block_at.to_le_bytes()); |
| 612 | out.extend_from_slice(&(dir.path.len() as u32).to_le_bytes()); |
| 613 | out.extend_from_slice(&first.to_le_bytes()); |
| 614 | out.extend_from_slice(&count.to_le_bytes()); |
| 615 | out.extend_from_slice(dir.base.unwrap_or(ZERO).as_bytes()); |
| 616 | out.extend_from_slice(&dir.flags().to_le_bytes()); |
| 617 | let stamp = dir.stamp.unwrap_or(DirStamp { |
| 618 | mtime: (0, 0), |
| 619 | ctime: (0, 0), |
| 620 | ino: 0, |
| 621 | }); |
| 622 | out.extend_from_slice(&stamp.mtime.1.to_le_bytes()); |
| 623 | out.extend_from_slice(&stamp.mtime.0.to_le_bytes()); |
| 624 | out.extend_from_slice(&stamp.ctime.0.to_le_bytes()); |
| 625 | out.extend_from_slice(&stamp.ctime.1.to_le_bytes()); |
| 626 | out.extend_from_slice(&block_len.to_le_bytes()); |
| 627 | out.extend_from_slice(&stamp.ino.to_le_bytes()); |
| 628 | out.extend_from_slice(&dir.rules.to_le_bytes()); |
| 629 | name_table.extend_from_slice(&dir.path); |
| 630 | for file in &dir.files { |
| 631 | let offset = name_table.len() as u32 - block_at; |
| 632 | name_table.extend_from_slice(&file.name); |
| 633 | file_table.extend_from_slice(&offset.to_le_bytes()); |
| 634 | file_table.extend_from_slice(&(file.name.len() as u32).to_le_bytes()); |
| 635 | file_table.extend_from_slice(&file.mtime.0.to_le_bytes()); |
| 636 | file_table.extend_from_slice(&file.mtime.1.to_le_bytes()); |
| 637 | file_table.push(file.kind); |
| 638 | file_table.push(if file.vouches { FILE_VOUCHES } else { 0 }); |
| 639 | file_table.extend_from_slice(&0u16.to_le_bytes()); |
| 640 | file_table.extend_from_slice(&file.size.to_le_bytes()); |
| 641 | file_table.extend_from_slice(&file.ino.to_le_bytes()); |
| 642 | file_table.extend_from_slice(file.blob.as_bytes()); |
| 643 | } |
| 644 | } |
| 645 | } |
| 646 | first += count; |
| 647 | } |
| 648 | out.extend_from_slice(&file_table); |
| 649 | out.extend_from_slice(&name_table); |
| 650 | let check = crc32c::crc32c(&out); |
| 651 | out.extend_from_slice(&check.to_le_bytes()); |
| 652 | Some(out) |
| 653 | } |
| 654 | |
| 655 | fn u32_at(bytes: &[u8], at: usize) -> u32 { |
| 656 | let mut word = [0u8; 4]; |
| 657 | word.copy_from_slice(&bytes[at..at + 4]); |
| 658 | u32::from_le_bytes(word) |
| 659 | } |
| 660 | |
| 661 | fn u64_at(bytes: &[u8], at: usize) -> u64 { |
| 662 | let mut word = [0u8; 8]; |
| 663 | word.copy_from_slice(&bytes[at..at + 8]); |
| 664 | u64::from_le_bytes(word) |
| 665 | } |
| 666 | |
| 667 | fn i64_at(bytes: &[u8], at: usize) -> i64 { |
| 668 | u64_at(bytes, at) as i64 |
| 669 | } |
| 670 | |
| 671 | fn id_at(bytes: &[u8], at: usize) -> ObjectId { |
| 672 | let mut id = [0u8; 32]; |
| 673 | id.copy_from_slice(&bytes[at..at + 32]); |
| 674 | ObjectId::from_bytes(id) |
| 675 | } |
| 676 | |
| 677 | #[cfg(test)] |
| 678 | mod tests { |
| 679 | use super::*; |
| 680 | use braid_format::Kind; |
| 681 | |
| 682 | fn stat(mtime: i64) -> Stat { |
| 683 | Stat { |
| 684 | kind: StatKind::File, |
| 685 | executable: false, |
| 686 | size: 5, |
| 687 | mtime: (mtime, 7), |
| 688 | ino: 42, |
| 689 | } |
| 690 | } |
| 691 | |
| 692 | fn record(name: &str, mtime: i64, vouches: bool) -> FileRecord { |
| 693 | let blob = ObjectId::hash(Kind::Blob, name.as_bytes()); |
| 694 | FileRecord::new(name.into(), &stat(mtime), KIND_FILE, vouches, blob) |
| 695 | } |
| 696 | |
| 697 | fn dirs() -> Vec<DirRecord> { |
| 698 | let tree = ObjectId::hash(Kind::Tree, b"t"); |
| 699 | let sub = ObjectId::hash(Kind::Tree, b"sub"); |
| 700 | vec![ |
| 701 | DirRecord { |
| 702 | path: Vec::new(), |
| 703 | base: Some(tree), |
| 704 | clean: true, |
| 705 | stamp: Some(DirStamp { |
| 706 | mtime: (40, 1), |
| 707 | ctime: (41, 2), |
| 708 | ino: 9, |
| 709 | }), |
| 710 | ignored: false, |
| 711 | rules: 77, |
| 712 | ignore_files: 2, |
| 713 | files: vec![ |
| 714 | record("a", 50, true), |
| 715 | record("b", 50, false), |
| 716 | FileRecord::bare(b"new".to_vec(), KIND_SUBDIR, None), |
| 717 | FileRecord::bare(b"sub".to_vec(), KIND_TREE, Some(sub)), |
| 718 | ], |
| 719 | }, |
| 720 | DirRecord { |
| 721 | path: b"sub".to_vec(), |
| 722 | base: Some(sub), |
| 723 | clean: false, |
| 724 | stamp: None, |
| 725 | ignored: true, |
| 726 | rules: 0, |
| 727 | ignore_files: 0, |
| 728 | files: Vec::new(), |
| 729 | }, |
| 730 | DirRecord { |
| 731 | path: b"sub/deep".to_vec(), |
| 732 | base: None, |
| 733 | clean: false, |
| 734 | stamp: None, |
| 735 | ignored: false, |
| 736 | rules: 0, |
| 737 | ignore_files: 1, |
| 738 | files: vec![record("x", 60, true)], |
| 739 | }, |
| 740 | ] |
| 741 | } |
| 742 | |
| 743 | fn made(dirs: Vec<DirRecord>) -> Vec<Record<'static>> { |
| 744 | dirs.into_iter().map(Record::Made).collect() |
| 745 | } |
| 746 | |
| 747 | #[test] |
| 748 | fn round_trip_and_damage() { |
| 749 | let dir = tempfile::tempdir().unwrap(); |
| 750 | let empty = Cache::load(dir.path()); |
| 751 | assert_eq!((empty.dir_count(), empty.time()), (0, (0, 0))); |
| 752 | assert!(empty.dir(b"").is_none()); |
| 753 | |
| 754 | let written = dirs(); |
| 755 | save(dir.path(), (100, 9), &made(written.clone())).unwrap(); |
| 756 | let cache = Cache::load(dir.path()); |
| 757 | assert_eq!((cache.dir_count(), cache.time()), (3, (100, 9))); |
| 758 | for record in &written { |
| 759 | let found = cache.dir(&record.path).unwrap(); |
| 760 | assert!(record.same_as(&found), "{:?}", record.path); |
| 761 | assert_eq!(found.path(), record.path); |
| 762 | assert_eq!(found.stamp(), record.stamp); |
| 763 | assert_eq!( |
| 764 | (found.ignored(), found.rules(), found.ignore_files()), |
| 765 | (record.ignored, record.rules, record.ignore_files) |
| 766 | ); |
| 767 | } |
| 768 | assert!(cache.dir(b"other").is_none()); |
| 769 | let root = cache.dir(b"").unwrap(); |
| 770 | assert_eq!(root.file(b"b").unwrap().name, b"b"); |
| 771 | assert_eq!(root.file(b"sub").unwrap().kind, KIND_TREE); |
| 772 | assert!(root.file(b"c").is_none()); |
| 773 | // Only the directory's own entries are its own. |
| 774 | assert!(root.file(b"x").is_none()); |
| 775 | // Nothing but the cache is left in the directory. |
| 776 | assert_eq!(fs::read_dir(dir.path()).unwrap().count(), 1); |
| 777 | |
| 778 | // Records kept from a loaded cache are written again as they were. |
| 779 | let mut kept: Vec<Record<'_>> = vec![ |
| 780 | Record::Kept(cache.dir(b"").unwrap()), |
| 781 | Record::Made(written[1].clone()), |
| 782 | Record::Kept(cache.dir(b"sub/deep").unwrap()), |
| 783 | ]; |
| 784 | kept.sort_by(|a, b| a.path().cmp(b.path())); |
| 785 | let other = tempfile::tempdir().unwrap(); |
| 786 | save(other.path(), (100, 9), &kept).unwrap(); |
| 787 | assert_eq!( |
| 788 | fs::read(other.path().join(FILE)).unwrap(), |
| 789 | fs::read(dir.path().join(FILE)).unwrap() |
| 790 | ); |
| 791 | |
| 792 | // Read back as made, a kept record is the one written. |
| 793 | for record in &written { |
| 794 | let made = Record::Kept(cache.dir(&record.path).unwrap()).into_made(); |
| 795 | assert_eq!(&made, record); |
| 796 | } |
| 797 | |
| 798 | // A record that differs in anything is not the same. |
| 799 | let mut changed = written[0].clone(); |
| 800 | changed.rules = 78; |
| 801 | assert!(!changed.same_as(&root)); |
| 802 | let mut changed = written[0].clone(); |
| 803 | changed.files[1].vouches = true; |
| 804 | assert!(!changed.same_as(&root)); |
| 805 | |
| 806 | let mut bytes = fs::read(dir.path().join(FILE)).unwrap(); |
| 807 | bytes[60] ^= 1; |
| 808 | fs::write(dir.path().join(FILE), &bytes).unwrap(); |
| 809 | assert_eq!(Cache::load(dir.path()).dir_count(), 0); |
| 810 | fs::write(dir.path().join(FILE), b"braidwsc").unwrap(); |
| 811 | assert_eq!(Cache::load(dir.path()).dir_count(), 0); |
| 812 | } |
| 813 | |
| 814 | #[test] |
| 815 | fn the_guard() { |
| 816 | let dir = tempfile::tempdir().unwrap(); |
| 817 | let mut written = dirs(); |
| 818 | written[0].files.insert(2, record("racy", 100, true)); |
| 819 | save(dir.path(), (100, 0), &made(written)).unwrap(); |
| 820 | let cache = Cache::load(dir.path()); |
| 821 | let root = cache.dir(b"").unwrap(); |
| 822 | let time = cache.time(); |
| 823 | let blob = ObjectId::hash(Kind::Blob, b"a"); |
| 824 | let a = root.file(b"a").unwrap(); |
| 825 | assert_eq!(a.vouch(&stat(50), time), Some(blob)); |
| 826 | // Modified since, or written in the same instant as the scan. |
| 827 | assert_eq!(a.vouch(&stat(51), time), None); |
| 828 | let racy = root.file(b"racy").unwrap(); |
| 829 | assert_eq!(racy.vouch(&stat(100), time), None); |
| 830 | // Another inode, size or kind. |
| 831 | let mut moved = stat(50); |
| 832 | moved.ino = 43; |
| 833 | assert_eq!(a.vouch(&moved, time), None); |
| 834 | let mut exec = stat(50); |
| 835 | exec.executable = true; |
| 836 | assert_eq!(a.vouch(&exec, time), None); |
| 837 | let mut longer = stat(50); |
| 838 | longer.size = 6; |
| 839 | assert_eq!(a.vouch(&longer, time), None); |
| 840 | // A record that does not vouch is never used. |
| 841 | assert_eq!(root.file(b"b").unwrap().vouch(&stat(50), time), None); |
| 842 | } |
| 843 | } |