forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.07.1 MiB490f099Tahinli7 hours ago322 commits

worker.rs374 lines, 13.3 KiBHistoryRawDownload
1//! The mail worker. It leases due outbox rows and sends them. A transient failure is retried on
2//! the schedule in `forge_core::mail::retry_delay`; a permanent one, or the last failed try, gives
3//! up. It sleeps until the next due time, or until `AppState::mail_waker` is notified (a message
4//! was queued, or the settings changed). While mail is off it sends nothing and keeps the
5//! messages queued.
6
7use std::time::Duration;
8
9use forge_core::mail::{MailError, OutboxEntry, OutgoingMail, retry_delay};
10use forge_core::time::{now_stamp, stamp_after};
11use time::OffsetDateTime;
12use time::format_description::well_known::Rfc3339;
13
14use crate::mail::live;
15use crate::state::AppState;
16
17/// The longest the worker sleeps. It guards against a missed wake, not polling.
18const BACKSTOP: Duration = Duration::from_secs(15 * 60);
19/// The shortest sleep, so a due time that has already passed does not spin the loop.
20const MIN_SLEEP: Duration = Duration::from_secs(1);
21/// Messages leased per pass.
22const BATCH: u32 = 20;
23/// How long a leased row stays with this pass before another may take it.
24const LEASE: Duration = Duration::from_secs(5 * 60);
25
26/// Starts the worker task. It runs until the process exits.
27pub fn spawn(state: AppState) {
28 tokio::spawn(run(state));
29}
30
31/// Makes the outbox safe to resume after a restart: a row leased by a pass that died is released,
32/// so it is sent on the first pass instead of after its lease runs out. A message whose send had
33/// started but not finished may be sent again; that is the price of a queue that never loses mail.
34pub async fn boot(state: &AppState) -> forge_core::Result<u64> {
35 let released = state.store.release_mail_leases().await?;
36 if released > 0 {
37 tracing::info!(released, "mail: released leases left by an earlier run");
38 live::bump();
39 }
40 Ok(released)
41}
42
43async fn run(state: AppState) {
44 if let Err(e) = boot(&state).await {
45 tracing::error!(error = %e, "mail: could not release leases at boot");
46 }
47 loop {
48 let nap = match tick(&state).await {
49 Ok(nap) => nap,
50 Err(e) => {
51 tracing::error!(error = %e, "mail: could not run a pass");
52 BACKSTOP
53 }
54 };
55 tokio::select! {
56 _ = tokio::time::sleep(nap) => {}
57 _ = state.mail_waker.notified() => {}
58 }
59 }
60}
61
62/// One pass: sends what is due when mail is on. Returns how long to sleep before the next one.
63async fn tick(state: &AppState) -> forge_core::Result<Duration> {
64 let settings = state.store.mail_settings().await?;
65 if !settings.enabled {
66 // Turning mail on notifies the waker; the backstop only guards a missed wake.
67 return Ok(BACKSTOP);
68 }
69 let now = now_stamp();
70 let lease_until = stamp_after(LEASE);
71 let leased = state.store.lease_mail(&now, &lease_until, BATCH).await?;
72 if !leased.is_empty() {
73 // The queue page shows these as Sending while the batch goes out.
74 live::bump();
75 }
76 for entry in leased {
77 deliver(state, &entry).await;
78 }
79 let next = state.store.next_mail_due().await?;
80 Ok(sleep_for(next.as_deref(), OffsetDateTime::now_utc()))
81}
82
83/// Sends one leased message and records the outcome.
84async fn deliver(state: &AppState, entry: &OutboxEntry) {
85 let mail = OutgoingMail {
86 to: entry.to_addr.clone(),
87 subject: entry.subject.clone(),
88 body: entry.body.clone(),
89 message_id: entry.message_id.clone(),
90 in_reply_to: entry.in_reply_to.clone(),
91 kind: entry.kind,
92 user_id: entry.user_id.clone(),
93 };
94 let recorded = match state.mailer.send(&mail).await {
95 Ok(()) => state.store.mark_mail_sent(&entry.id, &now_stamp()).await,
96 Err(MailError::Permanent(error)) => {
97 tracing::warn!(id = %entry.id, error = %error, "mail: permanent failure, giving up");
98 state.store.mark_mail_failed(&entry.id, &error, None).await
99 }
100 Err(MailError::Transient(error)) => {
101 // `attempts` counts the tries before this one; this try makes one more.
102 let next = retry_delay(entry.attempts + 1).map(stamp_after);
103 if next.is_none() {
104 tracing::warn!(id = %entry.id, error = %error, "mail: last try failed, giving up");
105 } else {
106 tracing::info!(id = %entry.id, error = %error, "mail: try failed, will retry");
107 }
108 state
109 .store
110 .mark_mail_failed(&entry.id, &error, next.as_deref())
111 .await
112 }
113 };
114 if let Err(e) = recorded {
115 tracing::error!(id = %entry.id, error = %e, "mail: could not record the outcome");
116 }
117 live::bump();
118}
119
120/// How long the worker sleeps: until `next_due` (an RFC 3339 stamp), clamped to
121/// `MIN_SLEEP..=BACKSTOP`. `None` (nothing queued) or an unparsable stamp gives `BACKSTOP`.
122pub fn sleep_for(next_due: Option<&str>, now: OffsetDateTime) -> Duration {
123 let Some(due) = next_due.and_then(|s| OffsetDateTime::parse(s, &Rfc3339).ok()) else {
124 return BACKSTOP;
125 };
126 let until = Duration::try_from(due - now).unwrap_or(Duration::ZERO);
127 until.clamp(MIN_SLEEP, BACKSTOP)
128}
129
130#[cfg(test)]
131mod tests {
132 use std::sync::Arc;
133
134 use forge_core::mail::{MailKind, MailSettingsUpdate, OutboxStatus, Security};
135 use forge_core::time::{now_stamp, stamp_after};
136
137 use super::*;
138 use crate::mail::{FakeMailer, enqueue};
139 use crate::test_support::test_state;
140
141 async fn enabled_state(dir: &std::path::Path) -> (AppState, Arc<FakeMailer>) {
142 let mut state = test_state(dir).await;
143 let fake = Arc::new(FakeMailer::default());
144 state.mailer = fake.clone();
145 state
146 .store
147 .update_mail_settings(&MailSettingsUpdate {
148 host: "smtp.example",
149 port: 587,
150 security: Security::StartTls,
151 username: "",
152 from_addr: "forge@example.com",
153 from_name: "forge",
154 enabled: true,
155 password: None,
156 })
157 .await
158 .expect("settings");
159 (state, fake)
160 }
161
162 #[test]
163 fn sleep_stops_at_the_next_due_time_and_is_clamped() {
164 use time::macros::datetime;
165
166 let now = datetime!(2026-10-15 12:00:00 UTC);
167 let stamp = |t: OffsetDateTime| t.format(&Rfc3339).expect("stamp");
168 assert_eq!(sleep_for(None, now), BACKSTOP);
169 let in_10s = stamp(now + time::Duration::seconds(10));
170 assert_eq!(sleep_for(Some(&in_10s), now), Duration::from_secs(10));
171 let in_1h = stamp(now + time::Duration::hours(1));
172 assert_eq!(sleep_for(Some(&in_1h), now), BACKSTOP);
173 let past = stamp(now - time::Duration::seconds(5));
174 assert_eq!(sleep_for(Some(&past), now), MIN_SLEEP);
175 assert_eq!(sleep_for(Some("soon"), now), BACKSTOP);
176 }
177
178 #[tokio::test]
179 async fn a_row_leased_before_a_restart_is_sent_by_the_first_pass_after_boot() {
180 let dir = tempfile::tempdir().expect("tempdir");
181 let (state, fake) = enabled_state(dir.path()).await;
182 enqueue(
183 &state,
184 "stuck",
185 MailKind::Notification,
186 None,
187 "a@example.com",
188 "Hi",
189 "body",
190 )
191 .await
192 .expect("queued");
193 // A pass that took the row and died before it finished: the lease is still set.
194 let held = state
195 .store
196 .lease_mail(&now_stamp(), &stamp_after(LEASE), BATCH)
197 .await
198 .expect("lease");
199 assert_eq!(held.len(), 1);
200 assert!(fake.sent().is_empty());
201
202 assert_eq!(boot(&state).await.expect("boot"), 1);
203 tick(&state).await.expect("pass");
204 assert_eq!(
205 fake.sent().len(),
206 1,
207 "the released row goes out without waiting"
208 );
209 let row = state.store.recent_mail(10).await.expect("rows").remove(0);
210 assert_eq!(row.status(), OutboxStatus::Sent);
211 }
212
213 #[tokio::test]
214 async fn a_queued_message_is_sent_once() {
215 let dir = tempfile::tempdir().expect("tempdir");
216 let (state, fake) = enabled_state(dir.path()).await;
217 assert!(
218 enqueue(
219 &state,
220 "reset:1",
221 MailKind::PasswordReset,
222 None,
223 "a@example.com",
224 "Hi",
225 "body"
226 )
227 .await
228 .expect("queued")
229 );
230 // A second enqueue with the same key is a no-op.
231 assert!(
232 !enqueue(
233 &state,
234 "reset:1",
235 MailKind::PasswordReset,
236 None,
237 "a@example.com",
238 "Hi",
239 "body"
240 )
241 .await
242 .expect("again")
243 );
244
245 tick(&state).await.expect("pass");
246 tick(&state).await.expect("second pass");
247 let sent = fake.sent();
248 assert_eq!(sent.len(), 1);
249 assert_eq!(sent[0].to, "a@example.com");
250 let row = state.store.recent_mail(10).await.expect("rows");
251 assert_eq!(row.len(), 1);
252 assert_eq!(row[0].status(), OutboxStatus::Sent);
253 }
254
255 #[tokio::test]
256 async fn nothing_is_sent_while_mail_is_off() {
257 let dir = tempfile::tempdir().expect("tempdir");
258 let (state, fake) = enabled_state(dir.path()).await;
259 state
260 .store
261 .update_mail_settings(&MailSettingsUpdate {
262 host: "smtp.example",
263 port: 587,
264 security: Security::StartTls,
265 username: "",
266 from_addr: "forge@example.com",
267 from_name: "forge",
268 enabled: false,
269 password: None,
270 })
271 .await
272 .expect("off");
273 enqueue(
274 &state,
275 "k",
276 MailKind::Other,
277 None,
278 "a@example.com",
279 "Hi",
280 "body",
281 )
282 .await
283 .expect("queued");
284 assert_eq!(tick(&state).await.expect("pass"), BACKSTOP);
285 assert!(fake.sent().is_empty());
286 let row = state.store.recent_mail(10).await.expect("rows");
287 assert_eq!(row[0].status(), OutboxStatus::Queued);
288 assert_eq!(row[0].attempts, 0, "waiting costs no attempts");
289 }
290
291 #[tokio::test]
292 async fn a_transient_failure_is_retried_later_and_a_permanent_one_gives_up() {
293 let dir = tempfile::tempdir().expect("tempdir");
294 let (state, fake) = enabled_state(dir.path()).await;
295 enqueue(
296 &state,
297 "retry",
298 MailKind::Other,
299 None,
300 "a@example.com",
301 "Hi",
302 "body",
303 )
304 .await
305 .expect("queued");
306 enqueue(
307 &state,
308 "bounce",
309 MailKind::Other,
310 None,
311 "b@example.com",
312 "Hi",
313 "body",
314 )
315 .await
316 .expect("queued");
317 fake.fail_next(MailError::Transient("timeout".into()));
318 fake.fail_next(MailError::Permanent("550 no such user".into()));
319
320 tick(&state).await.expect("pass");
321 let rows = state.store.recent_mail(10).await.expect("rows");
322 let by_key = |to: &str| rows.iter().find(|r| r.to_addr == to).expect("row").clone();
323
324 let retried = by_key("a@example.com");
325 assert_eq!(retried.status(), OutboxStatus::Queued);
326 assert_eq!(retried.attempts, 1);
327 assert_eq!(retried.last_error.as_deref(), Some("timeout"));
328 let due = retried.next_attempt_at.expect("scheduled");
329 assert!(due > now_stamp(), "the retry waits about a minute");
330 assert!(due <= stamp_after(Duration::from_secs(120)));
331
332 let bounced = by_key("b@example.com");
333 assert_eq!(bounced.status(), OutboxStatus::GaveUp);
334 assert_eq!(bounced.attempts, 1);
335 assert_eq!(bounced.last_error.as_deref(), Some("550 no such user"));
336 assert_eq!(fake.sent().len(), 0, "nothing reached the transport");
337 }
338
339 #[tokio::test]
340 async fn the_last_try_gives_up_and_an_earlier_one_reschedules() {
341 let dir = tempfile::tempdir().expect("tempdir");
342 let (state, fake) = enabled_state(dir.path()).await;
343 enqueue(
344 &state,
345 "stubborn",
346 MailKind::Other,
347 None,
348 "a@example.com",
349 "Hi",
350 "body",
351 )
352 .await
353 .expect("queued");
354 let row = state.store.recent_mail(10).await.expect("rows").remove(0);
355 fake.fail_next(MailError::Transient("timeout".into()));
356 fake.fail_next(MailError::Transient("timeout".into()));
357
358 // The row has failed MAX_ATTEMPTS - 1 times already: this try is the last one.
359 let last = OutboxEntry {
360 attempts: forge_core::mail::MAX_ATTEMPTS - 1,
361 ..row.clone()
362 };
363 deliver(&state, &last).await;
364 let after = state.store.recent_mail(10).await.expect("rows").remove(0);
365 assert_eq!(after.status(), OutboxStatus::GaveUp);
366 assert_eq!(after.last_error.as_deref(), Some("timeout"));
367
368 // The same failure on an early try is rescheduled instead.
369 let early = OutboxEntry { attempts: 1, ..row };
370 deliver(&state, &early).await;
371 let after = state.store.recent_mail(10).await.expect("rows").remove(0);
372 assert_eq!(after.status(), OutboxStatus::Queued);
373 }
374}