Skip to main content

artifactize_core/monitor/live/
loader.rs

1//! One consistent read of the live branches and of the Run the Main area shows. Call
2//! [`Loader::load`] on a blocking thread; it never writes. What the change hints since the last
3//! read name is read again: the whole catalog of saved Runs, or the rows of the Runs named, and
4//! the open Run when it is one of them. Git is asked again which worktrees exist on a rescan.
5use super::{Branch, Discovery, Labels, Place, branches};
6use crate::{
7    changes::Changed,
8    monitor::{Node, Origin, model},
9    platform::Footprint,
10    store::{self, CatalogRun, RequestView, RunView, Unreadable, reader::Reader},
11    types::RunId,
12};
13use std::{path::PathBuf, sync::Arc};
14use time::OffsetDateTime;
15
16#[cfg(test)]
17mod tests;
18
19/// What one read needs.
20#[derive(Debug, Clone, Default)]
21pub struct Input {
22    pub state: PathBuf,
23    /// The folder the app was started for: its branch is listed even before its first Run.
24    pub launch: Option<PathBuf>,
25    /// The Run the Main area shows, read in full.
26    pub open: Option<RunId>,
27    /// Read the open Run again even when no hint named it.
28    pub force: bool,
29    /// Ask Git again which worktrees exist.
30    pub rescan: bool,
31    /// What the change hints since the last read named.
32    pub changed: Changed,
33}
34
35/// The open Run: its view, its requests, their projected tree and a share in the Run's memory.
36/// Keep the share with the rest, after it, so the memory goes back once nothing shows the Run.
37pub type Opened = (RunView, Vec<RequestView>, Arc<Vec<Node>>, Footprint);
38
39/// What happened to the selected Run during this read.
40pub enum OpenRun<T = Opened> {
41    /// No Run was selected, or the requested Run is gone or unreadable.
42    Absent,
43    /// The already loaded Run remains current.
44    Unchanged,
45    /// The Run was read and its view is ready to show.
46    Loaded(Box<T>),
47}
48
49impl<T> OpenRun<T> {
50    fn map_loaded<U>(self, map: impl FnOnce(T) -> U) -> OpenRun<U> {
51        match self {
52            Self::Loaded(run) => OpenRun::Loaded(Box::new(map(*run))),
53            Self::Unchanged => OpenRun::Unchanged,
54            Self::Absent => OpenRun::Absent,
55        }
56    }
57}
58
59/// One consistent read.
60pub struct Snapshot<T = Opened> {
61    pub origin: Origin,
62    /// The live branches, the most recent Run first.
63    pub branches: Vec<Branch>,
64    /// The project and branch of every readable saved Run.
65    pub labels: Labels,
66    /// The branch of the folder the app was started for, when it lives.
67    pub launch: Option<Place>,
68    /// Saved Run records that cannot be read, and records of the open Run that cannot.
69    pub unreadable: Vec<Unreadable>,
70    pub open_run: OpenRun<T>,
71}
72
73impl<T> Snapshot<T> {
74    /// Project a newly loaded Run without changing the catalog or selection state.
75    pub fn map_open_run<U>(self, map: impl FnOnce(T) -> U) -> Snapshot<U> {
76        Snapshot {
77            origin: self.origin,
78            branches: self.branches,
79            labels: self.labels,
80            launch: self.launch,
81            unreadable: self.unreadable,
82            open_run: self.open_run.map_loaded(map),
83        }
84    }
85}
86
87/// A persistent read-only worker with its caches.
88#[derive(Default)]
89pub struct Loader {
90    reader: Reader,
91    discovery: Discovery,
92    /// The catalog last read, kept until a hint names a change.
93    facts: Option<(Arc<Vec<CatalogRun>>, Vec<Unreadable>)>,
94}
95
96impl Loader {
97    pub fn load(&mut self, input: Input) -> Result<Snapshot, String> {
98        if input.rescan {
99            self.discovery.rescan();
100        }
101        let database = input.state.join(store::DATABASE);
102        if !database.try_exists().map_err(|error| error.to_string())? {
103            // Empty state is a normal baseline; its file safety checks still run here.
104            store::check_probe_files(&input.state)?;
105            self.reader.reset();
106            self.facts = None;
107            return Ok(self.empty(&input, Origin::default()));
108        }
109        let facts = &mut self.facts;
110        let saved = self
111            .reader
112            .snapshot_optional(&input.state, |db, cache, state| {
113                let changed = input.changed.or_written(cache.changed());
114                match (facts.as_mut(), &changed) {
115                    (Some((runs, unreadable)), Changed::Runs(ids)) if cache.has_catalog() => {
116                        let ids: Vec<_> = ids.iter().cloned().collect();
117                        let rows = cache.catalog_rows(db, state, &ids)?;
118                        *runs = Arc::new(merged(runs, &ids, rows.runs));
119                        unreadable.retain(|record| !ids.iter().any(|id| record.id == id.as_str()));
120                        unreadable.extend(rows.unreadable);
121                    }
122                    (Some(_), Changed::Nothing) if cache.has_catalog() => {}
123                    _ => {
124                        let runs = cache.catalog(db, state)?;
125                        *facts = Some((Arc::new(runs), cache.unreadable_runs()));
126                    }
127                }
128                let (runs, _) = facts.as_ref().expect("read above");
129                let open = input
130                    .open
131                    .as_ref()
132                    .filter(|id| runs.iter().any(|run| &run.id == *id));
133                let (open_run, unopened) = match open {
134                    None => {
135                        // With no Run selected, release the cache's share of its memory.
136                        cache.close();
137                        (OpenRun::Absent, None)
138                    }
139                    Some(id) if input.force || !cache.holds(id) || changed.run(id) => {
140                        match cache.selected(db, state, id, input.force) {
141                            Ok(Some((run, requests))) => {
142                                let footprint =
143                                    cache.footprint().expect("the Run just read is held");
144                                (OpenRun::Loaded(Box::new((run, requests, footprint))), None)
145                            }
146                            Ok(None) => (OpenRun::Unchanged, None),
147                            // The Run's definitions do not decode: it is listed with why, not opened.
148                            Err(store::receipts::Error::Unreadable(record)) => {
149                                (OpenRun::Absent, Some(record))
150                            }
151                            Err(error) => return Err(error),
152                        }
153                    }
154                    Some(_) => (OpenRun::Unchanged, None),
155                };
156                Ok((cache.identity(db)?, open_run, unopened))
157            })?;
158        let Some((identity, open_run, unopened)) = saved else {
159            self.facts = None;
160            return Ok(self.empty(&input, Origin::new(None, self.reader.database())));
161        };
162        let (runs, mut unreadable) = self.facts.clone().expect("read above");
163        unreadable.extend(unopened);
164        // No read transaction survives heavy projection or Git discovery.
165        let open_run = open_run.map_loaded(|(run, requests, footprint)| {
166            unreadable.extend(run.unreadable.iter().cloned());
167            let nodes = Arc::new(model::tree(&run, &requests, OffsetDateTime::now_utc()));
168            (run, requests, nodes, footprint)
169        });
170        let listing = branches(&runs, input.launch.as_deref(), &mut self.discovery);
171        self.reader.require_current(&input.state)?;
172        Ok(Snapshot {
173            origin: Origin::new(identity, self.reader.database()),
174            branches: listing.branches,
175            labels: listing.labels,
176            launch: listing.launch,
177            unreadable,
178            open_run,
179        })
180    }
181
182    fn empty(&mut self, input: &Input, origin: Origin) -> Snapshot {
183        let listing = branches(&[], input.launch.as_deref(), &mut self.discovery);
184        Snapshot {
185            origin,
186            branches: listing.branches,
187            labels: listing.labels,
188            launch: listing.launch,
189            unreadable: Vec::new(),
190            open_run: OpenRun::Absent,
191        }
192    }
193}
194
195/// `runs` with the rows of the Runs `ids` replaced by `rows`: a Run without a row is gone, and
196/// a new one is the newest, listed last.
197fn merged(runs: &[CatalogRun], ids: &[RunId], rows: Vec<CatalogRun>) -> Vec<CatalogRun> {
198    let mut rows: std::collections::BTreeMap<_, _> =
199        rows.into_iter().map(|run| (run.id.clone(), run)).collect();
200    let mut merged: Vec<_> = runs
201        .iter()
202        .filter_map(|run| {
203            if ids.contains(&run.id) {
204                rows.remove(&run.id)
205            } else {
206                Some(run.clone())
207            }
208        })
209        .collect();
210    merged.extend(rows.into_values());
211    merged
212}