autumn-web 0.6.0

An opinionated, convention-over-configuration web framework for Rust
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
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
//! Operator alerts connect Autumn's built-in failure signals to its existing
//! delivery channels — **with zero application code**.
//!
//! The signals reach the configured mailer and the signed outbound webhook
//! behind a small set of `[alerts]` config keys.
//!
//! # What this is
//!
//! Autumn already knows when things go wrong: a job is dead-lettered, a health
//! indicator reports `Down`, the 5xx rate spikes, or a framework-scheduled task
//! fails. Historically an operator had to wire each of those signals to a
//! notification sink by hand. This module closes that gap: provide an operator
//! email and/or a webhook URL in `[alerts]` and every built-in condition is
//! delivered to you, deduplicated, with a recovery notice when it clears.
//!
//! ## Built-in alertable conditions
//!
//! | Condition | Fires when | Where to look |
//! |-----------|------------|---------------|
//! | [`AlertCondition::DeadLetteredJob`](crate::alerts::AlertCondition::DeadLetteredJob) | a background job exhausts its retries and is dead-lettered | `/actuator/jobs` † |
//! | [`AlertCondition::HealthIndicatorDown`](crate::alerts::AlertCondition::HealthIndicatorDown) | a registered health indicator reports `Down` past the grace period | `/actuator/health` |
//! | [`AlertCondition::HighErrorRate`](crate::alerts::AlertCondition::HighErrorRate) | the rolling 5xx rate crosses the configured threshold | `/actuator/metrics` |
//! | [`AlertCondition::ScheduledTaskFailure`](crate::alerts::AlertCondition::ScheduledTaskFailure) | a framework-scheduled task (backup, cert-renewal, cron/fixed-delay) fails | `/actuator/tasks` † |
//!
//! † `/actuator/jobs` and `/actuator/tasks` are mounted only when `[actuator]
//! sensitive = true` (default `false`). When it is off, those two alerts point at
//! the always-mounted `/actuator/health` instead and note that the richer
//! endpoint needs `sensitive = true` (see `sensitive_gated_where_to_look`).
//!
//! # Delivery is a trait (extension point)
//!
//! Every destination implements [`AlertChannel`](crate::alerts::AlertChannel). The [`Alerter`](crate::alerts::Alerter) holds a
//! fan-out list of channels and delivers each alert to all of them on a
//! detached task — so a slow or unreachable channel never adds latency to a
//! request or blocks the others. Two built-in channels ship:
//! [`MailAlertChannel`](crate::alerts::MailAlertChannel) (reuses the app's [`Mailer`](crate::mail::Mailer)) and
//! [`WebhookAlertChannel`](crate::alerts::WebhookAlertChannel) (a signed, Stripe-style HMAC POST reusing the same
//! signing scheme as [`webhook_outbound`](crate::webhook_outbound)).
//!
//! **Design intent (follow-up #1630):** PagerDuty / Slack / Discord transports
//! are added purely by implementing [`AlertChannel`](crate::alerts::AlertChannel) and registering them with
//! [`AppBuilder::with_alert_channel`](crate::app::AppBuilder::with_alert_channel);
//! the core never changes. That is why every [`Alert`](crate::alerts::Alert) carries a **stable dedup
//! key** ([`Alert::dedup_key`](crate::alerts::Alert::dedup_key), which PagerDuty correlates on), a **severity
//! class** ([`Alert::severity`](crate::alerts::Alert::severity)), and a **trigger vs resolve** discriminator
//! ([`Alert::event`](crate::alerts::Alert::event)).
//!
//! # Deduplication and recovery
//!
//! A sustained or repeating condition does **not** produce one notification per
//! occurrence. [`AlertDeduplicator`](crate::alerts::AlertDeduplicator) bounds notifications to **at most one per
//! condition per dedup window** (default 15 minutes); the condition re-notifies
//! once per window while it persists. When a previously-alerted condition
//! clears, a single [`AlertEventKind::Resolve`](crate::alerts::AlertEventKind::Resolve) recovery notification is sent.
//!
//! # Fail-safe
//!
//! Delivery is best-effort and off the request path: if a channel is
//! unreachable the app keeps serving, the failure is logged, and no latency is
//! added. See [`AppBuilder::with_alert_channel`](crate::app::AppBuilder::with_alert_channel)
//! and `docs/guide/operator-alerts.md` for the full guide.

use std::collections::HashMap;
use std::future::Future;
use std::pin::Pin;
use std::sync::{Arc, Mutex};

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};

use crate::state::AppState;

// ── Core value types ────────────────────────────────────────────────────────

/// The built-in condition that produced an [`Alert`].
///
/// The condition determines the stable dedup-key prefix and the "where to look
/// next" actuator pointer. New transports (#1630) match on this to route.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum AlertCondition {
    /// A background job exhausted its retries and was dead-lettered.
    DeadLetteredJob,
    /// A registered health indicator reported `Down` past the grace period.
    HealthIndicatorDown,
    /// The rolling 5xx error rate crossed the configured threshold.
    HighErrorRate,
    /// A framework-scheduled task (cron or fixed-delay) failed.
    ScheduledTaskFailure,
}

impl AlertCondition {
    /// A short, stable machine name for this condition (used in dedup keys and
    /// webhook payloads).
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::DeadLetteredJob => "dead_lettered_job",
            Self::HealthIndicatorDown => "health_indicator_down",
            Self::HighErrorRate => "high_error_rate",
            Self::ScheduledTaskFailure => "scheduled_task_failure",
        }
    }

    /// The actuator endpoint an operator should consult for this condition,
    /// under the **default** actuator prefix (`/actuator`).
    ///
    /// This is the builder default. When the app configures a custom
    /// `[actuator] prefix`, the emitted alert's `where_to_look` is rebuilt from
    /// the effective prefix (see `actuator_where_to_look`) so it points at the
    /// real endpoint rather than a `/actuator/*` 404. Keep the suffixes here in
    /// sync with `Self::actuator_suffix`.
    #[must_use]
    pub const fn where_to_look(self) -> &'static str {
        match self {
            Self::DeadLetteredJob => "/actuator/jobs",
            Self::HealthIndicatorDown => "/actuator/health",
            Self::HighErrorRate => "/actuator/metrics",
            Self::ScheduledTaskFailure => "/actuator/tasks",
        }
    }

    /// The actuator endpoint suffix (path *below* the actuator prefix) an
    /// operator should consult for this condition. Combined with the effective
    /// prefix by [`actuator_where_to_look`].
    const fn actuator_suffix(self) -> &'static str {
        match self {
            Self::DeadLetteredJob => "/jobs",
            Self::HealthIndicatorDown => "/health",
            Self::HighErrorRate => "/metrics",
            Self::ScheduledTaskFailure => "/tasks",
        }
    }
}

/// Build the actuator `where_to_look` pointer for `condition` under the
/// effective actuator `prefix`.
///
/// Uses the same path builder as the router
/// ([`actuator_route_path`](crate::actuator::actuator_route_path)) so the
/// derived path matches the mounted endpoint exactly — including prefix
/// normalization (leading slash added, trailing slash trimmed, `/` or empty
/// treated as root) — and never yields `//` or a missing slash. With the
/// default prefix (`/actuator`) this reproduces
/// [`AlertCondition::where_to_look`] byte-for-byte.
fn actuator_where_to_look(prefix: &str, condition: AlertCondition) -> String {
    crate::actuator::actuator_route_path(prefix, condition.actuator_suffix())
}

/// Build the `where_to_look` pointer for a condition whose primary actuator
/// endpoint is gated behind `[actuator] sensitive`.
///
/// The `/jobs` (dead-lettered-job) and `/tasks` (scheduled-task-failure)
/// endpoints are mounted ONLY inside the `if sensitive` block of
/// `actuator_router_with_prefix`, and `[actuator] sensitive` defaults to
/// `false`. Pointing an alert at an unmounted endpoint would send operators to a
/// 404, so:
///
/// * `sensitive == true`: the gated endpoint exists — point straight at it
///   (`{prefix}/jobs`, `{prefix}/tasks`), reproducing the prior behavior.
/// * `sensitive == false` (default): the gated endpoint is a 404 — point at the
///   always-mounted `{prefix}/health` endpoint instead and append a short hint
///   naming the richer, sensitive-gated endpoint and the setting that exposes it.
///
/// `/health` (not `/metrics`) is the fallback because the job/task counters live
/// in the sensitive `/jobs` and `/tasks` registries; the HTTP `/metrics` snapshot
/// carries request/status counters, not job/task state — so `/metrics` is no more
/// informative here than the always-mounted `/health`.
fn sensitive_gated_where_to_look(
    prefix: &str,
    condition: AlertCondition,
    sensitive: bool,
) -> String {
    if sensitive {
        actuator_where_to_look(prefix, condition)
    } else {
        let fallback = actuator_where_to_look(prefix, AlertCondition::HealthIndicatorDown);
        let gated = actuator_where_to_look(prefix, condition);
        format!("{fallback} ({gated} requires [actuator] sensitive = true)")
    }
}

/// Severity class of an [`Alert`]. External routers (`PagerDuty` etc.) map this
/// onto their own severity/priority taxonomy.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
#[non_exhaustive]
pub enum AlertSeverity {
    /// A condition is firing and needs operator attention.
    Critical,
    /// A previously-firing condition has recovered (informational).
    Recovery,
}

/// Which alert severities a transport receives (issue #1630, per-channel
/// severity routing).
///
/// Every configured native transport (`PagerDutyAlertChannel`,
/// `SlackAlertChannel`) declares this; the [`Alerter`] consults
/// [`AlertChannel::accepts_severity`] before fanning an alert out, so an alert
/// whose severity a destination does not accept is **never delivered to it**.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum AlertRouting {
    /// Receive every severity — both firing ([`AlertSeverity::Critical`])
    /// alerts and their ([`AlertSeverity::Recovery`]) recoveries. The default
    /// for all channels. A pager-class channel (`PagerDuty`) needs this so a
    /// `resolve` event reaches the provider and the incident auto-resolves.
    #[default]
    All,
    /// Receive only firing ([`AlertSeverity::Critical`]) alerts; recoveries are
    /// not delivered. Use for a chat channel that should page/notify on failure
    /// but stay quiet on recovery.
    Critical,
}

impl AlertRouting {
    /// Whether a channel with this routing accepts an alert of `severity`.
    #[must_use]
    pub const fn accepts(self, severity: AlertSeverity) -> bool {
        match self {
            Self::All => true,
            Self::Critical => matches!(severity, AlertSeverity::Critical),
        }
    }
}

impl std::str::FromStr for AlertRouting {
    type Err = ();

    /// Parse the same `all` / `critical` spellings the `[alerts]` TOML/serde path
    /// accepts (see the `#[serde(rename_all = "snake_case")]` above), so the
    /// `AUTUMN_ALERTS__*_SEVERITIES` env overrides and the config file agree on
    /// the accepted values. Any other value is rejected (the env-override layer
    /// then logs and ignores it, leaving the existing value).
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "all" => Ok(Self::All),
            "critical" => Ok(Self::Critical),
            _ => Err(()),
        }
    }
}

/// Whether this alert opens (trigger) or closes (resolve) a condition. This is
/// the field an incident manager keys on to auto-resolve a correlated alert.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
#[non_exhaustive]
pub enum AlertEventKind {
    /// The condition started (or is still) firing.
    Trigger,
    /// The condition cleared; correlated triggers may be auto-resolved.
    Resolve,
}

/// A single operator alert.
///
/// Carries everything AC #4 requires: **what** failed ([`title`](Self::title) /
/// [`summary`](Self::summary)), **when** ([`timestamp`](Self::timestamp)), on
/// **which host/replica** ([`host`](Self::host)), and **where to look next**
/// ([`where_to_look`](Self::where_to_look)) — plus the machine-routing fields
/// ([`dedup_key`](Self::dedup_key), [`severity`](Self::severity),
/// [`event`](Self::event)).
#[derive(Debug, Clone, Serialize)]
#[non_exhaustive]
pub struct Alert {
    /// Stable key identifying the *condition instance* (e.g. the specific job
    /// or indicator). Identical across trigger and its recovery so an external
    /// system can correlate them. Never contains a timestamp.
    pub dedup_key: String,
    /// The built-in condition family.
    pub condition: AlertCondition,
    /// Severity class.
    pub severity: AlertSeverity,
    /// Trigger vs resolve.
    pub event: AlertEventKind,
    /// One-line human summary of what failed.
    pub title: String,
    /// Longer human-readable detail (the underlying error, counts, etc.).
    pub summary: String,
    /// When the alert was produced (UTC).
    pub timestamp: DateTime<Utc>,
    /// Host / replica identity the alert originated from.
    pub host: String,
    /// Where the operator should look next (an actuator endpoint or a log
    /// correlation id).
    pub where_to_look: String,
    /// Extra structured context (job name, error string, rates, …).
    pub details: HashMap<String, String>,
}

impl Alert {
    /// Build a trigger alert for `condition` with a stable dedup `key`.
    #[must_use]
    pub fn trigger(condition: AlertCondition, key: impl Into<String>) -> AlertBuilder {
        AlertBuilder::new(condition, key.into(), AlertEventKind::Trigger)
    }

    /// Build a recovery (resolve) alert for `condition` with the same stable
    /// dedup `key` its trigger used.
    #[must_use]
    pub fn recovery(condition: AlertCondition, key: impl Into<String>) -> AlertBuilder {
        AlertBuilder::new(condition, key.into(), AlertEventKind::Resolve)
    }
}

/// Builder for an [`Alert`]. Fills host, timestamp, severity, and the
/// where-to-look pointer from sensible defaults.
#[derive(Debug, Clone)]
pub struct AlertBuilder {
    alert: Alert,
}

impl AlertBuilder {
    fn new(condition: AlertCondition, dedup_key: String, event: AlertEventKind) -> Self {
        let severity = match event {
            AlertEventKind::Trigger => AlertSeverity::Critical,
            AlertEventKind::Resolve => AlertSeverity::Recovery,
        };
        Self {
            alert: Alert {
                dedup_key,
                condition,
                severity,
                event,
                title: String::new(),
                summary: String::new(),
                timestamp: Utc::now(),
                host: host_id(),
                where_to_look: condition.where_to_look().to_owned(),
                details: HashMap::new(),
            },
        }
    }

    /// Set the one-line title.
    #[must_use]
    pub fn title(mut self, title: impl Into<String>) -> Self {
        self.alert.title = title.into();
        self
    }

    /// Set the longer human summary.
    #[must_use]
    pub fn summary(mut self, summary: impl Into<String>) -> Self {
        self.alert.summary = summary.into();
        self
    }

    /// Override the "where to look next" pointer (defaults to the condition's
    /// actuator endpoint). Use this to attach a log correlation id.
    #[must_use]
    pub fn where_to_look(mut self, where_to_look: impl Into<String>) -> Self {
        self.alert.where_to_look = where_to_look.into();
        self
    }

    /// Add a structured detail field.
    #[must_use]
    pub fn detail(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.alert.details.insert(key.into(), value.into());
        self
    }

    /// Finish building.
    #[must_use]
    pub fn build(self) -> Alert {
        self.alert
    }
}

/// Resolve the host/replica identity to stamp on every alert.
///
/// Prefers an explicit `AUTUMN_REPLICA_ID`, then the container/host `HOSTNAME`,
/// falling back to `"unknown-host"`.
#[must_use]
pub fn host_id() -> String {
    std::env::var("AUTUMN_REPLICA_ID")
        .ok()
        .filter(|s| !s.trim().is_empty())
        .or_else(|| {
            std::env::var("HOSTNAME")
                .ok()
                .filter(|s| !s.trim().is_empty())
        })
        .unwrap_or_else(|| "unknown-host".to_owned())
}

/// Dedup key for the process-local **5xx-rate** condition, scoped to `host`.
///
/// The 5xx rate is evaluated from THIS process's local metrics, so every
/// replica computes its own rate. The key is host-scoped so a consumer that
/// correlates on `dedup_key` keeps each replica's incident separate: without
/// the suffix, replica B's resolve would clear replica A's still-active
/// incident and simultaneous spikes on different hosts would collapse into one
/// condition. A trigger and its later resolve run in the SAME process, so
/// `host_id()` yields an identical suffix and they still correlate.
fn error_rate_dedup_key(host: &str) -> String {
    format!("high_error_rate:5xx:{host}")
}

/// Dedup key for the process-local **health-indicator-down** condition, scoped
/// to the specific `indicator` and to `host`.
///
/// Health is evaluated from THIS process's local indicator registry, so — like
/// [`error_rate_dedup_key`] — the key is host-scoped so per-replica incidents
/// stay distinct while a trigger and its later resolve (same process, same
/// `host_id()`) still correlate.
fn health_indicator_dedup_key(indicator: &str, host: &str) -> String {
    format!("health_indicator_down:{indicator}:{host}")
}

// ── Delivery trait ──────────────────────────────────────────────────────────

/// The future returned by [`AlertChannel::deliver`].
pub type AlertDeliveryFuture<'a> =
    Pin<Box<dyn Future<Output = Result<(), AlertDeliveryError>> + Send + 'a>>;

/// A delivery failure. Channels return this so the [`Alerter`] can log it; a
/// failure never propagates to the request path.
#[derive(Debug, thiserror::Error)]
#[error("alert delivery via {channel} failed: {message}")]
pub struct AlertDeliveryError {
    /// Name of the channel that failed.
    pub channel: &'static str,
    /// Human-readable failure detail.
    pub message: String,
}

impl AlertDeliveryError {
    /// Construct a delivery error for `channel`.
    #[must_use]
    pub fn new(channel: &'static str, message: impl Into<String>) -> Self {
        Self {
            channel,
            message: message.into(),
        }
    }
}

/// A destination that operator alerts are delivered to.
///
/// This is the framework's extension point for #1630: implement it for
/// `PagerDuty`, Slack, Discord, or any sink and register it with
/// [`AppBuilder::with_alert_channel`](crate::app::AppBuilder::with_alert_channel).
/// Implementations MUST be non-blocking and swallow nothing silently — return
/// [`AlertDeliveryError`] so the framework can log it. Delivery runs on a
/// detached task, so an implementation that is slow or panics can never affect
/// a live request.
pub trait AlertChannel: Send + Sync + 'static {
    /// A short static name for logs (e.g. `"mail"`, `"webhook"`).
    fn name(&self) -> &'static str;

    /// Deliver `alert` to this channel.
    fn deliver<'a>(&'a self, alert: &'a Alert) -> AlertDeliveryFuture<'a>;

    /// Whether this channel receives an alert of the given `severity` (issue
    /// #1630, per-channel severity routing).
    ///
    /// Defaults to accepting **every** severity, so an external channel that
    /// does not override this behaves exactly as before. The built-in native
    /// transports override it to honor the `[alerts]` `*_severities` routing —
    /// a channel that declares [`AlertRouting::Critical`] returns `false` for a
    /// [`AlertSeverity::Recovery`] alert, so the [`Alerter`] skips it and the
    /// recovery is verifiably not delivered there.
    fn accepts_severity(&self, _severity: AlertSeverity) -> bool {
        true
    }
}

// ── Deduplication ───────────────────────────────────────────────────────────

/// Decision returned by the [`AlertDeduplicator`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DedupDecision {
    /// Deliver this alert.
    Send,
    /// Suppress this alert (a bounded duplicate, or a recovery for something
    /// that was never alerted).
    Suppress,
}

impl DedupDecision {
    /// Whether the alert should be delivered.
    #[must_use]
    pub const fn should_send(self) -> bool {
        matches!(self, Self::Send)
    }
}

#[derive(Debug, Clone)]
struct KeyState {
    /// Whether a trigger is currently outstanding (used to gate recovery).
    active: bool,
    /// When we last *delivered* a trigger for this key.
    last_sent: DateTime<Utc>,
}

/// Bounds alert volume for sustained/repeating conditions and gates recovery
/// notifications.
///
/// Policy (AC #3): the first occurrence of a condition alerts immediately;
/// further occurrences within `window` are suppressed. After `window` elapses
/// while the condition still fires, exactly one re-notification is allowed — so
/// the steady-state rate is bounded to **at most one notification per condition
/// per window**, never one-per-occurrence. A recovery is delivered exactly once
/// when a previously-alerted key clears, and never for a key that never fired.
#[derive(Debug)]
pub struct AlertDeduplicator {
    window: chrono::Duration,
    keys: HashMap<String, KeyState>,
}

impl AlertDeduplicator {
    /// Create a deduplicator with the given re-notification window.
    #[must_use]
    pub fn new(window: std::time::Duration) -> Self {
        Self {
            window: chrono::Duration::from_std(window)
                .unwrap_or_else(|_| chrono::Duration::seconds(900)),
            keys: HashMap::new(),
        }
    }

    /// Decide whether a trigger for `key` at `now` should be delivered.
    pub fn on_trigger(&mut self, key: &str, now: DateTime<Utc>) -> DedupDecision {
        match self.keys.get_mut(key) {
            Some(state) if state.active && (now - state.last_sent) < self.window => {
                // Still firing, still inside the window: bounded suppression.
                DedupDecision::Suppress
            }
            Some(state) => {
                // Either it had recovered, or the window has elapsed: re-notify.
                state.active = true;
                state.last_sent = now;
                DedupDecision::Send
            }
            None => {
                self.keys.insert(
                    key.to_owned(),
                    KeyState {
                        active: true,
                        last_sent: now,
                    },
                );
                DedupDecision::Send
            }
        }
    }

    /// Decide whether a recovery for `key` should be delivered. Only keys with
    /// an outstanding (delivered) trigger recover; the key is then cleared so a
    /// future trigger alerts immediately.
    pub fn on_resolve(&mut self, key: &str) -> DedupDecision {
        match self.keys.get_mut(key) {
            Some(state) if state.active => {
                state.active = false;
                DedupDecision::Send
            }
            _ => DedupDecision::Suppress,
        }
    }
}

// ── Alerter ─────────────────────────────────────────────────────────────────

/// Tunables the [`Alerter`] and its background evaluation loop read.
#[derive(Debug, Clone)]
pub struct AlerterSettings {
    /// Dedup / re-notification window.
    pub dedup_window: std::time::Duration,
    /// How long an indicator must stay `Down` before it alerts (condition b).
    pub health_grace: std::time::Duration,
    /// 5xx fraction (of requests in the sample window) that trips the alert.
    pub error_rate_threshold: f64,
    /// Minimum requests in the sample window before the rate is evaluated.
    pub error_rate_min_requests: u64,
    /// Background evaluation cadence (conditions b and c).
    pub eval_interval: std::time::Duration,
    /// The effective actuator URL prefix (`[actuator] prefix`, default
    /// `/actuator`). Every alert's `where_to_look` pointer is built from this so
    /// operators are sent to the real actuator endpoint even when the prefix is
    /// customized. Stored raw; normalization happens in `actuator_where_to_look`.
    pub actuator_prefix: String,
    /// The effective `[actuator] sensitive` flag (default `false`). The `/jobs`
    /// and `/tasks` actuator endpoints are mounted ONLY when this is `true`
    /// (see `actuator_router_with_prefix`), so the dead-lettered-job and
    /// scheduled-task-failure alerts point at them only when they exist and fall
    /// back to an always-mounted endpoint otherwise (see
    /// `sensitive_gated_where_to_look`).
    pub actuator_sensitive: bool,
}

/// Validate the configured 5xx `error_rate_threshold`, falling back to the
/// [`default_error_rate_threshold`] when it is unusable.
///
/// The threshold is compared against a rate computed as `err_delta / req_delta`
/// (see [`evaluate_error_rate`]), i.e. a **fraction in `[0, 1]`**, so the only
/// meaningful thresholds are in `(0, 1]`. A non-finite value (`NaN`/`±inf`) or
/// one `> 1` makes `rate >= threshold` false for every possible rate — the 5xx
/// alert would NEVER fire; a value `<= 0` makes it true even on a 0%-error
/// window — the alert would fire constantly. Neither can be meaningfully clamped
/// (`NaN` especially), so a bad value falls back to the default and is logged,
/// keeping 5xx alerting functional (fail-safe) rather than silently broken.
fn sanitize_error_rate_threshold(threshold: f64) -> f64 {
    if threshold.is_finite() && threshold > 0.0 && threshold <= 1.0 {
        threshold
    } else {
        let default = default_error_rate_threshold();
        tracing::warn!(
            configured = threshold,
            default,
            "alerts: [alerts] error_rate_threshold ({threshold}) is not a valid 5xx rate in \
             (0, 1]; falling back to the default ({default}) so 5xx alerting keeps working. Fix \
             [alerts] error_rate_threshold (or the AUTUMN_ALERTS__ERROR_RATE_THRESHOLD env var)."
        );
        default
    }
}

impl AlerterSettings {
    fn from_config(
        config: &AlertConfig,
        actuator_prefix: String,
        actuator_sensitive: bool,
    ) -> Self {
        Self {
            dedup_window: std::time::Duration::from_secs(config.dedup_window_secs.max(1)),
            health_grace: std::time::Duration::from_secs(config.health_grace_secs),
            error_rate_threshold: sanitize_error_rate_threshold(config.error_rate_threshold),
            error_rate_min_requests: config.error_rate_min_requests.max(1),
            eval_interval: std::time::Duration::from_secs(config.eval_interval_secs.max(1)),
            actuator_prefix,
            actuator_sensitive,
        }
    }
}

struct AlerterInner {
    channels: Vec<Arc<dyn AlertChannel>>,
    dedup: Mutex<AlertDeduplicator>,
    settings: AlerterSettings,
}

/// Runtime fan-out hub for operator alerts, installed as an [`AppState`]
/// extension so the built-in condition hooks can reach it.
///
/// Cloning is cheap (shared `Arc`). Use [`notify`](Self::notify) /
/// [`recover`](Self::recover) to emit alerts; both deduplicate and dispatch on
/// a detached task so nothing blocks the caller.
#[derive(Clone)]
pub struct Alerter {
    inner: Arc<AlerterInner>,
}

impl Alerter {
    /// Build an alerter from a channel list and settings.
    #[must_use]
    pub fn new(channels: Vec<Arc<dyn AlertChannel>>, settings: AlerterSettings) -> Self {
        let dedup = AlertDeduplicator::new(settings.dedup_window);
        Self {
            inner: Arc::new(AlerterInner {
                channels,
                dedup: Mutex::new(dedup),
                settings,
            }),
        }
    }

    /// Whether any channel is registered. When false, emitting is a no-op.
    #[must_use]
    pub fn has_channels(&self) -> bool {
        !self.inner.channels.is_empty()
    }

    pub(crate) fn settings(&self) -> &AlerterSettings {
        &self.inner.settings
    }

    /// Emit a trigger alert. Deduplicated; delivered on a detached task.
    /// Returns whether the alert passed the dedup gate (was dispatched).
    #[must_use]
    pub fn notify(&self, alert: Alert) -> bool {
        let decision = self
            .inner
            .dedup
            .lock()
            .map_or(DedupDecision::Send, |mut d| {
                d.on_trigger(&alert.dedup_key, alert.timestamp)
            });
        if decision.should_send() {
            self.dispatch(alert);
            true
        } else {
            false
        }
    }

    /// Emit a recovery alert if `dedup_key` had an outstanding trigger. The
    /// caller supplies the fully-built recovery [`Alert`]. Returns whether a
    /// recovery was actually dispatched.
    #[must_use]
    pub fn recover(&self, alert: Alert) -> bool {
        let decision = self
            .inner
            .dedup
            .lock()
            .map_or(DedupDecision::Suppress, |mut d| {
                d.on_resolve(&alert.dedup_key)
            });
        if decision.should_send() {
            self.dispatch(alert);
            true
        } else {
            false
        }
    }

    /// Fan the alert out to every channel on a detached task (fail-safe).
    fn dispatch(&self, alert: Alert) {
        if self.inner.channels.is_empty() {
            return;
        }
        // Dispatch is best-effort: with a Tokio runtime handle we spawn one
        // detached task *per channel* so a slow or hanging channel never blocks
        // delivery to the others; with no handle available (unlikely from a hook
        // site) the alert is logged and skipped, never blocking the caller.
        let Ok(handle) = tokio::runtime::Handle::try_current() else {
            tracing::warn!("no tokio runtime available for alert dispatch; skipping");
            return;
        };
        let alert = Arc::new(alert);
        for channel in &self.inner.channels {
            // Per-channel severity routing (issue #1630): a destination that
            // does not accept this alert's severity is skipped, so an alert
            // below a channel's threshold (e.g. a recovery to a critical-only
            // chat channel) is never delivered to it. Defaults to accept-all,
            // so every existing channel is unaffected.
            if !channel.accepts_severity(alert.severity) {
                continue;
            }
            let channel = Arc::clone(channel);
            let alert = Arc::clone(&alert);
            handle.spawn(async move {
                let name = channel.name();
                match channel.deliver(&alert).await {
                    Ok(()) => tracing::debug!(
                        channel = name,
                        dedup_key = %alert.dedup_key,
                        "operator alert delivered"
                    ),
                    Err(error) => tracing::error!(
                        channel = name,
                        dedup_key = %alert.dedup_key,
                        error = %error,
                        "operator alert delivery failed; app continues serving"
                    ),
                }
            });
        }
    }
}

// ── Built-in condition hooks ────────────────────────────────────────────────

/// Look up the installed [`Alerter`] on `state`, if any.
#[must_use]
pub fn alerter(state: &AppState) -> Option<Arc<Alerter>> {
    state.extension::<Alerter>()
}

/// Condition (a): a background job was dead-lettered. Called from the job
/// backends' dead-letter sites. No-op when no alerter is installed.
///
/// The dedup key is scoped to `job_name` (NOT `job_id`) **by design**: during a
/// mass failure of one job type the operator gets a bounded number of alerts —
/// at most one per failing job type per dedup window (AC #3) — rather than one
/// per dead-lettered instance. So that the bounded alert does not hide which
/// concrete job failed, the specific `job_id` is threaded into the alert's
/// human-facing title/summary and its `job_id` detail; the full set of
/// dead-lettered jobs remains visible at the `/actuator/jobs` endpoint.
pub fn notify_dead_lettered_job(state: &AppState, job_name: &str, job_id: &str, error: &str) {
    let Some(alerter) = alerter(state) else {
        return;
    };
    let alert = Alert::trigger(
        AlertCondition::DeadLetteredJob,
        format!("dead_lettered_job:{job_name}"),
    )
    .title(format!("Job '{job_name}' (id {job_id}) was dead-lettered"))
    .summary(format!(
        "Background job '{job_name}' (id {job_id}) exhausted its retries and was moved to the dead-letter queue. Last error: {error}"
    ))
    .where_to_look(sensitive_gated_where_to_look(
        &alerter.settings().actuator_prefix,
        AlertCondition::DeadLetteredJob,
        alerter.settings().actuator_sensitive,
    ))
    .detail("job", job_name)
    .detail("job_id", job_id)
    .detail("error", error)
    .build();
    let _ = alerter.notify(alert);
}

/// Condition (d): a framework-scheduled task failed. Called from the scheduler's
/// failure arms. No-op when no alerter is installed.
pub fn notify_scheduled_task_failure(state: &AppState, task_name: &str, error: &str) {
    let Some(alerter) = alerter(state) else {
        return;
    };
    let alert = Alert::trigger(
        AlertCondition::ScheduledTaskFailure,
        format!("scheduled_task_failure:{task_name}"),
    )
    .title(format!("Scheduled task '{task_name}' failed"))
    .summary(format!(
        "The framework-scheduled task '{task_name}' returned an error on its last run: {error}"
    ))
    .where_to_look(sensitive_gated_where_to_look(
        &alerter.settings().actuator_prefix,
        AlertCondition::ScheduledTaskFailure,
        alerter.settings().actuator_sensitive,
    ))
    .detail("task", task_name)
    .detail("error", error)
    .build();
    let _ = alerter.notify(alert);
}

/// Recovery for condition (d): a previously-failing framework-scheduled task
/// completed successfully. Called from the scheduler's success arms.
///
/// No-op when no alerter is installed. Uses the SAME dedup key as
/// [`notify_scheduled_task_failure`] so the recovery clears an outstanding
/// failure; the dedup gate ([`AlertDeduplicator::on_resolve`]) makes it a no-op
/// when the failure key was never active, so a task that has only ever succeeded
/// sends nothing.
pub fn notify_scheduled_task_recovered(state: &AppState, task_name: &str) {
    let Some(alerter) = alerter(state) else {
        return;
    };
    // KNOWN LIMITATION (multi-replica fleets): the `AlertDeduplicator` is
    // process-local, so a recovery only clears an outstanding failure when it is
    // emitted by the SAME replica that observed the failure. Scheduled tasks are
    // lease-coordinated across the fleet, so the failure can be seen by replica A
    // and the later success run by replica B after a leader handoff; B has no
    // active `scheduled_task_failure:{task}` key locally, so `on_resolve`
    // suppresses the resolve and A's failure alert is never cleared. This is why
    // the scheduled-task key is deliberately NOT host-scoped (a global key is
    // still the closest correlation available). A real fix needs shared
    // active-alert state (Postgres/Redis) or an unconditional correlated resolve,
    // both out of scope for #1610 (fleet-level alert aggregation is listed as a
    // non-goal). The native PagerDuty/Slack/Discord transports (#1630) do not
    // change this process-local behaviour; shared active-alert state remains a
    // separate future follow-up.
    let alert = Alert::recovery(
        AlertCondition::ScheduledTaskFailure,
        format!("scheduled_task_failure:{task_name}"),
    )
    .title(format!("Scheduled task '{task_name}' recovered"))
    .summary(format!(
        "The framework-scheduled task '{task_name}' completed successfully after a previous failure."
    ))
    .where_to_look(sensitive_gated_where_to_look(
        &alerter.settings().actuator_prefix,
        AlertCondition::ScheduledTaskFailure,
        alerter.settings().actuator_sensitive,
    ))
    .detail("task", task_name)
    .build();
    let _ = alerter.recover(alert);
}

// ── Config ──────────────────────────────────────────────────────────────────

const fn default_alerts_enabled() -> bool {
    true
}
const fn default_dedup_window_secs() -> u64 {
    900
}
const fn default_health_grace_secs() -> u64 {
    60
}
const fn default_error_rate_threshold() -> f64 {
    0.05
}
const fn default_error_rate_min_requests() -> u64 {
    20
}
const fn default_eval_interval_secs() -> u64 {
    30
}

/// Default `PagerDuty` Events API v2 enqueue endpoint.
///
/// Override via `[alerts] pagerduty_url` (or `AUTUMN_ALERTS__PAGERDUTY_URL`) to
/// target a PagerDuty-Events-compatible endpoint offered by another paging
/// service.
pub const PAGERDUTY_EVENTS_URL: &str = "https://events.pagerduty.com/v2/enqueue";

/// `[alerts]` configuration.
///
/// Providing **only** a destination (an operator [`email`](Self::email) and/or
/// a [`webhook_url`](Self::webhook_url)) is enough to receive alerts for every
/// built-in condition — no application code required. Every destination and
/// tuning knob is also settable via `AUTUMN_ALERTS__*` environment variables.
///
/// ```toml
/// [alerts]
/// email = "oncall@example.com"
/// webhook_url = "https://alerts.example.com/hooks/autumn"
/// webhook_secret = "..."          # prefer AUTUMN_ALERTS__WEBHOOK_SECRET
/// # Tuning (defaults shown):
/// dedup_window_secs = 900         # at most one notice per condition per 15 min
/// health_grace_secs = 60          # indicator must stay Down this long
/// error_rate_threshold = 0.05     # 5% of sampled requests are 5xx
/// error_rate_min_requests = 20    # ignore the rate below this sample size
/// eval_interval_secs = 30         # background evaluation cadence
/// ```
#[derive(Debug, Clone, Deserialize)]
#[serde(default)]
pub struct AlertConfig {
    /// Master switch. Alerts are only ever emitted when this is `true` **and**
    /// at least one destination is configured.
    pub enabled: bool,
    /// Operator email destination (mail channel). Delivered via the app's
    /// configured mailer with suppression bypassed (alerts are security-class).
    pub email: Option<String>,
    /// Signed outbound webhook destination.
    pub webhook_url: Option<String>,
    /// HMAC signing secret for the webhook destination. Prefer the
    /// `AUTUMN_ALERTS__WEBHOOK_SECRET` env var over committing it.
    pub webhook_secret: Option<String>,
    /// `PagerDuty` Events API v2 routing (integration) key. When set
    /// (non-empty), the `PagerDuty` channel is enabled and every alert is
    /// delivered as an Events API v2 event correlated on the alert's stable
    /// [`Alert::dedup_key`], so a repeating condition folds into a single
    /// incident and an [`AlertEventKind::Resolve`] event auto-resolves it.
    /// Prefer the `AUTUMN_ALERTS__PAGERDUTY_ROUTING_KEY` env var over committing
    /// it.
    pub pagerduty_routing_key: Option<String>,
    /// Override for the `PagerDuty` Events API v2 enqueue endpoint. Defaults to
    /// [`PAGERDUTY_EVENTS_URL`]; set this to target a PagerDuty-Events-compatible
    /// endpoint offered by another paging service.
    pub pagerduty_url: Option<String>,
    /// Which severities the `PagerDuty` channel receives (default
    /// [`AlertRouting::All`], so a `resolve` event reaches `PagerDuty` and the
    /// incident auto-resolves).
    #[serde(default)]
    pub pagerduty_severities: AlertRouting,
    /// Slack incoming-webhook URL. When set (non-empty, absolute `http(s)`), the
    /// Slack channel posts a human-readable message for each alert. Prefer the
    /// `AUTUMN_ALERTS__SLACK_WEBHOOK_URL` env var over committing it.
    pub slack_webhook_url: Option<String>,
    /// Which severities the Slack channel receives (default
    /// [`AlertRouting::All`]).
    #[serde(default)]
    pub slack_severities: AlertRouting,
    /// Discord webhook URL. Delivered via Discord's Slack-compatible endpoint
    /// (append `/slack` to a Discord webhook URL), reusing the exact same
    /// payload dialect as Slack. When set (non-empty, absolute `http(s)`), the
    /// Discord channel posts a human-readable message for each alert. Prefer the
    /// `AUTUMN_ALERTS__DISCORD_WEBHOOK_URL` env var over committing it.
    pub discord_webhook_url: Option<String>,
    /// Which severities the Discord channel receives (default
    /// [`AlertRouting::All`]).
    #[serde(default)]
    pub discord_severities: AlertRouting,
    /// Set true to tell `autumn doctor` you register an alert channel in code via
    /// `AppBuilder::with_alert_channel`; suppresses the no-destination warning.
    /// The runtime installs code-registered channels regardless of this flag.
    #[serde(default)]
    pub custom_channel: bool,
    /// At most one notification per condition per this many seconds.
    pub dedup_window_secs: u64,
    /// How long (seconds) an indicator must stay `Down` before it alerts.
    pub health_grace_secs: u64,
    /// 5xx fraction of the sampled request window that trips the alert.
    pub error_rate_threshold: f64,
    /// Minimum requests in the sample window before the 5xx rate is evaluated.
    pub error_rate_min_requests: u64,
    /// Background evaluation cadence (seconds) for the health and 5xx-rate
    /// conditions.
    pub eval_interval_secs: u64,
}

impl Default for AlertConfig {
    fn default() -> Self {
        Self {
            enabled: default_alerts_enabled(),
            email: None,
            webhook_url: None,
            webhook_secret: None,
            pagerduty_routing_key: None,
            pagerduty_url: None,
            pagerduty_severities: AlertRouting::All,
            slack_webhook_url: None,
            slack_severities: AlertRouting::All,
            discord_webhook_url: None,
            discord_severities: AlertRouting::All,
            custom_channel: false,
            dedup_window_secs: default_dedup_window_secs(),
            health_grace_secs: default_health_grace_secs(),
            error_rate_threshold: default_error_rate_threshold(),
            error_rate_min_requests: default_error_rate_min_requests(),
            eval_interval_secs: default_eval_interval_secs(),
        }
    }
}

impl AlertConfig {
    /// Whether a delivery destination is configured — an email, a generic
    /// webhook URL, or any native transport (`PagerDuty` routing key, Slack or
    /// Discord webhook URL).
    #[must_use]
    pub fn has_destination(&self) -> bool {
        let set = |v: &Option<String>| v.as_ref().is_some_and(|s| !s.trim().is_empty());
        set(&self.email)
            || set(&self.webhook_url)
            || set(&self.pagerduty_routing_key)
            || set(&self.slack_webhook_url)
            || set(&self.discord_webhook_url)
    }

    /// Whether alerts should actually be active (enabled + a destination).
    #[must_use]
    pub fn is_active(&self) -> bool {
        self.enabled && self.has_destination()
    }
}

// ── Built-in channels ───────────────────────────────────────────────────────

/// Mail alert channel: delivers each alert as an email through the app's
/// configured [`Mailer`](crate::mail::Mailer).
///
/// The message is built with
/// [`Mail::ignore_suppression`](crate::mail::MailBuilder::ignore_suppression):
/// operator alerts are security-class and must never be silently dropped by the
/// bounce/complaint suppression list.
#[cfg(feature = "mail")]
pub struct MailAlertChannel {
    mailer: Arc<crate::mail::Mailer>,
    to: String,
}

#[cfg(feature = "mail")]
impl MailAlertChannel {
    /// Create a mail channel delivering to `to` via `mailer`.
    #[must_use]
    pub fn new(mailer: Arc<crate::mail::Mailer>, to: impl Into<String>) -> Self {
        Self {
            mailer,
            to: to.into(),
        }
    }

    fn render_text(alert: &Alert) -> String {
        use std::fmt::Write as _;
        let mut body = format!(
            "{}\n\nSeverity: {:?}\nEvent: {:?}\nCondition: {}\nHost/replica: {}\nWhen: {}\nWhere to look next: {}\n\n{}\n",
            alert.title,
            alert.severity,
            alert.event,
            alert.condition.as_str(),
            alert.host,
            alert.timestamp.to_rfc3339(),
            alert.where_to_look,
            alert.summary,
        );
        if !alert.details.is_empty() {
            body.push_str("\nDetails:\n");
            let mut keys: Vec<&String> = alert.details.keys().collect();
            keys.sort();
            for k in keys {
                if let Some(v) = alert.details.get(k) {
                    let _ = writeln!(body, "  {k}: {v}");
                }
            }
        }
        body
    }
}

#[cfg(feature = "mail")]
impl AlertChannel for MailAlertChannel {
    fn name(&self) -> &'static str {
        "mail"
    }

    fn deliver<'a>(&'a self, alert: &'a Alert) -> AlertDeliveryFuture<'a> {
        Box::pin(async move {
            let prefix = match alert.event {
                AlertEventKind::Trigger => "[ALERT]",
                AlertEventKind::Resolve => "[RECOVERED]",
            };
            let subject = format!("{prefix} {}", alert.title);
            let mail = crate::mail::Mail::builder()
                .to(self.to.clone())
                .subject(subject)
                .text(Self::render_text(alert))
                .ignore_suppression()
                .build()
                .map_err(|e| AlertDeliveryError::new("mail", e.to_string()))?;
            self.mailer
                .send(mail)
                .await
                .map_err(|e| AlertDeliveryError::new("mail", e.to_string()))
        })
    }
}

/// Signed-webhook alert channel: POSTs the alert as JSON to a configured URL.
///
/// The request is signed with the same Stripe-style
/// `Autumn-Signature: t=<ts>,v1=<hmac>` scheme as the outbound webhook
/// machinery ([`webhook_outbound`](crate::webhook_outbound)) — no new
/// dependency.
#[cfg(feature = "http-client")]
pub struct WebhookAlertChannel {
    client: crate::http_client::Client,
    url: String,
    secret: Option<String>,
}

#[cfg(feature = "http-client")]
impl WebhookAlertChannel {
    /// Create a webhook channel posting to `url`, optionally HMAC-signing with
    /// `secret`.
    #[must_use]
    pub fn new(
        client: crate::http_client::Client,
        url: impl Into<String>,
        secret: Option<String>,
    ) -> Self {
        Self {
            client,
            url: url.into(),
            secret,
        }
    }
}

#[cfg(feature = "http-client")]
impl AlertChannel for WebhookAlertChannel {
    fn name(&self) -> &'static str {
        "webhook"
    }

    fn deliver<'a>(&'a self, alert: &'a Alert) -> AlertDeliveryFuture<'a> {
        Box::pin(async move {
            let body = serde_json::to_string(alert)
                .map_err(|e| AlertDeliveryError::new("webhook", e.to_string()))?;
            let mut req = self
                .client
                .named(&self.url)
                .post(&self.url)
                .header("Content-Type", "application/json");
            if let Some(secret) = self.secret.as_ref() {
                let timestamp = Utc::now().timestamp();
                let signing_payload = format!("{timestamp}.{body}");
                let signature = crate::security::config::hmac_sha256_hex(
                    secret.as_bytes(),
                    signing_payload.as_bytes(),
                );
                req = req.header("Autumn-Signature", format!("t={timestamp},v1={signature}"));
            }
            let response = req
                .text_body(body)
                .send()
                .await
                .map_err(|e| AlertDeliveryError::new("webhook", e.to_string()))?;
            if response.is_success() {
                Ok(())
            } else {
                Err(AlertDeliveryError::new(
                    "webhook",
                    format!("endpoint returned status {}", response.status()),
                ))
            }
        })
    }
}

// ── Native transports (issue #1630) ─────────────────────────────────────────

/// Map an [`AlertSeverity`] onto the `PagerDuty` Events API v2 `severity`
/// taxonomy (`critical` / `error` / `warning` / `info`). Autumn's built-in
/// conditions are all operator-critical, so a firing alert maps to `critical`;
/// a recovery is informational (`info`) — though a `resolve` event carries no
/// `payload`, this keeps the mapping total.
#[cfg(feature = "http-client")]
const fn pagerduty_severity(severity: AlertSeverity) -> &'static str {
    match severity {
        AlertSeverity::Critical => "critical",
        AlertSeverity::Recovery => "info",
    }
}

/// Build the `PagerDuty` Events API v2 request body for `alert`, correlated on
/// the alert's stable [`Alert::dedup_key`] with `routing_key`.
///
/// A [`AlertEventKind::Trigger`] produces a full `trigger` event (with the
/// `payload` block `PagerDuty` requires); a [`AlertEventKind::Resolve`] produces a
/// minimal `resolve` event (only `routing_key`, `event_action`, and `dedup_key`,
/// per the Events API v2 contract) that auto-resolves the correlated incident.
#[cfg(feature = "http-client")]
#[must_use]
pub fn pagerduty_event_payload(alert: &Alert, routing_key: &str) -> serde_json::Value {
    // Reserved standard-field names Autumn writes into `custom_details` below.
    // PagerDuty routing/correlation depends on these carrying the authoritative
    // values, so a user detail keyed with one of these must NOT clobber it — nor
    // be clobbered by it. Colliding user keys are preserved under `custom_<key>`.
    const RESERVED: &[&str] = &["condition", "where_to_look", "detail"];
    if alert.event == AlertEventKind::Resolve {
        return serde_json::json!({
            "routing_key": routing_key,
            "event_action": "resolve",
            "dedup_key": alert.dedup_key,
        });
    }
    let mut custom = serde_json::Map::new();
    let mut keys: Vec<&String> = alert.details.keys().collect();
    keys.sort();
    for k in keys {
        if let Some(v) = alert.details.get(k) {
            let key = if RESERVED.contains(&k.as_str()) {
                format!("custom_{k}")
            } else {
                k.clone()
            };
            custom.insert(key, serde_json::Value::String(v.clone()));
        }
    }
    custom.insert(
        "condition".to_owned(),
        serde_json::Value::String(alert.condition.as_str().to_owned()),
    );
    custom.insert(
        "where_to_look".to_owned(),
        serde_json::Value::String(alert.where_to_look.clone()),
    );
    if !alert.summary.is_empty() {
        custom.insert(
            "detail".to_owned(),
            serde_json::Value::String(alert.summary.clone()),
        );
    }
    serde_json::json!({
        "routing_key": routing_key,
        "event_action": "trigger",
        "dedup_key": alert.dedup_key,
        "payload": {
            "summary": alert.title,
            "source": alert.host,
            "severity": pagerduty_severity(alert.severity),
            "timestamp": alert.timestamp.to_rfc3339(),
            "component": alert.condition.as_str(),
            "custom_details": serde_json::Value::Object(custom),
        },
    })
}

/// `PagerDuty` Events API v2 alert channel (issue #1630).
///
/// POSTs each alert as an Events API v2 event correlated on the alert's stable
/// [`Alert::dedup_key`], so a repeating condition folds into a single incident
/// and a recovery emits a `resolve` event that auto-resolves it. Works against
/// PagerDuty-Events-compatible endpoints offered by other paging services (set
/// `[alerts] pagerduty_url`).
///
/// The endpoint URL is validated only for *shape* — an absolute `http(s)` URL —
/// at config load and by `autumn doctor`'s `alert_transports` check. The
/// outbound POST does NOT apply the
/// [`http_client::Client`](crate::http_client::Client)'s SSRF deny-list /
/// address pinning (that guard is only enabled via
/// [`Client::get_ssrf_safe`](crate::http_client::Client::get_ssrf_safe)). Alert
/// URLs are treated as trusted operator configuration and are intentionally
/// exempt so operators can page internal endpoints.
#[cfg(feature = "http-client")]
pub struct PagerDutyAlertChannel {
    client: crate::http_client::Client,
    url: String,
    routing_key: String,
    routing: AlertRouting,
}

#[cfg(feature = "http-client")]
impl PagerDutyAlertChannel {
    /// Create a `PagerDuty` channel posting to `url` (typically
    /// [`PAGERDUTY_EVENTS_URL`]) with the Events API v2 `routing_key`, receiving
    /// the severities `routing` accepts.
    #[must_use]
    pub fn new(
        client: crate::http_client::Client,
        url: impl Into<String>,
        routing_key: impl Into<String>,
        routing: AlertRouting,
    ) -> Self {
        Self {
            client,
            url: url.into(),
            routing_key: routing_key.into(),
            routing,
        }
    }
}

#[cfg(feature = "http-client")]
impl AlertChannel for PagerDutyAlertChannel {
    fn name(&self) -> &'static str {
        "pagerduty"
    }

    fn accepts_severity(&self, severity: AlertSeverity) -> bool {
        self.routing.accepts(severity)
    }

    fn deliver<'a>(&'a self, alert: &'a Alert) -> AlertDeliveryFuture<'a> {
        Box::pin(async move {
            let payload = pagerduty_event_payload(alert, &self.routing_key);
            let response = self
                .client
                .named(&self.url)
                .post(&self.url)
                .json(&payload)
                .send()
                .await
                .map_err(|e| AlertDeliveryError::new("pagerduty", e.to_string()))?;
            // The Events API v2 returns 202 Accepted on success.
            if response.is_success() {
                Ok(())
            } else {
                Err(AlertDeliveryError::new(
                    "pagerduty",
                    format!("endpoint returned status {}", response.status()),
                ))
            }
        })
    }
}

/// Build the Slack/Discord-compatible message text for `alert`, carrying the
/// operator-actionable fields (#1610): what failed, when, host/replica, and
/// where to look next, plus any structured details.
#[cfg(feature = "http-client")]
fn slack_message_text(alert: &Alert) -> String {
    use std::fmt::Write as _;
    let (icon, label) = match alert.event {
        AlertEventKind::Trigger => ("\u{1f534}", "ALERT"),
        AlertEventKind::Resolve => ("\u{2705}", "RECOVERED"),
    };
    let mut body = format!("{icon} *[{label}] {}*\n", alert.title);
    let _ = writeln!(body, "*When:* {}", alert.timestamp.to_rfc3339());
    let _ = writeln!(body, "*Host/replica:* {}", alert.host);
    let _ = writeln!(body, "*Condition:* {}", alert.condition.as_str());
    let _ = writeln!(body, "*Where to look:* {}", alert.where_to_look);
    if !alert.summary.is_empty() {
        let _ = write!(body, "\n{}", alert.summary);
    }
    if !alert.details.is_empty() {
        body.push_str("\n\n*Details:*");
        let mut keys: Vec<&String> = alert.details.keys().collect();
        keys.sort();
        for k in keys {
            if let Some(v) = alert.details.get(k) {
                let _ = write!(body, "\n{k}: {v}");
            }
        }
    }
    body
}

/// Build the Slack (and Discord Slack-compatible) webhook request body for
/// `alert`. Both accept a top-level `text` field, so one payload dialect covers
/// both chat tools.
#[cfg(feature = "http-client")]
#[must_use]
pub fn slack_message_payload(alert: &Alert) -> serde_json::Value {
    serde_json::json!({ "text": slack_message_text(alert) })
}

/// Slack / Discord chat alert channel (issue #1630).
///
/// POSTs a human-readable message to a Slack incoming-webhook URL, or to a
/// Discord webhook's Slack-compatible endpoint (append `/slack`), using one
/// payload dialect for both.
///
/// The webhook URL is validated only for *shape* — an absolute `https` URL — at
/// config load and by `autumn doctor`'s `alert_transports` check. The outbound
/// POST does NOT apply the
/// [`http_client::Client`](crate::http_client::Client)'s SSRF deny-list /
/// address pinning (that guard is only enabled via
/// [`Client::get_ssrf_safe`](crate::http_client::Client::get_ssrf_safe)). Alert
/// URLs are treated as trusted operator configuration and are intentionally
/// exempt so operators can alert to internal chat endpoints.
#[cfg(feature = "http-client")]
pub struct SlackAlertChannel {
    client: crate::http_client::Client,
    url: String,
    name: &'static str,
    routing: AlertRouting,
}

#[cfg(feature = "http-client")]
impl SlackAlertChannel {
    /// Create a Slack channel posting to the incoming-webhook `url`.
    #[must_use]
    pub fn slack(
        client: crate::http_client::Client,
        url: impl Into<String>,
        routing: AlertRouting,
    ) -> Self {
        Self {
            client,
            url: url.into(),
            name: "slack",
            routing,
        }
    }

    /// Create a Discord channel posting to a Discord webhook's Slack-compatible
    /// endpoint (`.../slack`), reusing the Slack payload dialect.
    #[must_use]
    pub fn discord(
        client: crate::http_client::Client,
        url: impl Into<String>,
        routing: AlertRouting,
    ) -> Self {
        Self {
            client,
            url: url.into(),
            name: "discord",
            routing,
        }
    }
}

#[cfg(feature = "http-client")]
impl AlertChannel for SlackAlertChannel {
    fn name(&self) -> &'static str {
        self.name
    }

    fn accepts_severity(&self, severity: AlertSeverity) -> bool {
        self.routing.accepts(severity)
    }

    fn deliver<'a>(&'a self, alert: &'a Alert) -> AlertDeliveryFuture<'a> {
        Box::pin(async move {
            let payload = slack_message_payload(alert);
            let response = self
                .client
                .named(&self.url)
                .post(&self.url)
                .json(&payload)
                .send()
                .await
                .map_err(|e| AlertDeliveryError::new(self.name, e.to_string()))?;
            if response.is_success() {
                Ok(())
            } else {
                Err(AlertDeliveryError::new(
                    self.name,
                    format!("endpoint returned status {}", response.status()),
                ))
            }
        })
    }
}

/// Build the native provider channels (`PagerDuty`, Slack, Discord) configured
/// in `[alerts]` (issue #1630).
///
/// Skips any transport whose required config is missing or unusable (a blank
/// routing key, or a non-absolute webhook URL that the HTTP client could never
/// dispatch), with a dedicated `tracing::warn!` for each skip — mirroring the
/// built-in webhook's skip-and-warn rigor so a transport that *looks* configured
/// actually delivers.
///
/// Shared by [`install_from_config`] (runtime wiring) and the CLI `autumn alert
/// test` command so both agree on exactly which transports are usable.
///
/// All outbound calls go through the passed `client`, but only the transport
/// URL *shape* is validated (absolute `https` for Slack/Discord; absolute
/// `http(s)` for `PagerDuty`) — at config load and by `autumn doctor`'s
/// `alert_transports` check. Dispatch does NOT apply the client's SSRF deny-list
/// / address pinning (that guard is only enabled via
/// [`Client::get_ssrf_safe`](crate::http_client::Client::get_ssrf_safe)); alert
/// URLs are trusted operator configuration and are intentionally exempt so
/// operators can alert to internal endpoints.
#[cfg(feature = "http-client")]
#[must_use]
pub fn native_transport_channels(
    config: &AlertConfig,
    client: &crate::http_client::Client,
) -> Vec<Arc<dyn AlertChannel>> {
    let mut channels: Vec<Arc<dyn AlertChannel>> = Vec::new();

    if let Some(routing_key) = config
        .pagerduty_routing_key
        .as_ref()
        .map(|s| s.trim())
        .filter(|s| !s.is_empty())
    {
        let url = config
            .pagerduty_url
            .as_ref()
            .map(|s| s.trim())
            .filter(|s| !s.is_empty())
            .unwrap_or(PAGERDUTY_EVENTS_URL);
        if is_absolute_http_url(url) {
            channels.push(Arc::new(PagerDutyAlertChannel::new(
                client.clone(),
                url.to_owned(),
                routing_key.to_owned(),
                config.pagerduty_severities,
            )));
        } else {
            tracing::warn!(
                pagerduty_url = url,
                "alerts: the configured [alerts] pagerduty_url ({url}) is not an absolute \
                 http(s) URL; no PagerDuty alerts will be delivered. Fix [alerts] pagerduty_url \
                 (or the AUTUMN_ALERTS__PAGERDUTY_URL env var)."
            );
        }
    }

    push_chat_channel(
        &mut channels,
        client,
        config.slack_webhook_url.as_deref(),
        "slack",
        config.slack_severities,
    );
    push_chat_channel(
        &mut channels,
        client,
        config.discord_webhook_url.as_deref(),
        "discord",
        config.discord_severities,
    );

    channels
}

/// Register a Slack-compatible chat channel (`slack` or `discord`) from a
/// configured webhook `url`, skipping (with a warning) a URL that is not an
/// absolute `https` URL — Slack and Discord only expose `https` webhook
/// endpoints, so a relative, malformed, or plaintext `http://` value would never
/// deliver (mirrors `autumn doctor`'s `is_absolute_https_url_doctor`).
#[cfg(feature = "http-client")]
fn push_chat_channel(
    channels: &mut Vec<Arc<dyn AlertChannel>>,
    client: &crate::http_client::Client,
    url: Option<&str>,
    provider: &'static str,
    routing: AlertRouting,
) {
    let Some(url) = url.map(str::trim).filter(|s| !s.is_empty()) else {
        return;
    };
    if !is_absolute_https_url(url) {
        tracing::warn!(
            provider,
            webhook_url = url,
            "alerts: the configured [alerts] {provider}_webhook_url ({url}) is not an absolute \
             https URL; no {provider} alerts will be delivered ({provider} only exposes https \
             webhook endpoints). Fix the URL (or the AUTUMN_ALERTS__{PROVIDER}_WEBHOOK_URL env \
             var).",
            PROVIDER = provider.to_uppercase(),
        );
        return;
    }
    let channel: Arc<dyn AlertChannel> = if provider == "discord" {
        Arc::new(SlackAlertChannel::discord(
            client.clone(),
            url.to_owned(),
            routing,
        ))
    } else {
        Arc::new(SlackAlertChannel::slack(
            client.clone(),
            url.to_owned(),
            routing,
        ))
    };
    channels.push(channel);
}

// ── Wiring ──────────────────────────────────────────────────────────────────

/// Whether `url` is a non-empty ABSOLUTE `http(s)` URL that the outbound HTTP
/// client will actually dispatch.
///
/// This mirrors the runtime absoluteness rule in
/// [`http_client::Client::build_request`](crate::http_client::Client): a request
/// URL is dispatched verbatim only when it starts with `http://` or `https://`
/// (both schemes accepted, no TLS requirement); anything else is treated as
/// relative and resolved against a base-url alias — of which the alert webhook
/// client has none, so a relative/malformed value fails `reqwest::Url::parse` at
/// send time and every alert POST fails. Requiring a parseable URL with a
/// non-empty host here rejects such values BEFORE the channel is registered, so
/// a webhook that looks configured actually delivers. Kept in lock-step with
/// `autumn-cli`'s `is_absolute_http_url_doctor` (same rule) so doctor and the
/// runtime agree on which webhook URLs are usable.
#[cfg(feature = "http-client")]
fn is_absolute_http_url(url: &str) -> bool {
    if !(url.starts_with("http://") || url.starts_with("https://")) {
        return false;
    }
    ::url::Url::parse(url)
        .ok()
        .and_then(|parsed| parsed.host_str().map(|h| !h.is_empty()))
        .unwrap_or(false)
}

/// Whether `url` is a non-empty ABSOLUTE **`https`** URL with a host.
///
/// Stricter than [`is_absolute_http_url`]: it additionally requires the `https`
/// scheme. Slack and Discord only expose `https` webhook endpoints, so a
/// plaintext `http://` URL will never deliver (and would transmit insecurely) —
/// the runtime must reject it just as `autumn doctor` does. Kept in lock-step
/// with `autumn-cli`'s `is_absolute_https_url_doctor` (same rule) so doctor and
/// the runtime agree on which Slack/Discord webhook URLs are usable and cannot
/// drift.
#[cfg(feature = "http-client")]
fn is_absolute_https_url(url: &str) -> bool {
    url.starts_with("https://") && is_absolute_http_url(url)
}

/// Whether `email` parses as the SAME lettre [`Mailbox`](lettre::message::Mailbox)
/// the mail send path requires of every recipient.
///
/// The runtime's alert mail hands `[alerts] email` verbatim to
/// `Mail::builder().to(...)`, and lettre parses the recipient only at SEND time —
/// in [`parse_mailbox`](crate::mail)/`lettre_message`, not when the alert `Mail`
/// is built. So a present-but-unparsable value like `not-an-address` or
/// `mailto:oncall@example.com` passes every earlier gate yet fails EVERY delivery
/// with `MailError::InvalidAddress`. Running the exact same `str::parse::<Mailbox>`
/// here rejects such a value BEFORE the channel is registered, mirroring the
/// disabled-transport / invalid-webhook skips and keeping the runtime in lock-step
/// with `autumn-cli`'s `is_valid_bare_mailbox_doctor` (same validity notion) so
/// doctor and the runtime agree on which addresses are usable.
#[cfg(feature = "mail")]
fn is_valid_alert_mailbox(email: &str) -> bool {
    email.parse::<lettre::message::Mailbox>().is_ok()
}

/// Whether a mail transport actually needs a `from` address to deliver an alert.
///
/// Only `smtp` builds a real RFC 5322 message: `mail.rs`'s `lettre_message` errors
/// with "mail from address is required" when `from` is absent, and it is reached
/// solely from the SMTP transport. The `log` and `file` transports render `from`
/// only when present and deliver without it; `disabled` is already skipped by the
/// [`Mailer::is_disabled`](crate::mail::Mailer::is_disabled) guard. Mirrors
/// `autumn-cli`'s `mail_transport_requires_from` so doctor and the runtime agree
/// on which transports are blocked by a missing `from`.
#[cfg(feature = "mail")]
const fn mail_transport_requires_from(transport: crate::mail::Transport) -> bool {
    matches!(transport, crate::mail::Transport::Smtp)
}

/// Resolve the built-in mail alert channel for a configured, non-empty `[alerts]
/// email`, or `None` (after a dedicated `tracing::warn!`) when the mailer would
/// deliver nothing at runtime.
///
/// Mirrors the disabled-transport / invalid-webhook skip-and-warn pattern in
/// [`install_from_config`], skipping when:
/// - the transport is the no-op disabled one (`Mailer::is_disabled`): it accepts
///   and silently drops every message, so a registered channel would make an
///   email-only prod config look active while delivering nothing;
/// - the address is not a valid lettre [`Mailbox`](lettre::message::Mailbox):
///   lettre parses `[alerts] email` only at SEND time, so a malformed value fails
///   EVERY delivery with `MailError::InvalidAddress`;
/// - the transport needs a `from` (SMTP) and no non-empty `[mail] from` resolves:
///   the alert mail carries no per-message `from` and falls back to the mailer
///   default, so SMTP send fails with "mail from address is required".
///
/// The resolved `[mail]` config is the faithful source for the last two
/// preconditions: the framework builds this `Mailer` from `config.mail`
/// (`Mailer::from_config`), so its transport kind and default `from` are exactly
/// these fields — keeping the runtime skips in lock-step with doctor.
#[cfg(feature = "mail")]
fn build_mail_alert_channel(
    state: &AppState,
    mailer: Arc<crate::mail::Mailer>,
    email: &str,
) -> Option<Arc<dyn AlertChannel>> {
    // TRIM the resolved address and treat the trimmed value as canonical (the
    // caller already guaranteed it is non-empty after trimming): lettre parses
    // the recipient at send time, so validate — and deliver to — the exact
    // address the send path would parse.
    let email_trimmed = email.trim();
    if mailer.is_disabled() {
        tracing::warn!(
            "alerts: an operator email is configured but [mail] transport is disabled; \
             no email alerts will be delivered. Set [mail] transport to a real backend \
             or use a webhook destination."
        );
        return None;
    }
    if !is_valid_alert_mailbox(email_trimmed) {
        tracing::warn!(
            email = email_trimmed,
            "alerts: the configured [alerts] email ({email_trimmed}) is not a valid email \
             address; no email alerts will be delivered. Fix [alerts] email (or the \
             AUTUMN_ALERTS__EMAIL env var)."
        );
        return None;
    }
    let mail_cfg = state.config().mail;
    if mail_transport_requires_from(mail_cfg.transport)
        && mail_cfg
            .from
            .as_deref()
            .is_none_or(|from| from.trim().is_empty())
    {
        tracing::warn!(
            "alerts: an operator email is configured but [mail] from is not set, so SMTP alert \
             delivery will fail; no email alerts will be delivered. Set [mail] from (or the \
             AUTUMN_MAIL__FROM env var) to a sender address, or use a webhook destination."
        );
        return None;
    }
    Some(Arc::new(MailAlertChannel::new(
        mailer,
        email_trimmed.to_owned(),
    )))
}

/// Append the native provider channels (issue #1630, `PagerDuty` / Slack /
/// Discord) to `channels`, built through [`native_transport_channels`] with the
/// shared HTTP client.
///
/// Alert dispatch validates only the transport URL's *shape*; it does NOT apply
/// the client's SSRF deny-list / address pinning (see
/// [`native_transport_channels`]). Alert URLs are trusted operator
/// configuration and are intentionally exempt so operators can alert to
/// internal endpoints.
///
/// Compiled to a warn-only no-op when the `http-client` feature is off, so a
/// PagerDuty/Slack/Discord-only config does not silently deliver nothing.
fn push_native_transport_channels(
    state: &AppState,
    config: &AlertConfig,
    channels: &mut Vec<Arc<dyn AlertChannel>>,
) {
    #[cfg(feature = "http-client")]
    {
        let client = crate::http_client::Client::from_state(state);
        channels.extend(native_transport_channels(config, &client));
    }
    #[cfg(not(feature = "http-client"))]
    {
        let _ = (state, channels);
        if config
            .pagerduty_routing_key
            .as_ref()
            .is_some_and(|s| !s.trim().is_empty())
            || config
                .slack_webhook_url
                .as_ref()
                .is_some_and(|s| !s.trim().is_empty())
            || config
                .discord_webhook_url
                .as_ref()
                .is_some_and(|s| !s.trim().is_empty())
        {
            tracing::warn!(
                "operator-alerts: a PagerDuty/Slack/Discord transport is configured but the \
                 `http-client` feature is not enabled; no such alerts will be delivered. Enable \
                 the `http-client` feature or use an email destination."
            );
        }
    }
}

/// Install the operator alerter from `config` plus any builder channels.
///
/// Builds the built-in channels from `config`, combines them with any
/// `extra_channels` registered via the builder, installs the resulting
/// [`Alerter`] onto `state`, and starts the background evaluation loop for the
/// health and 5xx-rate conditions.
///
/// `config.enabled` is the master off switch. When it is `false` the *entire*
/// alerting subsystem is silent: no built-in channels, no custom/extra channels
/// registered via [`AppBuilder::with_alert_channel`](crate::app::AppBuilder::with_alert_channel),
/// no background evaluation loop, and no [`Alerter`] installed onto `state` (so
/// the `notify_*` hooks become no-ops). Nothing is installed either when
/// alerting is enabled but there is no destination and no extra channel — so an
/// app with no configured destination pays nothing.
pub fn install_from_config(
    state: &AppState,
    config: &AlertConfig,
    extra_channels: Vec<Arc<dyn AlertChannel>>,
) {
    // Master off switch: `enabled = false` silences EVERYTHING, including any
    // custom channel registered via `with_alert_channel`. Install nothing, do
    // not start the evaluation loop, and do not put an alerter onto `state`.
    if !config.enabled {
        return;
    }

    let mut channels: Vec<Arc<dyn AlertChannel>> = Vec::new();

    #[cfg(feature = "mail")]
    if let Some(email) = config.email.as_ref().filter(|s| !s.trim().is_empty()) {
        if let Some(mailer) = state.extension::<crate::mail::Mailer>() {
            if let Some(channel) = build_mail_alert_channel(state, mailer, email) {
                channels.push(channel);
            }
        } else {
            tracing::warn!(
                "alerts: an operator email is configured but no mailer is installed; \
                 configure [mail] to enable email alerts"
            );
        }
    }
    // Without the `mail` feature the email branch above is compiled out, so an
    // email-only config would silently install no channels and deliver no
    // alerts. Warn loudly so operators don't believe email alerts are active.
    #[cfg(not(feature = "mail"))]
    if config.email.as_ref().is_some_and(|s| !s.trim().is_empty()) {
        tracing::warn!(
            "operator-alerts: an email destination is configured but the `mail` feature is not \
             enabled; no email alerts will be delivered. Enable the `mail` feature or use a \
             webhook destination."
        );
    }
    #[cfg(feature = "http-client")]
    if let Some(raw_url) = config.webhook_url.as_ref().filter(|s| !s.trim().is_empty()) {
        // TRIM the resolved webhook URL and treat the trimmed value as canonical:
        // a copied env var commonly carries leading/trailing whitespace, and the
        // runtime dispatch rule matches on `http://`/`https://` PREFIXES, so an
        // untrimmed `"  https://…"` would never be treated as absolute and every
        // POST would fail `reqwest::Url::parse`. Building the channel with the
        // trimmed URL also keeps doctor (which trims + validates) and the runtime
        // from disagreeing about whether the webhook is usable.
        let url = raw_url.trim();
        // Match the missing-secret check's trimming so the stored secret is the
        // canonical, whitespace-free value used to sign.
        let secret = config
            .webhook_secret
            .as_ref()
            .map(|s| s.trim())
            .filter(|s| !s.is_empty());
        // Reject an unusable webhook URL BEFORE registering the channel. Without
        // this, a relative/malformed value (or one whose whitespace an app that
        // doesn't run doctor never trims) installs a webhook channel that looks
        // configured but fails EVERY delivery at `build_request`. Mirror the
        // disabled-transport / missing-secret skip-and-warn pattern above.
        if !is_absolute_http_url(url) {
            tracing::warn!(
                webhook_url = url,
                "alerts: the configured [alerts] webhook_url ({url}) is not an absolute http(s) \
                 URL (it must start with `http://` or `https://` and have a host); no webhook \
                 alerts will be delivered. Fix [alerts] webhook_url (or the \
                 AUTUMN_ALERTS__WEBHOOK_URL env var)."
            );
        } else if let Some(secret) = secret {
            // Alert webhooks are ALWAYS signed: the operator guide documents
            // receivers verifying the `Autumn-Signature` header. A configured
            // webhook with no non-empty signing secret would send UNSIGNED
            // requests that a documented receiver rejects (or accepts
            // unauthenticated) — so refuse to register the channel and warn,
            // mirroring the disabled-mail-transport skip above. Never send
            // unsigned.
            let client = crate::http_client::Client::from_state(state);
            channels.push(Arc::new(WebhookAlertChannel::new(
                client,
                url.to_owned(),
                Some(secret.to_owned()),
            )));
        } else {
            tracing::warn!(
                "alerts: a webhook destination is configured but no `webhook_secret` is set; \
                 alert webhooks are always signed, so no webhook alerts will be delivered. Set \
                 [alerts] webhook_secret (or the AUTUMN_ALERTS__WEBHOOK_SECRET env var)."
            );
        }
    }
    // Without the `http-client` feature the webhook branch above is compiled out,
    // so a webhook-only config would silently install no channels and deliver no
    // alerts. Warn loudly so operators don't believe webhook alerts are active.
    #[cfg(not(feature = "http-client"))]
    if config
        .webhook_url
        .as_ref()
        .is_some_and(|s| !s.trim().is_empty())
    {
        tracing::warn!(
            "operator-alerts: a webhook destination is configured but the `http-client` feature \
             is not enabled; no webhook alerts will be delivered. Enable the `http-client` \
             feature or use an email destination."
        );
    }

    // Native provider transports (issue #1630): PagerDuty / Slack / Discord.
    push_native_transport_channels(state, config, &mut channels);

    channels.extend(extra_channels);

    if channels.is_empty() {
        return;
    }

    // Capture the effective actuator prefix AND the `sensitive` flag so every
    // alert's `where_to_look` points at a REAL, mounted actuator endpoint: the
    // prefix keeps custom-prefix deployments off `/actuator/*` 404s, and
    // `sensitive` keeps the dead-lettered-job/scheduled-task alerts off the
    // `/jobs` and `/tasks` endpoints, which are mounted only when `sensitive =
    // true`. The full config is installed on `state` before this runs.
    let actuator_cfg = state.config().actuator;
    let actuator_sensitive = actuator_cfg.sensitive;
    let actuator_prefix = actuator_cfg.prefix;
    let settings = AlerterSettings::from_config(config, actuator_prefix, actuator_sensitive);
    let alerter = Alerter::new(channels, settings);
    state.insert_extension(alerter.clone());
    spawn_evaluation_loop(state.clone(), alerter);
}

/// Spawn the background loop that evaluates the *pull-based* conditions:
/// health-indicator down-duration (b) and the rolling 5xx rate (c). Both are
/// evaluated off the request path so AC #6 (no request-path latency) holds.
fn spawn_evaluation_loop(state: AppState, alerter: Alerter) {
    let settings = alerter.settings().clone();
    tokio::spawn(async move {
        // Per-indicator: when it first went Down (None once it is Up again).
        let mut down_since: HashMap<String, DateTime<Utc>> = HashMap::new();
        // Prime the cumulative counters so the first tick measures a real delta.
        let (mut last_requests, mut last_5xx) = {
            let snap = state.metrics().snapshot();
            (snap.http.requests_total, snap.http.by_status.s5xx)
        };
        loop {
            tokio::time::sleep(settings.eval_interval).await;
            evaluate_error_rate(
                &alerter,
                &state,
                &settings,
                &mut last_requests,
                &mut last_5xx,
            );
            evaluate_health(&alerter, &state, &settings, &mut down_since).await;
        }
    });
}

/// Advance the 5xx sampling window for one tick.
///
/// Returns `Some((req_delta, err_delta))` — and advances the baseline counters
/// — only when the accumulated request delta has reached `min_requests`, i.e.
/// when a real evaluation should happen. When the tick is still below the
/// threshold it returns `None` and leaves the baselines **untouched**, so a
/// low-traffic app whose per-tick traffic never reaches `min_requests` keeps
/// accumulating requests across ticks instead of resetting every tick. The
/// window therefore measures "since the last evaluation" rather than "since the
/// last tick."
const fn sample_error_window(
    total: u64,
    s5xx: u64,
    last_requests: &mut u64,
    last_5xx: &mut u64,
    min_requests: u64,
) -> Option<(u64, u64)> {
    let req_delta = total.saturating_sub(*last_requests);
    if req_delta < min_requests {
        // Leave baselines untouched so counts accumulate across ticks.
        return None;
    }
    let err_delta = s5xx.saturating_sub(*last_5xx);
    *last_requests = total;
    *last_5xx = s5xx;
    Some((req_delta, err_delta))
}

/// Condition (c): compute the 5xx rate over the requests seen since the last
/// evaluation and compare to the threshold. Reads existing cumulative counters
/// — the request path is untouched.
fn evaluate_error_rate(
    alerter: &Alerter,
    state: &AppState,
    settings: &AlerterSettings,
    last_requests: &mut u64,
    last_5xx: &mut u64,
) {
    let snap = state.metrics().snapshot();
    let total = snap.http.requests_total;
    let s5xx = snap.http.by_status.s5xx;
    let Some((req_delta, err_delta)) = sample_error_window(
        total,
        s5xx,
        last_requests,
        last_5xx,
        settings.error_rate_min_requests,
    ) else {
        return;
    };
    #[allow(clippy::cast_precision_loss)]
    let rate = err_delta as f64 / req_delta as f64;
    // Host-scope the key: this rate is from the local process's metrics, so
    // each replica must own its incident (see `error_rate_dedup_key`). The
    // trigger and resolve below share this same `key`, so they still correlate.
    let key = error_rate_dedup_key(&host_id());
    if rate >= settings.error_rate_threshold {
        let pct = rate * 100.0;
        let threshold_pct = settings.error_rate_threshold * 100.0;
        let alert = Alert::trigger(AlertCondition::HighErrorRate, key)
            .title(format!("5xx error rate is {pct:.1}%"))
            .summary(format!(
                "{err_delta} of the last {req_delta} requests returned 5xx ({pct:.1}%), \
                 crossing the {threshold_pct:.1}% threshold."
            ))
            .where_to_look(actuator_where_to_look(
                &settings.actuator_prefix,
                AlertCondition::HighErrorRate,
            ))
            .detail("rate", format!("{rate:.4}"))
            .detail("errors", err_delta.to_string())
            .detail("requests", req_delta.to_string())
            .build();
        let _ = alerter.notify(alert);
    } else {
        let alert = Alert::recovery(AlertCondition::HighErrorRate, key)
            .title("5xx error rate recovered")
            .summary(format!(
                "The 5xx error rate is back under the threshold ({pct:.1}% of {req_delta} requests).",
                pct = rate * 100.0,
            ))
            .where_to_look(actuator_where_to_look(
                &settings.actuator_prefix,
                AlertCondition::HighErrorRate,
            ))
            .build();
        let _ = alerter.recover(alert);
    }
}

/// How a health indicator's current status maps onto the alert state machine.
///
/// Factored out of [`evaluate_health`] so the branch is unit-testable without an
/// `AppState`/registry. The decision hinges on [`HealthStatus::is_healthy`]: any
/// non-healthy status triggers, and only a genuinely healthy status recovers.
/// `OutOfService` is non-`Down` but still UNHEALTHY (`/actuator/health` reports
/// non-200), so it takes the **trigger** path — an indicator that reports
/// `OUT_OF_SERVICE` without ever passing through `Down` is still alerted. This
/// also preserves the no-false-recovery property: an already-alerted `Down`
/// indicator that dips to `OutOfService` stays unhealthy, so it stays active
/// instead of emitting a spurious "recovered".
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum HealthTransition {
    /// Status is not healthy (`Down`, `OutOfService`, or any other non-healthy
    /// variant): run the grace-period trigger logic.
    Trigger,
    /// Status is genuinely healthy again (`is_healthy()`): clear tracking and
    /// emit a recovery for any outstanding alert.
    Recover,
}

/// Classify a health indicator's status into the alert-state transition it
/// drives. Uses [`HealthStatus::is_healthy`] (not `== Up`/`== Down`) so `Unknown`
/// — which the actuator reports as healthy — recovers, while every non-healthy
/// status (`Down`, `OutOfService`, …) triggers.
const fn classify_health_transition(status: crate::actuator::HealthStatus) -> HealthTransition {
    if status.is_healthy() {
        HealthTransition::Recover
    } else {
        HealthTransition::Trigger
    }
}

/// Condition (b): run all health indicators, track how long each has been
/// non-healthy, and alert once an indicator has stayed non-healthy past the grace
/// period. The trigger fires for **any** non-healthy status (`Down`,
/// `OutOfService`, …), matching what `/actuator/health` reports as non-200.
/// Recover only when it reports a genuinely healthy status again — a still-unhealthy
/// status (e.g. `OutOfService` after `Down`) keeps the active alert rather than
/// emitting a false recovery.
async fn evaluate_health(
    alerter: &Alerter,
    state: &AppState,
    settings: &AlerterSettings,
    down_since: &mut HashMap<String, DateTime<Utc>>,
) {
    let results = state.health_indicator_registry().run_all().await;
    let now = Utc::now();
    let grace = chrono::Duration::from_std(settings.health_grace)
        .unwrap_or_else(|_| chrono::Duration::seconds(60));

    let host = host_id();
    for result in &results {
        // Host-scope the per-indicator key: health is evaluated from this
        // process's local registry, so each replica owns its incident (see
        // `health_indicator_dedup_key`). The trigger and resolve arms below
        // share this same `key`, so they still correlate.
        let key = health_indicator_dedup_key(&result.name, &host);
        match classify_health_transition(result.output.status) {
            HealthTransition::Trigger => {
                let status = result.output.status;
                let first = *down_since.entry(result.name.clone()).or_insert(now);
                if now - first >= grace {
                    let secs = (now - first).num_seconds().max(0);
                    let alert = Alert::trigger(AlertCondition::HealthIndicatorDown, key)
                        .title(format!("Health indicator '{}' is {status:?}", result.name))
                        .summary(format!(
                            "Health indicator '{}' has reported {status:?} for {secs}s, past the \
                             {grace_secs}s grace period.",
                            result.name,
                            grace_secs = settings.health_grace.as_secs(),
                        ))
                        .where_to_look(actuator_where_to_look(
                            &settings.actuator_prefix,
                            AlertCondition::HealthIndicatorDown,
                        ))
                        .detail("indicator", result.name.clone())
                        .detail("status", status.as_str())
                        .detail("down_seconds", secs.to_string())
                        .build();
                    let _ = alerter.notify(alert);
                }
            }
            HealthTransition::Recover => {
                // Only clear the down-tracking (and emit a recovery) when the
                // indicator is genuinely healthy again. `recover` is itself gated
                // by `on_resolve`, so it is a no-op unless an alert was active.
                if down_since.remove(&result.name).is_some() {
                    let alert = Alert::recovery(AlertCondition::HealthIndicatorDown, key)
                        .title(format!("Health indicator '{}' recovered", result.name))
                        .summary(format!(
                            "Health indicator '{}' is reporting healthy again.",
                            result.name
                        ))
                        .where_to_look(actuator_where_to_look(
                            &settings.actuator_prefix,
                            AlertCondition::HealthIndicatorDown,
                        ))
                        .detail("indicator", result.name.clone())
                        .build();
                    let _ = alerter.recover(alert);
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::Mutex as StdMutex;

    fn ts(secs: i64) -> DateTime<Utc> {
        DateTime::from_timestamp(1_700_000_000 + secs, 0).expect("valid timestamp")
    }

    // ── Dedup window bounding (AC #3) ────────────────────────────────────────

    #[test]
    fn first_trigger_sends() {
        let mut d = AlertDeduplicator::new(std::time::Duration::from_secs(900));
        assert_eq!(d.on_trigger("k", ts(0)), DedupDecision::Send);
    }

    #[test]
    fn repeated_triggers_within_window_are_suppressed() {
        let mut d = AlertDeduplicator::new(std::time::Duration::from_secs(900));
        assert_eq!(d.on_trigger("k", ts(0)), DedupDecision::Send);
        // Many occurrences inside the window -> all suppressed (not one-per).
        for s in 1..100 {
            assert_eq!(
                d.on_trigger("k", ts(s)),
                DedupDecision::Suppress,
                "occurrence at {s}s inside window must be suppressed"
            );
        }
    }

    #[test]
    fn trigger_renotifies_once_after_window_elapses() {
        let mut d = AlertDeduplicator::new(std::time::Duration::from_secs(900));
        assert_eq!(d.on_trigger("k", ts(0)), DedupDecision::Send);
        assert_eq!(d.on_trigger("k", ts(500)), DedupDecision::Suppress);
        // Window elapsed: exactly one re-notification.
        assert_eq!(d.on_trigger("k", ts(901)), DedupDecision::Send);
        assert_eq!(d.on_trigger("k", ts(902)), DedupDecision::Suppress);
    }

    #[test]
    fn distinct_keys_are_independent() {
        let mut d = AlertDeduplicator::new(std::time::Duration::from_secs(900));
        assert_eq!(d.on_trigger("a", ts(0)), DedupDecision::Send);
        assert_eq!(d.on_trigger("b", ts(0)), DedupDecision::Send);
    }

    // ── Recovery emission (AC #3) ────────────────────────────────────────────

    #[test]
    fn recovery_sends_only_for_active_key() {
        let mut d = AlertDeduplicator::new(std::time::Duration::from_secs(900));
        // Never triggered: no recovery.
        assert_eq!(d.on_resolve("k"), DedupDecision::Suppress);
        // Trigger, then recover once.
        assert_eq!(d.on_trigger("k", ts(0)), DedupDecision::Send);
        assert_eq!(d.on_resolve("k"), DedupDecision::Send);
        // Double-recover: suppressed.
        assert_eq!(d.on_resolve("k"), DedupDecision::Suppress);
    }

    #[test]
    fn trigger_after_recovery_alerts_immediately() {
        let mut d = AlertDeduplicator::new(std::time::Duration::from_secs(900));
        assert_eq!(d.on_trigger("k", ts(0)), DedupDecision::Send);
        assert_eq!(d.on_resolve("k"), DedupDecision::Send);
        // Fresh trigger inside the original window still sends because the key
        // recovered in between.
        assert_eq!(d.on_trigger("k", ts(10)), DedupDecision::Send);
    }

    // ── Health-indicator classification (P2: unhealthy triggers, healthy recovers)
    // The branch in `evaluate_health`: any non-healthy status (`Down`,
    // `OutOfService`, …) triggers the grace-period logic, and only a genuinely
    // healthy status recovers. This means `OutOfService` reached WITHOUT a prior
    // `Down` is still alerted, while a `Down`→`OutOfService` dip stays unhealthy
    // (no false recovery).

    use crate::actuator::HealthStatus;

    #[test]
    fn health_down_status_drives_trigger_branch() {
        assert_eq!(
            classify_health_transition(HealthStatus::Down),
            HealthTransition::Trigger
        );
    }

    #[test]
    fn healthy_statuses_recover() {
        // `is_healthy()` treats both `Up` and `Unknown` as healthy, so both
        // recover — the actuator reports 200 for either.
        assert_eq!(
            classify_health_transition(HealthStatus::Up),
            HealthTransition::Recover
        );
        assert_eq!(
            classify_health_transition(HealthStatus::Unknown),
            HealthTransition::Recover
        );
    }

    #[test]
    fn out_of_service_triggers_like_down() {
        // `OutOfService` is non-`Down` but still UNHEALTHY: it must take the
        // trigger path (not recover, not silently hold), so an indicator that
        // reports `OUT_OF_SERVICE` without ever going `Down` is still alerted.
        assert!(!HealthStatus::OutOfService.is_healthy());
        assert_eq!(
            classify_health_transition(HealthStatus::OutOfService),
            HealthTransition::Trigger
        );
    }

    /// What `evaluate_health` did for an indicator on a single tick. Lets the
    /// sequence tests distinguish a *trigger* send from a *recovery* send (an
    /// `Option<DedupDecision>` alone would conflate them).
    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    enum HealthTick {
        /// The trigger arm ran (non-healthy, past grace); carries the dedup
        /// decision (`Send` on first alert, `Suppress` while already active).
        Triggered(DedupDecision),
        /// The recover arm emitted a resolve for a previously-active key.
        Recovered(DedupDecision),
        /// Nothing was emitted (inside the grace window, or a healthy tick with
        /// no active alert to clear).
        Idle,
    }

    /// Drive the exact `down_since` + deduplicator bookkeeping `evaluate_health`
    /// performs for a single indicator across a status sequence, applying the
    /// given grace period, and reporting what happened on the FINAL tick. Proves
    /// both directions of the unified rule: any non-healthy status triggers, and
    /// recovery is gated on a genuinely healthy status (not merely `!= Down`).
    fn health_tick_for_sequence(statuses: &[HealthStatus], grace: chrono::Duration) -> HealthTick {
        let name = "db";
        let key = format!("health_indicator_down:{name}");
        let mut dedup = AlertDeduplicator::new(std::time::Duration::from_secs(900));
        let mut down_since: HashMap<String, DateTime<Utc>> = HashMap::new();
        let mut last = HealthTick::Idle;
        for (i, status) in statuses.iter().enumerate() {
            last = HealthTick::Idle;
            let now = ts(i64::try_from(i).unwrap());
            match classify_health_transition(*status) {
                HealthTransition::Trigger => {
                    let first = *down_since.entry(name.to_owned()).or_insert(now);
                    if now - first >= grace {
                        last = HealthTick::Triggered(dedup.on_trigger(&key, now));
                    }
                }
                HealthTransition::Recover => {
                    if down_since.remove(name).is_some() {
                        last = HealthTick::Recovered(dedup.on_resolve(&key));
                    }
                }
            }
        }
        last
    }

    /// Convenience wrapper: run [`health_tick_for_sequence`] with a zero grace
    /// period (so a single non-healthy tick alerts immediately). Used by the
    /// recovery-focused sequences below.
    fn recovery_tick_for_sequence(statuses: &[HealthStatus]) -> HealthTick {
        health_tick_for_sequence(statuses, chrono::Duration::seconds(0))
    }

    #[test]
    fn out_of_service_without_prior_down_triggers_after_grace() {
        // The former bug: an indicator that reports OutOfService WITHOUT ever
        // going Down was never alerted. Now it takes the trigger path, so once the
        // down-duration passes the grace period an alert fires (Send on the first
        // notification).
        let tick = recovery_tick_for_sequence(&[HealthStatus::OutOfService]);
        assert_eq!(
            tick,
            HealthTick::Triggered(DedupDecision::Send),
            "OutOfService with no prior Down must fire an alert once past the grace period"
        );
    }

    #[test]
    fn down_then_out_of_service_does_not_recover() {
        // Down (alert) → OutOfService: the alert stays active (the OutOfService
        // tick re-enters the trigger arm and is deduped as still-active) and NO
        // recovery is emitted — the service is still unhealthy.
        let tick = recovery_tick_for_sequence(&[HealthStatus::Down, HealthStatus::OutOfService]);
        assert_eq!(
            tick,
            HealthTick::Triggered(DedupDecision::Suppress),
            "OutOfService after Down must stay active (no recovery, deduped trigger)"
        );
    }

    #[test]
    fn down_then_up_recovers() {
        // Down (alert) → Up: a genuine recovery is emitted for the active key.
        let tick = recovery_tick_for_sequence(&[HealthStatus::Down, HealthStatus::Up]);
        assert_eq!(
            tick,
            HealthTick::Recovered(DedupDecision::Send),
            "a genuinely healthy status after Down must emit a recovery"
        );
    }

    #[test]
    fn down_then_out_of_service_then_up_recovers_once() {
        // The alert survives the OutOfService dip and recovers when finally Up.
        let tick = recovery_tick_for_sequence(&[
            HealthStatus::Down,
            HealthStatus::OutOfService,
            HealthStatus::Up,
        ]);
        assert_eq!(tick, HealthTick::Recovered(DedupDecision::Send));
    }

    #[test]
    fn brief_unhealthy_blip_inside_grace_window_does_not_alert() {
        // A single non-healthy tick that recovers before the grace period elapses
        // must NOT alert. With a 60s grace and consecutive 1s ticks, the lone
        // OutOfService tick is inside the window (no trigger fires), and the
        // following Up tick clears the tracking — but since no alert ever
        // triggered, the resolve is dedup-gated to `Suppress`, so no notification
        // is sent either way.
        let tick = health_tick_for_sequence(
            &[HealthStatus::OutOfService, HealthStatus::Up],
            chrono::Duration::seconds(60),
        );
        assert_eq!(
            tick,
            HealthTick::Recovered(DedupDecision::Suppress),
            "an unhealthy blip inside the grace window must not send a trigger, and its \
             resolve must be suppressed (no active alert to clear)"
        );
    }

    // ── Severity classification ──────────────────────────────────────────────

    #[test]
    fn trigger_is_critical_resolve_is_recovery() {
        let t = Alert::trigger(AlertCondition::DeadLetteredJob, "k").build();
        assert_eq!(t.severity, AlertSeverity::Critical);
        assert_eq!(t.event, AlertEventKind::Trigger);
        let r = Alert::recovery(AlertCondition::DeadLetteredJob, "k").build();
        assert_eq!(r.severity, AlertSeverity::Recovery);
        assert_eq!(r.event, AlertEventKind::Resolve);
    }

    #[test]
    fn where_to_look_defaults_per_condition() {
        assert_eq!(
            Alert::trigger(AlertCondition::DeadLetteredJob, "k")
                .build()
                .where_to_look,
            "/actuator/jobs"
        );
        assert_eq!(
            Alert::trigger(AlertCondition::HighErrorRate, "k")
                .build()
                .where_to_look,
            "/actuator/metrics"
        );
        assert_eq!(
            Alert::trigger(AlertCondition::HealthIndicatorDown, "k")
                .build()
                .where_to_look,
            "/actuator/health"
        );
        assert_eq!(
            Alert::trigger(AlertCondition::ScheduledTaskFailure, "k")
                .build()
                .where_to_look,
            "/actuator/tasks"
        );
    }

    #[test]
    fn actuator_where_to_look_honors_prefix() {
        // Default prefix reproduces the const builder default byte-for-byte.
        assert_eq!(
            actuator_where_to_look("/actuator", AlertCondition::DeadLetteredJob),
            "/actuator/jobs"
        );
        assert_eq!(
            actuator_where_to_look("/actuator", AlertCondition::HealthIndicatorDown),
            "/actuator/health"
        );
        // A custom prefix is honored for every condition.
        assert_eq!(
            actuator_where_to_look("/_ops", AlertCondition::DeadLetteredJob),
            "/_ops/jobs"
        );
        assert_eq!(
            actuator_where_to_look("/_ops", AlertCondition::HighErrorRate),
            "/_ops/metrics"
        );
        assert_eq!(
            actuator_where_to_look("/_ops", AlertCondition::ScheduledTaskFailure),
            "/_ops/tasks"
        );
        // Normalization matches the router: a trailing slash is trimmed and a
        // missing leading slash is added, so no `//` or missing-slash paths.
        assert_eq!(
            actuator_where_to_look("_ops/", AlertCondition::HealthIndicatorDown),
            "/_ops/health"
        );
        // Root ("/" or empty) prefix yields the bare suffix, matching the router.
        assert_eq!(
            actuator_where_to_look("/", AlertCondition::DeadLetteredJob),
            "/jobs"
        );
    }

    #[test]
    fn sensitive_gated_where_to_look_points_at_mounted_endpoint() {
        // `sensitive = true`: `/jobs` and `/tasks` ARE mounted, so point at them.
        assert_eq!(
            sensitive_gated_where_to_look("/actuator", AlertCondition::DeadLetteredJob, true),
            "/actuator/jobs"
        );
        assert_eq!(
            sensitive_gated_where_to_look("/actuator", AlertCondition::ScheduledTaskFailure, true),
            "/actuator/tasks"
        );

        // `sensitive = false` (the production default): `/jobs` and `/tasks` are
        // NOT mounted (404). The pointer must NOT link them directly — it points
        // at the always-mounted `/health` and names the setting that would expose
        // the richer endpoint.
        let dead =
            sensitive_gated_where_to_look("/actuator", AlertCondition::DeadLetteredJob, false);
        assert!(
            !dead.starts_with("/actuator/jobs"),
            "must not link the unmounted /jobs endpoint directly: {dead}"
        );
        assert!(
            dead.contains("/actuator/health"),
            "must point at the always-mounted /health endpoint: {dead}"
        );
        assert!(
            dead.contains("/actuator/jobs") && dead.contains("[actuator] sensitive = true"),
            "must hint that /jobs requires enabling [actuator] sensitive: {dead}"
        );

        let task =
            sensitive_gated_where_to_look("/actuator", AlertCondition::ScheduledTaskFailure, false);
        assert!(
            !task.starts_with("/actuator/tasks"),
            "must not link the unmounted /tasks endpoint directly: {task}"
        );
        assert!(
            task.contains("/actuator/health"),
            "must point at the always-mounted /health endpoint: {task}"
        );
        assert!(
            task.contains("/actuator/tasks") && task.contains("[actuator] sensitive = true"),
            "must hint that /tasks requires enabling [actuator] sensitive: {task}"
        );

        // The custom prefix flows through both the fallback and the hint.
        let custom = sensitive_gated_where_to_look("/_ops", AlertCondition::DeadLetteredJob, false);
        assert!(custom.contains("/_ops/health"));
        assert!(custom.contains("/_ops/jobs"));
    }

    #[test]
    fn stable_dedup_key_survives_trigger_and_recovery() {
        let key = "dead_lettered_job:emailer";
        let t = Alert::trigger(AlertCondition::DeadLetteredJob, key).build();
        let r = Alert::recovery(AlertCondition::DeadLetteredJob, key).build();
        assert_eq!(t.dedup_key, r.dedup_key);
    }

    // ── Host-scoped dedup keys for the process-local conditions (P2) ──────────
    // The 5xx-rate and health-indicator-down conditions are evaluated from THIS
    // process's local metrics/registry, so their dedup keys carry the host id:
    // two replicas produce DIFFERENT keys (their incidents stay distinct), while
    // a single replica's trigger and resolve — same process, same `host_id()` —
    // produce the SAME key so a consumer still correlates them.

    #[test]
    fn error_rate_dedup_key_is_host_scoped() {
        // Different hosts -> different keys (incidents stay separate per replica).
        assert_ne!(
            error_rate_dedup_key("replica-a"),
            error_rate_dedup_key("replica-b"),
            "two replicas must not share the 5xx dedup key"
        );
        // Same host -> the trigger and its later resolve (both in-process) match.
        let host = "replica-a";
        let trigger_key = error_rate_dedup_key(host);
        let resolve_key = error_rate_dedup_key(host);
        assert_eq!(
            trigger_key, resolve_key,
            "same-host trigger and resolve must correlate"
        );
        // The host is appended to the existing key format.
        assert_eq!(trigger_key, "high_error_rate:5xx:replica-a");
    }

    #[test]
    fn health_indicator_dedup_key_is_host_scoped() {
        // Different hosts -> different keys for the same indicator.
        assert_ne!(
            health_indicator_dedup_key("db", "replica-a"),
            health_indicator_dedup_key("db", "replica-b"),
            "two replicas must not share a health dedup key for the same indicator"
        );
        // Different indicators on the same host also stay distinct.
        assert_ne!(
            health_indicator_dedup_key("db", "replica-a"),
            health_indicator_dedup_key("cache", "replica-a"),
        );
        // Same host + indicator -> the trigger and its resolve match.
        let host = "replica-a";
        let trigger_key = health_indicator_dedup_key("db", host);
        let resolve_key = health_indicator_dedup_key("db", host);
        assert_eq!(
            trigger_key, resolve_key,
            "same-host trigger and resolve must correlate"
        );
        // The host is appended to the existing per-indicator key format.
        assert_eq!(trigger_key, "health_indicator_down:db:replica-a");
    }

    // ── Fan-out (delivery to every channel) ──────────────────────────────────

    #[derive(Default)]
    struct CapturingChannel {
        received: Arc<StdMutex<Vec<Alert>>>,
        name: &'static str,
    }

    impl AlertChannel for CapturingChannel {
        fn name(&self) -> &'static str {
            self.name
        }
        fn deliver<'a>(&'a self, alert: &'a Alert) -> AlertDeliveryFuture<'a> {
            let received = Arc::clone(&self.received);
            let cloned = alert.clone();
            Box::pin(async move {
                received.lock().expect("lock").push(cloned);
                Ok(())
            })
        }
    }

    fn settings() -> AlerterSettings {
        AlerterSettings {
            dedup_window: std::time::Duration::from_secs(900),
            health_grace: std::time::Duration::from_secs(60),
            error_rate_threshold: 0.05,
            error_rate_min_requests: 20,
            eval_interval: std::time::Duration::from_secs(30),
            actuator_prefix: "/actuator".to_owned(),
            actuator_sensitive: false,
        }
    }

    #[tokio::test]
    async fn dispatch_fans_out_to_all_channels() {
        let a = Arc::new(StdMutex::new(Vec::new()));
        let b = Arc::new(StdMutex::new(Vec::new()));
        let channels: Vec<Arc<dyn AlertChannel>> = vec![
            Arc::new(CapturingChannel {
                received: Arc::clone(&a),
                name: "a",
            }),
            Arc::new(CapturingChannel {
                received: Arc::clone(&b),
                name: "b",
            }),
        ];
        let alerter = Alerter::new(channels, settings());
        assert!(
            alerter.notify(
                Alert::trigger(AlertCondition::DeadLetteredJob, "dead_lettered_job:x")
                    .title("x failed")
                    .build()
            )
        );
        // Let the detached task run.
        tokio::task::yield_now().await;
        tokio::time::sleep(std::time::Duration::from_millis(20)).await;
        assert_eq!(a.lock().expect("lock").len(), 1);
        assert_eq!(b.lock().expect("lock").len(), 1);
        assert_eq!(a.lock().expect("lock")[0].title, "x failed");
    }

    #[tokio::test]
    async fn sustained_condition_dispatches_once_per_window() {
        let seen = Arc::new(StdMutex::new(Vec::new()));
        let channels: Vec<Arc<dyn AlertChannel>> = vec![Arc::new(CapturingChannel {
            received: Arc::clone(&seen),
            name: "cap",
        })];
        let alerter = Alerter::new(channels, settings());
        // 50 occurrences of the same condition in quick succession.
        let mut sent = 0;
        for _ in 0..50 {
            if alerter.notify(
                Alert::trigger(AlertCondition::HighErrorRate, "high_error_rate:5xx").build(),
            ) {
                sent += 1;
            }
        }
        assert_eq!(sent, 1, "sustained condition must alert once per window");
        tokio::time::sleep(std::time::Duration::from_millis(20)).await;
        assert_eq!(seen.lock().expect("lock").len(), 1);
    }

    #[test]
    fn config_active_requires_enabled_and_destination() {
        let mut c = AlertConfig::default();
        assert!(!c.is_active(), "no destination -> inactive");
        c.email = Some("ops@example.com".to_owned());
        assert!(c.is_active());
        c.enabled = false;
        assert!(!c.is_active(), "disabled -> inactive even with destination");
    }

    // ── 5xx error_rate_threshold sanitization (P2) ───────────────────────────
    // The threshold is compared against a FRACTION in [0, 1] (rate = err/req),
    // so only (0, 1] is meaningful. A non-finite value or one > 1 makes the
    // alert never fire; a value <= 0 makes it fire on 0%-error windows. Any such
    // value falls back to the default so 5xx alerting stays functional.

    fn from_config_with_threshold(threshold: f64) -> AlerterSettings {
        let config = AlertConfig {
            error_rate_threshold: threshold,
            ..AlertConfig::default()
        };
        AlerterSettings::from_config(&config, "/actuator".to_owned(), false)
    }

    // Compare two f64s for the EXACT equality these tests intend (the sanitizer
    // returns either the verbatim input or the bit-identical default constant), by
    // bit pattern — avoids `clippy::float_cmp` while staying exact.
    fn assert_threshold_eq(actual: f64, expected: f64, msg: &str) {
        assert_eq!(actual.to_bits(), expected.to_bits(), "{msg}");
    }

    #[test]
    fn valid_error_rate_threshold_is_kept() {
        // An in-range finite value is preserved verbatim.
        assert_threshold_eq(
            from_config_with_threshold(0.2).error_rate_threshold,
            0.2,
            "a valid (0, 1] threshold must be kept",
        );
        // The boundary value 1.0 (100% of requests) is valid.
        assert_threshold_eq(
            from_config_with_threshold(1.0).error_rate_threshold,
            1.0,
            "the boundary 1.0 must be kept",
        );
    }

    #[test]
    fn nan_error_rate_threshold_falls_back_to_default() {
        assert_threshold_eq(
            from_config_with_threshold(f64::NAN).error_rate_threshold,
            default_error_rate_threshold(),
            "NaN threshold must fall back to the default (can't be clamped)",
        );
        // Infinities are non-finite too and must fall back.
        assert_threshold_eq(
            from_config_with_threshold(f64::INFINITY).error_rate_threshold,
            default_error_rate_threshold(),
            "infinity threshold must fall back to the default",
        );
    }

    #[test]
    fn out_of_range_error_rate_threshold_falls_back_to_default() {
        // > 1: the alert would NEVER fire (no rate can reach it).
        assert_threshold_eq(
            from_config_with_threshold(1.5).error_rate_threshold,
            default_error_rate_threshold(),
            "a threshold > 1 must fall back to the default",
        );
        // <= 0: the alert would fire even on a 0%-error window.
        assert_threshold_eq(
            from_config_with_threshold(0.0).error_rate_threshold,
            default_error_rate_threshold(),
            "a zero threshold must fall back to the default",
        );
        assert_threshold_eq(
            from_config_with_threshold(-0.1).error_rate_threshold,
            default_error_rate_threshold(),
            "a negative threshold must fall back to the default",
        );
    }

    #[test]
    fn sanitized_threshold_behaves_as_default_in_comparison() {
        // A valid threshold fires for a rate at/above it and not below (the
        // runtime gate is `rate >= threshold`).
        let valid = from_config_with_threshold(0.10).error_rate_threshold;
        assert!(0.10 >= valid, "a rate at the threshold fires");
        assert!(0.05 < valid, "a rate below the threshold does not fire");
        // The sanitized (bad) threshold compares exactly like the default: a rate
        // at/above the DEFAULT fires, one below does not — the 5xx alert stays
        // functional rather than silently broken.
        let sanitized = from_config_with_threshold(f64::NAN).error_rate_threshold;
        let default = default_error_rate_threshold();
        assert!(default >= sanitized, "a rate at the default fires");
        assert!(
            default - 0.001 < sanitized,
            "a rate below the default does not"
        );
    }

    #[test]
    fn sub_threshold_ticks_accumulate_until_window_crosses_min_requests() {
        // min_requests = 10; each tick adds 4 requests (below threshold) with
        // 1 new 5xx. Baselines must NOT reset on the sub-threshold ticks so the
        // requests accumulate until the summed window finally crosses 10.
        let min_requests = 10;
        let mut last_requests = 0;
        let mut last_5xx = 0;

        // Tick 1: total=4, 5xx=1 -> below threshold, no evaluation.
        assert_eq!(
            sample_error_window(4, 1, &mut last_requests, &mut last_5xx, min_requests),
            None,
            "first sub-threshold tick must not evaluate"
        );
        // Baselines must be untouched so progress is preserved.
        assert_eq!(
            last_requests, 0,
            "sub-threshold tick must not reset baseline"
        );
        assert_eq!(
            last_5xx, 0,
            "sub-threshold tick must not reset 5xx baseline"
        );

        // Tick 2: total=8, 5xx=2 -> still below threshold (delta from 0 is 8).
        assert_eq!(
            sample_error_window(8, 2, &mut last_requests, &mut last_5xx, min_requests),
            None,
            "second sub-threshold tick must not evaluate"
        );
        assert_eq!(last_requests, 0);
        assert_eq!(last_5xx, 0);

        // Tick 3: total=12, 5xx=3 -> accumulated delta 12 >= 10, evaluate now
        // over the whole accumulated window (12 requests, 3 errors).
        assert_eq!(
            sample_error_window(12, 3, &mut last_requests, &mut last_5xx, min_requests),
            Some((12, 3)),
            "window must evaluate once summed requests cross the threshold"
        );
        // Only now do the baselines advance to the evaluated point.
        assert_eq!(last_requests, 12, "baseline advances only after evaluation");
        assert_eq!(last_5xx, 3);

        // Next sub-threshold tick starts a fresh accumulation from 12.
        assert_eq!(
            sample_error_window(15, 3, &mut last_requests, &mut last_5xx, min_requests),
            None
        );
        assert_eq!(
            last_requests, 12,
            "baseline held across the next sub-threshold tick"
        );
        assert_eq!(last_5xx, 3);
    }

    #[cfg(feature = "http-client")]
    #[test]
    fn is_absolute_http_url_matches_runtime_absoluteness() {
        // Both schemes are accepted (runtime dispatches either verbatim), with no
        // TLS requirement and query/fragment allowed.
        assert!(is_absolute_http_url(
            "https://alerts.example.com/hooks/autumn"
        ));
        assert!(is_absolute_http_url(
            "http://alerts.example.com/hooks/autumn"
        ));
        assert!(is_absolute_http_url("http://h.example.com:8080/x?a=1#f"));
        // Relative / malformed / non-http / empty-host values are rejected.
        assert!(!is_absolute_http_url("hooks.example/x"));
        assert!(!is_absolute_http_url("/hooks/autumn"));
        assert!(!is_absolute_http_url("ftp://h.example.com/x"));
        assert!(!is_absolute_http_url("https://"));
        assert!(!is_absolute_http_url(""));
    }

    #[test]
    fn alert_serializes_to_json_for_webhook() {
        let alert = Alert::trigger(AlertCondition::DeadLetteredJob, "dead_lettered_job:x")
            .title("x failed")
            .detail("job", "x")
            .build();
        let v: serde_json::Value = serde_json::to_value(&alert).expect("serialize");
        assert_eq!(v["dedup_key"], "dead_lettered_job:x");
        assert_eq!(v["condition"], "dead_lettered_job");
        assert_eq!(v["severity"], "critical");
        assert_eq!(v["event"], "trigger");
        assert_eq!(v["where_to_look"], "/actuator/jobs");
    }

    // ── Per-channel severity routing (#1630) ─────────────────────────────────

    #[test]
    fn alert_routing_accepts_matches_severity() {
        // `All` receives both a firing alert and its recovery.
        assert!(AlertRouting::All.accepts(AlertSeverity::Critical));
        assert!(AlertRouting::All.accepts(AlertSeverity::Recovery));
        // `Critical` receives only firing alerts; a recovery is NOT delivered.
        assert!(AlertRouting::Critical.accepts(AlertSeverity::Critical));
        assert!(!AlertRouting::Critical.accepts(AlertSeverity::Recovery));
    }

    #[test]
    fn alert_routing_defaults_to_all() {
        assert_eq!(AlertRouting::default(), AlertRouting::All);
    }

    #[test]
    fn routing_deserializes_from_toml() {
        #[derive(Deserialize)]
        struct Holder {
            r: AlertRouting,
        }
        let all: Holder = toml::from_str(r#"r = "all""#).expect("parse all");
        assert_eq!(all.r, AlertRouting::All);
        let crit: Holder = toml::from_str(r#"r = "critical""#).expect("parse critical");
        assert_eq!(crit.r, AlertRouting::Critical);
    }

    #[test]
    fn routing_from_str_matches_toml_spellings() {
        // The env-override path parses via FromStr; it must accept exactly the
        // same `all` / `critical` spellings the TOML/serde path does, and reject
        // anything else (the env layer then logs+ignores, keeping the default).
        assert_eq!("all".parse::<AlertRouting>(), Ok(AlertRouting::All));
        assert_eq!(
            "critical".parse::<AlertRouting>(),
            Ok(AlertRouting::Critical)
        );
        assert!("warning".parse::<AlertRouting>().is_err());
        assert!("All".parse::<AlertRouting>().is_err());
        assert!("".parse::<AlertRouting>().is_err());
    }

    // ── Native transport payloads (#1630) ────────────────────────────────────

    #[cfg(feature = "http-client")]
    #[test]
    fn pagerduty_trigger_payload_is_events_v2_shaped() {
        let alert = Alert::trigger(AlertCondition::DeadLetteredJob, "dead_lettered_job:emailer")
            .title("Job 'emailer' was dead-lettered")
            .summary("exhausted retries")
            .detail("job", "emailer")
            .build();
        let v = pagerduty_event_payload(&alert, "R0UT1NGKEY");
        assert_eq!(v["routing_key"], "R0UT1NGKEY");
        assert_eq!(v["event_action"], "trigger");
        // Stable dedup key correlates repeats into one incident.
        assert_eq!(v["dedup_key"], "dead_lettered_job:emailer");
        assert_eq!(v["payload"]["severity"], "critical");
        assert_eq!(v["payload"]["source"], alert.host);
        assert_eq!(v["payload"]["summary"], "Job 'emailer' was dead-lettered");
        assert_eq!(v["payload"]["component"], "dead_lettered_job");
        // Custom details carry the routing/where-to-look context.
        assert_eq!(
            v["payload"]["custom_details"]["condition"],
            "dead_lettered_job"
        );
        assert_eq!(
            v["payload"]["custom_details"]["where_to_look"],
            "/actuator/jobs"
        );
        assert_eq!(v["payload"]["custom_details"]["job"], "emailer");
    }

    #[cfg(feature = "http-client")]
    #[test]
    fn pagerduty_custom_details_preserves_user_key_colliding_with_reserved_field() {
        // A user detail keyed with a RESERVED standard-field name (`condition`,
        // `where_to_look`, `detail`) must not silently clobber — nor be clobbered
        // by — the authoritative standard field. The standard field keeps its
        // canonical name (PagerDuty routing/correlation depends on it); the user's
        // value is preserved under a `custom_`-prefixed key.
        let alert = Alert::trigger(AlertCondition::DeadLetteredJob, "dead_lettered_job:emailer")
            .title("Job 'emailer' was dead-lettered")
            .summary("exhausted retries")
            .detail("condition", "user-supplied-condition")
            .detail("where_to_look", "user-supplied-pointer")
            .detail("detail", "user-supplied-detail")
            .build();
        let v = pagerduty_event_payload(&alert, "R0UT1NGKEY");
        let cd = &v["payload"]["custom_details"];
        // Standard fields stay authoritative under their canonical names.
        assert_eq!(cd["condition"], "dead_lettered_job");
        assert_eq!(cd["where_to_look"], "/actuator/jobs");
        assert_eq!(cd["detail"], "exhausted retries");
        // The colliding user values are preserved under `custom_<key>`.
        assert_eq!(cd["custom_condition"], "user-supplied-condition");
        assert_eq!(cd["custom_where_to_look"], "user-supplied-pointer");
        assert_eq!(cd["custom_detail"], "user-supplied-detail");
    }

    #[cfg(feature = "http-client")]
    #[test]
    fn pagerduty_resolve_payload_is_minimal_and_correlates() {
        let alert = Alert::recovery(
            AlertCondition::ScheduledTaskFailure,
            "scheduled_task_failure:backup",
        )
        .title("Scheduled task 'backup' recovered")
        .build();
        let v = pagerduty_event_payload(&alert, "R0UT1NGKEY");
        assert_eq!(v["event_action"], "resolve");
        // Same dedup key as its trigger → the correlated incident auto-resolves.
        assert_eq!(v["dedup_key"], "scheduled_task_failure:backup");
        // A resolve carries no payload block per the Events API v2 contract.
        assert!(v.get("payload").is_none(), "resolve must omit payload: {v}");
    }

    #[cfg(feature = "http-client")]
    #[test]
    fn slack_payload_carries_required_operator_fields() {
        let alert = Alert::trigger(AlertCondition::HighErrorRate, "high_error_rate:5xx:h1")
            .title("5xx error rate is 12.0%")
            .summary("60 of the last 500 requests returned 5xx")
            .where_to_look("/actuator/metrics")
            .detail("rate", "0.1200")
            .build();
        let v = slack_message_payload(&alert);
        let text = v["text"].as_str().expect("text field");
        // #1610 required fields: what failed, when, host/replica, where to look.
        assert!(text.contains("5xx error rate is 12.0%"), "title: {text}");
        assert!(text.contains(&alert.host), "host: {text}");
        assert!(text.contains("/actuator/metrics"), "where_to_look: {text}");
        assert!(
            text.contains(&alert.timestamp.to_rfc3339()),
            "timestamp: {text}"
        );
        assert!(text.contains("rate: 0.1200"), "details: {text}");
    }

    #[cfg(feature = "http-client")]
    #[test]
    fn pagerduty_channel_accepts_severity_reflects_routing() {
        let crit = PagerDutyAlertChannel::new(
            crate::http_client::Client::new(),
            PAGERDUTY_EVENTS_URL,
            "k",
            AlertRouting::Critical,
        );
        assert_eq!(crit.name(), "pagerduty");
        assert!(crit.accepts_severity(AlertSeverity::Critical));
        assert!(!crit.accepts_severity(AlertSeverity::Recovery));
    }

    #[cfg(feature = "http-client")]
    #[test]
    fn slack_and_discord_channels_name_and_route() {
        let slack = SlackAlertChannel::slack(
            crate::http_client::Client::new(),
            "https://hooks.slack.com/services/x",
            AlertRouting::Critical,
        );
        assert_eq!(slack.name(), "slack");
        assert!(!slack.accepts_severity(AlertSeverity::Recovery));
        let discord = SlackAlertChannel::discord(
            crate::http_client::Client::new(),
            "https://discord.com/api/webhooks/x/y/slack",
            AlertRouting::All,
        );
        assert_eq!(discord.name(), "discord");
        assert!(discord.accepts_severity(AlertSeverity::Recovery));
    }

    // ── native_transport_channels construction / skips (#1630) ───────────────

    #[cfg(feature = "http-client")]
    fn channel_names(config: &AlertConfig) -> Vec<&'static str> {
        let client = crate::http_client::Client::new();
        native_transport_channels(config, &client)
            .iter()
            .map(|c| c.name())
            .collect()
    }

    #[cfg(feature = "http-client")]
    #[test]
    fn native_transports_build_all_three_when_configured() {
        let config = AlertConfig {
            pagerduty_routing_key: Some("R0UT1NGKEY".to_owned()),
            slack_webhook_url: Some("https://hooks.slack.com/services/x".to_owned()),
            discord_webhook_url: Some("https://discord.com/api/webhooks/x/y/slack".to_owned()),
            ..AlertConfig::default()
        };
        let names = channel_names(&config);
        assert!(names.contains(&"pagerduty"), "{names:?}");
        assert!(names.contains(&"slack"), "{names:?}");
        assert!(names.contains(&"discord"), "{names:?}");
    }

    #[cfg(feature = "http-client")]
    #[test]
    fn native_transports_skip_blank_routing_key_and_relative_urls() {
        let config = AlertConfig {
            pagerduty_routing_key: Some("   ".to_owned()),
            slack_webhook_url: Some("hooks.slack/x".to_owned()),
            discord_webhook_url: Some("/relative".to_owned()),
            ..AlertConfig::default()
        };
        assert!(
            channel_names(&config).is_empty(),
            "a blank routing key and relative URLs must register no channel"
        );
    }

    #[cfg(feature = "http-client")]
    #[test]
    fn native_transports_skip_non_absolute_pagerduty_url() {
        let config = AlertConfig {
            pagerduty_routing_key: Some("R0UT1NGKEY".to_owned()),
            pagerduty_url: Some("events.pagerduty.com/v2/enqueue".to_owned()),
            ..AlertConfig::default()
        };
        assert!(
            channel_names(&config).is_empty(),
            "a non-absolute pagerduty_url must skip the PagerDuty channel"
        );
    }

    #[cfg(feature = "http-client")]
    #[test]
    fn native_transports_reject_non_https_slack_and_discord() {
        // Slack and Discord only expose https webhook endpoints, so a plaintext
        // http:// URL will not deliver (and would transmit insecurely). The
        // runtime must reject it — mirroring `autumn doctor` — and register no
        // channel. Prevents a config doctor rejects from silently "passing" at
        // runtime.
        let slack = AlertConfig {
            slack_webhook_url: Some("http://hooks.slack.com/services/x".to_owned()),
            ..AlertConfig::default()
        };
        assert!(
            channel_names(&slack).is_empty(),
            "a non-https slack_webhook_url must not register a Slack channel"
        );
        let discord = AlertConfig {
            discord_webhook_url: Some("http://discord.com/api/webhooks/x/slack".to_owned()),
            ..AlertConfig::default()
        };
        assert!(
            channel_names(&discord).is_empty(),
            "a non-https discord_webhook_url must not register a Discord channel"
        );
        // An absolute https URL is still accepted.
        let ok = AlertConfig {
            slack_webhook_url: Some("https://hooks.slack.com/services/x".to_owned()),
            ..AlertConfig::default()
        };
        assert_eq!(channel_names(&ok), vec!["slack"]);
    }

    #[cfg(feature = "http-client")]
    #[test]
    fn has_destination_counts_native_transports() {
        let pd = AlertConfig {
            pagerduty_routing_key: Some("k".to_owned()),
            ..AlertConfig::default()
        };
        assert!(pd.has_destination() && pd.is_active());
        let slack = AlertConfig {
            slack_webhook_url: Some("https://hooks.slack.com/x".to_owned()),
            ..AlertConfig::default()
        };
        assert!(slack.has_destination());
        assert!(!AlertConfig::default().has_destination());
    }

    // ── Delivery through the mocked SSRF-hardened client (#1630) ──────────────

    #[cfg(feature = "http-client")]
    #[tokio::test]
    async fn pagerduty_channel_delivers_trigger_to_events_endpoint() {
        use crate::http_client::{Client, MockEntry, MockRegistry};
        use std::sync::atomic::AtomicUsize;

        let registry = Arc::new(MockRegistry::new());
        let calls = Arc::new(AtomicUsize::new(0));
        registry.register(MockEntry {
            method: Some(reqwest::Method::POST),
            path: "/v2/enqueue".to_owned(),
            alias: None,
            status: 202,
            body: Some(serde_json::json!({"status": "success"})),
            call_count: calls.clone(),
        });
        let client = Client::new().with_mock(registry);
        let channel = PagerDutyAlertChannel::new(
            client,
            PAGERDUTY_EVENTS_URL,
            "R0UT1NGKEY",
            AlertRouting::All,
        );
        let alert = Alert::trigger(AlertCondition::DeadLetteredJob, "dead_lettered_job:x")
            .title("x failed")
            .build();
        channel.deliver(&alert).await.expect("delivered");
        assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 1);
    }

    #[cfg(feature = "http-client")]
    #[tokio::test]
    async fn slack_channel_reports_non_2xx_as_delivery_error() {
        use crate::http_client::{Client, MockEntry, MockRegistry};
        use std::sync::atomic::AtomicUsize;

        let registry = Arc::new(MockRegistry::new());
        registry.register(MockEntry {
            method: Some(reqwest::Method::POST),
            path: "/services/x".to_owned(),
            alias: None,
            status: 500,
            body: None,
            call_count: Arc::new(AtomicUsize::new(0)),
        });
        let client = Client::new().with_mock(registry);
        let channel = SlackAlertChannel::slack(
            client,
            "https://hooks.slack.com/services/x",
            AlertRouting::All,
        );
        let alert = Alert::trigger(AlertCondition::HighErrorRate, "high_error_rate:5xx").build();
        let err = channel
            .deliver(&alert)
            .await
            .expect_err("must error on 500");
        assert_eq!(err.channel, "slack");
    }
}