Skip to main content

schedr_config/
roots.rs

1//! Path lists (`SCHEDR_DAG_PATH`, `SCHEDR_SCRIPT_PATH`) and the roots made from them.
2//!
3//! Every entry of a path list is a root, named after its last path component unless renamed
4//! (see archive/PROJECT.md, DAG roots and Plain script delivery: script roots). Paths are compared
5//! lexically: the configuration is checked without touching the filesystem.
6
7use std::collections::BTreeMap;
8use std::fmt;
9use std::path::{Component, Path, PathBuf};
10
11use serde::de::{self, Deserializer, SeqAccess, Visitor};
12
13#[cfg(test)]
14mod tests;
15
16/// A named root: one entry of a path list.
17#[derive(Debug, Clone, PartialEq, Eq)]
18pub struct Root {
19    /// The root's name, used in references such as `etl-repo:team_a/sync.py`.
20    pub name: String,
21    /// The directory.
22    pub path: PathBuf,
23    /// Only these `.py` files of it are parsed (paths relative to it), the others still
24    /// importable: `schedr dags test` of one file (decision 117, B118). Never from the
25    /// configuration file: every configured root is parsed whole.
26    pub only: Option<Vec<String>>,
27}
28
29/// Why a path list and its renames don't make a valid set of roots.
30#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
31pub enum RootError {
32    /// The same directory is listed twice.
33    #[error("{list}: `{}` is listed twice", path.display())]
34    DuplicateEntry {
35        /// The path list's name, e.g. `SCHEDR_DAG_PATH`.
36        list: &'static str,
37        /// The repeated directory.
38        path: PathBuf,
39    },
40    /// One entry is inside another.
41    #[error("{list}: `{}` is inside `{}`; nested entries aren't allowed", inner.display(), outer.display())]
42    Nested {
43        /// The path list's name.
44        list: &'static str,
45        /// The containing entry.
46        outer: PathBuf,
47        /// The entry inside it.
48        inner: PathBuf,
49    },
50    /// An entry has no last component to name it after (e.g. `/`).
51    #[error("{list}: `{}` has no name; rename it in [{section}.roots]", path.display())]
52    Unnamed {
53        /// The path list's name.
54        list: &'static str,
55        /// The configuration section, `dags` or `scripts`.
56        section: &'static str,
57        /// The entry.
58        path: PathBuf,
59    },
60    /// Two entries have the same name.
61    #[error(
62        "{list}: `{}` and `{}` are both named `{name}`; rename one in [{section}.roots]",
63        first.display(),
64        second.display()
65    )]
66    DuplicateName {
67        /// The path list's name.
68        list: &'static str,
69        /// The configuration section.
70        section: &'static str,
71        /// The shared name.
72        name: String,
73        /// The first entry with it.
74        first: PathBuf,
75        /// The second entry with it.
76        second: PathBuf,
77    },
78    /// A script root and a DAG root have the same name (decision 299).
79    #[error(
80        "{list}: `{}` is named `{name}`, as the DAG root `{}`; rename one in \
81         [scripts.roots] or [dags.roots]",
82        script.display(),
83        dag.display()
84    )]
85    ScriptNamedAsDag {
86        /// The script path list's name, `SCHEDR_SCRIPT_PATH` or `--script-path`.
87        list: &'static str,
88        /// The shared name.
89        name: String,
90        /// The script root.
91        script: PathBuf,
92        /// The DAG root.
93        dag: PathBuf,
94    },
95    /// A rename names a directory that isn't in the path list.
96    #[error(
97        "[{section}.roots] `{name}` = `{}` is not an entry of {list}; renaming never adds directories",
98        path.display()
99    )]
100    RenameNotListed {
101        /// The path list's name.
102        list: &'static str,
103        /// The configuration section.
104        section: &'static str,
105        /// The new name.
106        name: String,
107        /// The directory that isn't listed.
108        path: PathBuf,
109    },
110}
111
112/// A list of directories, written as an array in TOML or as a `PATH`-style colon-separated
113/// string (`/git/dags/a:/git/dags/b`) in environment variables.
114#[derive(Debug, Clone, PartialEq, Eq, Default, serde::Serialize)]
115pub struct PathList(pub Vec<PathBuf>);
116
117impl schemars::JsonSchema for PathList {
118    fn schema_name() -> std::borrow::Cow<'static, str> {
119        "PathList".into()
120    }
121
122    fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
123        schemars::json_schema!({
124            "anyOf": [
125                {"type": "array", "items": {"type": "string"}},
126                {"type": "string"}
127            ],
128            "description": "Directories: an array, or a colon-separated string as in `PATH`."
129        })
130    }
131}
132
133impl PathList {
134    /// Splits a `PATH`-style string; empty entries (`a::b`, a trailing `:`) are skipped.
135    #[must_use]
136    pub fn from_path_string(s: &str) -> Self {
137        Self(
138            s.split(':')
139                .filter(|p| !p.is_empty())
140                .map(PathBuf::from)
141                .collect(),
142        )
143    }
144}
145
146impl<'de> serde::Deserialize<'de> for PathList {
147    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
148        struct PathListVisitor;
149
150        impl<'de> Visitor<'de> for PathListVisitor {
151            type Value = PathList;
152
153            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
154                f.write_str("a list of paths, or a colon-separated string of paths")
155            }
156
157            fn visit_str<E: de::Error>(self, s: &str) -> Result<PathList, E> {
158                Ok(PathList::from_path_string(s))
159            }
160
161            fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<PathList, A::Error> {
162                let mut paths = Vec::new();
163                while let Some(path) = seq.next_element::<String>()? {
164                    paths.push(PathBuf::from(path));
165                }
166                Ok(PathList(paths))
167            }
168        }
169
170        d.deserialize_any(PathListVisitor)
171    }
172}
173
174/// `path` without `.` components or a trailing separator, for lexical comparison.
175#[must_use]
176pub fn normalize(path: &Path) -> PathBuf {
177    path.components()
178        .filter(|c| !matches!(c, Component::CurDir))
179        .collect()
180}
181
182/// Builds the roots of a path list: checks that no entry is repeated or nested in another,
183/// names each entry (its last component, or its rename), and checks that names are unique.
184///
185/// `list` names the path list and `section` its configuration section, for error messages.
186///
187/// # Errors
188///
189/// Returns the first [`RootError`] found, in the order: repeated entries, nested entries,
190/// renames of unlisted directories, unnamed entries, duplicate names.
191pub fn resolve_roots(
192    list: &'static str,
193    section: &'static str,
194    entries: &PathList,
195    renames: &BTreeMap<String, PathBuf>,
196) -> Result<Vec<Root>, RootError> {
197    let paths: Vec<PathBuf> = entries.0.iter().map(|p| normalize(p)).collect();
198    for (i, a) in paths.iter().enumerate() {
199        for b in &paths[i + 1..] {
200            if a == b {
201                return Err(RootError::DuplicateEntry {
202                    list,
203                    path: a.clone(),
204                });
205            }
206            if b.starts_with(a) || a.starts_with(b) {
207                let (outer, inner) = if b.starts_with(a) { (a, b) } else { (b, a) };
208                return Err(RootError::Nested {
209                    list,
210                    outer: outer.clone(),
211                    inner: inner.clone(),
212                });
213            }
214        }
215    }
216    let mut names_by_path: BTreeMap<PathBuf, &str> = BTreeMap::new();
217    for (name, path) in renames {
218        let path = normalize(path);
219        if !paths.contains(&path) {
220            return Err(RootError::RenameNotListed {
221                list,
222                section,
223                name: name.clone(),
224                path,
225            });
226        }
227        names_by_path.insert(path, name);
228    }
229    let mut roots: Vec<Root> = Vec::with_capacity(paths.len());
230    for path in paths {
231        let name = match names_by_path.get(&path) {
232            Some(name) => (*name).to_owned(),
233            None => match path.file_name() {
234                Some(name) => name.to_string_lossy().into_owned(),
235                None => {
236                    return Err(RootError::Unnamed {
237                        list,
238                        section,
239                        path,
240                    });
241                }
242            },
243        };
244        if let Some(first) = roots.iter().find(|r| r.name == name) {
245            return Err(RootError::DuplicateName {
246                list,
247                section,
248                name,
249                first: first.path.clone(),
250                second: path,
251            });
252        }
253        // Absolute, against the working directory the role starts in: the agent runs parse
254        // jobs and tasks in the root's directory, and gives them the root's path too (B60: a
255        // relative `dags/etl` became `dags/etl/dags/etl/dag.py`).
256        let path = std::path::absolute(&path).unwrap_or(path);
257        roots.push(Root {
258            name,
259            path,
260            only: None,
261        });
262    }
263    Ok(roots)
264}
265
266/// Script roots and DAG roots named apart (decision 299): a name means one directory in logs,
267/// the UI and references.
268///
269/// # Errors
270///
271/// [`RootError::ScriptNamedAsDag`] for the first script root named as a DAG root.
272pub fn check_apart(list: &'static str, dags: &[Root], scripts: &[Root]) -> Result<(), RootError> {
273    for script in scripts {
274        if let Some(dag) = dags.iter().find(|dag| dag.name == script.name) {
275            return Err(RootError::ScriptNamedAsDag {
276                list,
277                name: script.name.clone(),
278                script: script.path.clone(),
279                dag: dag.path.clone(),
280            });
281        }
282    }
283    Ok(())
284}