Skip to main content

orbit_ir/
types.rs

1//! Resolved ORBIT types and runtime payload validation.
2//!
3//! Values travel between the runtime and workers as JSON. The canonical JSON
4//! encoding of each ORBIT type is:
5//!
6//! | ORBIT type  | JSON encoding                                   |
7//! |-------------|-------------------------------------------------|
8//! | `String`    | string                                          |
9//! | `Int`       | integer (signed 64-bit)                         |
10//! | `Float`     | number (integers are accepted)                  |
11//! | `Bool`      | `true` / `false`                                |
12//! | `Bytes`     | base64 string                                   |
13//! | `Duration`  | integer milliseconds                            |
14//! | `Timestamp` | RFC 3339 string in UTC, e.g. `2026-01-01T00:00:00Z` |
15//! | `UUID`      | canonical hyphenated UUID string                |
16//! | `JSON`      | any JSON value                                  |
17//! | `List<T>`   | array                                           |
18//! | `Map<String,T>` | object                                      |
19//! | `T?`        | `null` or the encoding of `T`                   |
20//! | record      | object                                          |
21
22use serde::{Deserialize, Serialize};
23use serde_json::Value;
24use std::fmt;
25
26#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
27#[serde(tag = "kind", rename_all = "snake_case")]
28pub enum Type {
29    String,
30    Int,
31    Float,
32    Bool,
33    Bytes,
34    Duration,
35    Timestamp,
36    Uuid,
37    Json,
38    /// The type of the `null` literal. Never appears in a field position.
39    Null,
40    List {
41        item: Box<Type>,
42    },
43    Map {
44        key: Box<Type>,
45        value: Box<Type>,
46    },
47    Optional {
48        inner: Box<Type>,
49    },
50    Record {
51        #[serde(default, skip_serializing_if = "Option::is_none")]
52        name: Option<String>,
53        fields: Vec<FieldType>,
54    },
55}
56
57#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
58pub struct FieldType {
59    pub name: String,
60    #[serde(rename = "type")]
61    pub ty: Type,
62    /// `Some(Value::Null)` is a real default of `null`, distinct from no default.
63    #[serde(
64        default,
65        skip_serializing_if = "Option::is_none",
66        deserialize_with = "present"
67    )]
68    pub default: Option<Value>,
69}
70
71/// Deserialize a present field as `Some`, even when its value is `null`.
72fn present<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<Value>, D::Error> {
73    Value::deserialize(d).map(Some)
74}
75
76impl FieldType {
77    /// A field must be supplied unless it is optional or has a default.
78    pub fn required(&self) -> bool {
79        self.default.is_none() && !self.ty.is_optional()
80    }
81}
82
83impl Type {
84    pub fn optional(self) -> Type {
85        match self {
86            Type::Optional { .. } | Type::Json | Type::Null => self,
87            other => Type::Optional {
88                inner: Box::new(other),
89            },
90        }
91    }
92
93    pub fn is_optional(&self) -> bool {
94        matches!(self, Type::Optional { .. } | Type::Json | Type::Null)
95    }
96
97    /// Strip one level of `?`.
98    pub fn unwrap_optional(&self) -> &Type {
99        match self {
100            Type::Optional { inner } => inner,
101            other => other,
102        }
103    }
104
105    pub fn is_numeric(&self) -> bool {
106        matches!(self, Type::Int | Type::Float)
107    }
108
109    pub fn record(name: Option<&str>, fields: Vec<FieldType>) -> Type {
110        Type::Record {
111            name: name.map(str::to_string),
112            fields,
113        }
114    }
115
116    pub fn field(&self, name: &str) -> Option<&FieldType> {
117        match self {
118            Type::Record { fields, .. } => fields.iter().find(|f| f.name == name),
119            _ => None,
120        }
121    }
122
123    /// Validate a JSON value against this type.
124    ///
125    /// With `strict`, records reject fields they do not declare. Execution
126    /// inputs are validated strictly; worker outputs are validated leniently so
127    /// that workers can add fields without breaking older workflows.
128    pub fn validate(&self, value: &Value, strict: bool) -> Result<(), ValidationError> {
129        let mut path = String::from("$");
130        self.validate_at(value, strict, &mut path)
131    }
132
133    fn validate_at(
134        &self,
135        value: &Value,
136        strict: bool,
137        path: &mut String,
138    ) -> Result<(), ValidationError> {
139        let fail = |path: &str, expected: &Type| {
140            Err(ValidationError {
141                path: path.to_string(),
142                message: format!("expected {expected}, found {}", describe(value)),
143            })
144        };
145        match self {
146            Type::Json => Ok(()),
147            Type::Null => {
148                if value.is_null() {
149                    Ok(())
150                } else {
151                    fail(path, self)
152                }
153            }
154            Type::Optional { inner } => {
155                if value.is_null() {
156                    Ok(())
157                } else {
158                    inner.validate_at(value, strict, path)
159                }
160            }
161            _ if value.is_null() => fail(path, self),
162            Type::String => {
163                if value.is_string() {
164                    Ok(())
165                } else {
166                    fail(path, self)
167                }
168            }
169            Type::Int => {
170                if value.is_i64() {
171                    Ok(())
172                } else {
173                    fail(path, self)
174                }
175            }
176            Type::Float => {
177                if value.is_number() {
178                    Ok(())
179                } else {
180                    fail(path, self)
181                }
182            }
183            Type::Bool => {
184                if value.is_boolean() {
185                    Ok(())
186                } else {
187                    fail(path, self)
188                }
189            }
190            Type::Duration => {
191                if value.is_u64() {
192                    Ok(())
193                } else {
194                    fail(path, self)
195                }
196            }
197            Type::Bytes => match value.as_str() {
198                Some(s) if is_base64(s) => Ok(()),
199                _ => fail(path, self),
200            },
201            Type::Timestamp => match value.as_str() {
202                Some(s) if is_timestamp(s) => Ok(()),
203                _ => fail(path, self),
204            },
205            Type::Uuid => match value.as_str() {
206                Some(s) if is_uuid(s) => Ok(()),
207                _ => fail(path, self),
208            },
209            Type::List { item } => {
210                let Some(items) = value.as_array() else {
211                    return fail(path, self);
212                };
213                for (i, v) in items.iter().enumerate() {
214                    let len = path.len();
215                    path.push_str(&format!("[{i}]"));
216                    item.validate_at(v, strict, path)?;
217                    path.truncate(len);
218                }
219                Ok(())
220            }
221            Type::Map { value: vt, .. } => {
222                let Some(obj) = value.as_object() else {
223                    return fail(path, self);
224                };
225                for (k, v) in obj {
226                    let len = path.len();
227                    path.push_str(&format!("[{k:?}]"));
228                    vt.validate_at(v, strict, path)?;
229                    path.truncate(len);
230                }
231                Ok(())
232            }
233            Type::Record { fields, .. } => {
234                let Some(obj) = value.as_object() else {
235                    return fail(path, self);
236                };
237                for f in fields {
238                    let len = path.len();
239                    path.push('.');
240                    path.push_str(&f.name);
241                    match obj.get(&f.name) {
242                        Some(v) => f.ty.validate_at(v, strict, path)?,
243                        None if f.required() => {
244                            return Err(ValidationError {
245                                path: path.clone(),
246                                message: format!(
247                                    "missing required field `{}` of type {}",
248                                    f.name, f.ty
249                                ),
250                            })
251                        }
252                        None => {}
253                    }
254                    path.truncate(len);
255                }
256                if strict {
257                    if let Some(k) = obj.keys().find(|k| !fields.iter().any(|f| &f.name == *k)) {
258                        return Err(ValidationError {
259                            path: path.clone(),
260                            message: format!("unknown field `{k}`"),
261                        });
262                    }
263                }
264                Ok(())
265            }
266        }
267    }
268
269    /// Fill in declared defaults (recursively) for record fields that are absent.
270    pub fn apply_defaults(&self, value: &mut Value) {
271        match (self, value) {
272            (Type::Optional { inner }, v) if !v.is_null() => inner.apply_defaults(v),
273            (Type::List { item }, Value::Array(items)) => {
274                items.iter_mut().for_each(|v| item.apply_defaults(v))
275            }
276            (Type::Map { value: vt, .. }, Value::Object(obj)) => {
277                obj.values_mut().for_each(|v| vt.apply_defaults(v))
278            }
279            (Type::Record { fields, .. }, Value::Object(obj)) => {
280                for f in fields {
281                    match obj.get_mut(&f.name) {
282                        Some(v) => f.ty.apply_defaults(v),
283                        None => {
284                            if let Some(d) = &f.default {
285                                obj.insert(f.name.clone(), d.clone());
286                            }
287                        }
288                    }
289                }
290            }
291            _ => {}
292        }
293    }
294}
295
296impl fmt::Display for Type {
297    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
298        match self {
299            Type::String => write!(f, "String"),
300            Type::Int => write!(f, "Int"),
301            Type::Float => write!(f, "Float"),
302            Type::Bool => write!(f, "Bool"),
303            Type::Bytes => write!(f, "Bytes"),
304            Type::Duration => write!(f, "Duration"),
305            Type::Timestamp => write!(f, "Timestamp"),
306            Type::Uuid => write!(f, "UUID"),
307            Type::Json => write!(f, "JSON"),
308            Type::Null => write!(f, "null"),
309            Type::List { item } => write!(f, "List<{item}>"),
310            Type::Map { key, value } => write!(f, "Map<{key}, {value}>"),
311            Type::Optional { inner } => write!(f, "{inner}?"),
312            Type::Record { name: Some(n), .. } => write!(f, "{n}"),
313            Type::Record { name: None, fields } => {
314                write!(f, "{{ ")?;
315                for (i, fl) in fields.iter().enumerate() {
316                    if i > 0 {
317                        write!(f, ", ")?;
318                    }
319                    write!(f, "{}: {}", fl.name, fl.ty)?;
320                }
321                write!(f, " }}")
322            }
323        }
324    }
325}
326
327#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
328pub struct ValidationError {
329    pub path: String,
330    pub message: String,
331}
332
333impl fmt::Display for ValidationError {
334    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
335        write!(f, "{}: {}", self.path, self.message)
336    }
337}
338
339impl std::error::Error for ValidationError {}
340
341pub fn describe(v: &Value) -> &'static str {
342    match v {
343        Value::Null => "null",
344        Value::Bool(_) => "a boolean",
345        Value::Number(n) if n.is_i64() || n.is_u64() => "an integer",
346        Value::Number(_) => "a float",
347        Value::String(_) => "a string",
348        Value::Array(_) => "an array",
349        Value::Object(_) => "an object",
350    }
351}
352
353pub fn is_uuid(s: &str) -> bool {
354    let b = s.as_bytes();
355    b.len() == 36
356        && b.iter().enumerate().all(|(i, c)| {
357            if matches!(i, 8 | 13 | 18 | 23) {
358                *c == b'-'
359            } else {
360                c.is_ascii_hexdigit()
361            }
362        })
363}
364
365/// RFC 3339 `YYYY-MM-DDTHH:MM:SS[.frac](Z|±HH:MM)`.
366pub fn is_timestamp(s: &str) -> bool {
367    let b = s.as_bytes();
368    let digits =
369        |r: std::ops::Range<usize>| r.clone().all(|i| b.get(i).is_some_and(u8::is_ascii_digit));
370    if b.len() < 20
371        || !digits(0..4)
372        || b[4] != b'-'
373        || !digits(5..7)
374        || b[7] != b'-'
375        || !digits(8..10)
376    {
377        return false;
378    }
379    if !matches!(b[10], b'T' | b't' | b' ')
380        || !digits(11..13)
381        || b[13] != b':'
382        || !digits(14..16)
383        || b[16] != b':'
384        || !digits(17..19)
385    {
386        return false;
387    }
388    let mut i = 19;
389    if b.get(i) == Some(&b'.') {
390        i += 1;
391        let start = i;
392        while b.get(i).is_some_and(u8::is_ascii_digit) {
393            i += 1;
394        }
395        if i == start {
396            return false;
397        }
398    }
399    match b.get(i) {
400        Some(b'Z' | b'z') => i + 1 == b.len(),
401        Some(b'+' | b'-') => {
402            b.len() == i + 6 && digits(i + 1..i + 3) && b[i + 3] == b':' && digits(i + 4..i + 6)
403        }
404        _ => false,
405    }
406}
407
408pub fn is_base64(s: &str) -> bool {
409    s.len().is_multiple_of(4)
410        && s.trim_end_matches('=')
411            .bytes()
412            .all(|c| c.is_ascii_alphanumeric() || c == b'+' || c == b'/')
413        && s.len() - s.trim_end_matches('=').len() <= 2
414}
415
416#[cfg(test)]
417mod tests {
418    use super::*;
419    use serde_json::json;
420
421    fn order() -> Type {
422        Type::record(
423            Some("Order"),
424            vec![
425                FieldType {
426                    name: "id".into(),
427                    ty: Type::Uuid,
428                    default: None,
429                },
430                FieldType {
431                    name: "qty".into(),
432                    ty: Type::Int,
433                    default: Some(json!(1)),
434                },
435                FieldType {
436                    name: "note".into(),
437                    ty: Type::String.optional(),
438                    default: None,
439                },
440                FieldType {
441                    name: "tags".into(),
442                    ty: Type::List {
443                        item: Box::new(Type::String),
444                    },
445                    default: None,
446                },
447            ],
448        )
449    }
450
451    #[test]
452    fn validates_records() {
453        let t = order();
454        let id = "123e4567-e89b-12d3-a456-426614174000";
455        assert!(t.validate(&json!({"id": id, "tags": []}), true).is_ok());
456        let e = t
457            .validate(&json!({"id": id, "tags": [1]}), true)
458            .unwrap_err();
459        assert_eq!(e.path, "$.tags[0]");
460        let e = t.validate(&json!({"tags": []}), true).unwrap_err();
461        assert!(e.message.contains("missing required field `id`"));
462        assert!(t
463            .validate(&json!({"id": id, "tags": [], "x": 1}), true)
464            .is_err());
465        assert!(t
466            .validate(&json!({"id": id, "tags": [], "x": 1}), false)
467            .is_ok());
468        assert!(t
469            .validate(&json!({"id": "nope", "tags": []}), true)
470            .is_err());
471    }
472
473    #[test]
474    fn defaults() {
475        let mut v = json!({"id": "x", "tags": []});
476        order().apply_defaults(&mut v);
477        assert_eq!(v["qty"], json!(1));
478    }
479
480    #[test]
481    fn formats() {
482        assert!(is_timestamp("2026-11-14T10:00:00Z"));
483        assert!(is_timestamp("2026-11-14T10:00:00.123+05:30"));
484        assert!(!is_timestamp("2026-11-14"));
485        assert!(is_base64("aGVsbG8="));
486        assert!(!is_base64("abc"));
487    }
488}