Skip to main content

schedr_model/
ids.rs

1//! Identifiers: DAG IDs and task IDs.
2//!
3//! Both are validated when created, so a value of these types is always well formed. They
4//! serialize as plain strings.
5
6use std::borrow::Cow;
7use std::fmt;
8use std::str::FromStr;
9
10use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
11use serde::{Deserialize, Serialize};
12
13#[cfg(test)]
14mod tests;
15
16/// The longest allowed identifier, in bytes.
17pub const MAX_ID_LEN: usize = 250;
18
19/// Characters allowed in a DAG ID, as shown in error messages.
20const DAG_ID_ALLOWED: &str = "ASCII letters, digits and `_ . - : / #`";
21
22/// Characters allowed in a task ID, as shown in error messages.
23const TASK_ID_ALLOWED: &str = "ASCII letters, digits and `_ . -`";
24
25/// Why a string isn't a valid identifier.
26#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
27pub enum IdError {
28    /// The identifier is empty.
29    #[error("{kind} is empty")]
30    Empty {
31        /// Which kind of identifier ("DAG ID", "task ID").
32        kind: &'static str,
33    },
34    /// The identifier is longer than [`MAX_ID_LEN`] bytes.
35    #[error("{kind} `{id}` is longer than {MAX_ID_LEN} bytes")]
36    TooLong {
37        /// Which kind of identifier.
38        kind: &'static str,
39        /// The rejected identifier.
40        id: String,
41    },
42    /// The identifier contains a character that isn't allowed.
43    #[error("{kind} `{id}` contains `{ch}`; allowed are {allowed}")]
44    InvalidChar {
45        /// Which kind of identifier.
46        kind: &'static str,
47        /// The rejected identifier.
48        id: String,
49        /// The first character that isn't allowed.
50        ch: char,
51        /// A description of the allowed characters.
52        allowed: &'static str,
53    },
54    /// A DAG ID that is `.` or `..`: a URL path segment URL parsing removes, so the API
55    /// couldn't be asked about it (decision 127).
56    #[error(
57        "DAG ID `{id}` can't be addressed: `.` and `..` mean the current and parent paths in a URL"
58    )]
59    DotSegment {
60        /// The rejected identifier.
61        id: String,
62    },
63    /// A task ID has an empty part around a `.` (group separator).
64    #[error("task ID `{id}` has an empty group or task name around `.`")]
65    EmptyPart {
66        /// The rejected identifier.
67        id: String,
68    },
69}
70
71/// Checks length and characters shared by every identifier kind.
72fn check_chars(
73    kind: &'static str,
74    id: &str,
75    allowed: &'static str,
76    is_allowed: fn(char) -> bool,
77) -> Result<(), IdError> {
78    if id.is_empty() {
79        return Err(IdError::Empty { kind });
80    }
81    if id.len() > MAX_ID_LEN {
82        return Err(IdError::TooLong {
83            kind,
84            id: id.to_owned(),
85        });
86    }
87    if let Some(ch) = id.chars().find(|&c| !is_allowed(c)) {
88        return Err(IdError::InvalidChar {
89            kind,
90            id: id.to_owned(),
91            ch,
92            allowed,
93        });
94    }
95    Ok(())
96}
97
98/// The ID of a DAG: a native DAG's explicit ID, or a standalone job's reference
99/// (`etl-repo:team_a/schedr.toml#report_daily`).
100#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
101#[serde(try_from = "String", into = "String")]
102pub struct DagId(String);
103
104impl DagId {
105    /// Validates `id` and wraps it.
106    ///
107    /// # Errors
108    ///
109    /// Returns an [`IdError`] if `id` is empty, too long, contains a character that isn't
110    /// allowed, or is `.` or `..` (a URL couldn't name it).
111    pub fn new(id: impl Into<String>) -> Result<Self, IdError> {
112        let id = id.into();
113        check_chars("DAG ID", &id, DAG_ID_ALLOWED, |c| {
114            c.is_ascii_alphanumeric() || "_.-:/#".contains(c)
115        })?;
116        if id == "." || id == ".." {
117            return Err(IdError::DotSegment { id });
118        }
119        Ok(Self(id))
120    }
121
122    /// The ID as a string slice.
123    #[must_use]
124    pub fn as_str(&self) -> &str {
125        &self.0
126    }
127}
128
129/// The name of an event posted through the API (decision 354): written as a DAG ID is.
130#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
131#[serde(try_from = "String", into = "String")]
132pub struct EventName(String);
133
134impl EventName {
135    /// Validates `name` and wraps it.
136    ///
137    /// # Errors
138    ///
139    /// Returns an [`IdError`] if `name` is empty, too long, contains a character that isn't
140    /// allowed, or is `.` or `..`.
141    pub fn new(name: impl Into<String>) -> Result<Self, IdError> {
142        let name = name.into();
143        check_chars("event name", &name, DAG_ID_ALLOWED, |c| {
144            c.is_ascii_alphanumeric() || "_.-:/#".contains(c)
145        })?;
146        if name == "." || name == ".." {
147            return Err(IdError::DotSegment { id: name });
148        }
149        Ok(Self(name))
150    }
151
152    /// The name as a string slice.
153    #[must_use]
154    pub fn as_str(&self) -> &str {
155        &self.0
156    }
157}
158
159/// The ID of a task within its DAG, `group.task` for tasks in groups.
160#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
161#[serde(try_from = "String", into = "String")]
162pub struct TaskId(String);
163
164impl TaskId {
165    /// Validates `id` and wraps it.
166    ///
167    /// # Errors
168    ///
169    /// Returns an [`IdError`] if `id` is empty, too long, contains a character that isn't
170    /// allowed, or has an empty part around a `.`.
171    pub fn new(id: impl Into<String>) -> Result<Self, IdError> {
172        let id = id.into();
173        check_chars("task ID", &id, TASK_ID_ALLOWED, |c| {
174            c.is_ascii_alphanumeric() || "_.-".contains(c)
175        })?;
176        if id.split('.').any(str::is_empty) {
177            return Err(IdError::EmptyPart { id });
178        }
179        Ok(Self(id))
180    }
181
182    /// The ID as a string slice.
183    #[must_use]
184    pub fn as_str(&self) -> &str {
185        &self.0
186    }
187}
188
189/// Implements the string conversions and the JSON Schema shared by both identifier types.
190macro_rules! id_conversions {
191    ($ty:ident, $pattern:literal) => {
192        impl fmt::Display for $ty {
193            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
194                f.write_str(&self.0)
195            }
196        }
197
198        impl FromStr for $ty {
199            type Err = IdError;
200
201            fn from_str(s: &str) -> Result<Self, Self::Err> {
202                Self::new(s)
203            }
204        }
205
206        impl TryFrom<String> for $ty {
207            type Error = IdError;
208
209            fn try_from(s: String) -> Result<Self, Self::Error> {
210                Self::new(s)
211            }
212        }
213
214        impl From<$ty> for String {
215            fn from(id: $ty) -> Self {
216                id.0
217            }
218        }
219
220        impl JsonSchema for $ty {
221            fn schema_name() -> Cow<'static, str> {
222                stringify!($ty).into()
223            }
224
225            fn json_schema(_: &mut SchemaGenerator) -> Schema {
226                json_schema!({
227                    "type": "string",
228                    "minLength": 1,
229                    "maxLength": MAX_ID_LEN,
230                    "pattern": $pattern,
231                })
232            }
233        }
234    };
235}
236
237id_conversions!(DagId, r"^[A-Za-z0-9_.:/#-]+$");
238id_conversions!(EventName, r"^[A-Za-z0-9_.:/#-]+$");
239id_conversions!(TaskId, r"^[A-Za-z0-9_-]+(\.[A-Za-z0-9_-]+)*$");