Skip to main content

schedr_master/
notifications.rs

1//! Notifications (decisions 408-429): which channels hear of an event, the message each gets,
2//! and the checks on a DAG's `notify=`.
3//!
4//! An event queues one notification per channel told of it, in the transaction that records
5//! the event (the outbox, decision 410); [`sender`] delivers them. A body is filled here, when
6//! it is queued, from fixed values ([`Placeholder`]): nothing in it is code.
7
8use std::collections::BTreeMap;
9use std::fmt::Write as _;
10use std::time::Duration;
11
12use jiff::Timestamp;
13use schedr_config::config::{ChannelKind, NotificationsSection, SmtpSection, SmtpTls};
14use schedr_db::notifications::{FailedTask, NewNotification};
15use schedr_model::notify::{Body, ChannelRef, NotifyEvent, Part, PathKey, Placeholder, Ref};
16use schedr_model::{Dag, Trigger};
17use serde_json::{Map, Value, json};
18
19use crate::metrics::MasterMetrics;
20
21pub mod sender;
22#[cfg(test)]
23mod tests;
24
25/// The event name of a message a task sends itself.
26pub const MESSAGE: &str = "MESSAGE";
27
28/// A notification posted to a webhook (`notifications.kind`).
29pub const KIND_WEBHOOK: &str = "webhook";
30
31/// A notification sent as an email; its body holds `to`, `subject` and `text`.
32pub const KIND_EMAIL: &str = "email";
33
34/// The most bytes a filled body may take by default (1 MiB).
35pub const DEFAULT_MAX_BODY: usize = 1 << 20;
36
37/// The most failed tasks a message lists.
38pub const MAX_FAILED_TASKS: u32 = 20;
39
40/// The notification settings (`[notifications]`), checked.
41#[derive(Debug, Clone, PartialEq, Eq)]
42pub struct Notifications {
43    /// The UI's address, without a trailing `/`; none: messages carry no links.
44    pub ui_url: Option<String>,
45    /// The events a channel named without events is told of.
46    pub default_events: Vec<NotifyEvent>,
47    /// The server's webhooks, by name.
48    pub servers: BTreeMap<String, ServerWebhook>,
49    /// The server's email channels, by name (decision 426).
50    pub emails: BTreeMap<String, EmailChannel>,
51    /// The mail server they send through; none: no email channel is configured.
52    pub smtp: Option<Smtp>,
53    /// Where a DAG's own webhook may post: its URL starts with one of them; none: DAGs define
54    /// no webhooks (decision 425).
55    pub dag_urls: Vec<String>,
56    /// Extra CAs trusted for deliveries, PEM (`[notifications] ca_file`, read by the caller).
57    pub extra_roots: Option<Vec<u8>>,
58    /// The limit for one delivery.
59    pub timeout: Duration,
60    /// How long a notification is retried.
61    pub give_up_after: Duration,
62    /// The most notifications a task attempt may send itself.
63    pub max_per_attempt: u32,
64    /// The most bytes a filled body may take (`SCHEDR_HIDDEN__MASTER__NOTIFICATION_BODY`).
65    pub max_body: usize,
66}
67
68/// A server webhook, its headers read from the environment.
69#[derive(Clone, PartialEq, Eq)]
70pub struct ServerWebhook {
71    /// Where it posts (it may be its secret: never logged).
72    pub url: String,
73    /// Its headers, name and value (values are secrets: never logged).
74    pub headers: Vec<(String, String)>,
75    /// Its body; none: schedr's fixed JSON.
76    pub body: Option<Body>,
77}
78
79impl std::fmt::Debug for ServerWebhook {
80    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
81        let names: Vec<&str> = self.headers.iter().map(|(name, _)| name.as_str()).collect();
82        f.debug_struct("ServerWebhook")
83            .field("headers", &names)
84            .field("body", &self.body.is_some())
85            .finish_non_exhaustive()
86    }
87}
88
89/// A server email channel (`type = "email"`): its recipients, every one in To.
90#[derive(Debug, Clone, PartialEq, Eq)]
91pub struct EmailChannel {
92    /// The recipients, checked.
93    pub to: Vec<String>,
94}
95
96/// The mail server (`[notifications.smtp]`), checked.
97#[derive(Clone, PartialEq, Eq)]
98pub struct Smtp {
99    /// Its host.
100    pub host: String,
101    /// Its port.
102    pub port: u16,
103    /// How the connection is secured.
104    pub tls: SmtpTls,
105    /// The login, user and password, if any (the password is a secret: never logged).
106    pub login: Option<(String, String)>,
107    /// The sender.
108    pub from: String,
109}
110
111impl std::fmt::Debug for Smtp {
112    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
113        f.debug_struct("Smtp")
114            .field("host", &self.host)
115            .field("port", &self.port)
116            .field("tls", &self.tls)
117            .field("user", &self.login.as_ref().map(|(user, _)| user))
118            .field("from", &self.from)
119            .finish_non_exhaustive()
120    }
121}
122
123impl Default for Notifications {
124    fn default() -> Self {
125        Self::from_config(&NotificationsSection::default(), &BTreeMap::new())
126            .unwrap_or_else(|_| unreachable!("the default settings are valid"))
127    }
128}
129
130impl Notifications {
131    /// The settings of `section`, header values read from `env`.
132    ///
133    /// # Errors
134    ///
135    /// A message naming the key: an unknown default event, a URL that isn't `http(s)://`, a
136    /// header's variable that isn't set, or a body with a bad placeholder.
137    pub fn from_config(
138        section: &NotificationsSection,
139        env: &BTreeMap<String, String>,
140    ) -> Result<Self, String> {
141        let default_events = section
142            .default_events
143            .iter()
144            .map(|name| {
145                NotifyEvent::parse(name).ok_or_else(|| {
146                    let known: Vec<&str> = NotifyEvent::ALL.iter().map(|e| e.name()).collect();
147                    format!(
148                        "[notifications] default_events: unknown event `{name}` (known: {})",
149                        known.join(", ")
150                    )
151                })
152            })
153            .collect::<Result<Vec<_>, _>>()?;
154        let smtp = smtp_of(&section.smtp)?;
155        let mut servers = BTreeMap::new();
156        let mut emails = BTreeMap::new();
157        for (name, channel) in &section.channels {
158            let key = format!("[notifications.channels.{name}]");
159            if channel.kind == ChannelKind::Email {
160                if smtp.is_none() {
161                    return Err(format!(
162                        "{key}: an email channel sends through [notifications.smtp], which has \
163                         no `host`"
164                    ));
165                }
166                emails.insert(name.clone(), email_channel(&key, channel)?);
167                continue;
168            }
169            if !channel.to.is_empty() {
170                return Err(format!(
171                    "{key} to: a webhook has no recipients (`to` is an email's)"
172                ));
173            }
174            let url = channel
175                .url
176                .as_ref()
177                .ok_or_else(|| format!("{key}: a webhook needs its `url`"))?;
178            check_url(url).map_err(|e| format!("{key} url: {e}"))?;
179            let headers = channel
180                .headers_env
181                .iter()
182                .map(|(header, variable)| {
183                    env.get(variable)
184                        .filter(|value| !value.is_empty())
185                        .map(|value| (header.clone(), value.clone()))
186                        .ok_or_else(|| {
187                            format!(
188                                "{key} headers_env: `{header}` is read from the environment \
189                                 variable {variable}, which isn't set"
190                            )
191                        })
192                })
193                .collect::<Result<Vec<_>, _>>()?;
194            let body = channel
195                .body
196                .as_ref()
197                .map(Body::from_config)
198                .transpose()
199                .map_err(|e| format!("{key} body: {e}"))?;
200            servers.insert(
201                name.clone(),
202                ServerWebhook {
203                    url: url.clone(),
204                    headers,
205                    body,
206                },
207            );
208        }
209        for url in &section.dag_urls {
210            check_url(url).map_err(|e| format!("[notifications] dag_urls: {e}"))?;
211            let parsed = reqwest::Url::parse(url)
212                .map_err(|e| format!("[notifications] dag_urls: `{url}` doesn't read: {e}"))?;
213            if !parsed.username().is_empty() || parsed.password().is_some() {
214                return Err(format!(
215                    "[notifications] dag_urls: `{url}` holds a user or a password"
216                ));
217            }
218        }
219        if let Some(url) = &section.ui_url {
220            check_url(url).map_err(|e| format!("[notifications] ui_url: {e}"))?;
221        }
222        Ok(Self {
223            ui_url: section
224                .ui_url
225                .as_ref()
226                .map(|url| url.trim_end_matches('/').to_owned()),
227            default_events,
228            servers,
229            emails,
230            smtp,
231            dag_urls: section.dag_urls.clone(),
232            extra_roots: None,
233            timeout: section.timeout,
234            give_up_after: section.give_up_after,
235            max_per_attempt: section.max_per_attempt,
236            max_body: DEFAULT_MAX_BODY,
237        })
238    }
239
240    /// What is wrong with `dag`'s `notify=`: a server channel that isn't configured, a DAG
241    /// channel where they are off, outside `dag_urls`, named as a server channel, or two of
242    /// one name.
243    #[must_use]
244    pub fn problems(&self, dag: &Dag) -> Vec<String> {
245        let mut problems = Vec::new();
246        let mut names = std::collections::BTreeSet::new();
247        for entry in &dag.notify {
248            let name = entry.channel.name();
249            if !names.insert(name) {
250                problems.push(format!("notify: two channels are named `{name}`"));
251            }
252            match &entry.channel {
253                ChannelRef::Server { name } if !self.is_server_channel(name) => {
254                    problems.push(format!(
255                        "notify: no server channel `{name}` ([notifications.channels.{name}] in \
256                         the master's configuration; configured: {})",
257                        self.server_names()
258                    ));
259                }
260                ChannelRef::Server { .. } => {}
261                ChannelRef::Webhook(hook) => {
262                    if self.dag_webhook_allowed(&hook.url).is_err() {
263                        problems.push(format!(
264                            "notify: WebhookChannel `{name}`: its URL isn't one DAGs may post to \
265                             ([notifications] dag_urls: {}); a server channel can be named \
266                             instead",
267                            list(self.dag_urls.iter())
268                        ));
269                    }
270                    if self.is_server_channel(name) {
271                        problems.push(format!(
272                            "notify: WebhookChannel `{name}` is named as a server channel; give \
273                             it another name"
274                        ));
275                    }
276                }
277            }
278        }
279        problems
280    }
281
282    /// The notifications `event` queues: one per channel of the DAG told of it. A missing
283    /// value fills as null. A DAG webhook whose URL is off `dag_urls` now, or a body past its
284    /// size, is logged as an error, counted in `metrics` as failed and skipped; a server
285    /// channel not configured now is queued (the sender keeps it until `give_up_after`).
286    #[must_use]
287    pub fn queued(
288        &self,
289        event: &Event<'_>,
290        kind: NotifyEvent,
291        metrics: &MasterMetrics,
292    ) -> Vec<NewNotification> {
293        let vars = self.vars(event, kind.name());
294        event
295            .dag
296            .notify
297            .iter()
298            .filter(|entry| {
299                entry
300                    .events
301                    .as_ref()
302                    .map_or(self.default_events.contains(&kind), |events| {
303                        events.contains(&kind)
304                    })
305            })
306            .filter_map(|entry| {
307                self.notification(event, &entry.channel, kind.name(), &vars, false)
308                    .map_err(|error| {
309                        tracing::error!(dag_id = %event.dag.id, channel = entry.channel.name(),
310                            event = kind.name(), %error, "a notification can't be sent; dropped");
311                        metrics.notification_failed(entry.channel.name());
312                    })
313                    .ok()
314            })
315            .collect()
316    }
317
318    /// The notification a task's own `send` queues to channel `name` of its DAG (its own
319    /// channels first, then the server's).
320    ///
321    /// # Errors
322    ///
323    /// A message for the caller: no such channel, or a path into `data` the data lacks.
324    pub fn message(&self, event: &Event<'_>, name: &str) -> Result<NewNotification, String> {
325        let own = event
326            .dag
327            .notify
328            .iter()
329            .map(|entry| &entry.channel)
330            .find(|channel| channel.name() == name);
331        let server = ChannelRef::Server {
332            name: name.to_owned(),
333        };
334        let channel = match own {
335            Some(channel) => channel,
336            None if self.is_server_channel(name) => &server,
337            None => {
338                return Err(format!(
339                    "no channel `{name}`: not in DAG `{}`'s notify=, nor a server channel \
340                     (configured: {})",
341                    event.dag.id,
342                    self.server_names()
343                ));
344            }
345        };
346        let vars = self.vars(event, MESSAGE);
347        self.notification(event, channel, MESSAGE, &vars, true)
348    }
349
350    /// Whether `name` is a channel of the server's configuration, of either type.
351    fn is_server_channel(&self, name: &str) -> bool {
352        self.servers.contains_key(name) || self.emails.contains_key(name)
353    }
354
355    /// The server's channels' names, for messages.
356    fn server_names(&self) -> String {
357        let names: std::collections::BTreeSet<&String> =
358            self.servers.keys().chain(self.emails.keys()).collect();
359        list(names.into_iter())
360    }
361
362    fn notification(
363        &self,
364        happened: &Event<'_>,
365        channel: &ChannelRef,
366        event: &str,
367        vars: &Vars,
368        strict: bool,
369    ) -> Result<NewNotification, String> {
370        let dag = happened.dag;
371        if let ChannelRef::Server { name } = channel
372            && self.emails.contains_key(name)
373        {
374            let body = email_json(happened, event, vars);
375            Budget::new(self.max_body).spend(json_len(&body))?;
376            return Ok(NewNotification {
377                dag_id: dag.id.to_string(),
378                channel: name.clone(),
379                kind: KIND_EMAIL.to_owned(),
380                url: None,
381                event: event.to_owned(),
382                body,
383            });
384        }
385        let (url, body) = match channel {
386            // Not configured now: queued all the same, with schedr's JSON; the sender keeps it
387            // until `give_up_after`, so a master started with the channel back delivers it
388            // (decision 425; Codex's review of M4.13a).
389            ChannelRef::Server { name } => (
390                None,
391                self.servers
392                    .get(name)
393                    .and_then(|server| server.body.as_ref()),
394            ),
395            ChannelRef::Webhook(hook) => {
396                self.dag_webhook_allowed(&hook.url)?;
397                (Some(hook.url.clone()), hook.body.as_ref())
398            }
399        };
400        let body = if let Some(body) = body {
401            fill(body, vars, strict, &mut Budget::new(self.max_body))?
402        } else {
403            // A task's data is in it whole: held to the same limit (Codex's docs round).
404            let body = fixed(vars);
405            Budget::new(self.max_body).spend(json_len(&body))?;
406            body
407        };
408        Ok(NewNotification {
409            dag_id: dag.id.to_string(),
410            channel: channel.name().to_owned(),
411            kind: KIND_WEBHOOK.to_owned(),
412            url,
413            event: event.to_owned(),
414            body,
415        })
416    }
417
418    /// Whether a DAG's own webhook may post to `url` under the settings now (they may have
419    /// changed since its DAG was checked).
420    ///
421    /// # Errors
422    ///
423    /// Why not: `url` outside `dag_urls`.
424    pub fn dag_webhook_allowed(&self, url: &str) -> Result<(), String> {
425        if self.dag_urls.iter().any(|allowed| url_within(url, allowed)) {
426            Ok(())
427        } else {
428            Err("its URL isn't one DAGs may post to any more ([notifications] dag_urls)".to_owned())
429        }
430    }
431
432    fn vars(&self, event: &Event<'_>, name: &str) -> Vars {
433        let link = match (&self.ui_url, event.run_id) {
434            (Some(base), Some(run)) => Value::String(format!("{base}/runs/{run}")),
435            (Some(base), None) => Value::String(format!("{base}/dags/{}", event.dag.id)),
436            (None, _) => Value::Null,
437        };
438        let failed: Vec<Value> = event
439            .failed_tasks
440            .iter()
441            .map(|t| {
442                let task = if t.map_index >= 0 {
443                    format!("{}[{}]", t.task_id, t.map_index)
444                } else {
445                    t.task_id.clone()
446                };
447                json!({"task": task, "error": t.error})
448            })
449            .collect();
450        let text = event.text.clone().unwrap_or_else(|| summary(event, name));
451        let text = match &link {
452            Value::String(link) if event.text.is_none() => format!("{text} {link}"),
453            _ => text,
454        };
455        BTreeMap::from([
456            (Placeholder::Event, Value::String(name.to_owned())),
457            (Placeholder::Dag, Value::String(event.dag.id.to_string())),
458            (Placeholder::Run, opt(event.run_id)),
459            (
460                Placeholder::PlannedFor,
461                event
462                    .planned_for
463                    .map_or(Value::Null, |t| Value::String(t.to_string())),
464            ),
465            (Placeholder::State, opt(event.state)),
466            (Placeholder::Text, Value::String(text)),
467            (Placeholder::Link, link),
468            (Placeholder::FailedTasks, Value::Array(failed)),
469            (Placeholder::Task, opt(event.task)),
470            (
471                Placeholder::Attempt,
472                event.attempt.map_or(Value::Null, Value::from),
473            ),
474            (Placeholder::Time, Value::String(event.time.to_string())),
475            (Placeholder::Zone, Value::String(zone(event.dag).to_owned())),
476            (Placeholder::Data, event.data.clone()),
477        ])
478    }
479}
480
481/// What happened, for the message.
482#[derive(Debug, Clone)]
483pub struct Event<'a> {
484    /// The DAG.
485    pub dag: &'a Dag,
486    /// The run, if any (not for a failing trigger).
487    pub run_id: Option<&'a str>,
488    /// The run's planned time.
489    pub planned_for: Option<Timestamp>,
490    /// The run's or the task's state.
491    pub state: Option<&'a str>,
492    /// The task, for task events and `send`.
493    pub task: Option<&'a str>,
494    /// The attempt's number, for task events and `send`.
495    pub attempt: Option<u32>,
496    /// The failed tasks.
497    pub failed_tasks: Vec<FailedTask>,
498    /// The error, for a failing trigger or a task event.
499    pub error: Option<String>,
500    /// A task's own text (`send`); none: schedr's summary.
501    pub text: Option<String>,
502    /// A task's own data (`send`); null otherwise.
503    pub data: Value,
504    /// When it happened.
505    pub time: Timestamp,
506}
507
508impl<'a> Event<'a> {
509    /// An event of `dag` at `time`, nothing else known yet.
510    #[must_use]
511    pub const fn new(dag: &'a Dag, time: Timestamp) -> Self {
512        Self {
513            dag,
514            run_id: None,
515            planned_for: None,
516            state: None,
517            task: None,
518            attempt: None,
519            failed_tasks: Vec::new(),
520            error: None,
521            text: None,
522            data: Value::Null,
523            time,
524        }
525    }
526}
527
528type Vars = BTreeMap<Placeholder, Value>;
529
530fn opt(value: Option<&str>) -> Value {
531    value.map_or(Value::Null, |v| Value::String(v.to_owned()))
532}
533
534fn list<'a>(names: impl Iterator<Item = &'a String>) -> String {
535    let names: Vec<String> = names.map(|n| format!("`{n}`")).collect();
536    if names.is_empty() {
537        "none".to_owned()
538    } else {
539        names.join(", ")
540    }
541}
542
543/// Whether `url` is within `allowed` (decision 425): the same scheme, host and port, no user or
544/// password, and a path under `allowed`'s, at a `/` (`https://a.example.com/hooks` allows
545/// `/hooks` and `/hooks/x`, not `/hooksy`). Both are parsed, as the client parses them, so a
546/// host suffix (`a.example.com.evil`) or userinfo (`a.example.com@127.0.0.1`) can't pass.
547#[must_use]
548pub fn url_within(url: &str, allowed: &str) -> bool {
549    let (Ok(url), Ok(allowed)) = (reqwest::Url::parse(url), reqwest::Url::parse(allowed)) else {
550        return false;
551    };
552    if !url.username().is_empty() || url.password().is_some() {
553        return false;
554    }
555    let same_origin = url.scheme() == allowed.scheme()
556        && url.host_str().is_some()
557        && url.host_str() == allowed.host_str()
558        && url.port_or_known_default() == allowed.port_or_known_default();
559    let base = allowed.path();
560    let path = url.path();
561    same_origin
562        && (base.ends_with('/') && path.starts_with(base)
563            || path == base
564            || path
565                .strip_prefix(base)
566                .is_some_and(|rest| rest.starts_with('/')))
567}
568
569fn check_url(url: &str) -> Result<(), String> {
570    if url.starts_with("https://") || url.starts_with("http://") {
571        Ok(())
572    } else {
573        Err(format!("`{url}` must start with https:// or http://"))
574    }
575}
576
577/// The DAG's time zone: its schedule's, UTC otherwise.
578fn zone(dag: &Dag) -> &str {
579    match &dag.trigger {
580        Trigger::Cron { timezone, .. } => timezone,
581        _ => "UTC",
582    }
583}
584
585/// schedr's one-line summary of an event.
586fn summary(event: &Event<'_>, name: &str) -> String {
587    let dag = &event.dag.id;
588    let run = event.run_id.unwrap_or("?");
589    let task = event.task.unwrap_or("?");
590    let error = event
591        .error
592        .as_deref()
593        .map(|e| format!(": {}", first_line(e)))
594        .unwrap_or_default();
595    let failed = || {
596        let names: Vec<String> = event
597            .failed_tasks
598            .iter()
599            .map(|t| {
600                if t.map_index >= 0 {
601                    format!("{}[{}]", t.task_id, t.map_index)
602                } else {
603                    t.task_id.clone()
604                }
605            })
606            .collect();
607        if names.is_empty() {
608            String::new()
609        } else {
610            format!(" (failed: {})", names.join(", "))
611        }
612    };
613    match NotifyEvent::parse(name) {
614        Some(NotifyEvent::RunFailed) => format!("DAG `{dag}`: run {run} failed{}", failed()),
615        Some(NotifyEvent::TaskFailed) => {
616            format!("DAG `{dag}`: task `{task}` failed in run {run}{error}")
617        }
618        Some(NotifyEvent::TaskRetry) => format!(
619            "DAG `{dag}`: task `{task}` failed in run {run} (attempt {}) and will be retried{error}",
620            event.attempt.unwrap_or(0)
621        ),
622        Some(NotifyEvent::RunCancelled) => format!("DAG `{dag}`: run {run} was cancelled"),
623        Some(NotifyEvent::RunSucceeded) => format!("DAG `{dag}`: run {run} succeeded"),
624        Some(NotifyEvent::RunRecovered) => {
625            format!("DAG `{dag}`: run {run} succeeded after the previous run failed")
626        }
627        Some(NotifyEvent::TriggerFailing) => format!("DAG `{dag}`: its trigger is failing{error}"),
628        Some(NotifyEvent::LateCleanupFailed) => format!(
629            "DAG `{dag}`: a cleanup of task `{task}` failed after run {run} succeeded; handles \
630             may be left behind{error}"
631        ),
632        None => format!("DAG `{dag}`: a message from task `{task}`"),
633    }
634}
635
636fn first_line(text: &str) -> &str {
637    let line = text.lines().next().unwrap_or_default();
638    match line.char_indices().nth(300) {
639        Some((at, _)) => &line[..at],
640        None => line,
641    }
642}
643
644/// schedr's fixed JSON (decision 412): every value, `data` only when set.
645fn fixed(vars: &Vars) -> Value {
646    let mut out = Map::new();
647    for (placeholder, value) in vars {
648        if *placeholder == Placeholder::Data && value.is_null() {
649            continue;
650        }
651        out.insert(placeholder.name().to_owned(), value.clone());
652    }
653    Value::Object(out)
654}
655
656/// What a body may still take, in bytes of its JSON, as it is filled: each value is measured
657/// before it is copied, so a template using a big value many times stops at the limit instead
658/// of filling the master's memory (Codex's review of M4.13a).
659#[derive(Debug)]
660pub struct Budget {
661    left: usize,
662    max: usize,
663}
664
665impl Budget {
666    /// `max` bytes.
667    #[must_use]
668    pub const fn new(max: usize) -> Self {
669        Self { left: max, max }
670    }
671
672    fn spend(&mut self, bytes: usize) -> Result<(), String> {
673        self.left = self.left.checked_sub(bytes).ok_or_else(|| {
674            format!(
675                "the body would take more than {} bytes \
676                 (SCHEDR_HIDDEN__MASTER__NOTIFICATION_BODY)",
677                self.max
678            )
679        })?;
680        Ok(())
681    }
682}
683
684/// The bytes of `value`'s JSON, counted without writing it.
685fn json_len(value: &Value) -> usize {
686    struct Count(usize);
687    impl std::io::Write for Count {
688        fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
689            self.0 += bytes.len();
690            Ok(bytes.len())
691        }
692        fn flush(&mut self) -> std::io::Result<()> {
693            Ok(())
694        }
695    }
696    let mut count = Count(0);
697    let _ = serde_json::to_writer(&mut count, value);
698    count.0
699}
700
701/// `body` filled from `vars`, within `budget`. With `strict` (a task's own `send`), a path into
702/// `data` that the data lacks is an error; otherwise it fills as null (empty in text).
703///
704/// # Errors
705///
706/// Past the budget; with `strict`, a path into `data` that isn't there. The message says which.
707pub fn fill(body: &Body, vars: &Vars, strict: bool, budget: &mut Budget) -> Result<Value, String> {
708    Ok(match body {
709        Body::Value(value) => {
710            budget.spend(json_len(value))?;
711            value.clone()
712        }
713        Body::Ref(reference) => {
714            let value = resolve(reference, vars, strict)?;
715            budget.spend(json_len(value))?;
716            value.clone()
717        }
718        Body::Template(parts) => {
719            let mut text = String::new();
720            for part in parts {
721                match part {
722                    Part::Text(piece) => {
723                        budget.spend(piece.len())?;
724                        text.push_str(piece);
725                    }
726                    Part::Ref(reference) => match resolve(reference, vars, strict)? {
727                        Value::Null => {}
728                        Value::String(value) => {
729                            budget.spend(value.len())?;
730                            text.push_str(value);
731                        }
732                        other => {
733                            budget.spend(json_len(other))?;
734                            text.push_str(&other.to_string());
735                        }
736                    },
737                }
738            }
739            Value::String(text)
740        }
741        Body::Object(map) => Value::Object(
742            map.iter()
743                .map(|(key, body)| {
744                    budget.spend(key.len())?;
745                    Ok((key.clone(), fill(body, vars, strict, budget)?))
746                })
747                .collect::<Result<_, String>>()?,
748        ),
749        Body::Array(items) => Value::Array(
750            items
751                .iter()
752                .map(|body| fill(body, vars, strict, budget))
753                .collect::<Result<_, _>>()?,
754        ),
755    })
756}
757
758static NULL: Value = Value::Null;
759
760fn resolve<'a>(reference: &Ref, vars: &'a Vars, strict: bool) -> Result<&'a Value, String> {
761    let mut value = vars.get(&reference.name).unwrap_or(&NULL);
762    for key in &reference.path {
763        let next = match (key, value) {
764            (PathKey::Key(key), Value::Object(map)) => map.get(key),
765            (PathKey::Index(index), Value::Array(items)) => {
766                usize::try_from(*index).ok().and_then(|i| items.get(i))
767            }
768            _ => None,
769        };
770        match next {
771            Some(next) => value = next,
772            None if strict && reference.name == Placeholder::Data => {
773                return Err(format!(
774                    "the channel's body uses `{reference}`, which the data sent hasn't"
775                ));
776            }
777            None => return Ok(&NULL),
778        }
779    }
780    Ok(value)
781}
782
783/// `[notifications.smtp]` checked: none without a host.
784fn smtp_of(section: &SmtpSection) -> Result<Option<Smtp>, String> {
785    let Some(host) = section.host.clone().filter(|host| !host.is_empty()) else {
786        return Ok(None);
787    };
788    let from = section
789        .from
790        .clone()
791        .ok_or_else(|| "[notifications.smtp]: `from`, the sender, is needed".to_owned())?;
792    from.parse::<lettre::message::Mailbox>()
793        .map_err(|e| format!("[notifications.smtp] from: `{from}` isn't an address: {e}"))?;
794    let login = match (&section.username, &section.password) {
795        (Some(user), Some(password)) => Some((user.clone(), password.clone())),
796        (None, None) => None,
797        (Some(_), None) => {
798            return Err("[notifications.smtp] username: its password is set in \
799                 SCHEDR_CONFIG__NOTIFICATIONS__SMTP__PASSWORD, which isn't set"
800                .to_owned());
801        }
802        (None, Some(_)) => {
803            return Err(
804                "[notifications.smtp]: a password with no `username` to log in as".to_owned(),
805            );
806        }
807    };
808    if section.tls == SmtpTls::None && login.is_some() {
809        return Err(
810            "[notifications.smtp]: a login over `tls = \"none\"` would send the password in \
811             plain text; use `starttls` or `tls`"
812                .to_owned(),
813        );
814    }
815    Ok(Some(Smtp {
816        host,
817        port: section.port,
818        tls: section.tls,
819        login,
820        from,
821    }))
822}
823
824/// A `type = "email"` channel checked: `to` only, every address one.
825fn email_channel(
826    key: &str,
827    channel: &schedr_config::config::ChannelConfig,
828) -> Result<EmailChannel, String> {
829    if channel.url.is_some() || !channel.headers_env.is_empty() || channel.body.is_some() {
830        return Err(format!(
831            "{key}: an email channel takes `to` only (`url`, `headers_env` and `body` are a \
832             webhook's)"
833        ));
834    }
835    if channel.to.is_empty() {
836        return Err(format!("{key} to: an email channel needs its recipients"));
837    }
838    for address in &channel.to {
839        address
840            .parse::<lettre::message::Mailbox>()
841            .map_err(|e| format!("{key} to: `{address}` isn't an address: {e}"))?;
842    }
843    Ok(EmailChannel {
844        to: channel.to.clone(),
845    })
846}
847
848/// An email's subject: one line of at most 200 characters.
849pub(crate) fn subject_of(text: &str) -> String {
850    let line = text.lines().next().unwrap_or_default().trim();
851    let cut: String = line.chars().take(200).collect();
852    if cut.len() < line.len() {
853        format!("{cut}…")
854    } else {
855        cut
856    }
857}
858
859/// The email for `happened` (decision 426): plain text, the summary as the subject, then the
860/// run, the task, the failed tasks with their errors, the times, a task's data and the link.
861fn email_json(happened: &Event<'_>, event: &str, vars: &Vars) -> Value {
862    let summary = happened
863        .text
864        .clone()
865        .unwrap_or_else(|| summary(happened, event));
866    let mut text = format!("{summary}\n\n");
867    let mut line = |name: &str, value: &str| {
868        let _ = writeln!(text, "{name:<13} {value}");
869    };
870    line("Event:", event);
871    line("DAG:", happened.dag.id.as_str());
872    if let Some(run) = happened.run_id {
873        line("Run:", run);
874    }
875    let zone = zone(happened.dag);
876    if let Some(planned) = happened.planned_for {
877        line("Planned for:", &both_times(planned, zone));
878    }
879    if let Some(task) = happened.task {
880        match happened.attempt {
881            Some(attempt) => line("Task:", &format!("{task} (attempt {attempt})")),
882            None => line("Task:", task),
883        }
884    }
885    if let Some(error) = &happened.error {
886        line("Error:", first_line(error));
887    }
888    line("At:", &both_times(happened.time, zone));
889    if let Some(Value::String(link)) = vars.get(&Placeholder::Link) {
890        line("Link:", link);
891    }
892    if !happened.failed_tasks.is_empty() {
893        text.push_str("\nFailed tasks:\n");
894        for task in &happened.failed_tasks {
895            let name = if task.map_index >= 0 {
896                format!("{}[{}]", task.task_id, task.map_index)
897            } else {
898                task.task_id.clone()
899            };
900            let _ = writeln!(
901                text,
902                "  {name}: {}",
903                task.error
904                    .as_deref()
905                    .map_or("(no error recorded)", first_line)
906            );
907        }
908    }
909    if !happened.data.is_null() {
910        let data = serde_json::to_string_pretty(&happened.data).unwrap_or_default();
911        let _ = write!(text, "\nData:\n{data}\n");
912    }
913    json!({"subject": subject_of(&summary), "text": text})
914}
915
916/// `2026-11-09T03:00:00Z (04:00 Europe/Warsaw)`: UTC, and the DAG's zone when it isn't UTC.
917fn both_times(at: Timestamp, zone: &str) -> String {
918    if zone == "UTC" {
919        return at.to_string();
920    }
921    match at.in_tz(zone) {
922        Ok(local) => format!("{at} ({} {zone})", local.strftime("%Y-%m-%d %H:%M")),
923        Err(_) => at.to_string(),
924    }
925}