| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | use std::sync::Arc; |
| 9 | use std::time::Duration; |
| 10 | |
| 11 | use im_core::config::SmtpConfig; |
| 12 | use im_core::secret; |
| 13 | use im_core::store::Store; |
| 14 | use im_core::store::mail::{MailAttempt, MailJob}; |
| 15 | use im_core::time::{now_stamp, stamp_after}; |
| 16 | use serde::Deserialize; |
| 17 | use tokio::sync::watch; |
| 18 | |
| 19 | use super::message::{Recipient, Sender, build}; |
| 20 | use super::transport; |
| 21 | |
| 22 | |
| 23 | pub const MAX_ATTEMPTS: i64 = 5; |
| 24 | |
| 25 | |
| 26 | const TICK: Duration = Duration::from_secs(5); |
| 27 | |
| 28 | |
| 29 | const BATCH: i64 = 10; |
| 30 | |
| 31 | |
| 32 | pub 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 | |
| 42 | #[derive(Deserialize)] |
| 43 | struct Body { |
| 44 | to_name: Option<String>, |
| 45 | text: String, |
| 46 | html: String, |
| 47 | } |
| 48 | |
| 49 | |
| 50 | pub 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 | |
| 81 | async 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 | |
| 106 | |
| 107 | pub 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> |
| 114 | where |
| 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 | |
| 130 | async fn attempt_once<T>( |
| 131 | sender: &Sender, |
| 132 | transport: &T, |
| 133 | key: &[u8; 32], |
| 134 | job: &MailJob, |
| 135 | ) -> MailAttempt |
| 136 | where |
| 137 | T: lettre::AsyncTransport + Sync, |
| 138 | T::Error: std::fmt::Debug, |
| 139 | { |
| 140 | |
| 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 | |
| 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 | |
| 175 | fn 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 | |
| 191 | fn truncate(text: &str, max: usize) -> String { |
| 192 | text.chars().take(max).collect() |
| 193 | } |