Skip to main content

aft_store/family/
mod.rs

1//! A family's files and the protocol that publishes and reclaims them.
2//!
3//! A family is every checkout, clone and fork of one repository on this
4//! machine. Its directory holds:
5//!
6//! ```text
7//! writer.lock                         held by the one process writing the family
8//! MANIFEST-<generation>               one per published generation
9//! HORIZON-<n>                         the reclamation horizon; the newest valid one counts
10//! segments/<id>.seg                   published segments
11//! tmp/<id>.seg                        segments the current writer is still building
12//! checkouts/<checkout>/STATE-<n>      checkout states
13//! leases/<owner>.owner                one per process reading the family, locked while it lives
14//! leases/<owner>.<n>.lease            one per snapshot in use: the generation it reads
15//! incoming/<owner>.owner              an owner file before it is locked into place
16//! ```
17//!
18//! Every file is written once under a new name and never changed, renamed
19//! over or reused. The rules:
20//!
21//! - **Writing.** One process at a time holds `writer.lock` and does all
22//!   writing: it builds segments in `tmp/`, renames them into `segments/`,
23//!   writes checkout states, then publishes a new manifest naming exactly the
24//!   segments and states of the new generation. A crash before the manifest
25//!   is complete leaves the previous one current; the files it left behind
26//!   are never read and are removed later.
27//! - **Reading.** A reader reads the newest valid manifest, records a lease
28//!   naming its generation, then reads the horizon. If the horizon is above
29//!   the generation, a reclamation may be removing it, and the reader starts
30//!   again. Otherwise everything that manifest names stays on disk until the
31//!   lease is released.
32//! - **Reclaiming.** The writer computes the horizon as the lowest of the
33//!   newest generation and every live lease, writes it, checks the leases
34//!   again, and only then removes files that no manifest at or above the
35//!   horizon names. A lease that appeared below the horizon in between stops
36//!   the reclamation.
37//!
38//! A process is alive while it holds the lock on its owner file. The
39//! operating system releases that lock when the process ends however it
40//! ends, so a lease never outlives its process, and a reused process id
41//! means nothing.
42
43mod disk;
44mod lease;
45mod manifest;
46pub(crate) mod record;
47mod snapshot;
48pub mod workspace;
49mod writer;
50
51#[cfg(test)]
52mod model;
53#[cfg(test)]
54mod tests;
55
56use std::fs::OpenOptions;
57use std::io;
58use std::path::{Path, PathBuf};
59use std::sync::{Arc, Mutex};
60
61pub use disk::{DiskUsage, DiskUsageStop, measure_disk_usage};
62pub use manifest::{Manifest, SegmentEntry, StateRef};
63pub use snapshot::Snapshot;
64pub use writer::{
65    BuildScratch, PendingSegment, Publication, ReclaimOutcome, ReclaimReport, Reclaimed,
66    ScratchClaim, ScratchDir, WriteSession, reclaim_dead_workspaces,
67};
68
69use crate::ids::{CheckoutId, FamilyId, Generation, SegmentId};
70use crate::segment::SegmentError;
71use lease::Owner;
72use record::{Kind, RecordError};
73
74/// A failure in a family's files, naming the file.
75#[derive(Debug, thiserror::Error)]
76pub enum FamilyError {
77    #[error("{}: {source}", path.display())]
78    Io {
79        path: PathBuf,
80        #[source]
81        source: io::Error,
82    },
83    /// A record written by an older format version or for another family.
84    #[error("{}: {reason}", path.display())]
85    Foreign { path: PathBuf, reason: String },
86    /// A file a manifest names is missing or fails its checks.
87    #[error("{}: {reason}", path.display())]
88    Damaged { path: PathBuf, reason: String },
89    /// A record or segment a newer build wrote, in a format version above
90    /// the highest this build reads. Unlike every other file this build
91    /// cannot use, it is refused: never read past its version, treated as
92    /// absent, rebuilt over, reclaimed or replaced. Rolling back to an older
93    /// build must not destroy what the newer one wrote.
94    #[error(transparent)]
95    NewerFormat(NewerFormat),
96    /// A segment failure. A segment in a newer format version is reported
97    /// as [`Self::NewerFormat`] instead, never as this.
98    #[error(transparent)]
99    Segment(SegmentError),
100    #[error(
101        "no snapshot after {0} tries: each generation read was reclaimed before its lease took hold"
102    )]
103    SnapshotRetries(u32),
104    #[error(
105        "this write session failed while publishing and cannot publish again; start a new session"
106    )]
107    Poisoned,
108    #[error("{0}")]
109    Misuse(&'static str),
110    /// Another live build holds the checkout's `checkout.lock`: the work
111    /// can be tried again once it ends.
112    #[error("{0}")]
113    CheckoutBusy(&'static str),
114}
115
116impl FamilyError {
117    /// True when a file cannot be used as it stands: an older build's format
118    /// version wrote it, or its bytes failed their checks. A reader treats
119    /// such a file as absent, and what it held is built again. An I/O
120    /// failure is not one: the file may read fine next time. Neither is a
121    /// file in a newer format version ([`Self::newer_format`]): it is
122    /// refused, and nothing is built in its place.
123    ///
124    /// A segment with a required section this build does not know, at the
125    /// segment format version it reads, counts as unusable like a damaged
126    /// one. No build of ours writes such a segment: one that adds or changes
127    /// a required section raises the segment format version too (see
128    /// [`crate::segment::FORMAT_VERSION`]), so an older build refuses it by
129    /// that version instead.
130    #[must_use]
131    pub fn is_unusable_file(&self) -> bool {
132        match self {
133            Self::Foreign { .. } | Self::Damaged { .. } => true,
134            Self::Segment(error) => {
135                error.is_corruption()
136                    || match error.kind() {
137                        crate::segment::ErrorKind::UnsupportedVersion { found, supported } => {
138                            found < supported
139                        }
140                        crate::segment::ErrorKind::UnknownRequiredSection { .. }
141                        | crate::segment::ErrorKind::NotASegment => true,
142                        _ => false,
143                    }
144            }
145            _ => false,
146        }
147    }
148
149    /// The refusal, when a newer build wrote the file in a format version
150    /// above the highest this build reads.
151    #[must_use]
152    pub fn newer_format(&self) -> Option<&NewerFormat> {
153        match self {
154            Self::NewerFormat(refusal) => Some(refusal),
155            _ => None,
156        }
157    }
158
159    fn io(path: &Path) -> impl FnOnce(io::Error) -> Self + '_ {
160        move |source| Self::Io {
161            path: path.to_path_buf(),
162            source,
163        }
164    }
165
166    fn record(path: &Path, error: RecordError) -> Self {
167        match error {
168            RecordError::Io(source) => Self::Io {
169                path: path.to_path_buf(),
170                source,
171            },
172            RecordError::Invalid(reason) => Self::Damaged {
173                path: path.to_path_buf(),
174                reason: format!("the record's bytes do not check ({reason})"),
175            },
176            RecordError::UnsupportedVersion { found, supported }
177            | RecordError::NewerPayload { found, supported }
178                if found > supported =>
179            {
180                Self::NewerFormat(NewerFormat {
181                    path: path.to_path_buf(),
182                    file: FileKind::Record,
183                    found,
184                    supported,
185                })
186            }
187            foreign => Self::Foreign {
188                path: path.to_path_buf(),
189                reason: foreign.to_string(),
190            },
191        }
192    }
193}
194
195impl From<SegmentError> for FamilyError {
196    fn from(error: SegmentError) -> Self {
197        match NewerFormat::of_segment(&error) {
198            Some(refusal) => Self::NewerFormat(refusal),
199            None => Self::Segment(error),
200        }
201    }
202}
203
204/// Which kind of family file a [`NewerFormat`] refusal names.
205#[derive(Clone, Copy, Debug, PartialEq, Eq)]
206pub enum FileKind {
207    /// A manifest, horizon, checkout state or lease record.
208    Record,
209    /// A segment.
210    Segment,
211}
212
213/// A family file that a newer build wrote, in a format version above the
214/// highest this build reads (see [`FamilyError::NewerFormat`]). For a
215/// record, the version is the record's own or, for a checkout state, that
216/// of the state layout its payload holds.
217#[derive(Clone, Debug, PartialEq, Eq)]
218pub struct NewerFormat {
219    pub path: PathBuf,
220    pub file: FileKind,
221    /// The format version the file names.
222    pub found: u16,
223    /// The highest format version of its kind this build reads.
224    pub supported: u16,
225}
226
227impl NewerFormat {
228    /// The refusal a segment error carries, when the segment names a format
229    /// version above the one this build reads.
230    #[must_use]
231    pub fn of_segment(error: &SegmentError) -> Option<Self> {
232        match *error.kind() {
233            crate::segment::ErrorKind::UnsupportedVersion { found, supported }
234                if found > supported =>
235            {
236                Some(Self {
237                    path: error.path().to_path_buf(),
238                    file: FileKind::Segment,
239                    found,
240                    supported,
241                })
242            }
243            _ => None,
244        }
245    }
246}
247
248impl std::fmt::Display for NewerFormat {
249    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
250        // A record's refusal names either its own format version or that of
251        // the layout its payload holds, so it says only "format version".
252        let kind = match self.file {
253            FileKind::Record => "",
254            FileKind::Segment => "segment ",
255        };
256        write!(
257            f,
258            "{}: {kind}format version {} is not supported; this build reads version {}",
259            self.path.display(),
260            self.found,
261            self.supported
262        )
263    }
264}
265
266impl std::error::Error for NewerFormat {}
267
268/// One family's directory, opened by this process.
269#[derive(Debug)]
270pub struct Family {
271    layout: Layout,
272    id: FamilyId,
273    owner: Mutex<Option<Arc<Owner>>>,
274}
275
276impl Family {
277    /// Opens the family stored in `dir`, creating its directories if needed.
278    ///
279    /// # Errors
280    ///
281    /// When a directory cannot be created.
282    pub fn open(dir: &Path, id: FamilyId) -> Result<Self, FamilyError> {
283        let layout = Layout::new(dir);
284        for sub in [
285            layout.dir.clone(),
286            layout.segments_dir(),
287            layout.tmp_dir(),
288            layout.checkouts_dir(),
289            layout.leases_dir(),
290            layout.incoming_dir(),
291        ] {
292            std::fs::create_dir_all(&sub).map_err(FamilyError::io(&sub))?;
293        }
294        Ok(Self {
295            layout,
296            id,
297            owner: Mutex::new(None),
298        })
299    }
300
301    #[must_use]
302    pub const fn id(&self) -> FamilyId {
303        self.id
304    }
305
306    #[must_use]
307    pub fn dir(&self) -> &Path {
308        &self.layout.dir
309    }
310
311    /// Takes a consistent view of the newest generation. Everything the
312    /// snapshot's manifest names stays on disk until the snapshot is dropped.
313    ///
314    /// # Errors
315    ///
316    /// When the family's files cannot be read, the newest manifest is from
317    /// another format version or family, or reclamation kept outrunning the
318    /// lease. A manifest or horizon a newer build wrote fails it with
319    /// [`FamilyError::NewerFormat`].
320    pub fn snapshot(&self) -> Result<Snapshot, FamilyError> {
321        snapshot::take(self)
322    }
323
324    /// The newest generation a [`snapshot`](Self::snapshot) would read now,
325    /// without taking a lease on it: for a reader that keeps a snapshot and
326    /// wants to know, cheaply, whether a newer one has been published. The
327    /// answer protects nothing; read the generation's files only through a
328    /// snapshot.
329    ///
330    /// # Errors
331    ///
332    /// As [`snapshot`](Self::snapshot).
333    pub fn newest_generation(&self) -> Result<Generation, FamilyError> {
334        self.newest_manifest()
335            .map(|(manifest, _)| manifest.generation())
336    }
337
338    /// Whether the family's directory holds a manifest numbered above
339    /// `generation`, valid or not: the cheap first test for a reader that
340    /// already holds `generation`. It lists the directory and opens no
341    /// file, takes no lock and writes nothing. `false` means
342    /// [`newest_generation`](Self::newest_generation) would answer
343    /// `generation` or an older one now; `true` means it may answer a newer
344    /// one, which only it can tell, because the newer manifest may be torn.
345    ///
346    /// # Errors
347    ///
348    /// When the directory cannot be listed.
349    pub fn has_manifest_above(&self, generation: Generation) -> Result<bool, FamilyError> {
350        let dir = &self.layout.dir;
351        for entry in std::fs::read_dir(dir).map_err(FamilyError::io(dir))? {
352            let name = entry.map_err(FamilyError::io(dir))?.file_name();
353            if name
354                .to_str()
355                .and_then(|name| name.strip_prefix(MANIFEST_PREFIX))
356                .and_then(canonical_number)
357                .is_some_and(|number| number > generation.get())
358            {
359                return Ok(true);
360            }
361        }
362        Ok(false)
363    }
364
365    /// Starts writing the family, if no other process is writing it.
366    /// Returns `None` while another process holds the writer lock.
367    ///
368    /// # Errors
369    ///
370    /// When the lock file or the family's files cannot be read or cleaned,
371    /// and with [`FamilyError::NewerFormat`], before anything is removed or
372    /// written, when a newer build wrote the newest generation or a file it
373    /// names (see [`check_formats`](Self::check_formats)).
374    pub fn try_write(&self) -> Result<Option<WriteSession<'_>>, FamilyError> {
375        let path = self.layout.writer_lock();
376        let mut options = OpenOptions::new();
377        options.read(true).write(true).create(true).truncate(false);
378        #[cfg(unix)]
379        {
380            use std::os::unix::fs::OpenOptionsExt;
381            options.mode(0o600);
382        }
383        let lock = options.open(&path).map_err(FamilyError::io(&path))?;
384        match lock.try_lock() {
385            Ok(()) => WriteSession::start(self, lock).map(Some),
386            Err(std::fs::TryLockError::WouldBlock) => Ok(None),
387            Err(std::fs::TryLockError::Error(error)) => Err(FamilyError::io(&path)(error)),
388        }
389    }
390
391    /// Fails with [`FamilyError::NewerFormat`] when a newer build wrote the
392    /// newest manifest, or a segment or checkout state it names, in a format
393    /// version above the highest this build reads (for a checkout state, the
394    /// record's own version or that of the state layout its payload holds):
395    /// this build can then
396    /// neither read the family whole nor write it without harming what the
397    /// newer build wrote. Reads only each named file's header unless the
398    /// header names a newer version. A named file that cannot be read is left
399    /// to the reader that needs it, which reports why.
400    ///
401    /// # Errors
402    ///
403    /// That refusal, or a failure to read the newest manifest.
404    pub fn check_formats(&self) -> Result<(), FamilyError> {
405        let (manifest, _) = self.newest_manifest()?;
406        self.check_named_formats(&manifest)
407    }
408
409    /// The [`check_formats`](Self::check_formats) refusal for the files
410    /// `manifest` names.
411    fn check_named_formats(&self, manifest: &Manifest) -> Result<(), FamilyError> {
412        for entry in manifest.segments() {
413            if let Some(error) = crate::segment::newer_version(&self.layout.segment(entry.id)) {
414                return Err(error.into());
415            }
416        }
417        for state in manifest.checkouts() {
418            let path = self.layout.state(state.checkout, state.number);
419            if let Some(error) = record::newer_version(&path, Kind::State, self.id, state.number)
420                .or_else(|| crate::checkout::newer_state_format(&path, self.id, state.number))
421            {
422                return Err(FamilyError::record(&path, error));
423            }
424        }
425        Ok(())
426    }
427
428    /// This process's owner file in the family, created on first use.
429    fn owner(&self) -> Result<Arc<Owner>, FamilyError> {
430        let mut owner = self
431            .owner
432            .lock()
433            .unwrap_or_else(std::sync::PoisonError::into_inner);
434        if let Some(owner) = owner.as_ref() {
435            return Ok(owner.clone());
436        }
437        let created = Arc::new(Owner::create(&self.layout)?);
438        *owner = Some(created.clone());
439        Ok(created)
440    }
441
442    /// The newest manifest whose record checks, or the empty generation when
443    /// there is none. Damaged or half-written manifests are skipped; their
444    /// count is returned. A manifest from another format version or family
445    /// fails the call instead: it is not this build's to ignore.
446    fn newest_manifest(&self) -> Result<(Manifest, usize), FamilyError> {
447        for _ in 0..snapshot::MAX_TRIES {
448            if let Some(found) = self.list_newest_manifest()? {
449                return Ok(found);
450            }
451        }
452        Err(FamilyError::SnapshotRetries(snapshot::MAX_TRIES))
453    }
454
455    /// One attempt. If all listed manifests are unusable and at least one
456    /// vanished, a writer may have published a replacement and removed the
457    /// old manifest after we listed the directory.
458    fn list_newest_manifest(&self) -> Result<Option<(Manifest, usize)>, FamilyError> {
459        let mut skipped = 0;
460        let mut vanished = false;
461        let listed = numbered_desc(&self.layout.dir, MANIFEST_PREFIX)?;
462        #[cfg(test)]
463        tests::AFTER_MANIFEST_LIST.with(|slot| {
464            let callback = slot.borrow_mut().take();
465            if let Some(callback) = callback {
466                callback();
467            }
468        });
469        for (number, path) in listed {
470            match record::read(&path, Kind::Manifest, self.id, number) {
471                Ok(payload) => match Manifest::decode(Generation::new(number), &payload) {
472                    Ok(manifest) => return Ok(Some((manifest, skipped))),
473                    Err(RecordError::Invalid(_)) => skipped += 1,
474                    Err(error) => return Err(FamilyError::record(&path, error)),
475                },
476                Err(RecordError::Invalid(_)) => skipped += 1,
477                Err(RecordError::Io(error)) if error.kind() == io::ErrorKind::NotFound => {
478                    vanished = true;
479                }
480                Err(error) => return Err(FamilyError::record(&path, error)),
481            }
482        }
483        Ok((!vanished).then(|| (Manifest::empty(), skipped)))
484    }
485
486    /// The newest valid horizon, as a generation, with its file number.
487    fn newest_horizon(&self) -> Result<Option<(u64, Generation)>, FamilyError> {
488        for (number, path) in numbered_desc(&self.layout.dir, HORIZON_PREFIX)? {
489            match read_horizon(&path, self.id, number) {
490                Ok(horizon) => return Ok(Some((number, horizon))),
491                Err(RecordError::Invalid(_)) => {}
492                Err(RecordError::Io(error)) if error.kind() == io::ErrorKind::NotFound => {}
493                Err(error) => return Err(FamilyError::record(&path, error)),
494            }
495        }
496        Ok(None)
497    }
498}
499
500const MANIFEST_PREFIX: &str = "MANIFEST-";
501const HORIZON_PREFIX: &str = "HORIZON-";
502const STATE_PREFIX: &str = "STATE-";
503
504fn read_horizon(path: &Path, family: FamilyId, number: u64) -> Result<Generation, RecordError> {
505    let payload = record::read(path, Kind::Horizon, family, number)?;
506    let mut input = record::Payload::new(&payload);
507    let generation = Generation::new(input.u64()?);
508    input.finish()?;
509    Ok(generation)
510}
511
512/// Where each of a family's files lives.
513#[derive(Clone, Debug)]
514struct Layout {
515    dir: PathBuf,
516}
517
518impl Layout {
519    fn new(dir: &Path) -> Self {
520        Self {
521            dir: dir.to_path_buf(),
522        }
523    }
524
525    fn writer_lock(&self) -> PathBuf {
526        self.dir.join("writer.lock")
527    }
528
529    fn manifest(&self, generation: Generation) -> PathBuf {
530        self.dir.join(format!("{MANIFEST_PREFIX}{generation}"))
531    }
532
533    fn horizon(&self, number: u64) -> PathBuf {
534        self.dir.join(format!("{HORIZON_PREFIX}{number}"))
535    }
536
537    fn segments_dir(&self) -> PathBuf {
538        self.dir.join("segments")
539    }
540
541    fn segment(&self, id: SegmentId) -> PathBuf {
542        self.segments_dir().join(format!("{id}.seg"))
543    }
544
545    fn tmp_dir(&self) -> PathBuf {
546        self.dir.join("tmp")
547    }
548
549    fn tmp_segment(&self, id: SegmentId) -> PathBuf {
550        self.tmp_dir().join(format!("{id}.seg"))
551    }
552
553    fn checkouts_dir(&self) -> PathBuf {
554        self.dir.join("checkouts")
555    }
556
557    fn checkout_dir(&self, checkout: CheckoutId) -> PathBuf {
558        self.checkouts_dir().join(checkout.to_string())
559    }
560
561    fn state(&self, checkout: CheckoutId, number: u64) -> PathBuf {
562        self.checkout_dir(checkout)
563            .join(format!("{STATE_PREFIX}{number}"))
564    }
565
566    fn leases_dir(&self) -> PathBuf {
567        self.dir.join("leases")
568    }
569
570    fn incoming_dir(&self) -> PathBuf {
571        self.dir.join("incoming")
572    }
573}
574
575/// The entries of `dir` named `<prefix><number>`, newest first. Other names
576/// are ignored, and so is a number written with leading zeros or a sign, so
577/// each number has exactly one spelling.
578fn numbered_desc(dir: &Path, prefix: &str) -> Result<Vec<(u64, PathBuf)>, FamilyError> {
579    let mut found = Vec::new();
580    for entry in std::fs::read_dir(dir).map_err(FamilyError::io(dir))? {
581        let entry = entry.map_err(FamilyError::io(dir))?;
582        let name = entry.file_name();
583        let Some(number) = name
584            .to_str()
585            .and_then(|name| name.strip_prefix(prefix))
586            .and_then(canonical_number)
587        else {
588            continue;
589        };
590        found.push((number, entry.path()));
591    }
592    found.sort_by_key(|(number, _)| std::cmp::Reverse(*number));
593    Ok(found)
594}
595
596/// Parses a decimal number written the one way this crate writes numbers.
597fn canonical_number(text: &str) -> Option<u64> {
598    let number = text.parse::<u64>().ok()?;
599    (number.to_string() == text).then_some(number)
600}
601
602/// The names in `dir` that end with `suffix`, with that suffix removed.
603fn names_with_suffix(dir: &Path, suffix: &str) -> Result<Vec<(String, PathBuf)>, FamilyError> {
604    let mut found = Vec::new();
605    for entry in std::fs::read_dir(dir).map_err(FamilyError::io(dir))? {
606        let entry = entry.map_err(FamilyError::io(dir))?;
607        if let Some(stem) = entry
608            .file_name()
609            .to_str()
610            .and_then(|name| name.strip_suffix(suffix))
611        {
612            found.push((stem.to_string(), entry.path()));
613        }
614    }
615    Ok(found)
616}
617
618crate::heap_bytes_of_fields!(Layout { dir });
619crate::heap_bytes_none!(FileKind);
620crate::heap_bytes_of_fields!(NewerFormat {
621    path,
622    file,
623    found,
624    supported,
625});