Skip to main content

schedr_agent/
render.rs

1//! Rendering templates and command lines: references filled in from the run's inputs and
2//! context, values written as text the same way the Python API writes literals.
3//!
4//! A shell command takes no references (decision 99): a value in shell source can run as code
5//! whatever the quoting, so values reach a shell program as arguments or environment variables.
6
7use std::collections::BTreeMap;
8use std::fmt::Write as _;
9
10use jiff::civil::Time;
11use jiff::fmt::temporal::Pieces;
12use jiff::tz::TimeZone;
13use schedr_model::{
14    CommandLine, DagCtxField, PathElem, Reference, SecretName, Template, TemplatePart,
15};
16use serde_json::{Value, json};
17
18#[cfg(test)]
19mod tests;
20
21/// The program that runs shell commands.
22pub const SHELL: &str = "/bin/sh";
23
24/// Why a template can't be rendered.
25#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
26pub enum RenderError {
27    /// The task's inputs don't include an upstream output it references.
28    #[error("the output of `{0}` isn't among the task's inputs")]
29    MissingInput(String),
30    /// A path doesn't exist in the upstream output.
31    #[error("`{0}` doesn't exist in the upstream output")]
32    MissingPath(String),
33    /// The referenced stream was truncated; partial data is never used silently.
34    #[error("`{0}` was truncated (over the output size limit); read the whole ProcessResult")]
35    Truncated(String),
36    /// A value that can't be written as text (None, a list, an object).
37    #[error("`{reference}` is {kind}, which can't be rendered into text")]
38    NotRenderable {
39        /// The reference.
40        reference: String,
41        /// What the value is.
42        kind: &'static str,
43    },
44    /// A format spec that doesn't fit the value.
45    #[error("`{reference}`: the format spec `:{spec}` doesn't apply: {reason}")]
46    BadFormat {
47        /// The reference.
48        reference: String,
49        /// The spec.
50        spec: String,
51        /// Why.
52        reason: String,
53    },
54    /// A secret that wasn't fetched for the attempt.
55    #[error("`{0}` wasn't fetched for this attempt")]
56    MissingSecret(String),
57    /// A shell command with a reference: refused, as the master and the Python API refuse it.
58    #[error(
59        "`{0}` in a shell command: the shell would read the value as code (pass values as \
60         arguments or in `env`)"
61    )]
62    ShellPlaceholder(String),
63}
64
65/// What references are filled in from.
66#[derive(Debug, Clone, PartialEq, Default)]
67pub struct RenderContext {
68    /// The run's context fields, as stored JSON (`planned_for` / `since` tagged).
69    pub dag_ctx: BTreeMap<DagCtxField, Value>,
70    /// The run's parameters, as stored JSON (decision 138); `{}` when the DAG takes none.
71    pub params: Value,
72    /// The upstream outputs the task uses, by task ID, as stored JSON.
73    pub inputs: BTreeMap<String, Value>,
74    /// The outcomes of the upstream tasks it uses, by task ID, as JSON strings; `null` for one
75    /// that was skipped (each of its edges counts as not taken). A task missing here is
76    /// neither: its reference fails as a missing input.
77    pub outcomes: BTreeMap<String, Value>,
78    /// The secrets fetched for the attempt, by name: a key's value as a string, a whole
79    /// secret as an object of key to value.
80    pub secrets: BTreeMap<SecretName, Value>,
81}
82
83/// What a reference stands for when its edge wasn't taken (the data rule: `None`).
84static NOT_TAKEN: Value = Value::Null;
85
86impl RenderContext {
87    /// A context with the run's fields; `planned_for` and `since` are RFC 3339 instants.
88    #[must_use]
89    pub fn new(dag_id: &str, run_id: &str, run_kind: &str, planned_for: &str, since: &str) -> Self {
90        Self {
91            dag_ctx: BTreeMap::from([
92                (DagCtxField::DagId, json!(dag_id)),
93                (DagCtxField::RunId, json!(run_id)),
94                (DagCtxField::RunKind, json!(run_kind)),
95                (DagCtxField::PlannedFor, json!({"$datetime": planned_for})),
96                (DagCtxField::Since, json!({"$datetime": since})),
97            ]),
98            params: json!({}),
99            inputs: BTreeMap::new(),
100            outcomes: BTreeMap::new(),
101            secrets: BTreeMap::new(),
102        }
103    }
104
105    /// With the event that started the run, for those of its tasks that read `dag_ctx.event`.
106    #[must_use]
107    pub fn with_event(mut self, event: &schedr_model::RunEvent, planned_for: &str) -> Self {
108        let at = event
109            .at
110            .map_or_else(|| planned_for.to_owned(), |at| at.to_string());
111        self.dag_ctx.insert(DagCtxField::EventKey, json!(event.key));
112        self.dag_ctx
113            .insert(DagCtxField::EventData, event.data.clone());
114        self.dag_ctx
115            .insert(DagCtxField::EventAt, json!({"$datetime": at}));
116        self
117    }
118}
119
120/// A reference as written in the DAG file, for messages (`extract.rows[0]`).
121#[must_use]
122pub fn reference_label(reference: &Reference) -> String {
123    match reference {
124        Reference::DagCtx {
125            field: DagCtxField::DagId,
126        } => "dag_ctx.dag_id".to_owned(),
127        Reference::DagCtx {
128            field: field @ (DagCtxField::EventKey | DagCtxField::EventData | DagCtxField::EventAt),
129        } => {
130            let name = serde_json::to_value(field).unwrap_or_default();
131            let name = name
132                .as_str()
133                .unwrap_or_default()
134                .trim_start_matches("event_");
135            format!("dag_ctx.event.{name}")
136        }
137        Reference::DagCtx { field } => {
138            let name = serde_json::to_value(field).unwrap_or_default();
139            let name = name.as_str().unwrap_or_default().trim_start_matches("run_");
140            format!("dag_ctx.run.{name}")
141        }
142        Reference::Outcome { task } => format!("{task}.outcome"),
143        Reference::Param { path } => with_path("dag_ctx.params".to_owned(), path),
144        Reference::Output { task, path, .. } => with_path(task.to_string(), path),
145        Reference::Secret(name) => name.to_string(),
146    }
147}
148
149/// `label` followed by a path as written in Python (`.rows[0]`).
150fn with_path(mut label: String, path: &[PathElem]) -> String {
151    for step in path {
152        match step {
153            PathElem::Field(name) => {
154                let _ = write!(label, ".{name}");
155            }
156            PathElem::Index(i) => {
157                let _ = write!(label, "[{i}]");
158            }
159        }
160    }
161    label
162}
163
164/// The stored value a reference stands for.
165///
166/// # Errors
167///
168/// Returns a [`RenderError`] for a missing input or path, or a truncated stream.
169pub fn resolve<'a>(
170    reference: &Reference,
171    ctx: &'a RenderContext,
172) -> Result<&'a Value, RenderError> {
173    match reference {
174        Reference::DagCtx { field } => ctx
175            .dag_ctx
176            .get(field)
177            .ok_or_else(|| RenderError::MissingInput(reference_label(reference))),
178        Reference::Param { path } => follow(&ctx.params, path, reference),
179        Reference::Secret(name) => ctx
180            .secrets
181            .get(name)
182            .ok_or_else(|| RenderError::MissingSecret(name.to_string())),
183        Reference::Outcome { task } => match ctx.outcomes.get(task.as_str()) {
184            Some(Value::Null) => Ok(&NOT_TAKEN),
185            Some(outcome) => Ok(outcome),
186            None => Err(RenderError::MissingInput(reference_label(reference))),
187        },
188        Reference::Output { task, path, on } => {
189            match ctx.outcomes.get(task.as_str()) {
190                // Skipped: every edge from it counts as not taken.
191                Some(Value::Null) => return Ok(&NOT_TAKEN),
192                Some(Value::String(outcome)) if !on.is_empty() && !on.contains(outcome) => {
193                    return Ok(&NOT_TAKEN);
194                }
195                _ => {}
196            }
197            let value = ctx
198                .inputs
199                .get(task.as_str())
200                .ok_or_else(|| RenderError::MissingInput(task.to_string()))?;
201            follow(value, path, reference)
202        }
203    }
204}
205
206/// The part of a stored value at `path` (`reference`'s, for messages).
207fn follow<'a>(
208    mut value: &'a Value,
209    path: &[PathElem],
210    reference: &Reference,
211) -> Result<&'a Value, RenderError> {
212    for step in path {
213        let missing = || RenderError::MissingPath(reference_label(reference));
214        value = match step {
215            PathElem::Field(name) => {
216                let mut object = value.as_object().ok_or_else(missing)?;
217                // A dict shaped like a tag is stored escaped (B66).
218                if object.len() == 1
219                    && let Some(Value::Object(inner)) = object.get("$dict")
220                {
221                    object = inner;
222                }
223                if is_process_result(object)
224                    && object.get(&format!("{name}_truncated")) == Some(&Value::Bool(true))
225                {
226                    return Err(RenderError::Truncated(reference_label(reference)));
227                }
228                object.get(name).ok_or_else(missing)?
229            }
230            PathElem::Index(i) => {
231                let items = value
232                    .get("$tuple")
233                    .unwrap_or(value)
234                    .as_array()
235                    .ok_or_else(missing)?;
236                usize::try_from(*i)
237                    .ok()
238                    .and_then(|i| items.get(i))
239                    .ok_or_else(missing)?
240            }
241        };
242    }
243    Ok(value)
244}
245
246/// Whether `object` is a stored `ProcessResult`: only its streams are ever truncated, a
247/// user's `<field>_truncated` is data (B75).
248fn is_process_result(object: &serde_json::Map<String, Value>) -> bool {
249    const FIELDS: [&str; 5] = [
250        "stdout",
251        "stderr",
252        "exit_code",
253        "stdout_truncated",
254        "stderr_truncated",
255    ];
256    object.len() == FIELDS.len() && FIELDS.iter().all(|f| object.contains_key(*f))
257}
258
259/// A float written like Python's `str()` (`1.0`, `1.5`, `1e+20`, `1e-05`).
260#[must_use]
261pub fn python_float(value: f64) -> String {
262    if value.is_nan() {
263        return "nan".to_owned();
264    }
265    if value.is_infinite() {
266        return if value > 0.0 {
267            "inf".to_owned()
268        } else {
269            "-inf".to_owned()
270        };
271    }
272    let scientific = format!("{value:e}");
273    let (mantissa, exponent) = scientific.split_once('e').unwrap_or((&scientific, "0"));
274    let exponent: i32 = exponent.parse().unwrap_or(0);
275    if (-4..16).contains(&exponent) {
276        let text = format!("{value}");
277        if text.contains('.') {
278            text
279        } else {
280            format!("{text}.0")
281        }
282    } else {
283        let sign = if exponent < 0 { '-' } else { '+' };
284        format!("{mantissa}e{sign}{:02}", exponent.abs())
285    }
286}
287
288fn kind_of(value: &Value) -> &'static str {
289    match value {
290        Value::Null => "None",
291        Value::Array(_) => "a list",
292        Value::Object(_) => "an object",
293        _ => "a value",
294    }
295}
296
297/// A date-time or date from its stored text, in its own offset (midnight for a date).
298fn zoned(text: &str, is_date: bool) -> Option<jiff::Zoned> {
299    let pieces = Pieces::parse(text).ok()?;
300    let offset = if is_date {
301        jiff::tz::Offset::UTC
302    } else {
303        pieces.offset()?.to_numeric_offset()
304    };
305    let datetime = pieces
306        .date()
307        .to_datetime(pieces.time().unwrap_or(Time::midnight()));
308    TimeZone::fixed(offset).to_zoned(datetime).ok()
309}
310
311/// A stored value as text.
312///
313/// # Errors
314///
315/// Returns [`RenderError::NotRenderable`] for None, lists and objects, or
316/// [`RenderError::BadFormat`] for a spec that doesn't fit (strftime only on dates and times).
317pub fn to_text(value: &Value, spec: Option<&str>, label: &str) -> Result<String, RenderError> {
318    let spec = spec.filter(|s| !s.is_empty());
319    let bad = |reason: &str| RenderError::BadFormat {
320        reference: label.to_owned(),
321        spec: spec.unwrap_or_default().to_owned(),
322        reason: reason.to_owned(),
323    };
324    if let Some(object) = value.as_object()
325        && object.len() == 1
326    {
327        if let Some(Value::String(text)) = object.get("$datetime").or_else(|| object.get("$date")) {
328            let is_date = object.contains_key("$date");
329            return match spec {
330                None => Ok(text.clone()),
331                Some(pattern) => {
332                    let moment =
333                        zoned(text, is_date).ok_or_else(|| bad("the stored date is invalid"))?;
334                    jiff::fmt::strtime::format(pattern, &moment).map_err(|e| bad(&e.to_string()))
335                }
336            };
337        }
338        // As i64 or u64: Python stores up to 2**64 - 1 microseconds (B77).
339        let micros = object.get("$timedelta").and_then(|v| {
340            v.as_i64()
341                .map(i128::from)
342                .or_else(|| v.as_u64().map(i128::from))
343        });
344        if let Some(micros) = micros {
345            if spec.is_some() {
346                return Err(bad("durations are written as seconds"));
347            }
348            let (seconds, rest) = (micros / 1_000_000, micros % 1_000_000);
349            return Ok(if rest == 0 {
350                seconds.to_string()
351            } else {
352                #[expect(
353                    clippy::cast_precision_loss,
354                    reason = "a duration's seconds as a float"
355                )]
356                python_float(micros as f64 / 1_000_000.0)
357            });
358        }
359    }
360    if spec.is_some() {
361        return Err(bad("only dates and times take a format spec"));
362    }
363    match value {
364        Value::String(text) => Ok(text.clone()),
365        Value::Bool(true) => Ok("True".to_owned()),
366        Value::Bool(false) => Ok("False".to_owned()),
367        Value::Number(n) if n.is_f64() => Ok(python_float(n.as_f64().unwrap_or_default())),
368        Value::Number(n) => Ok(n.to_string()),
369        _ => Err(RenderError::NotRenderable {
370            reference: label.to_owned(),
371            kind: kind_of(value),
372        }),
373    }
374}
375
376/// Renders a template, each reference written as text.
377///
378/// # Errors
379///
380/// Returns a [`RenderError`] if a reference can't be resolved or written as text.
381pub fn render(template: &Template, ctx: &RenderContext) -> Result<String, RenderError> {
382    let mut out = String::new();
383    for part in &template.0 {
384        match part {
385            TemplatePart::Text(text) => out.push_str(text),
386            TemplatePart::Ref(r) => {
387                let label = reference_label(&r.reference);
388                let text = to_text(resolve(&r.reference, ctx)?, r.format.as_deref(), &label)?;
389                match r.encode {
390                    Some(encoding) => out.push_str(&encoding.apply(&text)),
391                    None => out.push_str(&text),
392                }
393            }
394        }
395    }
396    Ok(out)
397}
398
399/// A value's stored JSON, its references and templates filled in: what a connection's
400/// parameter gets (decision 174), decoded by its type where it is used. A dict that would
401/// read as a tag is escaped, as the Python codec stores it (B66).
402///
403/// # Errors
404///
405/// Returns a [`RenderError`] if a reference can't be resolved or a template rendered.
406pub fn resolve_value(
407    value: &schedr_model::Value,
408    ctx: &RenderContext,
409) -> Result<Value, RenderError> {
410    use schedr_model::Value as Stored;
411    Ok(match value {
412        Stored::Literal(literal) => literal.clone(),
413        Stored::Ref(reference) => match resolve(reference, ctx)? {
414            // A whole secret, keys to values: a plain dict.
415            Value::Object(keys) if matches!(reference, Reference::Secret(_)) => {
416                schedr_model::params::escaped(keys.clone())
417            }
418            resolved => resolved.clone(),
419        },
420        Stored::Template(template) => Value::String(render(template, ctx)?),
421        Stored::List(items) => Value::Array(
422            items
423                .iter()
424                .map(|item| resolve_value(item, ctx))
425                .collect::<Result<_, _>>()?,
426        ),
427        Stored::Map(entries) => schedr_model::params::escaped(
428            entries
429                .iter()
430                .map(|(key, item)| Ok((key.clone(), resolve_value(item, ctx)?)))
431                .collect::<Result<_, RenderError>>()?,
432        ),
433    })
434}
435
436/// The program and arguments of a command line.
437///
438/// A shell command runs as `/bin/sh -c <text>`; an argument list renders each element, the
439/// first being the program.
440///
441/// # Errors
442///
443/// Returns a [`RenderError`] if a template can't be rendered, or for a shell command with a
444/// reference.
445pub fn command_line(
446    command: &CommandLine,
447    ctx: &RenderContext,
448) -> Result<(String, Vec<String>), RenderError> {
449    match command {
450        CommandLine::Shell(template) => {
451            if let Some(TemplatePart::Ref(r)) = template
452                .0
453                .iter()
454                .find(|p| matches!(p, TemplatePart::Ref(_)))
455            {
456                return Err(RenderError::ShellPlaceholder(reference_label(&r.reference)));
457            }
458            Ok((
459                SHELL.to_owned(),
460                vec!["-c".to_owned(), render(template, ctx)?],
461            ))
462        }
463        CommandLine::Argv(templates) => {
464            let mut args = templates
465                .iter()
466                .map(|t| render(t, ctx))
467                .collect::<Result<Vec<_>, _>>()?;
468            let program = if args.is_empty() {
469                String::new()
470            } else {
471                args.remove(0)
472            };
473            Ok((program, args))
474        }
475    }
476}