Skip to main content

schedr_master/
catalog.rs

1//! The DAG list worked out from the current parse of each root.
2//!
3//! Given the current parse of every root and the stored DAGs, [`plan`] decides what changes
4//! (see archive/PROJECT.md, DAG code delivery and DAG ID conflicts):
5//!
6//! - a DAG defined in **one place** gets the parse's version as its current one; a **new**
7//!   DAG is stored paused, and so is a removed DAG that **comes back**;
8//! - a DAG ID defined in **more than one place** (two files, two roots) is in **conflict**
9//!   and can't run;
10//! - a DAG whose file **failed to import** (or holds an invalid DAG) keeps its last good
11//!   version: a broken file doesn't remove its DAGs; a conflict whose remaining file failed
12//!   stays a conflict when the version stored is another file's (B95);
13//! - a DAG of a reported root that its current parse no longer defines is **removed**.
14
15use std::collections::{BTreeMap, BTreeSet};
16
17use schedr_db::dags::{DagChange, StoredDag};
18use schedr_model::runner::ParsedFile;
19use schedr_model::{Dag, DagId, DagLocation};
20
21#[cfg(test)]
22mod tests;
23
24/// The current parse of a root.
25#[derive(Debug, Clone, PartialEq, Eq)]
26pub struct Source {
27    /// The root's name.
28    pub root: String,
29    /// The parse's ID.
30    pub parse_id: String,
31    /// Its files (after validation).
32    pub files: Vec<ParsedFile>,
33}
34
35/// One place defining a DAG ID.
36struct Definition<'a> {
37    place: DagLocation,
38    /// The new definition and its parse; `None` for a file that failed, keeping what is stored.
39    new: Option<(&'a Dag, &'a str)>,
40}
41
42/// The changes that bring the stored DAGs in line with the sources.
43#[must_use]
44pub fn plan(sources: &[Source], stored: &[StoredDag]) -> Vec<DagChange> {
45    let by_id: BTreeMap<&DagId, &StoredDag> = stored.iter().map(|d| (&d.dag_id, d)).collect();
46    let roots: BTreeSet<&str> = sources.iter().map(|s| s.root.as_str()).collect();
47    let definitions = definitions(sources, stored);
48    let mut changes = Vec::new();
49    for (dag_id, defs) in &definitions {
50        let known = by_id.get(dag_id).copied();
51        let comes_back = known.is_none_or(|d| d.removed);
52        if defs.len() > 1 {
53            let mut places: Vec<DagLocation> = defs.iter().map(|d| d.place.clone()).collect();
54            places.sort();
55            if comes_back || known.and_then(|d| d.conflict.as_ref()) != Some(&places) {
56                changes.push(DagChange::Conflict {
57                    dag_id: (*dag_id).clone(),
58                    places,
59                    pause: comes_back,
60                });
61            }
62            continue;
63        }
64        let new = match (defs[0].new, known.and_then(|d| d.current.as_ref())) {
65            (Some((dag, parse_id)), _) => Some((dag.clone(), parse_id.to_owned())),
66            // The file failed: keep the stored version, only clearing a conflict, when it is
67            // that file's. Another place's (a file removed) stays in conflict until the file
68            // left loads: its version must not come back (B95).
69            (None, Some(current)) if known.is_some_and(|d| d.conflict.is_some()) => {
70                if current.dag.location == defs[0].place {
71                    Some((current.dag.clone(), current.parse_id.clone()))
72                } else {
73                    let left = &defs[0].place;
74                    tracing::warn!(
75                        dag_id = dag_id.as_str(),
76                        root = left.root.as_str(),
77                        path = left.path.as_str(),
78                        "DAG stays in conflict: only one file defines it now, but that file \
79                         failed to import, and the version stored is from the file removed; \
80                         it can't run until the file left imports (see its import error)"
81                    );
82                    None
83                }
84            }
85            (None, _) => None,
86        };
87        let Some((dag, parse_id)) = new else {
88            continue;
89        };
90        let unchanged = known.is_some_and(|d| {
91            !d.removed
92                && d.conflict.is_none()
93                && d.current.as_ref().is_some_and(|c| c.parse_id == parse_id)
94        });
95        if !unchanged {
96            changes.push(DagChange::Define {
97                dag: Box::new(dag),
98                parse_id,
99                pause: known.is_some_and(|d| d.removed),
100            });
101        }
102    }
103    for dag in stored.iter().filter(|d| !d.removed) {
104        if !definitions.contains_key(&dag.dag_id)
105            && places_of(dag).any(|p| roots.contains(p.root.as_str()))
106        {
107            changes.push(DagChange::Remove {
108                dag_id: dag.dag_id.clone(),
109            });
110        }
111    }
112    changes
113}
114
115/// Every place defining each DAG ID: the DAGs of the sources' files, and the stored places of
116/// files that failed (they keep what was there).
117fn definitions<'a>(
118    sources: &'a [Source],
119    stored: &'a [StoredDag],
120) -> BTreeMap<&'a DagId, Vec<Definition<'a>>> {
121    let mut found: BTreeMap<&DagId, Vec<Definition<'a>>> = BTreeMap::new();
122    let mut failed: BTreeSet<(&str, &str)> = BTreeSet::new();
123    for source in sources {
124        for file in &source.files {
125            if file.error.is_some() {
126                failed.insert((&source.root, &file.path));
127                continue;
128            }
129            for dag in &file.dags {
130                found.entry(&dag.id).or_default().push(Definition {
131                    place: dag.location.clone(),
132                    new: Some((dag, &source.parse_id)),
133                });
134            }
135        }
136    }
137    for dag in stored.iter().filter(|d| !d.removed) {
138        let kept: BTreeSet<&DagLocation> = places_of(dag)
139            .filter(|p| failed.contains(&(p.root.as_str(), p.path.as_str())))
140            .collect();
141        for place in kept {
142            found.entry(&dag.dag_id).or_default().push(Definition {
143                place: place.clone(),
144                new: None,
145            });
146        }
147    }
148    found
149}
150
151/// The places a stored DAG is known at: its current version's, and its conflict's.
152fn places_of(dag: &StoredDag) -> impl Iterator<Item = &DagLocation> {
153    dag.current
154        .iter()
155        .map(|c| &c.dag.location)
156        .chain(dag.conflict.iter().flatten())
157}