Skip to main content

schedr_api/views/
form.rs

1//! A DAG's run parameters as the UI's trigger form shows them (decisions 149-152): the
2//! webserver reads the declaration (a dataclass's type, a Pydantic model's JSON Schema) so the
3//! UI never interprets JSON Schema, and withholds the defaults it mustn't show.
4
5use schedr_config::masked::{mask_data, names_secret_in_words};
6use schedr_model::TypeDesc;
7use schedr_model::dag::Params;
8use serde::{Deserialize, Serialize};
9use serde_json::Value;
10use utoipa::ToSchema;
11
12#[cfg(test)]
13mod tests;
14
15/// One field of a DAG's run parameters, as a form shows it.
16#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
17pub struct ParamFieldView {
18    /// The field's name, as a trigger's values name it.
19    pub name: String,
20    /// How it is entered.
21    pub kind: ParamKind,
22    /// Whether a trigger must give it (it has no default).
23    pub required: bool,
24    /// Whether it may be `null` (`T | None`): the form has a "none" box beside it.
25    pub nullable: bool,
26    /// Whether its default and choices are withheld (decision 150): its name has a word naming
27    /// a secret, or its default or a choice holds one. The form gives it an empty password
28    /// input; left empty, the master uses the default.
29    pub secret: bool,
30    /// Its default as JSON, the form's starting value (`null` is a default); absent when it
31    /// has none or it is withheld.
32    #[serde(
33        default,
34        skip_serializing_if = "Option::is_none",
35        deserialize_with = "present"
36    )]
37    #[schema(value_type = Option<Object>)]
38    pub default: Option<Value>,
39    /// A `choice`'s values, as JSON (strings, numbers, booleans; `null` is `nullable`).
40    #[serde(default, skip_serializing_if = "Vec::is_empty")]
41    #[schema(value_type = Vec<Object>)]
42    pub choices: Vec<Value>,
43}
44
45/// A field that is present, `null` included (serde reads a `null` `Option` as absent).
46fn present<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<Option<Value>, D::Error> {
47    Value::deserialize(deserializer).map(Some)
48}
49
50/// How a parameter is entered.
51#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
52#[serde(rename_all = "snake_case")]
53pub enum ParamKind {
54    /// `bool`: a check box.
55    Bool,
56    /// `int`: a whole number.
57    Int,
58    /// `float`: a number.
59    Float,
60    /// `str`: text.
61    Text,
62    /// `date`: `2026-10-15`.
63    Date,
64    /// `datetime`: RFC 3339 text with its offset.
65    Datetime,
66    /// `timedelta`: an ISO 8601 duration (`PT1H30M`).
67    Duration,
68    /// A `Literal` (or an `enum` in a model's schema): one of `choices`.
69    Choice,
70    /// Anything else (a nested dataclass or model, a list, a tuple, a dict, a union): JSON text
71    /// (decision 152), as `--params` takes it.
72    Json,
73}
74
75impl ParamFieldView {
76    /// The fields of `params`: a dataclass's in declaration order, a model's by name (its
77    /// schema's properties, as stored, keep no order).
78    #[must_use]
79    pub fn of(params: &Params) -> Vec<Self> {
80        let required: Vec<&str> = root_object(&params.schema)
81            .get("required")
82            .and_then(Value::as_array)
83            .map(|names| names.iter().filter_map(Value::as_str).collect())
84            .unwrap_or_default();
85        let shapes: Vec<(String, Shape)> = match &params.ty {
86            TypeDesc::Dataclass { fields, .. } => fields
87                .iter()
88                .map(|f| (f.name.clone(), Shape::of_type(&f.ty)))
89                .collect(),
90            _ => root_object(&params.schema)
91                .get("properties")
92                .and_then(Value::as_object)
93                .map(|properties| {
94                    properties
95                        .iter()
96                        .map(|(name, schema)| {
97                            (name.clone(), Shape::of_schema(schema, &params.schema, 0))
98                        })
99                        .collect()
100                })
101                .unwrap_or_default(),
102        };
103        shapes
104            .into_iter()
105            .map(|(name, shape)| {
106                let default = params.defaults.get(&name).cloned();
107                let secret = names_secret_in_words(&name)
108                    || default
109                        .iter()
110                        .chain(&shape.choices)
111                        .any(|v| holds_secret(&name, v));
112                Self {
113                    required: default.is_none() && required.contains(&name.as_str()),
114                    kind: shape.kind,
115                    nullable: shape.nullable,
116                    // A `Literal`'s values are copies of values too.
117                    choices: if secret { Vec::new() } else { shape.choices },
118                    default: if secret { None } else { default },
119                    secret,
120                    name,
121                }
122            })
123            .collect()
124    }
125}
126
127/// The schema of a model's object: the root, or what a root `$ref` names (Pydantic writes a
128/// recursive model as `{"$ref": "#/$defs/P", "$defs": {...}}`).
129fn root_object(root: &Value) -> &Value {
130    root.get("$ref")
131        .and_then(Value::as_str)
132        .and_then(|target| target.strip_prefix('#'))
133        .and_then(|path| root.pointer(path))
134        .unwrap_or(root)
135}
136
137/// Whether masking `value` under `name` as a task's data changes it: a text holding a secret
138/// (a URL's password), or a field below it named by a secret word.
139fn holds_secret(name: &str, value: &Value) -> bool {
140    let mut fields = serde_json::Map::new();
141    fields.insert(name.to_owned(), value.clone());
142    let original = Value::Object(fields);
143    let mut masked = original.clone();
144    mask_data(&mut masked);
145    masked != original
146}
147
148/// What a field's type says about its input.
149struct Shape {
150    kind: ParamKind,
151    nullable: bool,
152    choices: Vec<Value>,
153}
154
155impl Shape {
156    fn plain(kind: ParamKind) -> Self {
157        Self {
158            kind,
159            nullable: false,
160            choices: Vec::new(),
161        }
162    }
163
164    fn choice(values: &[Value]) -> Self {
165        Self {
166            kind: ParamKind::Choice,
167            nullable: values.iter().any(Value::is_null),
168            choices: values.iter().filter(|v| !v.is_null()).cloned().collect(),
169        }
170    }
171
172    /// A dataclass field's type.
173    fn of_type(ty: &TypeDesc) -> Self {
174        match ty {
175            TypeDesc::Bool => Self::plain(ParamKind::Bool),
176            TypeDesc::Int => Self::plain(ParamKind::Int),
177            TypeDesc::Float => Self::plain(ParamKind::Float),
178            TypeDesc::Str => Self::plain(ParamKind::Text),
179            TypeDesc::Date => Self::plain(ParamKind::Date),
180            TypeDesc::Datetime => Self::plain(ParamKind::Datetime),
181            TypeDesc::Timedelta => Self::plain(ParamKind::Duration),
182            TypeDesc::Literal { values } => Self::choice(values),
183            TypeDesc::Union { variants } => {
184                let others: Vec<&TypeDesc> = variants
185                    .iter()
186                    .filter(|v| !matches!(v, TypeDesc::None))
187                    .collect();
188                match others.as_slice() {
189                    [one] if others.len() < variants.len() => {
190                        let mut shape = Self::of_type(one);
191                        if shape.kind != ParamKind::Json {
192                            shape.nullable = true;
193                        }
194                        shape
195                    }
196                    _ => Self::plain(ParamKind::Json),
197                }
198            }
199            _ => Self::plain(ParamKind::Json),
200        }
201    }
202
203    /// A Pydantic model's property schema; `root` holds its `$defs`.
204    fn of_schema(schema: &Value, root: &Value, depth: u8) -> Self {
205        // A `$ref` to a `$ref`... is followed a few steps; a loop is JSON.
206        if depth > 8 {
207            return Self::plain(ParamKind::Json);
208        }
209        if let Some(target) = schema.get("$ref").and_then(Value::as_str) {
210            return match target
211                .strip_prefix("#/")
212                .and_then(|path| root.pointer(&format!("/{path}")))
213            {
214                Some(found) => Self::of_schema(found, root, depth + 1),
215                None => Self::plain(ParamKind::Json),
216            };
217        }
218        if let Some(values) = schema.get("enum").and_then(Value::as_array) {
219            return Self::choice(values);
220        }
221        if let Some(value) = schema.get("const") {
222            return Self::choice(std::slice::from_ref(value));
223        }
224        if let Some(variants) = schema.get("anyOf").and_then(Value::as_array) {
225            let others: Vec<&Value> = variants
226                .iter()
227                .filter(|v| v.get("type").and_then(Value::as_str) != Some("null"))
228                .collect();
229            return match others.as_slice() {
230                [one] if others.len() < variants.len() => {
231                    let mut shape = Self::of_schema(one, root, depth + 1);
232                    if shape.kind != ParamKind::Json {
233                        shape.nullable = true;
234                    }
235                    shape
236                }
237                _ => Self::plain(ParamKind::Json),
238            };
239        }
240        let format = schema.get("format").and_then(Value::as_str);
241        match schema.get("type").and_then(Value::as_str) {
242            Some("boolean") => Self::plain(ParamKind::Bool),
243            Some("integer") => Self::plain(ParamKind::Int),
244            Some("number") => Self::plain(ParamKind::Float),
245            Some("string") => Self::plain(match format {
246                Some("date") => ParamKind::Date,
247                Some("date-time") => ParamKind::Datetime,
248                Some("duration") => ParamKind::Duration,
249                _ => ParamKind::Text,
250            }),
251            _ => Self::plain(ParamKind::Json),
252        }
253    }
254}