Skip to main content

artifactize_core/monitor/
loader.rs

1//! One in-flight snapshot job, isolated from UI navigation. Generation checks discard stale
2//! scopes/pages; state hints coalesce in the driver, and a read reads again what they named.
3//!
4//! [`Loader`] is the UI-agnostic seam: the terminal monitor and the desktop app both read
5//! their catalog, Runs page and selected Run through it.
6use super::{Scope, catalog, model};
7use crate::{
8    changes::Changed,
9    store::{self, RunSummary, reader::Reader},
10    types::RunId,
11};
12use std::{path::PathBuf, sync::Arc};
13use time::OffsetDateTime;
14
15/// Which Runs page of which scope a snapshot reads, and the Run it opens.
16#[derive(Debug, Clone, PartialEq, Eq)]
17pub struct Page {
18    pub scope: Scope,
19    /// The selected Run; `None` opens the first (or, with `tail`, the last) Run of the page.
20    pub open: Option<RunId>,
21    pub offset: u32,
22    pub tail: bool,
23    pub limit: u32,
24}
25
26/// Where the page of older Runs starts, when the page shown (`shown` Runs of `limit`) is full.
27pub fn older_offset(offset: u32, limit: u32, shown: u32) -> Option<u32> {
28    (shown >= limit).then(|| offset.saturating_add(limit))
29}
30
31/// Where the page of newer Runs starts, when this one is not the first.
32pub fn newer_offset(offset: u32, limit: u32) -> Option<u32> {
33    (offset > 0).then(|| offset.saturating_sub(limit))
34}
35
36/// The monitor's page plus what tells an obsolete job from a current one.
37#[derive(Debug, Clone, PartialEq, Eq)]
38pub struct Selection {
39    pub state: PathBuf,
40    pub page: Page,
41    pub revision: u64,
42}
43
44/// Everything one snapshot read needs; the caller keeps the catalog between reads.
45pub struct Input {
46    pub state: PathBuf,
47    /// cwd, `--repo` or `--all` (`None`): only the first selection.
48    pub initial: Option<PathBuf>,
49    pub catalog: catalog::Catalog,
50    /// False before the first accepted snapshot, which picks the initial scope.
51    pub initialized: bool,
52    pub page: Page,
53    /// Read the database catalog and the shown Run afresh; Git discovery stays cached until
54    /// [`Loader::rescan`].
55    pub full: bool,
56    /// The Run the caller already shows; it is read again only when a hint named it.
57    pub displayed: Option<RunId>,
58    /// What the change hints since the last read named.
59    pub changed: Changed,
60    /// The page the caller already shows, reused while the database is unchanged.
61    pub runs: Option<Vec<RunSummary>>,
62}
63
64/// Where a snapshot was read from: the state identity and the database file.
65#[derive(Debug, Clone, Default, PartialEq, Eq)]
66pub struct Origin {
67    identity: Option<crate::types::StateId>,
68    database: Option<crate::platform::FileIdentity>,
69}
70impl Origin {
71    /// The origin of a snapshot read from the state `identity` in the database file `database`.
72    pub(crate) fn new(
73        identity: Option<crate::types::StateId>,
74        database: Option<crate::platform::FileIdentity>,
75    ) -> Self {
76        Self { identity, database }
77    }
78    /// The state was replaced since `previous` was read: Details, drafts and sessions
79    /// of the old state no longer apply.
80    pub fn replaces(&self, previous: &Self) -> bool {
81        previous.database.is_some() && previous.database != self.database
82            || previous.identity.is_some() && previous.identity != self.identity
83    }
84    pub fn identity(&self) -> Option<&crate::types::StateId> {
85        self.identity.as_ref()
86    }
87    /// The state's origin as it stands, read without a snapshot: its database file, then its
88    /// identity. A UI that keeps work outside snapshots (open reviews, drafts, claims taken)
89    /// compares it with [`Origin::replaces`] as the monitor compares snapshots.
90    pub fn read(state: &std::path::Path) -> Result<Self, String> {
91        let path = state.join(store::DATABASE);
92        let database =
93            match crate::platform::open_no_follow(std::fs::File::options().read(true), &path) {
94                Ok(file) => Some(crate::platform::file_identity(&file).map_err(|e| e.to_string())?),
95                Err(error) if error.kind() == std::io::ErrorKind::NotFound => None,
96                Err(error) => return Err(error.to_string()),
97            };
98        Ok(Self {
99            identity: store::read_state_id(state)?,
100            database,
101        })
102    }
103}
104
105/// One consistent read: the catalog, the scope's Runs page and the selected Run with its tree.
106pub struct Snapshot {
107    pub origin: Origin,
108    pub catalog: catalog::Catalog,
109    pub scope: Scope,
110    pub runs: Vec<RunSummary>,
111    pub selected_id: Option<RunId>,
112    /// The selected Run when it was read again: its requests, projected tree and a share in its
113    /// memory, kept after the rest so the memory goes back once nothing shows the Run.
114    pub selected: Option<super::live::Opened>,
115}
116
117/// A persistent, read-only snapshot worker with its caches. Call [`Loader::load`] on a
118/// blocking thread; it never writes.
119#[derive(Default)]
120pub struct Loader {
121    reader: Reader,
122    /// The catalog is supplied by the caller, so reset invalidates its Git caches on load.
123    reset_git: bool,
124}
125impl Loader {
126    pub fn load(&mut self, mut input: Input) -> Result<Snapshot, String> {
127        if self.reset_git {
128            input.catalog.reset_git();
129        }
130        let result = load(&mut self.reader, input);
131        if result.is_ok() {
132            self.reset_git = false;
133        }
134        result
135    }
136    /// Ask Git again on the next load. The state is read by queries, which keep nothing that a
137    /// change could make wrong.
138    pub fn rescan(&mut self) {
139        self.reset_git = true;
140    }
141}
142
143pub struct Completed {
144    pub selection: Selection,
145    pub loader: Loader,
146    pub result: Result<Snapshot, String>,
147    /// The SELECT statements the read ran.
148    #[cfg(any(test, feature = "test-support"))]
149    pub queries: Vec<String>,
150}
151impl Completed {
152    /// Read the snapshot of `input` with `loader`, keeping what the caller needs to apply it.
153    pub fn run(selection: Selection, mut loader: Loader, input: Input) -> Self {
154        #[cfg(any(test, feature = "test-support"))]
155        loader.traced_statements();
156        let result = loader.load(input);
157        #[cfg(any(test, feature = "test-support"))]
158        let queries = loader.traced_statements();
159        Self {
160            selection,
161            loader,
162            result,
163            #[cfg(any(test, feature = "test-support"))]
164            queries,
165        }
166    }
167}
168
169fn load(reader: &mut Reader, input: Input) -> Result<Snapshot, String> {
170    let mut catalog = input.catalog;
171    let mut scope = input.page.scope.clone();
172    // Empty state is a normal baseline. File safety checks still run on the worker.
173    if !input
174        .state
175        .join(store::DATABASE)
176        .try_exists()
177        .map_err(|error| error.to_string())?
178    {
179        store::check_probe_files(&input.state)?;
180        catalog.update(&[], input.initial.as_deref());
181        if !input.initialized {
182            scope = catalog.initial(input.initial.as_deref());
183        }
184        reader.reset();
185        return Ok(Snapshot {
186            origin: Origin::default(),
187            catalog,
188            scope,
189            runs: Vec::new(),
190            selected_id: None,
191            selected: None,
192        });
193    }
194    let saved = reader.snapshot_optional(&input.state, |db, cache, state| {
195        let reuse_page = input.runs.is_some()
196            && !input.full
197            && input.initialized
198            && cache.has_catalog()
199            && !cache.changed();
200        if input.initialized {
201            catalog.selected = Some(scope.clone());
202        }
203        if input.full || !input.initialized || !cache.has_catalog() || cache.changed() {
204            let facts = cache.catalog(db, state)?;
205            if input.initialized {
206                catalog.selected = Some(scope.clone());
207            }
208            catalog.update(&facts, input.initial.as_deref());
209            if !input.initialized {
210                scope = catalog.initial(input.initial.as_deref());
211                catalog.selected = Some(scope.clone());
212                catalog.update(&facts, input.initial.as_deref());
213            }
214        }
215        if !input.full && input.initialized {
216            catalog.rebuild();
217        }
218        let paths = catalog.paths(&scope);
219        let runs = if reuse_page {
220            input.runs.clone().expect("accepted same-database page")
221        } else {
222            cache.page(
223                db,
224                state,
225                paths.as_deref(),
226                input.page.limit,
227                input.page.offset,
228                input.page.open.as_ref(),
229            )?
230        };
231        let selected = input
232            .page
233            .open
234            .as_ref()
235            .and_then(|id| runs.iter().find(|run| &run.id == id))
236            .or_else(|| {
237                if input.page.tail {
238                    runs.iter().take(input.page.limit as usize).next_back()
239                } else {
240                    runs.first()
241                }
242            });
243        let selected_id = selected.map(|run| run.id.clone());
244        if selected_id.is_none() {
245            // Nothing shows a Run: the one held goes, and with its last share its memory.
246            cache.close();
247        }
248        let mut runs = runs;
249        // The shown Run is read again when a hint named it; another Run is read in full.
250        let shown = |id: &RunId| input.displayed.as_ref() == Some(id);
251        let changed = input.changed.or_written(cache.changed());
252        let read = selected_id
253            .as_ref()
254            .filter(|id| !shown(id) || input.full || changed.run(id) || !cache.holds(id));
255        let selected = match read {
256            Some(id) => match cache.selected(db, state, id, !shown(id)) {
257                Ok(selected) => selected.map(|(run, requests)| {
258                    let footprint = cache.footprint().expect("the Run just read is held");
259                    (run, requests, footprint)
260                }),
261                // The Run's own record does not decode: it is listed with why, and not opened.
262                Err(store::receipts::Error::Unreadable(record)) => {
263                    let run = runs.iter_mut().find(|run| &run.id == id);
264                    let run = run.expect("the selected Run is listed");
265                    if !run.unreadable.contains(&record) {
266                        run.unreadable.push(record);
267                    }
268                    None
269                }
270                Err(error) => return Err(error),
271            },
272            None => None,
273        };
274        Ok((cache.identity(db)?, runs, selected_id, selected))
275    })?;
276    let Some((identity, runs, selected_id, selected)) = saved else {
277        catalog.update(&[], input.initial.as_deref());
278        if !input.initialized {
279            scope = catalog.initial(input.initial.as_deref());
280        }
281        return Ok(Snapshot {
282            origin: Origin {
283                identity: None,
284                database: reader.database(),
285            },
286            catalog,
287            scope,
288            runs: Vec::new(),
289            selected_id: None,
290            selected: None,
291        });
292    };
293    // No read transaction survives heavy projection or live-file reads.
294    let selected = selected.map(|(run, requests, footprint)| {
295        let nodes = Arc::new(model::tree(&run, &requests, OffsetDateTime::now_utc()));
296        (run, requests, nodes, footprint)
297    });
298    reader.require_current(&input.state)?;
299    Ok(Snapshot {
300        origin: Origin {
301            identity,
302            database: reader.database(),
303        },
304        catalog,
305        scope,
306        runs,
307        selected_id,
308        selected,
309    })
310}
311
312#[cfg(any(test, feature = "test-support"))]
313mod tests;