Skip to main content

schedr_model/
connection.rs

1//! Connections (archive/PROJECT.md, Connections; decisions 53 and 174): what the parser records of
2//! a `@connection` function, so the agent can render it for a task by name.
3//!
4//! A connection's values may name secrets; the record holds the names (as in DAG JSON),
5//! never a value. Its name is unique in a DAG root.
6
7use std::collections::BTreeMap;
8
9use schemars::JsonSchema;
10use serde::{Deserialize, Serialize};
11
12use crate::ids::TaskId;
13use crate::secret::SecretName;
14use crate::value::{Reference, Value};
15
16#[cfg(test)]
17mod tests;
18
19/// A connection as the runner reports it when parsing (`file_parsed`).
20#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
21#[serde(deny_unknown_fields)]
22pub struct ConnectionDef {
23    /// Its name: the function's, or a typed connection's first argument (an identifier,
24    /// unique in the root).
25    pub name: String,
26    /// A typed connection's type (decision 174); none for a `@connection` function.
27    #[serde(default, rename = "type", skip_serializing_if = "Option::is_none")]
28    pub kind: Option<ConnectionType>,
29    /// Its parameters' values, by parameter: literals, secrets, and t-strings of them.
30    pub params: BTreeMap<String, Value>,
31}
32
33/// The built-in connection types (decision 174): each a fixed shape, given to a command as
34/// variables and files of its own (M4.7b2).
35#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
36#[serde(rename_all = "lowercase")]
37pub enum ConnectionType {
38    /// An HTTP API (httpx).
39    Http,
40    /// An SSH host (paramiko).
41    Ssh,
42    /// A MongoDB database (pymongo).
43    Mongo,
44    /// A Postgres or MySQL database, by URL (psycopg 3, `PyMySQL`).
45    Sql,
46    /// Keys of one's own.
47    Generic,
48    /// A schedr deployment's REST API (`schedr.api.Client`, M4.11h).
49    Schedr,
50}
51
52impl ConnectionDef {
53    /// Checks what a runner can't be trusted to have checked: a name like a task ID, and
54    /// only secrets referenced (a connection is defined outside any DAG).
55    ///
56    /// # Errors
57    ///
58    /// What is wrong, naming the connection.
59    pub fn check(&self) -> Result<(), String> {
60        TaskId::new(&self.name).map_err(|e| format!("connection `{}`: {e}", self.name))?;
61        for (param, value) in &self.params {
62            for reference in value.references() {
63                match reference {
64                    Reference::Secret(name) => name
65                        .check()
66                        .map_err(|e| format!("connection `{}`, `{param}`: {e}", self.name))?,
67                    _ => {
68                        return Err(format!(
69                            "connection `{}`, `{param}`: only secrets can be referenced",
70                            self.name
71                        ));
72                    }
73                }
74            }
75        }
76        Ok(())
77    }
78
79    /// The secrets its values name, in order (each once).
80    #[must_use]
81    pub fn secrets(&self) -> Vec<&SecretName> {
82        let mut found: Vec<&SecretName> = Vec::new();
83        for reference in self.params.values().flat_map(Value::references) {
84            if let Reference::Secret(name) = reference
85                && !found.contains(&name)
86            {
87                found.push(name);
88            }
89        }
90        found
91    }
92}
93
94/// The most a connection's recorded values may take, as JSON: they travel with each
95/// assignment of a task that opens it, within the worker's 4 MiB message. A file defining a
96/// bigger one fails to import.
97pub const MAX_CONNECTION_SIZE: usize = 1024 * 1024;
98
99/// A root's connections (decision 174), from its current parse: what the agent renders by
100/// name for the root's tasks.
101#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
102#[serde(deny_unknown_fields)]
103pub struct Registry {
104    /// The connections, by name.
105    #[serde(default)]
106    pub connections: BTreeMap<String, ConnectionDef>,
107    /// Names that can't be used, with why: defined in more than one file, or invalid.
108    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
109    pub refused: BTreeMap<String, String>,
110    /// The file defining each connection, relative to the root: a test imports it.
111    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
112    pub files: BTreeMap<String, String>,
113}
114
115impl Registry {
116    /// The registry of a root's parsed files (in any order). A file that failed to import
117    /// records none; one the master refused after it imported (a DAG of it invalid) keeps its
118    /// connections: one bad DAG doesn't fail the tasks of other files using them.
119    #[must_use]
120    pub fn of(files: &[crate::runner::ParsedFile]) -> Self {
121        let mut places: BTreeMap<&str, Vec<(&str, &ConnectionDef)>> = BTreeMap::new();
122        for file in files {
123            for def in &file.connections {
124                places
125                    .entry(def.name.as_str())
126                    .or_default()
127                    .push((file.path.as_str(), def));
128            }
129        }
130        let mut registry = Self::default();
131        for (name, mut defined) in places {
132            defined.sort_by_key(|(path, _)| *path);
133            if let [(path, def)] = defined.as_slice() {
134                match def.check() {
135                    Ok(()) => {
136                        registry.connections.insert(name.to_owned(), (*def).clone());
137                        registry.files.insert(name.to_owned(), (*path).to_owned());
138                    }
139                    Err(why) => {
140                        registry.refused.insert(name.to_owned(), why);
141                    }
142                }
143            } else {
144                let paths: Vec<&str> = defined.iter().map(|(path, _)| *path).collect();
145                registry.refused.insert(
146                    name.to_owned(),
147                    format!(
148                        "connection `{name}` is defined in more than one file ({}): rename one",
149                        paths.join(", ")
150                    ),
151                );
152            }
153        }
154        registry
155    }
156
157    /// Every connection's name, the refused ones' after.
158    pub fn names(&self) -> impl Iterator<Item = &String> {
159        self.connections.keys().chain(self.refused.keys())
160    }
161
162    /// Only the connections named in `names`, and why those refused are: what one task
163    /// declares, sent with its assignment (the agent serves no other).
164    #[must_use]
165    pub fn only(&self, names: &[String]) -> Self {
166        let mut subset = Self::default();
167        for name in names {
168            if let Some(def) = self.connections.get(name) {
169                subset.connections.insert(name.clone(), def.clone());
170                if let Some(path) = self.files.get(name) {
171                    subset.files.insert(name.clone(), path.clone());
172                }
173            } else if let Some(why) = self.refused.get(name) {
174                subset.refused.insert(name.clone(), why.clone());
175            }
176        }
177        subset
178    }
179
180    /// What is wrong with the connections `dag`'s tasks declare (decision 179), one line
181    /// each: `task `load`: connections=: <why>`.
182    #[must_use]
183    pub fn problems(&self, dag: &crate::Dag) -> Vec<String> {
184        let trigger = match &dag.trigger {
185            crate::Trigger::Event { task, .. } => Some(task.as_ref()),
186            _ => None,
187        };
188        dag.tasks
189            .iter()
190            .chain(trigger)
191            .flat_map(|task| {
192                task.connections.iter().filter_map(move |name| {
193                    self.get(name)
194                        .err()
195                        .map(|why| format!("task `{}`: connections=: {why}", task.id))
196                })
197            })
198            .collect()
199    }
200
201    /// The connection named `name`.
202    ///
203    /// # Errors
204    ///
205    /// Why it can't be used: unknown, defined twice, or invalid.
206    pub fn get(&self, name: &str) -> Result<&ConnectionDef, String> {
207        if let Some(def) = self.connections.get(name) {
208            return Ok(def);
209        }
210        Err(self.refused.get(name).cloned().unwrap_or_else(|| {
211            format!(
212                "connection `{name}` isn't defined in the DAG folder (a `@connection` function \
213                 in a file of the DAG root that imports)"
214            )
215        }))
216    }
217}
218
219/// A connection's prefix in a command's `connections={"DB": ...}` (decision 184): the start
220/// of an environment variable's name, not schedr's own.
221///
222/// # Errors
223///
224/// What is wrong with it.
225pub fn check_prefix(prefix: &str) -> Result<(), String> {
226    let mut chars = prefix.chars();
227    let starts = chars
228        .next()
229        .is_some_and(|c| c.is_ascii_alphabetic() || c == '_');
230    if !starts || !chars.all(|c| c.is_ascii_alphanumeric() || c == '_') {
231        return Err(format!(
232            "`{prefix}`: a prefix is letters, digits and `_`, not starting with a digit"
233        ));
234    }
235    if prefix.to_ascii_uppercase().starts_with("SCHEDR") {
236        return Err(format!(
237            "`{prefix}`: prefixes starting with SCHEDR are schedr's own"
238        ));
239    }
240    Ok(())
241}