artifactize-core 0.27.2

The library behind artifactize: Artifacts, evals, reviews, the monitor and review models, and the shared operations every interface calls.
Documentation
//! One consistent read of the live branches and of the Run the Main area shows. Call
//! [`Loader::load`] on a blocking thread; it never writes. What the change hints since the last
//! read name is read again: the whole catalog of saved Runs, or the rows of the Runs named, and
//! the open Run when it is one of them. Git is asked again which worktrees exist on a rescan.
use super::{Branch, Discovery, Labels, Place, branches};
use crate::{
    changes::Changed,
    monitor::{Node, Origin, model},
    platform::Footprint,
    store::{self, CatalogRun, RequestView, RunView, Unreadable, reader::Reader},
    types::RunId,
};
use std::{path::PathBuf, sync::Arc};
use time::OffsetDateTime;

#[cfg(test)]
mod tests;

/// What one read needs.
#[derive(Debug, Clone, Default)]
pub struct Input {
    pub state: PathBuf,
    /// The folder the app was started for: its branch is listed even before its first Run.
    pub launch: Option<PathBuf>,
    /// The Run the Main area shows, read in full.
    pub open: Option<RunId>,
    /// Read the open Run again even when no hint named it.
    pub force: bool,
    /// Ask Git again which worktrees exist.
    pub rescan: bool,
    /// What the change hints since the last read named.
    pub changed: Changed,
}

/// The open Run: its view, its requests, their projected tree and a share in the Run's memory.
/// Keep the share with the rest, after it, so the memory goes back once nothing shows the Run.
pub type Opened = (RunView, Vec<RequestView>, Arc<Vec<Node>>, Footprint);

/// What happened to the selected Run during this read.
pub enum OpenRun<T = Opened> {
    /// No Run was selected, or the requested Run is gone or unreadable.
    Absent,
    /// The already loaded Run remains current.
    Unchanged,
    /// The Run was read and its view is ready to show.
    Loaded(Box<T>),
}

impl<T> OpenRun<T> {
    fn map_loaded<U>(self, map: impl FnOnce(T) -> U) -> OpenRun<U> {
        match self {
            Self::Loaded(run) => OpenRun::Loaded(Box::new(map(*run))),
            Self::Unchanged => OpenRun::Unchanged,
            Self::Absent => OpenRun::Absent,
        }
    }
}

/// One consistent read.
pub struct Snapshot<T = Opened> {
    pub origin: Origin,
    /// The live branches, the most recent Run first.
    pub branches: Vec<Branch>,
    /// The project and branch of every readable saved Run.
    pub labels: Labels,
    /// The branch of the folder the app was started for, when it lives.
    pub launch: Option<Place>,
    /// Saved Run records that cannot be read, and records of the open Run that cannot.
    pub unreadable: Vec<Unreadable>,
    pub open_run: OpenRun<T>,
}

impl<T> Snapshot<T> {
    /// Project a newly loaded Run without changing the catalog or selection state.
    pub fn map_open_run<U>(self, map: impl FnOnce(T) -> U) -> Snapshot<U> {
        Snapshot {
            origin: self.origin,
            branches: self.branches,
            labels: self.labels,
            launch: self.launch,
            unreadable: self.unreadable,
            open_run: self.open_run.map_loaded(map),
        }
    }
}

/// The retained graph and branch of one explicitly opened Run.
pub struct RunReference {
    pub origin: Origin,
    pub opened: Option<Box<Opened>>,
    pub branch: Option<Place>,
}

/// A persistent read-only worker with its caches.
#[derive(Default)]
pub struct Loader {
    reader: Reader,
    discovery: Discovery,
    /// The catalog last read, kept until a hint names a change.
    facts: Option<(Arc<Vec<CatalogRun>>, Vec<Unreadable>)>,
}

impl Loader {
    /// Open one Run directly, without constructing a catalog or scanning other repositories.
    pub fn open(&mut self, state: &std::path::Path, id: &RunId) -> Result<RunReference, String> {
        let (identity, records, catalog_dirty) =
            self.reader.snapshot(state, |db, cache, state| {
                let catalog_dirty = cache.changed();
                let records = match cache.selected(db, state, id, true) {
                    Ok(Some((run, requests))) => Some((
                        run,
                        requests,
                        cache.footprint().expect("the Run just read is held"),
                    )),
                    Ok(None) => unreachable!("a forced reading returns the Run"),
                    Err(store::receipts::Error::Unreadable(_)) => None,
                    Err(error) => return Err(error),
                };
                Ok((cache.identity(db)?, records, catalog_dirty))
            })?;
        if catalog_dirty {
            self.facts = None;
        }
        let (opened, branch) = match records {
            Some((run, requests, footprint)) => {
                let branch = super::branch_for(&run.run, &mut self.discovery);
                let nodes = Arc::new(model::tree(&run, &requests, OffsetDateTime::now_utc()));
                (Some(Box::new((run, requests, nodes, footprint))), branch)
            }
            None => (None, None),
        };
        self.reader.require_current(state)?;
        Ok(RunReference {
            origin: Origin::new(identity, self.reader.database()),
            opened,
            branch,
        })
    }

    pub fn load(&mut self, input: Input) -> Result<Snapshot, String> {
        if input.rescan {
            self.discovery.rescan();
        }
        let database = input.state.join(store::DATABASE);
        if !crate::platform::paths::target_exists(&database).map_err(|error| error.to_string())? {
            // Empty state is a normal baseline; its file safety checks still run here.
            store::check_probe_files(&input.state)?;
            self.reader.reset();
            self.facts = None;
            return Ok(self.empty(&input, Origin::default()));
        }
        let facts = &mut self.facts;
        let saved = self
            .reader
            .snapshot_optional(&input.state, |db, cache, state| {
                let changed = input.changed.or_written(cache.changed());
                match (facts.as_mut(), &changed) {
                    (Some((runs, unreadable)), Changed::Runs(ids)) if cache.has_catalog() => {
                        let ids: Vec<_> = ids.iter().cloned().collect();
                        let rows = cache.catalog_rows(db, state, &ids)?;
                        *runs = Arc::new(merged(runs, &ids, rows.runs));
                        unreadable.retain(|record| !ids.iter().any(|id| record.id == id.as_str()));
                        unreadable.extend(rows.unreadable);
                    }
                    (Some(_), Changed::Nothing) if cache.has_catalog() => {}
                    _ => {
                        let runs = cache.catalog(db, state)?;
                        *facts = Some((Arc::new(runs), cache.unreadable_runs()));
                    }
                }
                let (runs, _) = facts.as_ref().expect("read above");
                let open = input
                    .open
                    .as_ref()
                    .filter(|id| runs.iter().any(|run| &run.id == *id));
                let (open_run, unopened) = match open {
                    None => {
                        // With no Run selected, release the cache's share of its memory.
                        cache.close();
                        (OpenRun::Absent, None)
                    }
                    Some(id) if input.force || !cache.holds(id) || changed.run(id) => {
                        match cache.selected(db, state, id, input.force) {
                            Ok(Some((run, requests))) => {
                                let footprint =
                                    cache.footprint().expect("the Run just read is held");
                                (OpenRun::Loaded(Box::new((run, requests, footprint))), None)
                            }
                            Ok(None) => (OpenRun::Unchanged, None),
                            // The Run's definitions do not decode: it is listed with why, not opened.
                            Err(store::receipts::Error::Unreadable(record)) => {
                                (OpenRun::Absent, Some(record))
                            }
                            Err(error) => return Err(error),
                        }
                    }
                    Some(_) => (OpenRun::Unchanged, None),
                };
                Ok((cache.identity(db)?, open_run, unopened))
            })?;
        let Some((identity, open_run, unopened)) = saved else {
            self.facts = None;
            return Ok(self.empty(&input, Origin::new(None, self.reader.database())));
        };
        let (runs, mut unreadable) = self.facts.clone().expect("read above");
        unreadable.extend(unopened);
        // No read transaction survives heavy projection or Git discovery.
        let open_run = open_run.map_loaded(|(run, requests, footprint)| {
            unreadable.extend(run.unreadable.iter().cloned());
            let nodes = Arc::new(model::tree(&run, &requests, OffsetDateTime::now_utc()));
            (run, requests, nodes, footprint)
        });
        let listing = branches(&runs, input.launch.as_deref(), &mut self.discovery);
        self.reader.require_current(&input.state)?;
        Ok(Snapshot {
            origin: Origin::new(identity, self.reader.database()),
            branches: listing.branches,
            labels: listing.labels,
            launch: listing.launch,
            unreadable,
            open_run,
        })
    }

    fn empty(&mut self, input: &Input, origin: Origin) -> Snapshot {
        let listing = branches(&[], input.launch.as_deref(), &mut self.discovery);
        Snapshot {
            origin,
            branches: listing.branches,
            labels: listing.labels,
            launch: listing.launch,
            unreadable: Vec::new(),
            open_run: OpenRun::Absent,
        }
    }
}

/// `runs` with the rows of the Runs `ids` replaced by `rows`: a Run without a row is gone, and
/// a new one is the newest, listed last.
fn merged(runs: &[CatalogRun], ids: &[RunId], rows: Vec<CatalogRun>) -> Vec<CatalogRun> {
    let mut rows: std::collections::BTreeMap<_, _> =
        rows.into_iter().map(|run| (run.id.clone(), run)).collect();
    let mut merged: Vec<_> = runs
        .iter()
        .filter_map(|run| {
            if ids.contains(&run.id) {
                rows.remove(&run.id)
            } else {
                Some(run.clone())
            }
        })
        .collect();
    merged.extend(rows.into_values());
    merged
}