forge
Explore
Log in

Don't you dare go Hollow

im

Clone
★ 0

0 watching0 forksRustAGPL-3.0542.8 KiBb9f0726Tahinli27 days ago34 commits

worker.rs193 lines, 6.5 KiBHistoryRawDownload
1//! The mail worker (architecture section 8): sends the outbox, with retries.
2//!
3//! A row is tried when it is due. A failed try is retried after 1, 5, 15 and 60 minutes; the fifth
4//! failure abandons the row. A sent or abandoned row loses its sealed body in the same write. With no
5//! sender configured the rows wait untouched, and a sender that cannot be built (for example an unreadable
6//! password file) also spends no attempt.
7
8use std::sync::Arc;
9use std::time::Duration;
10
11use im_core::config::SmtpConfig;
12use im_core::secret;
13use im_core::store::Store;
14use im_core::store::mail::{MailAttempt, MailJob};
15use im_core::time::{now_stamp, stamp_after};
16use serde::Deserialize;
17use tokio::sync::watch;
18
19use super::message::{Recipient, Sender, build};
20use super::transport;
21
22/// Attempts before a row is abandoned.
23pub const MAX_ATTEMPTS: i64 = 5;
24
25/// How often the worker looks for due rows.
26const TICK: Duration = Duration::from_secs(5);
27
28/// The most rows one pass tries.
29const BATCH: i64 = 10;
30
31/// How long to wait before the next try, after `attempts` failed tries (1 to 4).
32pub fn retry_delay(attempts: i64) -> Duration {
33 match attempts {
34 1 => Duration::from_secs(60),
35 2 => Duration::from_secs(5 * 60),
36 3 => Duration::from_secs(15 * 60),
37 _ => Duration::from_secs(60 * 60),
38 }
39}
40
41/// The body as stored (after opening): the name, when known, and the two alternatives.
42#[derive(Deserialize)]
43struct Body {
44 to_name: Option<String>,
45 text: String,
46 html: String,
47}
48
49/// Starts the worker. It runs until `stop` is set.
50pub fn spawn(
51 store: Store,
52 key: Arc<[u8; 32]>,
53 smtp: SmtpConfig,
54 mut stop: watch::Receiver<bool>,
55) -> tokio::task::JoinHandle<()> {
56 tokio::spawn(async move {
57 if !smtp.enabled() {
58 tracing::info!("mail worker: no sender configured; mail waits in the outbox");
59 let _ = stop.wait_for(|stopped| *stopped).await;
60 return;
61 }
62 let sender = match Sender::from_config(&smtp) {
63 Ok(sender) => sender,
64 Err(error) => {
65 tracing::error!(error, "mail worker: the sender is not valid; mail waits");
66 let _ = stop.wait_for(|stopped| *stopped).await;
67 return;
68 }
69 };
70 loop {
71 run_once(&store, &key, &smtp, &sender).await;
72 tokio::select! {
73 () = tokio::time::sleep(TICK) => {}
74 _ = stop.wait_for(|stopped| *stopped) => break,
75 }
76 }
77 })
78}
79
80/// One pass: builds the transport (spending no attempt if that fails) and sends what is due.
81async fn run_once(store: &Store, key: &[u8; 32], smtp: &SmtpConfig, sender: &Sender) {
82 let password = if smtp.username.is_empty() {
83 None
84 } else {
85 match transport::read_password(&smtp.password_file) {
86 Ok(password) => Some(password),
87 Err(error) => {
88 tracing::error!(error, "mail worker: waiting, the sender is not ready");
89 return;
90 }
91 }
92 };
93 let transport = match transport::build(smtp, password) {
94 Ok(transport) => transport,
95 Err(error) => {
96 tracing::error!(error, "mail worker: waiting, the sender is not ready");
97 return;
98 }
99 };
100 if let Err(error) = deliver_due(store, key, sender, &transport, &now_stamp()).await {
101 tracing::error!(error = %error, "mail worker: outbox could not be read");
102 }
103}
104
105/// Sends the due rows through `transport` and records each outcome. Generic over the transport so the
106/// tests can use lettre's stub.
107pub async fn deliver_due<T>(
108 store: &Store,
109 key: &[u8; 32],
110 sender: &Sender,
111 transport: &T,
112 now: &str,
113) -> im_core::Result<usize>
114where
115 T: lettre::AsyncTransport + Sync,
116 T::Error: std::fmt::Debug,
117{
118 let due = store.due_mail(now, BATCH).await?;
119 let count = due.len();
120 for job in &due {
121 let attempt = attempt_once(sender, transport, key, job).await;
122 if let Err(error) = store.record_mail_attempt(&job.id, &attempt).await {
123 tracing::error!(error = %error, mail = %job.id, "mail outcome not recorded");
124 }
125 }
126 Ok(count)
127}
128
129/// Tries one row and says what happened to it.
130async fn attempt_once<T>(
131 sender: &Sender,
132 transport: &T,
133 key: &[u8; 32],
134 job: &MailJob,
135) -> MailAttempt
136where
137 T: lettre::AsyncTransport + Sync,
138 T::Error: std::fmt::Debug,
139{
140 // A body that cannot be opened or no longer checks out is not going to get better: give up now.
141 let message = match open_message(sender, key, job) {
142 Ok(message) => message,
143 Err(error) => {
144 tracing::error!(mail = %job.id, kind = %job.kind, error, "mail abandoned");
145 return MailAttempt::Abandon {
146 error: error.to_owned(),
147 };
148 }
149 };
150 match transport.send(message).await {
151 Ok(_) => {
152 tracing::info!(mail = %job.id, kind = %job.kind, "mail sent");
153 MailAttempt::Sent
154 }
155 Err(error) => {
156 let attempts = job.attempts + 1;
157 // The transport error describes the SMTP reply. The body is never part of it.
158 let reason = truncate(&format!("{error:?}"), 200);
159 if attempts >= MAX_ATTEMPTS {
160 tracing::error!(mail = %job.id, kind = %job.kind, attempts, "mail abandoned");
161 MailAttempt::Abandon { error: reason }
162 } else {
163 let delay = retry_delay(attempts);
164 tracing::warn!(mail = %job.id, kind = %job.kind, attempts, "mail attempt failed; retry scheduled");
165 MailAttempt::Retry {
166 next_at: stamp_after(delay),
167 error: reason,
168 }
169 }
170 }
171 }
172}
173
174/// Opens the sealed body and builds the message. Every failure is a fixed text.
175fn open_message(
176 sender: &Sender,
177 key: &[u8; 32],
178 job: &MailJob,
179) -> Result<lettre::Message, &'static str> {
180 if job.sealed_body.is_empty() {
181 return Err("mail body is missing");
182 }
183 let plain = secret::open(key, secret::purpose::MAIL_BODY, &job.sealed_body)
184 .map_err(|_| "mail body cannot be opened")?;
185 let body: Body = serde_json::from_slice(&plain).map_err(|_| "mail body is not valid")?;
186 let to = Recipient::new(body.to_name.as_deref(), &job.to_addr)?;
187 build(sender, &to, &job.subject, body.text, body.html)
188}
189
190/// Cuts `text` to at most `max` characters, on a character boundary.
191fn truncate(text: &str, max: usize) -> String {
192 text.chars().take(max).collect()
193}