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/// The retained graph and branch of one explicitly opened Run.
88pub struct RunReference {
89    pub origin: Origin,
90    pub opened: Option<Box<Opened>>,
91    pub branch: Option<Place>,
92}
93
94/// A persistent read-only worker with its caches.
95#[derive(Default)]
96pub struct Loader {
97    reader: Reader,
98    discovery: Discovery,
99    /// The catalog last read, kept until a hint names a change.
100    facts: Option<(Arc<Vec<CatalogRun>>, Vec<Unreadable>)>,
101}
102
103impl Loader {
104    /// Open one Run directly, without constructing a catalog or scanning other repositories.
105    pub fn open(&mut self, state: &std::path::Path, id: &RunId) -> Result<RunReference, String> {
106        let (identity, records, catalog_dirty) =
107            self.reader.snapshot(state, |db, cache, state| {
108                let catalog_dirty = cache.changed();
109                let records = match cache.selected(db, state, id, true) {
110                    Ok(Some((run, requests))) => Some((
111                        run,
112                        requests,
113                        cache.footprint().expect("the Run just read is held"),
114                    )),
115                    Ok(None) => unreachable!("a forced reading returns the Run"),
116                    Err(store::receipts::Error::Unreadable(_)) => None,
117                    Err(error) => return Err(error),
118                };
119                Ok((cache.identity(db)?, records, catalog_dirty))
120            })?;
121        if catalog_dirty {
122            self.facts = None;
123        }
124        let (opened, branch) = match records {
125            Some((run, requests, footprint)) => {
126                let branch = super::branch_for(&run.run, &mut self.discovery);
127                let nodes = Arc::new(model::tree(&run, &requests, OffsetDateTime::now_utc()));
128                (Some(Box::new((run, requests, nodes, footprint))), branch)
129            }
130            None => (None, None),
131        };
132        self.reader.require_current(state)?;
133        Ok(RunReference {
134            origin: Origin::new(identity, self.reader.database()),
135            opened,
136            branch,
137        })
138    }
139
140    pub fn load(&mut self, input: Input) -> Result<Snapshot, String> {
141        if input.rescan {
142            self.discovery.rescan();
143        }
144        let database = input.state.join(store::DATABASE);
145        if !database.try_exists().map_err(|error| error.to_string())? {
146            // Empty state is a normal baseline; its file safety checks still run here.
147            store::check_probe_files(&input.state)?;
148            self.reader.reset();
149            self.facts = None;
150            return Ok(self.empty(&input, Origin::default()));
151        }
152        let facts = &mut self.facts;
153        let saved = self
154            .reader
155            .snapshot_optional(&input.state, |db, cache, state| {
156                let changed = input.changed.or_written(cache.changed());
157                match (facts.as_mut(), &changed) {
158                    (Some((runs, unreadable)), Changed::Runs(ids)) if cache.has_catalog() => {
159                        let ids: Vec<_> = ids.iter().cloned().collect();
160                        let rows = cache.catalog_rows(db, state, &ids)?;
161                        *runs = Arc::new(merged(runs, &ids, rows.runs));
162                        unreadable.retain(|record| !ids.iter().any(|id| record.id == id.as_str()));
163                        unreadable.extend(rows.unreadable);
164                    }
165                    (Some(_), Changed::Nothing) if cache.has_catalog() => {}
166                    _ => {
167                        let runs = cache.catalog(db, state)?;
168                        *facts = Some((Arc::new(runs), cache.unreadable_runs()));
169                    }
170                }
171                let (runs, _) = facts.as_ref().expect("read above");
172                let open = input
173                    .open
174                    .as_ref()
175                    .filter(|id| runs.iter().any(|run| &run.id == *id));
176                let (open_run, unopened) = match open {
177                    None => {
178                        // With no Run selected, release the cache's share of its memory.
179                        cache.close();
180                        (OpenRun::Absent, None)
181                    }
182                    Some(id) if input.force || !cache.holds(id) || changed.run(id) => {
183                        match cache.selected(db, state, id, input.force) {
184                            Ok(Some((run, requests))) => {
185                                let footprint =
186                                    cache.footprint().expect("the Run just read is held");
187                                (OpenRun::Loaded(Box::new((run, requests, footprint))), None)
188                            }
189                            Ok(None) => (OpenRun::Unchanged, None),
190                            // The Run's definitions do not decode: it is listed with why, not opened.
191                            Err(store::receipts::Error::Unreadable(record)) => {
192                                (OpenRun::Absent, Some(record))
193                            }
194                            Err(error) => return Err(error),
195                        }
196                    }
197                    Some(_) => (OpenRun::Unchanged, None),
198                };
199                Ok((cache.identity(db)?, open_run, unopened))
200            })?;
201        let Some((identity, open_run, unopened)) = saved else {
202            self.facts = None;
203            return Ok(self.empty(&input, Origin::new(None, self.reader.database())));
204        };
205        let (runs, mut unreadable) = self.facts.clone().expect("read above");
206        unreadable.extend(unopened);
207        // No read transaction survives heavy projection or Git discovery.
208        let open_run = open_run.map_loaded(|(run, requests, footprint)| {
209            unreadable.extend(run.unreadable.iter().cloned());
210            let nodes = Arc::new(model::tree(&run, &requests, OffsetDateTime::now_utc()));
211            (run, requests, nodes, footprint)
212        });
213        let listing = branches(&runs, input.launch.as_deref(), &mut self.discovery);
214        self.reader.require_current(&input.state)?;
215        Ok(Snapshot {
216            origin: Origin::new(identity, self.reader.database()),
217            branches: listing.branches,
218            labels: listing.labels,
219            launch: listing.launch,
220            unreadable,
221            open_run,
222        })
223    }
224
225    fn empty(&mut self, input: &Input, origin: Origin) -> Snapshot {
226        let listing = branches(&[], input.launch.as_deref(), &mut self.discovery);
227        Snapshot {
228            origin,
229            branches: listing.branches,
230            labels: listing.labels,
231            launch: listing.launch,
232            unreadable: Vec::new(),
233            open_run: OpenRun::Absent,
234        }
235    }
236}
237
238/// `runs` with the rows of the Runs `ids` replaced by `rows`: a Run without a row is gone, and
239/// a new one is the newest, listed last.
240fn merged(runs: &[CatalogRun], ids: &[RunId], rows: Vec<CatalogRun>) -> Vec<CatalogRun> {
241    let mut rows: std::collections::BTreeMap<_, _> =
242        rows.into_iter().map(|run| (run.id.clone(), run)).collect();
243    let mut merged: Vec<_> = runs
244        .iter()
245        .filter_map(|run| {
246            if ids.contains(&run.id) {
247                rows.remove(&run.id)
248            } else {
249                Some(run.clone())
250            }
251        })
252        .collect();
253    merged.extend(rows.into_values());
254    merged
255}