ryuk 0.1.1

A Laravel-style full-stack web framework for Rust: axum, SeaORM and Inertia, with auth, queues, mail, storage, cache, scheduling and an MCP server.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
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
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
//! Push notifications: device registry (`push_devices`, self-created), a [`Notification`]
//! builder and a [`Push`] service with FCM HTTP v1 (Android) and APNs HTTP/2 (iOS) providers.
//!
//! Without provider configuration the `log` driver is used: it logs title, body, data and the
//! device count, never a device token. Real providers come from [`Push::from_env`]:
//! `FCM_PROJECT_ID` + `FCM_SERVICE_ACCOUNT_JSON` | `FCM_SERVICE_ACCOUNT_PATH`, and `APNS_KEY` |
//! `APNS_KEY_PATH`, `APNS_KEY_ID`, `APNS_TEAM_ID`, `APNS_TOPIC`, `APNS_ENV=production|sandbox`.
//! `PUSH_DRIVER=log` forces the log driver, `PUSH_DRIVER=live` insists on a real provider.
//!
//! ```ignore
//! let push = Push::from_env(db.clone()).await?;
//! push.devices().ensure_tables().await?;
//! push.devices().register(user.id, Platform::Ios, &token, Some("com.acme.app"), Some("iPhone")).await?;
//! let report = push.send_to_user(user.id, &Notification::new().title("Hi").body("Hello")).await?;
//! ```
//!
//! Outcomes: success; token rejected by the provider (APNs 410 / BadDeviceToken /
//! DeviceTokenNotForTopic, FCM 404 / INVALID_ARGUMENT about the token) marks the device invalid and
//! is never retried; 429, 5xx and network errors are retried (3 tries, exponential backoff with
//! jitter, `Retry-After` honored) and then reported as [`Delivery::Transient`].
//!
//! shortcut: FCM `badge` is ignored (Android has no badge field); retry sleeps are capped at 30 s.
use jsonwebtoken::{Algorithm, EncodingKey, Header};
use sea_orm::entity::prelude::*;
use sea_orm::{
    ActiveValue::Set, ColumnTrait, Condition, ConnectionTrait, DatabaseConnection, DbBackend,
    DbErr, EntityTrait, QueryFilter, Schema, sea_query::Expr,
};
use serde_json::{Value, json};
use std::collections::BTreeMap;
use std::sync::Arc;
use std::time::{Duration, Instant};

const MAX_PAYLOAD: usize = 4096;
const MAX_TRIES: u32 = 3;
const MAX_CONCURRENCY: usize = 16;
const TIMEOUT: Duration = Duration::from_secs(10);

/// Registry, payload or provider failure.
#[derive(Debug, thiserror::Error)]
pub enum PushError {
    /// Database error.
    #[error("database: {0}")]
    Db(#[from] DbErr),
    /// Invalid input (token, name, ...).
    #[error("invalid input: {0}")]
    Invalid(String),
    /// The payload is malformed or larger than the 4 KB provider limit.
    #[error("payload: {0}")]
    Payload(String),
    /// Bad configuration (env, key, URL) or no provider for a platform.
    #[error("push config: {0}")]
    Config(String),
    /// The provider answered with a non-retryable error.
    #[error("provider answered {status}: {detail}")]
    Provider {
        /// HTTP status.
        status: u16,
        /// Truncated response body.
        detail: String,
    },
}

/// Device platform.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Platform {
    /// APNs.
    Ios,
    /// FCM.
    Android,
}

impl Platform {
    /// `"ios"` or `"android"`.
    pub fn as_str(self) -> &'static str {
        match self {
            Platform::Ios => "ios",
            Platform::Android => "android",
        }
    }
    /// Inverse of [`as_str`](Self::as_str).
    pub fn parse(s: &str) -> Option<Self> {
        match s {
            "ios" => Some(Platform::Ios),
            "android" => Some(Platform::Android),
            _ => None,
        }
    }
}

/// `push_devices` table.
pub mod push_devices {
    use sea_orm::entity::prelude::*;
    /// One registered device. The raw token is kept (needed to send); uniqueness is on the hash.
    #[derive(Clone, PartialEq, DeriveEntityModel)]
    #[sea_orm(table_name = "push_devices")]
    pub struct Model {
        #[sea_orm(primary_key)]
        pub id: i64,
        #[sea_orm(indexed)]
        pub user_id: i64,
        /// `ios` or `android`.
        pub platform: String,
        #[sea_orm(column_type = "Text")]
        pub token: String,
        /// Lowercase hex sha256 of `platform:token`: a short unique key (a raw token would not fit a MySQL index).
        #[sea_orm(unique)]
        pub token_hash: String,
        pub app_id: Option<String>,
        pub name: Option<String>,
        pub created_at: i64,
        pub last_seen_at: i64,
        pub invalid_at: Option<i64>,
    }
    impl std::fmt::Debug for Model {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            f.debug_struct("push_devices::Model")
                .field("id", &self.id)
                .field("user_id", &self.user_id)
                .field("platform", &self.platform)
                .field("token", &"<redacted>")
                .finish_non_exhaustive()
        }
    }
    #[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
    pub enum Relation {}
    impl ActiveModelBehavior for ActiveModel {}
}
use push_devices::{Column, Entity};

/// A registered device with its token (for sending). `Debug` redacts the token.
#[derive(Clone, PartialEq)]
pub struct Device {
    /// Row id.
    pub id: i64,
    /// Owner.
    pub user_id: i64,
    /// Platform.
    pub platform: Platform,
    /// Provider token.
    pub token: String,
    /// Bundle id / package name.
    pub app_id: Option<String>,
}

impl std::fmt::Debug for Device {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Device")
            .field("id", &self.id)
            .field("user_id", &self.user_id)
            .field("platform", &self.platform)
            .field("token", &"<redacted>")
            .finish_non_exhaustive()
    }
}

/// A registered device without its token (safe to return from an API).
#[derive(Debug, Clone, PartialEq)]
pub struct DeviceInfo {
    /// Row id.
    pub id: i64,
    /// Owner.
    pub user_id: i64,
    /// Platform.
    pub platform: Platform,
    /// Bundle id / package name.
    pub app_id: Option<String>,
    /// Display name.
    pub name: Option<String>,
    /// Unix seconds.
    pub created_at: i64,
    /// Unix seconds of the last registration.
    pub last_seen_at: i64,
    /// Unix seconds when the provider rejected the token.
    pub invalid_at: Option<i64>,
}

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

fn platform_of(s: &str) -> Platform {
    Platform::parse(s).unwrap_or(Platform::Android)
}

fn info(m: push_devices::Model) -> DeviceInfo {
    DeviceInfo {
        id: m.id,
        user_id: m.user_id,
        platform: platform_of(&m.platform),
        app_id: m.app_id,
        name: m.name,
        created_at: m.created_at,
        last_seen_at: m.last_seen_at,
        invalid_at: m.invalid_at,
    }
}

/// sha256 hex. Hand-written: the `push` feature has no `sha2` dependency and only needs this for a lookup key.
fn sha256_hex(data: &[u8]) -> String {
    const K: [u32; 64] = [
        0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4,
        0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe,
        0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f,
        0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
        0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc,
        0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b,
        0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116,
        0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
        0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7,
        0xc67178f2,
    ];
    let mut h: [u32; 8] = [
        0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab,
        0x5be0cd19,
    ];
    let mut msg = data.to_vec();
    msg.push(0x80);
    while msg.len() % 64 != 56 {
        msg.push(0);
    }
    msg.extend_from_slice(&((data.len() as u64) * 8).to_be_bytes());
    for block in msg.chunks(64) {
        let mut w = [0u32; 64];
        for (i, c) in block.chunks(4).enumerate() {
            w[i] = u32::from_be_bytes([c[0], c[1], c[2], c[3]]);
        }
        for i in 16..64 {
            let s0 = w[i - 15].rotate_right(7) ^ w[i - 15].rotate_right(18) ^ (w[i - 15] >> 3);
            let s1 = w[i - 2].rotate_right(17) ^ w[i - 2].rotate_right(19) ^ (w[i - 2] >> 10);
            w[i] = w[i - 16]
                .wrapping_add(s0)
                .wrapping_add(w[i - 7])
                .wrapping_add(s1);
        }
        let mut v = h;
        for i in 0..64 {
            let s1 = v[4].rotate_right(6) ^ v[4].rotate_right(11) ^ v[4].rotate_right(25);
            let ch = (v[4] & v[5]) ^ (!v[4] & v[6]);
            let t1 = v[7]
                .wrapping_add(s1)
                .wrapping_add(ch)
                .wrapping_add(K[i])
                .wrapping_add(w[i]);
            let s0 = v[0].rotate_right(2) ^ v[0].rotate_right(13) ^ v[0].rotate_right(22);
            let maj = (v[0] & v[1]) ^ (v[0] & v[2]) ^ (v[1] & v[2]);
            let t2 = s0.wrapping_add(maj);
            v = [
                t1.wrapping_add(t2),
                v[0],
                v[1],
                v[2],
                v[3].wrapping_add(t1),
                v[4],
                v[5],
                v[6],
            ];
        }
        for (a, b) in h.iter_mut().zip(v) {
            *a = a.wrapping_add(b);
        }
    }
    h.iter().map(|x| format!("{x:08x}")).collect()
}

fn token_hash(p: Platform, token: &str) -> String {
    sha256_hex(format!("{}:{token}", p.as_str()).as_bytes())
}

/// The device registry.
#[derive(Clone)]
pub struct Devices {
    db: DatabaseConnection,
    max_per_user: usize,
}

/// Default cap of registered devices per user; the least recently seen one is evicted beyond it.
pub const MAX_DEVICES_PER_USER: usize = 20;

impl Devices {
    /// Registry over `db`.
    pub fn new(db: DatabaseConnection) -> Self {
        Self {
            db,
            max_per_user: MAX_DEVICES_PER_USER,
        }
    }

    /// Change the per-user device cap (default [`MAX_DEVICES_PER_USER`]).
    pub fn max_per_user(mut self, n: usize) -> Self {
        self.max_per_user = n.max(1);
        self
    }

    /// Delete the user's least recently seen devices beyond the cap, never `keep`.
    async fn evict(&self, user_id: i64, keep: i64) -> Result<(), PushError> {
        use sea_orm::QueryOrder;
        let stale = Entity::find()
            .filter(Column::UserId.eq(user_id))
            .order_by_desc(Column::LastSeenAt)
            .order_by_desc(Column::Id)
            .all(&self.db)
            .await?;
        let extra = stale
            .into_iter()
            .filter(|d| d.id != keep)
            .skip(self.max_per_user - 1);
        let ids: Vec<i64> = extra.map(|d| d.id).collect();
        if !ids.is_empty() {
            Entity::delete_many()
                .filter(Column::Id.is_in(ids))
                .exec(&self.db)
                .await?;
        }
        Ok(())
    }

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

    /// Register (or refresh) a device. Upsert by (platform, token): a token already registered for
    /// ANOTHER user moves to `user_id` (the phone changed hands); `invalid_at` is cleared and
    /// `last_seen_at` updated. `app_id` / `name` are replaced by the given values. A user keeps at most
    /// [`MAX_DEVICES_PER_USER`] devices (see [`Devices::max_per_user`]): registering one more evicts
    /// the least recently seen (concurrent registers may briefly overshoot, the next register trims).
    pub async fn register(
        &self,
        user_id: i64,
        platform: Platform,
        token: &str,
        app_id: Option<&str>,
        name: Option<&str>,
    ) -> Result<DeviceInfo, PushError> {
        let bad = |m: &str| Err(PushError::Invalid(m.into()));
        if !(8..=4096).contains(&token.chars().count()) || token.chars().any(char::is_whitespace) {
            return bad("token must be 8..=4096 characters without whitespace");
        }
        if platform == Platform::Ios && !token.chars().all(|c| c.is_ascii_alphanumeric()) {
            return bad("an iOS token is alphanumeric (hex)");
        }
        if name.is_some_and(|n| n.chars().count() > 100) {
            return bad("name is at most 100 characters");
        }
        if app_id.is_some_and(|a| a.chars().count() > 200) {
            return bad("app_id is at most 200 characters");
        }
        let h = token_hash(platform, token);
        let t = now();
        let mut insert_err = None;
        for _ in 0..2 {
            if let Some(row) = Entity::find()
                .filter(Column::TokenHash.eq(h.as_str()))
                .one(&self.db)
                .await?
            {
                Entity::update_many()
                    .col_expr(Column::UserId, Expr::value(user_id))
                    .col_expr(Column::AppId, Expr::value(app_id.map(String::from)))
                    .col_expr(Column::Name, Expr::value(name.map(String::from)))
                    .col_expr(Column::LastSeenAt, Expr::value(t))
                    .col_expr(Column::InvalidAt, Expr::value(None::<i64>))
                    .filter(Column::Id.eq(row.id))
                    .exec(&self.db)
                    .await?;
                self.evict(user_id, row.id).await?;
                let row = Entity::find_by_id(row.id).one(&self.db).await?;
                return row
                    .map(info)
                    .ok_or_else(|| PushError::Invalid("device vanished".into()));
            }
            // A concurrent register of the same token may win the unique index: loop once and update.
            match (push_devices::ActiveModel {
                user_id: Set(user_id),
                platform: Set(platform.as_str().into()),
                token: Set(token.into()),
                token_hash: Set(h.clone()),
                app_id: Set(app_id.map(String::from)),
                name: Set(name.map(String::from)),
                created_at: Set(t),
                last_seen_at: Set(t),
                invalid_at: Set(None),
                ..Default::default()
            })
            .insert(&self.db)
            .await
            {
                Ok(m) => {
                    self.evict(user_id, m.id).await?;
                    return Ok(info(m));
                }
                Err(e) => insert_err = Some(e),
            }
        }
        Err(insert_err.map(PushError::Db).unwrap())
    }

    /// The user's devices (valid and invalid), newest first, without tokens.
    pub async fn list(&self, user_id: i64) -> Result<Vec<DeviceInfo>, PushError> {
        use sea_orm::QueryOrder;
        Ok(Entity::find()
            .filter(Column::UserId.eq(user_id))
            .order_by_desc(Column::Id)
            .all(&self.db)
            .await?
            .into_iter()
            .map(info)
            .collect())
    }

    /// Delete a device; `false` if it does not exist or belongs to someone else.
    pub async fn unregister(&self, user_id: i64, id: i64) -> Result<bool, PushError> {
        let q = || {
            Entity::delete_many()
                .filter(Column::Id.eq(id))
                .filter(Column::UserId.eq(user_id))
        };
        let exists = Entity::find()
            .filter(Column::Id.eq(id))
            .filter(Column::UserId.eq(user_id))
            .one(&self.db)
            .await?
            .is_some();
        q().exec(&self.db).await?;
        Ok(exists)
    }

    /// Flag a token the provider rejected; it is no longer sent to until re-registered.
    pub async fn mark_invalid(&self, platform: Platform, token: &str) -> Result<(), PushError> {
        Entity::update_many()
            .col_expr(Column::InvalidAt, Expr::value(now()))
            .filter(Column::TokenHash.eq(token_hash(platform, token)))
            .exec(&self.db)
            .await?;
        Ok(())
    }

    /// The user's sendable devices (with tokens).
    pub async fn valid_for_user(&self, user_id: i64) -> Result<Vec<Device>, PushError> {
        Ok(Entity::find()
            .filter(Column::UserId.eq(user_id))
            .filter(Column::InvalidAt.is_null())
            .all(&self.db)
            .await?
            .into_iter()
            .map(|m| Device {
                id: m.id,
                user_id: m.user_id,
                platform: platform_of(&m.platform),
                token: m.token,
                app_id: m.app_id,
            })
            .collect())
    }

    /// Delete devices invalid for longer than `invalid_older_than` or not seen for `idle_older_than`.
    pub async fn prune(
        &self,
        invalid_older_than: Duration,
        idle_older_than: Duration,
    ) -> Result<u64, PushError> {
        let cut = |d: Duration| now().saturating_sub(d.as_secs().min(i64::MAX as u64 / 2) as i64);
        Ok(Entity::delete_many()
            .filter(
                Condition::any()
                    .add(Column::InvalidAt.lt(cut(invalid_older_than)))
                    .add(Column::LastSeenAt.lt(cut(idle_older_than))),
            )
            .exec(&self.db)
            .await?
            .rows_affected)
    }
}

/// Delivery urgency.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Priority {
    /// Wake the device now (APNs 10, FCM HIGH).
    High,
    /// Power-friendly (APNs 5, FCM NORMAL).
    Normal,
}

/// A push message. Build it with the chained setters.
///
/// ```ignore
/// let n = Notification::new().title("Order shipped").body("Arrives Friday").data("order", "42").badge(1);
/// ```
#[derive(Debug, Clone, PartialEq)]
pub struct Notification {
    title: Option<String>,
    body: Option<String>,
    data: BTreeMap<String, String>,
    badge: Option<u32>,
    sound: Option<String>,
    collapse_key: Option<String>,
    ttl: Option<Duration>,
    priority: Priority,
    content_available: bool,
}

impl Default for Notification {
    fn default() -> Self {
        Self {
            title: None,
            body: None,
            data: BTreeMap::new(),
            badge: None,
            sound: None,
            collapse_key: None,
            ttl: None,
            priority: Priority::High,
            content_available: false,
        }
    }
}

impl Notification {
    /// Empty notification (priority high).
    pub fn new() -> Self {
        Self::default()
    }
    /// Alert title.
    pub fn title(mut self, s: impl Into<String>) -> Self {
        self.title = Some(s.into());
        self
    }
    /// Alert body.
    pub fn body(mut self, s: impl Into<String>) -> Self {
        self.body = Some(s.into());
        self
    }
    /// Custom string data for the app.
    pub fn data(mut self, k: impl Into<String>, v: impl Into<String>) -> Self {
        self.data.insert(k.into(), v.into());
        self
    }
    /// App icon badge (APNs only).
    pub fn badge(mut self, n: u32) -> Self {
        self.badge = Some(n);
        self
    }
    /// Sound name (`"default"`).
    pub fn sound(mut self, s: impl Into<String>) -> Self {
        self.sound = Some(s.into());
        self
    }
    /// Newer messages with the same key replace older undelivered ones (max 64 bytes).
    pub fn collapse_key(mut self, s: impl Into<String>) -> Self {
        self.collapse_key = Some(s.into());
        self
    }
    /// How long the provider may hold the message for an offline device.
    pub fn ttl(mut self, d: Duration) -> Self {
        self.ttl = Some(d);
        self
    }
    /// Urgency (default High).
    pub fn priority(mut self, p: Priority) -> Self {
        self.priority = p;
        self
    }
    /// Silent/background push (wakes the app). Without title/body it carries no alert.
    pub fn content_available(mut self) -> Self {
        self.content_available = true;
        self
    }

    fn silent(&self) -> bool {
        self.title.is_none() && self.body.is_none()
    }

    fn validate(&self) -> Result<(), PushError> {
        let bad = |m: &str| Err(PushError::Payload(m.into()));
        if self.silent() && !self.content_available {
            return bad("a notification needs a title, a body or content_available");
        }
        if self.data.keys().any(|k| k.is_empty() || k == "aps") {
            return bad("data keys must be non-empty and not `aps`");
        }
        if self.collapse_key.as_ref().is_some_and(|c| c.len() > 64) {
            return bad("collapse_key is at most 64 bytes");
        }
        Ok(())
    }

    fn fcm_message(&self, token: &str) -> Value {
        let mut m = json!({ "token": token });
        if !self.data.is_empty() {
            m["data"] = json!(self.data);
        }
        if !self.silent() {
            let mut n = json!({});
            if let Some(t) = &self.title {
                n["title"] = json!(t);
            }
            if let Some(b) = &self.body {
                n["body"] = json!(b);
            }
            m["notification"] = n;
        }
        let high = self.priority == Priority::High || self.content_available;
        let mut a = json!({ "priority": if high { "HIGH" } else { "NORMAL" } });
        if let Some(t) = self.ttl {
            a["ttl"] = json!(format!("{}s", t.as_secs()));
        }
        if let Some(c) = &self.collapse_key {
            a["collapse_key"] = json!(c);
        }
        if let Some(s) = &self.sound {
            a["notification"] = json!({ "sound": s });
        }
        m["android"] = a;
        json!({ "message": m })
    }

    fn apns_body(&self) -> Value {
        let mut aps = json!({});
        if !self.silent() {
            let mut alert = json!({});
            if let Some(t) = &self.title {
                alert["title"] = json!(t);
            }
            if let Some(b) = &self.body {
                alert["body"] = json!(b);
            }
            aps["alert"] = alert;
        }
        if let Some(b) = self.badge {
            aps["badge"] = json!(b);
        }
        if let Some(s) = &self.sound {
            aps["sound"] = json!(s);
        }
        if self.content_available {
            aps["content-available"] = json!(1);
        }
        let mut v = json!({ "aps": aps });
        for (k, val) in &self.data {
            v[k] = json!(val);
        }
        v
    }
}

/// Result of one send to one device.
#[derive(Debug, Clone, PartialEq)]
pub enum Delivery {
    /// Accepted by the provider.
    Sent,
    /// The provider rejected the token; the device was marked invalid.
    Invalid,
    /// Still failing after the retries (reason without secrets).
    Transient(String),
}

/// Outcome of [`Push::send_to_user`]. `failed` includes transient and non-retryable errors.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct SendReport {
    /// Accepted by a provider (or logged by the log driver).
    pub sent: usize,
    /// Failed (transient, misconfigured platform, rejected payload).
    pub failed: usize,
    /// Tokens the provider rejected (now marked invalid).
    pub invalidated: usize,
}

// ---- shared HTTP plumbing -------------------------------------------------------------------

fn check_url(u: &str, what: &str, allow_http: bool) -> Result<(), PushError> {
    // Endpoint overrides are test-only; real builds must talk TLS.
    if allow_http || u.starts_with("https://") {
        Ok(())
    } else {
        Err(PushError::Config(format!("{what} must be an https:// URL")))
    }
}

fn http(prior_h2: bool) -> reqwest::Client {
    let mut b = reqwest::Client::builder()
        .timeout(TIMEOUT)
        .connect_timeout(TIMEOUT)
        .redirect(reqwest::redirect::Policy::none());
    if prior_h2 {
        b = b.http2_prior_knowledge();
    }
    b.build().expect("reqwest client")
}

fn truncate(s: &str) -> String {
    s.chars().take(200).collect()
}

enum Step {
    Done(Delivery),
    Retry(Option<Duration>, String),
    /// 401/403-expired: the credential cache was cleared; try once more at no cost.
    Reauth,
    Fail(PushError),
}

fn retry_after(r: &reqwest::Response) -> Option<Duration> {
    r.headers()
        .get("retry-after")?
        .to_str()
        .ok()?
        .trim()
        .parse::<u64>()
        .ok()
        .map(Duration::from_secs)
}

fn net_err(e: reqwest::Error) -> Step {
    // `without_url`: an APNs URL contains the device token.
    Step::Retry(None, format!("network: {}", e.without_url()))
}

async fn retrying<F, Fut>(base: Duration, mut attempt: F) -> Result<Delivery, PushError>
where
    F: FnMut() -> Fut,
    Fut: std::future::Future<Output = Step>,
{
    let (mut tries, mut reauthed) = (0u32, false);
    loop {
        match attempt().await {
            Step::Done(d) => return Ok(d),
            Step::Fail(e) => return Err(e),
            Step::Reauth if !reauthed => reauthed = true,
            Step::Reauth => {
                return Err(PushError::Provider {
                    status: 401,
                    detail: "credentials rejected after refresh".into(),
                });
            }
            Step::Retry(wait, why) => {
                tries += 1;
                if tries >= MAX_TRIES {
                    return Ok(Delivery::Transient(why));
                }
                let jitter = std::time::SystemTime::now()
                    .duration_since(std::time::UNIX_EPOCH)
                    .map(|d| d.subsec_nanos() % 250)
                    .unwrap_or(0) as u64;
                let backoff = base * 2u32.pow(tries - 1) + Duration::from_millis(jitter) / 10;
                let sleep = wait.map_or(backoff, |w| w.max(backoff));
                tokio::time::sleep(sleep.min(Duration::from_secs(30))).await;
            }
        }
    }
}

// ---- FCM --------------------------------------------------------------------------------------

/// FCM HTTP v1 provider (service-account OAuth2). `Debug` shows no key or token.
#[derive(Clone)]
pub struct Fcm {
    project_id: String,
    client_email: String,
    key: Arc<EncodingKey>,
    token_uri: String,
    endpoint: String,
    http: reqwest::Client,
    token: Arc<tokio::sync::Mutex<Option<(String, Instant)>>>,
    backoff: Duration,
}

impl std::fmt::Debug for Fcm {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Fcm")
            .field("project_id", &self.project_id)
            .field("client_email", &self.client_email)
            .finish_non_exhaustive()
    }
}

impl Fcm {
    /// From a service-account JSON (fields `client_email`, `private_key`, `token_uri`; `project_id`
    /// is used when `project_id` is empty). `token_uri` must be https.
    pub fn new(project_id: &str, service_account_json: &str) -> Result<Self, PushError> {
        #[derive(serde::Deserialize)]
        struct Sa {
            client_email: String,
            private_key: String,
            token_uri: String,
            #[serde(default)]
            project_id: String,
        }
        let sa: Sa = serde_json::from_str(service_account_json)
            .map_err(|_| PushError::Config("FCM service account JSON is invalid".into()))?;
        check_url(&sa.token_uri, "FCM token_uri", cfg!(test))?;
        let project_id = if project_id.is_empty() {
            sa.project_id
        } else {
            project_id.into()
        };
        if project_id.is_empty()
            || !project_id
                .chars()
                .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_' || c == ':' || c == '.')
        {
            return Err(PushError::Config(
                "FCM project id missing or invalid".into(),
            ));
        }
        let key = EncodingKey::from_rsa_pem(sa.private_key.as_bytes())
            .map_err(|_| PushError::Config("FCM private_key is not a valid RSA PEM".into()))?;
        Ok(Self {
            project_id,
            client_email: sa.client_email,
            key: Arc::new(key),
            token_uri: sa.token_uri,
            endpoint: "https://fcm.googleapis.com".into(),
            http: http(false),
            token: Default::default(),
            backoff: Duration::from_millis(500),
        })
    }

    #[cfg(test)]
    #[cfg_attr(not(feature = "sqlite"), allow(dead_code))] // only the sqlite-gated tests call it
    fn for_test(mut self, base: &str) -> Self {
        self.token_uri = format!("{base}/token");
        self.endpoint = base.into();
        self.backoff = Duration::from_millis(5);
        self
    }

    /// Cached access token; one request for any number of concurrent senders.
    async fn access_token(&self) -> Result<String, Step> {
        let mut g = self.token.lock().await;
        if let Some((t, exp)) = g.as_ref()
            && Instant::now() < *exp
        {
            return Ok(t.clone());
        }
        let iat = now();
        let claims = json!({
            "iss": self.client_email,
            "scope": "https://www.googleapis.com/auth/firebase.messaging",
            "aud": self.token_uri, "iat": iat, "exp": iat + 3600,
        });
        let jwt = jsonwebtoken::encode(&Header::new(Algorithm::RS256), &claims, &self.key)
            .map_err(|_| Step::Fail(PushError::Config("FCM JWT signing failed".into())))?;
        let r = self
            .http
            .post(&self.token_uri)
            .header("content-type", "application/x-www-form-urlencoded")
            .body(format!(
                "grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer&assertion={jwt}"
            ))
            .send()
            .await
            .map_err(net_err)?;
        let st = r.status();
        let ra = retry_after(&r);
        if !st.is_success() {
            let body = truncate(&r.text().await.unwrap_or_default());
            return Err(if st.as_u16() == 429 || st.is_server_error() {
                Step::Retry(ra, format!("FCM token endpoint {st}"))
            } else {
                Step::Fail(PushError::Provider {
                    status: st.as_u16(),
                    detail: format!("token endpoint: {body}"),
                })
            });
        }
        #[derive(serde::Deserialize)]
        struct Tok {
            access_token: String,
            #[serde(default = "d3600")]
            expires_in: u64,
        }
        fn d3600() -> u64 {
            3600
        }
        let t: Tok = r.json().await.map_err(|_| {
            Step::Fail(PushError::Provider {
                status: 200,
                detail: "token endpoint returned unexpected JSON".into(),
            })
        })?;
        // Valid until expiry - 60 s.
        let exp = Instant::now() + Duration::from_secs(t.expires_in.saturating_sub(60));
        *g = Some((t.access_token.clone(), exp));
        Ok(t.access_token)
    }

    async fn send(&self, token: &str, n: &Notification) -> Result<Delivery, PushError> {
        let body = serde_json::to_vec(&n.fcm_message(token)).expect("json");
        if body.len() > MAX_PAYLOAD {
            return Err(PushError::Payload("FCM payload exceeds 4096 bytes".into()));
        }
        let url = format!(
            "{}/v1/projects/{}/messages:send",
            self.endpoint, self.project_id
        );
        retrying(self.backoff, || async {
            let at = match self.access_token().await {
                Ok(t) => t,
                Err(s) => return s,
            };
            let r = match self
                .http
                .post(&url)
                .bearer_auth(at)
                .header("content-type", "application/json")
                .body(body.clone())
                .send()
                .await
            {
                Ok(r) => r,
                Err(e) => return net_err(e),
            };
            let st = r.status().as_u16();
            let ra = retry_after(&r);
            let text = r.text().await.unwrap_or_default();
            match st {
                200..=299 => Step::Done(Delivery::Sent),
                401 => {
                    *self.token.lock().await = None;
                    Step::Reauth
                }
                404 => Step::Done(Delivery::Invalid),
                400 if text.contains("INVALID_ARGUMENT")
                    && text.to_lowercase().contains("registration token") =>
                {
                    Step::Done(Delivery::Invalid)
                }
                429 | 500..=599 => Step::Retry(ra, format!("FCM answered {st}")),
                _ => Step::Fail(PushError::Provider {
                    status: st,
                    detail: truncate(&text),
                }),
            }
        })
        .await
    }
}

// ---- APNs -------------------------------------------------------------------------------------

/// APNs environment.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ApnsEnv {
    /// `api.push.apple.com`.
    Production,
    /// `api.sandbox.push.apple.com`.
    Sandbox,
}

/// APNs HTTP/2 provider (ES256 provider token). `Debug` shows no key or token.
#[derive(Clone)]
pub struct Apns {
    key: Arc<EncodingKey>,
    key_id: String,
    team_id: String,
    topic: String,
    base: String,
    http: reqwest::Client,
    jwt: Arc<std::sync::Mutex<Option<(String, Instant)>>>,
    jwt_ttl: Duration,
    backoff: Duration,
}

impl std::fmt::Debug for Apns {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Apns")
            .field("key_id", &self.key_id)
            .field("team_id", &self.team_id)
            .field("topic", &self.topic)
            .finish_non_exhaustive()
    }
}

impl Apns {
    /// `key_pem` is the `.p8` contents (PKCS#8 EC P-256); `topic` the bundle id.
    pub fn new(
        key_pem: &str,
        key_id: &str,
        team_id: &str,
        topic: &str,
        env: ApnsEnv,
    ) -> Result<Self, PushError> {
        if key_id.is_empty() || team_id.is_empty() || topic.is_empty() {
            return Err(PushError::Config(
                "APNs key id, team id and topic are required".into(),
            ));
        }
        let key = EncodingKey::from_ec_pem(key_pem.as_bytes())
            .map_err(|_| PushError::Config("APNS key is not a valid EC PEM (.p8)".into()))?;
        let base = match env {
            ApnsEnv::Production => "https://api.push.apple.com",
            ApnsEnv::Sandbox => "https://api.sandbox.push.apple.com",
        };
        Ok(Self {
            key: Arc::new(key),
            key_id: key_id.into(),
            team_id: team_id.into(),
            topic: topic.into(),
            base: base.into(),
            http: http(false),
            jwt: Default::default(),
            jwt_ttl: Duration::from_secs(50 * 60),
            backoff: Duration::from_millis(500),
        })
    }

    #[cfg(test)]
    #[cfg_attr(not(feature = "sqlite"), allow(dead_code))] // only the sqlite-gated tests call it
    fn for_test(mut self, base: &str) -> Self {
        check_url(base, "base", true).unwrap();
        self.base = base.into();
        self.http = http(base.starts_with("http://")); // cleartext h2 needs prior knowledge
        self.backoff = Duration::from_millis(5);
        self
    }

    fn provider_token(&self) -> Result<String, PushError> {
        let mut g = self.jwt.lock().unwrap();
        if let Some((t, exp)) = g.as_ref()
            && Instant::now() < *exp
        {
            return Ok(t.clone());
        }
        let mut h = Header::new(Algorithm::ES256);
        h.kid = Some(self.key_id.clone());
        let t = jsonwebtoken::encode(&h, &json!({"iss": self.team_id, "iat": now()}), &self.key)
            .map_err(|_| PushError::Config("APNs JWT signing failed".into()))?;
        *g = Some((t.clone(), Instant::now() + self.jwt_ttl));
        Ok(t)
    }

    async fn send(&self, token: &str, n: &Notification) -> Result<Delivery, PushError> {
        let body = serde_json::to_vec(&n.apns_body()).expect("json");
        if body.len() > MAX_PAYLOAD {
            return Err(PushError::Payload("APNs payload exceeds 4096 bytes".into()));
        }
        if token.is_empty() || !token.chars().all(|c| c.is_ascii_alphanumeric()) {
            return Ok(Delivery::Invalid);
        }
        let background = n.silent();
        let url = format!("{}/3/device/{token}", self.base);
        retrying(self.backoff, || async {
            let jwt = match self.provider_token() {
                Ok(j) => j,
                Err(e) => return Step::Fail(e),
            };
            let mut rb = self
                .http
                .post(&url)
                .header("authorization", format!("bearer {jwt}"))
                .header("apns-topic", &self.topic)
                .header(
                    "apns-push-type",
                    if background { "background" } else { "alert" },
                )
                .header(
                    "apns-priority",
                    if n.priority == Priority::High && !background {
                        "10"
                    } else {
                        "5"
                    },
                )
                .header("content-type", "application/json");
            if let Some(t) = n.ttl {
                rb = rb.header("apns-expiration", (now() + t.as_secs() as i64).to_string());
            }
            if let Some(c) = &n.collapse_key {
                rb = rb.header("apns-collapse-id", c);
            }
            let r = match rb.body(body.clone()).send().await {
                Ok(r) => r,
                Err(e) => return net_err(e),
            };
            let st = r.status().as_u16();
            let ra = retry_after(&r);
            let text = r.text().await.unwrap_or_default();
            let reason = serde_json::from_str::<Value>(&text)
                .ok()
                .and_then(|v| v["reason"].as_str().map(String::from))
                .unwrap_or_default();
            match (st, reason.as_str()) {
                (200..=299, _) => Step::Done(Delivery::Sent),
                (410, _) | (400, "BadDeviceToken" | "DeviceTokenNotForTopic") => {
                    Step::Done(Delivery::Invalid)
                }
                (403, "ExpiredProviderToken") => {
                    *self.jwt.lock().unwrap() = None;
                    Step::Reauth
                }
                (429, _) | (500..=599, _) => Step::Retry(ra, format!("APNs answered {st}")),
                _ => Step::Fail(PushError::Provider {
                    status: st,
                    detail: truncate(&text),
                }),
            }
        })
        .await
    }
}

// ---- Push service -----------------------------------------------------------------------------

struct Inner {
    devices: Devices,
    fcm: Option<Fcm>,
    apns: Option<Apns>,
    gate: tokio::sync::Semaphore,
}

/// The push service: registry + providers (or the log driver when none is configured).
#[derive(Clone)]
pub struct Push {
    inner: Arc<Inner>,
}

impl std::fmt::Debug for Push {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Push")
            .field("fcm", &self.inner.fcm)
            .field("apns", &self.inner.apns)
            .finish_non_exhaustive()
    }
}

impl Push {
    /// Log driver over `devices`; add providers with [`fcm`](Self::fcm) / [`apns`](Self::apns).
    pub fn new(devices: Devices) -> Self {
        Self {
            inner: Arc::new(Inner {
                devices,
                fcm: None,
                apns: None,
                gate: tokio::sync::Semaphore::new(MAX_CONCURRENCY),
            }),
        }
    }

    fn edit(mut self, f: impl FnOnce(&mut Inner)) -> Self {
        let i = Arc::get_mut(&mut self.inner).expect("configure Push before cloning it");
        f(i);
        self
    }

    /// Send Android devices through FCM.
    pub fn fcm(self, fcm: Fcm) -> Self {
        self.edit(|i| i.fcm = Some(fcm))
    }

    /// Send iOS devices through APNs.
    pub fn apns(self, apns: Apns) -> Self {
        self.edit(|i| i.apns = Some(apns))
    }

    /// The registry.
    pub fn devices(&self) -> &Devices {
        &self.inner.devices
    }

    /// Configure from the environment (see the module docs).
    pub async fn from_env(db: DatabaseConnection) -> Result<Self, PushError> {
        Self::from_lookup(db, |k| std::env::var(k).ok().filter(|v| !v.is_empty()))
    }

    fn from_lookup(
        db: DatabaseConnection,
        get: impl Fn(&str) -> Option<String>,
    ) -> Result<Self, PushError> {
        let mut p = Self::new(Devices::new(db));
        let driver = get("PUSH_DRIVER").unwrap_or_default();
        match driver.as_str() {
            "log" => return Ok(p),
            "" | "live" => {}
            other => return Err(PushError::Config(format!("unknown PUSH_DRIVER `{other}`"))),
        }
        let read = |inline: &str, path: &str| -> Result<Option<String>, PushError> {
            match (get(inline), get(path)) {
                (Some(v), _) => Ok(Some(v)),
                (None, Some(p)) => std::fs::read_to_string(&p)
                    .map(Some)
                    .map_err(|e| PushError::Config(format!("cannot read {path}: {}", e.kind()))),
                _ => Ok(None),
            }
        };
        if let Some(json) = read("FCM_SERVICE_ACCOUNT_JSON", "FCM_SERVICE_ACCOUNT_PATH")? {
            let fcm = Fcm::new(&get("FCM_PROJECT_ID").unwrap_or_default(), &json)?;
            p = p.fcm(fcm);
        }
        if let Some(key) = read("APNS_KEY", "APNS_KEY_PATH")? {
            let env = match get("APNS_ENV").as_deref() {
                None | Some("production") => ApnsEnv::Production,
                Some("sandbox") => ApnsEnv::Sandbox,
                Some(_) => return Err(PushError::Config("APNS_ENV is production|sandbox".into())),
            };
            let req = |k: &str| get(k).ok_or_else(|| PushError::Config(format!("{k} is required")));
            let apns = Apns::new(
                &key,
                &req("APNS_KEY_ID")?,
                &req("APNS_TEAM_ID")?,
                &req("APNS_TOPIC")?,
                env,
            )?;
            p = p.apns(apns);
        }
        if driver == "live" && p.inner.fcm.is_none() && p.inner.apns.is_none() {
            return Err(PushError::Config(
                "PUSH_DRIVER=live but neither FCM nor APNs is configured".into(),
            ));
        }
        Ok(p)
    }

    fn is_log(&self) -> bool {
        self.inner.fcm.is_none() && self.inner.apns.is_none()
    }

    /// Send to one device. A rejected token marks the device invalid. Errors: payload problems,
    /// a platform without provider, non-retryable provider answers.
    pub async fn send_to_device(
        &self,
        d: &Device,
        n: &Notification,
    ) -> Result<Delivery, PushError> {
        n.validate()?;
        let _permit = self.inner.gate.acquire().await.expect("semaphore open");
        let out = if self.is_log() {
            tracing::info!(
                platform = d.platform.as_str(), title = ?n.title, body = ?n.body, data = ?n.data,
                "push (log driver)"
            );
            Delivery::Sent
        } else {
            match (d.platform, &self.inner.fcm, &self.inner.apns) {
                (Platform::Android, Some(f), _) => f.send(&d.token, n).await?,
                (Platform::Ios, _, Some(a)) => a.send(&d.token, n).await?,
                _ => {
                    return Err(PushError::Config(format!(
                        "no provider configured for {}",
                        d.platform.as_str()
                    )));
                }
            }
        };
        if out == Delivery::Invalid {
            self.inner
                .devices
                .mark_invalid(d.platform, &d.token)
                .await?;
        }
        Ok(out)
    }

    /// Fan out to all of the user's valid devices (at most 16 in flight). One failing device never
    /// aborts the others; only a registry error or an invalid notification returns `Err`.
    pub async fn send_to_user(
        &self,
        user_id: i64,
        n: &Notification,
    ) -> Result<SendReport, PushError> {
        n.validate()?;
        let devices = self.inner.devices.valid_for_user(user_id).await?;
        if self.is_log() {
            tracing::info!(
                user_id,
                devices = devices.len(),
                "push (log driver) to user"
            );
        }
        let mut set = tokio::task::JoinSet::new();
        for d in devices {
            let (this, n) = (self.clone(), n.clone());
            set.spawn(async move { this.send_to_device(&d, &n).await });
        }
        let mut r = SendReport::default();
        while let Some(res) = set.join_next().await {
            match res {
                Ok(Ok(Delivery::Sent)) => r.sent += 1,
                Ok(Ok(Delivery::Invalid)) => r.invalidated += 1,
                Ok(Ok(Delivery::Transient(_))) | Err(_) => r.failed += 1,
                Ok(Err(e)) => {
                    tracing::warn!("push to one device failed: {e}");
                    r.failed += 1;
                }
            }
        }
        Ok(r)
    }
}

// Throwaway test keys below were generated for these tests only (`openssl genpkey`); they protect nothing.
#[cfg(all(test, feature = "sqlite"))]
mod tests {
    use super::*;
    use axum::body::to_bytes;
    use axum::extract::{Request, State};
    use axum::response::{IntoResponse, Response};
    use jsonwebtoken::{DecodingKey, Validation};
    use std::collections::{HashMap, VecDeque};
    use std::sync::Mutex;
    use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};

    const EC_PRIV: &str = r#"-----BEGIN PRIVATE KEY-----
MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgfp8BgpRhlPdNNJ1j
o00Lm4/eHWZAzQcVgXKXQlZ1doChRANCAAQATRjY6DtJ13iPJZPeO22NTgH60tez
t7q3SZMrvJ9KOrGcK5UL70eGwmM0OQDoYb3yFTeLclIvK966yP6Mf+Jl
-----END PRIVATE KEY-----
"#;
    const EC_PUB: &str = r#"-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEAE0Y2Og7Sdd4jyWT3jttjU4B+tLX
s7e6t0mTK7yfSjqxnCuVC+9HhsJjNDkA6GG98hU3i3JSLyveusj+jH/iZQ==
-----END PUBLIC KEY-----
"#;
    const RSA_PRIV: &str = r#"-----BEGIN PRIVATE KEY-----
MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCvxuXx65vYB39b
xUvAmcihrnWyMfI6n8b8NbhvgHILGsGvDo3FXWLKCjb5tggi/JQ/ZbBSU9n8ovQt
a8L4AVPKr4cj3+kceVCAPntPvz2+0usYOkiXLgfe4Evqv7TxowD9uxEyavq07nlf
pYSlErU3aYThxawe02hdAHl8EBGEkbkJZ+JnHA0YW7Z2568DhDW3exApm2atldtU
BntaZs1T7zWFwhXpihUAXirvQQudp/oEK9vThh6OB30LcOO2jrz+RwWFSOLEOo5A
0XWhEbhmpQlgSD06K9hBFYZJkHRqbcvuUtl9ZhqBDsxoaYN4q9vfd3FxeQoS0Dxd
By8Ew/HfAgMBAAECggEAEV5s1qX/3RhckCkOLlwOdFTPV3TSU9L5msQE01ZqA8k4
jeo5EwwCbia/6OvWS6gRTrRnIwjFwk4oekaAL6O977S+0fTW+CklTbl0KNyjpslO
UV4M/IygBXi8t60KyFJhj4YzvFDQMMmxtO704kosyEAae86zDna4Whw+ZNvCR2A5
mlHxL8Hdhl02US3UdY/8bKzMurGzQ4foTPF8+h1DHu01TQV7DqsyC8fgbY4663JG
pWmmaymppc6ftIghjdRmyANSrzRLdMQDk9lPnBaWBNm5pEKjj3mxzwKQzKHJ8eZm
k8TevpsIMQMxMXa1UpVK0REhhGtOOQViaYU60N6mfQKBgQDWQ74dJQhPH17TTe03
T/mbaIsdWZplaebSUfDgfZxICtOgf2gNQRwL9MuariR9Aordn8Xq9OnKmUsvTolH
nqB4straD2j9iVjCFpyTiRCV6P00q/gBRICJAewQI4kk5a8KCBEEJS+S5Ct3kGrk
JjjzJ/DWUHSb4qEeIFog+DrBCwKBgQDSA/nyakJJNPzIBqOvBgGoxUJ5dsVOq9lr
cpzim7ZvlqR9pV6cGtgSAbMCu+JDGaWH4LGO7k0uFf9LycJLjKZGffP1pnkRQlx7
waZhSLgpaVBDGn3SPAZ8CoYmn3kDfDgRThvWHcz9CHikBPPYYzgJi/87uV2q2YbN
RFOKxGe+/QKBgDJxbl+kKUmfZA6xKOi9vlD1EtNNFglMHlhjjCb9y342dk4x0IhW
TMkPz6NR3itEHvdANzMyh5v37PhtL+qZkMP5r4Zo3FncLPY8po4hVbNFT99HoTKD
MxOOTUobY505KbVd4susCYA2kXkrmc6upPex7oQ2Gs3cU/wot69NYV+zAoGAG73c
uXHh2au/LGj8HDWN6I5ODp9qxs6ahL/6C1EIU0sx5Ur/6Vz+Z7qDu/u3kqeDnyRG
MBw4Y7sSIx++o54rpKoknLFl0qrSbqKQ6M7jTM0VhheswSWesanuOJHeOWCiQ17u
/GSpXE9PKFNjJpVMpK4yg+AjiFr9nIXHB1CUZ70CgYApx2HeboWFCTcOnbelZmdp
qcNp8AiIMLlp/gwzfHOgl4BerGArCevLCsM1acZTtEum/fx0ruRhTR43VYYuVCOj
GlM8ujpx6MX6gtf/8VTnGco6YJVIN+BnjprldewInMG+c+2OyD84vOuyGKAbz9WJ
cgPW3vRe37myhhfdirH4Rw==
-----END PRIVATE KEY-----
"#;
    const RSA_PUB: &str = r#"-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAr8bl8eub2Ad/W8VLwJnI
oa51sjHyOp/G/DW4b4ByCxrBrw6NxV1iygo2+bYIIvyUP2WwUlPZ/KL0LWvC+AFT
yq+HI9/pHHlQgD57T789vtLrGDpIly4H3uBL6r+08aMA/bsRMmr6tO55X6WEpRK1
N2mE4cWsHtNoXQB5fBARhJG5CWfiZxwNGFu2duevA4Q1t3sQKZtmrZXbVAZ7WmbN
U+81hcIV6YoVAF4q70ELnaf6BCvb04Yejgd9C3Djto68/kcFhUjixDqOQNF1oRG4
ZqUJYEg9OivYQRWGSZB0am3L7lLZfWYagQ7MaGmDeKvb33dxcXkKEtA8XQcvBMPx
3wIDAQAB
-----END PUBLIC KEY-----
"#;

    fn uniq() -> i64 {
        static N: AtomicUsize = AtomicUsize::new(0);
        let ns = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos() as i64;
        (ns % 1_000_000_000_000) * 100 + N.fetch_add(1, Ordering::SeqCst) as i64
    }
    fn tok(prefix: &str) -> String {
        format!("{prefix}{:x}", uniq())
    }

    async fn sqlite() -> DatabaseConnection {
        let path = std::env::temp_dir().join(format!("ryuk-push-{}.db", uniq()));
        let db = sea_orm::Database::connect(format!("sqlite://{}?mode=rwc", path.display()))
            .await
            .unwrap();
        Devices::new(db.clone()).ensure_tables().await.unwrap();
        db
    }

    async fn dbs() -> Vec<(&'static str, DatabaseConnection)> {
        let mut v = vec![("sqlite", sqlite().await)];
        for (name, var) in [
            ("postgres", "TEST_POSTGRES_URL"),
            ("mysql", "TEST_MYSQL_URL"),
        ] {
            if let Ok(url) = std::env::var(var) {
                let db = sea_orm::Database::connect(url).await.unwrap();
                Devices::new(db.clone()).ensure_tables().await.unwrap();
                v.push((name, db));
            }
        }
        v
    }

    #[test]
    fn sha256_known_vectors() {
        assert_eq!(
            sha256_hex(b"abc"),
            "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
        );
        assert_eq!(
            sha256_hex(&[b'a'; 1000]),
            "41edece42d63e8d9bf515a9ba6932e1c20cbc9f5a5d134645adb5db1b9737ea3"
        );
    }

    #[tokio::test]
    async fn the_21st_device_evicts_the_least_recently_seen() {
        for (name, db) in dbs().await {
            let d = Devices::new(db.clone());
            let u = uniq();
            let mut ids = vec![];
            for i in 0..MAX_DEVICES_PER_USER {
                let r = d
                    .register(u, Platform::Android, &tok(&format!("c{i}")), None, None)
                    .await
                    .unwrap();
                // device 5 is the stalest, the rest are recent
                let seen = if i == 5 { 1 } else { 1000 + i as i64 };
                Entity::update_many()
                    .col_expr(Column::LastSeenAt, Expr::value(seen))
                    .filter(Column::Id.eq(r.id))
                    .exec(&db)
                    .await
                    .unwrap();
                ids.push(r.id);
            }
            assert_eq!(d.list(u).await.unwrap().len(), 20, "{name}");
            let new = d
                .register(u, Platform::Android, &tok("c-new"), None, None)
                .await
                .unwrap();
            let left: Vec<i64> = d.list(u).await.unwrap().iter().map(|x| x.id).collect();
            assert_eq!(left.len(), 20, "{name}");
            assert!(!left.contains(&ids[5]) && left.contains(&new.id), "{name}");
            // a lower cap applies on the next register, never evicting the new device
            let d2 = Devices::new(db.clone()).max_per_user(3);
            let n2 = d2
                .register(u, Platform::Android, &tok("c-new2"), None, None)
                .await
                .unwrap();
            let left: Vec<i64> = d2.list(u).await.unwrap().iter().map(|x| x.id).collect();
            assert_eq!(left.len(), 3, "{name}");
            assert!(left.contains(&n2.id), "{name}");
            // concurrent registers: the next one trims back to the cap
            let u = uniq();
            let hs: Vec<_> = (0..30)
                .map(|i| {
                    let d = d.clone();
                    tokio::spawn(async move {
                        d.register(u, Platform::Android, &tok(&format!("k{i}")), None, None)
                            .await
                            .unwrap()
                    })
                })
                .collect();
            for h in hs {
                h.await.unwrap();
            }
            d.register(u, Platform::Android, &tok("k-last"), None, None)
                .await
                .unwrap();
            assert_eq!(d.list(u).await.unwrap().len(), 20, "{name}");
        }
    }

    #[tokio::test]
    async fn registry_semantics_on_every_backend() {
        for (name, db) in dbs().await {
            let d = Devices::new(db);
            let (u1, u2) = (uniq(), uniq());
            let t = tok("tok");
            let a = d
                .register(u1, Platform::Android, &t, Some("com.acme"), Some("Pixel"))
                .await
                .unwrap_or_else(|e| panic!("{name}: {e}"));
            assert_eq!((a.user_id, a.invalid_at), (u1, None));
            // same token for another user: moves, same row, still one device
            let b = d
                .register(u2, Platform::Android, &t, None, None)
                .await
                .unwrap();
            assert_eq!((b.id, b.user_id), (a.id, u2), "{name}");
            assert!(d.list(u1).await.unwrap().is_empty());
            // same token string on the other platform is a different device
            let ios = d.register(u2, Platform::Ios, &t, None, None).await.unwrap();
            assert_ne!(ios.id, a.id);
            // invalid -> not sendable; re-register clears
            d.mark_invalid(Platform::Android, &t).await.unwrap();
            assert_eq!(d.valid_for_user(u2).await.unwrap().len(), 1, "{name}");
            assert!(
                d.list(u2)
                    .await
                    .unwrap()
                    .iter()
                    .any(|i| i.invalid_at.is_some())
            );
            d.register(u2, Platform::Android, &t, None, None)
                .await
                .unwrap();
            assert_eq!(d.valid_for_user(u2).await.unwrap().len(), 2);
            // owner check
            assert!(!d.unregister(u1, a.id).await.unwrap());
            assert!(d.unregister(u2, a.id).await.unwrap());
            assert!(!d.unregister(u2, a.id).await.unwrap());
            // prune: invalid long ago + idle long ago (zero durations match "everything older than now")
            let t2 = tok("old");
            d.register(u1, Platform::Android, &t2, None, None)
                .await
                .unwrap();
            d.mark_invalid(Platform::Android, &t2).await.unwrap();
            tokio::time::sleep(Duration::from_millis(1100)).await;
            d.prune(Duration::ZERO, Duration::from_secs(86400))
                .await
                .unwrap();
            assert!(
                d.list(u1).await.unwrap().is_empty(),
                "{name}: invalid pruned"
            );
            assert_eq!(d.list(u2).await.unwrap().len(), 1, "{name}: fresh kept");
        }
    }

    #[tokio::test]
    async fn registry_validation_and_redaction() {
        let d = Devices::new(sqlite().await);
        let u = uniq();
        for (p, t, n) in [
            (Platform::Android, "short", None),
            (Platform::Android, "has space inside", None),
            (Platform::Ios, "not-hex-token-1234", None),
            (Platform::Android, "validtoken123", Some("x".repeat(101))),
        ] {
            assert!(
                matches!(
                    d.register(u, p, t, None, n.as_deref()).await,
                    Err(PushError::Invalid(_))
                ),
                "{t}"
            );
        }
        assert!(
            d.register(u, Platform::Android, &"a".repeat(4097), None, None)
                .await
                .is_err()
        );
        d.register(u, Platform::Android, &"a".repeat(4096), None, None)
            .await
            .unwrap();
        let t = tok("secrettoken");
        d.register(u, Platform::Android, &t, None, None)
            .await
            .unwrap();
        let dev = d.valid_for_user(u).await.unwrap().remove(0);
        let shown = format!("{dev:?} {:?}", d.list(u).await.unwrap());
        assert!(!shown.contains("aaaaaaaa") && !shown.contains(&t));
        let m = push_devices::Model {
            id: 1,
            user_id: 1,
            platform: "ios".into(),
            token: t.clone(),
            token_hash: "h".into(),
            app_id: None,
            name: None,
            created_at: 0,
            last_seen_at: 0,
            invalid_at: None,
        };
        assert!(!format!("{m:?}").contains(&t));
    }

    #[test]
    fn ddl_indexes_the_hash_not_the_token() {
        let my = Schema::new(DbBackend::MySql).create_table_with_index_from_entity(Entity);
        let sql = DbBackend::MySql.build(&my).to_string();
        assert!(sql.contains("`token` text NOT NULL"), "{sql}");
        assert!(
            sql.contains("UNIQUE") && sql.contains("`token_hash`"),
            "{sql}"
        );
        assert!(!sql.contains("(`token`)"));
    }

    #[test]
    fn payload_shapes_and_validation() {
        let n = Notification::new()
            .title("T")
            .body("B")
            .data("k", "v")
            .badge(3)
            .sound("default")
            .collapse_key("c")
            .ttl(Duration::from_secs(60))
            .priority(Priority::Normal);
        let a = n.apns_body();
        assert_eq!(a["aps"]["alert"], json!({"title":"T","body":"B"}));
        assert_eq!(
            (a["aps"]["badge"].clone(), a["k"].clone()),
            (json!(3), json!("v"))
        );
        let f = n.fcm_message("tk");
        assert_eq!(f["message"]["token"], "tk");
        assert_eq!(f["message"]["android"]["priority"], "NORMAL");
        assert_eq!(f["message"]["android"]["ttl"], "60s");
        assert_eq!(f["message"]["data"]["k"], "v");
        assert!(Notification::new().validate().is_err());
        assert!(
            Notification::new()
                .title("t")
                .data("aps", "x")
                .validate()
                .is_err()
        );
        assert!(Notification::new().content_available().validate().is_ok());
        assert!(
            Notification::new().content_available().apns_body()["aps"]
                .get("alert")
                .is_none()
        );
    }

    // ---- mock providers ----

    #[derive(Clone)]
    struct R(u16, Option<&'static str>, &'static str);
    struct Rec {
        path: String,
        headers: HashMap<String, String>,
        body: String,
        version: axum::http::Version,
    }
    #[derive(Default)]
    struct Mock {
        recs: Mutex<Vec<Rec>>,
        queue: Mutex<VecDeque<R>>,
        by_token: Mutex<HashMap<String, R>>,
        tokens: AtomicUsize,
        expires_in: AtomicU64,
    }
    impl Mock {
        fn pushes(&self) -> Vec<(String, HashMap<String, String>, String)> {
            self.recs
                .lock()
                .unwrap()
                .iter()
                .filter(|r| r.path != "/token")
                .map(|r| (r.path.clone(), r.headers.clone(), r.body.clone()))
                .collect()
        }
        fn script(&self, r: &[R]) {
            self.queue.lock().unwrap().extend(r.iter().cloned());
        }
    }

    async fn mock_handler(State(m): State<Arc<Mock>>, req: Request) -> Response {
        let (p, b) = req.into_parts();
        let body = String::from_utf8(to_bytes(b, 1 << 20).await.unwrap().to_vec()).unwrap();
        let path = p.uri.path().to_string();
        let headers = p
            .headers
            .iter()
            .map(|(k, v)| (k.to_string(), v.to_str().unwrap().to_string()))
            .collect();
        m.recs.lock().unwrap().push(Rec {
            path: path.clone(),
            headers,
            body: body.clone(),
            version: p.version,
        });
        if path == "/token" {
            let n = m.tokens.fetch_add(1, Ordering::SeqCst) + 1;
            return axum::Json(json!({"access_token": format!("at-{n}"), "expires_in": m.expires_in.load(Ordering::SeqCst)})).into_response();
        }
        let hay = format!("{path} {body}");
        let by = m
            .by_token
            .lock()
            .unwrap()
            .iter()
            .find(|(k, _)| hay.contains(k.as_str()))
            .map(|(_, r)| r.clone());
        let R(st, ra, text) = by
            .or_else(|| m.queue.lock().unwrap().pop_front())
            .unwrap_or(R(200, None, "{}"));
        let mut resp = (axum::http::StatusCode::from_u16(st).unwrap(), text).into_response();
        if let Some(ra) = ra {
            resp.headers_mut()
                .insert("retry-after", ra.parse().unwrap());
        }
        resp
    }

    /// Plain axum::serve: hyper-util's auto builder also accepts HTTP/2 prior knowledge (cleartext h2).
    async fn start() -> (String, Arc<Mock>) {
        let m = Arc::new(Mock::default());
        m.expires_in.store(3600, Ordering::SeqCst);
        let app = axum::Router::new()
            .fallback(mock_handler)
            .with_state(m.clone());
        let l = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let base = format!("http://{}", l.local_addr().unwrap());
        tokio::spawn(async move { axum::serve(l, app).await.unwrap() });
        (base, m)
    }

    fn sa_json() -> String {
        json!({"type":"service_account","project_id":"proj-1","client_email":"svc@proj-1.iam.test",
            "private_key": RSA_PRIV, "token_uri": "https://oauth2.example/token"})
        .to_string()
    }
    fn fcm(base: &str) -> Fcm {
        Fcm::new("", &sa_json()).unwrap().for_test(base)
    }
    fn apns(base: &str) -> Apns {
        Apns::new(
            EC_PRIV,
            "KEY123",
            "TEAM456",
            "com.acme.app",
            ApnsEnv::Sandbox,
        )
        .unwrap()
        .for_test(base)
    }
    fn dev(p: Platform, token: &str) -> Device {
        Device {
            id: 0,
            user_id: 0,
            platform: p,
            token: token.into(),
            app_id: None,
        }
    }
    async fn svc(db: DatabaseConnection, f: Option<Fcm>, a: Option<Apns>) -> Push {
        let mut p = Push::new(Devices::new(db));
        if let Some(f) = f {
            p = p.fcm(f);
        }
        if let Some(a) = a {
            p = p.apns(a);
        }
        p
    }

    fn verify(jwt: &str, pubkey: &str, alg: Algorithm) -> (Header, Value) {
        let mut v = Validation::new(alg);
        v.validate_exp = false;
        v.validate_aud = false;
        v.required_spec_claims.clear();
        let key = if alg == Algorithm::RS256 {
            DecodingKey::from_rsa_pem(pubkey.as_bytes())
        } else {
            DecodingKey::from_ec_pem(pubkey.as_bytes())
        }
        .unwrap();
        let d =
            jsonwebtoken::decode::<Value>(jwt, &key, &v).expect("JWT verifies with the public key");
        (d.header, d.claims)
    }

    #[tokio::test]
    async fn fcm_request_shape_jwt_and_token_cache() {
        let (base, m) = start().await;
        let p = svc(sqlite().await, Some(fcm(&base)), None).await;
        let n = Notification::new()
            .title("Hi")
            .body("There")
            .data("a", "b")
            .collapse_key("c")
            .sound("default");
        let ts: Vec<_> = (0..6).map(|_| tok("fcmtok")).collect();
        let mut set = tokio::task::JoinSet::new();
        for t in &ts {
            let (p, n, d) = (p.clone(), n.clone(), dev(Platform::Android, t));
            set.spawn(async move { p.send_to_device(&d, &n).await.unwrap() });
        }
        while let Some(r) = set.join_next().await {
            assert_eq!(r.unwrap(), Delivery::Sent);
        }
        assert_eq!(
            m.tokens.load(Ordering::SeqCst),
            1,
            "one token request for 6 sends"
        );
        let recs = m.recs.lock().unwrap();
        let tr = recs.iter().find(|r| r.path == "/token").unwrap();
        assert_eq!(
            tr.headers["content-type"],
            "application/x-www-form-urlencoded"
        );
        let jwt = tr.body.split("assertion=").nth(1).unwrap();
        assert!(
            tr.body
                .starts_with("grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer&")
        );
        let (h, c) = verify(jwt, RSA_PUB, Algorithm::RS256);
        assert_eq!(h.alg, Algorithm::RS256);
        assert_eq!(c["iss"], "svc@proj-1.iam.test");
        assert_eq!(
            c["scope"],
            "https://www.googleapis.com/auth/firebase.messaging"
        );
        assert_eq!(c["aud"], format!("{base}/token"));
        assert_eq!(
            c["exp"].as_i64().unwrap() - c["iat"].as_i64().unwrap(),
            3600
        );
        let send = recs.iter().find(|r| r.path != "/token").unwrap();
        assert_eq!(send.path, "/v1/projects/proj-1/messages:send");
        assert_eq!(send.headers["authorization"], "Bearer at-1");
        let b: Value = serde_json::from_str(&send.body).unwrap();
        assert_eq!(
            b["message"]["notification"],
            json!({"title":"Hi","body":"There"})
        );
        assert_eq!(b["message"]["data"], json!({"a":"b"}));
        assert_eq!(b["message"]["android"]["collapse_key"], "c");
        assert_eq!(b["message"]["android"]["notification"]["sound"], "default");
        assert!(ts.iter().any(|t| b["message"]["token"] == *t));
    }

    #[tokio::test]
    async fn fcm_token_refreshes_on_expiry_and_on_401() {
        let (base, m) = start().await;
        let p = svc(sqlite().await, Some(fcm(&base)), None).await;
        let (n, d) = (
            Notification::new().title("t"),
            dev(Platform::Android, &tok("fcm")),
        );
        m.expires_in.store(60, Ordering::SeqCst); // expiry - 60 s = already stale
        p.send_to_device(&d, &n).await.unwrap();
        p.send_to_device(&d, &n).await.unwrap();
        assert_eq!(m.tokens.load(Ordering::SeqCst), 2);
        m.expires_in.store(3600, Ordering::SeqCst);
        p.send_to_device(&d, &n).await.unwrap(); // fetches 3 (cached stale one expired)
        m.script(&[R(401, None, "{}")]);
        assert_eq!(p.send_to_device(&d, &n).await.unwrap(), Delivery::Sent);
        let auth: Vec<_> = m
            .pushes()
            .iter()
            .map(|x| x.1["authorization"].clone())
            .collect();
        assert_eq!(
            auth[auth.len() - 2..],
            ["Bearer at-3", "Bearer at-4"],
            "{auth:?}"
        );
        assert_eq!(m.tokens.load(Ordering::SeqCst), 4);
    }

    #[tokio::test]
    async fn fcm_outcomes_invalid_retry_and_fatal() {
        let (base, m) = start().await;
        let db = sqlite().await;
        let p = svc(db.clone(), Some(fcm(&base)), None).await;
        let n = Notification::new().title("t");
        let u = uniq();
        let (t404, t400, tbad) = (tok("gone"), tok("badarg"), tok("payload"));
        for t in [&t404, &t400, &tbad] {
            p.devices()
                .register(u, Platform::Android, t, None, None)
                .await
                .unwrap();
        }
        m.by_token.lock().unwrap().extend([
            (t404.clone(), R(404, None, r#"{"error":{"status":"NOT_FOUND","details":[{"errorCode":"UNREGISTERED"}]}}"#)),
            (t400.clone(), R(400, None, r#"{"error":{"status":"INVALID_ARGUMENT","message":"The registration token is not a valid FCM registration token"}}"#)),
            (tbad.clone(), R(400, None, r#"{"error":{"status":"INVALID_ARGUMENT","message":"Invalid JSON payload"}}"#)),
        ]);
        let before = m.pushes().len();
        assert_eq!(
            p.send_to_device(&dev(Platform::Android, &t404), &n)
                .await
                .unwrap(),
            Delivery::Invalid
        );
        assert_eq!(
            p.send_to_device(&dev(Platform::Android, &t400), &n)
                .await
                .unwrap(),
            Delivery::Invalid
        );
        assert_eq!(
            m.pushes().len() - before,
            2,
            "invalid tokens are not retried"
        );
        assert!(matches!(
            p.send_to_device(&dev(Platform::Android, &tbad), &n).await,
            Err(PushError::Provider { status: 400, .. })
        ));
        assert_eq!(
            p.devices().valid_for_user(u).await.unwrap().len(),
            1,
            "only the payload-rejected one stays"
        );
        // 503, 503, 200
        let d = dev(Platform::Android, &tok("retry"));
        let before = m.pushes().len();
        m.script(&[R(503, None, "x"), R(503, None, "x")]);
        assert_eq!(p.send_to_device(&d, &n).await.unwrap(), Delivery::Sent);
        assert_eq!(m.pushes().len() - before, 3);
        // always 503 -> Transient after exactly 3 tries
        let before = m.pushes().len();
        m.script(&[R(503, None, "x"), R(500, None, "x"), R(503, None, "x")]);
        assert!(matches!(
            p.send_to_device(&d, &n).await.unwrap(),
            Delivery::Transient(_)
        ));
        assert_eq!(m.pushes().len() - before, 3);
    }

    #[tokio::test]
    async fn retry_after_is_honored() {
        let (base, m) = start().await;
        let p = svc(sqlite().await, Some(fcm(&base)), None).await;
        let d = dev(Platform::Android, &tok("ra"));
        m.script(&[R(429, Some("1"), "slow down")]);
        let t = Instant::now();
        assert_eq!(
            p.send_to_device(&d, &Notification::new().title("t"))
                .await
                .unwrap(),
            Delivery::Sent
        );
        assert!(
            t.elapsed() >= Duration::from_millis(990),
            "{:?}",
            t.elapsed()
        );
    }

    #[tokio::test]
    async fn apns_http2_request_shape_and_jwt() {
        let (base, m) = start().await;
        let p = svc(sqlite().await, None, Some(apns(&base))).await;
        let t = tok("abcdef");
        let n = Notification::new()
            .title("Hi")
            .body("Yo")
            .badge(2)
            .sound("default")
            .data("order", "42")
            .collapse_key("col")
            .ttl(Duration::from_secs(120));
        assert_eq!(
            p.send_to_device(&dev(Platform::Ios, &t), &n).await.unwrap(),
            Delivery::Sent
        );
        let recs = m.recs.lock().unwrap();
        let r = &recs[0];
        assert_eq!(
            r.version,
            axum::http::Version::HTTP_2,
            "cleartext HTTP/2 was spoken"
        );
        assert_eq!(r.path, format!("/3/device/{t}"));
        let h = &r.headers;
        assert_eq!(h["apns-topic"], "com.acme.app");
        assert_eq!(h["apns-push-type"], "alert");
        assert_eq!(h["apns-priority"], "10");
        assert_eq!(h["apns-collapse-id"], "col");
        let exp: i64 = h["apns-expiration"].parse().unwrap();
        assert!((exp - now() - 120).abs() <= 5);
        let jwt = h["authorization"].strip_prefix("bearer ").unwrap();
        let (hd, c) = verify(jwt, EC_PUB, Algorithm::ES256);
        assert_eq!(hd.kid.as_deref(), Some("KEY123"));
        assert_eq!(c["iss"], "TEAM456");
        assert!((c["iat"].as_i64().unwrap() - now()).abs() <= 5);
        let b: Value = serde_json::from_str(&r.body).unwrap();
        assert_eq!(
            b,
            json!({"aps":{"alert":{"title":"Hi","body":"Yo"},"badge":2,"sound":"default"},"order":"42"})
        );
    }

    #[tokio::test]
    async fn apns_silent_push_and_priorities() {
        let (base, m) = start().await;
        let p = svc(sqlite().await, None, Some(apns(&base))).await;
        let d = dev(Platform::Ios, &tok("abc"));
        p.send_to_device(
            &d,
            &Notification::new().content_available().data("sync", "1"),
        )
        .await
        .unwrap();
        p.send_to_device(
            &d,
            &Notification::new().title("t").priority(Priority::Normal),
        )
        .await
        .unwrap();
        let ps = m.pushes();
        assert_eq!(ps[0].1["apns-push-type"], "background");
        assert_eq!(ps[0].1["apns-priority"], "5");
        assert_eq!(
            serde_json::from_str::<Value>(&ps[0].2).unwrap(),
            json!({"aps":{"content-available":1},"sync":"1"})
        );
        assert_eq!(ps[1].1["apns-priority"], "5");
        assert!(!ps[1].1.contains_key("apns-expiration"));
    }

    #[tokio::test]
    async fn apns_jwt_cached_then_refreshed_on_expiry_and_403() {
        let (base, m) = start().await;
        let a = apns(&base);
        let p = svc(sqlite().await, None, Some(a)).await;
        let (d, n) = (
            dev(Platform::Ios, &tok("abc")),
            Notification::new().title("t"),
        );
        let jwts = |m: &Mock| -> Vec<String> {
            m.pushes()
                .iter()
                .map(|x| x.1["authorization"].clone())
                .collect()
        };
        for _ in 0..3 {
            p.send_to_device(&d, &n).await.unwrap();
        }
        let j = jwts(&m);
        assert!(j.iter().all(|x| *x == j[0]), "one provider token reused");
        // iat has second resolution: wait so a new token differs
        tokio::time::sleep(Duration::from_millis(1100)).await;
        m.script(&[R(403, None, r#"{"reason":"ExpiredProviderToken"}"#)]);
        assert_eq!(p.send_to_device(&d, &n).await.unwrap(), Delivery::Sent);
        let j = jwts(&m);
        assert_eq!(j.len(), 5);
        assert_eq!(j[3], j[0], "the rejected request used the cached token");
        assert_ne!(j[4], j[3], "token was regenerated after 403");
        // other 403 is fatal, not retried
        m.script(&[R(403, None, r#"{"reason":"InvalidProviderToken"}"#)]);
        assert!(matches!(
            p.send_to_device(&d, &n).await,
            Err(PushError::Provider { status: 403, .. })
        ));
        assert_eq!(m.pushes().len(), 6);
        // time-based refresh
        let mut a2 = apns(&base);
        a2.jwt_ttl = Duration::ZERO;
        let p2 = svc(sqlite().await, None, Some(a2)).await;
        let before = m.pushes().len();
        tokio::time::sleep(Duration::from_millis(1100)).await;
        p2.send_to_device(&d, &n).await.unwrap();
        p2.send_to_device(&d, &n).await.unwrap();
        let j = jwts(&m);
        assert_ne!(j[before], j[before + 1]);
    }

    #[tokio::test]
    async fn apns_invalid_tokens_are_flagged() {
        let (base, m) = start().await;
        let db = sqlite().await;
        let p = svc(db, None, Some(apns(&base))).await;
        let u = uniq();
        let (a, b, c) = (tok("aa"), tok("bb"), tok("cc"));
        for t in [&a, &b, &c] {
            p.devices()
                .register(u, Platform::Ios, t, None, None)
                .await
                .unwrap();
        }
        m.by_token.lock().unwrap().extend([
            (a.clone(), R(410, None, r#"{"reason":"Unregistered"}"#)),
            (b.clone(), R(400, None, r#"{"reason":"BadDeviceToken"}"#)),
        ]);
        let r = p
            .send_to_user(u, &Notification::new().title("t"))
            .await
            .unwrap();
        assert_eq!(
            r,
            SendReport {
                sent: 1,
                failed: 0,
                invalidated: 2
            }
        );
        assert_eq!(p.devices().valid_for_user(u).await.unwrap().len(), 1);
        // second round only reaches the good device
        let r = p
            .send_to_user(u, &Notification::new().title("t"))
            .await
            .unwrap();
        assert_eq!(
            r,
            SendReport {
                sent: 1,
                failed: 0,
                invalidated: 0
            }
        );
    }

    #[tokio::test]
    async fn one_bad_device_does_not_stop_the_others() {
        let (base, m) = start().await;
        let p = svc(sqlite().await, Some(fcm(&base)), Some(apns(&base))).await;
        let u = uniq();
        let (good_a, flaky, gone, good_i) = (tok("ga"), tok("flaky"), tok("gone"), tok("1a"));
        for t in [&good_a, &flaky, &gone] {
            p.devices()
                .register(u, Platform::Android, t, None, None)
                .await
                .unwrap();
        }
        p.devices()
            .register(u, Platform::Ios, &good_i, None, None)
            .await
            .unwrap();
        m.by_token.lock().unwrap().extend([
            (flaky.clone(), R(503, None, "x")),
            (gone.clone(), R(404, None, "{}")),
        ]);
        let r = p
            .send_to_user(u, &Notification::new().title("t"))
            .await
            .unwrap();
        assert_eq!(
            r,
            SendReport {
                sent: 2,
                failed: 1,
                invalidated: 1
            }
        );
    }

    #[tokio::test]
    async fn missing_provider_is_a_failure_not_a_panic() {
        let (base, _m) = start().await;
        let p = svc(sqlite().await, Some(fcm(&base)), None).await;
        let u = uniq();
        p.devices()
            .register(u, Platform::Ios, &tok("ab"), None, None)
            .await
            .unwrap();
        let r = p
            .send_to_user(u, &Notification::new().title("t"))
            .await
            .unwrap();
        assert_eq!(
            r,
            SendReport {
                sent: 0,
                failed: 1,
                invalidated: 0
            }
        );
    }

    #[tokio::test]
    async fn oversize_payload_is_rejected_before_sending() {
        let (base, m) = start().await;
        let p = svc(sqlite().await, Some(fcm(&base)), Some(apns(&base))).await;
        let big = Notification::new().title("t").data("k", "x".repeat(5000));
        for d in [
            dev(Platform::Android, &tok("big")),
            dev(Platform::Ios, &tok("ab")),
        ] {
            assert!(matches!(
                p.send_to_device(&d, &big).await,
                Err(PushError::Payload(_))
            ));
        }
        assert!(m.recs.lock().unwrap().is_empty());
    }

    #[test]
    fn config_validation_and_debug_redaction() {
        let rsa_marker = RSA_PRIV.lines().nth(2).unwrap();
        let f = Fcm::new("", &sa_json()).unwrap();
        let a = Apns::new(EC_PRIV, "K", "T", "com.x", ApnsEnv::Production).unwrap();
        let shown = format!("{f:?} {a:?}");
        assert!(!shown.contains(rsa_marker) && !shown.contains(EC_PRIV.lines().nth(1).unwrap()));
        assert!(shown.contains("svc@proj-1.iam.test"));
        assert!(Fcm::new("", "{").is_err());
        assert!(Fcm::new("bad/id", &sa_json()).is_err());
        assert!(Apns::new("not a key", "K", "T", "t", ApnsEnv::Production).is_err());
        assert!(Apns::new(EC_PRIV, "", "T", "t", ApnsEnv::Production).is_err());
        assert_eq!(a.base, "https://api.push.apple.com");
        assert!(
            check_url("http://x", "u", false).is_err()
                && check_url("https://x", "u", false).is_ok()
        );
    }

    #[tokio::test]
    async fn from_env_lookup() {
        let db = sqlite().await;
        let env = |pairs: &[(&str, String)]| {
            let m: HashMap<String, String> = pairs
                .iter()
                .map(|(k, v)| (ToString::to_string(&k), v.clone()))
                .collect();
            Push::from_lookup(db.clone(), move |k| m.get(k).cloned())
        };
        assert!(env(&[]).unwrap().is_log());
        assert!(
            env(&[
                ("PUSH_DRIVER", "log".into()),
                ("APNS_KEY", "garbage".into())
            ])
            .unwrap()
            .is_log()
        );
        assert!(env(&[("PUSH_DRIVER", "live".into())]).is_err());
        assert!(env(&[("PUSH_DRIVER", "nope".into())]).is_err());
        let p = env(&[("FCM_SERVICE_ACCOUNT_JSON", sa_json())]).unwrap();
        assert!(!p.is_log() && p.inner.apns.is_none());
        assert!(
            env(&[("APNS_KEY", EC_PRIV.into())]).is_err(),
            "key id etc. required"
        );
        let p = env(&[
            ("APNS_KEY", EC_PRIV.into()),
            ("APNS_KEY_ID", "K".into()),
            ("APNS_TEAM_ID", "T".into()),
            ("APNS_TOPIC", "com.x".into()),
            ("APNS_ENV", "sandbox".into()),
        ])
        .unwrap();
        assert_eq!(
            p.inner.apns.as_ref().unwrap().base,
            "https://api.sandbox.push.apple.com"
        );
        // token_uri must be https outside tests: exercised through check_url's rule
        assert!(env(&[("FCM_SERVICE_ACCOUNT_PATH", "/nonexistent/sa.json".into())]).is_err());
    }

    #[derive(Clone, Default)]
    struct Buf(Arc<Mutex<Vec<u8>>>);
    impl std::io::Write for Buf {
        fn write(&mut self, b: &[u8]) -> std::io::Result<usize> {
            self.0.lock().unwrap().extend_from_slice(b);
            Ok(b.len())
        }
        fn flush(&mut self) -> std::io::Result<()> {
            Ok(())
        }
    }
    impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for Buf {
        type Writer = Buf;
        fn make_writer(&'a self) -> Buf {
            self.clone()
        }
    }

    #[tokio::test]
    async fn log_driver_logs_content_but_never_tokens() {
        let buf = Buf::default();
        let _g = tracing::subscriber::set_default(
            tracing_subscriber::fmt()
                .with_writer(buf.clone())
                .with_ansi(false)
                .finish(),
        );
        let p = Push::new(Devices::new(sqlite().await));
        assert!(p.is_log());
        let u = uniq();
        let t = tok("verysecrettoken");
        p.devices()
            .register(u, Platform::Android, &t, None, None)
            .await
            .unwrap();
        let n = Notification::new()
            .title("Hello title")
            .body("Hello body")
            .data("k", "v");
        let r = p.send_to_user(u, &n).await.unwrap();
        assert_eq!(
            r,
            SendReport {
                sent: 1,
                failed: 0,
                invalidated: 0
            }
        );
        let out = String::from_utf8(buf.0.lock().unwrap().clone()).unwrap();
        assert!(
            out.contains("Hello title") && out.contains("Hello body") && out.contains("devices=1"),
            "{out}"
        );
        assert!(!out.contains(&t), "token leaked into logs: {out}");
        assert!(!format!("{p:?}").contains(&t));
    }
}