larust_queue/lib.rs
1//! A durable job queue - Laravel's `dispatch(new Job)`/`queue:work`.
2//! Unlike `larust-events` (in-process, synchronous, no persistence), a
3//! `Job` survives the current request and even a process restart:
4//! `dispatch()` enqueues it durably; a separate `xr queue:work` process
5//! (backed by `work()`) claims and executes jobs until stopped.
6//!
7//! Backed by SQL-family storage (`Config::queue_driver == "database"`, the
8//! default) or Redis (`"redis"`) - see [`dispatch`]/[`worker`]'s own doc
9//! comments for the dispatch shape, and [`sql_worker`]/[`redis_worker`]
10//! for the two claim/lease/retry implementations.
11
12mod dispatch;
13mod prune;
14mod redis_conn;
15mod redis_dispatch;
16mod redis_worker;
17mod sql_dispatch;
18mod sql_worker;
19mod worker;
20
21pub use dispatch::{dispatch, Job};
22pub use prune::prune_failed_jobs;
23pub use worker::{work, JobRegistry};
24
25/// Uses `larust_core::try_config()`, not `config()` - see
26/// `larust_cache::store::cache_driver`'s own doc comment for the identical
27/// reasoning. Shared by [`dispatch`] and [`worker`].
28pub(crate) fn queue_driver() -> &'static str {
29 larust_core::try_config()
30 .map(|config| config.queue_driver.as_str())
31 .unwrap_or("database")
32}
33
34use larust_core::AppError;
35use larust_orm::Backend;
36use sqlx::AnyPool;
37use std::time::{SystemTime, UNIX_EPOCH};
38use tokio::sync::OnceCell;
39
40/// Set once per process, the first time `dispatch()` or `work()` runs -
41/// same lazy self-bootstrap idiom `larust-cache` already established for
42/// `cache_items` (see that crate's `store.rs` for the fuller rationale: it
43/// goes a step further than `larust_orm::migrate::run`'s or
44/// `larust_http::session`'s self-bootstrapping tables, neither of which
45/// runs its `CREATE TABLE IF NOT EXISTS` lazily on first *use* - both
46/// still need one explicit call at startup/wiring time).
47static TABLES_READY: OnceCell<()> = OnceCell::const_new();
48
49pub(crate) async fn ensure_tables(pool: &AnyPool) -> Result<(), AppError> {
50 TABLES_READY
51 .get_or_try_init(|| async {
52 let (jobs_table, failed_jobs_table) = match larust_orm::backend() {
53 Backend::Sqlite => (
54 "CREATE TABLE IF NOT EXISTS jobs (\
55 id INTEGER PRIMARY KEY AUTOINCREMENT, \
56 job_type TEXT NOT NULL, \
57 payload TEXT NOT NULL, \
58 created_at INTEGER NOT NULL, \
59 attempts INTEGER NOT NULL DEFAULT 0, \
60 reserved_at INTEGER, \
61 available_at INTEGER NOT NULL DEFAULT 0\
62 )",
63 "CREATE TABLE IF NOT EXISTS failed_jobs (\
64 id INTEGER PRIMARY KEY AUTOINCREMENT, \
65 job_type TEXT NOT NULL, \
66 payload TEXT NOT NULL, \
67 error TEXT NOT NULL, \
68 failed_at INTEGER NOT NULL\
69 )",
70 ),
71 // `VARCHAR`, not MySQL's own `TEXT` - confirmed
72 // empirically (a real, live MySQL server) that `sqlx`'s
73 // `Any` driver maps every MySQL `TEXT`-family column to
74 // its own generic `Blob` kind unconditionally, and
75 // `Decode<Any> for String` only accepts `Text`-kind
76 // values - so a `TEXT` column here would fail to decode
77 // back as `String` at all (only `CHAR`/`VARCHAR` map to
78 // `Any`'s `Text` kind; see `larust-http::session`'s own
79 // `AnySessionStore::migrate` for the same finding in more
80 // detail). `payload`/`error` get a generous cap
81 // (`VARCHAR(4000)`) rather than an arbitrary-size one -
82 // a real, documented trade-off for a large job payload.
83 Backend::MySql => (
84 "CREATE TABLE IF NOT EXISTS jobs (\
85 id INTEGER PRIMARY KEY AUTO_INCREMENT, \
86 job_type VARCHAR(255) NOT NULL, \
87 payload VARCHAR(4000) NOT NULL, \
88 created_at INTEGER NOT NULL, \
89 attempts INTEGER NOT NULL DEFAULT 0, \
90 reserved_at INTEGER, \
91 available_at INTEGER NOT NULL DEFAULT 0\
92 )",
93 "CREATE TABLE IF NOT EXISTS failed_jobs (\
94 id INTEGER PRIMARY KEY AUTO_INCREMENT, \
95 job_type VARCHAR(255) NOT NULL, \
96 payload VARCHAR(4000) NOT NULL, \
97 error VARCHAR(4000) NOT NULL, \
98 failed_at INTEGER NOT NULL\
99 )",
100 ),
101 // Postgres has native, unbounded `TEXT` (no `Any`-driver
102 // decode gap forcing MySQL's `VARCHAR(n)` workaround) and
103 // its own `GENERATED ... AS IDENTITY` auto-increment syntax
104 // - the modern, SQL-standard replacement for the older
105 // `SERIAL` pseudo-type.
106 Backend::Postgres => (
107 "CREATE TABLE IF NOT EXISTS jobs (\
108 id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY, \
109 job_type TEXT NOT NULL, \
110 payload TEXT NOT NULL, \
111 created_at INTEGER NOT NULL, \
112 attempts INTEGER NOT NULL DEFAULT 0, \
113 reserved_at INTEGER, \
114 available_at INTEGER NOT NULL DEFAULT 0\
115 )",
116 "CREATE TABLE IF NOT EXISTS failed_jobs (\
117 id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY, \
118 job_type TEXT NOT NULL, \
119 payload TEXT NOT NULL, \
120 error TEXT NOT NULL, \
121 failed_at INTEGER NOT NULL\
122 )",
123 ),
124 };
125
126 sqlx::query(jobs_table)
127 .execute(pool)
128 .await
129 .map_err(|source| AppError::Internal(Box::new(source)))?;
130
131 // Compatibility upgrade for an app created before `attempts`/
132 // `reserved_at`/`available_at` existed - SQLite-only: the
133 // `CREATE TABLE` above already includes them for a brand-new
134 // database, so a fresh MySQL app (MySQL support didn't exist
135 // before these columns did) never has a pre-existing table
136 // missing them, and there's no need to match MySQL's
137 // differently-worded duplicate-column error text at all.
138 if larust_orm::backend() == Backend::Sqlite {
139 for statement in [
140 "ALTER TABLE jobs ADD COLUMN attempts INTEGER NOT NULL DEFAULT 0",
141 "ALTER TABLE jobs ADD COLUMN reserved_at INTEGER",
142 "ALTER TABLE jobs ADD COLUMN available_at INTEGER NOT NULL DEFAULT 0",
143 ] {
144 if let Err(error) = sqlx::query(statement).execute(pool).await {
145 let duplicate_column = matches!(&error, sqlx::Error::Database(database)
146 if database.message().contains("duplicate column name"));
147 if !duplicate_column {
148 return Err(AppError::Internal(Box::new(error)));
149 }
150 }
151 }
152 }
153 // MySQL's `CREATE INDEX` has no `IF NOT EXISTS` clause at all
154 // (unlike its `CREATE TABLE IF NOT EXISTS`, which is
155 // standard) - so on MySQL this has to attempt the plain
156 // `CREATE INDEX` and tolerate the specific "already exists"
157 // error on every run after the first, the same error-text-
158 // tolerance shape the SQLite `ALTER TABLE ADD COLUMN`
159 // compatibility shim above already uses for its own
160 // once-only-really-an-error case.
161 match larust_orm::backend() {
162 // Postgres supports `IF NOT EXISTS` on `CREATE INDEX`
163 // (unlike MySQL) - same statement shape as SQLite.
164 Backend::Sqlite | Backend::Postgres => {
165 sqlx::query(
166 "CREATE INDEX IF NOT EXISTS idx_jobs_available \
167 ON jobs (reserved_at, available_at, id)",
168 )
169 .execute(pool)
170 .await
171 .map_err(|source| AppError::Internal(Box::new(source)))?;
172 }
173 Backend::MySql => {
174 if let Err(error) = sqlx::query(
175 "CREATE INDEX idx_jobs_available ON jobs (reserved_at, available_at, id)",
176 )
177 .execute(pool)
178 .await
179 {
180 let duplicate_key = matches!(&error, sqlx::Error::Database(database)
181 if database.message().contains("Duplicate key name"));
182 if !duplicate_key {
183 return Err(AppError::Internal(Box::new(error)));
184 }
185 }
186 }
187 }
188
189 sqlx::query(failed_jobs_table)
190 .execute(pool)
191 .await
192 .map_err(|source| AppError::Internal(Box::new(source)))?;
193
194 Ok(())
195 })
196 .await?;
197 Ok(())
198}
199
200pub(crate) fn now_unix_secs() -> i64 {
201 SystemTime::now()
202 .duration_since(UNIX_EPOCH)
203 .expect("system clock is before the Unix epoch")
204 .as_secs() as i64
205}