artifactize_core/monitor/live/
loader.rs1use 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#[derive(Debug, Clone, Default)]
21pub struct Input {
22 pub state: PathBuf,
23 pub launch: Option<PathBuf>,
25 pub open: Option<RunId>,
27 pub force: bool,
29 pub rescan: bool,
31 pub changed: Changed,
33}
34
35pub type Opened = (RunView, Vec<RequestView>, Arc<Vec<Node>>, Footprint);
38
39pub enum OpenRun<T = Opened> {
41 Absent,
43 Unchanged,
45 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
59pub struct Snapshot<T = Opened> {
61 pub origin: Origin,
62 pub branches: Vec<Branch>,
64 pub labels: Labels,
66 pub launch: Option<Place>,
68 pub unreadable: Vec<Unreadable>,
70 pub open_run: OpenRun<T>,
71}
72
73impl<T> Snapshot<T> {
74 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#[derive(Default)]
89pub struct Loader {
90 reader: Reader,
91 discovery: Discovery,
92 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 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 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 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 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
195fn 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}