Skip to main content

schedr_model/
notify.rs

1//! Notifications in DAG JSON (decisions 408, 409, 417-423): which channels a DAG tells of which
2//! events, the channels a DAG defines itself, and message bodies as data.
3//!
4//! A body is JSON whose strings may be templates. A DAG writes them as t-strings over
5//! `schedr.notify` placeholders; the server configuration as `"{name}"` strings. Both arrive
6//! here as the same [`Body`]: text parts and references, which the master fills value by value.
7//! Nothing in a body is code, and filling one never runs anything.
8
9use std::fmt;
10
11use schemars::JsonSchema;
12use serde::{Deserialize, Serialize};
13
14#[cfg(test)]
15mod tests;
16
17/// An event a channel can be told of (decision 408; `Notify` in Python, decision 409).
18#[derive(
19    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, JsonSchema,
20)]
21#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
22pub enum NotifyEvent {
23    /// A run ended `failed` (a cancel with a failure included).
24    RunFailed,
25    /// A task failed after its last retry.
26    TaskFailed,
27    /// An attempt failed and will be retried.
28    TaskRetry,
29    /// A run was cancelled, with no failure.
30    RunCancelled,
31    /// A run ended `success`.
32    RunSucceeded,
33    /// A run succeeded after the DAG's previous run failed.
34    RunRecovered,
35    /// The DAG's trigger kept failing (`[triggers] failing_after`), or its generator returned.
36    TriggerFailing,
37    /// A cleanup that ran after its run had ended failed (decision 309).
38    LateCleanupFailed,
39}
40
41impl NotifyEvent {
42    /// Every event, in the order above.
43    pub const ALL: [Self; 8] = [
44        Self::RunFailed,
45        Self::TaskFailed,
46        Self::TaskRetry,
47        Self::RunCancelled,
48        Self::RunSucceeded,
49        Self::RunRecovered,
50        Self::TriggerFailing,
51        Self::LateCleanupFailed,
52    ];
53
54    /// Its name, as written in Python and in configuration (`RUN_FAILED`).
55    #[must_use]
56    pub const fn name(self) -> &'static str {
57        match self {
58            Self::RunFailed => "RUN_FAILED",
59            Self::TaskFailed => "TASK_FAILED",
60            Self::TaskRetry => "TASK_RETRY",
61            Self::RunCancelled => "RUN_CANCELLED",
62            Self::RunSucceeded => "RUN_SUCCEEDED",
63            Self::RunRecovered => "RUN_RECOVERED",
64            Self::TriggerFailing => "TRIGGER_FAILING",
65            Self::LateCleanupFailed => "LATE_CLEANUP_FAILED",
66        }
67    }
68
69    /// The event named `name`, if any.
70    #[must_use]
71    pub fn parse(name: &str) -> Option<Self> {
72        Self::ALL.into_iter().find(|event| event.name() == name)
73    }
74}
75
76impl fmt::Display for NotifyEvent {
77    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
78        f.write_str(self.name())
79    }
80}
81
82/// One channel a DAG notifies (`notify=[...]` or `notify={channel: [...]}`).
83#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
84#[serde(deny_unknown_fields)]
85pub struct NotifyEntry {
86    /// The channel.
87    pub channel: ChannelRef,
88    /// The events it is told of; none: the server's default events
89    /// (`[notifications] default_events`).
90    #[serde(default, skip_serializing_if = "Option::is_none")]
91    pub events: Option<Vec<NotifyEvent>>,
92}
93
94/// A channel: one the server configuration defines (named by a string in Python), or one the
95/// DAG defines itself (an object).
96#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
97#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
98pub enum ChannelRef {
99    /// `[notifications.channels.<name>]`: a webhook or an email channel.
100    Server {
101        /// Its name in the configuration.
102        name: String,
103    },
104    /// A `WebhookChannel` of the DAG's own (decision 425).
105    Webhook(WebhookChannel),
106}
107
108impl ChannelRef {
109    /// The channel's name, as `send` and `schedr task-ctx notify` name it.
110    #[must_use]
111    pub fn name(&self) -> &str {
112        match self {
113            Self::Server { name } => name,
114            Self::Webhook(webhook) => &webhook.name,
115        }
116    }
117}
118
119/// A webhook a DAG defines (decision 425): its URL must start with one of
120/// `[notifications] dag_urls`, and it carries no secrets (its URL is in the DAG file).
121#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
122#[serde(deny_unknown_fields)]
123pub struct WebhookChannel {
124    /// Its name, unique among the DAG's channels.
125    pub name: String,
126    /// Where it posts.
127    pub url: String,
128    /// The JSON it posts; none: schedr's fixed JSON (decision 417).
129    #[serde(default, skip_serializing_if = "Option::is_none")]
130    pub body: Option<Body>,
131}
132
133/// A message body (decision 417): JSON, with values filled in when a notification is queued.
134#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
135#[serde(rename_all = "snake_case", deny_unknown_fields)]
136pub enum Body {
137    /// A JSON value as it is.
138    Value(serde_json::Value),
139    /// A placeholder's value, keeping its JSON type.
140    Ref(Ref),
141    /// A string of text parts and placeholders.
142    Template(Vec<Part>),
143    /// An object of bodies.
144    Object(std::collections::BTreeMap<String, Body>),
145    /// An array of bodies.
146    Array(Vec<Body>),
147}
148
149impl Body {
150    /// Every reference in it, in order.
151    #[must_use]
152    pub fn refs(&self) -> Vec<&Ref> {
153        let mut out = Vec::new();
154        self.collect_refs(&mut out);
155        out
156    }
157
158    fn collect_refs<'a>(&'a self, out: &mut Vec<&'a Ref>) {
159        match self {
160            Self::Value(_) => {}
161            Self::Ref(reference) => out.push(reference),
162            Self::Template(parts) => out.extend(parts.iter().filter_map(|part| match part {
163                Part::Ref(reference) => Some(reference),
164                Part::Text(_) => None,
165            })),
166            Self::Object(map) => map.values().for_each(|body| body.collect_refs(out)),
167            Self::Array(items) => items.iter().for_each(|body| body.collect_refs(out)),
168        }
169    }
170
171    /// A body written in the server configuration: JSON whose strings may hold `{name}`
172    /// placeholders (`{{` and `}}` for literal braces). A string that is exactly one
173    /// placeholder is a [`Body::Ref`], keeping the value's JSON type.
174    ///
175    /// # Errors
176    ///
177    /// A string with an unknown placeholder, an unclosed `{`, or a lone `}`; the message names
178    /// the string.
179    pub fn from_config(value: &serde_json::Value) -> Result<Self, String> {
180        Ok(match value {
181            serde_json::Value::String(text) => {
182                let parts = parse_template(text)?;
183                match parts.as_slice() {
184                    [Part::Ref(reference)] => Self::Ref(reference.clone()),
185                    [] => Self::Value(serde_json::Value::String(String::new())),
186                    [Part::Text(text)] => Self::Value(serde_json::Value::String(text.clone())),
187                    _ => Self::Template(parts),
188                }
189            }
190            serde_json::Value::Array(items) => Self::Array(
191                items
192                    .iter()
193                    .map(Self::from_config)
194                    .collect::<Result<_, _>>()?,
195            ),
196            serde_json::Value::Object(map) => Self::Object(
197                map.iter()
198                    .map(|(key, value)| Ok((key.clone(), Self::from_config(value)?)))
199                    .collect::<Result<_, String>>()?,
200            ),
201            other => Self::Value(other.clone()),
202        })
203    }
204}
205
206/// A piece of a [`Body::Template`].
207#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
208#[serde(rename_all = "snake_case", deny_unknown_fields)]
209pub enum Part {
210    /// Text as it is.
211    Text(String),
212    /// A placeholder's value, as text (a string as it is, anything else as its JSON).
213    Ref(Ref),
214}
215
216/// A placeholder, and a path into its value (`data['rows']`, decision 423).
217#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
218#[serde(deny_unknown_fields)]
219pub struct Ref {
220    /// The placeholder.
221    pub name: Placeholder,
222    /// Keys and indexes into its value, outermost first.
223    #[serde(default, skip_serializing_if = "Vec::is_empty")]
224    pub path: Vec<PathKey>,
225}
226
227/// A step of a [`Ref`]'s path.
228#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
229#[serde(untagged)]
230pub enum PathKey {
231    /// An index into an array.
232    Index(u64),
233    /// A key of an object.
234    Key(String),
235}
236
237impl fmt::Display for Ref {
238    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
239        f.write_str(self.name.name())?;
240        for key in &self.path {
241            match key {
242                PathKey::Index(index) => write!(f, "[{index}]")?,
243                PathKey::Key(key) => write!(f, "[{key:?}]")?,
244            }
245        }
246        Ok(())
247    }
248}
249
250/// The values a body can use (decision 417).
251#[derive(
252    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, JsonSchema,
253)]
254#[serde(rename_all = "snake_case")]
255pub enum Placeholder {
256    /// The event's name (`RUN_FAILED`; `MESSAGE` for a task's own `send`).
257    Event,
258    /// The DAG's ID.
259    Dag,
260    /// The run's ID.
261    Run,
262    /// The run's planned time (UTC, RFC 3339), or null.
263    PlannedFor,
264    /// The run's or the task's state.
265    State,
266    /// schedr's one-line summary; a task's own `send`: its `text`.
267    Text,
268    /// The link to the run in the UI (`[notifications] ui_url`), or null.
269    Link,
270    /// The failed tasks: a list of `{task, error}`.
271    FailedTasks,
272    /// The task's ID, for task events and `send`; null otherwise.
273    Task,
274    /// The attempt's number, for task events and `send`; null otherwise.
275    Attempt,
276    /// When the event happened (UTC, RFC 3339).
277    Time,
278    /// The DAG's time zone.
279    Zone,
280    /// A task's own `send`: its `data`; null in event notifications.
281    Data,
282}
283
284impl Placeholder {
285    /// Every placeholder.
286    pub const ALL: [Self; 13] = [
287        Self::Event,
288        Self::Dag,
289        Self::Run,
290        Self::PlannedFor,
291        Self::State,
292        Self::Text,
293        Self::Link,
294        Self::FailedTasks,
295        Self::Task,
296        Self::Attempt,
297        Self::Time,
298        Self::Zone,
299        Self::Data,
300    ];
301
302    /// Its name, as written in templates.
303    #[must_use]
304    pub const fn name(self) -> &'static str {
305        match self {
306            Self::Event => "event",
307            Self::Dag => "dag",
308            Self::Run => "run",
309            Self::PlannedFor => "planned_for",
310            Self::State => "state",
311            Self::Text => "text",
312            Self::Link => "link",
313            Self::FailedTasks => "failed_tasks",
314            Self::Task => "task",
315            Self::Attempt => "attempt",
316            Self::Time => "time",
317            Self::Zone => "zone",
318            Self::Data => "data",
319        }
320    }
321
322    /// The placeholder named `name`, if any.
323    #[must_use]
324    pub fn parse(name: &str) -> Option<Self> {
325        Self::ALL
326            .into_iter()
327            .find(|placeholder| placeholder.name() == name)
328    }
329}
330
331/// `"[ops] {dag} {data[rows]}"` into parts: `{name}` or `{name[key]...}` (a key of digits is an
332/// index), `{{` and `}}` literal braces.
333fn parse_template(text: &str) -> Result<Vec<Part>, String> {
334    let mut parts = Vec::new();
335    let mut literal = String::new();
336    let mut chars = text.chars().peekable();
337    while let Some(c) = chars.next() {
338        match c {
339            '{' if chars.peek() == Some(&'{') => {
340                chars.next();
341                literal.push('{');
342            }
343            '}' if chars.peek() == Some(&'}') => {
344                chars.next();
345                literal.push('}');
346            }
347            '}' => return Err(format!("{text:?}: a lone `}}` (write `}}}}` for a brace)")),
348            '{' => {
349                let mut inner = String::new();
350                loop {
351                    match chars.next() {
352                        Some('}') => break,
353                        Some(c) => inner.push(c),
354                        None => return Err(format!("{text:?}: a `{{` that isn't closed")),
355                    }
356                }
357                if !literal.is_empty() {
358                    parts.push(Part::Text(std::mem::take(&mut literal)));
359                }
360                parts.push(Part::Ref(
361                    parse_ref(&inner).map_err(|e| format!("{text:?}: {e}"))?,
362                ));
363            }
364            c => literal.push(c),
365        }
366    }
367    if !literal.is_empty() {
368        parts.push(Part::Text(literal));
369    }
370    Ok(parts)
371}
372
373fn parse_ref(inner: &str) -> Result<Ref, String> {
374    let (name, mut rest) = inner.find('[').map_or((inner, ""), |at| inner.split_at(at));
375    let placeholder = Placeholder::parse(name.trim()).ok_or_else(|| {
376        let known: Vec<&str> = Placeholder::ALL.iter().map(|p| p.name()).collect();
377        format!(
378            "unknown placeholder `{{{inner}}}` (known: {})",
379            known.join(", ")
380        )
381    })?;
382    let mut path = Vec::new();
383    while !rest.is_empty() {
384        let end = rest
385            .strip_prefix('[')
386            .and_then(|tail| tail.find(']'))
387            .ok_or_else(|| format!("`{{{inner}}}`: a path is `[key]` after the name"))?;
388        let key = &rest[1..=end];
389        path.push(
390            key.parse::<u64>()
391                .map_or_else(|_| PathKey::Key(key.to_owned()), PathKey::Index),
392        );
393        rest = &rest[end + 2..];
394    }
395    Ok(Ref {
396        name: placeholder,
397        path,
398    })
399}