axa-postgres-job-queue 0.7.0

A Postgres job queue, worker pool, and recurring schedules for Axum services.
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
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
#![allow(
    clippy::unwrap_used,
    clippy::expect_used,
    clippy::panic,
    reason = "RCA-SCOPE-4: tests may unwrap"
)]
#![allow(
    clippy::arithmetic_side_effects,
    reason = "RCA-SCOPE-4: tests may use plain operators"
)]
//! The queue against a real Postgres. The tests share three tables, so run them with
//! `--test-threads=1`. `axa_job_acts` refuses `DELETE` and `TRUNCATE`, so a test
//! starts by dropping it.
//!
//! ```sh
//! AXA_TEST_DB_URL=postgres://... cargo test -p axa-postgres-job-queue -- --ignored --test-threads=1
//! ```

use std::{
    collections::HashSet,
    sync::{
        Arc, Mutex,
        atomic::{AtomicUsize, Ordering},
    },
    time::{Duration, Instant},
};

use axa_postgres_job_queue::{
    ActKind, Error, JobState, NewJob, Queue, QueueOptions, SETUP_STATEMENTS, Schedule, Timestamp,
    enqueue_all_on,
};
use jiff::{SignedDuration, tz::TimeZone};
use sqlx::{PgPool, Row};
use tokio::sync::watch;
use uuid::Uuid;

fn uri() -> String {
    std::env::var("AXA_TEST_DB_URL").expect("AXA_TEST_DB_URL")
}

fn quick() -> QueueOptions {
    QueueOptions {
        workers: 4,
        poll_interval: Duration::from_millis(20),
        retry_backoff: Duration::ZERO,
        ..QueueOptions::default()
    }
}

/// A queue on empty tables. The acts table is dropped, as it refuses `DELETE`, and
/// `connect` makes it again.
async fn fresh(options: QueueOptions) -> Queue {
    let admin = PgPool::connect(&uri()).await.expect("connect");
    sqlx::query("DROP TABLE IF EXISTS axa_job_acts")
        .execute(&admin)
        .await
        .unwrap();
    admin.close().await;
    let queue = Queue::connect(&uri(), options).await.expect("connect");
    for statement in ["DELETE FROM axa_queue", "DELETE FROM axa_schedule"] {
        sqlx::query(statement).execute(queue.pool()).await.unwrap();
    }
    queue
}

/// Another process on the same tables.
async fn replica(options: QueueOptions) -> Queue {
    Queue::connect_existing(&uri(), options)
        .await
        .expect("connect")
}

fn start(queue: Queue) -> (Arc<Queue>, watch::Sender<bool>, tokio::task::JoinHandle<()>) {
    let queue = Arc::new(queue);
    let (stop, stopped) = watch::channel(false);
    let run = tokio::spawn(queue.clone().run(stopped));
    (queue, stop, run)
}

async fn until(mut done: impl AsyncFnMut() -> bool) {
    for _ in 0_i32..400_i32 {
        if done().await {
            return;
        }
        tokio::time::sleep(Duration::from_millis(20)).await;
    }
    panic!("gave up waiting");
}

async fn state(queue: &Queue, id: Uuid) -> JobState {
    queue.job(id).await.unwrap().expect("a job").state
}

async fn count(pool: &PgPool, sql: &'static str) -> i64 {
    sqlx::query_scalar(sql).fetch_one(pool).await.unwrap()
}

/// Cancel `id` as a person would, in a transaction of its own.
async fn cancel(queue: &Queue, id: Uuid) -> bool {
    let mut transaction = queue.pool().begin().await.unwrap();
    let cancelled =
        axa_postgres_job_queue::cancel(&mut transaction, id, "ops:alice", "test_cancel")
            .await
            .unwrap();
    transaction.commit().await.unwrap();
    cancelled
}

/// Retry `id` as a person would, in a transaction of its own.
async fn retry(queue: &Queue, id: Uuid) -> bool {
    let mut transaction = queue.pool().begin().await.unwrap();
    let retried = axa_postgres_job_queue::retry(&mut transaction, id, "ops:alice", "test_retry")
        .await
        .unwrap();
    transaction.commit().await.unwrap();
    retried
}

/// Counts jobs running now and the most ever running at once.
#[derive(Clone, Default)]
struct Gauge {
    now: Arc<AtomicUsize>,
    most: Arc<AtomicUsize>,
    done: Arc<AtomicUsize>,
}

impl Gauge {
    fn handler(
        &self,
        millis: u64,
    ) -> impl Fn(
        serde_json::Value,
    ) -> std::pin::Pin<Box<dyn Future<Output = Result<(), String>> + Send>>
    + Send
    + Sync
    + 'static {
        let gauge = self.clone();
        move |_| {
            let gauge = gauge.clone();
            Box::pin(async move {
                let now = gauge.now.fetch_add(1, Ordering::SeqCst) + 1;
                gauge.most.fetch_max(now, Ordering::SeqCst);
                tokio::time::sleep(Duration::from_millis(millis)).await;
                gauge.now.fetch_sub(1, Ordering::SeqCst);
                gauge.done.fetch_add(1, Ordering::SeqCst);
                Ok(())
            })
        }
    }

    fn most(&self) -> usize {
        self.most.load(Ordering::SeqCst)
    }

    fn done(&self) -> usize {
        self.done.load(Ordering::SeqCst)
    }
}

#[tokio::test]
#[ignore = "needs AXA_TEST_DB_URL"]
async fn a_process_runs_no_more_jobs_at_once_than_its_loops() {
    let mut queue = fresh(QueueOptions {
        workers: 3,
        ..quick()
    })
    .await;
    let gauge = Gauge::default();
    queue.handle("Slow", gauge.handler(60));
    for _ in 0_i32..24_i32 {
        queue
            .enqueue("Slow", serde_json::Value::Null)
            .await
            .unwrap();
    }
    let (_queue, stop, run) = start(queue);
    until(async || gauge.done() == 24).await;
    stop.send(true).unwrap();
    run.await.unwrap();
    assert_eq!(
        gauge.most(),
        3,
        "the loops ran in parallel up to their number"
    );
}

#[tokio::test]
#[ignore = "needs AXA_TEST_DB_URL"]
async fn a_limit_holds_one_job_type_and_the_rest_keep_the_loops() {
    let mut queue = fresh(quick()).await;
    let limited = Gauge::default();
    let free = Gauge::default();
    queue.handle("Limited", limited.handler(50));
    queue.handle("Free", free.handler(50));
    queue.limit("Limited", 1);
    for _ in 0_i32..8_i32 {
        queue
            .enqueue("Limited", serde_json::Value::Null)
            .await
            .unwrap();
        queue
            .enqueue("Free", serde_json::Value::Null)
            .await
            .unwrap();
    }
    let (_queue, stop, run) = start(queue);
    until(async || limited.done() == 8 && free.done() == 8).await;
    stop.send(true).unwrap();
    run.await.unwrap();
    assert_eq!(limited.most(), 1);
    assert!(
        free.most() >= 2,
        "free jobs used the other loops: {}",
        free.most()
    );
}

#[tokio::test]
#[ignore = "needs AXA_TEST_DB_URL"]
async fn two_processes_run_each_job_once() {
    let mut first = fresh(quick()).await;
    let mut second = replica(quick()).await;
    let seen = Arc::new(Mutex::new(Vec::new()));
    for queue in [&mut first, &mut second] {
        let seen = seen.clone();
        queue.handle("Once", move |args: serde_json::Value| {
            let seen = seen.clone();
            async move {
                seen.lock().unwrap().push(args["n"].as_i64().unwrap());
                Ok::<(), String>(())
            }
        });
    }
    for n in 0_i32..60_i32 {
        first
            .enqueue("Once", serde_json::json!({ "n": n }))
            .await
            .unwrap();
    }
    let (_a, stop_a, run_a) = start(first);
    let (_b, stop_b, run_b) = start(second);
    until(async || seen.lock().unwrap().len() >= 60).await;
    tokio::time::sleep(Duration::from_millis(100)).await;
    stop_a.send(true).unwrap();
    stop_b.send(true).unwrap();
    run_a.await.unwrap();
    run_b.await.unwrap();
    let seen = seen.lock().unwrap();
    let unique: HashSet<_> = seen.iter().collect();
    assert_eq!((seen.len(), unique.len()), (60, 60));
}

#[tokio::test]
#[ignore = "needs AXA_TEST_DB_URL"]
async fn jobs_in_flight_finish_at_shutdown_and_dropping_the_run_stops_them() {
    let mut queue = fresh(quick()).await;
    let gauge = Gauge::default();
    queue.handle("Slow", gauge.handler(300));
    let finished = queue
        .enqueue("Slow", serde_json::Value::Null)
        .await
        .unwrap();
    let (queue, stop, run) = start(queue);
    until(async || state(&queue, finished).await == JobState::Running).await;
    stop.send(true).unwrap();
    run.await.unwrap();
    assert_eq!(state(&queue, finished).await, JobState::Completed);

    // A caller with a time limit drops the run at it, and the job stops too.
    let mut queue = fresh(quick()).await;
    let stopped = Gauge::default();
    queue.handle("Slow", stopped.handler(1_000));
    let cut_off = queue
        .enqueue("Slow", serde_json::Value::Null)
        .await
        .unwrap();
    let (queue, _stop, run) = start(queue);
    until(async || state(&queue, cut_off).await == JobState::Running).await;
    run.abort();
    let _ = run.await;
    tokio::time::sleep(Duration::from_millis(1_200)).await;
    assert_eq!(stopped.done(), 0, "the job was stopped with its loop");
    // Left for stale recovery, as a crash would be.
    assert_eq!(state(&queue, cut_off).await, JobState::Running);
}

#[tokio::test]
#[ignore = "needs AXA_TEST_DB_URL"]
async fn a_delayed_job_is_not_claimed_before_its_time() {
    let mut queue = fresh(quick()).await;
    queue.handle("Job", |_| async { Ok::<(), String>(()) });
    let later = queue
        .enqueue_job(&NewJob::new("Job", serde_json::Value::Null).run_in(Duration::from_hours(1)))
        .await
        .unwrap();
    let soon = queue
        .enqueue_job(
            // Far enough off that the checks below finish first, however slow the machine.
            &NewJob::new("Job", serde_json::Value::Null).run_in(Duration::from_secs(2)),
        )
        .await
        .unwrap();
    let past = a_minute_ago(&queue).await;
    let due = queue
        .enqueue_job(&NewJob::new("Job", serde_json::Value::Null).run_at(past))
        .await
        .unwrap();
    assert!(queue.run_one().await.unwrap());
    assert_eq!(state(&queue, due).await, JobState::Completed);
    assert!(!queue.run_one().await.unwrap(), "nothing else is due yet");
    assert_eq!(state(&queue, soon).await, JobState::Queued);
    let until = Instant::now() + Duration::from_secs(20);
    while !queue.run_one().await.unwrap() {
        assert!(Instant::now() < until, "the delayed job never came due");
        tokio::time::sleep(Duration::from_millis(50)).await;
    }
    assert_eq!(state(&queue, soon).await, JobState::Completed);
    assert_eq!(state(&queue, later).await, JobState::Queued);
    let counts = queue.counts().await.unwrap();
    assert_eq!((counts.ready, counts.waiting, counts.completed), (0, 1, 2));
}

async fn a_minute_ago(queue: &Queue) -> Timestamp {
    time_of(queue.pool(), "SELECT now() - interval '1 minute'").await
}

/// The one time a query gives.
async fn time_of(pool: &PgPool, sql: &'static str) -> Timestamp {
    sqlx::query_scalar::<_, jiff_sqlx::Timestamp>(sql)
        .fetch_one(pool)
        .await
        .unwrap()
        .to_jiff()
}

#[tokio::test]
#[ignore = "needs AXA_TEST_DB_URL"]
async fn a_higher_priority_runs_first() {
    let mut queue = fresh(quick()).await;
    let order = Arc::new(Mutex::new(Vec::new()));
    {
        let order = order.clone();
        queue.handle("Job", move |args: serde_json::Value| {
            let order = order.clone();
            async move {
                order.lock().unwrap().push(args.as_i64().unwrap());
                Ok::<(), String>(())
            }
        });
    }
    for (n, priority) in [(1_i32, 0), (2_i32, 5), (3_i32, -1), (4_i32, 5)] {
        queue
            .enqueue_job(&NewJob::new("Job", serde_json::json!(n)).priority(priority))
            .await
            .unwrap();
    }
    while queue.run_one().await.unwrap() {}
    assert_eq!(*order.lock().unwrap(), vec![2, 4, 1, 3]);
}

#[tokio::test]
#[ignore = "needs AXA_TEST_DB_URL"]
async fn a_job_status_follows_it_and_leaves_out_its_arguments() {
    let mut queue = fresh(quick()).await;
    let gate = Arc::new(tokio::sync::Notify::new());
    {
        let gate = gate.clone();
        queue.handle("Gated", move |args: serde_json::Value| {
            let gate = gate.clone();
            async move {
                gate.notified().await;
                if args["fail"].as_bool().unwrap() {
                    Err("x".repeat(5_000))
                } else {
                    Ok(())
                }
            }
        });
    }
    let ok = queue
        .enqueue("Gated", serde_json::json!({ "fail": false }))
        .await
        .unwrap();
    let info = queue.job(ok).await.unwrap().unwrap();
    assert_eq!(
        (info.state, info.attempts, info.name.as_str()),
        (JobState::Queued, 0_i32, "Gated")
    );
    assert!(!format!("{info:?}").contains("fail"));
    let queue = Arc::new(queue);
    let run = {
        let queue = queue.clone();
        tokio::spawn(async move { queue.run_one().await.unwrap() })
    };
    until(async || state(&queue, ok).await == JobState::Running).await;
    let info = queue.job(ok).await.unwrap().unwrap();
    assert!(info.started_at.is_some());
    assert_eq!(info.attempts, 1_i32);
    gate.notify_one();
    assert!(run.await.unwrap());
    assert_eq!(state(&queue, ok).await, JobState::Completed);

    let bad = queue
        .enqueue("Gated", serde_json::json!({ "fail": true }))
        .await
        .unwrap();
    let run = {
        let queue = queue.clone();
        tokio::spawn(async move { queue.run_one().await.unwrap() })
    };
    until(async || state(&queue, bad).await == JobState::Running).await;
    gate.notify_one();
    run.await.unwrap();
    let info = queue.job(bad).await.unwrap().unwrap();
    assert_eq!(info.state, JobState::Failed);
    let error = info.error.unwrap();
    assert!(
        error.len() <= 1024 && error.starts_with("xxx"),
        "{}",
        error.len()
    );
    assert!(queue.job(Uuid::new_v4()).await.unwrap().is_none());
}

#[tokio::test]
#[ignore = "needs AXA_TEST_DB_URL"]
async fn a_cancelled_job_never_runs_and_a_running_one_cannot_be_cancelled() {
    let mut queue = fresh(quick()).await;
    let gauge = Gauge::default();
    queue.handle("Slow", gauge.handler(200));
    let cancelled = queue
        .enqueue("Slow", serde_json::Value::Null)
        .await
        .unwrap();
    assert!(cancel(&queue, cancelled).await);
    assert!(!cancel(&queue, cancelled).await, "only once");
    assert!(!queue.run_one().await.unwrap());
    assert_eq!(state(&queue, cancelled).await, JobState::Cancelled);

    let running = queue
        .enqueue("Slow", serde_json::Value::Null)
        .await
        .unwrap();
    let queue = Arc::new(queue);
    let run = {
        let queue = queue.clone();
        tokio::spawn(async move { queue.run_one().await.unwrap() })
    };
    until(async || state(&queue, running).await == JobState::Running).await;
    assert!(!cancel(&queue, running).await);
    run.await.unwrap();
    assert_eq!(state(&queue, running).await, JobState::Completed);
}

#[tokio::test]
#[ignore = "needs AXA_TEST_DB_URL"]
async fn cancelling_while_loops_claim_runs_each_job_or_cancels_it_never_both() {
    let mut queue = fresh(quick()).await;
    let ran = Arc::new(Mutex::new(HashSet::new()));
    {
        let ran = ran.clone();
        queue.handle("Job", move |args: serde_json::Value| {
            let ran = ran.clone();
            async move {
                ran.lock()
                    .unwrap()
                    .insert(args.as_str().unwrap().to_string());
                Ok::<(), String>(())
            }
        });
    }
    let mut ids = Vec::new();
    for n in 0_i32..80_i32 {
        let id = Uuid::new_v4().to_string();
        let job = queue.enqueue("Job", serde_json::json!(id)).await.unwrap();
        ids.push((n, id, job));
    }
    let (queue, stop, run) = start(queue);
    let mut cancelled = HashSet::new();
    for (_, name, id) in &ids {
        if cancel(&queue, *id).await {
            cancelled.insert(name.clone());
        }
    }
    until(async || queue.counts().await.unwrap().ready == 0).await;
    tokio::time::sleep(Duration::from_millis(100)).await;
    stop.send(true).unwrap();
    run.await.unwrap();
    let ran = ran.lock().unwrap();
    assert_eq!(ran.len() + cancelled.len(), 80);
    assert!(ran.is_disjoint(&cancelled));
}

#[tokio::test]
#[ignore = "needs AXA_TEST_DB_URL"]
async fn a_failed_job_retried_gets_one_more_try_and_a_lost_run_cannot_overwrite_it() {
    let mut queue = fresh(quick()).await;
    let fail = Arc::new(std::sync::atomic::AtomicBool::new(true));
    {
        let fail = fail.clone();
        queue.handle("Flaky", move |_| {
            let fail = fail.clone();
            async move {
                if fail.load(Ordering::SeqCst) {
                    Err("down".to_string())
                } else {
                    Ok(())
                }
            }
        });
    }
    let id = queue
        .enqueue("Flaky", serde_json::Value::Null)
        .await
        .unwrap();
    assert!(queue.run_one().await.unwrap());
    assert_eq!(state(&queue, id).await, JobState::Failed);
    assert!(!retry(&queue, Uuid::new_v4()).await);
    assert!(retry(&queue, id).await);
    assert!(!retry(&queue, id).await, "it is queued, not failed");
    let info = queue.job(id).await.unwrap().unwrap();
    assert_eq!(
        (info.state, info.max_attempts),
        (JobState::Queued, Some(2_i32))
    );

    // A run lost at attempt one still holds its old claim, and its result is
    // refused.
    let lost = sqlx::query(
        "UPDATE axa_queue SET status = 'failed', error = 'from the lost run', updated_at = now()
         WHERE id = $1 AND attempts = 1 AND status = 'running'",
    )
    .bind(id)
    .execute(queue.pool())
    .await
    .unwrap();
    assert_eq!(lost.rows_affected(), 0);

    fail.store(false, Ordering::SeqCst);
    assert!(queue.run_one().await.unwrap());
    let info = queue.job(id).await.unwrap().unwrap();
    assert_eq!((info.state, info.attempts), (JobState::Completed, 2_i32));
}

#[tokio::test]
#[ignore = "needs AXA_TEST_DB_URL"]
async fn a_batch_is_queued_whole_or_not_at_all() {
    let queue = fresh(quick()).await;
    let jobs: Vec<_> = (0_i32..3_i32)
        .map(|n| NewJob::new("Job", serde_json::json!(n)))
        .collect();
    let ids = queue.enqueue_all(&jobs).await.unwrap();
    assert_eq!(ids.len(), 3);
    for id in &ids {
        assert_eq!(state(&queue, *id).await, JobState::Queued);
    }
    let mut transaction = queue.pool().begin().await.unwrap();
    let dropped = enqueue_all_on(&mut transaction, &jobs).await.unwrap();
    transaction.rollback().await.unwrap();
    for id in dropped {
        assert!(queue.job(id).await.unwrap().is_none());
    }
    assert_eq!(
        count(queue.pool(), "SELECT count(*) FROM axa_queue").await,
        3
    );
}

#[tokio::test]
#[ignore = "needs AXA_TEST_DB_URL"]
async fn connecting_to_tables_without_the_new_columns_fails_and_changes_nothing() {
    let queue = fresh(quick()).await;
    sqlx::query("DROP TABLE axa_schedule")
        .execute(queue.pool())
        .await
        .unwrap();
    assert!(Queue::connect_existing(&uri(), quick()).await.is_err());
    sqlx::query("ALTER TABLE axa_queue DROP COLUMN priority")
        .execute(queue.pool())
        .await
        .unwrap();
    assert!(Queue::connect_existing(&uri(), quick()).await.is_err());
    assert_eq!(
        count(
            queue.pool(),
            "SELECT count(*) FROM information_schema.tables WHERE table_name = 'axa_schedule'"
        )
        .await,
        0
    );
    for statement in SETUP_STATEMENTS {
        sqlx::query(statement).execute(queue.pool()).await.unwrap();
    }
    assert!(Queue::connect_existing(&uri(), quick()).await.is_ok());
}

// Schedules.

fn every(queue: &mut Queue, name: &str, interval: Duration) {
    queue
        .schedule(
            Schedule::every(
                name,
                interval,
                NewJob::new("Tick", serde_json::json!({ "from": name })),
            )
            .unwrap(),
        )
        .unwrap();
}

async fn jobs_named(pool: &PgPool, name: &str) -> i64 {
    sqlx::query_scalar("SELECT count(*) FROM axa_queue WHERE name = $1")
        .bind(name)
        .fetch_one(pool)
        .await
        .unwrap()
}

/// Seconds between the row's due time and `from`, and between now and the due
/// time, on the database's clock.
async fn due(pool: &PgPool, name: &str) -> (f64, f64) {
    let row = sqlx::query(
        "SELECT EXTRACT(EPOCH FROM due_at - created_at)::float8 AS since,
                EXTRACT(EPOCH FROM due_at - now())::float8 AS ahead
         FROM axa_schedule WHERE name = $1",
    )
    .bind(name)
    .fetch_one(pool)
    .await
    .unwrap();
    (row.get("since"), row.get("ahead"))
}

#[tokio::test]
#[ignore = "needs AXA_TEST_DB_URL"]
async fn replicas_ticking_together_queue_each_due_time_once() {
    let mut replicas = Vec::new();
    replicas.push(fresh(quick()).await);
    for _ in 0_i32..5_i32 {
        replicas.push(replica(quick()).await);
    }
    for queue in &mut replicas {
        every(queue, "race", Duration::from_secs(1));
    }
    let pool = replicas[0].pool().clone();
    let replicas: Vec<_> = replicas.into_iter().map(Arc::new).collect();
    // Five due times, every replica ticking as fast as it can.
    let ticks: Vec<_> = replicas
        .iter()
        .map(|queue| {
            let queue = queue.clone();
            tokio::spawn(async move {
                let end = tokio::time::Instant::now() + Duration::from_millis(4_500);
                let mut mine = 0;
                while tokio::time::Instant::now() < end {
                    mine += queue.tick_schedules().await.unwrap();
                    // A due time is skipped while its last job is queued, so
                    // finish each job as soon as it is there. Only rows no other
                    // replica holds, so that six of these never deadlock.
                    sqlx::query(
                        "UPDATE axa_queue SET status = 'completed' WHERE id IN (
                             SELECT id FROM axa_queue WHERE status <> 'completed'
                             ORDER BY id FOR UPDATE SKIP LOCKED)",
                    )
                    .execute(queue.pool())
                    .await
                    .unwrap();
                }
                mine
            })
        })
        .collect();
    let mut total = 0;
    for tick in ticks {
        total += tick.await.unwrap();
    }
    let jobs = jobs_named(&pool, "Tick").await;
    assert_eq!(i64::try_from(total).unwrap(), jobs);
    assert!(
        (4..=6).contains(&jobs),
        "one job a second for 4.5 seconds: {jobs}"
    );
}

#[tokio::test]
#[ignore = "needs AXA_TEST_DB_URL"]
async fn missed_times_queue_one_job_and_the_schedule_keeps_its_place() {
    let mut queue = fresh(quick()).await;
    every(&mut queue, "missed", Duration::from_secs(10));
    assert_eq!(queue.tick_schedules().await.unwrap(), 1);
    sqlx::query("UPDATE axa_queue SET status = 'completed'")
        .execute(queue.pool())
        .await
        .unwrap();
    // As if every process had been down for about 95 seconds.
    sqlx::query(
        "UPDATE axa_schedule SET created_at = created_at - interval '95 seconds',
                due_at = due_at - interval '95 seconds'",
    )
    .execute(queue.pool())
    .await
    .unwrap();
    assert_eq!(queue.tick_schedules().await.unwrap(), 1);
    assert_eq!(queue.tick_schedules().await.unwrap(), 0);
    assert_eq!(jobs_named(queue.pool(), "Tick").await, 2);
    let (since, ahead) = due(queue.pool(), "missed").await;
    assert!(
        ahead > 0.0_f64 && ahead <= 10.0_f64,
        "the next time is ahead: {ahead}"
    );
    assert!(
        ((since / 10.0) - (since / 10.0).round()).abs() < 0.01_f64,
        "still on the grid of the first time: {since}"
    );
}

#[tokio::test]
#[ignore = "needs AXA_TEST_DB_URL"]
async fn a_due_time_is_skipped_while_the_last_job_has_not_finished() {
    let mut queue = fresh(quick()).await;
    every(&mut queue, "busy", Duration::from_secs(1));
    assert_eq!(queue.tick_schedules().await.unwrap(), 1);
    for state in ["queued", "running"] {
        sqlx::query("UPDATE axa_queue SET status = $1")
            .bind(state)
            .execute(queue.pool())
            .await
            .unwrap();
        sqlx::query("UPDATE axa_schedule SET due_at = now() - interval '1 second'")
            .execute(queue.pool())
            .await
            .unwrap();
        assert_eq!(
            queue.tick_schedules().await.unwrap(),
            0,
            "skipped while {state}"
        );
        let (_, ahead) = due(queue.pool(), "busy").await;
        assert!(ahead > 0.0_f64, "the skipped time is passed, not kept");
    }
    for state in ["completed", "failed", "cancelled", "needs_review"] {
        sqlx::query("UPDATE axa_queue SET status = $1")
            .bind(state)
            .execute(queue.pool())
            .await
            .unwrap();
        sqlx::query("UPDATE axa_schedule SET due_at = now() - interval '1 second'")
            .execute(queue.pool())
            .await
            .unwrap();
        assert_eq!(
            queue.tick_schedules().await.unwrap(),
            1,
            "queued after {state}"
        );
    }
}

#[tokio::test]
#[ignore = "needs AXA_TEST_DB_URL"]
async fn due_times_count_from_the_first_and_do_not_drift() {
    let mut queue = fresh(quick()).await;
    every(&mut queue, "steady", Duration::from_secs(1));
    queue.handle("Tick", |_| async {
        // Slower than nothing, so a schedule counting from when a job ran would drift.
        tokio::time::sleep(Duration::from_millis(150)).await;
        Ok::<(), String>(())
    });
    let (queue, stop, run) = start(queue);
    tokio::time::sleep(Duration::from_millis(3_600)).await;
    stop.send(true).unwrap();
    run.await.unwrap();
    let (since, _) = due(queue.pool(), "steady").await;
    assert!(
        (since - since.round()).abs() < 0.01_f64,
        "whole seconds from the first: {since}"
    );
    let times: Vec<f64> = sqlx::query_scalar(
        "SELECT EXTRACT(EPOCH FROM q.created_at - s.created_at)::float8
         FROM axa_queue q, axa_schedule s ORDER BY q.created_at",
    )
    .fetch_all(queue.pool())
    .await
    .unwrap();
    assert!((3..=5).contains(&times.len()), "{times:?}");
    // The due times themselves are checked above. A job is queued once its time has
    // come and before the next one, however late a busy machine wakes the poller.
    for (n, at) in times.iter().enumerate() {
        let n = f64::from(u32::try_from(n).unwrap());
        assert!(
            *at >= n && *at < n + 1.0_f64,
            "job {n} queued {at} seconds in"
        );
    }
}

#[tokio::test]
#[ignore = "needs AXA_TEST_DB_URL"]
async fn a_first_time_applies_only_when_the_row_is_made() {
    let mut queue = fresh(quick()).await;
    let first = time_of(
        queue.pool(),
        "SELECT date_trunc('second', now()) + interval '1 hour'",
    )
    .await;
    let job = NewJob::new("Tick", serde_json::Value::Null);
    queue
        .schedule(
            Schedule::every("nightly", Duration::from_hours(24), job.clone())
                .unwrap()
                .first_at(first),
        )
        .unwrap();
    assert_eq!(
        queue.tick_schedules().await.unwrap(),
        0,
        "not due until its first time"
    );
    let stored = time_of(
        queue.pool(),
        "SELECT due_at FROM axa_schedule WHERE name = 'nightly'",
    )
    .await;
    assert_eq!(stored, first);

    // A later release with another first time leaves the row where it is.
    let earlier = time_of(queue.pool(), "SELECT now() - interval '5 hours'").await;
    let mut later = replica(quick()).await;
    later
        .schedule(
            Schedule::every("nightly", Duration::from_hours(24), job)
                .unwrap()
                .first_at(earlier),
        )
        .unwrap();
    later.tick_schedules().await.unwrap();
    let stored = time_of(
        queue.pool(),
        "SELECT due_at FROM axa_schedule WHERE name = 'nightly'",
    )
    .await;
    assert_eq!(stored, first);
}

#[tokio::test]
#[ignore = "needs AXA_TEST_DB_URL"]
async fn a_scheduled_job_is_an_ordinary_job_and_shutdown_stops_the_ticks() {
    let mut queue = fresh(quick()).await;
    every(&mut queue, "report", Duration::from_secs(1));
    let runs = Arc::new(AtomicUsize::new(0));
    {
        let runs = runs.clone();
        queue.handle("Tick", move |args: serde_json::Value| {
            let runs = runs.clone();
            async move {
                assert_eq!(args["from"], "report");
                runs.fetch_add(1, Ordering::SeqCst);
                Ok::<(), String>(())
            }
        });
    }
    let (queue, stop, run) = start(queue);
    until(async || runs.load(Ordering::SeqCst) >= 1).await;
    stop.send(true).unwrap();
    tokio::time::timeout(Duration::from_secs(2), run)
        .await
        .expect("the ticks stopped")
        .unwrap();
    let after = jobs_named(queue.pool(), "Tick").await;
    tokio::time::sleep(Duration::from_millis(1_500)).await;
    assert_eq!(
        jobs_named(queue.pool(), "Tick").await,
        after,
        "nothing ticks after shutdown"
    );
    let counts = queue.counts().await.unwrap();
    assert!(counts.completed >= 1);
}

#[tokio::test]
#[ignore = "needs AXA_TEST_DB_URL"]
async fn a_heartbeat_that_hangs_stops_the_job_before_another_worker_may_take_it() {
    let mut queue = fresh(QueueOptions {
        heartbeat_interval: Duration::from_millis(30),
        // The least stale time, a minute, so the run stops two heartbeats before it.
        stale_minutes: 1,
        ..quick()
    })
    .await;
    let finished = Arc::new(AtomicUsize::new(0));
    {
        let finished = finished.clone();
        queue.handle("Long", move |_| {
            let finished = finished.clone();
            async move {
                tokio::time::sleep(Duration::from_secs(90)).await;
                finished.fetch_add(1, Ordering::SeqCst);
                Ok::<(), String>(())
            }
        });
    }
    let id = queue
        .enqueue("Long", serde_json::Value::Null)
        .await
        .unwrap();
    let queue = Arc::new(queue);
    let run = {
        let queue = queue.clone();
        tokio::spawn(async move { queue.run_one().await.unwrap() })
    };
    until(async || state(&queue, id).await == JobState::Running).await;
    // The row locked elsewhere, so each heartbeat waits, as on a database that hangs.
    let mut holder = queue.pool().begin().await.unwrap();
    sqlx::query("SELECT 1 FROM axa_queue WHERE id = $1 FOR UPDATE")
        .bind(id)
        .execute(&mut *holder)
        .await
        .unwrap();
    tokio::time::sleep(Duration::from_secs(62)).await;
    assert_eq!(
        finished.load(Ordering::SeqCst),
        0,
        "the job ran on while its heartbeat hung"
    );
    holder.rollback().await.unwrap();
    tokio::time::timeout(Duration::from_secs(10), run)
        .await
        .expect("the run stopped once it could mark the job")
        .unwrap();
    let info = queue.job(id).await.unwrap().unwrap();
    assert_eq!(info.state, JobState::NeedsReview);
    assert!(info.error.unwrap().contains("could not report in"));
}

#[tokio::test]
#[ignore = "needs AXA_TEST_DB_URL"]
async fn a_run_that_loses_its_claim_is_stopped_and_waits_for_review() {
    let mut queue = fresh(QueueOptions {
        heartbeat_interval: Duration::from_millis(30),
        ..quick()
    })
    .await;
    let finished = Arc::new(AtomicUsize::new(0));
    {
        let finished = finished.clone();
        queue.handle("Long", move |_| {
            let finished = finished.clone();
            async move {
                tokio::time::sleep(Duration::from_millis(800)).await;
                finished.fetch_add(1, Ordering::SeqCst);
                Ok::<(), String>(())
            }
        });
    }
    let id = queue
        .enqueue("Long", serde_json::Value::Null)
        .await
        .unwrap();
    let queue = Arc::new(queue);
    let run = {
        let queue = queue.clone();
        tokio::spawn(async move { queue.run_one().await.unwrap() })
    };
    until(async || state(&queue, id).await == JobState::Running).await;
    // Another worker took it over, as after a long outage.
    sqlx::query("UPDATE axa_queue SET attempts = attempts + 1, updated_at = now()")
        .execute(queue.pool())
        .await
        .unwrap();
    tokio::time::timeout(Duration::from_millis(500), run)
        .await
        .expect("the run stopped at its next report")
        .unwrap();
    tokio::time::sleep(Duration::from_millis(900)).await;
    assert_eq!(
        finished.load(Ordering::SeqCst),
        0,
        "the job itself was stopped"
    );
    let info = queue.job(id).await.unwrap().unwrap();
    assert_eq!(info.state, JobState::NeedsReview);
    assert!(info.error.unwrap().contains("took its claim"));
    // Nothing retries it by itself.
    sqlx::query("UPDATE axa_queue SET updated_at = now() - interval '2 hours'")
        .execute(queue.pool())
        .await
        .unwrap();
    assert_eq!(queue.requeue_stale().await.unwrap(), 0);
    assert_eq!(queue.purge_finished().await.unwrap(), 0);
    assert!(!queue.run_one().await.unwrap());
    assert_eq!(queue.counts().await.unwrap().needs_review, 1);
    // A person releases it, and the act is kept.
    assert!(retry(&queue, id).await);
    assert_eq!(state(&queue, id).await, JobState::Queued);
    assert_eq!(queue.acts(id).await.unwrap()[0].kind, ActKind::Released);
}

#[tokio::test]
#[ignore = "needs AXA_TEST_DB_URL"]
async fn a_run_that_finishes_after_losing_its_claim_waits_for_review() {
    let mut queue = fresh(quick()).await;
    queue.handle("Quick", |_| async {
        tokio::time::sleep(Duration::from_millis(200)).await;
        Ok::<(), String>(())
    });
    let id = queue
        .enqueue("Quick", serde_json::Value::Null)
        .await
        .unwrap();
    let queue = Arc::new(queue);
    let run = {
        let queue = queue.clone();
        tokio::spawn(async move { queue.run_one().await.unwrap() })
    };
    until(async || state(&queue, id).await == JobState::Running).await;
    sqlx::query("UPDATE axa_queue SET attempts = attempts + 1")
        .execute(queue.pool())
        .await
        .unwrap();
    run.await.unwrap();
    assert_eq!(state(&queue, id).await, JobState::NeedsReview);
}

#[tokio::test]
#[ignore = "needs AXA_TEST_DB_URL"]
async fn a_job_has_no_time_limit_unless_it_is_given_one() {
    let mut queue = fresh(quick()).await;
    queue.handle("Sleep", |millis: serde_json::Value| async move {
        tokio::time::sleep(Duration::from_millis(millis.as_u64().unwrap())).await;
        Ok::<(), String>(())
    });
    let unlimited = queue
        .enqueue("Sleep", serde_json::json!(1_500_i32))
        .await
        .unwrap();
    assert!(queue.run_one().await.unwrap());
    let info = queue.job(unlimited).await.unwrap().unwrap();
    assert_eq!((info.state, info.timeout), (JobState::Completed, None));

    let limited = queue
        .enqueue_job(
            &NewJob::new("Sleep", serde_json::json!(5_000_i32)).timeout(Duration::from_millis(200)),
        )
        .await
        .unwrap();
    let started = Instant::now();
    assert!(queue.run_one().await.unwrap());
    assert!(
        started.elapsed() < Duration::from_secs(2),
        "stopped at its limit"
    );
    let info = queue.job(limited).await.unwrap().unwrap();
    assert_eq!(info.state, JobState::Failed);
    assert_eq!(info.timeout, Some(Duration::from_millis(200)));
    assert_eq!(
        info.error.as_deref(),
        Some("worker error: timed out after 0.2s")
    );
}

async fn archived(pool: &PgPool, name: &str) -> Option<bool> {
    sqlx::query_scalar("SELECT archived_at IS NOT NULL FROM axa_schedule WHERE name = $1")
        .bind(name)
        .fetch_optional(pool)
        .await
        .unwrap()
}

#[tokio::test]
#[ignore = "needs AXA_TEST_DB_URL"]
async fn a_schedule_gone_from_code_is_archived_kept_and_restored_when_it_returns() {
    let mut old = fresh(quick()).await;
    every(&mut old, "retired", Duration::from_secs(1));
    every(&mut old, "kept", Duration::from_secs(1));
    assert_eq!(old.tick_schedules().await.unwrap(), 2);
    let leftover =
        sqlx::query_scalar::<_, Uuid>("SELECT last_job FROM axa_schedule WHERE name = 'retired'")
            .fetch_one(old.pool())
            .await
            .unwrap();

    // A new release drops `retired`. While a process may still have it, it stays.
    let mut new = replica(quick()).await;
    every(&mut new, "kept", Duration::from_secs(1));
    assert_eq!(
        new.archive_schedules().await.unwrap(),
        0,
        "seen recently, so maybe still live"
    );
    // Once no process has seen it for `stale_minutes`, it is archived, once.
    sqlx::query("UPDATE axa_schedule SET seen_at = now() - interval '2 hours'")
        .execute(new.pool())
        .await
        .unwrap();
    new.tick_schedules().await.unwrap(); // `kept` is seen again
    assert_eq!(new.archive_schedules().await.unwrap(), 1);
    assert_eq!(new.archive_schedules().await.unwrap(), 0);
    assert_eq!(archived(new.pool(), "retired").await, Some(true));
    assert_eq!(archived(new.pool(), "kept").await, Some(false));

    // Archived, it queues nothing, its row stays, and its last job still runs.
    sqlx::query("UPDATE axa_schedule SET due_at = now() - interval '1 minute'")
        .execute(new.pool())
        .await
        .unwrap();
    sqlx::query("UPDATE axa_queue SET status = 'completed' WHERE id <> $1")
        .bind(leftover)
        .execute(new.pool())
        .await
        .unwrap();
    assert_eq!(new.tick_schedules().await.unwrap(), 1, "only `kept`");
    assert_eq!(state(&new, leftover).await, JobState::Queued);
    let listed = new.schedules().await.unwrap();
    let retired = listed.iter().find(|s| s.name == "retired").unwrap();
    assert!(retired.archived_at.is_some());
    assert_eq!(retired.interval, Some(Duration::from_secs(1)));
    assert_eq!(retired.last_job, Some(leftover));
    assert_eq!(retired.last_state, Some(JobState::Queued));

    // It returns to code: the same row is restored, keeping its due time.
    let due_before = time_of(
        new.pool(),
        "SELECT due_at FROM axa_schedule WHERE name = 'retired'",
    )
    .await;
    let mut back = replica(quick()).await;
    every(&mut back, "retired", Duration::from_secs(1));
    back.tick_schedules().await.unwrap();
    assert_eq!(archived(back.pool(), "retired").await, Some(false));
    assert_eq!(
        count(
            back.pool(),
            "SELECT count(*) FROM axa_schedule WHERE name = 'retired'"
        )
        .await,
        1
    );
    let due_after = time_of(
        back.pool(),
        "SELECT due_at FROM axa_schedule WHERE name = 'retired'",
    )
    .await;
    // Its first time does not reset: the row keeps its place, and the time missed
    // while archived is skipped, as its last job is still queued.
    assert!(due_after > due_before);
    let last: Uuid = sqlx::query_scalar("SELECT last_job FROM axa_schedule WHERE name = 'retired'")
        .fetch_one(back.pool())
        .await
        .unwrap();
    assert_eq!(last, leftover);
}

// A person's acts.

/// A failed job, from a handler that always fails.
async fn failed_job(queue: &mut Queue) -> Uuid {
    queue.handle("Fails", |_| async { Err::<(), _>("down") });
    let id = queue
        .enqueue("Fails", serde_json::Value::Null)
        .await
        .unwrap();
    assert!(queue.run_one().await.unwrap());
    assert_eq!(state(queue, id).await, JobState::Failed);
    id
}

#[tokio::test]
#[ignore = "needs AXA_TEST_DB_URL"]
async fn each_act_is_kept_with_who_and_why_and_a_refused_one_is_not() {
    let mut queue = fresh(quick()).await;
    let queued = queue
        .enqueue("Nobody", serde_json::Value::Null)
        .await
        .unwrap();
    let failed = failed_job(&mut queue).await;
    let review = queue
        .enqueue("Nobody", serde_json::Value::Null)
        .await
        .unwrap();
    sqlx::query("UPDATE axa_queue SET status = 'needs_review' WHERE id = $1")
        .bind(review)
        .execute(queue.pool())
        .await
        .unwrap();

    assert!(cancel(&queue, queued).await);
    assert!(retry(&queue, failed).await);
    assert!(retry(&queue, review).await);
    // Acts that do not apply change nothing and are not kept.
    assert!(!cancel(&queue, queued).await, "already cancelled");
    assert!(!retry(&queue, queued).await, "cancelled is final");
    assert!(!retry(&queue, failed).await, "it is queued, not failed");
    assert!(!cancel(&queue, Uuid::new_v4()).await, "no such job");
    assert_eq!(
        count(queue.pool(), "SELECT count(*) FROM axa_job_acts").await,
        3
    );

    for (id, kind, name, attempts) in [
        (queued, ActKind::Cancelled, "Nobody", 0_i32),
        (failed, ActKind::Retried, "Fails", 1_i32),
        (review, ActKind::Released, "Nobody", 0_i32),
    ] {
        let acts = queue.acts(id).await.unwrap();
        assert_eq!(acts.len(), 1, "{kind:?}");
        let act = &acts[0];
        assert_eq!(act.job_id, id);
        assert_eq!(act.kind, kind);
        assert_eq!(act.job_name, name);
        assert_eq!(act.attempts, attempts);
        assert_eq!(act.by, "ops:alice");
        assert!(act.reason.starts_with("test_"));
    }
    assert!(queue.acts(Uuid::new_v4()).await.unwrap().is_empty());
}

#[tokio::test]
#[ignore = "needs AXA_TEST_DB_URL"]
async fn an_act_commits_with_its_change_and_the_callers_audit() {
    let queue = fresh(quick()).await;
    sqlx::query("CREATE TABLE IF NOT EXISTS service_audit (job UUID NOT NULL)")
        .execute(queue.pool())
        .await
        .unwrap();
    let id = queue
        .enqueue("Nobody", serde_json::Value::Null)
        .await
        .unwrap();
    let audits = async |id: Uuid| -> i64 {
        sqlx::query_scalar("SELECT count(*) FROM service_audit WHERE job = $1")
            .bind(id)
            .fetch_one(queue.pool())
            .await
            .unwrap()
    };

    // Rolled back: the job, its act, and the service's audit row all go.
    let mut transaction = queue.pool().begin().await.unwrap();
    assert!(
        axa_postgres_job_queue::cancel(&mut transaction, id, "ops:alice", "duplicate")
            .await
            .unwrap()
    );
    sqlx::query("INSERT INTO service_audit (job) VALUES ($1)")
        .bind(id)
        .execute(&mut *transaction)
        .await
        .unwrap();
    transaction.rollback().await.unwrap();
    assert_eq!(state(&queue, id).await, JobState::Queued);
    assert!(queue.acts(id).await.unwrap().is_empty());
    assert_eq!(audits(id).await, 0);

    // Committed: all three stand.
    let mut transaction = queue.pool().begin().await.unwrap();
    assert!(
        axa_postgres_job_queue::cancel(&mut transaction, id, "ops:alice", "duplicate")
            .await
            .unwrap()
    );
    sqlx::query("INSERT INTO service_audit (job) VALUES ($1)")
        .bind(id)
        .execute(&mut *transaction)
        .await
        .unwrap();
    transaction.commit().await.unwrap();
    assert_eq!(state(&queue, id).await, JobState::Cancelled);
    assert_eq!(queue.acts(id).await.unwrap().len(), 1);
    assert_eq!(audits(id).await, 1);
    sqlx::query("DROP TABLE service_audit")
        .execute(queue.pool())
        .await
        .unwrap();
}

#[tokio::test]
#[ignore = "needs AXA_TEST_DB_URL"]
async fn an_act_needs_a_short_code_for_who_and_why() {
    let queue = fresh(quick()).await;
    let id = queue
        .enqueue("Nobody", serde_json::Value::Null)
        .await
        .unwrap();
    let long = "x".repeat(201);
    for (by, reason, what) in [
        ("", "duplicate", "by"),
        ("ops:alice", "", "reason"),
        ("ops:alice", long.as_str(), "reason"),
        ("ops\nalice", "duplicate", "by"),
        ("ops:alice", "two\nlines", "reason"),
    ] {
        let mut transaction = queue.pool().begin().await.unwrap();
        let error = axa_postgres_job_queue::cancel(&mut transaction, id, by, reason)
            .await
            .unwrap_err();
        assert!(
            matches!(error, Error::NotACode { what: w } if w == what),
            "{error}"
        );
        let error = axa_postgres_job_queue::retry(&mut transaction, id, by, reason)
            .await
            .unwrap_err();
        assert!(matches!(error, Error::NotACode { .. }), "{error}");
        transaction.commit().await.unwrap();
    }
    assert_eq!(state(&queue, id).await, JobState::Queued);
    assert!(queue.acts(id).await.unwrap().is_empty());
    // The table refuses one written by hand too.
    let by_hand = sqlx::query(
        "INSERT INTO axa_job_acts (job_id, job_name, act, attempts, by, reason)
         VALUES ($1, 'Nobody', 'cancelled', 0, 'ops:alice', $2)",
    )
    .bind(id)
    .bind("two\nlines")
    .execute(queue.pool())
    .await;
    assert!(by_hand.is_err());
}

#[tokio::test]
#[ignore = "needs AXA_TEST_DB_URL"]
async fn the_acts_table_refuses_every_change() {
    let queue = fresh(quick()).await;
    let id = queue
        .enqueue("Nobody", serde_json::Value::Null)
        .await
        .unwrap();
    assert!(cancel(&queue, id).await);
    let changes = [
        "UPDATE axa_job_acts SET reason = 'changed'",
        "DELETE FROM axa_job_acts",
        "TRUNCATE axa_job_acts",
    ];
    // Whoever sends them, and with triggers for replication turned off too.
    for role in ["origin", "replica"] {
        let mut connection = queue.pool().acquire().await.unwrap();
        sqlx::query(sqlx::AssertSqlSafe(format!(
            "SET session_replication_role = {role}"
        )))
        .execute(&mut *connection)
        .await
        .unwrap();
        for change in changes {
            let error = sqlx::query(change)
                .execute(&mut *connection)
                .await
                .expect_err(change)
                .to_string();
            assert!(error.contains("refused"), "{change}: {error}");
        }
        sqlx::query("RESET session_replication_role")
            .execute(&mut *connection)
            .await
            .unwrap();
    }
    let acts = queue.acts(id).await.unwrap();
    assert_eq!(acts.len(), 1);
    assert_eq!(acts[0].reason, "test_cancel");
}

#[tokio::test]
#[ignore = "needs AXA_TEST_DB_URL"]
async fn acts_are_kept_when_their_job_is_swept() {
    let queue = fresh(quick()).await;
    let id = queue
        .enqueue("Nobody", serde_json::Value::Null)
        .await
        .unwrap();
    assert!(cancel(&queue, id).await);
    sqlx::query("UPDATE axa_queue SET updated_at = now() - interval '30 days'")
        .execute(queue.pool())
        .await
        .unwrap();
    assert_eq!(queue.purge_finished().await.unwrap(), 1);
    assert!(queue.job(id).await.unwrap().is_none());
    let acts = queue.acts(id).await.unwrap();
    assert_eq!(acts.len(), 1);
    assert_eq!(
        (acts[0].kind, acts[0].job_name.as_str()),
        (ActKind::Cancelled, "Nobody")
    );
}

#[tokio::test]
#[ignore = "needs AXA_TEST_DB_URL"]
async fn a_missing_or_turned_off_acts_trigger_stops_the_queue() {
    let queue = fresh(quick()).await;
    let setup = async || {
        for statement in SETUP_STATEMENTS {
            sqlx::query(statement).execute(queue.pool()).await.unwrap();
        }
    };
    assert!(Queue::connect_existing(&uri(), quick()).await.is_ok());
    for change in [
        "ALTER TABLE axa_job_acts DISABLE TRIGGER axa_job_acts_refuse",
        // On, but not always: `session_replication_role` could turn it off.
        "ALTER TABLE axa_job_acts ENABLE TRIGGER axa_job_acts_refuse_truncate",
        "DROP TRIGGER axa_job_acts_refuse ON axa_job_acts",
        "DROP TABLE axa_job_acts",
    ] {
        sqlx::query(change).execute(queue.pool()).await.unwrap();
        let error = Queue::connect_existing(&uri(), quick())
            .await
            .expect_err(change)
            .to_string();
        assert!(error.contains("axa_job_acts"), "{change}: {error}");
        setup().await;
        assert!(Queue::connect_existing(&uri(), quick()).await.is_ok());
    }
    // `connect` makes them.
    sqlx::query("DROP TABLE axa_job_acts")
        .execute(queue.pool())
        .await
        .unwrap();
    assert!(Queue::connect(&uri(), quick()).await.is_ok());
    assert!(Queue::connect_existing(&uri(), quick()).await.is_ok());
}

/// A tenant and the arguments, as a handler that takes a tenant saw them.
type Seen = (Option<String>, serde_json::Value);

#[tokio::test]
#[ignore = "needs AXA_TEST_DB_URL"]
async fn a_job_carries_its_tenant_to_a_handler_that_takes_one() {
    let mut queue = fresh(quick()).await;
    let seen: Arc<Mutex<Vec<Seen>>> = Arc::default();
    let record = Arc::clone(&seen);
    queue.handle_with_tenant("Tenanted", move |tenant, args| {
        record.lock().unwrap().push((tenant, args));
        async { Ok::<(), String>(()) }
    });
    queue.handle("Plain", |_args| async { Ok::<(), String>(()) });

    let job = NewJob::new("Tenanted", serde_json::json!({ "id": 7_i32 })).tenant("acme");
    assert_eq!(job.tenant_id(), Some("acme"));
    let acme = queue.enqueue_job(&job).await.unwrap();
    let none = queue
        .enqueue("Tenanted", serde_json::json!({ "id": 8_i32 }))
        .await
        .unwrap();
    let plain = queue
        .enqueue_job(&NewJob::new("Plain", serde_json::Value::Null).tenant("acme"))
        .await
        .unwrap();
    assert_eq!(
        queue.job(acme).await.unwrap().unwrap().tenant.as_deref(),
        Some("acme")
    );
    assert_eq!(queue.job(none).await.unwrap().unwrap().tenant, None);

    while queue.run_one().await.unwrap() {}
    let mut seen = seen.lock().unwrap().clone();
    seen.sort_by_key(|(_, args)| args["id"].as_i64());
    assert_eq!(
        seen,
        vec![
            (Some("acme".to_string()), serde_json::json!({ "id": 7_i32 })),
            (None, serde_json::json!({ "id": 8_i32 })),
        ]
    );
    // A handler that takes no tenant never runs a tenant's job.
    let plain = queue.job(plain).await.unwrap().unwrap();
    assert_eq!(plain.state, JobState::Failed);
    assert!(
        plain.error.unwrap().contains("handle_with_tenant"),
        "the failure says what to do"
    );
}

#[tokio::test]
#[ignore = "needs AXA_TEST_DB_URL"]
async fn a_tenant_that_is_not_a_tenant_id_is_refused() {
    let queue = fresh(quick()).await;
    for bad in [
        "",
        "Acme",
        "-acme",
        "acme-",
        "acme corp",
        "acme'--",
        &"a".repeat(64),
    ] {
        let job = NewJob::new("Tenanted", serde_json::Value::Null).tenant(bad);
        assert!(
            matches!(queue.enqueue_job(&job).await, Err(Error::NotATenant)),
            "{bad:?}"
        );
    }
    let count: i64 = sqlx::query_scalar("SELECT count(*) FROM axa_queue")
        .fetch_one(queue.pool())
        .await
        .unwrap();
    assert_eq!(count, 0, "nothing was written");
    // The table holds to the same rule, whatever writes to it.
    let direct = sqlx::query(
        "INSERT INTO axa_queue (id, name, args, tenant) VALUES ($1, 'x', 'null', 'Acme')",
    )
    .bind(Uuid::new_v4())
    .execute(queue.pool())
    .await;
    assert!(direct.is_err());
}

// Unique keys.

async fn set_status(queue: &Queue, id: Uuid, status: &str) {
    sqlx::query("UPDATE axa_queue SET status = $2 WHERE id = $1")
        .bind(id)
        .bind(status)
        .execute(queue.pool())
        .await
        .unwrap();
}

#[tokio::test]
#[ignore = "needs AXA_TEST_DB_URL"]
async fn a_job_with_a_key_is_queued_once_while_it_is_queued_or_running() {
    let queue = fresh(quick()).await;
    let job = |id: i64| NewJob::new("Sync", serde_json::json!({ "id": id })).unique("sync:42");
    assert_eq!(job(1).unique_key(), Some("sync:42"));
    let first = queue.enqueue_job(&job(1)).await.unwrap();
    assert_eq!(queue.enqueue_job(&job(2)).await.unwrap(), first);
    set_status(&queue, first, "running").await;
    assert_eq!(queue.enqueue_job(&job(3)).await.unwrap(), first);
    assert_eq!(
        queue
            .job(first)
            .await
            .unwrap()
            .unwrap()
            .unique_key
            .as_deref(),
        Some("sync:42")
    );
    let args: serde_json::Value = sqlx::query_scalar("SELECT args FROM axa_queue WHERE id = $1")
        .bind(first)
        .fetch_one(queue.pool())
        .await
        .unwrap();
    assert_eq!(
        args,
        serde_json::json!({ "id": 1_i32 }),
        "the first job's arguments stand"
    );

    // Another tenant, another name, or another key is another job, and so is one
    // with no key.
    let others = [
        job(4).tenant("acme"),
        NewJob::new("Other", serde_json::Value::Null).unique("sync:42"),
        NewJob::new("Sync", serde_json::Value::Null).unique("sync:43"),
        NewJob::new("Sync", serde_json::Value::Null),
        NewJob::new("Sync", serde_json::Value::Null),
    ];
    let mut ids = HashSet::from([first]);
    for other in &others {
        assert!(
            ids.insert(queue.enqueue_job(other).await.unwrap()),
            "{other:?}"
        );
    }
    assert_eq!(queue.enqueue_job(&job(5).tenant("acme")).await.unwrap(), {
        let acme: Uuid = sqlx::query_scalar("SELECT id FROM axa_queue WHERE tenant = 'acme'")
            .fetch_one(queue.pool())
            .await
            .unwrap();
        acme
    });

    // Once the job is done in any way, the key is free again.
    let mut last = first;
    for status in ["completed", "failed", "cancelled", "needs_review"] {
        set_status(&queue, last, status).await;
        let next = queue.enqueue_job(&job(6)).await.unwrap();
        assert_ne!(next, last, "free after {status}");
        last = next;
    }
}

#[tokio::test]
#[ignore = "needs AXA_TEST_DB_URL"]
async fn a_key_holds_against_a_job_in_a_transaction_not_yet_committed() {
    let queue = Arc::new(fresh(quick()).await);
    let job = || NewJob::new("Sync", serde_json::Value::Null).unique("sync:7");
    for commit in [true, false] {
        sqlx::query("DELETE FROM axa_queue")
            .execute(queue.pool())
            .await
            .unwrap();
        let mut transaction = queue.pool().begin().await.unwrap();
        let held = axa_postgres_job_queue::enqueue_on(&mut *transaction, &job())
            .await
            .unwrap();
        let other = {
            let queue = Arc::clone(&queue);
            tokio::spawn(async move { queue.enqueue_job(&job()).await.unwrap() })
        };
        tokio::time::sleep(Duration::from_millis(200)).await;
        assert!(
            !other.is_finished(),
            "the second enqueue waits for the first"
        );
        if commit {
            transaction.commit().await.unwrap();
            assert_eq!(other.await.unwrap(), held, "and then finds its job");
        } else {
            transaction.rollback().await.unwrap();
            assert_ne!(other.await.unwrap(), held, "or queues its own");
        }
        assert_eq!(
            count(queue.pool(), "SELECT count(*) FROM axa_queue").await,
            1
        );
    }
}

#[tokio::test]
#[ignore = "needs AXA_TEST_DB_URL"]
async fn a_failed_job_is_not_retried_while_another_of_its_key_is_queued() {
    let queue = fresh(quick()).await;
    let job = || NewJob::new("Sync", serde_json::Value::Null).unique("sync:9");
    let failed = queue.enqueue_job(&job()).await.unwrap();
    set_status(&queue, failed, "failed").await;
    let queued = queue.enqueue_job(&job()).await.unwrap();
    assert!(!retry(&queue, failed).await, "another of its key is queued");
    assert_eq!(state(&queue, failed).await, JobState::Failed);
    assert!(
        queue.acts(failed).await.unwrap().is_empty(),
        "and no act is kept"
    );
    set_status(&queue, queued, "completed").await;
    assert!(
        retry(&queue, failed).await,
        "and once it is done, it may be"
    );
}

#[tokio::test]
#[ignore = "needs AXA_TEST_DB_URL"]
async fn a_key_that_is_not_a_code_is_refused() {
    let queue = fresh(quick()).await;
    for bad in [String::new(), "a\nb".to_string(), "k".repeat(201)] {
        let job = NewJob::new("Sync", serde_json::Value::Null).unique(bad.clone());
        assert!(
            matches!(
                queue.enqueue_job(&job).await,
                Err(Error::NotACode { what: "unique key" })
            ),
            "{bad:?}"
        );
    }
    assert_eq!(
        count(queue.pool(), "SELECT count(*) FROM axa_queue").await,
        0
    );
    let direct = sqlx::query(
        "INSERT INTO axa_queue (id, name, args, unique_key) VALUES ($1, 'x', 'null', '')",
    )
    .bind(Uuid::new_v4())
    .execute(queue.pool())
    .await;
    assert!(direct.is_err(), "the table refuses it too");
    // And a queue without the key's index is stopped at boot.
    sqlx::query("DROP INDEX axa_queue_unique")
        .execute(queue.pool())
        .await
        .unwrap();
    assert!(Queue::connect_existing(&uri(), quick()).await.is_err());
}

// Cron schedules.

fn cron(queue: &mut Queue, name: &str, pattern: &str) {
    queue
        .schedule(
            Schedule::cron(
                name,
                pattern,
                NewJob::new("Tick", serde_json::json!({ "from": name })),
            )
            .unwrap(),
        )
        .unwrap();
}

async fn set_due(pool: &PgPool, name: &str, seconds_ago: f64) {
    sqlx::query(
        "UPDATE axa_schedule SET due_at = now() - make_interval(secs => $2) WHERE name = $1",
    )
    .bind(name)
    .bind(seconds_ago)
    .execute(pool)
    .await
    .unwrap();
}

/// The schedule's due time, and the database's now.
async fn due_and_now(pool: &PgPool, name: &str) -> (Timestamp, Timestamp) {
    let row = sqlx::query("SELECT due_at, now() AS now FROM axa_schedule WHERE name = $1")
        .bind(name)
        .fetch_one(pool)
        .await
        .unwrap();
    let time = |column| row.get::<jiff_sqlx::Timestamp, _>(column).to_jiff();
    (time("due_at"), time("now"))
}

#[tokio::test]
#[ignore = "needs AXA_TEST_DB_URL"]
async fn a_cron_schedule_first_runs_at_its_patterns_next_time() {
    let mut queue = fresh(quick()).await;
    cron(&mut queue, "at-two", "0 2 * * *");
    assert_eq!(queue.tick_schedules().await.unwrap(), 0, "not due at boot");
    let (due, now) = due_and_now(queue.pool(), "at-two").await;
    assert!(due > now && due.duration_since(now) <= SignedDuration::from_hours(24));
    let due = TimeZone::UTC.to_datetime(due);
    assert_eq!(
        (due.hour(), due.minute(), due.second()),
        (2, 0, 0),
        "in UTC"
    );
    let info = queue.schedules().await.unwrap();
    assert_eq!(info[0].cron.as_deref(), Some("0 2 * * *"));
    assert_eq!(info[0].interval, None);
}

#[tokio::test]
#[ignore = "needs AXA_TEST_DB_URL"]
async fn a_cron_schedule_queues_once_for_missed_times_and_skips_while_busy() {
    let mut queue = fresh(quick()).await;
    cron(&mut queue, "secondly", "* * * * * *");
    queue.tick_schedules().await.unwrap();
    // That tick makes the row, and queues a job too if a second has passed since, which
    // would leave the schedule busy below. Start with none.
    sqlx::query("DELETE FROM axa_queue")
        .execute(queue.pool())
        .await
        .unwrap();
    // Every process was down for a week.
    set_due(queue.pool(), "secondly", 7.0 * 86_400.0).await;
    assert_eq!(
        queue.tick_schedules().await.unwrap(),
        1,
        "one job for them all"
    );
    let (due, now) = due_and_now(queue.pool(), "secondly").await;
    assert!(
        due > now - SignedDuration::from_secs(1),
        "the next is the pattern's after now"
    );
    assert_eq!(
        due.subsec_microsecond(),
        0_i32,
        "on the pattern's whole second"
    );
    // Due again while its job is still queued: skipped, and moved on.
    set_due(queue.pool(), "secondly", 1.0).await;
    assert_eq!(queue.tick_schedules().await.unwrap(), 0);
    assert_eq!(jobs_named(queue.pool(), "Tick").await, 1);
    let (due, now) = due_and_now(queue.pool(), "secondly").await;
    assert!(due > now - SignedDuration::from_secs(1));
    // Once it finished, the next due time queues again.
    sqlx::query("UPDATE axa_queue SET status = 'completed'")
        .execute(queue.pool())
        .await
        .unwrap();
    set_due(queue.pool(), "secondly", 1.0).await;
    assert_eq!(queue.tick_schedules().await.unwrap(), 1);
}

#[tokio::test]
#[ignore = "needs AXA_TEST_DB_URL"]
async fn a_changed_pattern_takes_its_next_time_from_the_new_one() {
    let hour = |due: Timestamp| TimeZone::UTC.to_datetime(due).hour();
    let mut queue = fresh(quick()).await;
    every(&mut queue, "nightly", Duration::from_hours(24));
    queue.tick_schedules().await.unwrap();
    let mut queue = replica(quick()).await;
    cron(&mut queue, "nightly", "0 2 * * *");
    queue.tick_schedules().await.unwrap();
    let (due, _) = due_and_now(queue.pool(), "nightly").await;
    assert_eq!(hour(due), 2, "from an interval to a pattern");
    let mut queue = replica(quick()).await;
    cron(&mut queue, "nightly", "0 3 * * *");
    queue.tick_schedules().await.unwrap();
    let (due, _) = due_and_now(queue.pool(), "nightly").await;
    assert_eq!(hour(due), 3, "from one pattern to another");
    let info = queue.schedules().await.unwrap();
    assert_eq!(info[0].cron.as_deref(), Some("0 3 * * *"));
}

#[tokio::test]
#[ignore = "needs AXA_TEST_DB_URL"]
async fn replicas_ticking_a_cron_schedule_queue_each_due_time_once() {
    let mut replicas = Vec::new();
    replicas.push(fresh(quick()).await);
    for _ in 0_i32..5_i32 {
        replicas.push(replica(quick()).await);
    }
    for queue in &mut replicas {
        cron(queue, "race", "* * * * * *");
    }
    let pool = replicas[0].pool().clone();
    let replicas: Vec<_> = replicas.into_iter().map(Arc::new).collect();
    let ticks: Vec<_> = replicas
        .iter()
        .map(|queue| {
            let queue = queue.clone();
            tokio::spawn(async move {
                let end = tokio::time::Instant::now() + Duration::from_millis(4_500);
                let mut mine = 0;
                while tokio::time::Instant::now() < end {
                    mine += queue.tick_schedules().await.unwrap();
                    sqlx::query(
                        "UPDATE axa_queue SET status = 'completed' WHERE id IN (
                             SELECT id FROM axa_queue WHERE status <> 'completed'
                             ORDER BY id FOR UPDATE SKIP LOCKED)",
                    )
                    .execute(queue.pool())
                    .await
                    .unwrap();
                }
                mine
            })
        })
        .collect();
    let mut total = 0;
    for tick in ticks {
        total += tick.await.unwrap();
    }
    let jobs = jobs_named(&pool, "Tick").await;
    assert_eq!(i64::try_from(total).unwrap(), jobs);
    assert!(
        (3..=5).contains(&jobs),
        "one job a second for 4.5 seconds: {jobs}"
    );
}

#[tokio::test]
#[ignore = "needs AXA_TEST_DB_URL"]
async fn a_job_that_asks_for_a_delay_is_tried_again_after_it() {
    let mut queue = fresh(quick()).await;
    queue.handle("Busy", |_| async {
        Err(
            axa_postgres_job_queue::RetryAfter::new(Duration::from_mins(2), "the receiver is busy")
                .unwrap(),
        )
    });
    let job = NewJob::new("Busy", serde_json::Value::Null).max_attempts(Some(3_i32));
    let id = queue.enqueue_job(&job).await.unwrap();
    assert!(queue.run_one().await.unwrap());
    let info = queue.job(id).await.unwrap().unwrap();
    assert_eq!(info.state, JobState::Queued);
    assert_eq!(info.error.as_deref(), Some("the receiver is busy"));
    let wait = info.run_at.duration_since(info.updated_at).as_millis();
    assert!((119_000..=121_000).contains(&wait), "{wait}");
    assert!(!queue.run_one().await.unwrap(), "not before its time");
}

#[tokio::test]
#[ignore = "needs AXA_TEST_DB_URL"]
async fn a_queued_job_wakes_an_idle_loop_before_its_next_poll() {
    let mut queue = fresh(QueueOptions {
        poll_interval: Duration::from_mins(1),
        ..quick()
    })
    .await;
    let ran = Arc::new(AtomicUsize::new(0));
    {
        let ran = ran.clone();
        queue.handle("Ping", move |_| {
            let ran = ran.clone();
            async move {
                ran.fetch_add(1, Ordering::SeqCst);
                Ok::<(), String>(())
            }
        });
    }
    let (queue, stop, run) = start(queue);
    // Every loop has polled once and found nothing, and the listener is in place.
    tokio::time::sleep(Duration::from_millis(500)).await;
    let began = Instant::now();
    queue
        .enqueue("Ping", serde_json::Value::Null)
        .await
        .unwrap();
    let mut tx = queue.pool().begin().await.unwrap();
    enqueue_all_on(&mut tx, &[NewJob::new("Ping", serde_json::Value::Null)])
        .await
        .unwrap();
    tx.commit().await.unwrap();
    until(async || ran.load(Ordering::SeqCst) == 2).await;
    assert_eq!(ran.load(Ordering::SeqCst), 2);
    assert!(
        began.elapsed() < Duration::from_secs(5),
        "{:?}",
        began.elapsed()
    );
    stop.send(true).unwrap();
    run.await.unwrap();
}

#[tokio::test]
#[ignore = "needs AXA_TEST_DB_URL"]
async fn a_job_that_panics_fails_and_its_loop_carries_on() {
    let mut queue = fresh(QueueOptions {
        workers: 1,
        ..quick()
    })
    .await;
    // Its job's arguments are null, so it panics.
    queue.handle("Panics", |args: serde_json::Value| async move {
        assert!(!args.is_null(), "the panic's own text");
        Ok::<(), String>(())
    });
    let gauge = Gauge::default();
    queue.handle("Fine", gauge.handler(0));
    assert_eq!(queue.handled(), HashSet::from(["Panics", "Fine"]));
    queue.ping().await.unwrap();
    let panics = queue
        .enqueue_limited("Panics", serde_json::Value::Null, Some(1_i32))
        .await
        .unwrap();
    assert_eq!(
        queue.job(panics).await.unwrap().unwrap().max_attempts,
        Some(1_i32)
    );
    queue
        .enqueue("Fine", serde_json::Value::Null)
        .await
        .unwrap();
    let (queue, stop, run) = start(queue);
    until(async || gauge.done() == 1 && state(&queue, panics).await == JobState::Failed).await;
    let failed = queue.job(panics).await.unwrap().unwrap();
    assert_eq!(failed.attempts, 1_i32, "its own limit of one try");
    let error = failed.error.unwrap();
    assert!(error.contains("the job panicked"), "{error}");
    assert!(!error.contains("own text"), "{error}");
    stop.send(true).unwrap();
    run.await.unwrap();
}