schedr_master/notifications/
sender.rs1use 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
23pub const BATCH: u32 = 50;
25
26#[derive(Debug, Clone, Copy, PartialEq, Eq)]
28pub struct Backoff {
29 pub first: Duration,
31 pub max: Duration,
33}
34
35impl Backoff {
36 #[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#[derive(Debug, Clone)]
48pub struct Sender {
49 db: Database,
50 settings: Arc<Notifications>,
51 client: reqwest::Client,
52 metrics: MasterMetrics,
53 backoff: Backoff,
54 smtp: Option<AsyncSmtpTransport<Tokio1Executor>>,
56 per_pass: u32,
58}
59
60#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
62pub struct Pass {
63 pub sent: usize,
65 pub retried: usize,
67 pub dropped: usize,
69}
70
71impl Sender {
72 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 #[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 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 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(¬ification.id).await?;
145 self.metrics.notification_failed(¬ification.channel);
146 pass.dropped += 1;
147 continue;
148 }
149 match self.deliver(¬ification).await {
150 Ok(()) => {
151 self.db.delete_notification(¬ification.id).await?;
152 self.metrics.notification_sent(¬ification.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(¬ification.id).await?;
165 self.metrics.notification_failed(¬ification.channel);
166 pass.dropped += 1;
167 }
168 Err(Failure::Passing(error)) if self.given_up(¬ification, 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(¬ification.id).await?;
179 self.metrics.notification_failed(¬ification.channel);
180 pass.dropped += 1;
181 }
182 Err(Failure::Passing(error))
183 if notification.url.is_none()
184 && !self.settings.servers.contains_key(¬ification.channel)
185 && !self.settings.emails.contains_key(¬ification.channel) =>
186 {
187 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(¬ification, 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(¬ification, 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(¬ification.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 async fn deliver(&self, notification: &Notification) -> Result<(), Failure> {
242 if notification.url.is_none()
246 && let Some(channel) = self.settings.emails.get(¬ification.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) = ¬ification.url {
257 (url.as_str(), &[][..])
258 } else {
259 let server = self
260 .settings
261 .servers
262 .get(¬ification.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(¬ification.body);
272 for (name, value) in headers {
273 request = request.header(name, value);
274 }
275 let answer = request.send().await.map_err(|error| {
276 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 Err(Failure::Refused(format!("HTTP {status}")))
293 } else {
294 Err(Failure::Passing(format!("HTTP {status}")))
295 }
296 }
297}
298
299impl Sender {
300 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, ¬ification.body).map_err(Failure::Refused)?;
309 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 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
326fn 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
350fn 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#[derive(Debug)]
383enum Failure {
384 Refused(String),
386 Passing(String),
388}