ryuk 0.1.1

A Laravel-style full-stack web framework for Rust: axum, SeaORM and Inertia, with auth, queues, mail, storage, cache, scheduling and an MCP server.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
//! DB-backed background jobs (tables `jobs` / `failed_jobs`, self-created).
//!
//! ```ignore
//! #[derive(Serialize, Deserialize)]
//! struct Welcome { user: i64 }
//! impl Job for Welcome {
//!     const NAME: &'static str = "welcome";
//!     async fn handle(self, ctx: &JobContext) -> Result<(), JobError> { Ok(()) }
//! }
//! let queue = Queue::new(db).register::<Welcome>();
//! queue.ensure_tables().await?;
//! queue.dispatch(Welcome { user: 1 }).await?;
//! queue.work().await; // usually in `ryuk queue:work`
//! ```
use sea_orm::entity::prelude::*;
use sea_orm::sea_query::{
    Expr, ExprTrait, LockBehavior, LockType, Query, SelectStatement, UpdateStatement,
};
use sea_orm::{
    ActiveValue::Set, ConnectionTrait, DatabaseConnection, DbBackend, DbErr, FromQueryResult,
    Iterable, Schema, TransactionTrait,
};
use serde::{Serialize, de::DeserializeOwned};
use std::{collections::HashMap, future::Future, pin::Pin, sync::Arc, time::Duration};

/// `jobs` table.
pub mod jobs {
    use sea_orm::entity::prelude::*;
    /// A pending or reserved job row.
    #[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
    #[sea_orm(table_name = "jobs")]
    pub struct Model {
        #[sea_orm(primary_key)]
        pub id: i64,
        pub name: String,
        /// JSON text. shortcut: `text` is 64KB on MySQL (sea_query has no portable LONGTEXT), fine for ids/small args.
        #[sea_orm(column_type = "Text")]
        pub payload: String,
        pub attempts: i32,
        /// Unix seconds when the job may first run.
        #[sea_orm(indexed)]
        pub available_at: i64,
        /// Unix seconds when a worker claimed it; `None` while waiting.
        pub reserved_at: Option<i64>,
    }
    #[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
    pub enum Relation {}
    impl ActiveModelBehavior for ActiveModel {}
}

/// `failed_jobs` table.
pub mod failed_jobs {
    use sea_orm::entity::prelude::*;
    /// A job that exhausted its tries (or could not be run at all).
    #[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
    #[sea_orm(table_name = "failed_jobs")]
    pub struct Model {
        #[sea_orm(primary_key)]
        pub id: i64,
        pub name: String,
        #[sea_orm(column_type = "Text")]
        pub payload: String,
        #[sea_orm(column_type = "Text")]
        pub error: String,
        pub failed_at: i64,
    }
    #[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
    pub enum Relation {}
    impl ActiveModelBehavior for ActiveModel {}
}

/// Error returned by a job; any message is fine.
#[derive(Debug, thiserror::Error)]
#[error("{0}")]
pub struct JobError(pub String);

impl From<DbErr> for JobError {
    fn from(e: DbErr) -> Self {
        Self(e.to_string())
    }
}
impl From<String> for JobError {
    fn from(e: String) -> Self {
        Self(e)
    }
}
impl From<&str> for JobError {
    fn from(e: &str) -> Self {
        Self(e.into())
    }
}

/// Passed to every job run.
#[derive(Clone)]
pub struct JobContext {
    /// The application database.
    pub db: DatabaseConnection,
}

/// A queueable unit of work. `NAME` is the stable key stored in the DB.
pub trait Job: Serialize + DeserializeOwned + Send + Sync + 'static {
    /// Unique job name.
    const NAME: &'static str;
    /// Run the job.
    fn handle(self, ctx: &JobContext) -> impl Future<Output = Result<(), JobError>> + Send;
}

type Handler = Arc<
    dyn Fn(String, JobContext) -> Pin<Box<dyn Future<Output = Result<(), JobError>> + Send>>
        + Send
        + Sync,
>;

/// Dispatches jobs and runs the worker loop.
pub struct Queue {
    db: DatabaseConnection,
    handlers: HashMap<&'static str, Handler>,
    max_tries: i32,
    backoff: Duration,
    job_timeout: Duration,
}

/// A reservation older than this is considered abandoned by a dead worker.
const STALE_SECS: i64 = 300;

/// A job running longer than this is cancelled and counted as a failed attempt. It must stay below
/// `STALE_SECS`: past that another worker re-claims the job and it would run twice at once.
const JOB_TIMEOUT: Duration = Duration::from_secs(STALE_SECS as u64 - 30);

fn now() -> i64 {
    chrono::Utc::now().timestamp()
}

impl Queue {
    /// New queue with `max_tries = 3` and a 2s backoff base (delay = base * 2^(attempt-1)).
    pub fn new(db: DatabaseConnection) -> Self {
        Self {
            db,
            handlers: HashMap::new(),
            max_tries: 3,
            backoff: Duration::from_secs(2),
            job_timeout: JOB_TIMEOUT,
        }
    }

    /// Cancel a job that runs longer than `d` (default 270 s) and count it as a failed attempt, so one hung
    /// job cannot block a worker forever. Keep it below 300 s: that is when another worker takes the job over.
    pub fn job_timeout(mut self, d: Duration) -> Self {
        self.job_timeout = d.min(JOB_TIMEOUT);
        self
    }

    /// Set the maximum number of attempts before a job moves to `failed_jobs`.
    pub fn max_tries(mut self, n: i32) -> Self {
        self.max_tries = n;
        self
    }

    /// Set the exponential backoff base.
    pub fn backoff(mut self, base: Duration) -> Self {
        self.backoff = base;
        self
    }

    /// Map `J::NAME` to its handler.
    pub fn register<J: Job>(mut self) -> Self {
        self.handlers.insert(
            J::NAME,
            Arc::new(|payload, ctx| {
                Box::pin(async move {
                    let job: J =
                        serde_json::from_str(&payload).map_err(|e| JobError(e.to_string()))?;
                    job.handle(&ctx).await
                })
            }),
        );
        self
    }

    /// Create the `jobs` and `failed_jobs` tables if missing.
    pub async fn ensure_tables(&self) -> Result<(), DbErr> {
        let b = self.db.get_database_backend();
        let schema = Schema::new(b);
        if b == DbBackend::MySql {
            // MySQL has no CREATE INDEX IF NOT EXISTS, but accepts indexes inline in CREATE TABLE.
            let mut t = schema.create_table_with_index_from_entity(jobs::Entity);
            self.db.execute(t.if_not_exists()).await?;
        } else {
            let mut t = schema.create_table_from_entity(jobs::Entity);
            self.db.execute(t.if_not_exists()).await?;
            for mut i in schema.create_index_from_entity(jobs::Entity) {
                self.db.execute(i.if_not_exists()).await?;
            }
        }
        let mut t = schema.create_table_from_entity(failed_jobs::Entity);
        self.db.execute(t.if_not_exists()).await?;
        Ok(())
    }

    /// Queue a job to run as soon as possible.
    pub async fn dispatch<J: Job>(&self, job: J) -> Result<(), DbErr> {
        self.dispatch_later(job, Duration::ZERO).await
    }

    /// Queue a job to run after `delay`.
    pub async fn dispatch_later<J: Job>(&self, job: J, delay: Duration) -> Result<(), DbErr> {
        let payload = serde_json::to_string(&job).map_err(|e| DbErr::Custom(e.to_string()))?;
        jobs::Entity::insert(jobs::ActiveModel {
            name: Set(J::NAME.into()),
            payload: Set(payload),
            attempts: Set(0),
            available_at: Set(now() + delay.as_secs() as i64),
            reserved_at: Set(None),
            ..Default::default()
        })
        .exec_without_returning(&self.db)
        .await?;
        Ok(())
    }

    /// Run forever: claim, run, sleep 1s when idle. DB errors are logged, never fatal.
    pub async fn work(&self) {
        loop {
            match self.work_once().await {
                Ok(true) => {}
                Ok(false) => tokio::time::sleep(Duration::from_secs(1)).await,
                Err(e) => {
                    tracing::error!("queue: {e}");
                    tokio::time::sleep(Duration::from_secs(1)).await;
                }
            }
        }
    }

    /// Claim and run at most one due job. Returns whether a job was processed.
    pub async fn work_once(&self) -> Result<bool, DbErr> {
        let Some(job) = self.claim().await? else {
            return Ok(false);
        };
        let handler = self.handlers.get(job.name.as_str());
        // `attempts` was incremented by the claim: more than `max_tries` means earlier attempts never reported
        // back (the process died or was killed mid-job, so no failure was recorded). Retrying forever would loop
        // a crashing job; park it instead.
        let crashed = job.attempts > self.max_tries;
        let result = match handler {
            _ if crashed => Err(JobError(format!(
                "never finished in {} attempts (the worker died or was killed while running it)",
                self.max_tries
            ))),
            None => Err(JobError(format!("unknown job `{}`", job.name))),
            Some(h) => {
                // Spawned so a panic surfaces as a JoinError instead of killing the worker.
                let fut = h(
                    job.payload.clone(),
                    JobContext {
                        db: self.db.clone(),
                    },
                );
                let mut task = tokio::spawn(fut);
                match tokio::time::timeout(self.job_timeout, &mut task).await {
                    Ok(Ok(r)) => r,
                    Ok(Err(e)) => Err(JobError(format!("job panicked: {e}"))),
                    Err(_) => {
                        task.abort();
                        Err(JobError(format!(
                            "job timed out after {:?}",
                            self.job_timeout
                        )))
                    }
                }
            }
        };
        match result {
            Ok(()) => {
                jobs::Entity::delete_by_id(job.id).exec(&self.db).await?;
            }
            Err(e) => {
                tracing::warn!(
                    "job {} #{} failed (attempt {}): {e}",
                    job.name,
                    job.id,
                    job.attempts
                );
                if handler.is_none() || crashed || job.attempts >= self.max_tries {
                    failed_jobs::ActiveModel {
                        name: Set(job.name),
                        payload: Set(job.payload),
                        error: Set(e.0),
                        failed_at: Set(now()),
                        ..Default::default()
                    }
                    .insert(&self.db)
                    .await?;
                    jobs::Entity::delete_by_id(job.id).exec(&self.db).await?;
                } else {
                    let delay = self.backoff.as_secs_f64() * 2f64.powi(job.attempts - 1);
                    let mut m: jobs::ActiveModel = job.into();
                    m.available_at = Set(now() + delay.ceil() as i64);
                    m.reserved_at = Set(None);
                    m.update(&self.db).await?;
                }
            }
        }
        Ok(true)
    }

    /// Atomically claim the oldest due job (attempts += 1). Statements are sea_query builders, so
    /// quoting/placeholders render per backend; only the locking strategy differs:
    /// - Postgres: `UPDATE .. WHERE id IN (SELECT .. FOR UPDATE SKIP LOCKED LIMIT 1) RETURNING ..`.
    /// - MySQL/MariaDB (no UPDATE..RETURNING): transaction of `SELECT .. FOR UPDATE SKIP LOCKED`, then `UPDATE`.
    /// - SQLite: the same single UPDATE..RETURNING without a lock clause (writers are serialized; needs >= 3.35).
    ///
    /// Reservations older than STALE_SECS are re-claimed, so a job that outlives that (or a crashed
    /// worker) may run again: at-least-once delivery.
    async fn claim(&self) -> Result<Option<jobs::Model>, DbErr> {
        let b = self.db.get_database_backend();
        let t = now();
        if b != DbBackend::MySql {
            let row = self
                .db
                .query_one_raw(b.build(&claim_returning(b, t)))
                .await?;
            return row
                .map(|r| jobs::Model::from_query_result(&r, ""))
                .transpose();
        }
        let tx = self.db.begin().await?;
        let Some(row) = tx
            .query_one_raw(b.build(&claim_select(b, t, false)))
            .await?
        else {
            tx.commit().await?;
            return Ok(None);
        };
        let mut job = jobs::Model::from_query_result(&row, "")?;
        tx.execute_raw(b.build(&claim_update(job.id, t))).await?;
        tx.commit().await?;
        job.attempts += 1;
        job.reserved_at = Some(t);
        Ok(Some(job))
    }
}

/// `SELECT <job> .. WHERE due ORDER BY id LIMIT 1` (+ `FOR UPDATE SKIP LOCKED` off SQLite).
fn claim_select(b: DbBackend, t: i64, id_only: bool) -> SelectStatement {
    let mut q = Query::select();
    if id_only {
        q.column(jobs::Column::Id);
    } else {
        q.columns(jobs::Column::iter());
    }
    q.from(jobs::Entity)
        .and_where(Expr::col(jobs::Column::AvailableAt).lte(t))
        .and_where(
            Expr::col(jobs::Column::ReservedAt)
                .is_null()
                .or(Expr::col(jobs::Column::ReservedAt).lt(t - STALE_SECS)),
        )
        .order_by(jobs::Column::Id, sea_orm::Order::Asc)
        .limit(1);
    if b != DbBackend::Sqlite {
        q.lock_with_behavior(LockType::Update, LockBehavior::SkipLocked);
    }
    q.take()
}

fn claim_set(q: &mut UpdateStatement, t: i64) {
    q.table(jobs::Entity)
        .value(jobs::Column::ReservedAt, t)
        .value(
            jobs::Column::Attempts,
            Expr::col(jobs::Column::Attempts).add(1),
        );
}

/// Single-statement claim for Postgres and SQLite.
fn claim_returning(b: DbBackend, t: i64) -> UpdateStatement {
    let mut q = Query::update();
    claim_set(&mut q, t);
    q.and_where(Expr::col(jobs::Column::Id).in_subquery(claim_select(b, t, true)))
        .returning(Query::returning().columns(jobs::Column::iter()));
    q.take()
}

/// Second half of the MySQL claim (the row is already locked by `claim_select`).
fn claim_update(id: i64, t: i64) -> UpdateStatement {
    let mut q = Query::update();
    claim_set(&mut q, t);
    q.and_where(Expr::col(jobs::Column::Id).eq(id));
    q.take()
}

#[cfg(test)]
mod tests {
    use super::*;
    use sea_orm::QueryTrait;
    use serde::Deserialize;
    use std::sync::Mutex;

    // Tags make parallel tests (and the env-var backends) independent of each other.
    static RUNS: Mutex<Vec<String>> = Mutex::new(Vec::new());
    static FAILS: Mutex<Vec<String>> = Mutex::new(Vec::new());
    /// A label no other test body (or backend run) shares, so the global counters cannot bleed.
    fn uniq(prefix: &str) -> String {
        static N: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
        format!(
            "{prefix}-{}",
            N.fetch_add(1, std::sync::atomic::Ordering::SeqCst)
        )
    }
    fn count(v: &Mutex<Vec<String>>, tag: &str) -> usize {
        v.lock()
            .unwrap()
            .iter()
            .filter(|t| t.as_str() == tag)
            .count()
    }

    #[derive(Serialize, Deserialize)]
    struct Ok1(String);
    impl Job for Ok1 {
        const NAME: &'static str = "ok1";
        async fn handle(self, _: &JobContext) -> Result<(), JobError> {
            RUNS.lock().unwrap().push(self.0);
            Ok(())
        }
    }

    #[derive(Serialize, Deserialize)]
    struct Bad(bool, String);
    impl Job for Bad {
        const NAME: &'static str = "bad";
        async fn handle(self, _: &JobContext) -> Result<(), JobError> {
            FAILS.lock().unwrap().push(self.1);
            if self.0 {
                panic!("boom");
            }
            Err("nope".into())
        }
    }

    async fn queue_on(url: &str, max_conn: u32) -> Queue {
        // sqlite::memory: needs max_connections(1): each pooled connection is its own database.
        let mut o = sea_orm::ConnectOptions::new(url);
        o.max_connections(max_conn);
        let db = sea_orm::Database::connect(o).await.unwrap();
        let q = Queue::new(db)
            .register::<Ok1>()
            .register::<Bad>()
            .backoff(Duration::ZERO);
        q.ensure_tables().await.unwrap();
        q.ensure_tables().await.unwrap(); // idempotent (indexes included)
        // Shared server databases keep rows between runs.
        jobs::Entity::delete_many().exec(&q.db).await.unwrap();
        failed_jobs::Entity::delete_many()
            .exec(&q.db)
            .await
            .unwrap();
        q
    }

    #[cfg(feature = "sqlite")]
    async fn sqlite() -> Queue {
        queue_on("sqlite::memory:", 1).await
    }

    async fn runs_once_and_delays(q: &Queue) {
        let (now_tag, later_tag) = (uniq("delays"), uniq("delays-later"));
        q.dispatch(Ok1(now_tag.clone())).await.unwrap();
        q.dispatch_later(Ok1(later_tag.clone()), Duration::from_secs(60))
            .await
            .unwrap();
        assert!(q.work_once().await.unwrap());
        assert!(!q.work_once().await.unwrap()); // delayed one not due
        assert_eq!(count(&RUNS, &now_tag), 1);
        assert_eq!(count(&RUNS, &later_tag), 0);
        assert_eq!(jobs::Entity::find().all(&q.db).await.unwrap().len(), 1);
    }

    async fn failing_jobs_retry_then_fail(q: &Queue) {
        let (err_tag, panic_tag) = (uniq("err"), uniq("panic"));
        q.dispatch(Bad(false, err_tag.clone())).await.unwrap();
        q.dispatch(Bad(true, panic_tag.clone())).await.unwrap(); // panics each try
        while q.work_once().await.unwrap() {}
        assert_eq!(count(&FAILS, &err_tag), 3);
        assert_eq!(count(&FAILS, &panic_tag), 3);
        assert!(jobs::Entity::find().all(&q.db).await.unwrap().is_empty());
        let failed = failed_jobs::Entity::find().all(&q.db).await.unwrap();
        assert_eq!(failed.len(), 2);
        assert!(failed.iter().any(|f| f.error.contains("panicked")));
    }

    async fn unknown_job_marked_failed(q: &Queue) {
        jobs::Entity::insert(jobs::ActiveModel {
            name: Set("ghost".into()),
            payload: Set("{}".into()),
            attempts: Set(0),
            available_at: Set(0),
            ..Default::default()
        })
        .exec_without_returning(&q.db)
        .await
        .unwrap();
        assert!(q.work_once().await.unwrap());
        assert_eq!(
            failed_jobs::Entity::find().all(&q.db).await.unwrap().len(),
            1
        );
    }

    #[derive(Serialize, Deserialize)]
    struct Hang(String);
    impl Job for Hang {
        const NAME: &'static str = "hang";
        async fn handle(self, _: &JobContext) -> Result<(), JobError> {
            FAILS.lock().unwrap().push(self.0);
            std::future::pending::<()>().await;
            Ok(())
        }
    }

    /// A hung job is cancelled (counted as a failed attempt) and does not block the jobs behind it; a job whose
    /// earlier attempts never reported back (worker killed mid-job) is parked without running again.
    async fn hung_and_crashed_jobs_do_not_block_or_loop(q: &Queue) {
        let q = Queue {
            db: q.db.clone(),
            handlers: q.handlers.clone(),
            max_tries: q.max_tries,
            backoff: Duration::ZERO,
            job_timeout: Duration::from_millis(50),
        }
        .register::<Hang>();
        let (hang_tag, after_tag, crash_tag) = (uniq("hang"), uniq("after"), uniq("crash"));
        q.dispatch(Hang(hang_tag.clone())).await.unwrap();
        q.dispatch(Ok1(after_tag.clone())).await.unwrap();
        while q.work_once().await.unwrap() {}
        assert_eq!(
            count(&FAILS, &hang_tag),
            3,
            "retried max_tries times, each cancelled"
        );
        assert_eq!(
            count(&RUNS, &after_tag),
            1,
            "the job behind the hung one ran"
        );
        let failed = failed_jobs::Entity::find().all(&q.db).await.unwrap();
        assert!(failed.iter().any(|f| f.error.contains("timed out")));

        // 3 earlier attempts left a reservation behind and never finished: the 4th claim must not run it.
        failed_jobs::Entity::delete_many()
            .exec(&q.db)
            .await
            .unwrap();
        jobs::Entity::insert(jobs::ActiveModel {
            name: Set("ok1".into()),
            payload: Set(serde_json::to_string(&crash_tag).unwrap()),
            attempts: Set(q.max_tries),
            available_at: Set(0),
            reserved_at: Set(Some(now() - STALE_SECS - 1)),
            ..Default::default()
        })
        .exec_without_returning(&q.db)
        .await
        .unwrap();
        assert!(q.work_once().await.unwrap());
        assert_eq!(count(&RUNS, &crash_tag), 0, "a crash-looping job ran again");
        let failed = failed_jobs::Entity::find().all(&q.db).await.unwrap();
        assert_eq!(failed.len(), 1);
        assert!(failed[0].error.contains("never finished"));
        assert!(jobs::Entity::find().all(&q.db).await.unwrap().is_empty());
    }

    /// Two workers draining N jobs: every job runs exactly once.
    async fn two_workers_run_each_job_once(q: Queue, tag: &str) {
        const N: usize = 40;
        for i in 0..N {
            q.dispatch(Ok1(format!("{tag}{i}"))).await.unwrap();
        }
        let q = Arc::new(q);
        let w = |q: Arc<Queue>| tokio::spawn(async move { while q.work_once().await.unwrap() {} });
        let (a, b) = (w(q.clone()), w(q.clone()));
        a.await.unwrap();
        b.await.unwrap();
        for i in 0..N {
            assert_eq!(count(&RUNS, &format!("{tag}{i}")), 1, "job {i}");
        }
        assert!(jobs::Entity::find().all(&q.db).await.unwrap().is_empty());
    }

    #[cfg(feature = "sqlite")]
    #[tokio::test]
    async fn sqlite_runs_once_and_delays() {
        runs_once_and_delays(&sqlite().await).await;
    }

    #[cfg(feature = "sqlite")]
    #[tokio::test]
    async fn sqlite_failing_jobs_retry_then_fail() {
        failing_jobs_retry_then_fail(&sqlite().await).await;
    }

    #[cfg(feature = "sqlite")]
    #[tokio::test]
    async fn sqlite_hung_and_crashed_jobs_do_not_block_or_loop() {
        hung_and_crashed_jobs_do_not_block_or_loop(&sqlite().await).await;
    }

    #[cfg(feature = "sqlite")]
    #[tokio::test]
    async fn sqlite_unknown_job_marked_failed() {
        unknown_job_marked_failed(&sqlite().await).await;
    }

    #[cfg(feature = "sqlite")]
    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
    async fn sqlite_two_workers_run_each_job_once() {
        // File DB + a pool of 4 so the workers really use separate connections.
        let path = std::env::temp_dir().join(format!("ryuk-queue-{}.db", std::process::id()));
        let _ = std::fs::remove_file(&path);
        let q = queue_on(&format!("sqlite://{}?mode=rwc", path.display()), 4).await;
        two_workers_run_each_job_once(q, "sqlite-w").await;
        let _ = std::fs::remove_file(&path);
    }

    /// Same bodies against real servers when TEST_POSTGRES_URL / TEST_MYSQL_URL are set.
    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
    async fn external_backends() {
        for var in ["TEST_POSTGRES_URL", "TEST_MYSQL_URL"] {
            let Ok(url) = std::env::var(var) else {
                eprintln!("{var} not set: skipped");
                continue;
            };
            // One at a time: the tables are shared and each body clears them first.
            runs_once_and_delays(&queue_on(&url, 4).await).await;
            failing_jobs_retry_then_fail(&queue_on(&url, 4).await).await;
            unknown_job_marked_failed(&queue_on(&url, 4).await).await;
            hung_and_crashed_jobs_do_not_block_or_loop(&queue_on(&url, 4).await).await;
            two_workers_run_each_job_once(queue_on(&url, 4).await, var).await;
        }
    }

    #[test]
    fn generated_sql() {
        let (t, id) = (1_000, 7);
        let insert = |b: DbBackend| {
            jobs::Entity::insert(jobs::ActiveModel {
                name: Set("n".into()),
                payload: Set("{}".into()),
                attempts: Set(0),
                available_at: Set(t),
                reserved_at: Set(None),
                ..Default::default()
            })
            .build(b)
            .to_string()
        };
        let cols =
            r#"RETURNING "id", "name", "payload", "attempts", "available_at", "reserved_at""#;
        let due = r#"WHERE "available_at" <= 1000 AND ("reserved_at" IS NULL OR "reserved_at" < 700) ORDER BY "id" ASC LIMIT 1"#;
        let set = r#"UPDATE "jobs" SET "reserved_at" = 1000, "attempts" = "attempts" + 1"#;

        // SQLite: one UPDATE..RETURNING, no lock clause.
        let (sl, pg, my) = (DbBackend::Sqlite, DbBackend::Postgres, DbBackend::MySql);
        assert_eq!(
            insert(sl),
            r#"INSERT INTO "jobs" ("name", "payload", "attempts", "available_at", "reserved_at") VALUES ('n', '{}', 0, 1000, NULL)"#
        );
        assert_eq!(
            sl.build(&claim_returning(sl, t)).to_string(),
            format!(r#"{set} WHERE "id" IN (SELECT "id" FROM "jobs" {due}) {cols}"#)
        );
        // Postgres: same, with the row lock inside the subquery.
        assert_eq!(insert(pg), insert(sl));
        assert_eq!(
            pg.build(&claim_returning(pg, t)).to_string(),
            format!(
                r#"{set} WHERE "id" IN (SELECT "id" FROM "jobs" {due} FOR UPDATE SKIP LOCKED) {cols}"#
            )
        );
        // MySQL: backtick quoting, no RETURNING, SELECT .. FOR UPDATE SKIP LOCKED then UPDATE by id.
        assert_eq!(
            insert(my),
            "INSERT INTO `jobs` (`name`, `payload`, `attempts`, `available_at`, `reserved_at`) VALUES ('n', '{}', 0, 1000, NULL)"
        );
        assert_eq!(
            my.build(&claim_select(my, t, false)).to_string(),
            "SELECT `id`, `name`, `payload`, `attempts`, `available_at`, `reserved_at` FROM `jobs` WHERE `available_at` <= 1000 AND (`reserved_at` IS NULL OR `reserved_at` < 700) ORDER BY `id` ASC LIMIT 1 FOR UPDATE SKIP LOCKED"
        );
        assert_eq!(
            my.build(&claim_update(id, t)).to_string(),
            "UPDATE `jobs` SET `reserved_at` = 1000, `attempts` = `attempts` + 1 WHERE `id` = 7"
        );

        // Table creation: text payloads and the available_at index (inline for MySQL).
        let ddl = |b: DbBackend| {
            b.build(&Schema::new(b).create_table_with_index_from_entity(jobs::Entity))
                .to_string()
        };
        assert!(
            ddl(my).contains("`payload` text NOT NULL")
                && ddl(my).contains("KEY `idx-jobs-available_at` (`available_at`)")
        );
        assert!(
            ddl(pg).contains(r#""payload" text NOT NULL"#)
                && ddl(pg).contains(r#""available_at" bigint NOT NULL"#)
        );
        let idx = Schema::new(sl).create_index_from_entity(jobs::Entity);
        assert_eq!(
            sl.build(idx[0].clone().if_not_exists()).to_string(),
            r#"CREATE INDEX IF NOT EXISTS "idx-jobs-available_at" ON "jobs" ("available_at")"#
        );
    }
}