Skip to main content

schedr_model/
params.rs

1//! A run's parameters (decision 138): from the JSON a trigger gives to the form they are
2//! stored and sent in, which is how outputs are stored (dates and tuples tagged), and back to
3//! JSON for showing them.
4
5use serde_json::{Map, Value, json};
6
7use crate::TypeDesc;
8
9#[cfg(test)]
10mod tests;
11
12/// At most this many bytes of a run's parameters as JSON, defaults included (decision 135).
13pub const MAX_PARAMS_BYTES: usize = 64 * 1024;
14
15/// The keys of tagged values, as the Python codec writes them.
16const TAGS: [&str; 5] = ["$datetime", "$date", "$timedelta", "$tuple", "$dict"];
17
18/// Microseconds in a day.
19const DAY_MICROS: i128 = 86_400_000_000;
20
21/// Values given as JSON (`{"day": "2026-10-01"}`), already checked against the schema, in the
22/// form they are stored in, by the declared type (`{"day": {"$date": "2026-10-01"}}`).
23///
24/// # Errors
25///
26/// Where and why a value doesn't fit its type: a date that isn't one, a duration in months, a
27/// value of a type outputs can't hold, text containing NUL. The reason never quotes the value.
28pub fn to_stored(value: &Value, ty: &TypeDesc) -> Result<Value, Misfit> {
29    checked(value, ty, Form::Given)
30}
31
32/// A value reported from outside Python (`schedr task-ctx resource set`), in the form it is
33/// stored in: as [`to_stored`], and a dataclass gives every field, since nothing fills in its
34/// defaults before a command reads the value (`t"{cluster.value.region}"`).
35///
36/// # Errors
37///
38/// As [`to_stored`], and a dataclass field left out.
39pub fn to_reported(value: &Value, ty: &TypeDesc) -> Result<Value, Misfit> {
40    checked(value, ty, Form::Whole)
41}
42
43/// Whether a dataclass may leave out its fields that have defaults.
44#[derive(Debug, Clone, Copy, PartialEq, Eq)]
45enum Form {
46    /// Yes: Python fills them in where it reads the value.
47    Given,
48    /// No: the value is read as stored.
49    Whole,
50}
51
52fn checked(value: &Value, ty: &TypeDesc, form: Form) -> Result<Value, Misfit> {
53    let result = match nul_at(value) {
54        Some(at) => Err((at, "text containing NUL (\\0) can't be stored".to_owned())),
55        None => stored(value, ty, form),
56    };
57    result.map_err(|(path, why)| Misfit { path, why })
58}
59
60/// A value that doesn't fit its type. `why` doesn't quote the value; `path` names where.
61#[derive(Debug, Clone, PartialEq, Eq)]
62pub struct Misfit {
63    /// Where in the parameters, outermost first (`config`, `"limits"`, `0`); empty for the
64    /// whole.
65    pub path: Vec<Step>,
66    /// Why (`not an ISO 8601 duration`).
67    pub why: String,
68}
69
70/// A step into a value: a field or key, or a list's index.
71#[derive(Debug, Clone, PartialEq, Eq)]
72pub enum Step {
73    /// A field of an object, or a key of a dict.
74    Key(String),
75    /// An element of a list or tuple.
76    Index(usize),
77}
78
79impl Misfit {
80    /// The field names and keys along the path, as given (`api.key` stays one).
81    pub fn fields(&self) -> impl Iterator<Item = &str> {
82        self.path.iter().filter_map(|step| match step {
83            Step::Key(key) => Some(key.as_str()),
84            Step::Index(_) => None,
85        })
86    }
87
88    /// The path as written (`config.limits[0]`); empty for the whole.
89    #[must_use]
90    pub fn at(&self) -> String {
91        let mut at = String::new();
92        for step in &self.path {
93            match step {
94                Step::Key(key) => {
95                    if !at.is_empty() {
96                        at.push('.');
97                    }
98                    at.push_str(key);
99                }
100                Step::Index(i) => {
101                    at.push('[');
102                    at.push_str(&i.to_string());
103                    at.push(']');
104                }
105            }
106        }
107        at
108    }
109}
110
111impl std::fmt::Display for Misfit {
112    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
113        if self.path.is_empty() {
114            f.write_str(&self.why)
115        } else {
116            write!(f, "`{}`: {}", self.at(), self.why)
117        }
118    }
119}
120
121impl std::error::Error for Misfit {}
122
123/// A problem, with where in the value it is.
124type Problem = (Vec<Step>, String);
125
126fn misfit(why: impl Into<String>) -> Problem {
127    (Vec::new(), why.into())
128}
129
130/// Where a text or a key containing NUL is (no store keeps one: Postgres refuses it in JSON,
131/// the database layer replaces it (decision 114), and the runner refuses to decode it).
132#[must_use]
133pub fn nul_at(value: &Value) -> Option<Vec<Step>> {
134    match value {
135        Value::String(text) if text.contains('\0') => Some(Vec::new()),
136        Value::Array(items) => items.iter().enumerate().find_map(|(i, v)| {
137            nul_at(v).map(|mut path| {
138                path.insert(0, Step::Index(i));
139                path
140            })
141        }),
142        Value::Object(object) => object.iter().find_map(|(k, v)| {
143            if k.contains('\0') {
144                // The key itself can't be named: it is the text refused.
145                return Some(Vec::new());
146            }
147            nul_at(v).map(|mut path| {
148                path.insert(0, Step::Key(k.clone()));
149                path
150            })
151        }),
152        _ => None,
153    }
154}
155
156fn stored(value: &Value, ty: &TypeDesc, form: Form) -> Result<Value, Problem> {
157    match ty {
158        TypeDesc::Any | TypeDesc::Model { .. } => Ok(escape_tags(value)),
159        TypeDesc::None if value.is_null() => Ok(Value::Null),
160        TypeDesc::Bool if value.is_boolean() => Ok(value.clone()),
161        TypeDesc::Int if value.is_i64() || value.is_u64() => Ok(value.clone()),
162        // `3.0`: JSON Schema's `integer` takes a whole number written with a fraction.
163        TypeDesc::Int if let Some(number) = whole(value) => Ok(Value::from(number)),
164        TypeDesc::Float if value.is_number() => Ok(value.clone()),
165        TypeDesc::Str if value.is_string() => Ok(value.clone()),
166        TypeDesc::Datetime => text(value, "a date and time").and_then(|t| {
167            t.parse::<jiff::Timestamp>()
168                .map_err(|_| misfit("not a date and time with an offset (RFC 3339)"))
169                .and_then(|_| python_year(t))
170                .map(|()| json!({"$datetime": t}))
171        }),
172        TypeDesc::Date => text(value, "a date").and_then(|t| {
173            t.parse::<jiff::civil::Date>()
174                .map_err(|_| misfit("not a date (YYYY-MM-DD)"))
175                .and_then(|_| python_year(t))
176                .map(|()| json!({"$date": t}))
177        }),
178        TypeDesc::Timedelta => text(value, "a duration").and_then(|t| {
179            duration_micros(t)
180                .map(|micros| json!({"$timedelta": micros}))
181                .map_err(misfit)
182        }),
183        TypeDesc::List { item } => {
184            let items = array(value)?;
185            Ok(Value::Array(elements(items, |_| item, form)?))
186        }
187        TypeDesc::Tuple { items: types } => {
188            let items = array(value)?;
189            if items.len() != types.len() {
190                return Err(misfit(format!(
191                    "expected {} elements, got {}",
192                    types.len(),
193                    items.len()
194                )));
195            }
196            Ok(json!({"$tuple": elements(items, |i| &types[i], form)?}))
197        }
198        TypeDesc::Dict { value: item } => {
199            let object = object(value)?;
200            let mut out = Map::new();
201            for (key, v) in object {
202                out.insert(
203                    key.clone(),
204                    within(stored(v, item, form), Step::Key(key.clone()))?,
205                );
206            }
207            Ok(escaped(out))
208        }
209        TypeDesc::Literal { values } if values.contains(value) => Ok(value.clone()),
210        // A type that checks the value first: a model or `Any` takes anything, and would keep a
211        // tuple or a date untagged.
212        TypeDesc::Union { variants } => variants
213            .iter()
214            .filter(|v| !matches!(v, TypeDesc::Any | TypeDesc::Model { .. }))
215            .chain(
216                variants
217                    .iter()
218                    .filter(|v| matches!(v, TypeDesc::Any | TypeDesc::Model { .. })),
219            )
220            .find_map(|v| stored(value, v, form).ok())
221            .ok_or_else(|| misfit(format!("{} fits none of its types", kind_of(value)))),
222        TypeDesc::TypedDict { fields, .. } | TypeDesc::Dataclass { fields, .. } => {
223            let object = object(value)?;
224            let mut out = Map::new();
225            for (key, v) in object {
226                let field = fields
227                    .iter()
228                    .find(|f| &f.name == key)
229                    .ok_or_else(|| misfit(format!("unknown field `{key}`")))?;
230                out.insert(
231                    key.clone(),
232                    within(stored(v, &field.ty, form), Step::Key(key.clone()))?,
233                );
234            }
235            let whole = form == Form::Whole && matches!(ty, TypeDesc::Dataclass { .. });
236            if let Some(missing) = fields
237                .iter()
238                .find(|f| (f.required || whole) && !out.contains_key(&f.name))
239            {
240                return Err(misfit(format!("`{}` is required", missing.name)));
241            }
242            Ok(escaped(out))
243        }
244        TypeDesc::ProcessResult => Err(misfit("a command's result can't be a parameter")),
245        TypeDesc::None
246        | TypeDesc::Bool
247        | TypeDesc::Int
248        | TypeDesc::Float
249        | TypeDesc::Str
250        | TypeDesc::Literal { .. } => Err(misfit(format!(
251            "expected {}, got {}",
252            expected(ty),
253            kind_of(value)
254        ))),
255    }
256}
257
258/// Text that starts with a year Python's `date` and `datetime` read: four digits, 0001 to
259/// 9999 (not `+002026`, nor year 0).
260fn python_year(text: &str) -> Result<(), Problem> {
261    let year = text
262        .get(..4)
263        .filter(|y| y.bytes().all(|b| b.is_ascii_digit()))
264        .and_then(|y| y.parse::<u16>().ok());
265    match year {
266        Some(1..=9999) if text.as_bytes().get(4) == Some(&b'-') => Ok(()),
267        _ => Err(misfit(
268            "a year Python can't read: four digits, 0001 to 9999",
269        )),
270    }
271}
272
273/// A number with no fraction (`3.0`) as an integer, if it fits one.
274fn whole(value: &Value) -> Option<i64> {
275    // Up to 2^53, where every whole number is exact.
276    const EXACT: f64 = 9_007_199_254_740_992.0;
277    let number = value.as_f64().filter(|n| n.fract() == 0.0)?;
278    #[expect(
279        clippy::cast_possible_truncation,
280        reason = "a whole number, checked in range"
281    )]
282    (-EXACT..=EXACT).contains(&number).then_some(number as i64)
283}
284
285fn within(result: Result<Value, Problem>, step: Step) -> Result<Value, Problem> {
286    result.map_err(|(mut path, why)| {
287        path.insert(0, step);
288        (path, why)
289    })
290}
291
292fn elements<'t>(
293    items: &[Value],
294    ty: impl Fn(usize) -> &'t TypeDesc,
295    form: Form,
296) -> Result<Vec<Value>, Problem> {
297    items
298        .iter()
299        .enumerate()
300        .map(|(i, v)| within(stored(v, ty(i), form), Step::Index(i)))
301        .collect()
302}
303
304fn text<'v>(value: &'v Value, what: &str) -> Result<&'v str, Problem> {
305    value
306        .as_str()
307        .ok_or_else(|| misfit(format!("expected {what} as text, got {}", kind_of(value))))
308}
309
310fn array(value: &Value) -> Result<&Vec<Value>, Problem> {
311    value
312        .as_array()
313        .ok_or_else(|| misfit(format!("expected a list, got {}", kind_of(value))))
314}
315
316fn object(value: &Value) -> Result<&Map<String, Value>, Problem> {
317    value
318        .as_object()
319        .ok_or_else(|| misfit(format!("expected an object, got {}", kind_of(value))))
320}
321
322/// An ISO 8601 duration (`P1DT2H`, `PT0.5S`, `-PT1M`, `P1W`) in whole microseconds, a day
323/// being 24 hours and a week 7 days (decision 139).
324///
325/// # Errors
326///
327/// Why it isn't one, without quoting it: not ISO 8601, in years or months (they aren't fixed
328/// lengths), or too long.
329pub fn duration_micros(text: &str) -> Result<i64, &'static str> {
330    let span = jiff::fmt::temporal::SpanParser::new()
331        .parse_span(text)
332        .map_err(|_| "not an ISO 8601 duration (e.g. PT1H30M, P1DT0.5S)")?;
333    if span.get_years() != 0 || span.get_months() != 0 {
334        return Err(
335            "a duration in years or months, which vary: give it in weeks, days, hours, minutes \
336             and seconds",
337        );
338    }
339    let micros = i128::from(span.get_weeks()) * 7 * DAY_MICROS
340        + i128::from(span.get_days()) * DAY_MICROS
341        + i128::from(span.get_hours()) * 3_600_000_000
342        + i128::from(span.get_minutes()) * 60_000_000
343        + i128::from(span.get_seconds()) * 1_000_000
344        + i128::from(span.get_milliseconds()) * 1000
345        + i128::from(span.get_microseconds())
346        + i128::from(span.get_nanoseconds()) / 1000;
347    i64::try_from(micros).map_err(|_| "a duration too long to store")
348}
349
350/// A dict stored escaped when its only key would read as a tag (B66).
351#[must_use]
352pub fn escaped(object: Map<String, Value>) -> Value {
353    if object.len() == 1 && object.keys().all(|k| TAGS.contains(&k.as_str())) {
354        json!({ "$dict": object })
355    } else {
356        Value::Object(object)
357    }
358}
359
360/// Every dict shaped like a tag escaped, at any depth (a model's or `Any`'s data).
361#[must_use]
362pub fn escape_tags(value: &Value) -> Value {
363    match value {
364        Value::Array(items) => Value::Array(items.iter().map(escape_tags).collect()),
365        Value::Object(object) => escaped(
366            object
367                .iter()
368                .map(|(k, v)| (k.clone(), escape_tags(v)))
369                .collect(),
370        ),
371        other => other.clone(),
372    }
373}
374
375fn kind_of(value: &Value) -> &'static str {
376    match value {
377        Value::Null => "null",
378        Value::Bool(_) => "a boolean",
379        Value::Number(n) if n.is_f64() => "a number",
380        Value::Number(_) => "an integer",
381        Value::String(_) => "text",
382        Value::Array(_) => "a list",
383        Value::Object(_) => "an object",
384    }
385}
386
387const fn expected(ty: &TypeDesc) -> &'static str {
388    match ty {
389        TypeDesc::None => "null",
390        TypeDesc::Bool => "a boolean",
391        TypeDesc::Int => "an integer",
392        TypeDesc::Float => "a number",
393        TypeDesc::Str => "text",
394        TypeDesc::Literal { .. } => "one of its values",
395        _ => "another type",
396    }
397}
398
399/// Stored parameters as JSON, for showing them: dates and times as ISO 8601 text, a duration
400/// as an ISO 8601 duration, a tuple as a list, an escaped dict unwrapped (what
401/// `--params` takes).
402#[must_use]
403pub fn shown(stored: &Value) -> Value {
404    match stored {
405        Value::Array(items) => Value::Array(items.iter().map(shown).collect()),
406        Value::Object(object) if object.len() == 1 => {
407            let (tag, inner) = object.iter().next().unwrap_or_else(|| unreachable!());
408            match (tag.as_str(), inner) {
409                ("$datetime" | "$date", Value::String(_)) => inner.clone(),
410                ("$tuple", Value::Array(_)) | ("$dict", Value::Object(_)) => shown_fields(inner),
411                ("$timedelta", Value::Number(n)) if n.is_i64() => {
412                    Value::String(iso_duration(n.as_i64().unwrap_or_default()))
413                }
414                _ => shown_fields(stored),
415            }
416        }
417        _ => shown_fields(stored),
418    }
419}
420
421fn shown_fields(value: &Value) -> Value {
422    match value {
423        Value::Array(items) => Value::Array(items.iter().map(shown).collect()),
424        Value::Object(object) => {
425            Value::Object(object.iter().map(|(k, v)| (k.clone(), shown(v))).collect())
426        }
427        other => other.clone(),
428    }
429}
430
431/// Microseconds as the Python layer writes a duration for Pydantic (`P1DT3600.000000S`).
432fn iso_duration(micros: i64) -> String {
433    let sign = if micros < 0 { "-" } else { "" };
434    let all = i128::from(micros).abs();
435    let (days, rest) = (all / DAY_MICROS, all % DAY_MICROS);
436    format!(
437        "{sign}P{days}DT{}.{:06}S",
438        rest / 1_000_000,
439        rest % 1_000_000
440    )
441}