Skip to main content

schedr_model/
types.rs

1//! Type descriptors: the type of a task's output, as recorded in DAG JSON.
2//!
3//! The Python runner derives them from the return annotation at parse time (see archive/PROJECT.md,
4//! Output serialization). The master uses them to check output references and paths without
5//! running Python.
6
7use schemars::JsonSchema;
8use serde::{Deserialize, Serialize};
9
10#[cfg(test)]
11mod tests;
12
13/// `Any`, for the parts of a model.
14static ANY: TypeDesc = TypeDesc::Any;
15
16/// The type of a value that can be stored as a task output.
17#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
18#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
19pub enum TypeDesc {
20    /// Anything (an explicit `Any`): only the run-time check applies.
21    Any,
22    /// `None`.
23    None,
24    /// `bool`.
25    Bool,
26    /// `int`.
27    Int,
28    /// `float`.
29    Float,
30    /// `str`.
31    Str,
32    /// `datetime` (stored tagged).
33    Datetime,
34    /// `date` (stored tagged).
35    Date,
36    /// `timedelta` (stored tagged).
37    Timedelta,
38    /// `list[T]`.
39    List {
40        /// The element type.
41        item: Box<TypeDesc>,
42    },
43    /// `tuple[A, B, ...]` (stored tagged).
44    Tuple {
45        /// The element types, in order.
46        items: Vec<TypeDesc>,
47    },
48    /// `dict[str, T]` (keys are always strings).
49    Dict {
50        /// The value type.
51        value: Box<TypeDesc>,
52    },
53    /// `Literal[...]`.
54    Literal {
55        /// The allowed values (strings, integers, booleans or `null`).
56        values: Vec<serde_json::Value>,
57    },
58    /// A union, including `Optional[T]` (`T | None`).
59    Union {
60        /// The member types.
61        variants: Vec<TypeDesc>,
62    },
63    /// A `TypedDict`.
64    TypedDict {
65        /// The class name, for messages.
66        name: String,
67        /// The keys, in declaration order.
68        fields: Vec<Field>,
69    },
70    /// A dataclass.
71    Dataclass {
72        /// The class name, for messages and outcome names.
73        name: String,
74        /// The fields, in declaration order.
75        fields: Vec<Field>,
76    },
77    /// A Pydantic model (decision 59), described by Pydantic's JSON Schema of it: what
78    /// `model_dump(mode="json")` writes. Only the Python layer compares it; here its parts
79    /// are `Any`.
80    Model {
81        /// The class name, for messages and outcome names.
82        name: String,
83        /// The JSON Schema (with its `$defs`).
84        schema: serde_json::Value,
85    },
86    /// The output of a `command` or `script` task.
87    ProcessResult,
88}
89
90/// A named field of a `TypedDict` or dataclass.
91#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
92#[serde(deny_unknown_fields)]
93pub struct Field {
94    /// The field or key name.
95    pub name: String,
96    /// The field's type.
97    #[serde(rename = "type")]
98    pub ty: TypeDesc,
99    /// Whether the field must be present (`TypedDict`) or has no default (dataclass).
100    pub required: bool,
101}
102
103impl TypeDesc {
104    /// The type of the named field or key, for checking an output path such as `out.rows`.
105    ///
106    /// Returns `None` if this type has no such field: `TypedDict`s, dataclasses and
107    /// `ProcessResult` have named fields, `dict[str, T]` has any key (giving `T`), and `Any`
108    /// and a model give `Any`.
109    #[must_use]
110    pub fn field(&self, name: &str) -> Option<&TypeDesc> {
111        static STR: TypeDesc = TypeDesc::Str;
112        static INT: TypeDesc = TypeDesc::Int;
113        static BOOL: TypeDesc = TypeDesc::Bool;
114        match self {
115            Self::Any => Some(self),
116            // Checked by the Python layer against the model's schema (decision 59).
117            Self::Model { .. } => Some(&ANY),
118            Self::Dict { value } => Some(value),
119            Self::ProcessResult => match name {
120                "stdout" | "stderr" => Some(&STR),
121                "exit_code" => Some(&INT),
122                "stdout_truncated" | "stderr_truncated" => Some(&BOOL),
123                _ => None,
124            },
125            Self::TypedDict { fields, .. } | Self::Dataclass { fields, .. } => {
126                fields.iter().find(|f| f.name == name).map(|f| &f.ty)
127            }
128            _ => None,
129        }
130    }
131
132    /// The type of the element at `index`, for checking an output path such as `out[0]`.
133    ///
134    /// Returns `None` if this type can't be indexed, or for a tuple index out of range;
135    /// `Any` and a model give `Any`.
136    #[must_use]
137    pub fn element(&self, index: u64) -> Option<&TypeDesc> {
138        match self {
139            Self::Any => Some(self),
140            Self::Model { .. } => Some(&ANY),
141            Self::List { item } => Some(item),
142            Self::Tuple { items } => usize::try_from(index).ok().and_then(|i| items.get(i)),
143            _ => None,
144        }
145    }
146}