forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.07.1 MiB490f099Tahinli7 hours ago322 commits

mod.rs116 lines, 3.5 KiBHistoryRawDownload
1//! Outgoing mail. Callers queue a message with [`enqueue`]; the worker in [`worker`] sends it
2//! through the [`Mailer`] held in `AppState`, retrying on the schedule in `forge_core::mail`.
3//! Nothing sends mail inside a request.
4
5pub mod account;
6pub mod live;
7pub mod log;
8pub mod smtp;
9pub mod templates;
10pub mod worker;
11
12use std::future::Future;
13use std::pin::Pin;
14
15use forge_core::mail::{MailError, MailKind, OutgoingMail};
16
17use crate::state::AppState;
18
19pub use log::LogMailer;
20pub use smtp::SmtpMailer;
21
22/// The future a [`Mailer::send`] call returns.
23pub type SendFuture<'a> = Pin<Box<dyn Future<Output = Result<(), MailError>> + Send + 'a>>;
24
25/// A transport that delivers one message. Object-safe, so `AppState` holds it as `Arc<dyn Mailer>`.
26pub trait Mailer: Send + Sync {
27 /// Delivers `mail`. Must not return until the transport has finished or timed out.
28 fn send<'a>(&'a self, mail: &'a OutgoingMail) -> SendFuture<'a>;
29}
30
31/// Queues one message of `kind` about the account `user_id` (if any), keyed by `idem_key`. Returns
32/// `false` when that key was already queued, so the caller can retry without sending twice. The
33/// worker is woken to pick it up.
34pub async fn enqueue(
35 state: &AppState,
36 idem_key: &str,
37 kind: MailKind,
38 user_id: Option<&str>,
39 to: &str,
40 subject: &str,
41 body: &str,
42) -> forge_core::Result<bool> {
43 let mail = OutgoingMail {
44 to: to.to_owned(),
45 subject: subject.to_owned(),
46 body: body.to_owned(),
47 message_id: None,
48 in_reply_to: None,
49 kind,
50 user_id: user_id.map(str::to_owned),
51 };
52 enqueue_message(state, idem_key, &mail).await
53}
54
55/// Queues a message that may carry threading headers. Same contract as [`enqueue`].
56pub async fn enqueue_message(
57 state: &AppState,
58 idem_key: &str,
59 mail: &OutgoingMail,
60) -> forge_core::Result<bool> {
61 let queued = state.store.enqueue_mail(idem_key, mail).await?;
62 if queued {
63 state.mail_waker.notify_one();
64 live::bump();
65 }
66 Ok(queued)
67}
68
69/// A mailer for tests. It records every message it accepts. [`FakeMailer::fail_next`] makes the
70/// next sends fail, to exercise the retry path.
71#[cfg(any(test, feature = "test-support"))]
72#[derive(Default)]
73pub struct FakeMailer {
74 sent: std::sync::Mutex<Vec<OutgoingMail>>,
75 failures: std::sync::Mutex<std::collections::VecDeque<MailError>>,
76}
77
78#[cfg(any(test, feature = "test-support"))]
79impl FakeMailer {
80 /// Messages accepted so far, oldest first.
81 pub fn sent(&self) -> Vec<OutgoingMail> {
82 self.sent
83 .lock()
84 .unwrap_or_else(std::sync::PoisonError::into_inner)
85 .clone()
86 }
87
88 /// Queues one failure for the next send.
89 pub fn fail_next(&self, error: MailError) {
90 self.failures
91 .lock()
92 .unwrap_or_else(std::sync::PoisonError::into_inner)
93 .push_back(error);
94 }
95}
96
97#[cfg(any(test, feature = "test-support"))]
98impl Mailer for FakeMailer {
99 fn send<'a>(&'a self, mail: &'a OutgoingMail) -> SendFuture<'a> {
100 Box::pin(async move {
101 let failure = self
102 .failures
103 .lock()
104 .unwrap_or_else(std::sync::PoisonError::into_inner)
105 .pop_front();
106 if let Some(error) = failure {
107 return Err(error);
108 }
109 self.sent
110 .lock()
111 .unwrap_or_else(std::sync::PoisonError::into_inner)
112 .push(mail.clone());
113 Ok(())
114 })
115 }
116}