Skip to main content

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