Skip to main content

schedr_model/
value.rs

1//! Values in DAG JSON: references, templates and task arguments.
2//!
3//! Python records everything the DAG body declared as plain data: literal values, references to
4//! upstream outputs or the run's context, and t-strings as literal text plus references (see
5//! archive/PROJECT.md, Airflow compatibility, Scope: Templating). The agent and the runner fill
6//! them in at run time.
7
8use std::collections::BTreeMap;
9use std::fmt::Write as _;
10
11use schemars::JsonSchema;
12use serde::{Deserialize, Serialize};
13
14use crate::ids::TaskId;
15use crate::secret::SecretName;
16
17#[cfg(test)]
18mod tests;
19
20/// One step of a path into an output: a field or key, or a list / tuple index.
21#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
22#[serde(untagged)]
23pub enum PathElem {
24    /// A dataclass field or dictionary key.
25    Field(String),
26    /// A list or tuple index.
27    Index(u64),
28}
29
30/// A field of the run's context, `dag_ctx.run.*` and `dag_ctx.dag_id`.
31#[derive(
32    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, JsonSchema,
33)]
34#[serde(rename_all = "snake_case")]
35pub enum DagCtxField {
36    /// `dag_ctx.run.id`.
37    RunId,
38    /// `dag_ctx.run.kind`.
39    RunKind,
40    /// `dag_ctx.run.planned_for`.
41    PlannedFor,
42    /// `dag_ctx.run.since`.
43    Since,
44    /// `dag_ctx.dag_id`.
45    DagId,
46    /// `dag_ctx.event.key`.
47    EventKey,
48    /// `dag_ctx.event.data`.
49    EventData,
50    /// `dag_ctx.event.at`.
51    EventAt,
52}
53
54/// A reference to data known only at run time.
55#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
56#[serde(tag = "kind", rename_all = "snake_case")]
57pub enum Reference {
58    /// An upstream task's output, or a part of it.
59    Output {
60        /// The upstream task.
61        task: TaskId,
62        /// The path into the output; empty for the whole output.
63        #[serde(default, skip_serializing_if = "Vec::is_empty")]
64        path: Vec<PathElem>,
65        /// The outcomes it was narrowed to (`.on(...)`); empty for any. On another outcome,
66        /// or a skipped upstream task, it stands for `null`.
67        #[serde(default, skip_serializing_if = "Vec::is_empty")]
68        on: Vec<String>,
69    },
70    /// An upstream task's outcome itself (`.outcome`), as its name.
71    Outcome {
72        /// The upstream task.
73        task: TaskId,
74    },
75    /// A field of the run's context.
76    DagCtx {
77        /// Which field.
78        field: DagCtxField,
79    },
80    /// The run's parameters, or a part of them (`dag_ctx.params.region`, decision 138).
81    Param {
82        /// The path into the parameters; empty for all of them.
83        #[serde(default, skip_serializing_if = "Vec::is_empty")]
84        path: Vec<PathElem>,
85    },
86    /// A secret from a secret storage (`secrets['etl/db']['password']`), fetched by the agent
87    /// that runs the task, never by the master (see archive/PROJECT.md, Secret storage).
88    Secret(SecretName),
89}
90
91impl Reference {
92    /// The upstream task this reference depends on, if any.
93    #[must_use]
94    pub fn upstream_task(&self) -> Option<&TaskId> {
95        match self {
96            Self::Output { task, .. } | Self::Outcome { task } => Some(task),
97            Self::DagCtx { .. } | Self::Param { .. } | Self::Secret { .. } => None,
98        }
99    }
100}
101
102/// A reference inside a template, with its optional format spec (e.g. `%Y-%m-%d`).
103#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
104pub struct TemplateRef {
105    /// What is filled in.
106    #[serde(flatten)]
107    pub reference: Reference,
108    /// The t-string format spec, if any.
109    #[serde(default, skip_serializing_if = "Option::is_none")]
110    pub format: Option<String>,
111    /// How the text is written into the template, if not as it is (decision 188).
112    #[serde(default, skip_serializing_if = "Option::is_none")]
113    pub encode: Option<Encoding>,
114}
115
116/// How a reference's text is written into its template.
117#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
118#[serde(rename_all = "snake_case")]
119pub enum Encoding {
120    /// Percent-encoded, every byte but RFC 3986's unreserved ones (`A-Z a-z 0-9 - . _ ~`):
121    /// a value in a URL (a typed connection's) is only the text it stands for, never the
122    /// URL's structure (another host, a query).
123    Url,
124}
125
126impl Encoding {
127    /// `text` written this way.
128    #[must_use]
129    pub fn apply(self, text: &str) -> String {
130        match self {
131            Self::Url => {
132                let mut out = String::with_capacity(text.len());
133                for byte in text.bytes() {
134                    if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~') {
135                        out.push(char::from(byte));
136                    } else {
137                        let _ = write!(out, "%{byte:02X}"); // writing to a `String` can't fail
138                    }
139                }
140                out
141            }
142        }
143    }
144}
145
146/// One part of a template: literal text, or a reference filled in at run time.
147#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
148#[serde(rename_all = "snake_case", deny_unknown_fields)]
149pub enum TemplatePart {
150    /// Literal text.
151    Text(String),
152    /// A reference, rendered at run time.
153    Ref(TemplateRef),
154}
155
156/// A t-string as data: its parts in order.
157#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize, JsonSchema)]
158#[serde(transparent)]
159pub struct Template(pub Vec<TemplatePart>);
160
161impl Template {
162    /// A template that is only literal text.
163    #[must_use]
164    pub fn text(text: impl Into<String>) -> Self {
165        Self(vec![TemplatePart::Text(text.into())])
166    }
167
168    /// The references in this template, in order.
169    pub fn references(&self) -> impl Iterator<Item = &Reference> {
170        self.0.iter().filter_map(|part| match part {
171            TemplatePart::Text(_) => None,
172            TemplatePart::Ref(r) => Some(&r.reference),
173        })
174    }
175}
176
177/// A task argument: a literal, a reference, a template, or a container of values (so
178/// references inside lists and dictionaries stay visible).
179#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
180#[serde(rename_all = "snake_case", deny_unknown_fields)]
181pub enum Value {
182    /// A JSON value as encoded by the Python API (with tagged extra types such as
183    /// `{"$datetime": "..."}`), passed as is.
184    Literal(serde_json::Value),
185    /// A reference, passed with its type (a `date` stays a `date`).
186    Ref(Reference),
187    /// A t-string, rendered to a string.
188    Template(Template),
189    /// A list whose elements may contain references.
190    List(Vec<Value>),
191    /// A dictionary (string keys) whose values may contain references.
192    Map(BTreeMap<String, Value>),
193}
194
195impl Value {
196    /// Every reference in this value, at any depth, in order.
197    #[must_use]
198    pub fn references(&self) -> Vec<&Reference> {
199        let mut found = Vec::new();
200        self.collect_references(&mut found);
201        found
202    }
203
204    /// Appends the references in this value to `found`.
205    fn collect_references<'a>(&'a self, found: &mut Vec<&'a Reference>) {
206        match self {
207            Self::Literal(_) => {}
208            Self::Ref(r) => found.push(r),
209            Self::Template(t) => found.extend(t.references()),
210            Self::List(items) => items.iter().for_each(|v| v.collect_references(found)),
211            Self::Map(entries) => entries.values().for_each(|v| v.collect_references(found)),
212        }
213    }
214}