rustango 0.64.0

Batteries-included web framework for Rust: ORM + migrations + auto-admin + multi-tenancy + audit log + auth (sessions, JWT, OAuth2/OIDC, HMAC) + APIs (ViewSet, OpenAPI auto-derive, JSON:API) + jobs (in-mem + Postgres) + email + media (S3 / R2 / B2 / MinIO + presigned uploads + collections + tags) + production middleware (CSRF, CSP, rate-limiting, compression, idempotency, etc.).
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
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
//! Background job queue — async work outside the request lifecycle.
//!
//! ## Quick start
//!
//! ```ignore
//! use rustango::jobs::{Job, JobQueue, InMemoryJobQueue, JobError};
//! use serde::{Serialize, Deserialize};
//! use std::sync::Arc;
//!
//! #[derive(Serialize, Deserialize)]
//! struct SendWelcomeEmail { user_id: i64 }
//!
//! #[async_trait::async_trait]
//! impl Job for SendWelcomeEmail {
//!     const NAME: &'static str = "welcome_email";
//!
//!     async fn run(&self) -> Result<(), JobError> {
//!         // ... send the email
//!         Ok(())
//!     }
//! }
//!
//! // At startup:
//! let queue = Arc::new(InMemoryJobQueue::with_workers(4));
//! queue.register::<SendWelcomeEmail>().await;
//! queue.start().await;
//!
//! // From a handler:
//! queue.dispatch(&SendWelcomeEmail { user_id: 42 }).await?;
//!
//! // On shutdown:
//! queue.shutdown().await;
//! ```
//!
//! ## Backends
//!
//! | Backend | When to use |
//! |---|---|
//! | [`InMemoryJobQueue`] | One process: dev, tests, small apps. Jobs are lost on restart. |
//! | `pg::PgJobQueue` (feature `jobs-postgres`) | Many processes or replicas. Runs on PostgreSQL, MySQL 8+ or SQLite. |
//!
//! ## Retry policy
//!
//! A job that returns `Err(JobError::Retryable(_))` is retried with
//! growing backoff (1s, 2s, 4s, 8s, … up to 1024s). `max_attempts` counts **all**
//! runs, so the default of 5 means one run plus four retries.
//! A job can set its own wait with `Job::retry_backoff`.
//! `Err(JobError::Fatal(_))` goes straight to the dead-letter handler.
//!
//! [`InMemoryJobQueue`]: crate::jobs::InMemoryJobQueue

#[cfg(feature = "jobs-postgres")]
pub mod pg;

/// Alias for [`pg::PgJobQueue`]. The queue is not PG-only — the `Pg`
/// prefix is historical. Prefer this name in new code.
#[cfg(feature = "jobs-postgres")]
pub type DatabaseJobQueue = pg::PgJobQueue;

use std::collections::HashMap;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::time::Duration;

use serde::{de::DeserializeOwned, Serialize};
use tokio::sync::{mpsc, watch, Mutex};
use tokio::task::{JoinHandle, JoinSet};

#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum JobError {
    /// Transient failure — worker will retry with exponential backoff.
    #[error("retryable: {0}")]
    Retryable(String),
    /// Permanent failure — goes straight to dead-letter, no retries.
    #[error("fatal: {0}")]
    Fatal(String),
    /// Internal error in the queue itself (serialization, registration, etc.).
    #[error("queue error: {0}")]
    Queue(String),
}

// ------------------------------------------------------------------ Job trait

/// One unit of background work.
///
/// `NAME` identifies the job kind for routing (the queue uses it to find
/// the registered handler). Two job structs can't share the same NAME.
#[async_trait::async_trait]
pub trait Job: Send + Sync + Sized + Serialize + DeserializeOwned + 'static {
    /// Stable identifier for this job kind. Routes payloads to handlers.
    const NAME: &'static str;

    /// Cap on **total** runs, not extra retries. The default of 5 is
    /// one run plus four retries; 3 gives two retries. 0 counts as 1.
    const MAX_ATTEMPTS: u32 = 5;

    /// Wait before the retry after run `failed_attempt` (0 is the first
    /// run). The default is 1s doubling; override it to ride out longer outages.
    fn retry_backoff(failed_attempt: u32) -> Duration {
        exponential_backoff(Duration::from_secs(1), failed_attempt)
    }

    /// [`Self::MAX_ATTEMPTS`] for this job, read at dispatch. Override it
    /// to set the cap per job from its payload.
    fn max_attempts(&self) -> u32 {
        Self::MAX_ATTEMPTS
    }

    /// [`Self::retry_backoff`] for this job. Override it to set the wait
    /// per job from its payload.
    fn retry_delay(&self, failed_attempt: u32) -> Duration {
        Self::retry_backoff(failed_attempt)
    }

    /// Run the job. Return `Ok(())` on success, `Err(Retryable(_))` to
    /// retry with backoff, `Err(Fatal(_))` to dead-letter at once.
    ///
    /// **Which ambient context reaches here depends on the queue.**
    /// [`tokio::spawn`] inherits no `tokio::task_local!` state, so the
    /// queue must carry it — see [`crate::task_context::TaskContext`].
    ///
    /// Both queues carry the enqueuer's audit source and active
    /// timezone. `PgJobQueue` keeps them in `rustango_jobs.context`,
    /// which `PgJobQueue::ensure_table_pool` adds; without that column
    /// its jobs run as `System` in the default timezone.
    ///
    /// A source set by the tenant admin is recorded only on writes to
    /// its own tenant: write through `tenancy::with_tenant`.
    ///
    /// **Neither queue carries a session or a tenant.** Anything else a
    /// job needs travels in its payload.
    async fn run(&self) -> Result<(), JobError>;

    /// What the queues call: [`Self::run`] by default. Override it to read the
    /// run's [`JobCtx`], such as the job id as an idempotency key.
    async fn run_with(&self, ctx: &JobCtx) -> Result<(), JobError> {
        let _ = ctx;
        self.run().await
    }
}

// ------------------------------------------------------------------ JobCtx

/// A queued job's id, the same on every run of it. Unique on its queue only:
/// for an outside system use [`JobCtx::idempotency_key`].
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct JobId(Arc<str>);

impl JobId {
    /// A database row's id: the row id and its enqueue time in µs, so a
    /// recreated table, whose ids restart at 1, does not repeat one.
    #[cfg(feature = "jobs-postgres")]
    pub(crate) fn of_row(id: i64, created_at: Option<chrono::DateTime<chrono::Utc>>) -> Self {
        match created_at {
            Some(at) => Self(format!("{id}-{}", at.timestamp_micros()).into()),
            None => Self(id.to_string().into()),
        }
    }

    /// The id as text, e.g. for an idempotency-key header.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl std::fmt::Display for JobId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.0)
    }
}

/// One run of a job, as [`Job::run_with`] sees it.
#[derive(Clone)]
#[non_exhaustive]
pub struct JobCtx {
    id: JobId,
    attempt: u32,
    stop: StopSignal,
}

impl JobCtx {
    pub(crate) fn new(id: JobId, attempt: u32, stop: StopSignal) -> Self {
        Self { id, attempt, stop }
    }

    /// The job's id, stable across its retries.
    #[must_use]
    pub fn id(&self) -> &JobId {
        &self.id
    }

    /// [`Self::id`] under `scope`, for an outside system such as a payment
    /// API. Pass what tells this queue's table apart from others, e.g. the
    /// tenant slug when each tenant has its own job table.
    #[must_use]
    pub fn idempotency_key(&self, scope: &str) -> String {
        format!("{scope}:{}", self.id)
    }

    /// This run's number: 1 for the first run, 2 for the first retry.
    #[must_use]
    pub fn attempt(&self) -> u32 {
        self.attempt
    }

    /// `true` once the queue is shutting down.
    #[must_use]
    pub fn is_stopping(&self) -> bool {
        self.stop.is_set()
    }

    /// Resolves once the queue starts shutting down. The job then has the
    /// shutdown grace period to finish before it is aborted and re-queued.
    pub async fn stopping(&self) {
        self.stop.clone().wait().await;
    }
}

impl std::fmt::Debug for JobCtx {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("JobCtx")
            .field("id", &self.id)
            .field("attempt", &self.attempt)
            .field("stopping", &self.is_stopping())
            .finish()
    }
}

// ------------------------------------------------------------------ Queue trait

/// Pluggable job-queue backend.
#[async_trait::async_trait]
pub trait JobQueue: Send + Sync + 'static {
    /// Register a job type. Must be called before `dispatch::<T>` or `start`.
    async fn register<T: Job>(&self);

    /// Register `T` with `run` in place of [`Job::run`], so the handler
    /// can hold state the payload cannot carry, such as a mailer.
    ///
    /// Both built-in queues override this. The default ignores `run`
    /// and registers [`Job::run`], so a custom queue keeps compiling.
    async fn register_with<T, F, Fut>(&self, run: F)
    where
        T: Job,
        F: Fn(T) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<(), JobError>> + Send + 'static,
    {
        drop(run);
        tracing::warn!(
            target: "rustango::jobs",
            job = T::NAME,
            "this JobQueue does not override register_with; the handler is ignored \
             and Job::run (with any process-wide fallback) runs instead"
        );
        self.register::<T>().await;
    }

    /// Enqueue a job for asynchronous execution.
    async fn dispatch<T: Job>(&self, payload: &T) -> Result<(), JobError>;

    /// Spawn worker tasks. Calling `start` twice is a no-op; `start`
    /// after [`Self::shutdown`] starts a fresh set of workers.
    async fn start(&self);

    /// Stop all workers: running jobs get the shutdown grace period
    /// ([`DEFAULT_SHUTDOWN_GRACE`]), then are aborted and handed back
    /// to the queue. Queued jobs stay queued for the next `start`.
    ///
    /// A running job sees the stop through [`JobCtx::stopping`]. An aborted
    /// one runs again from the start, so jobs are at-least-once: make them
    /// idempotent, for example with [`JobCtx::id`].
    async fn shutdown(&self);

    /// Number of jobs currently queued (waiting to be picked up).
    async fn pending_count(&self) -> usize;
}

// ------------------------------------------------------------------ Lifecycle

/// How long `shutdown` lets running jobs finish before aborting them.
pub const DEFAULT_SHUTDOWN_GRACE: Duration = Duration::from_secs(5);

/// The workers of one `start()`. A queue holds `None` while stopped, so
/// each restart gets a fresh stop signal (#1677).
pub(crate) struct Running {
    workers: Vec<JoinHandle<()>>,
    stop: watch::Sender<bool>,
}

/// A worker's view of its run's stop signal.
#[derive(Clone)]
pub(crate) struct StopSignal(watch::Receiver<bool>);

impl StopSignal {
    /// Also true once the queue is dropped without `shutdown`.
    pub(crate) fn is_set(&self) -> bool {
        *self.0.borrow() || self.0.has_changed().is_err()
    }

    /// Resolves once the run stops, or its queue is dropped.
    pub(crate) async fn wait(&mut self) {
        let _ = self.0.wait_for(|stop| *stop).await;
    }
}

impl Running {
    pub(crate) fn new() -> (Self, StopSignal) {
        let (stop, rx) = watch::channel(false);
        let run = Self {
            workers: Vec::new(),
            stop,
        };
        (run, StopSignal(rx))
    }

    pub(crate) fn push(&mut self, worker: JoinHandle<()>) {
        self.workers.push(worker);
    }

    /// Signal stop, wait up to `grace` for every worker, then abort the
    /// rest. Returns the indexes of the aborted workers.
    pub(crate) async fn stop(self, grace: Duration) -> Vec<usize> {
        let _ = self.stop.send(true);
        let deadline = tokio::time::Instant::now() + grace;
        let mut aborted = Vec::new();
        for (n, mut h) in self.workers.into_iter().enumerate() {
            if tokio::time::timeout_at(deadline, &mut h).await.is_err() {
                h.abort();
                let _ = h.await;
                aborted.push(n);
            }
        }
        aborted
    }
}

// ------------------------------------------------------------------ JobEnvelope

#[derive(Debug, Clone)]
struct JobEnvelope {
    name: &'static str,
    /// Set at dispatch; a retry or a re-queue keeps it.
    id: JobId,
    payload: serde_json::Value,
    attempt: u32,
    max_attempts: u32,
    /// The caller's ambient context, captured at `dispatch`.
    ///
    /// Captured here rather than where the worker spawns, because
    /// workers are spawned once at `start()` — by then the caller is
    /// long gone and there is nothing to inherit. The context has to
    /// travel with the job.
    context: crate::task_context::TaskContext,
    /// A parked retry's due time; it survives a shutdown and restart.
    not_before: Option<tokio::time::Instant>,
}

// ------------------------------------------------------------------ Handler registry

/// Type-erased async handler. The queue stores one per registered Job::NAME.
/// It takes the payload and the run's context.
type HandlerFn = Arc<
    dyn Fn(serde_json::Value, JobCtx) -> Pin<Box<dyn Future<Output = Ran> + Send>> + Send + Sync,
>;

/// One run's result, and the wait before its retry should it fail.
struct Ran {
    result: Result<(), JobError>,
    retry_in: Duration,
}

tokio::task_local! {
    /// The least wait a running job asked for, see [`retry_after`].
    static RETRY_AFTER: std::cell::Cell<Option<Duration>>;
}

/// From inside [`Job::run`]: wait at least `at_least` before the retry,
/// as a receiver's `Retry-After` asks. Outside a run it does nothing.
#[cfg_attr(not(feature = "webhook-delivery"), allow(dead_code))]
pub(crate) fn retry_after(at_least: Duration) {
    let _ =
        RETRY_AFTER.try_with(|hint| hint.set(Some(hint.get().unwrap_or_default().max(at_least))));
}

/// A finished run's next step; one rule for every queue.
enum Next {
    Done,
    /// Run again after `wait`; `error` is the failed run's message.
    Retry {
        wait: Duration,
        error: String,
    },
    DeadLetter(String),
}

impl Ran {
    /// `runs` counts this run.
    fn next(self, runs: u32, max_attempts: u32) -> Next {
        match self.result {
            Ok(()) => Next::Done,
            Err(JobError::Retryable(error)) if !attempts_spent(runs, max_attempts) => Next::Retry {
                wait: self.retry_in,
                error,
            },
            Err(JobError::Retryable(msg)) => Next::DeadLetter(msg),
            Err(e) => Next::DeadLetter(e.to_string()),
        }
    }
}

/// `true` once `runs` finished runs leave no attempt for another.
fn attempts_spent(runs: u32, max_attempts: u32) -> bool {
    runs >= max_attempts.max(1)
}

/// A job's backoff, capped at a year so a runaway hook cannot overflow
/// a deadline.
fn cap_backoff(wait: Duration) -> Duration {
    wait.min(Duration::from_secs(365 * 86_400))
}

/// One registered job type, as the workers need it.
#[derive(Clone)]
struct Registered {
    handler: HandlerFn,
    /// `JobDeadLetter` needs the static name.
    name: &'static str,
    current_shape: fn(serde_json::Value) -> serde_json::Value,
}

/// `payload` as this release writes `T`. A row an older release stored
/// can hold what the current shape leaves out, such as a webhook's
/// signing secret. One that does not decode is returned as is.
fn current_shape<T: Job>(payload: serde_json::Value) -> serde_json::Value {
    serde_json::from_value::<T>(payload.clone())
        .ok()
        .and_then(|job| serde_json::to_value(job).ok())
        .unwrap_or(payload)
}

impl Registered {
    /// The dead letter for a job of this type, its payload in the current shape.
    fn dead_letter(
        &self,
        payload: serde_json::Value,
        attempts: u32,
        error: String,
    ) -> JobDeadLetter {
        JobDeadLetter {
            name: self.name,
            payload: (self.current_shape)(payload),
            attempts,
            error,
        }
    }
}

#[derive(Default)]
struct HandlerRegistry {
    handlers: HashMap<&'static str, Registered>,
}

impl HandlerRegistry {
    fn register<T: Job>(&mut self) {
        self.register_handler::<T, _, _>(|job: T, ctx| async move { job.run_with(&ctx).await });
    }

    /// Register `T` with `run` standing in for [`Job::run`].
    fn register_with<T, F, Fut>(&mut self, run: F)
    where
        T: Job,
        F: Fn(T) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<(), JobError>> + Send + 'static,
    {
        self.register_handler::<T, _, _>(move |job: T, _ctx| run(job));
    }

    fn register_handler<T, F, Fut>(&mut self, run: F)
    where
        T: Job,
        F: Fn(T, JobCtx) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<(), JobError>> + Send + 'static,
    {
        let run = Arc::new(run);
        let handler: HandlerFn = Arc::new(move |payload, ctx: JobCtx| {
            let run = run.clone();
            // 0-based, as the backoff hooks count.
            let failed_attempt = ctx.attempt().saturating_sub(1);
            Box::pin(async move {
                let job: T = match serde_json::from_value(payload) {
                    Ok(job) => job,
                    // Retryable: during a rolling deploy the row may be another
                    // release's shape, and a worker of that release can still run it.
                    Err(e) => {
                        return Ran {
                            result: Err(JobError::Retryable(format!("payload decode: {e}"))),
                            retry_in: cap_backoff(T::retry_backoff(failed_attempt)),
                        }
                    }
                };
                // A panicking override falls back to the type's backoff, not a dead worker.
                let delay = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                    job.retry_delay(failed_attempt)
                }))
                .unwrap_or_else(|_| T::retry_backoff(failed_attempt));
                let (result, asked) = RETRY_AFTER
                    .scope(std::cell::Cell::new(None), async move {
                        // A panic is a failed run, not a dead worker (#1843).
                        let result = crate::panic_guard::catch_unwind(run(job, ctx))
                            .await
                            .unwrap_or_else(|panic| {
                                let msg = crate::panic_guard::panic_message(&*panic);
                                Err(JobError::Retryable(format!("job panicked: {msg}")))
                            });
                        (result, RETRY_AFTER.with(std::cell::Cell::get))
                    })
                    .await;
                Ran {
                    result,
                    retry_in: cap_backoff(asked.map_or(delay, |a| a.max(delay))),
                }
            })
        });
        let entry = Registered {
            handler,
            name: T::NAME,
            current_shape: current_shape::<T>,
        };
        self.handlers.insert(T::NAME, entry);
    }

    fn lookup(&self, name: &str) -> Option<Registered> {
        self.handlers.get(name).cloned()
    }

    /// Refuse a dispatch nothing on this queue would run.
    fn require(&self, name: &str) -> Result<(), JobError> {
        if self.handlers.contains_key(name) {
            return Ok(());
        }
        Err(JobError::Queue(format!(
            "job `{name}` has no handler on this queue; register it before dispatching"
        )))
    }
}

// ------------------------------------------------------------------ DeadLetter

/// Callback invoked when a job exhausts retries or returns `Fatal`.
pub type DeadLetterFn =
    Arc<dyn Fn(JobDeadLetter) -> Pin<Box<dyn Future<Output = ()> + Send>> + Send + Sync>;

#[derive(Debug, Clone)]
pub struct JobDeadLetter {
    pub name: &'static str,
    pub payload: serde_json::Value,
    pub attempts: u32,
    pub error: String,
}

/// Run a dead-letter callback; a panic in it is logged, not propagated.
pub(crate) async fn deliver_dead_letter(cb: DeadLetterFn, dl: JobDeadLetter) {
    let name = dl.name;
    if let Err(panic) = crate::panic_guard::catch_unwind(cb(dl)).await {
        let msg = crate::panic_guard::panic_message(&*panic);
        tracing::error!(job = name, panic = msg, "dead-letter callback panicked");
    }
}

/// [`Job::max_attempts`] as the queues read it: 0 would never run (#2333).
pub(crate) fn max_attempts<T: Job>(job: &T) -> u32 {
    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| job.max_attempts()))
        .unwrap_or(T::MAX_ATTEMPTS)
        .max(1)
}

/// `base`, doubled for each earlier failure and capped at `base · 2^10`.
/// `failed_attempt` is 0-based, so the first retry waits `base`.
#[must_use]
pub fn exponential_backoff(base: Duration, failed_attempt: u32) -> Duration {
    base.saturating_mul(1u32 << failed_attempt.min(10))
}

// ------------------------------------------------------------------ InMemoryJobQueue

/// In-process job queue built on tokio mpsc channels.
///
/// **Nothing is persisted.** Queued and in-flight jobs are lost when
/// the process restarts. For production or multi-process deploys use
/// `pg::PgJobQueue` (feature `jobs-postgres`).
pub struct InMemoryJobQueue {
    tx: mpsc::UnboundedSender<JobEnvelope>,
    /// Owned by the queue, not a run, so jobs outlive a `shutdown`.
    rx: Arc<Mutex<mpsc::UnboundedReceiver<JobEnvelope>>>,
    registry: Arc<Mutex<HandlerRegistry>>,
    run: Mutex<Option<InMemoryRun>>,
    worker_count: usize,
    dead_letter: Arc<Mutex<Option<DeadLetterFn>>>,
    pending: Arc<std::sync::atomic::AtomicUsize>,
    /// Backoff timers; `shutdown` fires them at once and joins them.
    retries: Arc<std::sync::Mutex<JoinSet<()>>>,
    shutdown_grace: Duration,
}

/// The job each worker is running, so an aborted one can be re-queued.
type CurrentJob = Arc<std::sync::Mutex<Option<JobEnvelope>>>;

struct InMemoryRun {
    run: Running,
    current: Vec<CurrentJob>,
}

impl InMemoryJobQueue {
    /// Build a queue with `worker_count` worker tasks (call `start` to spawn them).
    #[must_use]
    pub fn with_workers(worker_count: usize) -> Self {
        let (tx, rx) = mpsc::unbounded_channel();
        Self {
            tx,
            rx: Arc::new(Mutex::new(rx)),
            registry: Arc::new(Mutex::new(HandlerRegistry::default())),
            run: Mutex::new(None),
            worker_count,
            dead_letter: Arc::new(Mutex::new(None)),
            pending: Arc::new(std::sync::atomic::AtomicUsize::new(0)),
            retries: Arc::default(),
            shutdown_grace: DEFAULT_SHUTDOWN_GRACE,
        }
    }

    /// How long `shutdown` waits for running jobs before aborting them
    /// (default [`DEFAULT_SHUTDOWN_GRACE`]). An aborted job is re-queued.
    #[must_use]
    pub fn shutdown_grace(mut self, grace: Duration) -> Self {
        self.shutdown_grace = grace;
        self
    }

    /// Default: 4 workers.
    #[must_use]
    pub fn new() -> Self {
        Self::with_workers(4)
    }

    /// Set a callback invoked for jobs that exhaust retries or return Fatal.
    /// Use this to write dead-letter rows to a DB / Slack / Sentry.
    pub async fn on_dead_letter<F, Fut>(&self, callback: F)
    where
        F: Fn(JobDeadLetter) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = ()> + Send + 'static,
    {
        let boxed: DeadLetterFn = Arc::new(move |dl| Box::pin(callback(dl)));
        *self.dead_letter.lock().await = Some(boxed);
    }
}

impl Default for InMemoryJobQueue {
    fn default() -> Self {
        Self::new()
    }
}

/// Build an [`InMemoryJobQueue`] from a loaded
/// [`crate::config::JobsSettings`]. Uses `s.concurrency`, or 4 workers
/// when it is unset.
///
/// ## Why only the in-memory backend?
///
/// [`JobQueue`] is not object-safe: `register<T>` and `dispatch<T>`
/// are generic, so `Arc<dyn JobQueue>` does not compile. There can be
/// no runtime backend picker with one shared return type. Wire any
/// other backend yourself:
///
/// ```ignore
/// let queue = match cfg.jobs.backend.as_deref() {
///     Some("pg") => Arc::new(rustango::jobs::pg::PgJobQueue::new(pool.clone())),
///     _ => rustango::jobs::inmemory_from_settings(&cfg.jobs),
/// };
/// ```
///
/// This function only reads `s.backend` to warn on a mismatch.
#[cfg(feature = "config")]
#[must_use]
pub fn inmemory_from_settings(s: &crate::config::JobsSettings) -> Arc<InMemoryJobQueue> {
    let workers = s.concurrency.map_or(4, |c| c as usize);
    if let Some(backend) = s.backend.as_deref() {
        if backend != "memory" {
            tracing::warn!(
                target: "rustango::jobs",
                backend = %backend,
                "jobs.backend = `{backend}` but inmemory_from_settings only builds InMemoryJobQueue. \
                 Wire the desired backend directly via Arc::new(...). See the docstring."
            );
        }
    }
    Arc::new(InMemoryJobQueue::with_workers(workers))
}

#[async_trait::async_trait]
impl JobQueue for InMemoryJobQueue {
    async fn register<T: Job>(&self) {
        self.registry.lock().await.register::<T>();
    }

    async fn register_with<T, F, Fut>(&self, run: F)
    where
        T: Job,
        F: Fn(T) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<(), JobError>> + Send + 'static,
    {
        self.registry.lock().await.register_with::<T, F, Fut>(run);
    }

    async fn dispatch<T: Job>(&self, payload: &T) -> Result<(), JobError> {
        // Memory is the job's only copy, and only this process's workers read it.
        self.registry.lock().await.require(T::NAME)?;
        let value = serde_json::to_value(payload).map_err(|e| JobError::Queue(e.to_string()))?;
        let envelope = JobEnvelope {
            name: T::NAME,
            id: JobId(uuid::Uuid::new_v4().to_string().into()),
            payload: value,
            attempt: 0,
            max_attempts: max_attempts(payload),
            // Captured here, at the hand-off. A worker is spawned at
            // boot and has no caller to inherit from.
            context: crate::task_context::TaskContext::capture(),
            not_before: None,
        };
        // Inside an `atomic` block the job waits for the commit, as on
        // the DB queue, and a rollback drops it.
        if crate::sql::in_any_block() {
            let (tx, pending) = (self.tx.clone(), self.pending.clone());
            crate::sql::on_commit(move || {
                if let Err(e) = enqueue(&tx, &pending, envelope) {
                    tracing::error!(error = %e, "job dispatched in a committed block was lost");
                }
            });
            return Ok(());
        }
        enqueue(&self.tx, &self.pending, envelope)
    }

    async fn start(&self) {
        let mut slot = self.run.lock().await;
        if slot.is_some() {
            return; // already started
        }
        let (mut run, stop) = Running::new();
        let mut current = Vec::with_capacity(self.worker_count);
        for _ in 0..self.worker_count {
            let job = CurrentJob::default();
            current.push(job.clone());
            let worker = InMemoryWorker {
                rx: self.rx.clone(),
                registry: self.registry.clone(),
                dead_letter: self.dead_letter.clone(),
                pending: self.pending.clone(),
                tx: self.tx.clone(),
                retries: self.retries.clone(),
                stop: stop.clone(),
                current: job,
            };
            run.push(tokio::spawn(worker_loop(worker)));
        }
        *slot = Some(InMemoryRun { run, current });
    }

    async fn shutdown(&self) {
        let mut slot = self.run.lock().await;
        let Some(InMemoryRun { run, current }) = slot.take() else {
            return;
        };
        for n in run.stop(self.shutdown_grace).await {
            // Still counted in `pending`; back on the queue for the next
            // start, with the run spent as on the DB queue.
            if let Some(mut job) = current[n].lock().unwrap().take() {
                tracing::warn!(job = job.name, "job aborted at shutdown; re-queued");
                job.attempt += 1;
                let _ = self.tx.send(job);
            }
        }
        // Stop is set, so every parked retry re-queues now, due time kept.
        let mut timers = std::mem::take(&mut *self.retries.lock().unwrap());
        while timers.join_next().await.is_some() {}
    }

    async fn pending_count(&self) -> usize {
        self.pending.load(std::sync::atomic::Ordering::SeqCst)
    }
}

/// Count the job pending and queue it.
fn enqueue(
    tx: &mpsc::UnboundedSender<JobEnvelope>,
    pending: &std::sync::atomic::AtomicUsize,
    envelope: JobEnvelope,
) -> Result<(), JobError> {
    pending.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
    // The queue owns the receiver, so this only fails mid-drop.
    tx.send(envelope).map_err(|e| {
        pending.fetch_sub(1, std::sync::atomic::Ordering::SeqCst);
        JobError::Queue(e.to_string())
    })
}

struct InMemoryWorker {
    rx: Arc<Mutex<mpsc::UnboundedReceiver<JobEnvelope>>>,
    registry: Arc<Mutex<HandlerRegistry>>,
    dead_letter: Arc<Mutex<Option<DeadLetterFn>>>,
    pending: Arc<std::sync::atomic::AtomicUsize>,
    tx: mpsc::UnboundedSender<JobEnvelope>,
    retries: Arc<std::sync::Mutex<JoinSet<()>>>,
    stop: StopSignal,
    current: CurrentJob,
}

async fn worker_loop(w: InMemoryWorker) {
    let InMemoryWorker {
        rx,
        registry,
        dead_letter,
        pending,
        tx,
        retries,
        mut stop,
        current,
    } = w;
    loop {
        // Stop wins over a ready job; `recv` is cancel-safe.
        let envelope = tokio::select! {
            biased;
            () = stop.wait() => return,
            e = async { rx.lock().await.recv().await } => match e {
                Some(e) => e,
                None => return, // channel closed
            },
        };

        // Before any await, so an abort from here on re-queues it.
        *current.lock().unwrap() = Some(envelope.clone());
        if let Some(until) = envelope
            .not_before
            .filter(|t| *t > tokio::time::Instant::now())
        {
            current.lock().unwrap().take();
            park(&retries, &tx, stop.clone(), envelope, until);
            continue;
        }
        if attempts_spent(envelope.attempt, envelope.max_attempts) {
            // Aborted at shutdown on its last run: dead-letter, do not rerun.
            current.lock().unwrap().take();
            pending.fetch_sub(1, std::sync::atomic::Ordering::SeqCst);
            let error = "attempts spent by runs aborted at shutdown".to_owned();
            let attempts = envelope.attempt;
            let entry = registry.lock().await.lookup(envelope.name);
            dead_letter_job(&dead_letter, entry.as_ref(), envelope, attempts, error).await;
            continue;
        }

        let handler = {
            let reg = registry.lock().await;
            reg.lookup(envelope.name)
        };

        let Some(entry) = handler else {
            current.lock().unwrap().take();
            pending.fetch_sub(1, std::sync::atomic::Ordering::SeqCst);
            // Memory is its only copy: hand it to the dead-letter callback.
            let attempts = envelope.attempt;
            let error = "no handler registered".to_owned();
            dead_letter_job(&dead_letter, None, envelope, attempts, error).await;
            continue;
        };

        let payload = envelope.payload.clone();
        let ctx = JobCtx::new(envelope.id.clone(), envelope.attempt + 1, stop.clone());
        // Run the handler inside the context the caller had at
        // `dispatch`. Without this the job sees none of it — an audit
        // row written here would record `system` and lose the actor.
        let ran = envelope
            .context
            .clone()
            .install((entry.handler)(payload, ctx))
            .await;
        current.lock().unwrap().take();

        let runs = envelope.attempt + 1;
        match ran.next(runs, envelope.max_attempts) {
            Next::Done => {
                pending.fetch_sub(1, std::sync::atomic::Ordering::SeqCst);
            }
            Next::Retry {
                wait: backoff,
                error,
            } => {
                tracing::debug!(target: "rustango::jobs", job = envelope.name, attempt = runs, %error, "job failed; retrying");
                let mut retry = envelope;
                retry.attempt = runs;
                // Still counted in `pending` while parked.
                let until = tokio::time::Instant::now() + backoff;
                park(&retries, &tx, stop.clone(), retry, until);
            }
            Next::DeadLetter(error) => {
                // Count it done first: an abort in the callback must not leak `pending`.
                pending.fetch_sub(1, std::sync::atomic::Ordering::SeqCst);
                dead_letter_job(&dead_letter, Some(&entry), envelope, runs, error).await;
            }
        }
    }
}

/// Hold `job` until `until`, then queue it. A shutdown queues it at once
/// with `until` kept, so the next run parks it again (#1255).
fn park(
    retries: &std::sync::Mutex<JoinSet<()>>,
    tx: &mpsc::UnboundedSender<JobEnvelope>,
    mut stop: StopSignal,
    mut job: JobEnvelope,
    until: tokio::time::Instant,
) {
    job.not_before = Some(until);
    let tx = tx.clone();
    let mut timers = retries.lock().unwrap();
    while timers.try_join_next().is_some() {}
    timers.spawn(async move {
        tokio::select! {
            () = tokio::time::sleep_until(until) => {}
            () = stop.wait() => {}
        }
        let _ = tx.send(job);
    });
}

async fn dead_letter_job(
    dead_letter: &Mutex<Option<DeadLetterFn>>,
    entry: Option<&Registered>,
    job: JobEnvelope,
    attempts: u32,
    error: String,
) {
    let cb = dead_letter.lock().await.clone();
    if let Some(cb) = cb {
        let dl = match entry {
            Some(entry) => entry.dead_letter(job.payload, attempts, error),
            None => JobDeadLetter {
                name: job.name,
                payload: job.payload,
                attempts,
                error,
            },
        };
        // The callback sees who enqueued the job, as the job did.
        job.context.install(deliver_dead_letter(cb, dl)).await;
    } else {
        tracing::error!(job = job.name, attempts, error = %error, "job dead-lettered");
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde::{Deserialize, Serialize};
    use std::sync::atomic::{AtomicUsize, Ordering};

    /// One retry rule for both queues: retry until `max_attempts` runs, then dead-letter.
    #[test]
    fn next_retries_until_the_cap_then_dead_letters() {
        let ran = |result| Ran {
            result,
            retry_in: Duration::from_secs(3),
        };
        let retry = || ran(Err(JobError::Retryable("boom".into())));
        assert!(matches!(ran(Ok(())).next(1, 3), Next::Done));
        assert!(matches!(
            retry().next(2, 3),
            Next::Retry { wait, error } if wait == Duration::from_secs(3) && error == "boom"
        ));
        assert!(matches!(retry().next(3, 3), Next::DeadLetter(e) if e == "boom"));
        // A cap of 0 still allows the one run.
        assert!(matches!(retry().next(1, 0), Next::DeadLetter(_)));
        let fatal = ran(Err(JobError::Fatal("no".into()))).next(1, 3);
        assert!(matches!(fatal, Next::DeadLetter(e) if e == "fatal: no"));
        assert!(attempts_spent(3, 3) && !attempts_spent(2, 3) && attempts_spent(1, 0));
    }

    /// Pins the documented 1s, 2s, 4s, 8s sequence.
    #[test]
    fn retry_backoff_starts_at_one_second_and_doubles() {
        // `failed_attempt` is 0-based: the run that just failed.
        let ms = |n| Increment::retry_backoff(n).as_millis();
        assert_eq!(ms(0), 1_000, "the first retry waits 1s, not 2s");
        assert_eq!(ms(1), 2_000);
        assert_eq!(ms(2), 4_000);
        assert_eq!(ms(3), 8_000);
    }

    /// The cap, and that it cannot overflow the shift.
    #[test]
    fn retry_backoff_caps_rather_than_overflowing() {
        let ms = |n| Increment::retry_backoff(n).as_millis();
        assert_eq!(ms(10), 1_024_000);
        assert_eq!(
            ms(u32::MAX),
            1_024_000,
            "a runaway attempt count must clamp, not shift past 63 and panic"
        );
    }

    /// A runaway hook is capped at a year, so no deadline overflows.
    #[tokio::test]
    async fn a_runaway_backoff_hook_is_capped_at_a_year() {
        #[derive(Serialize, Deserialize)]
        struct Forever;
        #[async_trait::async_trait]
        impl Job for Forever {
            const NAME: &'static str = "test:forever";
            fn retry_backoff(_: u32) -> Duration {
                Duration::MAX
            }
            async fn run(&self) -> Result<(), JobError> {
                Ok(())
            }
        }
        let mut reg = HandlerRegistry::default();
        reg.register::<Forever>();
        let handler = reg.lookup(Forever::NAME).unwrap().handler;
        let wait = handler(serde_json::Value::Null, first_run()).await.retry_in;
        assert_eq!(wait, Duration::from_secs(365 * 86_400));
        let _ = tokio::time::Instant::now() + wait;
        let _ = chrono::Utc::now() + chrono::Duration::from_std(wait).unwrap();
    }

    /// A job's own `retry_backoff` sets the wait before its retry (#2332).
    #[tokio::test]
    async fn a_jobs_backoff_hook_sets_the_retry_delay() {
        static RUNS: AtomicUsize = AtomicUsize::new(0);
        #[derive(Serialize, Deserialize)]
        struct Quick;
        #[async_trait::async_trait]
        impl Job for Quick {
            const NAME: &'static str = "test:quick_backoff";
            const MAX_ATTEMPTS: u32 = 3;
            fn retry_backoff(_: u32) -> Duration {
                Duration::from_millis(10)
            }
            async fn run(&self) -> Result<(), JobError> {
                RUNS.fetch_add(1, Ordering::SeqCst);
                Err(JobError::Retryable("again".into()))
            }
        }
        let q = InMemoryJobQueue::with_workers(1);
        q.register::<Quick>().await;
        q.start().await;
        q.dispatch(&Quick).await.unwrap();
        // The default 1s + 2s would take 3s.
        tokio::time::sleep(Duration::from_millis(500)).await;
        q.shutdown().await;
        assert_eq!(RUNS.load(Ordering::SeqCst), 3);
    }

    /// Panicking `retry_delay` / `max_attempts` overrides fall back to the
    /// type's backoff and `MAX_ATTEMPTS`; the worker keeps running.
    #[tokio::test]
    async fn panicking_retry_hooks_fall_back_and_the_worker_survives() {
        static RUNS: AtomicUsize = AtomicUsize::new(0);
        #[derive(Serialize, Deserialize)]
        struct Hooked;
        #[async_trait::async_trait]
        impl Job for Hooked {
            const NAME: &'static str = "test:panicking_hooks";
            const MAX_ATTEMPTS: u32 = 3;
            fn retry_backoff(_: u32) -> Duration {
                Duration::from_millis(7)
            }
            fn retry_delay(&self, _: u32) -> Duration {
                panic!("retry_delay hook")
            }
            fn max_attempts(&self) -> u32 {
                panic!("max_attempts hook")
            }
            async fn run(&self) -> Result<(), JobError> {
                RUNS.fetch_add(1, Ordering::SeqCst);
                Err(JobError::Retryable("again".into()))
            }
        }
        assert_eq!(max_attempts(&Hooked), 3);
        let mut reg = HandlerRegistry::default();
        reg.register::<Hooked>();
        let handler = reg.lookup(Hooked::NAME).unwrap().handler;
        let ran = handler(serde_json::Value::Null, first_run()).await;
        assert_eq!(ran.retry_in, Duration::from_millis(7));
        RUNS.store(0, Ordering::SeqCst);

        let q = InMemoryJobQueue::with_workers(1);
        q.register::<Hooked>().await;
        q.register::<Increment>().await;
        q.start().await;
        q.dispatch(&Hooked).await.unwrap();
        tokio::time::sleep(Duration::from_millis(300)).await;
        let before = COUNTER.load(Ordering::SeqCst);
        q.dispatch(&Increment).await.unwrap();
        tokio::time::sleep(Duration::from_millis(200)).await;
        q.shutdown().await;
        assert_eq!(
            RUNS.load(Ordering::SeqCst),
            3,
            "retried on the type's backoff"
        );
        assert!(COUNTER.load(Ordering::SeqCst) > before, "the worker died");
    }

    #[derive(Serialize, Deserialize, Debug)]
    struct Increment;

    static COUNTER: AtomicUsize = AtomicUsize::new(0);

    #[async_trait::async_trait]
    impl Job for Increment {
        const NAME: &'static str = "test:increment";
        async fn run(&self) -> Result<(), JobError> {
            COUNTER.fetch_add(1, Ordering::SeqCst);
            Ok(())
        }
    }

    #[derive(Serialize, Deserialize, Debug)]
    struct AlwaysFail {
        fatal: bool,
    }

    #[async_trait::async_trait]
    impl Job for AlwaysFail {
        const NAME: &'static str = "test:always_fail";
        const MAX_ATTEMPTS: u32 = 2;
        async fn run(&self) -> Result<(), JobError> {
            if self.fatal {
                Err(JobError::Fatal("dead now".into()))
            } else {
                Err(JobError::Retryable("transient".into()))
            }
        }
    }

    #[derive(Serialize, Deserialize, Debug)]
    struct EventuallyOk {
        fail_n: u32,
        success_marker_id: u64,
    }

    static SUCCESSES: std::sync::Mutex<Vec<u64>> = std::sync::Mutex::new(Vec::new());
    static ATTEMPTS: AtomicUsize = AtomicUsize::new(0);

    #[async_trait::async_trait]
    impl Job for EventuallyOk {
        const NAME: &'static str = "test:eventually_ok";
        const MAX_ATTEMPTS: u32 = 5;
        async fn run(&self) -> Result<(), JobError> {
            let n = ATTEMPTS.fetch_add(1, Ordering::SeqCst);
            if (n as u32) < self.fail_n {
                Err(JobError::Retryable(format!("attempt {n}")))
            } else {
                SUCCESSES.lock().unwrap().push(self.success_marker_id);
                Ok(())
            }
        }
    }

    /// The job records what the enqueuer's context was.
    ///
    /// Before this, a job ran with no ambient context at all — an audit
    /// row written from one recorded `system`, so "who deleted this?"
    /// was a dead end whenever a job did it.
    ///
    #[tokio::test]
    async fn a_job_sees_the_context_of_whoever_enqueued_it() {
        use crate::audit::{current_source, with_source, AuditSource};

        static SEEN: std::sync::Mutex<Option<String>> = std::sync::Mutex::new(None);

        #[derive(serde::Serialize, serde::Deserialize)]
        struct RecordSource;

        #[async_trait::async_trait]
        impl Job for RecordSource {
            const NAME: &'static str = "record_source";
            async fn run(&self) -> Result<(), JobError> {
                *SEEN.lock().unwrap() = Some(current_source().as_token());
                Ok(())
            }
        }

        let q = InMemoryJobQueue::with_workers(1);
        q.register::<RecordSource>().await;
        q.start().await;

        with_source(AuditSource::User { id: "99".into() }, async {
            q.dispatch(&RecordSource).await.unwrap();
        })
        .await;

        let deadline = std::time::Instant::now() + Duration::from_secs(5);
        while SEEN.lock().unwrap().is_none() && std::time::Instant::now() < deadline {
            tokio::time::sleep(Duration::from_millis(10)).await;
        }
        q.shutdown().await;

        assert_eq!(
            SEEN.lock().unwrap().clone(),
            Some("user:99".to_owned()),
            "the job should see who enqueued it"
        );
    }

    /// A job enqueued by nobody in particular stays attributable to the
    /// system — it does not invent an actor.
    #[tokio::test]
    async fn a_job_enqueued_outside_any_scope_is_system() {
        use crate::audit::current_source;

        static SEEN: std::sync::Mutex<Option<String>> = std::sync::Mutex::new(None);

        #[derive(serde::Serialize, serde::Deserialize)]
        struct RecordPlain;

        #[async_trait::async_trait]
        impl Job for RecordPlain {
            const NAME: &'static str = "record_plain";
            async fn run(&self) -> Result<(), JobError> {
                *SEEN.lock().unwrap() = Some(current_source().as_token());
                Ok(())
            }
        }

        let q = InMemoryJobQueue::with_workers(1);
        q.register::<RecordPlain>().await;
        q.start().await;
        q.dispatch(&RecordPlain).await.unwrap();
        let deadline = std::time::Instant::now() + Duration::from_secs(5);
        while SEEN.lock().unwrap().is_none() && std::time::Instant::now() < deadline {
            tokio::time::sleep(Duration::from_millis(10)).await;
        }
        q.shutdown().await;

        assert_eq!(SEEN.lock().unwrap().clone(), Some("system".to_owned()));
    }

    #[tokio::test]
    async fn dispatch_runs_handler() {
        COUNTER.store(0, Ordering::SeqCst);
        let q = InMemoryJobQueue::with_workers(2);
        q.register::<Increment>().await;
        q.start().await;
        q.dispatch(&Increment).await.unwrap();
        // Wait briefly for worker
        tokio::time::sleep(Duration::from_millis(50)).await;
        assert_eq!(COUNTER.load(Ordering::SeqCst), 1);
        q.shutdown().await;
    }

    /// A dispatch inside `atomic` runs only after the commit, never on rollback.
    #[cfg(feature = "sqlite")]
    #[tokio::test]
    async fn a_dispatch_in_a_block_waits_for_its_commit() {
        static RUNS: AtomicUsize = AtomicUsize::new(0);
        #[derive(Serialize, Deserialize)]
        struct Once;
        #[async_trait::async_trait]
        impl Job for Once {
            const NAME: &'static str = "test:once_after_commit";
            async fn run(&self) -> Result<(), JobError> {
                RUNS.fetch_add(1, Ordering::SeqCst);
                Ok(())
            }
        }
        let pool = crate::sql::Pool::connect("sqlite::memory:").await.unwrap();
        let q = Arc::new(InMemoryJobQueue::with_workers(1));
        q.register::<Once>().await;
        q.start().await;
        let q2 = q.clone();
        let rolled: Result<(), _> = crate::sql::atomic(&pool, move |_tx| {
            Box::pin(async move {
                q2.dispatch(&Once).await.unwrap();
                Err(crate::sql::ExecError::AtomicAborted)
            })
        })
        .await;
        assert!(rolled.is_err());
        let q2 = q.clone();
        crate::sql::atomic(&pool, move |_tx| {
            Box::pin(async move {
                q2.dispatch(&Once).await.unwrap();
                tokio::time::sleep(Duration::from_millis(100)).await;
                assert_eq!(RUNS.load(Ordering::SeqCst), 0, "ran before the commit");
                Ok(())
            })
        })
        .await
        .unwrap();
        tokio::time::sleep(Duration::from_millis(100)).await;
        assert_eq!(
            RUNS.load(Ordering::SeqCst),
            1,
            "the committed dispatch runs once"
        );
        q.shutdown().await;
    }

    #[tokio::test]
    async fn fatal_error_goes_to_dead_letter() {
        let q = InMemoryJobQueue::with_workers(1);
        q.register::<AlwaysFail>().await;
        let captured: Arc<Mutex<Vec<JobDeadLetter>>> = Arc::new(Mutex::new(Vec::new()));
        let cap = captured.clone();
        q.on_dead_letter(move |dl| {
            let cap = cap.clone();
            async move {
                cap.lock().await.push(dl);
            }
        })
        .await;
        q.start().await;
        q.dispatch(&AlwaysFail { fatal: true }).await.unwrap();
        tokio::time::sleep(Duration::from_millis(50)).await;
        assert_eq!(captured.lock().await.len(), 1);
        assert!(captured.lock().await[0].error.contains("dead now"));
        q.shutdown().await;
    }

    /// `MAX_ATTEMPTS = 0` runs once, then dead-letters its error (#2333).
    #[tokio::test]
    async fn zero_max_attempts_runs_once() {
        static RUNS: AtomicUsize = AtomicUsize::new(0);
        #[derive(Serialize, Deserialize)]
        struct NoAttempts;
        #[async_trait::async_trait]
        impl Job for NoAttempts {
            const NAME: &'static str = "test:no_attempts";
            const MAX_ATTEMPTS: u32 = 0;
            async fn run(&self) -> Result<(), JobError> {
                RUNS.fetch_add(1, Ordering::SeqCst);
                Err(JobError::Retryable("again".into()))
            }
        }
        let q = InMemoryJobQueue::with_workers(1);
        q.register::<NoAttempts>().await;
        let captured: Arc<std::sync::Mutex<Vec<JobDeadLetter>>> = Arc::default();
        let cap = captured.clone();
        q.on_dead_letter(move |dl| {
            cap.lock().unwrap().push(dl);
            async {}
        })
        .await;
        q.start().await;
        q.dispatch(&NoAttempts).await.unwrap();
        wait_until("the dead letter", || !captured.lock().unwrap().is_empty()).await;
        q.shutdown().await;
        assert_eq!(RUNS.load(Ordering::SeqCst), 1);
        let dl = captured.lock().unwrap();
        assert_eq!((dl[0].attempts, dl[0].error.as_str()), (1, "again"));
    }

    /// #1229 — the dead-letter callback runs as the job's enqueuer.
    #[tokio::test]
    async fn dead_letter_callback_sees_the_enqueuer() {
        use crate::audit::{current_source, with_source, AuditSource};
        let q = InMemoryJobQueue::with_workers(1);
        q.register::<AlwaysFail>().await;
        let seen: Arc<Mutex<Option<String>>> = Arc::default();
        let s = seen.clone();
        q.on_dead_letter(move |_dl| {
            let s = s.clone();
            async move {
                *s.lock().await = Some(current_source().as_token());
            }
        })
        .await;
        q.start().await;
        with_source(AuditSource::User { id: "5".into() }, async {
            q.dispatch(&AlwaysFail { fatal: true }).await.unwrap();
        })
        .await;
        let deadline = std::time::Instant::now() + Duration::from_secs(5);
        while seen.lock().await.is_none() && std::time::Instant::now() < deadline {
            tokio::time::sleep(Duration::from_millis(10)).await;
        }
        q.shutdown().await;
        assert_eq!(seen.lock().await.as_deref(), Some("user:5"));
    }

    #[tokio::test]
    async fn retryable_succeeds_eventually() {
        ATTEMPTS.store(0, Ordering::SeqCst);
        let q = InMemoryJobQueue::with_workers(1);
        q.register::<EventuallyOk>().await;
        q.start().await;
        let marker = 12345;
        q.dispatch(&EventuallyOk {
            fail_n: 2,
            success_marker_id: marker,
        })
        .await
        .unwrap();
        // Backoff is ~1s then ~2s; 7s leaves plenty of room.
        tokio::time::sleep(Duration::from_millis(7000)).await;
        let succ = SUCCESSES.lock().unwrap();
        assert!(succ.contains(&marker), "expected marker, got {succ:?}");
        drop(succ);
        q.shutdown().await;
    }

    #[derive(Serialize, Deserialize, Debug)]
    struct Panics;

    #[async_trait::async_trait]
    impl Job for Panics {
        const NAME: &'static str = "test:panics";
        const MAX_ATTEMPTS: u32 = 1;
        async fn run(&self) -> Result<(), JobError> {
            panic!("boom");
        }
    }

    #[derive(Serialize, Deserialize, Debug)]
    struct AfterPanic;

    static AFTER_PANIC: AtomicUsize = AtomicUsize::new(0);

    #[async_trait::async_trait]
    impl Job for AfterPanic {
        const NAME: &'static str = "test:after_panic";
        async fn run(&self) -> Result<(), JobError> {
            AFTER_PANIC.fetch_add(1, Ordering::SeqCst);
            Ok(())
        }
    }

    /// #1843: the one worker survives a panic, and the panic is a failed run.
    #[tokio::test]
    async fn a_panicking_job_keeps_the_worker() {
        let q = InMemoryJobQueue::with_workers(1);
        q.register::<Panics>().await;
        q.register::<AfterPanic>().await;
        let dead: Arc<Mutex<Vec<JobDeadLetter>>> = Arc::default();
        let d = dead.clone();
        q.on_dead_letter(move |dl| {
            let d = d.clone();
            async move { d.lock().await.push(dl) }
        })
        .await;
        q.start().await;
        q.dispatch(&Panics).await.unwrap();
        q.dispatch(&AfterPanic).await.unwrap();
        tokio::time::sleep(Duration::from_millis(200)).await;
        assert_eq!(AFTER_PANIC.load(Ordering::SeqCst), 1, "worker still runs");
        let dead = dead.lock().await;
        assert!(dead[0].error.contains("job panicked: boom"), "{dead:?}");
        assert_eq!(q.pending_count().await, 0);
        q.shutdown().await;
    }

    /// Nothing would run a job type with no handler, so dispatch refuses it.
    #[tokio::test]
    async fn an_unregistered_job_is_refused_at_dispatch() {
        #[derive(Serialize, Deserialize)]
        struct UnregisteredJob;

        #[async_trait::async_trait]
        impl Job for UnregisteredJob {
            const NAME: &'static str = "test:unregistered";
            async fn run(&self) -> Result<(), JobError> {
                Ok(())
            }
        }

        let q = InMemoryJobQueue::with_workers(1);
        q.start().await;
        let err = q.dispatch(&UnregisteredJob).await.unwrap_err();
        assert!(
            matches!(&err, JobError::Queue(m) if m.contains("test:unregistered")),
            "{err:?}"
        );
        assert_eq!(q.pending_count().await, 0);
        q.register::<UnregisteredJob>().await;
        q.dispatch(&UnregisteredJob).await.expect("registered now");
        q.shutdown().await;
    }

    #[tokio::test]
    async fn pending_count_tracks_in_flight() {
        let q = InMemoryJobQueue::with_workers(0); // no workers — jobs queue but don't run
        q.register::<Increment>().await;
        for _ in 0..3 {
            q.dispatch(&Increment).await.unwrap();
        }
        assert_eq!(q.pending_count().await, 3);
    }

    /// Sleeps `ms` on its first run, then counts a finish in `DRAINED`.
    #[derive(Serialize, Deserialize, Debug)]
    struct SlowOnce {
        ms: u64,
    }

    static DRAIN_RUNS: AtomicUsize = AtomicUsize::new(0);
    static DRAINED: AtomicUsize = AtomicUsize::new(0);

    #[async_trait::async_trait]
    impl Job for SlowOnce {
        const NAME: &'static str = "test:slow_once";
        async fn run(&self) -> Result<(), JobError> {
            if DRAIN_RUNS.fetch_add(1, Ordering::SeqCst) == 0 {
                tokio::time::sleep(Duration::from_millis(self.ms)).await;
            }
            DRAINED.fetch_add(1, Ordering::SeqCst);
            Ok(())
        }
    }

    /// Fails retryably on its first run, then succeeds.
    #[derive(Serialize, Deserialize, Debug)]
    struct RetryOnce;

    static RETRY_RUNS: AtomicUsize = AtomicUsize::new(0);

    #[async_trait::async_trait]
    impl Job for RetryOnce {
        const NAME: &'static str = "test:retry_once";
        async fn run(&self) -> Result<(), JobError> {
            if RETRY_RUNS.fetch_add(1, Ordering::SeqCst) == 0 {
                return Err(JobError::Retryable("once".into()));
            }
            Ok(())
        }
    }

    async fn wait_until(what: &str, cond: impl Fn() -> bool) {
        let deadline = tokio::time::Instant::now() + Duration::from_secs(5);
        while !cond() {
            assert!(tokio::time::Instant::now() < deadline, "timed out: {what}");
            tokio::time::sleep(Duration::from_millis(10)).await;
        }
    }

    // The tests below share the statics above.
    static LIFECYCLE: Mutex<()> = Mutex::const_new(());

    /// #1255: shutdown lets a running job finish instead of aborting it.
    #[tokio::test]
    async fn shutdown_drains_a_running_job() {
        let _g = LIFECYCLE.lock().await;
        DRAIN_RUNS.store(0, Ordering::SeqCst);
        DRAINED.store(0, Ordering::SeqCst);
        let q = InMemoryJobQueue::with_workers(1);
        q.register::<SlowOnce>().await;
        q.start().await;
        q.dispatch(&SlowOnce { ms: 300 }).await.unwrap();
        wait_until("the run to start", || {
            DRAIN_RUNS.load(Ordering::SeqCst) == 1
        })
        .await;
        q.shutdown().await;
        assert_eq!(DRAINED.load(Ordering::SeqCst), 1, "the job finished");
        assert_eq!(q.pending_count().await, 0);
    }

    /// #1255: a job past the grace period is aborted and re-queued.
    #[tokio::test]
    async fn a_job_past_the_grace_is_requeued() {
        let _g = LIFECYCLE.lock().await;
        DRAIN_RUNS.store(0, Ordering::SeqCst);
        DRAINED.store(0, Ordering::SeqCst);
        let q = InMemoryJobQueue::with_workers(1).shutdown_grace(Duration::from_millis(50));
        q.register::<SlowOnce>().await;
        q.start().await;
        q.dispatch(&SlowOnce { ms: 30_000 }).await.unwrap();
        wait_until("the run to start", || {
            DRAIN_RUNS.load(Ordering::SeqCst) == 1
        })
        .await;
        q.shutdown().await;
        assert_eq!(q.pending_count().await, 1, "aborted, not lost");
        q.start().await;
        wait_until("the rerun", || DRAINED.load(Ordering::SeqCst) == 1).await;
        wait_until("the count to settle", || {
            q.pending.load(Ordering::SeqCst) == 0
        })
        .await;
        q.shutdown().await;
    }

    /// #1255: a retry parked in backoff survives shutdown and runs on restart.
    #[tokio::test]
    async fn a_parked_retry_survives_shutdown() {
        let _g = LIFECYCLE.lock().await;
        RETRY_RUNS.store(0, Ordering::SeqCst);
        let q = InMemoryJobQueue::with_workers(1);
        q.register::<RetryOnce>().await;
        q.start().await;
        q.dispatch(&RetryOnce).await.unwrap();
        wait_until("the failed run", || RETRY_RUNS.load(Ordering::SeqCst) == 1).await;
        q.shutdown().await;
        assert_eq!(q.pending_count().await, 1, "the retry is still queued");
        q.start().await;
        wait_until("the retry", || RETRY_RUNS.load(Ordering::SeqCst) == 2).await;
        wait_until("the count to reach 0", || {
            q.pending.load(Ordering::SeqCst) == 0
        })
        .await;
        q.shutdown().await;
    }

    /// #1677: `start` after `shutdown` runs jobs again.
    #[tokio::test]
    async fn start_after_shutdown_runs_jobs() {
        let _g = LIFECYCLE.lock().await;
        DRAIN_RUNS.store(1, Ordering::SeqCst); // skip the slow first run
        DRAINED.store(0, Ordering::SeqCst);
        let q = InMemoryJobQueue::with_workers(1);
        q.register::<SlowOnce>().await;
        q.start().await;
        q.shutdown().await;
        q.start().await;
        q.dispatch(&SlowOnce { ms: 0 }).await.unwrap();
        wait_until("the job after a restart", || {
            DRAINED.load(Ordering::SeqCst) == 1
        })
        .await;
        q.shutdown().await;
    }

    #[derive(Serialize, Deserialize, Debug)]
    struct Marker;

    static MARKED: AtomicUsize = AtomicUsize::new(0);

    #[async_trait::async_trait]
    impl Job for Marker {
        const NAME: &'static str = "test:marker";
        async fn run(&self) -> Result<(), JobError> {
            MARKED.fetch_add(1, Ordering::SeqCst);
            Ok(())
        }
    }

    /// A one-run job that hangs; counts its runs.
    #[derive(Serialize, Deserialize, Debug)]
    struct HangOnce;

    static HANG_RUNS: AtomicUsize = AtomicUsize::new(0);

    #[async_trait::async_trait]
    impl Job for HangOnce {
        const NAME: &'static str = "test:hang_once";
        const MAX_ATTEMPTS: u32 = 1;
        async fn run(&self) -> Result<(), JobError> {
            HANG_RUNS.fetch_add(1, Ordering::SeqCst);
            tokio::time::sleep(Duration::from_secs(30)).await;
            Ok(())
        }
    }

    /// A job dispatched while shutdown drains stays queued for the next start.
    #[tokio::test]
    async fn dispatch_during_drain_stays_queued() {
        let _g = LIFECYCLE.lock().await;
        DRAIN_RUNS.store(0, Ordering::SeqCst);
        MARKED.store(0, Ordering::SeqCst);
        let q = InMemoryJobQueue::with_workers(1);
        q.register::<SlowOnce>().await;
        q.register::<Marker>().await;
        q.start().await;
        q.dispatch(&SlowOnce { ms: 300 }).await.unwrap();
        wait_until("the run to start", || {
            DRAIN_RUNS.load(Ordering::SeqCst) == 1
        })
        .await;
        tokio::join!(q.shutdown(), async {
            tokio::time::sleep(Duration::from_millis(50)).await;
            q.dispatch(&Marker).await.unwrap();
        });
        assert_eq!(MARKED.load(Ordering::SeqCst), 0, "not run while stopping");
        assert_eq!(q.pending_count().await, 1);
        q.start().await;
        wait_until("the queued job", || MARKED.load(Ordering::SeqCst) == 1).await;
        q.shutdown().await;
    }

    /// A parked retry keeps its backoff across a restart.
    #[tokio::test]
    async fn a_parked_retry_keeps_its_backoff_across_restart() {
        let _g = LIFECYCLE.lock().await;
        RETRY_RUNS.store(0, Ordering::SeqCst);
        let q = InMemoryJobQueue::with_workers(1);
        q.register::<RetryOnce>().await;
        q.start().await;
        q.dispatch(&RetryOnce).await.unwrap();
        wait_until("the failed run", || RETRY_RUNS.load(Ordering::SeqCst) == 1).await;
        q.shutdown().await;
        q.start().await;
        tokio::time::sleep(Duration::from_millis(400)).await;
        assert_eq!(
            RETRY_RUNS.load(Ordering::SeqCst),
            1,
            "the 1s backoff still holds"
        );
        wait_until("the retry", || RETRY_RUNS.load(Ordering::SeqCst) == 2).await;
        q.shutdown().await;
    }

    /// An aborted run spends its attempt, as on the DB queue.
    #[tokio::test]
    async fn an_aborted_run_spends_its_attempt() {
        let _g = LIFECYCLE.lock().await;
        HANG_RUNS.store(0, Ordering::SeqCst);
        let q = InMemoryJobQueue::with_workers(1).shutdown_grace(Duration::from_millis(50));
        q.register::<HangOnce>().await;
        let dead: Arc<Mutex<Vec<JobDeadLetter>>> = Arc::default();
        let d = dead.clone();
        q.on_dead_letter(move |dl| {
            let d = d.clone();
            async move { d.lock().await.push(dl) }
        })
        .await;
        q.start().await;
        q.dispatch(&HangOnce).await.unwrap();
        wait_until("the run to start", || HANG_RUNS.load(Ordering::SeqCst) == 1).await;
        q.shutdown().await;
        q.start().await;
        let deadline = tokio::time::Instant::now() + Duration::from_secs(5);
        while dead.lock().await.is_empty() {
            assert!(tokio::time::Instant::now() < deadline, "no dead letter");
            tokio::time::sleep(Duration::from_millis(10)).await;
        }
        assert_eq!(HANG_RUNS.load(Ordering::SeqCst), 1, "not run again");
        assert_eq!(q.pending_count().await, 0);
        q.shutdown().await;
    }

    /// A first run's context, for calling a handler directly.
    fn first_run() -> JobCtx {
        JobCtx::new(JobId("t".into()), 1, Running::new().1)
    }

    /// Every run's `(id, attempt)` per probe token.
    static CTX_SEEN: std::sync::Mutex<Vec<(u64, String, u32)>> = std::sync::Mutex::new(Vec::new());

    /// Records its context; fails its first run.
    #[derive(Serialize, Deserialize)]
    struct CtxProbe {
        token: u64,
    }

    #[async_trait::async_trait]
    impl Job for CtxProbe {
        const NAME: &'static str = "test:ctx_probe";
        fn retry_backoff(_: u32) -> Duration {
            Duration::from_millis(5)
        }
        async fn run(&self) -> Result<(), JobError> {
            Err(JobError::Fatal("the queue calls run_with".into()))
        }
        async fn run_with(&self, ctx: &JobCtx) -> Result<(), JobError> {
            let id = ctx.id().as_str().to_owned();
            CTX_SEEN
                .lock()
                .unwrap()
                .push((self.token, id, ctx.attempt()));
            if ctx.attempt() == 1 {
                return Err(JobError::Retryable("once more".into()));
            }
            Ok(())
        }
    }

    fn ctx_seen(token: u64) -> Vec<(String, u32)> {
        let seen = CTX_SEEN.lock().unwrap();
        seen.iter()
            .filter(|(t, ..)| *t == token)
            .map(|(_, id, n)| (id.clone(), *n))
            .collect()
    }

    /// A retry sees the first run's id and the next attempt number.
    #[tokio::test]
    async fn a_retry_keeps_the_job_id_and_counts_the_attempt() {
        let q = InMemoryJobQueue::with_workers(1);
        q.register::<CtxProbe>().await;
        q.start().await;
        q.dispatch(&CtxProbe { token: 1 }).await.unwrap();
        q.dispatch(&CtxProbe { token: 2 }).await.unwrap();
        let deadline = tokio::time::Instant::now() + Duration::from_secs(5);
        while ctx_seen(1).len() < 2 || ctx_seen(2).len() < 2 {
            assert!(tokio::time::Instant::now() < deadline, "no retry");
            tokio::time::sleep(Duration::from_millis(10)).await;
        }
        q.shutdown().await;
        let (one, two) = (ctx_seen(1), ctx_seen(2));
        assert_eq!(one[0].0, one[1].0, "same id on the retry");
        assert_eq!((one[0].1, one[1].1), (1, 2));
        assert_ne!(one[0].0, two[0].0, "each job has its own id");
    }

    /// The key carries the caller's scope, so two tenants' tables, whose
    /// first rows share an id, give different keys.
    #[test]
    fn the_idempotency_key_is_scoped() {
        let ctx = first_run();
        assert_eq!(ctx.idempotency_key("acme"), "acme:t");
        assert_ne!(ctx.idempotency_key("acme"), ctx.idempotency_key("globex"));
    }

    /// A row id alone repeats once a table is recreated; its enqueue time does not.
    #[cfg(feature = "jobs-postgres")]
    #[test]
    fn a_row_id_is_told_apart_by_its_enqueue_time() {
        let at = chrono::DateTime::from_timestamp_micros(1_700_000_000_123_456).unwrap();
        let later = at + chrono::Duration::microseconds(1);
        assert_eq!(JobId::of_row(1, Some(at)).as_str(), "1-1700000000123456");
        assert_ne!(JobId::of_row(1, Some(at)), JobId::of_row(1, Some(later)));
        assert_eq!(JobId::of_row(1, None).as_str(), "1");
    }

    static STOP_SEEN: AtomicUsize = AtomicUsize::new(0);

    /// Waits for the queue to stop, then finishes.
    #[derive(Serialize, Deserialize)]
    struct UntilStop;

    #[async_trait::async_trait]
    impl Job for UntilStop {
        const NAME: &'static str = "test:until_stop";
        async fn run(&self) -> Result<(), JobError> {
            Err(JobError::Fatal("the queue calls run_with".into()))
        }
        async fn run_with(&self, ctx: &JobCtx) -> Result<(), JobError> {
            STOP_SEEN.fetch_add(1, Ordering::SeqCst);
            ctx.stopping().await;
            assert!(ctx.is_stopping());
            STOP_SEEN.fetch_add(1, Ordering::SeqCst);
            Ok(())
        }
    }

    /// `shutdown` reaches a running job, which then finishes within the grace.
    #[tokio::test]
    async fn shutdown_fires_a_running_jobs_stop_signal() {
        let q = InMemoryJobQueue::with_workers(1).shutdown_grace(Duration::from_secs(10));
        q.register::<UntilStop>().await;
        q.start().await;
        q.dispatch(&UntilStop).await.unwrap();
        let deadline = tokio::time::Instant::now() + Duration::from_secs(5);
        while STOP_SEEN.load(Ordering::SeqCst) == 0 {
            assert!(tokio::time::Instant::now() < deadline, "never ran");
            tokio::time::sleep(Duration::from_millis(10)).await;
        }
        let began = std::time::Instant::now();
        q.shutdown().await;
        assert!(
            began.elapsed() < Duration::from_secs(5),
            "waited out the grace"
        );
        assert_eq!(
            STOP_SEEN.load(Ordering::SeqCst),
            2,
            "finished on the signal"
        );
        assert_eq!(q.pending_count().await, 0, "done, not re-queued");
    }

    static RUN_ONLY: AtomicUsize = AtomicUsize::new(0);

    /// A job written before `run_with`.
    #[derive(Serialize, Deserialize)]
    struct RunOnly;

    #[async_trait::async_trait]
    impl Job for RunOnly {
        const NAME: &'static str = "test:run_only";
        async fn run(&self) -> Result<(), JobError> {
            RUN_ONLY.fetch_add(1, Ordering::SeqCst);
            Ok(())
        }
    }

    /// The default `run_with` runs a job that implements only `run`.
    #[tokio::test]
    async fn a_job_with_only_run_still_runs() {
        RunOnly.run_with(&first_run()).await.unwrap();
        assert_eq!(RUN_ONLY.load(Ordering::SeqCst), 1);
        let q = InMemoryJobQueue::with_workers(1);
        q.register::<RunOnly>().await;
        q.start().await;
        q.dispatch(&RunOnly).await.unwrap();
        let deadline = tokio::time::Instant::now() + Duration::from_secs(5);
        while RUN_ONLY.load(Ordering::SeqCst) < 2 {
            assert!(tokio::time::Instant::now() < deadline, "never ran");
            tokio::time::sleep(Duration::from_millis(10)).await;
        }
        q.shutdown().await;
    }

    /// `inmemory_from_settings` uses `concurrency` when it is set.
    #[cfg(feature = "config")]
    #[test]
    fn inmemory_from_settings_uses_configured_concurrency() {
        let mut s = crate::config::JobsSettings::default();
        s.concurrency = Some(8);
        let q = inmemory_from_settings(&s);
        assert_eq!(q.worker_count, 8);
    }

    #[cfg(feature = "config")]
    #[test]
    fn inmemory_from_settings_defaults_to_four_workers() {
        let s = crate::config::JobsSettings::default();
        let q = inmemory_from_settings(&s);
        assert_eq!(q.worker_count, 4);
    }
}