Skip to main content

ocre/mail/
intercept.rs

1//! [`intercept`]: change or stop outgoing email before any adapter sends it (Rails' mail interceptors).
2
3use std::sync::{Arc, Mutex, PoisonError};
4
5use super::Email;
6
7/// An interceptor: returns the email to send (changed or not), or `None` to drop it.
8type Interceptor = dyn Fn(Email, &dyn Fn(&str) -> Option<String>) -> Option<Email> + Send + Sync;
9
10static INTERCEPTORS: Mutex<Vec<Arc<Interceptor>>> = Mutex::new(Vec::new());
11
12/// Registers an interceptor every outgoing email goes through, in registration order, before the adapter sends it.
13///
14/// Rails' `register_interceptor`: `interceptor` gets the [`Email`] and a
15/// lookup of Worker variables and secrets, and returns the email to send
16/// (rewritten, e.g. every recipient replaced on a staging copy) or `None`
17/// to drop it, logged as `[ocre mail] dropped by an interceptor: ...`. It
18/// applies to [`send`](crate::mail::send) and to emails sent from the
19/// queue ([`deliver_later`](crate::mail::deliver_later)), whatever the
20/// adapter, `log` included. Register interceptors once per Worker instance,
21/// in the `start` event of `src/lib.rs`.
22///
23/// # Examples
24///
25/// A safety switch for automated emails on a copy of production's users:
26/// marketing emails carry `X-Category: marketing`, and go out only when the
27/// `MARKETING_EMAILS` variable is `on`.
28///
29/// ```no_run
30/// #[worker::event(start)]
31/// fn start() {
32///     ocre::mail::intercept(|email, vars| {
33///         let marketing = email.headers.iter().any(|(name, value)| name == "X-Category" && value == "marketing");
34///         let allowed = vars("MARKETING_EMAILS").is_some_and(|value| value.trim() == "on");
35///         (!marketing || allowed).then_some(email)
36///     });
37/// }
38/// ```
39pub fn intercept(
40    interceptor: impl Fn(Email, &dyn Fn(&str) -> Option<String>) -> Option<Email> + Send + Sync + 'static,
41) {
42    INTERCEPTORS.lock().unwrap_or_else(PoisonError::into_inner).push(Arc::new(interceptor));
43}
44
45/// The email after every registered interceptor, or `None` when one dropped it.
46pub(crate) fn intercepted(email: Email, vars: &dyn Fn(&str) -> Option<String>) -> Option<Email> {
47    let interceptors = INTERCEPTORS.lock().unwrap_or_else(PoisonError::into_inner).clone();
48    run(&interceptors, email, vars)
49}
50
51fn run(interceptors: &[Arc<Interceptor>], email: Email, vars: &dyn Fn(&str) -> Option<String>) -> Option<Email> {
52    interceptors.iter().try_fold(email, |email, interceptor| interceptor(email, vars))
53}
54
55/// The log line of a dropped email: subject and recipients.
56pub(crate) fn dropped_line(email: &Email) -> String {
57    format!("{} dropped by an interceptor: {:?} to {}", super::LOG_PREFIX, email.subject, email.to.join(", "))
58}
59
60#[cfg(test)]
61#[path = "../../tests/mail/intercept.rs"]
62mod tests;