1use std::{error::Error as StdError, time::Duration};
2
3use crate::config::program_config::ProgramConfig;
4use crate::prelude::*;
5use anyhow::{Context, Result};
6use chrono::{DateTime, Utc};
7use futures::{FutureExt, StreamExt};
8use headless_lms_models::email_deliveries::{
9 Email, EmailDeliveryErrorInsert, FETCH_LIMIT, RETRY_WINDOW_SECS, fetch_emails,
10 increment_retry_and_mark_non_retryable, increment_retry_and_schedule,
11 insert_email_delivery_error, mark_as_sent, maybe_purge_expired_recipient_addresses,
12};
13use headless_lms_models::email_templates::EmailTemplateType;
14use headless_lms_models::user_email_codes::UserEmailCodePurpose;
15use headless_lms_models::user_passwords::get_unused_reset_password_token_with_user_id;
16use headless_lms_utils::backoff;
17use headless_lms_utils::email_processor::{self, BlockAttributes, EmailGutenbergBlock};
18use lettre::transport::smtp::Error as SmtpError;
19use lettre::transport::smtp::authentication::Credentials;
20use lettre::{
21 Message, SmtpTransport, Transport,
22 message::{MultiPart, SinglePart, header},
23};
24use once_cell::sync::Lazy;
25use secrecy::ExposeSecret;
26use sqlx::{Connection, PgConnection, PgPool};
27use std::collections::HashMap;
28use uuid::Uuid;
29const BATCH_SIZE: usize = FETCH_LIMIT as usize;
30
31const RECIPIENT_ADDRESS_PURGE_INTERVAL: Duration = Duration::from_secs(60 * 60);
34
35const BASE_BACKOFF_SECS: i64 = 60;
36const MAX_BACKOFF_SECS: i64 = 24 * 60 * 60;
37const JITTER_SECS: i64 = 30;
38
39static SMTP_FROM: Lazy<String> = Lazy::new(|| {
40 ProgramConfig::required("SMTP_FROM").expect("No moocfi email found in the env variables.")
41});
42static BASE_URL: Lazy<String> = Lazy::new(|| {
46 ProgramConfig::required("BASE_URL").expect("No BASE_URL found in the env variables.")
47});
48static SMTP_HOST: Lazy<String> = Lazy::new(|| {
49 ProgramConfig::required("SMTP_HOST").expect("No email relay found in the env variables.")
50});
51static DB_URL: Lazy<String> = Lazy::new(|| {
52 ProgramConfig::required("DATABASE_URL").expect("No db url found in the env variables.")
53});
54static SMTP_MESSAGE_ID_DOMAIN: Lazy<String> = Lazy::new(|| {
55 ProgramConfig::optional("SMTP_MESSAGE_ID_DOMAIN")
56 .and_then(|value| {
57 let trimmed = value.trim();
58 if trimmed.is_empty() {
59 None
60 } else {
61 Some(trimmed.to_string())
62 }
63 })
64 .or_else(|| infer_email_domain(SMTP_FROM.as_str()))
65 .unwrap_or_else(|| "courses.mooc.fi".to_string())
66});
67static SMTP_USER: Lazy<String> = Lazy::new(|| {
68 ProgramConfig::required("SMTP_USER").expect("No smtp user found in env variables.")
69});
70static SMTP_PASS: Lazy<String> = Lazy::new(|| {
71 ProgramConfig::required("SMTP_PASS").expect("No smtp password found in env variables.")
72});
73
74pub async fn mail_sender(pool: &PgPool, mailer: &SmtpTransport) -> Result<()> {
75 let mut conn = pool.acquire().await?;
76
77 let emails = fetch_emails(&mut conn).await?;
78
79 let mut futures = tokio_stream::iter(emails)
80 .map(|email| {
81 let email_id = email.id;
82 send_message(email, mailer, pool.clone()).inspect(move |r| {
83 if let Err(err) = r {
84 tracing::error!("Failed to send email {}: {}", email_id, err)
85 }
86 })
87 })
88 .buffer_unordered(BATCH_SIZE);
89
90 while futures.next().await.is_some() {}
91
92 Ok(())
93}
94
95pub async fn send_message(email: Email, mailer: &SmtpTransport, pool: PgPool) -> Result<()> {
96 let mut conn = pool.acquire().await?;
97 tracing::info!("Email send messages...");
98
99 let now = Utc::now();
100 let attempt = email.retry_count + 1;
101 if retry_window_expired(email.first_failed_at, now) {
102 tracing::warn!(
103 "Retry window expired for email {} (first_failed_at={:?})",
104 email.id,
105 email.first_failed_at
106 );
107 record_non_retryable_failure(
108 &mut conn,
109 email.id,
110 attempt,
111 "retry_window_expired",
112 format!(
113 "Retry window expired before send attempt (email_id={}, user_id={:?}, template={:?}, first_failed_at={:?})",
114 email.id, email.user_id, email.template_type, email.first_failed_at
115 ),
116 )
117 .await?;
118 return Ok(());
119 }
120
121 let mut email_block: Vec<EmailGutenbergBlock> =
122 match email.body.as_ref().context("No body").and_then(|value| {
123 serde_json::from_value(value.clone()).context("Failed to parse email body JSON")
124 }) {
125 Ok(blocks) => blocks,
126 Err(err) => {
127 record_message_build_failure(&mut conn, &email, attempt, &err).await?;
128 return Ok(());
129 }
130 };
131
132 if let Some(template_type) = email.template_type {
133 let template_result = apply_email_template_replacements(
134 &mut conn,
135 template_type,
136 email.id,
137 email.user_id,
138 email.placeholders.as_ref(),
139 email_block,
140 attempt,
141 )
142 .await?;
143 match template_result {
144 TemplateApplyResult::Ready(blocks) => email_block = blocks,
145 TemplateApplyResult::Abandoned => return Ok(()),
146 }
147 }
148
149 let msg_as_plaintext = email_processor::process_content_to_plaintext(&email_block);
150 let msg_as_html = email_processor::process_content_to_html(&email_block);
151
152 let msg = match build_email_message(&email, attempt, msg_as_plaintext, msg_as_html) {
153 Ok(msg) => msg,
154 Err(err) => {
155 record_message_build_failure(&mut conn, &email, attempt, &err).await?;
156 return Ok(());
157 }
158 };
159
160 match mailer.send(&msg) {
161 Ok(_) => {
162 tracing::info!("Email sent successfully {}", email.id);
163 mark_as_sent(&mut conn, email.id)
164 .await
165 .context("Couldn't mark as sent")?;
166 }
167 Err(err) => {
168 let is_transient = is_transient_smtp_error(&err);
169 let (error_code, smtp_response, smtp_response_code) = extract_smtp_error_details(&err);
170
171 tracing::error!(
172 "SMTP send failed for {} (attempt {}, transient={}): {:?}",
173 email.id,
174 attempt,
175 is_transient,
176 err
177 );
178
179 let mut tx = (*conn)
180 .begin()
181 .await
182 .context("Couldn't start email failure transaction")?;
183
184 insert_email_delivery_error(
185 &mut tx,
186 EmailDeliveryErrorInsert {
187 email_delivery_id: email.id,
188 attempt,
189 error_message: err.to_string(),
190 error_code,
191 smtp_response,
192 smtp_response_code,
193 is_transient,
194 },
195 )
196 .await
197 .context("Couldn't insert email delivery error history")?;
198
199 if is_transient {
200 if retry_window_expired(Some(email.first_failed_at.unwrap_or(now)), now) {
201 increment_retry_and_mark_non_retryable(&mut tx, email.id)
202 .await
203 .context("Couldn't close expired retryable email")?;
204 } else {
205 let next_retry_at = compute_next_retry_at(now, email.retry_count);
208 increment_retry_and_schedule(&mut tx, email.id, Some(next_retry_at))
209 .await
210 .context("Couldn't schedule retry")?;
211 }
212 } else {
213 increment_retry_and_mark_non_retryable(&mut tx, email.id)
214 .await
215 .context("Couldn't close non-retryable email")?;
216 }
217
218 tx.commit()
219 .await
220 .context("Couldn't commit email failure transaction")?;
221 }
222 };
223
224 Ok(())
225}
226
227enum TemplateApplyResult {
228 Ready(Vec<EmailGutenbergBlock>),
229 Abandoned,
230}
231
232async fn apply_email_template_replacements(
233 conn: &mut PgConnection,
234 template_type: EmailTemplateType,
235 email_id: Uuid,
236 user_id: Option<Uuid>,
237 placeholders: Option<&serde_json::Value>,
238 blocks: Vec<EmailGutenbergBlock>,
239 attempt: i32,
240) -> anyhow::Result<TemplateApplyResult> {
241 let mut replacements = HashMap::new();
242
243 if template_type == EmailTemplateType::Generic {
244 return Ok(TemplateApplyResult::Ready(blocks));
245 }
246
247 if template_type.uses_placeholder_bag() {
248 let replacements = placeholder_bag_replacements(placeholders);
249 return Ok(TemplateApplyResult::Ready(insert_placeholders(
250 blocks,
251 &replacements,
252 )));
253 }
254
255 let Some(user_id) = user_id else {
257 let msg = format!(
258 "Template {template_type:?} requires a user but the delivery is addressed to a raw address"
259 );
260 record_non_retryable_failure(conn, email_id, attempt, "template", msg).await?;
261 return Ok(TemplateApplyResult::Abandoned);
262 };
263
264 match template_type {
265 EmailTemplateType::ResetPasswordEmail => {
266 if let Some(token_str) =
267 get_unused_reset_password_token_with_user_id(conn, user_id).await?
268 {
269 let reset_url = format!(
270 "{}/reset-user-password/{}",
271 BASE_URL.trim_end_matches('/'),
272 token_str.token
273 );
274
275 replacements.insert("RESET_LINK".to_string(), reset_url);
276 } else {
277 let msg = anyhow::anyhow!("No reset token found for user {}", user_id);
278 record_non_retryable_failure(conn, email_id, attempt, "template", msg.to_string())
279 .await?;
280 return Ok(TemplateApplyResult::Abandoned);
281 }
282 }
283 EmailTemplateType::DeleteUserEmail => {
284 if let Some(code) =
285 headless_lms_models::user_email_codes::get_unused_user_email_code_with_user_id(
286 conn,
287 user_id,
288 UserEmailCodePurpose::AccountDeletion,
289 )
290 .await?
291 {
292 replacements.insert("CODE".to_string(), code.code.expose_secret().to_string());
293 } else {
294 let msg = anyhow::anyhow!("No deletion code found for user {}", user_id);
295 record_non_retryable_failure(conn, email_id, attempt, "template", msg.to_string())
296 .await?;
297 return Ok(TemplateApplyResult::Abandoned);
298 }
299 }
300 EmailTemplateType::ConfirmEmailCode => {
301 if let Some(code) =
302 headless_lms_models::user_email_codes::get_unused_user_email_code_with_user_id(
303 conn,
304 user_id,
305 UserEmailCodePurpose::AdminLogin,
306 )
307 .await?
308 {
309 replacements.insert("CODE".to_string(), code.code.expose_secret().to_string());
310 } else {
311 let msg = anyhow::anyhow!("No verification code found for user {}", user_id);
312 record_non_retryable_failure(conn, email_id, attempt, "template", msg.to_string())
313 .await?;
314 return Ok(TemplateApplyResult::Abandoned);
315 }
316 }
317 EmailTemplateType::VerifyEmailAddress => {
318 if let Some(code) =
319 headless_lms_models::user_email_codes::get_unused_user_email_code_with_user_id(
320 conn,
321 user_id,
322 UserEmailCodePurpose::EmailOwnershipVerification,
323 )
324 .await?
325 {
326 replacements.insert("CODE".to_string(), code.code.expose_secret().to_string());
327 } else {
328 let msg = anyhow::anyhow!(
329 "No email ownership verification code found for user {}",
330 user_id
331 );
332 record_non_retryable_failure(conn, email_id, attempt, "template", msg.to_string())
333 .await?;
334 return Ok(TemplateApplyResult::Abandoned);
335 }
336 }
337 EmailTemplateType::Generic
339 | EmailTemplateType::CreditRegistrationAccountLinking
340 | EmailTemplateType::CreditRegistrationActionNeeded
341 | EmailTemplateType::CreditRegistrationRegistered
342 | EmailTemplateType::CreditRegistrationStudentNumberLinked => {}
343 }
344
345 Ok(TemplateApplyResult::Ready(insert_placeholders(
346 blocks,
347 &replacements,
348 )))
349}
350
351fn placeholder_bag_replacements(
354 placeholders: Option<&serde_json::Value>,
355) -> HashMap<String, String> {
356 let Some(serde_json::Value::Object(bag)) = placeholders else {
357 return HashMap::new();
358 };
359 bag.iter()
360 .filter_map(|(key, value)| {
361 let rendered = match value {
362 serde_json::Value::String(s) => s.clone(),
363 serde_json::Value::Number(n) => n.to_string(),
364 serde_json::Value::Bool(b) => b.to_string(),
365 _ => return None,
366 };
367 Some((key.clone(), rendered))
368 })
369 .collect()
370}
371
372fn insert_placeholders(
373 blocks: Vec<EmailGutenbergBlock>,
374 replacements: &HashMap<String, String>,
375) -> Vec<EmailGutenbergBlock> {
376 blocks
377 .into_iter()
378 .map(|mut block| {
379 if let BlockAttributes::Paragraph {
380 content,
381 drop_cap,
382 rest,
383 } = block.attributes
384 {
385 let replaced_content = replacements.iter().fold(content, |acc, (key, value)| {
386 acc.replace(&format!("{{{{{}}}}}", key), value)
387 });
388
389 block.attributes = BlockAttributes::Paragraph {
390 content: replaced_content,
391 drop_cap,
392 rest,
393 };
394 }
395 block
396 })
397 .collect()
398}
399
400fn build_email_message(
401 email: &Email,
402 attempt: i32,
403 msg_as_plaintext: String,
404 msg_as_html: String,
405) -> Result<Message> {
406 Message::builder()
407 .from(SMTP_FROM.parse()?)
408 .to(email
409 .to
410 .parse()
411 .with_context(|| format!("Invalid recipient address for email_id {}", email.id))?)
412 .subject(email.subject.clone().context("No subject")?)
413 .message_id(Some(format!(
414 "<{}-{}@{}>",
415 email.id,
416 attempt,
417 SMTP_MESSAGE_ID_DOMAIN.as_str()
418 )))
419 .multipart(
420 MultiPart::alternative()
421 .singlepart(
422 SinglePart::builder()
423 .header(header::ContentType::TEXT_PLAIN)
424 .body(msg_as_plaintext),
425 )
426 .singlepart(
427 SinglePart::builder()
428 .header(header::ContentType::TEXT_HTML)
429 .body(msg_as_html),
430 ),
431 )
432 .context("Failed to build email message")
433}
434
435fn infer_email_domain(value: &str) -> Option<String> {
436 let candidate = value
437 .rsplit('<')
438 .next()
439 .unwrap_or(value)
440 .trim()
441 .trim_end_matches('>')
442 .trim();
443 let (_, domain) = candidate.rsplit_once('@')?;
444 let domain = domain.trim();
445 if domain.is_empty() || domain.contains(' ') {
446 None
447 } else {
448 Some(domain.to_string())
449 }
450}
451
452async fn record_message_build_failure(
453 conn: &mut PgConnection,
454 email: &Email,
455 attempt: i32,
456 err: &anyhow::Error,
457) -> Result<()> {
458 tracing::error!(
459 "Message construction failed for email {} (attempt {}): {:#}",
460 email.id,
461 attempt,
462 err
463 );
464 record_non_retryable_failure(
465 conn,
466 email.id,
467 attempt,
468 "message_build",
469 format!("Message construction failed: {err:#}"),
470 )
471 .await
472}
473
474pub async fn main() -> anyhow::Result<()> {
475 tracing_subscriber::fmt().init();
476 dotenvy::dotenv().ok();
477 tracing::info!("Email sender starting up...");
478
479 if ProgramConfig::optional("SMTP_USER").is_none()
480 || ProgramConfig::optional("SMTP_PASS").is_none()
481 {
482 tracing::warn!("SMTP user or password is missing or incorrect");
483 }
484
485 let pool = PgPool::connect(&DB_URL.to_string()).await?;
486 let creds = Credentials::new(SMTP_USER.to_string(), SMTP_PASS.to_string());
487
488 let mailer = match SmtpTransport::relay(&SMTP_HOST) {
489 Ok(builder) => builder.credentials(creds).build(),
490 Err(e) => {
491 tracing::error!("Could not configure SMTP transport: {}", e);
492 return Err(e.into());
493 }
494 };
495
496 let mut interval = tokio::time::interval(Duration::from_secs(10));
497 let mut last_purge_attempt = tokio::time::Instant::now();
500 loop {
501 interval.tick().await;
502 mail_sender(&pool, &mailer).await?;
503
504 if last_purge_attempt.elapsed() >= RECIPIENT_ADDRESS_PURGE_INTERVAL {
507 last_purge_attempt = tokio::time::Instant::now();
508 let purged = async {
509 let mut conn = pool.acquire().await?;
510 maybe_purge_expired_recipient_addresses(&mut conn).await
511 }
512 .await;
513 match purged {
516 Ok(purged) if purged > 0 => {
517 tracing::info!(
518 "Purged retained recipient addresses from {purged} email deliveries"
519 )
520 }
521 Ok(_) => {}
522 Err(err) => tracing::error!("Failed to purge retained recipient addresses: {err}"),
523 }
524 }
525 }
526}
527
528fn retry_window_expired(first_failed_at: Option<DateTime<Utc>>, now: DateTime<Utc>) -> bool {
529 backoff::window_expired(first_failed_at, now, RETRY_WINDOW_SECS)
530}
531
532fn compute_next_retry_at(now: DateTime<Utc>, retry_count: i32) -> DateTime<Utc> {
533 let delay = backoff::exponential_backoff_secs(BASE_BACKOFF_SECS, MAX_BACKOFF_SECS, retry_count);
534 backoff::next_attempt_at(now, delay, JITTER_SECS)
535}
536
537fn is_transient_smtp_error(err: &SmtpError) -> bool {
538 if err.is_transient() {
539 return true;
540 }
541 if err.is_timeout() || err.is_transport_shutdown() {
542 return true;
543 }
544 has_io_error(err)
545}
546
547fn has_io_error(err: &SmtpError) -> bool {
548 let mut source = err.source();
549 while let Some(inner) = source {
550 if inner.is::<std::io::Error>() {
551 return true;
552 }
553 source = inner.source();
554 }
555 false
556}
557
558fn extract_smtp_error_details(err: &SmtpError) -> (Option<String>, Option<String>, Option<i32>) {
559 let smtp_response_code = err.status().map(|code| i32::from(u16::from(code)));
560
561 let error_code = if err.is_transient() {
562 Some("transient".to_string())
563 } else if err.is_permanent() {
564 Some("permanent".to_string())
565 } else if err.is_timeout() {
566 Some("timeout".to_string())
567 } else if has_io_error(err) {
568 Some("network_io".to_string())
569 } else if err.is_transport_shutdown() {
570 Some("transport_shutdown".to_string())
571 } else if err.is_response() {
572 Some("response".to_string())
573 } else if err.is_client() {
574 Some("client".to_string())
575 } else {
576 None
577 };
578
579 let smtp_response = err.source().map(|source| source.to_string());
580
581 (error_code, smtp_response, smtp_response_code)
582}
583
584async fn record_non_retryable_failure(
585 conn: &mut PgConnection,
586 email_id: Uuid,
587 attempt: i32,
588 error_code: &'static str,
589 message: String,
590) -> Result<()> {
591 let mut tx = (*conn)
592 .begin()
593 .await
594 .context("Couldn't start template failure transaction")?;
595
596 insert_email_delivery_error(
597 &mut tx,
598 EmailDeliveryErrorInsert {
599 email_delivery_id: email_id,
600 attempt,
601 error_message: message,
602 error_code: Some(error_code.to_string()),
603 smtp_response: None,
604 smtp_response_code: None,
605 is_transient: false,
606 },
607 )
608 .await
609 .context("Couldn't insert email delivery error history")?;
610
611 increment_retry_and_mark_non_retryable(&mut tx, email_id)
612 .await
613 .context("Couldn't mark email as non-retryable for template error")?;
614
615 tx.commit()
616 .await
617 .context("Couldn't commit template failure transaction")?;
618
619 Ok(())
620}