larust_mail/queue_job.rs
1//! The already-rendered form of an email, enqueued by
2//! `MailBuilder::queue` - see that method's own doc comment for the full
3//! design rationale (why the typed `Mailable` itself can't be queued, and
4//! the deliberate deviation from Laravel's re-resolve-on-worker
5//! semantics).
6
7use crate::send::deliver;
8use larust_core::AppError;
9use larust_queue::Job;
10use serde::{Deserialize, Serialize};
11
12/// Framework-owned - fields are `pub(crate)`, so this is only ever built
13/// by `MailBuilder::queue`, never constructed (or queued) directly by app
14/// code. `registry.register::<larust_support::mail::MailJob>()` is a
15/// real registration, no different from any app-defined `Job`'s - it's
16/// just that `xr new`'s scaffold writes that line into every generated
17/// app's `queue:work` branch by default, rather than leaving it as a
18/// hint the app author must remember to add.
19#[derive(Serialize, Deserialize)]
20pub struct MailJob {
21 pub(crate) to: Vec<String>,
22 pub(crate) subject: String,
23 pub(crate) html_body: String,
24}
25
26impl Job for MailJob {
27 // `__larust_`-prefixed, matching this codebase's existing convention
28 // for framework-owned internal identifiers (`/__larust_wire/...`,
29 // `/__larust_push/{channel}`) - low collision risk against an app's
30 // own hand-chosen `JOB_TYPE` strings.
31 const JOB_TYPE: &'static str = "__larust_queued_mail";
32
33 async fn handle(&self) -> Result<(), AppError> {
34 deliver(&self.to, &self.subject, &self.html_body).await
35 }
36}
37
38#[cfg(test)]
39mod tests {
40 use super::*;
41 use larust_queue::{work, JobRegistry};
42 use std::time::Duration;
43
44 async fn connect_test_db() {
45 let dir = tempfile::tempdir().unwrap().keep();
46 let database_url = format!("sqlite://{}/test.sqlite", dir.display());
47 larust_orm::connect(&database_url).await.unwrap();
48 }
49
50 /// `deliver`'s log-driver branch reads `larust_core::config()`, which
51 /// panics if `Application::new()` was never called in this process.
52 /// Safe to call here: an empty config value, so nothing pulls in
53 /// unexpected settings - this defaults to `mail_driver = "log"` - no
54 /// network ever touched by these tests.
55 fn ensure_config() {
56 let _ = larust_core::Application::new(|| serde_json::json!({}));
57 }
58
59 /// Both scenarios share one test function, not two: `larust_orm::
60 /// connect()` sets a process-wide pool exactly once (a second call in
61 /// the same test binary errors with "connect() called more than
62 /// once"), the same singleton-per-process constraint `fake.rs`'s own
63 /// tests document for `FAKE_SENT`. Each phase's own `work()` loop
64 /// (which never returns on its own) is `.abort()`-ed before the next
65 /// phase starts a different one against the same `jobs` table, so the
66 /// two workers never race each other over the same row.
67 #[tokio::test]
68 async fn queued_mail_delivers_when_registered_and_fails_loudly_when_not() {
69 ensure_config();
70 connect_test_db().await;
71 let pool = larust_orm::pool().unwrap();
72
73 // Phase 1: a registered worker claims and delivers the job.
74 larust_queue::dispatch(&MailJob {
75 to: vec!["someone@example.test".to_string()],
76 subject: "Hello".to_string(),
77 html_body: "<p>Hi</p>".to_string(),
78 })
79 .await
80 .unwrap();
81
82 let registry = JobRegistry::new().register::<MailJob>();
83 let worker = tokio::spawn(work(registry));
84 // `work()` polls every 500ms when idle, but the job is already
85 // present the moment it starts, so it's claimed on the very
86 // first iteration - comfortably bounded well under that interval.
87 tokio::time::sleep(Duration::from_millis(200)).await;
88 worker.abort();
89
90 let jobs: (i64,) = sqlx::query_as("SELECT COUNT(*) FROM jobs")
91 .fetch_one(pool)
92 .await
93 .unwrap();
94 assert_eq!(jobs.0, 0, "the queued mail job should have been claimed");
95
96 let failed: (i64,) = sqlx::query_as("SELECT COUNT(*) FROM failed_jobs")
97 .fetch_one(pool)
98 .await
99 .unwrap();
100 assert_eq!(
101 failed.0, 0,
102 "a registered MailJob delivered via the log driver should never fail"
103 );
104
105 // Phase 2: an unregistered worker records "no handler" instead of
106 // silently delivering - proves `.queue()`'d mail isn't magically
107 // delivered without the app explicitly registering `MailJob`.
108 larust_queue::dispatch(&MailJob {
109 to: vec!["someone@example.test".to_string()],
110 subject: "Hello".to_string(),
111 html_body: "<p>Hi</p>".to_string(),
112 })
113 .await
114 .unwrap();
115
116 let registry = JobRegistry::new();
117 let worker = tokio::spawn(work(registry));
118 // A failing job isn't recorded to `failed_jobs` on its first
119 // attempt - `process_next` only does that once `attempts` reaches
120 // `MAX_ATTEMPTS` (3); every attempt before that just reschedules
121 // via `release_for_retry`'s real exponential backoff (starting at
122 // a full second), which a fixed short sleep can never outlast
123 // deterministically. Forcing `available_at` back to "now" between
124 // checks makes each retry immediately eligible instead of waiting
125 // out real backoff - the same technique `sql_worker.rs`'s own
126 // `dispatch_and_work_round_trip_including_failures` test already
127 // uses for identical reasoning. Bounded, not a blind sleep: exits
128 // the moment the job is gone from `jobs` (claimed, retried to
129 // exhaustion, and recorded), rather than a fixed guess.
130 for _ in 0..50 {
131 tokio::time::sleep(Duration::from_millis(20)).await;
132 sqlx::query("UPDATE jobs SET available_at = 0 WHERE reserved_at IS NULL")
133 .execute(pool)
134 .await
135 .unwrap();
136 let remaining: (i64,) = sqlx::query_as("SELECT COUNT(*) FROM jobs")
137 .fetch_one(pool)
138 .await
139 .unwrap();
140 if remaining.0 == 0 {
141 break;
142 }
143 }
144 worker.abort();
145
146 let failed: (String,) =
147 sqlx::query_as("SELECT error FROM failed_jobs ORDER BY id DESC LIMIT 1")
148 .fetch_one(pool)
149 .await
150 .unwrap();
151 assert!(failed.0.contains("no handler registered"));
152 }
153}