Skip to main content

schedr_master/notifications/
sender.rs

1//! The master's sender: delivers the outbox (decision 410). A notification delivered is
2//! deleted; one that fails is tried again later, waiting longer each time, until
3//! `[notifications] give_up_after` has passed since it was queued: then it is logged as an
4//! error, counted and deleted. Redirects aren't followed (decision 425), and a URL is never
5//! logged (a server webhook's may hold its secret).
6
7use std::sync::Arc;
8use std::time::Duration;
9
10use jiff::{SignedDuration, Timestamp};
11use schedr_db::notifications::Notification;
12use schedr_db::{Database, DbError};
13
14use lettre::AsyncTransport as _;
15use lettre::transport::smtp::authentication::Credentials;
16use lettre::transport::smtp::client::{Certificate, Tls, TlsParameters};
17use lettre::{AsyncSmtpTransport, Message, Tokio1Executor};
18use schedr_config::config::SmtpTls;
19
20use super::{KIND_EMAIL, Notifications, Smtp};
21use crate::metrics::MasterMetrics;
22
23/// The most notifications one pass delivers.
24pub const BATCH: u32 = 50;
25
26/// The waits between deliveries of a failing notification.
27#[derive(Debug, Clone, Copy, PartialEq, Eq)]
28pub struct Backoff {
29    /// The first wait; it doubles.
30    pub first: Duration,
31    /// The longest.
32    pub max: Duration,
33}
34
35impl Backoff {
36    /// The wait after the `tries`-th failure (1 for the first).
37    #[must_use]
38    pub fn after(self, tries: u32) -> Duration {
39        let factor = 1u32
40            .checked_shl(tries.saturating_sub(1))
41            .unwrap_or(u32::MAX);
42        self.first.saturating_mul(factor).min(self.max)
43    }
44}
45
46/// Delivers notifications.
47#[derive(Debug, Clone)]
48pub struct Sender {
49    db: Database,
50    settings: Arc<Notifications>,
51    client: reqwest::Client,
52    metrics: MasterMetrics,
53    backoff: Backoff,
54    /// The mail server's transport, when `[notifications.smtp]` has a host.
55    smtp: Option<AsyncSmtpTransport<Tokio1Executor>>,
56    /// The most notifications a pass delivers (decision 493).
57    per_pass: u32,
58}
59
60/// What a pass did.
61#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
62pub struct Pass {
63    /// Delivered.
64    pub sent: usize,
65    /// Failed, to be tried again.
66    pub retried: usize,
67    /// Given up on.
68    pub dropped: usize,
69}
70
71impl Sender {
72    /// A sender over `db`.
73    ///
74    /// # Errors
75    ///
76    /// The HTTP client or the mail server's transport can't be built (no TLS roots, a bad
77    /// `ca_file`).
78    pub fn new(
79        db: Database,
80        settings: Arc<Notifications>,
81        metrics: MasterMetrics,
82        backoff: Backoff,
83    ) -> Result<Self, String> {
84        let mut builder = reqwest::Client::builder()
85            .redirect(reqwest::redirect::Policy::none())
86            .timeout(settings.timeout)
87            .user_agent(concat!("schedr/", env!("CARGO_PKG_VERSION")));
88        if let Some(pem) = &settings.extra_roots {
89            let roots = reqwest::Certificate::from_pem_bundle(pem).map_err(|e| e.to_string())?;
90            builder = builder.tls_certs_merge(roots);
91        }
92        let client = builder.build().map_err(|e| e.to_string())?;
93        let smtp = settings
94            .smtp
95            .as_ref()
96            .map(|smtp| transport(smtp, settings.extra_roots.as_deref(), settings.timeout))
97            .transpose()
98            .map_err(|e| format!("[notifications.smtp]: {e}"))?;
99        Ok(Self {
100            db,
101            settings,
102            client,
103            metrics,
104            backoff,
105            smtp,
106            per_pass: BATCH,
107        })
108    }
109
110    /// The sender delivering at most `per_pass` notifications a pass
111    /// (`SCHEDR_HIDDEN__MASTER__NOTIFICATIONS_PER_PASS`).
112    #[must_use]
113    pub const fn with_per_pass(mut self, per_pass: u32) -> Self {
114        self.per_pass = per_pass;
115        self
116    }
117
118    /// Delivers what is due at `now`, at most its `per_pass` ([`BATCH`] by default), while
119    /// `leading` says this master still leads: it is asked before each delivery, so a master that lost its lease mid-pass starts
120    /// no more (Codex's review of M4.13a).
121    ///
122    /// # Errors
123    ///
124    /// [`DbError`] if the outbox can't be read or written.
125    pub async fn pass(&self, now: Timestamp, leading: impl Fn() -> bool) -> Result<Pass, DbError> {
126        let mut pass = Pass::default();
127        for notification in self.db.due_notifications(now, self.per_pass).await? {
128            if !leading() {
129                break;
130            }
131            // Queued under older settings: a DAG webhook no longer allowed goes nowhere.
132            if let Some(Err(why)) = notification
133                .url
134                .as_deref()
135                .map(|url| self.settings.dag_webhook_allowed(url))
136            {
137                tracing::error!(
138                    dag_id = notification.dag_id,
139                    channel = notification.channel,
140                    event = notification.event,
141                    why,
142                    "a notification to a DAG's webhook isn't allowed now; dropped"
143                );
144                self.db.delete_notification(&notification.id).await?;
145                self.metrics.notification_failed(&notification.channel);
146                pass.dropped += 1;
147                continue;
148            }
149            match self.deliver(&notification).await {
150                Ok(()) => {
151                    self.db.delete_notification(&notification.id).await?;
152                    self.metrics.notification_sent(&notification.channel);
153                    pass.sent += 1;
154                }
155                Err(Failure::Refused(error)) => {
156                    tracing::error!(
157                        dag_id = notification.dag_id,
158                        channel = notification.channel,
159                        event = notification.event,
160                        %error,
161                        "a notification was refused by its receiver; dropped (a refusal isn't \
162                         retried)"
163                    );
164                    self.db.delete_notification(&notification.id).await?;
165                    self.metrics.notification_failed(&notification.channel);
166                    pass.dropped += 1;
167                }
168                Err(Failure::Passing(error)) if self.given_up(&notification, now) => {
169                    tracing::error!(
170                        dag_id = notification.dag_id,
171                        channel = notification.channel,
172                        event = notification.event,
173                        tries = notification.tries + 1,
174                        %error,
175                        "a notification couldn't be delivered within [notifications] \
176                         give_up_after; dropped"
177                    );
178                    self.db.delete_notification(&notification.id).await?;
179                    self.metrics.notification_failed(&notification.channel);
180                    pass.dropped += 1;
181                }
182                Err(Failure::Passing(error))
183                    if notification.url.is_none()
184                        && !self.settings.servers.contains_key(&notification.channel)
185                        && !self.settings.emails.contains_key(&notification.channel) =>
186                {
187                    // An error, not a passing failure: kept until `give_up_after`, so a
188                    // master started with the channel back delivers it.
189                    tracing::error!(
190                        dag_id = notification.dag_id,
191                        channel = notification.channel,
192                        event = notification.event,
193                        %error,
194                        "a notification names a server channel that isn't configured"
195                    );
196                    self.retry_later(&notification, now, &error).await?;
197                    pass.retried += 1;
198                }
199                Err(Failure::Passing(error)) => {
200                    tracing::warn!(
201                        dag_id = notification.dag_id,
202                        channel = notification.channel,
203                        event = notification.event,
204                        %error,
205                        "a notification wasn't delivered; trying again in {}s",
206                        self.backoff.after(notification.tries + 1).as_secs()
207                    );
208                    self.retry_later(&notification, now, &error).await?;
209                    pass.retried += 1;
210                }
211            }
212        }
213        Ok(pass)
214    }
215
216    async fn retry_later(
217        &self,
218        notification: &Notification,
219        now: Timestamp,
220        error: &str,
221    ) -> Result<(), DbError> {
222        let wait = self.backoff.after(notification.tries + 1);
223        let next = now
224            .checked_add(SignedDuration::try_from(wait).unwrap_or(SignedDuration::MAX))
225            .unwrap_or(now);
226        self.db
227            .retry_notification(&notification.id, next, error)
228            .await
229    }
230
231    fn given_up(&self, notification: &Notification, now: Timestamp) -> bool {
232        let limit =
233            SignedDuration::try_from(self.settings.give_up_after).unwrap_or(SignedDuration::MAX);
234        notification
235            .created_at
236            .checked_add(limit)
237            .is_ok_and(|deadline| now >= deadline)
238    }
239
240    /// Sends `notification`: posts it, or mails it.
241    async fn deliver(&self, notification: &Notification) -> Result<(), Failure> {
242        // The channel as configured now: its recipients may have changed or gone since it
243        // was queued, and a channel missing then may be back as an email one (Codex's review
244        // of M4.13b).
245        if notification.url.is_none()
246            && let Some(channel) = self.settings.emails.get(&notification.channel)
247        {
248            return self.mail(notification, &channel.to).await;
249        }
250        if notification.kind == KIND_EMAIL {
251            return Err(Failure::Passing(format!(
252                "no email channel `{}` in the configuration any more",
253                notification.channel
254            )));
255        }
256        let (url, headers) = if let Some(url) = &notification.url {
257            (url.as_str(), &[][..])
258        } else {
259            let server = self
260                .settings
261                .servers
262                .get(&notification.channel)
263                .ok_or_else(|| {
264                    Failure::Passing(format!(
265                        "no server channel `{}` in the configuration any more",
266                        notification.channel
267                    ))
268                })?;
269            (server.url.as_str(), server.headers.as_slice())
270        };
271        let mut request = self.client.post(url).json(&notification.body);
272        for (name, value) in headers {
273            request = request.header(name, value);
274        }
275        let answer = request.send().await.map_err(|error| {
276            // Without the URL: reqwest's message names it.
277            let error = error.without_url();
278            Failure::Passing(if error.is_timeout() {
279                format!("no answer within {}s", self.settings.timeout.as_secs())
280            } else {
281                error.to_string()
282            })
283        })?;
284        let status = answer.status();
285        if status.is_success() {
286            Ok(())
287        } else if status.is_client_error()
288            && status != reqwest::StatusCode::REQUEST_TIMEOUT
289            && status != reqwest::StatusCode::TOO_MANY_REQUESTS
290        {
291            // It won't fix itself (decision 428).
292            Err(Failure::Refused(format!("HTTP {status}")))
293        } else {
294            Err(Failure::Passing(format!("HTTP {status}")))
295        }
296    }
297}
298
299impl Sender {
300    /// Mails `notification` to `to`: its body holds the email (`subject`, `text`), or, if it
301    /// was queued while its channel was missing, schedr's JSON.
302    async fn mail(&self, notification: &Notification, to: &[String]) -> Result<(), Failure> {
303        let (Some(transport), Some(smtp)) = (&self.smtp, &self.settings.smtp) else {
304            return Err(Failure::Passing(
305                "no [notifications.smtp] host in the configuration any more".to_owned(),
306            ));
307        };
308        let message = email(&smtp.from, to, &notification.body).map_err(Failure::Refused)?;
309        // A deadline over the whole exchange: lettre's own covers only connecting, and a server
310        // that never answers would hold up every notification behind it (Codex's review of
311        // M4.13b). Cut after the server took the message, it's sent again: at least once.
312        let timeout = self.settings.timeout;
313        match tokio::time::timeout(timeout, transport.send(message)).await {
314            Err(_) => Err(Failure::Passing(format!(
315                "no answer within {}s",
316                timeout.as_secs()
317            ))),
318            Ok(Ok(_)) => Ok(()),
319            // A 5xx won't fix itself (decision 428, as a webhook's 4xx).
320            Ok(Err(error)) if error.is_permanent() => Err(Failure::Refused(error.to_string())),
321            Ok(Err(error)) => Err(Failure::Passing(error.to_string())),
322        }
323    }
324}
325
326/// The message to `to` of an email notification's body: its `subject` and `text`, or schedr's
327/// JSON (queued while its channel was missing), its `text` as the subject and all of it below.
328fn email(from: &str, to: &[String], body: &serde_json::Value) -> Result<Message, String> {
329    let field = |key: &str| body.get(key).and_then(serde_json::Value::as_str);
330    let (subject, text) = if let (Some(subject), Some(text)) = (field("subject"), field("text")) {
331        (subject.to_owned(), text.to_owned())
332    } else {
333        let summary = field("text").unwrap_or("A notification from schedr");
334        let all = serde_json::to_string_pretty(body).unwrap_or_default();
335        (super::subject_of(summary), format!("{summary}\n\n{all}\n"))
336    };
337    let from = from.parse().map_err(|e| format!("from: {e}"))?;
338    let mut builder = Message::builder().from(from).subject(subject);
339    for address in to {
340        builder = builder.to(address
341            .parse()
342            .map_err(|e| format!("to `{address}`: {e}"))?);
343    }
344    builder
345        .header(lettre::message::header::ContentType::TEXT_PLAIN)
346        .body(text)
347        .map_err(|e| e.to_string())
348}
349
350/// The mail server's transport: TLS as `[notifications.smtp] tls` says, trusting the system's
351/// roots and `ca_file`'s; the login, if any.
352fn transport(
353    smtp: &Smtp,
354    extra_roots: Option<&[u8]>,
355    timeout: Duration,
356) -> Result<AsyncSmtpTransport<Tokio1Executor>, lettre::transport::smtp::Error> {
357    let tls = if smtp.tls == SmtpTls::None {
358        Tls::None
359    } else {
360        let mut parameters = TlsParameters::builder(smtp.host.clone());
361        if let Some(pem) = extra_roots {
362            parameters = parameters.add_root_certificate(Certificate::from_pem(pem)?);
363        }
364        let parameters = parameters.build()?;
365        if smtp.tls == SmtpTls::Tls {
366            Tls::Wrapper(parameters)
367        } else {
368            Tls::Required(parameters)
369        }
370    };
371    let mut builder = AsyncSmtpTransport::<Tokio1Executor>::builder_dangerous(&smtp.host)
372        .port(smtp.port)
373        .tls(tls)
374        .timeout(Some(timeout));
375    if let Some((user, password)) = &smtp.login {
376        builder = builder.credentials(Credentials::new(user.clone(), password.clone()));
377    }
378    Ok(builder.build())
379}
380
381/// How a delivery failed.
382#[derive(Debug)]
383enum Failure {
384    /// A 4xx but 408 and 429: dropped at once.
385    Refused(String),
386    /// Anything else: tried again until `give_up_after`.
387    Passing(String),
388}