| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright (c) 2026 UtopiaIA |
| 3 | |
| 4 | //! The derived index: where the records of derived values are, by key |
| 5 | //! (format spec, section 7). |
| 6 | //! |
| 7 | //! A derived value is stored as a derived object whose payload starts with |
| 8 | //! its key, and this index maps keys to the ids of those objects. It is a |
| 9 | //! cache: losing it, or part of it, only means computing values again, and |
| 10 | //! whoever reads an entry checks the record it names. So it needs no sync of |
| 11 | //! its own; but its writer makes the records durable first, so an entry never |
| 12 | //! outlives the record it names. |
| 13 | //! |
| 14 | //! ```text |
| 15 | //! derived/index append-only, 72-byte entries at multiples of 72: |
| 16 | //! [32] key | [32] record id | u32 0 | u32 crc32c of the 68 bytes before it |
| 17 | //! ``` |
| 18 | //! |
| 19 | //! A writer takes an exclusive lock on the file, appends its entries at the |
| 20 | //! first multiple of 72 at or after the end, and lets go: entries of |
| 21 | //! different writers never interleave, and the remains of an append cut short |
| 22 | //! by a crash fail their CRC and are skipped. Readers take no lock. A handle |
| 23 | //! reads the whole file when first asked, and on a miss reads what was |
| 24 | //! appended since. When a key has several entries, the last one counts. |
| 25 | //! Entries are never removed; a compacted form can come with the store's own |
| 26 | //! indexes. |
| 27 | |
| 28 | use std::collections::HashMap; |
| 29 | use std::fs::{self, File, OpenOptions}; |
| 30 | use std::io; |
| 31 | use std::path::{Path, PathBuf}; |
| 32 | use std::sync::{Mutex, MutexGuard}; |
| 33 | |
| 34 | use braid_format::ObjectId; |
| 35 | |
| 36 | use crate::error::{Error, io_error}; |
| 37 | use crate::fsutil::{read_range, write_all_at}; |
| 38 | |
| 39 | /// The directory of the derived index, inside the store. |
| 40 | pub const DERIVED_DIR: &str = "derived"; |
| 41 | |
| 42 | /// The file of entries, inside [`DERIVED_DIR`]. |
| 43 | const INDEX_FILE: &str = "index"; |
| 44 | |
| 45 | /// Bytes per entry. |
| 46 | const ENTRY_LEN: u64 = 72; |
| 47 | |
| 48 | /// The derived index of a store, opened by this process. |
| 49 | /// |
| 50 | /// Creating a handle does no I/O: the file is read when it is first needed. |
| 51 | /// A handle is `Send` and `Sync`. |
| 52 | #[derive(Debug)] |
| 53 | pub struct DerivedIndexFile { |
| 54 | path: PathBuf, |
| 55 | state: Mutex<State>, |
| 56 | } |
| 57 | |
| 58 | #[derive(Debug, Default)] |
| 59 | struct State { |
| 60 | /// What the entries read so far say, the last entry of a key winning. |
| 61 | map: HashMap<[u8; 32], ObjectId>, |
| 62 | /// The file, once it exists. |
| 63 | file: Option<File>, |
| 64 | /// Where reading resumes: the end of the last whole slot read. |
| 65 | read_to: u64, |
| 66 | } |
| 67 | |
| 68 | impl DerivedIndexFile { |
| 69 | /// The derived index of the store at `store_root`. |
| 70 | pub fn new(store_root: impl AsRef<Path>) -> Self { |
| 71 | DerivedIndexFile { |
| 72 | path: store_root.as_ref().join(DERIVED_DIR).join(INDEX_FILE), |
| 73 | state: Mutex::new(State::default()), |
| 74 | } |
| 75 | } |
| 76 | |
| 77 | /// The id of the record of `key`, if an entry names one. A miss reads |
| 78 | /// what other processes appended since this handle last looked. |
| 79 | pub fn find(&self, key: &[u8; 32]) -> Result<Option<ObjectId>, Error> { |
| 80 | let mut state = self.lock(); |
| 81 | if let Some(id) = state.map.get(key) { |
| 82 | return Ok(Some(*id)); |
| 83 | } |
| 84 | self.refresh(&mut state)?; |
| 85 | Ok(state.map.get(key).copied()) |
| 86 | } |
| 87 | |
| 88 | /// Appends entries, in order, after making sure nobody else is |
| 89 | /// appending. The records they name must already be durable. |
| 90 | pub fn append(&self, entries: &[([u8; 32], ObjectId)]) -> Result<(), Error> { |
| 91 | if entries.is_empty() { |
| 92 | return Ok(()); |
| 93 | } |
| 94 | let dir = self.path.parent().unwrap_or(Path::new(".")); |
| 95 | fs::create_dir_all(dir).map_err(io_error("create", dir))?; |
| 96 | let file = OpenOptions::new() |
| 97 | .read(true) |
| 98 | .write(true) |
| 99 | .create(true) |
| 100 | .truncate(false) |
| 101 | .open(&self.path) |
| 102 | .map_err(io_error("open", &self.path))?; |
| 103 | file.lock().map_err(io_error("lock", &self.path))?; |
| 104 | let mut bytes = Vec::with_capacity(entries.len() * ENTRY_LEN as usize); |
| 105 | for (key, id) in entries { |
| 106 | bytes.extend_from_slice(&encode(key, id)); |
| 107 | } |
| 108 | let end = file |
| 109 | .metadata() |
| 110 | .map_err(io_error("read the size of", &self.path))? |
| 111 | .len(); |
| 112 | let at = end.next_multiple_of(ENTRY_LEN); |
| 113 | write_all_at(&file, &bytes, at).map_err(io_error("append to", &self.path))?; |
| 114 | // Closing the file lets the next writer in. |
| 115 | drop(file); |
| 116 | let mut state = self.lock(); |
| 117 | for (key, id) in entries { |
| 118 | state.map.insert(*key, *id); |
| 119 | } |
| 120 | Ok(()) |
| 121 | } |
| 122 | |
| 123 | /// Reads the entries appended since the last read. |
| 124 | fn refresh(&self, state: &mut State) -> Result<(), Error> { |
| 125 | if state.file.is_none() { |
| 126 | match File::open(&self.path) { |
| 127 | Ok(file) => state.file = Some(file), |
| 128 | Err(err) if err.kind() == io::ErrorKind::NotFound => return Ok(()), |
| 129 | Err(err) => return Err(io_error("open", &self.path)(err)), |
| 130 | } |
| 131 | } |
| 132 | let Some(file) = &state.file else { |
| 133 | return Ok(()); |
| 134 | }; |
| 135 | let len = file |
| 136 | .metadata() |
| 137 | .map_err(io_error("read the size of", &self.path))? |
| 138 | .len(); |
| 139 | // Only whole slots: the last one may still be being written. |
| 140 | let end = len - len % ENTRY_LEN; |
| 141 | if end <= state.read_to { |
| 142 | return Ok(()); |
| 143 | } |
| 144 | let bytes = read_range(file, state.read_to, end - state.read_to) |
| 145 | .map_err(io_error("read", &self.path))?; |
| 146 | for slot in bytes.as_chunks::<{ ENTRY_LEN as usize }>().0 { |
| 147 | if let Some((key, id)) = decode(slot) { |
| 148 | state.map.insert(key, id); |
| 149 | } |
| 150 | } |
| 151 | state.read_to = end; |
| 152 | Ok(()) |
| 153 | } |
| 154 | |
| 155 | fn lock(&self) -> MutexGuard<'_, State> { |
| 156 | // Every change to the state is complete before it is visible. |
| 157 | self.state |
| 158 | .lock() |
| 159 | .unwrap_or_else(|poisoned| poisoned.into_inner()) |
| 160 | } |
| 161 | } |
| 162 | |
| 163 | /// The bytes of one entry. |
| 164 | fn encode(key: &[u8; 32], id: &ObjectId) -> [u8; ENTRY_LEN as usize] { |
| 165 | let mut out = [0u8; ENTRY_LEN as usize]; |
| 166 | out[0..32].copy_from_slice(key); |
| 167 | out[32..64].copy_from_slice(id.as_bytes()); |
| 168 | // out[64..68] stays zero. |
| 169 | let crc = crc32c::crc32c(&out[..68]); |
| 170 | out[68..72].copy_from_slice(&crc.to_le_bytes()); |
| 171 | out |
| 172 | } |
| 173 | |
| 174 | /// The key and record id of an entry, or `None` if it fails its checks. |
| 175 | fn decode(slot: &[u8]) -> Option<([u8; 32], ObjectId)> { |
| 176 | if slot.len() != ENTRY_LEN as usize || slot[64..68] != [0; 4] { |
| 177 | return None; |
| 178 | } |
| 179 | let mut crc = [0u8; 4]; |
| 180 | crc.copy_from_slice(&slot[68..72]); |
| 181 | if crc32c::crc32c(&slot[..68]) != u32::from_le_bytes(crc) { |
| 182 | return None; |
| 183 | } |
| 184 | let mut key = [0u8; 32]; |
| 185 | key.copy_from_slice(&slot[..32]); |
| 186 | let mut id = [0u8; 32]; |
| 187 | id.copy_from_slice(&slot[32..64]); |
| 188 | Some((key, ObjectId::from_bytes(id))) |
| 189 | } |
| 190 | |
| 191 | #[cfg(test)] |
| 192 | mod tests { |
| 193 | use super::*; |
| 194 | use braid_format::Kind; |
| 195 | |
| 196 | fn key(n: u32) -> [u8; 32] { |
| 197 | *ObjectId::hash(Kind::Derived, &n.to_le_bytes()).as_bytes() |
| 198 | } |
| 199 | |
| 200 | fn id(n: u32) -> ObjectId { |
| 201 | ObjectId::hash(Kind::Blob, &n.to_le_bytes()) |
| 202 | } |
| 203 | |
| 204 | #[test] |
| 205 | fn entries_round_trip_and_damage_is_caught() { |
| 206 | let bytes = encode(&key(1), &id(2)); |
| 207 | assert_eq!(decode(&bytes), Some((key(1), id(2)))); |
| 208 | for i in 0..bytes.len() { |
| 209 | let mut damaged = bytes; |
| 210 | damaged[i] ^= 0x10; |
| 211 | assert_eq!(decode(&damaged), None, "byte {i}"); |
| 212 | } |
| 213 | assert_eq!(decode(&[0; 72]), None); |
| 214 | assert_eq!(decode(&bytes[..71]), None); |
| 215 | } |
| 216 | |
| 217 | #[test] |
| 218 | fn appends_are_seen_by_other_handles() { |
| 219 | let dir = tempfile::tempdir().unwrap(); |
| 220 | let writer = DerivedIndexFile::new(dir.path()); |
| 221 | let reader = DerivedIndexFile::new(dir.path()); |
| 222 | // No file yet: a miss, and nothing created. |
| 223 | assert_eq!(reader.find(&key(1)).unwrap(), None); |
| 224 | assert!(!dir.path().join(DERIVED_DIR).exists()); |
| 225 | |
| 226 | writer.append(&[(key(1), id(1)), (key(2), id(2))]).unwrap(); |
| 227 | assert_eq!(writer.find(&key(1)).unwrap(), Some(id(1))); |
| 228 | assert_eq!(reader.find(&key(2)).unwrap(), Some(id(2))); |
| 229 | writer.append(&[(key(3), id(3)), (key(1), id(4))]).unwrap(); |
| 230 | assert_eq!(reader.find(&key(3)).unwrap(), Some(id(3))); |
| 231 | // The last entry of a key counts, once read. |
| 232 | assert_eq!(reader.find(&key(1)).unwrap(), Some(id(4))); |
| 233 | writer.append(&[]).unwrap(); |
| 234 | |
| 235 | let fresh = DerivedIndexFile::new(dir.path()); |
| 236 | assert_eq!(fresh.find(&key(1)).unwrap(), Some(id(4))); |
| 237 | assert_eq!(fresh.find(&key(9)).unwrap(), None); |
| 238 | } |
| 239 | |
| 240 | #[test] |
| 241 | fn torn_appends_are_skipped_and_written_after() { |
| 242 | let dir = tempfile::tempdir().unwrap(); |
| 243 | let index = DerivedIndexFile::new(dir.path()); |
| 244 | index.append(&[(key(1), id(1)), (key(2), id(2))]).unwrap(); |
| 245 | let path = dir.path().join(DERIVED_DIR).join(INDEX_FILE); |
| 246 | // A crash in the middle of the next append left half an entry, and |
| 247 | // damaged the second one. |
| 248 | let file = OpenOptions::new().write(true).open(&path).unwrap(); |
| 249 | write_all_at(&file, &encode(&key(3), &id(3))[..40], 2 * ENTRY_LEN).unwrap(); |
| 250 | write_all_at(&file, &[0xff], ENTRY_LEN + 3).unwrap(); |
| 251 | drop(file); |
| 252 | |
| 253 | index.append(&[(key(4), id(4))]).unwrap(); |
| 254 | assert_eq!(fs::metadata(&path).unwrap().len(), 4 * ENTRY_LEN); |
| 255 | let fresh = DerivedIndexFile::new(dir.path()); |
| 256 | assert_eq!(fresh.find(&key(1)).unwrap(), Some(id(1))); |
| 257 | assert_eq!(fresh.find(&key(2)).unwrap(), None); |
| 258 | assert_eq!(fresh.find(&key(3)).unwrap(), None); |
| 259 | assert_eq!(fresh.find(&key(4)).unwrap(), Some(id(4))); |
| 260 | } |
| 261 | |
| 262 | #[test] |
| 263 | fn concurrent_writers_never_mix_their_entries() { |
| 264 | let dir = tempfile::tempdir().unwrap(); |
| 265 | let root = dir.path().to_path_buf(); |
| 266 | // Separate handles open the file separately, so their locks exclude |
| 267 | // each other as those of separate processes do. |
| 268 | let threads: Vec<_> = (0..8u32) |
| 269 | .map(|t| { |
| 270 | let root = root.clone(); |
| 271 | std::thread::spawn(move || { |
| 272 | let index = DerivedIndexFile::new(&root); |
| 273 | for round in 0..20u32 { |
| 274 | let entries: Vec<_> = (0..5u32) |
| 275 | .map(|i| { |
| 276 | let n = t * 1000 + round * 10 + i; |
| 277 | (key(n), id(n)) |
| 278 | }) |
| 279 | .collect(); |
| 280 | index.append(&entries).unwrap(); |
| 281 | } |
| 282 | }) |
| 283 | }) |
| 284 | .collect(); |
| 285 | for thread in threads { |
| 286 | thread.join().unwrap(); |
| 287 | } |
| 288 | let path = root.join(DERIVED_DIR).join(INDEX_FILE); |
| 289 | assert_eq!(fs::metadata(&path).unwrap().len(), 8 * 20 * 5 * ENTRY_LEN); |
| 290 | let index = DerivedIndexFile::new(&root); |
| 291 | for t in 0..8u32 { |
| 292 | for round in 0..20u32 { |
| 293 | for i in 0..5u32 { |
| 294 | let n = t * 1000 + round * 10 + i; |
| 295 | assert_eq!(index.find(&key(n)).unwrap(), Some(id(n))); |
| 296 | } |
| 297 | } |
| 298 | } |
| 299 | } |
| 300 | } |