Elffuss BraidHub

utopia-ia/elffuss-braid public

main · 56.3 KiBRawPermalink
1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 UtopiaIA
3
4//! Segments: the files objects live in, and how processes share them.
5//!
6//! - **Leases.** A writer appends only to a segment it holds an exclusive,
7//! non-blocking lock on. It reuses an unlocked segment that is not sealed,
8//! or creates a new one with an exclusive create. The kernel releases the
9//! lock when the writer exits or dies, and the next writer resumes after
10//! the last record the journal describes. Nobody ever truncates a segment:
11//! other processes may be reading it.
12//! - **Journals.** After each record the lease holder appends a journal
13//! entry, so readers learn about the record without reading payloads.
14//! - **Sealing.** Once a segment passes the size threshold, or holds the
15//! most records a segment may, its holder writes its sorted index through
16//! a temporary file, flushed with the segment, and a rename, flushes the
17//! directory, and removes the journal. A sealed segment is never written
18//! again.
19//! - **Merging.** Once enough segment indexes pile up, a writer merges them
20//! into a merged index (see the `merge` submodule), so that lookups go
21//! through few indexes.
22//! - **Lookups.** Every handle keeps a map from id to location for the open
23//! segments only, built from their journals, which the record limit keeps
24//! short. Sealed segments are looked up in their indexes, which a handle
25//! reads as lookups need them (see the `sources` submodule): opening a
26//! store reads no index entry, whatever it holds. On a miss a handle
27//! reads the directory again once, since another process may have
28//! written, sealed or merged something since. When it knows several
29//! copies of one object, a lookup takes the first that serves: a delta's
30//! base must be stored whole, and a chunk must not be chunked itself.
31//! - **Durability.** [`Segments::put`] appends without flushing;
32//! [`Segments::sync`] flushes everything this handle wrote, segments and
33//! journals, in one batch. A copy written by someone else stands for a new
34//! write only together with what it needs to be read: a delta's base, a
35//! chunked blob's chunks. Those that sit in another writer's open segment
36//! are flushed by this handle's next sync too.
37//!
38//! How objects are stored whole, as deltas or in chunks, and read back, is
39//! in the `objects` submodule.
40
41mod merge;
42mod objects;
43mod sources;
44#[cfg(test)]
45mod tests;
46
47use std::collections::{BTreeMap, BTreeSet, HashMap, hash_map};
48use std::fmt;
49use std::fs::{self, File, OpenOptions, TryLockError};
50use std::io;
51use std::path::{Path, PathBuf};
52use std::sync::atomic::{AtomicBool, AtomicU32, AtomicUsize, Ordering};
53use std::sync::{Arc, Mutex, MutexGuard, OnceLock, PoisonError, RwLock};
54
55use braid_format::{Kind, ObjectId};
56
57use crate::error::{Error, io_error};
58use crate::fsutil::{
59 flush, is_random_name, open_dir, publish_file, random_name, read_range, remove_stale_temps,
60 sync_dir, write_all_at,
61};
62use crate::index::{self, Covered};
63use crate::journal::{self, ENTRY_LEN, Entry};
64use crate::prefix::HexPrefix;
65use crate::record::{self, CODEC_CHUNKED, CODEC_DELTA, CODEC_DICTIONARY, Encoded, Header};
66use crate::scan::{self, Window};
67use crate::{Durability, Options};
68use crate::{chunks, format_file};
69
70pub(crate) use objects::BaseCache;
71use sources::{Lookup, Source, SourceKind};
72
73/// Segments a handle keeps open for reading. Past this, a read opens the
74/// segment for itself.
75const MAX_CACHED_READERS: usize = 256;
76
77/// How many times a rescan lists the directory again while segments are
78/// sealed and merged under it.
79const RESCAN_PASSES: usize = 3;
80
81/// The storage version a store needs once it holds an index of version 2.
82pub(crate) const INDEX_STORAGE: u32 = 3;
83
84/// The worst copy a lookup takes, by [`record::rank`]: any this version
85/// can read.
86pub(crate) const ANY: u8 = 2;
87/// A copy that is not chunked: stored whole or as a delta.
88pub(crate) const NOT_CHUNKED: u8 = 1;
89/// A copy stored whole, as a delta's base must be.
90pub(crate) const WHOLE: u8 = 0;
91
92/// The object half of a store: the `seg/` directory.
93#[derive(Debug)]
94pub(crate) struct Segments {
95 /// The store's directory, where the `format` file is.
96 root: PathBuf,
97 dir: PathBuf,
98 segment_size: u64,
99 segment_records: u64,
100 merge_threshold: usize,
101 durability: Durability,
102 catalog: RwLock<Catalog>,
103 /// Held while rescanning the directory, so that one thread does it at a time.
104 rescanning: Mutex<()>,
105 writer: Mutex<Writer>,
106 /// Segments with a cached reader.
107 cached_readers: AtomicUsize,
108 /// Payloads of delta bases read recently.
109 bases: BaseCache,
110 /// The storage version the `format` file is known to have at least.
111 storage: AtomicU32,
112 /// Set when enough segment indexes have piled up to merge them.
113 merge_due: AtomicBool,
114}
115
116/// What this handle knows about the segments and the objects in them.
117#[derive(Debug)]
118struct Catalog {
119 segments: Vec<Segment>,
120 by_name: HashMap<String, u32>,
121 /// The best ranked copy of each object in the open segments, from their
122 /// journals and this handle's own appends.
123 open: HashMap<ObjectId, Location>,
124 /// Every index this handle has registered, by number.
125 sources: Vec<Arc<Source>>,
126 /// Their numbers, by file name.
127 by_file: HashMap<String, u32>,
128 /// The indexes lookups go through, in the order they try them.
129 active: Arc<[Active]>,
130}
131
132impl Default for Catalog {
133 fn default() -> Self {
134 Self {
135 segments: Vec::new(),
136 by_name: HashMap::new(),
137 open: HashMap::new(),
138 sources: Vec::new(),
139 by_file: HashMap::new(),
140 active: Arc::from(Vec::new()),
141 }
142 }
143}
144
145/// An index lookups go through, and which of its segments it serves: each
146/// sealed segment is served by one index, the best that covers it.
147#[derive(Debug)]
148struct Active {
149 source: Arc<Source>,
150 serves: Box<[bool]>,
151}
152
153#[derive(Debug)]
154struct Segment {
155 name: String,
156 state: SegmentState,
157 /// Opened on the first read, while fewer than [`MAX_CACHED_READERS`] are.
158 reader: OnceLock<Arc<File>>,
159}
160
161#[derive(Clone, Copy, Debug, PartialEq, Eq)]
162enum SegmentState {
163 /// Still open: its journal has been read up to this offset.
164 Open { journal_end: u64 },
165 /// Sealed, and looked up in this index. It will not change again.
166 Sealed { source: u32 },
167}
168
169/// Where a copy of an object is: its segment, and its journal or index
170/// entry.
171#[derive(Clone, Copy, Debug)]
172pub(crate) struct Location {
173 /// The segment's number in this handle's catalog.
174 pub segment: u32,
175 /// What the record holds and where it starts.
176 pub entry: Entry,
177}
178
179/// Which existing copies of an object can stand for a new write of it.
180#[derive(Clone, Copy, Debug, PartialEq, Eq)]
181pub(crate) enum Wanted {
182 /// Any copy this version can read: whole, a delta, or chunks.
183 Any,
184 /// A copy that is not chunked, as a chunk list needs.
185 NotChunked,
186}
187
188impl Wanted {
189 /// The worst rank of a copy it takes.
190 fn rank(self) -> u8 {
191 match self {
192 Wanted::Any => ANY,
193 Wanted::NotChunked => NOT_CHUNKED,
194 }
195 }
196}
197
198/// A record read from its segment: its checksum is valid, and it is the one
199/// its entry describes.
200#[derive(Debug)]
201pub(crate) struct Record {
202 bytes: Vec<u8>,
203 path: PathBuf,
204 offset: u64,
205 /// Its fixed fields.
206 pub header: Header,
207 /// The base it names, for a delta.
208 pub reference: Option<ObjectId>,
209}
210
211impl Record {
212 /// The payload as stored.
213 pub fn stored(&self) -> &[u8] {
214 let start = record::header_len(self.header.codec);
215 &self.bytes[start..start + self.header.stored_len as usize]
216 }
217
218 /// The error for a problem with this record.
219 pub fn corrupt(&self, detail: impl fmt::Display) -> Error {
220 Error::corrupt(
221 &self.path,
222 self.offset,
223 format!("object {}: {detail}", self.header.id),
224 )
225 }
226}
227
228/// The write side of this handle.
229#[derive(Debug, Default)]
230struct Writer {
231 /// The segment this handle appends to.
232 lease: Option<Lease>,
233 /// Segments this handle wrote to and gave up before flushing them.
234 unsynced: Vec<(String, Arc<File>, Arc<File>)>,
235 /// Open segments of other writers that hold objects this handle relied on
236 /// instead of writing them again. Their writers may not have flushed them
237 /// yet, so the next sync does.
238 foreign: BTreeSet<u32>,
239}
240
241impl Writer {
242 /// Gives the lease up: unlocks the segment for other writers, and keeps
243 /// its files open only to flush them at the next sync.
244 fn retire(&mut self) {
245 if let Some(lease) = self.lease.take() {
246 self.keep_unsynced(lease);
247 }
248 }
249
250 fn keep_unsynced(&mut self, lease: Lease) {
251 let _ = lease.seg.unlock();
252 self.unsynced.push((lease.name, lease.seg, lease.journal));
253 }
254}
255
256/// An open segment this handle holds the lock on.
257#[derive(Debug)]
258struct Lease {
259 segment: u32,
260 name: String,
261 /// Locked for as long as the lease lasts.
262 seg: Arc<File>,
263 journal: Arc<File>,
264 /// Where the next record goes.
265 seg_end: u64,
266 /// Where the next journal entry goes.
267 journal_end: u64,
268 /// Records its journal lists.
269 records: u64,
270 /// Whether something was written since the last sync.
271 dirty: bool,
272}
273
274/// Which of a segment's files exist.
275#[derive(Clone, Copy, Debug, Default)]
276pub(crate) struct Files {
277 pub seg: bool,
278 pub jrn: bool,
279 pub idx: bool,
280}
281
282/// What `seg/` holds.
283#[derive(Debug, Default)]
284pub(crate) struct Listing {
285 /// Segments by name, and which of their files exist.
286 pub segments: BTreeMap<String, Files>,
287 /// The names of merged indexes.
288 pub merged: BTreeSet<String>,
289}
290
291impl Segments {
292 /// Opens the segments of the store at `root`, whose `format` file says
293 /// it has storage version `storage`, and reads the journals of the open
294 /// segments; indexes are read as lookups need them. If the journals
295 /// already hold records that need a later storage version, as a writer
296 /// from before storage versions could leave, the version is raised.
297 pub fn open(root: &Path, options: &Options, storage: u32) -> Result<Self, Error> {
298 let segments = Self {
299 root: root.to_path_buf(),
300 dir: root.join("seg"),
301 segment_size: options.segment_size,
302 segment_records: options.segment_records,
303 merge_threshold: options.merge_threshold,
304 durability: options.durability,
305 catalog: RwLock::new(Catalog::default()),
306 rescanning: Mutex::new(()),
307 writer: Mutex::new(Writer::default()),
308 cached_readers: AtomicUsize::new(0),
309 bases: BaseCache::default(),
310 storage: AtomicU32::new(storage),
311 merge_due: AtomicBool::new(false),
312 };
313 segments.rescan()?;
314 let needed = segments
315 .read_catalog()
316 .open
317 .values()
318 .map(|location| record::storage_version(location.entry.codec))
319 .max()
320 .unwrap_or(1);
321 segments.need_storage(needed)?;
322 Ok(segments)
323 }
324
325 /// Makes sure the store's `format` file says it has at least storage
326 /// version `version`, raising it if needed, before anything that needs
327 /// that version is written.
328 pub(crate) fn need_storage(&self, version: u32) -> Result<(), Error> {
329 if self.storage.load(Ordering::Acquire) >= version {
330 return Ok(());
331 }
332 format_file::raise(&self.root, version, self.durability)?;
333 self.storage.fetch_max(version, Ordering::AcqRel);
334 Ok(())
335 }
336
337 /// The `seg/` directory.
338 pub fn dir(&self) -> &Path {
339 &self.dir
340 }
341
342 /// The path of one of a segment's files.
343 pub fn path(&self, name: &str, extension: &str) -> PathBuf {
344 segment_path(&self.dir, name, extension)
345 }
346
347 /// Appends the record `make` encodes for the object `id`, unless a copy
348 /// that `wanted` accepts can stand for it. `make` runs at most once,
349 /// outside the writer lock unless a copy appeared and turned out
350 /// unusable. Nothing is flushed: call [`Segments::sync`] before anything
351 /// durable refers to the object.
352 pub fn store_record(
353 &self,
354 id: &ObjectId,
355 wanted: Wanted,
356 make: impl FnOnce() -> Result<Encoded, Error>,
357 ) -> Result<(), Error> {
358 let mut make = Some(make);
359 // Encode outside the writer lock, unless a copy is already known.
360 let mut encoded = None;
361 if self.locate(id, wanted.rank())?.is_none()
362 && let Some(make) = make.take()
363 {
364 encoded = Some(make()?);
365 }
366 let mut writer = self.lock_writer();
367 if let Some(location) = self.locate(id, wanted.rank())?
368 && self.reuse(&mut writer, &location, wanted)?
369 {
370 return Ok(());
371 }
372 let encoded = match (encoded, make) {
373 (Some(encoded), _) => encoded,
374 (None, Some(make)) => make()?,
375 (None, None) => unreachable!("make runs only when nothing was encoded"),
376 };
377 self.append(&mut writer, encoded)
378 }
379
380 /// Whether a copy of `id` that `wanted` accepts can stand for a new
381 /// write of it. Like a write that finds it, this makes the next sync
382 /// flush the copy and what it needs, wherever another writer has not
383 /// flushed them yet.
384 pub fn stored(&self, id: &ObjectId, wanted: Wanted) -> Result<bool, Error> {
385 let Some(location) = self.locate(id, wanted.rank())? else {
386 return Ok(false);
387 };
388 let mut writer = self.lock_writer();
389 self.reuse(&mut writer, &location, wanted)
390 }
391
392 /// Reads and checks the record at `location`.
393 pub fn read_record(&self, location: &Location) -> Result<Record, Error> {
394 let (file, path) = self.reader(location.segment)?;
395 let entry = &location.entry;
396 let corrupt = |detail: &str| {
397 Error::corrupt(
398 &path,
399 entry.offset,
400 format!("object {}: {detail}", entry.id),
401 )
402 };
403 let header = entry.header();
404 let bytes = match read_range(&file, entry.offset, header.unpadded_len()) {
405 Ok(bytes) => bytes,
406 Err(err) if err.kind() == io::ErrorKind::UnexpectedEof => {
407 return Err(corrupt("record runs past the end of the segment"));
408 }
409 Err(err) => return Err(io_error("read", &path)(err)),
410 };
411 let checked = record::check(&bytes).map_err(corrupt)?;
412 if checked.header != header || checked.crc != entry.crc {
413 return Err(corrupt("record does not match its entry"));
414 }
415 let reference = checked.reference;
416 Ok(Record {
417 bytes,
418 path,
419 offset: entry.offset,
420 header,
421 reference,
422 })
423 }
424
425 /// The kind and size of an object, from its record's header alone: the
426 /// payload is neither read nor decompressed. The header is checked
427 /// against the object's index or journal entry, which has a checksum of
428 /// its own, so a damaged header is an error; damage to the payload only
429 /// shows on [`Segments::get`].
430 pub fn stat(&self, id: &ObjectId) -> Result<Option<(Kind, u64)>, Error> {
431 let Some(location) = self.find(id, ANY)? else {
432 return Ok(None);
433 };
434 let (file, path) = self.reader(location.segment)?;
435 let entry = &location.entry;
436 let corrupt = |detail: &str| {
437 Error::corrupt(
438 &path,
439 entry.offset,
440 format!("object {}: {detail}", entry.id),
441 )
442 };
443 let bytes = match read_range(&file, entry.offset, record::HEADER_LEN as u64) {
444 Ok(bytes) => bytes,
445 Err(err) if err.kind() == io::ErrorKind::UnexpectedEof => {
446 return Err(corrupt("record runs past the end of the segment"));
447 }
448 Err(err) => return Err(io_error("read", &path)(err)),
449 };
450 let header = record::parse_header(&bytes).map_err(corrupt)?;
451 if header != entry.header() {
452 return Err(corrupt("record does not match its entry"));
453 }
454 Ok(Some((header.kind, header.raw_len)))
455 }
456
457 /// Whether an index or a journal lists the object. The record is not read.
458 pub fn contains(&self, id: &ObjectId) -> Result<bool, Error> {
459 Ok(self.find(id, ANY)?.is_some())
460 }
461
462 /// The ids this handle knows of whose hex form starts with `prefix`,
463 /// sorted. Only the buckets of the indexes the prefix falls in are
464 /// read: see [`Segments::rescan`] for what is new.
465 pub fn ids_with_prefix(&self, prefix: &HexPrefix) -> Result<Vec<ObjectId>, Error> {
466 self.retry_gone(|| {
467 let (mut found, active) = {
468 let catalog = self.read_catalog();
469 let found: BTreeSet<ObjectId> = catalog
470 .open
471 .keys()
472 .filter(|id| prefix.matches(id))
473 .copied()
474 .collect();
475 (found, Arc::clone(&catalog.active))
476 };
477 for active in active.iter() {
478 for (entry, segment) in active.source.with_prefix(prefix, self)? {
479 if active.serves[usize::from(segment)] {
480 found.insert(entry.id);
481 }
482 }
483 }
484 Ok(found.into_iter().collect())
485 })
486 }
487
488 /// Flushes everything this handle wrote: segments and journals, in one
489 /// batch.
490 pub fn sync(&self) -> Result<(), Error> {
491 let mut writer = self.lock_writer();
492 self.sync_locked(&mut writer)
493 }
494
495 /// Makes sure the objects in `ids` are durable before something durable
496 /// refers to them: flushes this handle's writes, and the open segments of
497 /// other writers that hold any of them or what they need to be read.
498 /// Fails if a record, or a base or chunk it needs, is damaged or
499 /// missing. Objects this handle does not know about are skipped.
500 pub fn make_durable(&self, ids: &[ObjectId]) -> Result<(), Error> {
501 let mut writer = self.lock_writer();
502 for id in ids {
503 let Some(location) = self.locate(id, ANY)? else {
504 continue;
505 };
506 if !self.reuse(&mut writer, &location, Wanted::Any)? {
507 let (_, path) = self.reader(location.segment)?;
508 return Err(Error::corrupt(
509 &path,
510 location.entry.offset,
511 format!("object {id}: its record, or what it needs, is damaged or missing"),
512 ));
513 }
514 }
515 self.sync_locked(&mut writer)
516 }
517
518 /// Reads what changed in the directory since the last look: new
519 /// segments, new journal entries, segments sealed since, and indexes
520 /// merged since. Index entries are not read here: lookups read them.
521 pub fn rescan(&self) -> Result<(), Error> {
522 let _one_at_a_time = self
523 .rescanning
524 .lock()
525 .unwrap_or_else(PoisonError::into_inner);
526 // A listing may miss files that others create or remove while it is
527 // read: a segment sealed and merged meanwhile is found by listing
528 // again.
529 for pass in 1..=RESCAN_PASSES {
530 if self.rescan_once(pass == RESCAN_PASSES)? {
531 break;
532 }
533 }
534 self.note_own_indexes();
535 Ok(())
536 }
537
538 /// One look at the directory. Returns `false` when a segment that holds
539 /// records turned out to have neither a journal nor an index of its own,
540 /// and no merged index listed covers it: sealed and merged since the
541 /// listing, so that another listing finds it. On the `last` pass, such a
542 /// segment is read by scanning it if a merged index cannot be read.
543 fn rescan_once(&self, last: bool) -> Result<bool, Error> {
544 let listing = list(&self.dir)?;
545
546 // The heads of merged indexes this handle has not seen yet.
547 let mut fresh = Vec::new();
548 let mut unreadable = false;
549 for name in &listing.merged {
550 let file = format!("{name}.midx");
551 if self.read_catalog().by_file.contains_key(&file) {
552 continue;
553 }
554 match Source::open_merged(&self.dir, &file)? {
555 Some(Ok(opened)) => fresh.push(opened),
556 Some(Err(_damaged)) => unreadable = true,
557 // Merged into another one since the listing.
558 None => {}
559 }
560 }
561
562 let mut follow = Vec::new();
563 let mut settled = true;
564 {
565 let mut catalog = self.write_catalog();
566 for opened in fresh {
567 catalog.register(opened);
568 }
569 // Which merged index of those listed serves each segment.
570 let mut best: HashMap<&str, u32> = HashMap::new();
571 for name in &listing.merged {
572 let Some(&number) = catalog.by_file.get(&format!("{name}.midx")) else {
573 continue;
574 };
575 let source = &catalog.sources[number as usize];
576 for (segment, _) in &source.covered {
577 let better = best.get(segment.as_str()).is_none_or(|&other| {
578 catalog.sources[other as usize].rank() < source.rank()
579 });
580 if better {
581 best.insert(segment.as_str(), number);
582 }
583 }
584 }
585 let best: HashMap<String, u32> = best
586 .into_iter()
587 .map(|(name, number)| (name.to_owned(), number))
588 .collect();
589 let mut changed = false;
590 for (name, files) in &listing.segments {
591 if !files.seg {
592 continue;
593 }
594 // An index of its own that a lookup found gone is not
595 // there, whatever the listing says.
596 let own_gone = catalog
597 .by_file
598 .get(&format!("{name}.idx"))
599 .is_some_and(|&own| catalog.sources[own as usize].is_gone());
600 if let Some(&source) = best.get(name) {
601 changed |= catalog.seal(name, source);
602 } else if files.idx && !own_gone {
603 let source = catalog.own_source(&self.dir, name, None);
604 changed |= catalog.seal(name, source);
605 } else {
606 // Open, or new to this handle. Its journal is opened by
607 // name, whether the listing showed it or not.
608 match catalog.state(name) {
609 // Its own index is gone, merged into one that this
610 // listing missed.
611 Some(SegmentState::Sealed { source })
612 if catalog.sources[source as usize].kind == SourceKind::Own =>
613 {
614 settled &= last;
615 }
616 Some(SegmentState::Sealed { .. }) => {}
617 Some(SegmentState::Open { journal_end }) => {
618 follow.push((name.clone(), journal_end));
619 }
620 None => follow.push((name.clone(), 0)),
621 }
622 }
623 }
624 if changed {
625 catalog.refresh();
626 }
627 }
628 for (name, from) in follow {
629 if self.follow(&name, from)? {
630 continue;
631 }
632 // Neither a journal nor an index of its own: never written to,
633 // or sealed and merged since the listing.
634 let path = self.path(&name, "seg");
635 let len = match fs::metadata(&path) {
636 Ok(meta) => meta.len(),
637 Err(err) if err.kind() == io::ErrorKind::NotFound => continue,
638 Err(err) => return Err(io_error("read", &path)(err)),
639 };
640 if len == 0 {
641 continue;
642 }
643 if !last {
644 settled = false;
645 } else if unreadable {
646 // Merged into an index this handle cannot read: its records
647 // say what it holds.
648 let mut catalog = self.write_catalog();
649 let source = catalog.scan_source(&name);
650 if catalog.seal(&name, source) {
651 catalog.refresh();
652 }
653 }
654 }
655 Ok(settled)
656 }
657
658 /// Reads what is new in the journal of an open segment, from `from`.
659 /// Returns `false` if the segment has neither a journal nor an index of
660 /// its own any more.
661 fn follow(&self, name: &str, from: u64) -> Result<bool, Error> {
662 let path = self.path(name, "jrn");
663 match File::open(&path) {
664 Ok(file) => {
665 let read = journal::read(&file, from, &path)?;
666 self.apply(name, read.end, &read.entries);
667 Ok(true)
668 }
669 Err(err) if err.kind() == io::ErrorKind::NotFound => {
670 // Sealed since the listing: the index replaced the journal.
671 let idx = self.path(name, "idx");
672 if !idx.try_exists().map_err(io_error("check", &idx))? {
673 return Ok(false);
674 }
675 let mut catalog = self.write_catalog();
676 let source = catalog.own_source(&self.dir, name, None);
677 if catalog.seal(name, source) {
678 catalog.refresh();
679 }
680 Ok(true)
681 }
682 Err(err) => Err(io_error("open", &path)(err)),
683 }
684 }
685
686 /// Records the entries read from an open segment's journal, up to `end`,
687 /// and returns the segment's number.
688 fn apply(&self, name: &str, end: u64, entries: &[Entry]) -> u32 {
689 let mut catalog = self.write_catalog();
690 let segment = catalog.segment(name);
691 let SegmentState::Open { journal_end } = &mut catalog.segments[segment as usize].state
692 else {
693 // Sealed since: its index serves its objects.
694 return segment;
695 };
696 *journal_end = (*journal_end).max(end);
697 for entry in entries {
698 let location = Location {
699 segment,
700 entry: *entry,
701 };
702 match catalog.open.entry(entry.id) {
703 hash_map::Entry::Vacant(slot) => {
704 slot.insert(location);
705 }
706 // A copy stored whole beats a delta, which beats chunks.
707 hash_map::Entry::Occupied(mut slot) => {
708 if record::rank(entry.codec) < record::rank(slot.get().entry.codec) {
709 slot.insert(location);
710 }
711 }
712 }
713 }
714 segment
715 }
716
717 /// Where a copy of an object no worse than `rank` is, rescanning the
718 /// directory once on a miss.
719 pub fn find(&self, id: &ObjectId, rank: u8) -> Result<Option<Location>, Error> {
720 if let Some(location) = self.locate(id, rank)? {
721 return Ok(Some(location));
722 }
723 self.rescan()?;
724 self.locate(id, rank)
725 }
726
727 /// Where this handle knows a copy of an object no worse than `rank` to
728 /// be, by [`record::rank`], without listing the directory again: in an
729 /// open segment's journal, or in the first index that serves one. The
730 /// indexes it goes through are read as far as the lookup needs.
731 pub fn locate(&self, id: &ObjectId, rank: u8) -> Result<Option<Location>, Error> {
732 self.retry_gone(|| {
733 let active = {
734 let catalog = self.read_catalog();
735 if let Some(location) = catalog.open.get(id)
736 && record::rank(location.entry.codec) <= rank
737 {
738 return Ok(Some(*location));
739 }
740 Arc::clone(&catalog.active)
741 };
742 for active in active.iter() {
743 let Some((entry, segment)) = active.source.find(id, self)? else {
744 continue;
745 };
746 if active.serves[usize::from(segment)] && record::rank(entry.codec) <= rank {
747 return Ok(Some(Location {
748 segment: active.source.covered[usize::from(segment)].1,
749 entry,
750 }));
751 }
752 }
753 Ok(None)
754 })
755 }
756
757 /// Runs a lookup through the indexes, and again after a rescan if one of
758 /// them was merged away before this handle read it.
759 fn retry_gone<T>(&self, mut lookup: impl FnMut() -> Result<T, Lookup>) -> Result<T, Error> {
760 let mut rescans = 0;
761 loop {
762 match lookup() {
763 Ok(found) => return Ok(found),
764 Err(Lookup::Gone(_)) if rescans < RESCAN_PASSES => {
765 rescans += 1;
766 self.rescan()?;
767 }
768 Err(err) => return Err(err.into_error()),
769 }
770 }
771 }
772
773 /// The entries of every object this handle knows of, one copy each, the
774 /// best ranked, in no particular order. Every index is read whole.
775 pub fn known_entries(&self) -> Result<Vec<Entry>, Error> {
776 self.retry_gone(|| {
777 let (mut best, active) = {
778 let catalog = self.read_catalog();
779 let best: HashMap<ObjectId, Entry> = catalog
780 .open
781 .iter()
782 .map(|(id, location)| (*id, location.entry))
783 .collect();
784 (best, Arc::clone(&catalog.active))
785 };
786 for active in active.iter() {
787 for (entry, segment) in active.source.all(self)? {
788 if !active.serves[usize::from(segment)] {
789 continue;
790 }
791 match best.entry(entry.id) {
792 hash_map::Entry::Vacant(slot) => {
793 slot.insert(entry);
794 }
795 hash_map::Entry::Occupied(mut slot) => {
796 if record::rank(entry.codec) < record::rank(slot.get().codec) {
797 slot.insert(entry);
798 }
799 }
800 }
801 }
802 }
803 Ok(best.into_values().collect())
804 })
805 }
806
807 /// A handle to read a segment, and its path.
808 fn reader(&self, segment: u32) -> Result<(Arc<File>, PathBuf), Error> {
809 let catalog = self.read_catalog();
810 let segment = &catalog.segments[segment as usize];
811 let path = self.path(&segment.name, "seg");
812 if let Some(file) = segment.reader.get() {
813 return Ok((file.clone(), path));
814 }
815 let file = Arc::new(File::open(&path).map_err(io_error("open", &path))?);
816 if self.cached_readers.load(Ordering::Relaxed) < MAX_CACHED_READERS
817 && segment.reader.set(file.clone()).is_ok()
818 {
819 self.cached_readers.fetch_add(1, Ordering::Relaxed);
820 }
821 Ok((file, path))
822 }
823
824 /// Whether the copy at `location` can stand for a new write of the same
825 /// object: `wanted` accepts it, its record is there to stay, and so is
826 /// what it needs to be read. A delta needs its base stored whole; a
827 /// chunked blob needs every chunk, stored whole or as a delta, with the
828 /// size its list gives. Depth is bounded: a base is whole, and a chunk is
829 /// never chunked itself.
830 fn reuse(
831 &self,
832 writer: &mut Writer,
833 location: &Location,
834 wanted: Wanted,
835 ) -> Result<bool, Error> {
836 let codec = location.entry.codec;
837 if codec == CODEC_DICTIONARY || (wanted == Wanted::NotChunked && codec == CODEC_CHUNKED) {
838 return Ok(false);
839 }
840 if !self.record_stays(writer, location)? {
841 return Ok(false);
842 }
843 match codec {
844 CODEC_DELTA => {
845 let Some(base) = self.reference(location)? else {
846 return Ok(false);
847 };
848 match self.find(&base, WHOLE)? {
849 Some(base) => self.record_stays(writer, &base),
850 None => Ok(false),
851 }
852 }
853 CODEC_CHUNKED => {
854 let list = match self.read_record(location) {
855 Ok(list) => list,
856 Err(Error::Corrupt { .. }) => return Ok(false),
857 Err(err) => return Err(err),
858 };
859 let Ok(chunks) = chunks::decode_list(list.stored(), list.header.raw_len) else {
860 return Ok(false);
861 };
862 for chunk in chunks {
863 let usable = match self.find(&chunk.id, NOT_CHUNKED)? {
864 Some(found) => {
865 found.entry.kind == Kind::Blob
866 && found.entry.raw_len == chunk.size
867 && self.reuse(writer, &found, Wanted::NotChunked)?
868 }
869 None => false,
870 };
871 if !usable {
872 return Ok(false);
873 }
874 }
875 Ok(true)
876 }
877 _ => Ok(true),
878 }
879 }
880
881 /// The base that `location`, a delta, names in its header. `None` if
882 /// the header cannot be read or is not the one the entry describes.
883 fn reference(&self, location: &Location) -> Result<Option<ObjectId>, Error> {
884 let (file, path) = self.reader(location.segment)?;
885 let len = record::header_len(location.entry.codec);
886 let bytes = match read_range(&file, location.entry.offset, len as u64) {
887 Ok(bytes) => bytes,
888 Err(err) if err.kind() == io::ErrorKind::UnexpectedEof => return Ok(None),
889 Err(err) => return Err(io_error("read", &path)(err)),
890 };
891 match record::parse_header(&bytes) {
892 Ok(header) if header == location.entry.header() && len > record::HEADER_LEN => {
893 Ok(Some(ObjectId::from_bytes(record::array(
894 &bytes[record::HEADER_LEN..len],
895 ))))
896 }
897 _ => Ok(None),
898 }
899 }
900
901 /// Whether the base at `location` can be relied on by a new delta: it
902 /// is stored whole and there to stay. If it sits in another writer's
903 /// open segment, this handle's next sync flushes that segment.
904 pub fn rely_on_base(&self, location: &Location) -> Result<bool, Error> {
905 if !record::is_whole(location.entry.codec) {
906 return Ok(false);
907 }
908 let mut writer = self.lock_writer();
909 self.record_stays(&mut writer, location)
910 }
911
912 /// Whether the record at `location` is there to stay. A record in a
913 /// sealed segment, or in this handle's own segment, is. A record in
914 /// another writer's open segment is if it is whole; that segment is then
915 /// flushed by this handle's next sync, since its writer may not have
916 /// flushed it yet.
917 fn record_stays(&self, writer: &mut Writer, location: &Location) -> Result<bool, Error> {
918 let state = {
919 let catalog = self.read_catalog();
920 catalog.segments[location.segment as usize].state
921 };
922 let own = writer
923 .lease
924 .as_ref()
925 .is_some_and(|lease| lease.segment == location.segment);
926 if matches!(state, SegmentState::Sealed { .. }) || own {
927 return Ok(true);
928 }
929 let (file, path) = self.reader(location.segment)?;
930 let header = location.entry.header();
931 let whole = match read_range(&file, location.entry.offset, header.unpadded_len()) {
932 Ok(bytes) => matches!(
933 record::check(&bytes),
934 Ok(found) if found.header == header && found.crc == location.entry.crc
935 ),
936 Err(err) if err.kind() == io::ErrorKind::UnexpectedEof => false,
937 Err(err) => return Err(io_error("read", &path)(err)),
938 };
939 if whole {
940 writer.foreign.insert(location.segment);
941 }
942 Ok(whole)
943 }
944
945 /// Appends a record to the leased segment, taking a lease first if
946 /// needed, and seals the segment if it is now full. A record that needs
947 /// a later storage version than the store has raises it first, so that
948 /// no version of braid that does not know the record ever reads the
949 /// store.
950 fn append(&self, writer: &mut Writer, encoded: Encoded) -> Result<(), Error> {
951 self.need_storage(record::storage_version(encoded.header.codec))?;
952 if writer.lease.is_none() {
953 let lease = self.acquire(writer)?;
954 writer.lease = Some(lease);
955 }
956 let Some(lease) = writer.lease.as_mut() else {
957 unreachable!("a lease was just taken");
958 };
959 let entry = Entry::new(lease.seg_end, &encoded.header, encoded.crc);
960 let written = write_all_at(&lease.seg, &encoded.bytes, lease.seg_end)
961 .map_err(io_error("write", &self.path(&lease.name, "seg")))
962 .and_then(|()| {
963 write_all_at(&lease.journal, &entry.encode(), lease.journal_end)
964 .map_err(io_error("write", &self.path(&lease.name, "jrn")))
965 });
966 if let Err(err) = written {
967 // The write position is unknown now. Give the segment up: whoever
968 // takes it next resumes from what its files hold.
969 writer.retire();
970 return Err(err);
971 }
972 lease.seg_end += encoded.bytes.len() as u64;
973 lease.journal_end += ENTRY_LEN;
974 lease.records += 1;
975 lease.dirty = true;
976 let segment = lease.segment;
977 let journal_end = lease.journal_end;
978 let full = self.full(lease.seg_end, lease.records);
979 {
980 let mut catalog = self.write_catalog();
981 // Replaces a damaged copy elsewhere, if that is why this was written.
982 catalog.open.insert(entry.id, Location { segment, entry });
983 if let SegmentState::Open { journal_end: known } =
984 &mut catalog.segments[segment as usize].state
985 {
986 *known = (*known).max(journal_end);
987 }
988 }
989 if full && let Some(lease) = writer.lease.take() {
990 // The object is stored either way. If sealing fails, the segment
991 // stays open and full, and the next writer to take it seals it.
992 let _ = self.seal(writer, lease);
993 }
994 Ok(())
995 }
996
997 /// Whether a segment of `len` bytes and `records` records is full.
998 fn full(&self, len: u64, records: u64) -> bool {
999 len >= self.segment_size || (self.segment_records > 0 && records >= self.segment_records)
1000 }
1001
1002 /// Takes a lease: on an unlocked segment that is not sealed if there is
1003 /// one, else on a new segment.
1004 fn acquire(&self, writer: &mut Writer) -> Result<Lease, Error> {
1005 for (name, files) in list(&self.dir)?.segments {
1006 // An open segment has a journal and no index; a segment with
1007 // neither is sealed and merged, or was never written to.
1008 if !files.seg || !files.jrn || files.idx {
1009 continue;
1010 }
1011 let Some(lease) = self.try_lease(&name)? else {
1012 continue;
1013 };
1014 if self.full(lease.seg_end, lease.records) {
1015 // Full, but whoever filled it died before sealing it. If
1016 // sealing fails now, it is left for later.
1017 let _ = self.seal(writer, lease);
1018 continue;
1019 }
1020 return Ok(lease);
1021 }
1022 self.create()
1023 }
1024
1025 /// Takes a lease on an existing segment if nobody holds it and it is not
1026 /// sealed.
1027 fn try_lease(&self, name: &str) -> Result<Option<Lease>, Error> {
1028 let seg_path = self.path(name, "seg");
1029 let seg = match OpenOptions::new().read(true).write(true).open(&seg_path) {
1030 Ok(file) => file,
1031 Err(err) if err.kind() == io::ErrorKind::NotFound => return Ok(None),
1032 Err(err) => return Err(io_error("open", &seg_path)(err)),
1033 };
1034 match seg.try_lock() {
1035 Ok(()) => {}
1036 Err(TryLockError::WouldBlock) => return Ok(None),
1037 Err(TryLockError::Error(err)) => return Err(io_error("lock", &seg_path)(err)),
1038 }
1039 let idx_path = self.path(name, "idx");
1040 if idx_path
1041 .try_exists()
1042 .map_err(io_error("check", &idx_path))?
1043 {
1044 // Sealed since the listing. A journal still next to the index was
1045 // left by a sealer that died before removing it.
1046 remove_if_exists(&self.path(name, "jrn"))?;
1047 return Ok(None);
1048 }
1049 let jrn_path = self.path(name, "jrn");
1050 // Never created here: a segment without a journal is sealed and
1051 // merged since the listing, and merging removes a journal before it
1052 // removes the index.
1053 let journal = match OpenOptions::new().read(true).write(true).open(&jrn_path) {
1054 Ok(file) => file,
1055 Err(err) if err.kind() == io::ErrorKind::NotFound => return Ok(None),
1056 Err(err) => return Err(io_error("open", &jrn_path)(err)),
1057 };
1058 // A journal a newer version wrote to stops here: this version never
1059 // writes after entries it does not understand.
1060 let read = journal::read(&journal, 0, &jrn_path)?;
1061 if read.entries.is_empty() {
1062 // Whoever created these files may have died before flushing the
1063 // directory, and objects acknowledged from now on depend on
1064 // them. Once a journal lists a record, someone has.
1065 sync_dir(&self.dir, self.durability)?;
1066 }
1067 let seg_len = seg.metadata().map_err(io_error("read", &seg_path))?.len();
1068 // Never write over bytes an entry points at, even if they are gone.
1069 let claimed = read.entries.iter().map(Entry::end).max().unwrap_or(0);
1070 let seg_end = record::align(seg_len).max(claimed);
1071 let records = read.entries.len() as u64;
1072 let segment = self.apply(name, read.end, &read.entries);
1073 Ok(Some(Lease {
1074 segment,
1075 name: name.to_owned(),
1076 seg: Arc::new(seg),
1077 journal: Arc::new(journal),
1078 seg_end,
1079 journal_end: read.end,
1080 records,
1081 dirty: false,
1082 }))
1083 }
1084
1085 /// Creates a new segment and takes a lease on it.
1086 fn create(&self) -> Result<Lease, Error> {
1087 loop {
1088 let name = random_name(&self.dir)?;
1089 let seg_path = self.path(&name, "seg");
1090 let seg = match OpenOptions::new()
1091 .read(true)
1092 .write(true)
1093 .create_new(true)
1094 .open(&seg_path)
1095 {
1096 Ok(file) => file,
1097 Err(err) if err.kind() == io::ErrorKind::AlreadyExists => continue,
1098 Err(err) => return Err(io_error("create", &seg_path)(err)),
1099 };
1100 match seg.try_lock() {
1101 Ok(()) => {}
1102 // Another writer took the new segment before this one locked
1103 // it. Let it keep it.
1104 Err(TryLockError::WouldBlock) => continue,
1105 Err(TryLockError::Error(err)) => return Err(io_error("lock", &seg_path)(err)),
1106 }
1107 let jrn_path = self.path(&name, "jrn");
1108 let journal = OpenOptions::new()
1109 .read(true)
1110 .write(true)
1111 .create(true)
1112 .truncate(false)
1113 .open(&jrn_path)
1114 .map_err(io_error("create", &jrn_path))?;
1115 // Before any record: others may rely on what this segment holds
1116 // and flush it, but not its directory.
1117 sync_dir(&self.dir, self.durability)?;
1118 let segment = self.apply(&name, 0, &[]);
1119 return Ok(Lease {
1120 segment,
1121 name,
1122 seg: Arc::new(seg),
1123 journal: Arc::new(journal),
1124 seg_end: 0,
1125 journal_end: 0,
1126 records: 0,
1127 dirty: false,
1128 });
1129 }
1130 }
1131
1132 /// Seals a segment and gives its lease up.
1133 fn seal(&self, writer: &mut Writer, lease: Lease) -> Result<(), Error> {
1134 match self.write_index(&lease) {
1135 Ok(index) => {
1136 let mut catalog = self.write_catalog();
1137 let source = catalog.own_source(&self.dir, &lease.name, Some(index));
1138 if catalog.seal(&lease.name, source) {
1139 catalog.refresh();
1140 }
1141 drop(catalog);
1142 self.note_own_indexes();
1143 Ok(())
1144 }
1145 Err(err) => {
1146 writer.keep_unsynced(lease);
1147 Err(err)
1148 }
1149 }
1150 }
1151
1152 /// Writes a segment's index, flushing the segment with it, and removes
1153 /// its journal. Returns what it covers and its entries.
1154 fn write_index(&self, lease: &Lease) -> Result<(Covered, Vec<Entry>), Error> {
1155 // A version 2 index needs a store that says so first.
1156 self.need_storage(INDEX_STORAGE)?;
1157 let seg_path = self.path(&lease.name, "seg");
1158 let jrn_path = self.path(&lease.name, "jrn");
1159 let read = journal::read(&lease.journal, 0, &jrn_path)?;
1160 let seg_len = lease
1161 .seg
1162 .metadata()
1163 .map_err(io_error("read", &seg_path))?
1164 .len();
1165 // Only entries whose record is whole go in. Of several copies of an
1166 // object, the best ranked wins, and the first of those.
1167 let mut window = Window::new(&lease.seg, seg_len);
1168 let mut chosen: HashMap<ObjectId, usize> = HashMap::new();
1169 let mut entries: Vec<Entry> = Vec::with_capacity(read.entries.len());
1170 for entry in read.entries {
1171 if !scan::matches(&mut window, &entry).map_err(io_error("read", &seg_path))? {
1172 continue;
1173 }
1174 match chosen.get(&entry.id) {
1175 None => {
1176 chosen.insert(entry.id, entries.len());
1177 entries.push(entry);
1178 }
1179 Some(&at) if record::rank(entry.codec) < record::rank(entries[at].codec) => {
1180 entries[at] = entry;
1181 }
1182 Some(_) => {}
1183 }
1184 }
1185 entries.sort_by_key(|entry| entry.id);
1186 let covered = Covered {
1187 name: lease.name.clone(),
1188 len: entries.iter().map(Entry::end).fold(seg_len, u64::max),
1189 };
1190 let numbered: Vec<(Entry, u16)> = entries.iter().map(|entry| (*entry, 0)).collect();
1191 remove_stale_temps(&self.dir);
1192 // The index must never reach the disk before the records it points
1193 // at: they are flushed in one batch with it, before the rename.
1194 publish_file(
1195 &self.dir,
1196 &format!("{}.idx", lease.name),
1197 &index::encode(std::slice::from_ref(&covered), &numbered),
1198 self.durability,
1199 &[(&seg_path, &lease.seg)],
1200 )?;
1201 // The index supersedes the journal. A journal that cannot be removed
1202 // now is harmless, and the next writer to look at the segment
1203 // removes it.
1204 let _ = fs::remove_file(&jrn_path);
1205 Ok((covered, entries))
1206 }
1207
1208 fn sync_locked(&self, writer: &mut Writer) -> Result<(), Error> {
1209 let mut segments: Vec<(PathBuf, Arc<File>)> = Vec::new();
1210 let mut journals: Vec<(PathBuf, Arc<File>)> = Vec::new();
1211 if let Some(lease) = &writer.lease
1212 && lease.dirty
1213 {
1214 segments.push((self.path(&lease.name, "seg"), lease.seg.clone()));
1215 journals.push((self.path(&lease.name, "jrn"), lease.journal.clone()));
1216 }
1217 for (name, seg, journal) in &writer.unsynced {
1218 segments.push((self.path(name, "seg"), seg.clone()));
1219 journals.push((self.path(name, "jrn"), journal.clone()));
1220 }
1221 for &segment in &writer.foreign {
1222 let name = {
1223 let catalog = self.read_catalog();
1224 catalog.segments[segment as usize].name.clone()
1225 };
1226 for (extension, list) in [("seg", &mut segments), ("jrn", &mut journals)] {
1227 let path = self.path(&name, extension);
1228 match File::open(&path) {
1229 Ok(file) => list.push((path, Arc::new(file))),
1230 // Sealed since, and its journal removed: the index is durable.
1231 Err(err) if err.kind() == io::ErrorKind::NotFound => {}
1232 Err(err) => return Err(io_error("open", &path)(err)),
1233 }
1234 }
1235 }
1236 if segments.is_empty() && journals.is_empty() {
1237 return Ok(());
1238 }
1239 let dir = match self.durability {
1240 Durability::Full => open_dir(&self.dir)?,
1241 Durability::Ordered => None,
1242 };
1243 let mut batch: Vec<(&Path, &File)> = segments
1244 .iter()
1245 .chain(&journals)
1246 .map(|(path, file)| (path.as_path(), file.as_ref()))
1247 .collect();
1248 if let Some(dir) = &dir {
1249 batch.push((&self.dir, dir));
1250 }
1251 flush(&batch, self.durability)?;
1252 if let Some(lease) = &mut writer.lease {
1253 lease.dirty = false;
1254 }
1255 writer.unsynced.clear();
1256 writer.foreign.clear();
1257 Ok(())
1258 }
1259
1260 /// Notes whether enough segment indexes have piled up to merge them.
1261 fn note_own_indexes(&self) {
1262 if self.merge_threshold == 0 {
1263 return;
1264 }
1265 let own = self
1266 .read_catalog()
1267 .active
1268 .iter()
1269 .filter(|active| active.source.kind != SourceKind::Merged)
1270 .count();
1271 if own >= self.merge_threshold {
1272 self.merge_due.store(true, Ordering::Release);
1273 }
1274 }
1275
1276 fn lock_writer(&self) -> MutexGuard<'_, Writer> {
1277 match self.writer.lock() {
1278 Ok(writer) => writer,
1279 Err(poisoned) => {
1280 let mut writer = poisoned.into_inner();
1281 // A panic in the middle of an append leaves the write position
1282 // unknown: start over from the files.
1283 writer.retire();
1284 self.writer.clear_poison();
1285 writer
1286 }
1287 }
1288 }
1289
1290 fn read_catalog(&self) -> std::sync::RwLockReadGuard<'_, Catalog> {
1291 self.catalog.read().unwrap_or_else(PoisonError::into_inner)
1292 }
1293
1294 fn write_catalog(&self) -> std::sync::RwLockWriteGuard<'_, Catalog> {
1295 self.catalog.write().unwrap_or_else(PoisonError::into_inner)
1296 }
1297}
1298
1299impl Catalog {
1300 /// The number of a segment, registering it as open if it is new.
1301 fn segment(&mut self, name: &str) -> u32 {
1302 if let Some(&index) = self.by_name.get(name) {
1303 return index;
1304 }
1305 let index = u32::try_from(self.segments.len()).expect("fewer than 2^32 segments");
1306 self.segments.push(Segment {
1307 name: name.to_owned(),
1308 state: SegmentState::Open { journal_end: 0 },
1309 reader: OnceLock::new(),
1310 });
1311 self.by_name.insert(name.to_owned(), index);
1312 index
1313 }
1314
1315 /// What this handle knows of a segment's state.
1316 fn state(&self, name: &str) -> Option<SegmentState> {
1317 let &segment = self.by_name.get(name)?;
1318 Some(self.segments[segment as usize].state)
1319 }
1320
1321 /// Registers an index, numbering the segments it covers, and returns its
1322 /// number. An index already registered keeps its number.
1323 fn register(&mut self, source: Source) -> u32 {
1324 if let Some(&number) = self.by_file.get(&source.file) {
1325 return number;
1326 }
1327 let mut source = source;
1328 for (name, segment) in &mut source.covered {
1329 *segment = self.segment(name);
1330 }
1331 let number = u32::try_from(self.sources.len()).expect("fewer than 2^32 indexes");
1332 self.by_file.insert(source.file.clone(), number);
1333 self.sources.push(Arc::new(source));
1334 number
1335 }
1336
1337 /// The number of a segment's own index, registered if new. `known` is
1338 /// what it covers and its entries, when this handle just wrote it.
1339 fn own_source(&mut self, dir: &Path, name: &str, known: Option<(Covered, Vec<Entry>)>) -> u32 {
1340 let file = format!("{name}.idx");
1341 if let Some(&number) = self.by_file.get(&file) {
1342 return number;
1343 }
1344 self.register(Source::own(dir, name, known))
1345 }
1346
1347 /// The number of a source that scans a sealed segment no readable index
1348 /// covers.
1349 fn scan_source(&mut self, name: &str) -> u32 {
1350 let file = format!("{name}.seg");
1351 if let Some(&number) = self.by_file.get(&file) {
1352 return number;
1353 }
1354 self.register(Source::scan(name))
1355 }
1356
1357 /// Makes `source` serve the segment `name` if it is better than what
1358 /// serves it now, and returns whether anything changed. A segment that
1359 /// was open forgets its journal's entries: the index serves them now.
1360 fn seal(&mut self, name: &str, source: u32) -> bool {
1361 let segment = self.segment(name);
1362 let state = &mut self.segments[segment as usize].state;
1363 match *state {
1364 SegmentState::Sealed { source: current }
1365 if current == source
1366 || self.sources[current as usize].rank()
1367 >= self.sources[source as usize].rank() =>
1368 {
1369 false
1370 }
1371 SegmentState::Sealed { .. } => {
1372 *state = SegmentState::Sealed { source };
1373 true
1374 }
1375 SegmentState::Open { .. } => {
1376 *state = SegmentState::Sealed { source };
1377 self.open.retain(|_, location| location.segment != segment);
1378 true
1379 }
1380 }
1381 }
1382
1383 /// Rebuilds the list of indexes lookups go through: those that serve a
1384 /// segment, the segments' own first, which are the youngest, then the
1385 /// merged ones, smallest first.
1386 fn refresh(&mut self) {
1387 let mut active: Vec<Active> = Vec::new();
1388 for (number, source) in self.sources.iter().enumerate() {
1389 let serves: Box<[bool]> = source
1390 .covered
1391 .iter()
1392 .map(|(_, segment)| {
1393 self.segments[*segment as usize].state
1394 == SegmentState::Sealed {
1395 source: number as u32,
1396 }
1397 })
1398 .collect();
1399 if serves.iter().any(|serves| *serves) {
1400 active.push(Active {
1401 source: Arc::clone(source),
1402 serves,
1403 });
1404 }
1405 }
1406 active.sort_by(|a, b| {
1407 let key = |active: &Active| {
1408 (
1409 active.source.kind,
1410 active.source.covered.len(),
1411 active.source.file.clone(),
1412 )
1413 };
1414 key(a).cmp(&key(b))
1415 });
1416 self.active = Arc::from(active);
1417 }
1418}
1419
1420/// The error for an object whose stored form does not fit in a record.
1421pub(crate) fn too_large(size: u64) -> Error {
1422 Error::ObjectTooLarge { size }
1423}
1424
1425/// What `seg/` holds: segments and which of their files exist, and merged
1426/// indexes.
1427pub(crate) fn list(dir: &Path) -> Result<Listing, Error> {
1428 let mut out = Listing::default();
1429 for entry in fs::read_dir(dir).map_err(io_error("list", dir))? {
1430 let entry = entry.map_err(io_error("list", dir))?;
1431 let file_name = entry.file_name();
1432 let Some((stem, extension)) = file_name.to_str().and_then(|name| name.split_once('.'))
1433 else {
1434 continue;
1435 };
1436 if !is_random_name(stem) {
1437 continue;
1438 }
1439 if extension == "midx" {
1440 out.merged.insert(stem.to_owned());
1441 continue;
1442 }
1443 let files: &mut Files = out.segments.entry(stem.to_owned()).or_default();
1444 match extension {
1445 "seg" => files.seg = true,
1446 "jrn" => files.jrn = true,
1447 "idx" => files.idx = true,
1448 _ => {}
1449 }
1450 }
1451 Ok(out)
1452}
1453
1454/// The path of one of a segment's files.
1455pub(crate) fn segment_path(dir: &Path, name: &str, extension: &str) -> PathBuf {
1456 dir.join(format!("{name}.{extension}"))
1457}
1458
1459fn remove_if_exists(path: &Path) -> Result<(), Error> {
1460 match fs::remove_file(path) {
1461 Ok(()) => Ok(()),
1462 Err(err) if err.kind() == io::ErrorKind::NotFound => Ok(()),
1463 Err(err) => Err(io_error("remove", path)(err)),
1464 }
1465}