1use 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
21pub const SHELL: &str = "/bin/sh";
23
24#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
26pub enum RenderError {
27 #[error("the output of `{0}` isn't among the task's inputs")]
29 MissingInput(String),
30 #[error("`{0}` doesn't exist in the upstream output")]
32 MissingPath(String),
33 #[error("`{0}` was truncated (over the output size limit); read the whole ProcessResult")]
35 Truncated(String),
36 #[error("`{reference}` is {kind}, which can't be rendered into text")]
38 NotRenderable {
39 reference: String,
41 kind: &'static str,
43 },
44 #[error("`{reference}`: the format spec `:{spec}` doesn't apply: {reason}")]
46 BadFormat {
47 reference: String,
49 spec: String,
51 reason: String,
53 },
54 #[error("`{0}` wasn't fetched for this attempt")]
56 MissingSecret(String),
57 #[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#[derive(Debug, Clone, PartialEq, Default)]
67pub struct RenderContext {
68 pub dag_ctx: BTreeMap<DagCtxField, Value>,
70 pub params: Value,
72 pub inputs: BTreeMap<String, Value>,
74 pub outcomes: BTreeMap<String, Value>,
78 pub secrets: BTreeMap<SecretName, Value>,
81}
82
83static NOT_TAKEN: Value = Value::Null;
85
86impl RenderContext {
87 #[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 #[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#[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
149fn 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
164pub 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 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
206fn 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 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
246fn 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#[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
297fn 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
311pub 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 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
376pub 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
399pub 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 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
436pub 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}