1use 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
16pub const MAX_ID_LEN: usize = 250;
18
19const DAG_ID_ALLOWED: &str = "ASCII letters, digits and `_ . - : / #`";
21
22const TASK_ID_ALLOWED: &str = "ASCII letters, digits and `_ . -`";
24
25#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
27pub enum IdError {
28 #[error("{kind} is empty")]
30 Empty {
31 kind: &'static str,
33 },
34 #[error("{kind} `{id}` is longer than {MAX_ID_LEN} bytes")]
36 TooLong {
37 kind: &'static str,
39 id: String,
41 },
42 #[error("{kind} `{id}` contains `{ch}`; allowed are {allowed}")]
44 InvalidChar {
45 kind: &'static str,
47 id: String,
49 ch: char,
51 allowed: &'static str,
53 },
54 #[error(
57 "DAG ID `{id}` can't be addressed: `.` and `..` mean the current and parent paths in a URL"
58 )]
59 DotSegment {
60 id: String,
62 },
63 #[error("task ID `{id}` has an empty group or task name around `.`")]
65 EmptyPart {
66 id: String,
68 },
69}
70
71fn 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#[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 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 #[must_use]
124 pub fn as_str(&self) -> &str {
125 &self.0
126 }
127}
128
129#[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 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 #[must_use]
154 pub fn as_str(&self) -> &str {
155 &self.0
156 }
157}
158
159#[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 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 #[must_use]
184 pub fn as_str(&self) -> &str {
185 &self.0
186 }
187}
188
189macro_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_-]+)*$");