| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright (c) 2026 UtopiaIA |
| 3 | |
| 4 | //! The indexes of sealed segments, as one handle reads them. |
| 5 | //! |
| 6 | //! A sealed segment is covered by its own index, `seg/<name>.idx`, or by a |
| 7 | //! merged index, `seg/<name>.midx`, that a writer made out of several. A |
| 8 | //! handle registers an index when it lists the directory, and reads it as |
| 9 | //! lookups need it: |
| 10 | //! |
| 11 | //! - nothing of a segment's own index at first, since its name says what it |
| 12 | //! covers; its head on first use; |
| 13 | //! - the head of a merged index right away, since only its head says what it |
| 14 | //! covers; |
| 15 | //! - the entries of one fan-out bucket, the ids that share their first byte, |
| 16 | //! the first time a lookup needs that bucket, checked entry by entry. |
| 17 | //! |
| 18 | //! An index of version 1, which older versions wrote, is read and checked |
| 19 | //! whole on first use. So is nothing else: what a handle reads follows the |
| 20 | //! lookups it makes, not the size of the store. |
| 21 | //! |
| 22 | //! Damage found in an index, at any point, is worked around as it always |
| 23 | //! was: the segments it covers are scanned, and their records stand for its |
| 24 | //! entries. fsck reports the damage. |
| 25 | |
| 26 | use std::fs::{self, File}; |
| 27 | use std::io; |
| 28 | use std::path::{Path, PathBuf}; |
| 29 | use std::sync::atomic::{AtomicBool, Ordering}; |
| 30 | use std::sync::{Mutex, OnceLock, PoisonError}; |
| 31 | |
| 32 | use braid_format::ObjectId; |
| 33 | |
| 34 | use super::{Segments, segment_path}; |
| 35 | use crate::error::{Error, io_error}; |
| 36 | use crate::fsutil::read_range; |
| 37 | use crate::index::{self, Covered, HEADER_LEN, Head, Header, IndexError, Numbered}; |
| 38 | use crate::journal::{ENTRY_LEN, Entry}; |
| 39 | use crate::prefix::HexPrefix; |
| 40 | use crate::{record, scan}; |
| 41 | |
| 42 | /// What kind of index a source is, in the order lookups try them: a |
| 43 | /// segment's own indexes are the youngest. |
| 44 | #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] |
| 45 | pub(crate) enum SourceKind { |
| 46 | /// A segment's own index. |
| 47 | Own, |
| 48 | /// A sealed segment that no readable index covers: its records are |
| 49 | /// scanned. |
| 50 | Scan, |
| 51 | /// A merged index of several segments. |
| 52 | Merged, |
| 53 | } |
| 54 | |
| 55 | /// Why a lookup through an index failed. |
| 56 | #[derive(Debug)] |
| 57 | pub(crate) enum Lookup { |
| 58 | /// The index file is gone: merged into another one since the directory |
| 59 | /// was listed. Rescanning finds what replaced it. |
| 60 | Gone(Error), |
| 61 | /// Anything else. |
| 62 | Failed(Error), |
| 63 | } |
| 64 | |
| 65 | impl Lookup { |
| 66 | pub fn into_error(self) -> Error { |
| 67 | match self { |
| 68 | Lookup::Gone(err) | Lookup::Failed(err) => err, |
| 69 | } |
| 70 | } |
| 71 | } |
| 72 | |
| 73 | impl From<Error> for Lookup { |
| 74 | fn from(err: Error) -> Self { |
| 75 | Lookup::Failed(err) |
| 76 | } |
| 77 | } |
| 78 | |
| 79 | /// An index of one or more sealed segments. |
| 80 | #[derive(Debug)] |
| 81 | pub(crate) struct Source { |
| 82 | /// Its file name in `seg/`. |
| 83 | pub file: String, |
| 84 | pub kind: SourceKind, |
| 85 | /// The segments it covers, by their number in it: their names, and their |
| 86 | /// numbers in the handle's catalog once registered. |
| 87 | pub covered: Vec<(String, u32)>, |
| 88 | path: PathBuf, |
| 89 | /// Its entries, as far as they are read. |
| 90 | content: OnceLock<Content>, |
| 91 | /// Its entries made again from the records, once damage was found in it. |
| 92 | rebuilt: OnceLock<Vec<(Entry, u16)>>, |
| 93 | /// Held while the head is read or the entries are made again. |
| 94 | loading: Mutex<()>, |
| 95 | /// Set when its file turned out to be gone before it was read. |
| 96 | gone: AtomicBool, |
| 97 | } |
| 98 | |
| 99 | /// The 256 fan-out buckets of an index, each read on first use. |
| 100 | type Buckets = Box<[OnceLock<Box<[Numbered]>>]>; |
| 101 | |
| 102 | /// What a handle has of an index. |
| 103 | #[derive(Debug)] |
| 104 | enum Content { |
| 105 | /// A version 2 index: its file and head, and the buckets read so far. |
| 106 | Lazy { |
| 107 | file: File, |
| 108 | head: Head, |
| 109 | buckets: Buckets, |
| 110 | }, |
| 111 | /// Every entry, sorted by id: a version 1 index, or the index this |
| 112 | /// handle just wrote. |
| 113 | Whole(Vec<(Entry, u16)>), |
| 114 | } |
| 115 | |
| 116 | impl Source { |
| 117 | /// A segment's own index. `known` is what it covers and its entries, |
| 118 | /// when this handle just wrote it: then it is never read. |
| 119 | pub fn own(dir: &Path, name: &str, known: Option<(Covered, Vec<Entry>)>) -> Self { |
| 120 | let file = format!("{name}.idx"); |
| 121 | let source = Source { |
| 122 | path: dir.join(&file), |
| 123 | file, |
| 124 | kind: SourceKind::Own, |
| 125 | covered: vec![(name.to_owned(), 0)], |
| 126 | content: OnceLock::new(), |
| 127 | rebuilt: OnceLock::new(), |
| 128 | loading: Mutex::new(()), |
| 129 | gone: AtomicBool::new(false), |
| 130 | }; |
| 131 | if let Some((_, entries)) = known { |
| 132 | let entries = entries.into_iter().map(|entry| (entry, 0)).collect(); |
| 133 | let _ = source.content.set(Content::Whole(entries)); |
| 134 | } |
| 135 | source |
| 136 | } |
| 137 | |
| 138 | /// A sealed segment that no readable index covers, read by scanning it. |
| 139 | pub fn scan(name: &str) -> Self { |
| 140 | Source { |
| 141 | path: PathBuf::new(), |
| 142 | file: format!("{name}.seg"), |
| 143 | kind: SourceKind::Scan, |
| 144 | covered: vec![(name.to_owned(), 0)], |
| 145 | content: OnceLock::new(), |
| 146 | rebuilt: OnceLock::new(), |
| 147 | loading: Mutex::new(()), |
| 148 | gone: AtomicBool::new(false), |
| 149 | } |
| 150 | } |
| 151 | |
| 152 | /// Opens the merged index `file` in `dir` and reads its head: `None` if |
| 153 | /// it is gone, the reason if it cannot be read. A merged index a newer |
| 154 | /// version wrote is an error. |
| 155 | pub fn open_merged(dir: &Path, file: &str) -> Result<Option<Result<Self, IndexError>>, Error> { |
| 156 | let path = dir.join(file); |
| 157 | let opened = match File::open(&path) { |
| 158 | Ok(opened) => opened, |
| 159 | Err(err) if err.kind() == io::ErrorKind::NotFound => return Ok(None), |
| 160 | Err(err) => return Err(io_error("open", &path)(err)), |
| 161 | }; |
| 162 | let head = match read_head(&opened, &path).map_err(Lookup::into_error)? { |
| 163 | Ok(Some(head)) => head, |
| 164 | Ok(None) => { |
| 165 | return Ok(Some(Err(IndexError::Damaged( |
| 166 | "a merged index of version 1", |
| 167 | )))); |
| 168 | } |
| 169 | Err(IndexError::Newer(detail)) => return Err(newer(&path, detail)), |
| 170 | Err(damaged) => return Ok(Some(Err(damaged))), |
| 171 | }; |
| 172 | let source = Source { |
| 173 | covered: head |
| 174 | .covered |
| 175 | .iter() |
| 176 | .map(|segment| (segment.name.clone(), 0)) |
| 177 | .collect(), |
| 178 | content: OnceLock::new(), |
| 179 | rebuilt: OnceLock::new(), |
| 180 | loading: Mutex::new(()), |
| 181 | gone: AtomicBool::new(false), |
| 182 | path, |
| 183 | file: file.to_owned(), |
| 184 | kind: SourceKind::Merged, |
| 185 | }; |
| 186 | let _ = source.content.set(Content::Lazy { |
| 187 | file: opened, |
| 188 | head, |
| 189 | buckets: buckets(), |
| 190 | }); |
| 191 | Ok(Some(Ok(source))) |
| 192 | } |
| 193 | |
| 194 | /// Whether its file turned out to be gone before it was read: merged |
| 195 | /// into another index since it was registered. |
| 196 | pub fn is_gone(&self) -> bool { |
| 197 | self.gone.load(Ordering::Acquire) |
| 198 | } |
| 199 | |
| 200 | /// How good a source is at serving a segment it covers: a merged index |
| 201 | /// over a segment's own, and the merged index that covers more, which is |
| 202 | /// the newer, over one that covers less. |
| 203 | pub fn rank(&self) -> (u8, usize, &str) { |
| 204 | let kind = match self.kind { |
| 205 | SourceKind::Scan => 0, |
| 206 | SourceKind::Own => 1, |
| 207 | SourceKind::Merged => 2, |
| 208 | }; |
| 209 | (kind, self.covered.len(), &self.file) |
| 210 | } |
| 211 | |
| 212 | /// The entry for `id`, with the number of its segment, if this index |
| 213 | /// has one. |
| 214 | pub fn find(&self, id: &ObjectId, segments: &Segments) -> Result<Option<(Entry, u16)>, Lookup> { |
| 215 | let entries = self.bucket(id.as_bytes()[0], segments)?; |
| 216 | Ok(entries |
| 217 | .binary_search_by(|(entry, _)| entry.id.cmp(id)) |
| 218 | .ok() |
| 219 | .map(|at| entries[at])) |
| 220 | } |
| 221 | |
| 222 | /// The entries whose ids start with `prefix`. |
| 223 | pub fn with_prefix( |
| 224 | &self, |
| 225 | prefix: &HexPrefix, |
| 226 | segments: &Segments, |
| 227 | ) -> Result<Vec<(Entry, u16)>, Lookup> { |
| 228 | let mut out = Vec::new(); |
| 229 | for byte in prefix.first_bytes() { |
| 230 | out.extend( |
| 231 | self.bucket(byte, segments)? |
| 232 | .iter() |
| 233 | .filter(|(entry, _)| prefix.matches(&entry.id)), |
| 234 | ); |
| 235 | } |
| 236 | Ok(out) |
| 237 | } |
| 238 | |
| 239 | /// Every entry, in id order. |
| 240 | pub fn all(&self, segments: &Segments) -> Result<Vec<(Entry, u16)>, Lookup> { |
| 241 | let mut out = Vec::new(); |
| 242 | for byte in 0..=255u8 { |
| 243 | out.extend_from_slice(self.bucket(byte, segments)?); |
| 244 | } |
| 245 | Ok(out) |
| 246 | } |
| 247 | |
| 248 | /// The entries whose ids start with `byte`, sorted by id. |
| 249 | fn bucket(&self, byte: u8, segments: &Segments) -> Result<&[(Entry, u16)], Lookup> { |
| 250 | if let Some(rebuilt) = self.rebuilt.get() { |
| 251 | return Ok(slice_of(rebuilt, byte)); |
| 252 | } |
| 253 | let content = match self.content(segments)? { |
| 254 | Some(content) => content, |
| 255 | None => return self.rebuild(segments).map(|all| slice_of(all, byte)), |
| 256 | }; |
| 257 | match content { |
| 258 | Content::Whole(all) => Ok(slice_of(all, byte)), |
| 259 | Content::Lazy { |
| 260 | file, |
| 261 | head, |
| 262 | buckets, |
| 263 | } => { |
| 264 | let slot = &buckets[usize::from(byte)]; |
| 265 | if let Some(entries) = slot.get() { |
| 266 | return Ok(entries); |
| 267 | } |
| 268 | let range = head.bucket(byte); |
| 269 | let bytes = read_range( |
| 270 | file, |
| 271 | head.entry_offset(range.start), |
| 272 | (range.end - range.start) * ENTRY_LEN, |
| 273 | ); |
| 274 | let checked = match bytes { |
| 275 | Ok(bytes) => index::bucket(head, byte, &bytes), |
| 276 | Err(err) if err.kind() == io::ErrorKind::UnexpectedEof => { |
| 277 | Err(IndexError::Damaged("index file cut short")) |
| 278 | } |
| 279 | Err(err) => return Err(io_error("read", &self.path)(err).into()), |
| 280 | }; |
| 281 | match checked { |
| 282 | Ok(entries) => { |
| 283 | // Two threads may read the same bucket: one keeps it. |
| 284 | let _ = slot.set(entries.into_boxed_slice()); |
| 285 | Ok(slot.get().map_or(&[], |entries| entries)) |
| 286 | } |
| 287 | Err(IndexError::Newer(detail)) => Err(newer(&self.path, detail).into()), |
| 288 | Err(IndexError::Damaged(_)) => { |
| 289 | self.rebuild(segments).map(|all| slice_of(all, byte)) |
| 290 | } |
| 291 | } |
| 292 | } |
| 293 | } |
| 294 | } |
| 295 | |
| 296 | /// What this handle has of the index, its head read on first use. |
| 297 | /// `None` when the index cannot be used: its records are scanned |
| 298 | /// instead. |
| 299 | fn content(&self, segments: &Segments) -> Result<Option<&Content>, Lookup> { |
| 300 | if let Some(content) = self.content.get() { |
| 301 | return Ok(Some(content)); |
| 302 | } |
| 303 | if self.kind == SourceKind::Scan { |
| 304 | return Ok(None); |
| 305 | } |
| 306 | let _loading = self.loading.lock().unwrap_or_else(PoisonError::into_inner); |
| 307 | if let Some(content) = self.content.get() { |
| 308 | return Ok(Some(content)); |
| 309 | } |
| 310 | let file = match File::open(&self.path) { |
| 311 | Ok(file) => file, |
| 312 | Err(err) if err.kind() == io::ErrorKind::NotFound => { |
| 313 | self.gone.store(true, Ordering::Release); |
| 314 | return Err(Lookup::Gone(io_error("open", &self.path)(err))); |
| 315 | } |
| 316 | Err(err) => return Err(io_error("open", &self.path)(err).into()), |
| 317 | }; |
| 318 | let content = match read_head(&file, &self.path)? { |
| 319 | Ok(Some(head)) |
| 320 | if head.covered.len() == 1 && head.covered[0].name == self.covered[0].0 => |
| 321 | { |
| 322 | Content::Lazy { |
| 323 | file, |
| 324 | head, |
| 325 | buckets: buckets(), |
| 326 | } |
| 327 | } |
| 328 | Ok(Some(_)) => return Ok(None), |
| 329 | Ok(None) => { |
| 330 | let bytes = fs::read(&self.path).map_err(io_error("read", &self.path))?; |
| 331 | match index::decode(&bytes, Some(&self.covered[0].0)) { |
| 332 | Ok(decoded) => { |
| 333 | // Written by a version from before storage versions, |
| 334 | // it may hold records the store's format file does |
| 335 | // not declare. |
| 336 | let needed = decoded |
| 337 | .entries |
| 338 | .iter() |
| 339 | .map(|(entry, _)| record::storage_version(entry.codec)) |
| 340 | .max() |
| 341 | .unwrap_or(1); |
| 342 | segments.need_storage(needed)?; |
| 343 | Content::Whole(decoded.entries) |
| 344 | } |
| 345 | Err(IndexError::Newer(detail)) => { |
| 346 | return Err(newer(&self.path, detail).into()); |
| 347 | } |
| 348 | Err(IndexError::Damaged(_)) => return Ok(None), |
| 349 | } |
| 350 | } |
| 351 | Err(IndexError::Newer(detail)) => return Err(newer(&self.path, detail).into()), |
| 352 | Err(IndexError::Damaged(_)) => return Ok(None), |
| 353 | }; |
| 354 | let _ = self.content.set(content); |
| 355 | Ok(self.content.get()) |
| 356 | } |
| 357 | |
| 358 | /// Makes the entries again from the records of the covered segments, |
| 359 | /// which describe themselves: for an index found damaged, or a segment |
| 360 | /// no readable index covers. Of several copies of an object, the best |
| 361 | /// ranked wins, and the first of those. |
| 362 | fn rebuild(&self, segments: &Segments) -> Result<&[(Entry, u16)], Lookup> { |
| 363 | let _loading = self.loading.lock().unwrap_or_else(PoisonError::into_inner); |
| 364 | if let Some(rebuilt) = self.rebuilt.get() { |
| 365 | return Ok(rebuilt); |
| 366 | } |
| 367 | let mut found: Vec<(Entry, u16, usize)> = Vec::new(); |
| 368 | for (number, (name, _)) in self.covered.iter().enumerate() { |
| 369 | let path = segment_path(segments.dir(), name, "seg"); |
| 370 | let file = File::open(&path).map_err(io_error("open", &path))?; |
| 371 | let len = file.metadata().map_err(io_error("read", &path))?.len(); |
| 372 | let local = u16::try_from(number).unwrap_or(u16::MAX); |
| 373 | scan::scan(&file, len, |offset, record| { |
| 374 | let entry = Entry::new(offset, &record.header, record.crc); |
| 375 | found.push((entry, local, found.len())); |
| 376 | }) |
| 377 | .map_err(io_error("read", &path))?; |
| 378 | } |
| 379 | found.sort_by_key(|(entry, _, order)| (entry.id, record::rank(entry.codec), *order)); |
| 380 | found.dedup_by_key(|(entry, _, _)| entry.id); |
| 381 | let entries = found |
| 382 | .into_iter() |
| 383 | .map(|(entry, local, _)| (entry, local)) |
| 384 | .collect(); |
| 385 | let _ = self.rebuilt.set(entries); |
| 386 | Ok(self.rebuilt.get().map_or(&[], Vec::as_slice)) |
| 387 | } |
| 388 | } |
| 389 | |
| 390 | #[cfg(test)] |
| 391 | impl Source { |
| 392 | /// Whether its head is read, and how many of its buckets. |
| 393 | pub fn read_so_far(&self) -> (bool, usize) { |
| 394 | match self.content.get() { |
| 395 | None => (false, 0), |
| 396 | Some(Content::Whole(_)) => (true, 256), |
| 397 | Some(Content::Lazy { buckets, .. }) => ( |
| 398 | true, |
| 399 | buckets |
| 400 | .iter() |
| 401 | .filter(|bucket| bucket.get().is_some()) |
| 402 | .count(), |
| 403 | ), |
| 404 | } |
| 405 | } |
| 406 | } |
| 407 | |
| 408 | /// Reads the head of an index: `Ok(None)` for a version 1 index, which has |
| 409 | /// none of its own. |
| 410 | fn read_head(file: &File, path: &Path) -> Result<Result<Option<Head>, IndexError>, Lookup> { |
| 411 | let len = file.metadata().map_err(io_error("read", path))?.len(); |
| 412 | let read = |at: u64, n: u64| match read_range(file, at, n) { |
| 413 | Ok(bytes) => Ok(Ok(bytes)), |
| 414 | Err(err) if err.kind() == io::ErrorKind::UnexpectedEof => { |
| 415 | Ok(Err(IndexError::Damaged("index file cut short"))) |
| 416 | } |
| 417 | Err(err) => Err(Lookup::Failed(io_error("read", path)(err))), |
| 418 | }; |
| 419 | let first = match read(0, HEADER_LEN as u64)? { |
| 420 | Ok(first) => first, |
| 421 | Err(damaged) => return Ok(Err(damaged)), |
| 422 | }; |
| 423 | let segments = match index::header(&first) { |
| 424 | Ok(Header::V1) => return Ok(Ok(None)), |
| 425 | Ok(Header::V2 { segments, .. }) => segments, |
| 426 | Err(err) => return Ok(Err(err)), |
| 427 | }; |
| 428 | let bytes = match read(0, Header::head_len(segments) as u64)? { |
| 429 | Ok(bytes) => bytes, |
| 430 | Err(damaged) => return Ok(Err(damaged)), |
| 431 | }; |
| 432 | Ok(index::head(&bytes).and_then(|head| { |
| 433 | if head.file_len() == len { |
| 434 | Ok(Some(head)) |
| 435 | } else { |
| 436 | Err(IndexError::Damaged( |
| 437 | "index length does not match its entry count", |
| 438 | )) |
| 439 | } |
| 440 | })) |
| 441 | } |
| 442 | |
| 443 | /// Empty slots for the 256 buckets of an index. |
| 444 | fn buckets() -> Buckets { |
| 445 | (0..256).map(|_| OnceLock::new()).collect() |
| 446 | } |
| 447 | |
| 448 | /// The entries of `all`, sorted by id, whose ids start with `byte`. |
| 449 | fn slice_of(all: &[(Entry, u16)], byte: u8) -> &[(Entry, u16)] { |
| 450 | let start = all.partition_point(|(entry, _)| entry.id.as_bytes()[0] < byte); |
| 451 | let end = all.partition_point(|(entry, _)| entry.id.as_bytes()[0] <= byte); |
| 452 | &all[start..end] |
| 453 | } |
| 454 | |
| 455 | /// The error for an index a newer version of braid wrote. |
| 456 | fn newer(path: &Path, detail: &str) -> Error { |
| 457 | Error::NewerStore { |
| 458 | path: path.to_path_buf(), |
| 459 | detail: format!("it holds {detail}"), |
| 460 | } |
| 461 | } |