rama-net 0.4.0

rama network types and utilities
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
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
//! Route client requests through the operating system's proxy settings.

use std::{
    fmt,
    sync::{
        Arc, OnceLock,
        atomic::{AtomicU64, Ordering},
    },
    time::{Duration, Instant},
};

use arc_swap::ArcSwapOption;
use rama_core::{
    Layer, Service,
    error::{BoxError, BoxErrorExt as _, ErrorContext},
    error_sink::{ErrorSink, TracingErrorSink},
    extensions::{Extensions, ExtensionsRef},
    service::{BoxService, service_fn},
};
use rama_utils::macros::generate_set_and_with;

#[cfg(any(
    test,
    target_vendor = "apple",
    target_os = "android",
    target_os = "linux",
    target_os = "freebsd",
    target_os = "netbsd",
    target_os = "openbsd",
    target_os = "dragonfly"
))]
use crate::address::{Host, HostWithPort};
use crate::{
    Protocol,
    address::{Authority, HostRef, HostWithOptPort, ProxyAddress},
    input_ext::{AuthorityInputExt, ProtocolInputExt, UriInputExt},
    uri::Uri,
};

use super::{
    ProxyRoute, ProxyRoutes,
    bypass::{BypassRule, BypassRuleDialect, is_simple_hostname, matches_any_rule},
    load::LoadErrorPolicy,
};

mod platform;

/// How long a [`SystemProxyLayer`] keeps a system proxy snapshot before lazily
/// checking for changes.
///
/// The ten-second default follows the polling interval used by
/// [Chromium's Windows proxy configuration service][chromium] where change
/// notifications alone are insufficient. Use
/// [`SystemProxyLayer::new_with_ttl`] to select a different value.
///
/// [chromium]: https://chromium.googlesource.com/chromium/src/+/refs/heads/main/net/proxy_resolution/win/proxy_config_service_win.cc
pub const DEFAULT_SYSTEM_PROXY_CONFIG_TTL: Duration = Duration::from_secs(10);

/// How system proxy discovery handles bypass rules Rama cannot parse.
///
/// This policy applies independently of whether a platform uses ordinary or
/// reversed bypass-list semantics. Rejecting invalid rules prevents a partial
/// snapshot from making routing decisions with a different rule set than the
/// operating system supplied.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum SystemProxyInvalidBypassRulePolicy {
    /// Ignore an invalid rule and retain the rest of the system snapshot.
    #[default]
    Ignore,
    /// Reject the complete system snapshot when any bypass rule is invalid.
    Reject,
}

/// The request information passed to a system PAC resolver.
///
/// When produced by [`SystemProxyLayer`], the URI is absolute, has a root path
/// when the original target omitted one, and omits the scheme's default port.
/// The extension store is a cheap clone of the input's store. This keeps caller
/// metadata available to custom PAC implementations without borrowing the
/// request across an await point.
#[derive(Debug, Clone)]
pub struct SystemProxyPacRequest {
    /// Metadata cloned from the routed service input.
    pub extensions: Extensions,
    /// The normalized absolute URI for which routes are requested.
    pub uri: Uri,
}

impl SystemProxyPacRequest {
    /// Create a PAC request from an absolute request URI and its extensions.
    pub fn new(extensions: Extensions, uri: Uri) -> Result<Self, BoxError> {
        if !uri.is_absolute() || uri.host().is_none() {
            return Err(BoxError::from_static_str(
                "system proxy PAC request URI must be absolute and have a host",
            ));
        }
        Ok(Self { extensions, uri })
    }
}

impl ExtensionsRef for SystemProxyPacRequest {
    fn extensions(&self) -> &Extensions {
        &self.extensions
    }
}

impl UriInputExt for SystemProxyPacRequest {
    fn uri(&self) -> &Uri {
        &self.uri
    }
}

/// Resolves proxy routes for a request using one system-configured PAC script.
///
/// Returning `None` asks the system layer to try the fixed proxy settings from
/// the same snapshot, if any, and otherwise leave the request unchanged.
/// The blanket implementation accepts any resolver error that converts into
/// [`BoxError`]. Implementations may return a concrete service; no allocation
/// or type erasure is required.
pub trait SystemProxyPacResolver:
    Service<SystemProxyPacRequest, Output = Option<ProxyRoutes>, Error: Into<BoxError>>
{
}

impl<T> SystemProxyPacResolver for T where
    T: Service<SystemProxyPacRequest, Output = Option<ProxyRoutes>, Error: Into<BoxError>>
{
}

/// Supplies a resolver for a system-configured PAC URI.
///
/// The blanket implementation accepts any factory and resolver errors that
/// convert into [`BoxError`]. The resolver output remains concrete so
/// implementations can choose their own caching and sharing strategy.
pub trait SystemProxyPacService:
    Service<Uri, Error: Into<BoxError>, Output: SystemProxyPacResolver>
{
}

impl<T> SystemProxyPacService for T where
    T: Service<Uri, Error: Into<BoxError>, Output: SystemProxyPacResolver>
{
}

/// A snapshot of the operating system's proxy configuration.
///
/// HTTP and HTTPS identify the destination scheme, not necessarily the
/// transport protocol used to reach the proxy. A SOCKS5 proxy is used as a
/// fallback when no scheme-specific proxy is configured. A PAC URI takes
/// precedence over fixed proxies because it can make a per-request decision;
/// each platform reader records whether its bypass entries apply before PAC.
/// System proxy routing always bypasses loopback hosts, including before PAC
/// evaluation, matching native proxy stacks.
#[derive(Debug, Clone, Default)]
pub struct SystemProxyConfig {
    http: Option<ProxyAddress>,
    https: Option<ProxyAddress>,
    socks5: Option<ProxyAddress>,
    pac_uri: Option<Uri>,
    auto_detect: bool,
    bypass: Arc<[BypassRule]>,
    exclude_simple_hostnames: bool,
    reversed_bypass: bool,
    bypass_before_pac: bool,
}

impl SystemProxyConfig {
    fn replace_bypass_ignoring_invalid(
        &mut self,
        bypass: impl IntoIterator<Item = impl Into<Box<str>>>,
        dialect: BypassRuleDialect,
    ) {
        self.bypass = bypass
            .into_iter()
            .filter_map(
                |value| match BypassRule::compile_with_dialect(value, dialect) {
                    Ok(rule) => Some(rule),
                    Err(error) => {
                        rama_core::telemetry::tracing::debug!(
                            error = %error,
                            "ignoring invalid system proxy bypass pattern"
                        );
                        None
                    }
                },
            )
            .collect();
    }

    fn try_replace_bypass(
        &mut self,
        bypass: impl IntoIterator<Item = impl Into<Box<str>>>,
        policy: SystemProxyInvalidBypassRulePolicy,
        dialect: BypassRuleDialect,
    ) -> Result<(), BoxError> {
        match policy {
            SystemProxyInvalidBypassRulePolicy::Ignore => {
                self.replace_bypass_ignoring_invalid(bypass, dialect);
            }
            SystemProxyInvalidBypassRulePolicy::Reject => {
                self.bypass = bypass
                    .into_iter()
                    .map(|value| BypassRule::compile_with_dialect(value, dialect))
                    .collect::<Result<Vec<_>, _>>()?
                    .into();
            }
        }
        Ok(())
    }

    #[cfg(any(
        test,
        target_vendor = "apple",
        target_os = "android",
        target_os = "windows",
        target_os = "linux",
        target_os = "freebsd",
        target_os = "netbsd",
        target_os = "openbsd",
        target_os = "dragonfly"
    ))]
    fn try_set_bypass_with_dialect(
        &mut self,
        bypass: impl IntoIterator<Item = impl Into<Box<str>>>,
        policy: SystemProxyInvalidBypassRulePolicy,
        dialect: BypassRuleDialect,
    ) -> Result<(), BoxError> {
        self.try_replace_bypass(bypass, policy, dialect)
    }

    /// Read the current platform proxy snapshot.
    ///
    /// - Windows uses the active user's WinINET/Internet Options settings;
    /// - macOS and iOS use CFNetwork's system proxy dictionary;
    /// - Android uses `ConnectivityManager.getDefaultProxy()`, with the legacy
    ///   `Proxy` API on Android versions before API 23;
    /// - Linux and BSD prefer KDE's `kioslaverc` on KDE desktops, otherwise
    ///   reading GNOME `gsettings` before falling back to KDE.
    ///
    /// This deliberately does not inspect `http_proxy` or related environment
    /// variables. Those are application configuration and are handled by
    /// [`ProxyEnvLayer`][crate::client::ProxyEnvLayer] and
    /// [`NoProxyEnvLayer`][crate::client::NoProxyEnvLayer] instead.
    ///
    /// Automatic discovery such as WPAD is recorded by [`Self::auto_detect`]
    /// but is not attempted when the platform does not provide a concrete PAC
    /// URI. Malformed non-empty proxy values are reported as errors rather
    /// than silently bypassing a configured system policy.
    ///
    /// Platform operations that have asynchronous APIs are awaited directly.
    /// Native platforms that only expose a synchronous snapshot call keep that
    /// call narrowly isolated inside their platform reader.
    pub async fn try_from_system() -> Result<Self, BoxError> {
        Self::try_from_system_with_invalid_bypass_rule_policy(
            SystemProxyInvalidBypassRulePolicy::Ignore,
        )
        .await
    }

    /// Read the current platform proxy snapshot with an explicit invalid
    /// bypass-rule policy.
    ///
    /// [`Ignore`][SystemProxyInvalidBypassRulePolicy::Ignore] is the default
    /// used by [`Self::try_from_system`]. Selecting
    /// [`Reject`][SystemProxyInvalidBypassRulePolicy::Reject] returns an error
    /// instead of accepting a snapshot with one or more discarded rules.
    pub async fn try_from_system_with_invalid_bypass_rule_policy(
        policy: SystemProxyInvalidBypassRulePolicy,
    ) -> Result<Self, BoxError> {
        platform::read(policy)
            .await
            .context("read system proxy configuration")
    }

    /// Return whether this snapshot contains no automatic, PAC, or fixed proxy
    /// settings.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.http.is_none()
            && self.https.is_none()
            && self.socks5.is_none()
            && self.pac_uri.is_none()
            && !self.auto_detect
    }

    /// The proxy for HTTP destinations.
    #[must_use]
    pub const fn http_proxy(&self) -> Option<&ProxyAddress> {
        self.http.as_ref()
    }

    /// The proxy for HTTPS destinations.
    #[must_use]
    pub const fn https_proxy(&self) -> Option<&ProxyAddress> {
        self.https.as_ref()
    }

    /// The SOCKS5 fallback proxy.
    #[must_use]
    pub const fn socks5_proxy(&self) -> Option<&ProxyAddress> {
        self.socks5.as_ref()
    }

    /// The configured PAC script URI.
    #[must_use]
    pub const fn pac_uri(&self) -> Option<&Uri> {
        self.pac_uri.as_ref()
    }

    /// Whether the platform requested automatic proxy discovery (for example,
    /// WPAD) without necessarily supplying a concrete PAC URI.
    #[must_use]
    pub const fn auto_detect(&self) -> bool {
        self.auto_detect
    }

    /// Host patterns that bypass fixed proxies.
    pub fn bypass(&self) -> impl Iterator<Item = &str> {
        self.bypass.iter().map(BypassRule::raw)
    }

    /// Whether names without a dot bypass fixed proxies.
    #[must_use]
    pub const fn exclude_simple_hostnames(&self) -> bool {
        self.exclude_simple_hostnames
    }

    /// Whether fixed proxies are used only for hosts matching [`bypass`][Self::bypass].
    ///
    /// KDE exposes this uncommon inverted exception-list mode. The default is
    /// `false`, where matching hosts bypass the proxy in the usual way.
    #[must_use]
    pub const fn reversed_bypass(&self) -> bool {
        self.reversed_bypass
    }

    generate_set_and_with! {
        /// Set the proxy used for HTTP destinations.
        pub fn http_proxy(mut self, proxy: Option<ProxyAddress>) -> Self {
            self.http = proxy;
            self
        }
    }

    generate_set_and_with! {
        /// Set the proxy used for HTTPS destinations.
        pub fn https_proxy(mut self, proxy: Option<ProxyAddress>) -> Self {
            self.https = proxy;
            self
        }
    }

    generate_set_and_with! {
        /// Set the SOCKS5 fallback proxy.
        pub fn socks5_proxy(mut self, proxy: Option<ProxyAddress>) -> Self {
            self.socks5 = proxy;
            self
        }
    }

    generate_set_and_with! {
        /// Set the PAC script URI.
        pub fn pac_uri(mut self, pac_uri: Option<Uri>) -> Self {
            self.pac_uri = pac_uri;
            self
        }
    }

    generate_set_and_with! {
        /// Record whether automatic proxy discovery is enabled.
        ///
        /// Rama exposes this signal but does not perform WPAD itself.
        pub fn auto_detect(mut self, auto_detect: bool) -> Self {
            self.auto_detect = auto_detect;
            self
        }
    }

    generate_set_and_with! {
        /// Replace the fixed-proxy bypass patterns, ignoring invalid entries.
        ///
        /// Use [`Self::try_set_bypass`] with
        /// [`Reject`][SystemProxyInvalidBypassRulePolicy::Reject] when an invalid
        /// entry should reject the complete update. Boxed strings transfer
        /// directly into snapshot storage; borrowed strings are copied because
        /// the snapshot owns its rules.
        pub fn bypass(
            mut self,
            bypass: impl IntoIterator<Item = impl Into<Box<str>>>,
        ) -> Self {
            self.replace_bypass_ignoring_invalid(bypass, BypassRuleDialect::Rama);
            self
        }
    }

    generate_set_and_with! {
        /// Replace the fixed-proxy bypass patterns using an explicit invalid-rule
        /// policy.
        ///
        /// The update is atomic: when [`Reject`][SystemProxyInvalidBypassRulePolicy::Reject]
        /// encounters an invalid rule, this returns an error and leaves the prior
        /// bypass list unchanged. Boxed strings transfer directly into snapshot
        /// storage; borrowed strings are copied because the snapshot owns its
        /// rules.
        pub fn bypass(
            mut self,
            bypass: impl IntoIterator<Item = impl Into<Box<str>>>,
            policy: SystemProxyInvalidBypassRulePolicy,
        ) -> Result<Self, BoxError> {
            self.try_replace_bypass(bypass, policy, BypassRuleDialect::Rama)?;
            Ok(self)
        }
    }

    generate_set_and_with! {
        /// Configure whether names without a dot bypass fixed proxies.
        pub fn exclude_simple_hostnames(mut self, exclude: bool) -> Self {
            self.exclude_simple_hostnames = exclude;
            self
        }
    }

    generate_set_and_with! {
        /// Invert the meaning of fixed-proxy bypass patterns.
        pub fn reversed_bypass(mut self, reversed: bool) -> Self {
            self.reversed_bypass = reversed;
            self
        }
    }

    fn decision(&self, uri: &Uri) -> SystemProxyDecision {
        if let Some(pac_uri) = &self.pac_uri {
            if uri.host().is_some_and(|host| {
                host.is_loopback()
                    || (self.bypass_before_pac
                        && self.bypasses(
                            uri.scheme(),
                            host,
                            uri.port_u16()
                                .or_else(|| uri.scheme().and_then(Protocol::default_port)),
                        ))
            }) {
                return SystemProxyDecision::Route(ProxyRoute::Direct);
            }
            return SystemProxyDecision::Pac(pac_uri.clone());
        }

        self.fixed_route(uri)
            .map(SystemProxyDecision::Route)
            .unwrap_or(SystemProxyDecision::None)
    }

    fn fixed_route(&self, uri: &Uri) -> Option<ProxyRoute> {
        let host = uri.host()?;
        self.fixed_route_for(
            uri.scheme(),
            host,
            uri.port_u16()
                .or_else(|| uri.scheme().and_then(Protocol::default_port)),
        )
    }

    fn fixed_route_for(
        &self,
        scheme: Option<&Protocol>,
        host: HostRef<'_>,
        port: Option<u16>,
    ) -> Option<ProxyRoute> {
        let proxy = match scheme {
            Some(protocol) if *protocol == Protocol::HTTPS || *protocol == Protocol::WSS => {
                self.https.as_ref()
            }
            Some(protocol) if *protocol == Protocol::HTTP || *protocol == Protocol::WS => {
                self.http.as_ref()
            }
            _ => None,
        }
        .or(self.socks5.as_ref());
        let proxy = proxy?;

        // Platform proxy stacks implicitly keep loopback traffic local even
        // when their user-visible bypass list does not mention it.
        if host.is_loopback() || self.bypasses(scheme, host, port) {
            return Some(ProxyRoute::Direct);
        }
        Some(ProxyRoute::Proxy(proxy.clone()))
    }

    fn bypasses(&self, scheme: Option<&Protocol>, host: HostRef<'_>, port: Option<u16>) -> bool {
        let matches = (self.exclude_simple_hostnames && is_simple_hostname(host))
            || matches_any_rule(&self.bypass, scheme, host, port);
        if self.reversed_bypass {
            !matches
        } else {
            matches
        }
    }
}

enum SystemProxyDecision {
    None,
    Route(ProxyRoute),
    Pac(Uri),
}

type SystemProxyConfigReader = BoxService<(), SystemProxyConfig, BoxError>;
type BoxSystemProxyConfigChangeTrigger = BoxService<(), bool, BoxError>;

#[derive(Clone, Default)]
struct LazyPlatformConfigChangeTrigger {
    trigger: Arc<OnceLock<Arc<platform::PlatformConfigChangeTrigger>>>,
}

impl LazyPlatformConfigChangeTrigger {
    fn poll(&self) -> Result<bool, BoxError> {
        self.trigger
            .get_or_init(platform::config_change_trigger)
            .poll()
    }

    #[cfg(test)]
    fn is_initialized(&self) -> bool {
        self.trigger.get().is_some()
    }
}

#[derive(Clone)]
enum SystemProxyConfigChangeTrigger {
    Platform(LazyPlatformConfigChangeTrigger),
    Custom(BoxSystemProxyConfigChangeTrigger),
}

impl fmt::Debug for SystemProxyConfigChangeTrigger {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Platform(_) => f.write_str("Platform(_)"),
            Self::Custom(trigger) => f.debug_tuple("Custom").field(trigger).finish(),
        }
    }
}

#[derive(Debug, Default)]
struct RefreshRequestState {
    requested_generation: AtomicU64,
    completed_generation: AtomicU64,
}

impl RefreshRequestState {
    fn request(&self) -> u64 {
        self.requested_generation
            .fetch_update(Ordering::AcqRel, Ordering::Acquire, |generation| {
                Some(generation.saturating_add(1))
            })
            .unwrap_or_else(|generation| generation)
            .saturating_add(1)
    }
}

#[derive(Clone)]
struct RefreshRequest {
    state: Arc<RefreshRequestState>,
    generation: u64,
}

impl RefreshRequest {
    fn is_pending(&self) -> bool {
        self.generation > self.state.completed_generation.load(Ordering::Acquire)
    }

    fn complete(&self) {
        self.state
            .completed_generation
            .fetch_max(self.generation, Ordering::AcqRel);
    }
}

#[derive(Clone)]
struct SystemProxyConfigRefresh {
    enabled: bool,
    trigger: Option<SystemProxyConfigChangeTrigger>,
    trigger_error_sink: Arc<dyn ErrorSink>,
    requests: Arc<RefreshRequestState>,
}

impl fmt::Debug for SystemProxyConfigRefresh {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("SystemProxyConfigRefresh")
            .field("enabled", &self.enabled)
            .field("trigger", &self.trigger)
            .finish_non_exhaustive()
    }
}

impl Default for SystemProxyConfigRefresh {
    fn default() -> Self {
        Self {
            enabled: true,
            trigger: Some(SystemProxyConfigChangeTrigger::Platform(
                LazyPlatformConfigChangeTrigger::default(),
            )),
            trigger_error_sink: Arc::new(TracingErrorSink::default()),
            requests: Arc::new(RefreshRequestState::default()),
        }
    }
}

impl SystemProxyConfigRefresh {
    async fn requested(&self) -> RefreshRequest {
        let changed = if !self.enabled {
            false
        } else if let Some(trigger) = &self.trigger {
            match trigger {
                SystemProxyConfigChangeTrigger::Platform(trigger) => trigger.poll(),
                SystemProxyConfigChangeTrigger::Custom(trigger) => trigger.serve(()).await,
            }
            .unwrap_or_else(|error| {
                self.trigger_error_sink.sink_error(error);
                false
            })
        } else {
            false
        };
        let generation = if changed {
            self.requests.request()
        } else {
            self.requests.requested_generation.load(Ordering::Acquire)
        };
        RefreshRequest {
            state: self.requests.clone(),
            generation,
        }
    }
}

#[derive(Debug)]
struct IntoBoxErrorService<T>(T);

impl<T> Service<()> for IntoBoxErrorService<T>
where
    T: Service<(), Output = bool>,
    T::Error: Into<BoxError>,
{
    type Output = bool;
    type Error = BoxError;

    async fn serve(&self, (): ()) -> Result<Self::Output, Self::Error> {
        self.0.serve(()).await.map_err(Into::into)
    }
}

fn system_proxy_config_reader(
    policy: SystemProxyInvalidBypassRulePolicy,
) -> SystemProxyConfigReader {
    BoxService::new(service_fn(move |()| async move {
        SystemProxyConfig::try_from_system_with_invalid_bypass_rule_policy(policy).await
    }))
}

struct SystemProxyConfigCache {
    current: ArcSwapOption<SystemProxyConfig>,
    ttl: Duration,
    epoch: Instant,
    refresh_after_nanos: AtomicU64,
    cold_failure_generation: AtomicU64,
    refresh_lock: tokio::sync::Mutex<()>,
    reader: SystemProxyConfigReader,
}

impl fmt::Debug for SystemProxyConfigCache {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("SystemProxyConfigCache")
            .field("current", &self.current.load_full())
            .field("ttl", &self.ttl)
            .field(
                "refresh_after_nanos",
                &self.refresh_after_nanos.load(Ordering::Relaxed),
            )
            .field(
                "cold_failure_generation",
                &self.cold_failure_generation.load(Ordering::Relaxed),
            )
            .finish_non_exhaustive()
    }
}

impl SystemProxyConfigCache {
    fn new(
        current: Option<SystemProxyConfig>,
        ttl: Duration,
        reader: SystemProxyConfigReader,
    ) -> Self {
        let epoch = Instant::now();
        let refresh_after_nanos = if current.is_some() {
            duration_nanos(ttl)
        } else {
            0
        };
        Self {
            current: ArcSwapOption::from(current.map(Arc::new)),
            ttl,
            epoch,
            refresh_after_nanos: AtomicU64::new(refresh_after_nanos),
            cold_failure_generation: AtomicU64::new(0),
            refresh_lock: tokio::sync::Mutex::new(()),
            reader,
        }
    }

    fn cached(&self) -> Option<Arc<SystemProxyConfig>> {
        self.current.load_full()
    }

    fn is_fresh(&self, now: u64) -> bool {
        now < self.refresh_after_nanos.load(Ordering::Acquire)
    }

    fn schedule_next_refresh(&self) {
        let now = duration_nanos(self.epoch.elapsed());
        self.refresh_after_nanos.store(
            now.saturating_add(duration_nanos(self.ttl)),
            Ordering::Release,
        );
    }

    async fn refresh(
        &self,
        stale: Option<Arc<SystemProxyConfig>>,
        load_error_policy: &LoadErrorPolicy,
    ) -> Result<Arc<SystemProxyConfig>, BoxError> {
        match self.reader.serve(()).await {
            Ok(config) => {
                let config = Arc::new(config);
                self.current.store(Some(config.clone()));
                self.schedule_next_refresh();
                Ok(config)
            }
            Err(error) => {
                let Some(stale) = stale else {
                    load_error_policy.handle(error)?;
                    let config = Arc::new(SystemProxyConfig::default());
                    self.current.store(Some(config.clone()));
                    self.schedule_next_refresh();
                    return Ok(config);
                };
                self.schedule_next_refresh();
                if let Err(error) = load_error_policy.handle(error) {
                    rama_core::telemetry::tracing::warn!(
                        error = %error,
                        "failed to refresh system proxy configuration; retaining prior snapshot"
                    );
                }
                Ok(stale)
            }
        }
    }

    async fn snapshot(
        &self,
        refresh_enabled: bool,
        refresh_request: &RefreshRequest,
        load_error_policy: &LoadErrorPolicy,
    ) -> Result<Arc<SystemProxyConfig>, BoxError> {
        let refresh_requested = refresh_request.is_pending();
        let current = self.current.load_full();
        let now = duration_nanos(self.epoch.elapsed());
        if let Some(current) = current
            .as_ref()
            .filter(|_| !refresh_enabled || (!refresh_requested && self.is_fresh(now)))
        {
            return Ok(current.clone());
        }

        if let Some(stale) = current {
            let Ok(_guard) = self.refresh_lock.try_lock() else {
                return Ok(stale);
            };
            let latest = self.current.load_full().unwrap_or(stale);
            let now = duration_nanos(self.epoch.elapsed());
            if !refresh_request.is_pending() && self.is_fresh(now) {
                return Ok(latest);
            }
            let result = self.refresh(Some(latest), load_error_policy).await;
            refresh_request.complete();
            return result;
        }

        // Waiters that observed the same cold state share one failed attempt.
        // A later independent call still retries immediately, but a queue of
        // requests cannot serially repeat one slow platform failure.
        let observed_failure = self.cold_failure_generation.load(Ordering::Acquire);
        let _guard = self.refresh_lock.lock().await;
        if let Some(current) = self.current.load_full() {
            if !refresh_request.is_pending() {
                return Ok(current);
            }
            let result = self.refresh(Some(current), load_error_policy).await;
            refresh_request.complete();
            return result;
        }
        if observed_failure != self.cold_failure_generation.load(Ordering::Acquire) {
            return Err(BoxError::from_static_str(
                "system proxy configuration load failed while this request was waiting",
            ));
        }
        let result = self.refresh(None, load_error_policy).await;
        refresh_request.complete();
        if result.is_err() {
            self.cold_failure_generation.fetch_add(1, Ordering::Release);
        }
        result
    }
}

fn duration_nanos(duration: Duration) -> u64 {
    duration.as_nanos().try_into().unwrap_or(u64::MAX)
}

#[doc(hidden)]
#[derive(Debug, Clone, Copy, Default)]
pub struct SystemProxyPacDisabled;

#[doc(hidden)]
#[derive(Debug, Clone, Copy)]
pub struct SystemProxyPacDisabledResolver;

impl Service<Uri> for SystemProxyPacDisabled {
    type Output = SystemProxyPacDisabledResolver;
    type Error = std::convert::Infallible;

    async fn serve(&self, _uri: Uri) -> Result<Self::Output, Self::Error> {
        Ok(SystemProxyPacDisabledResolver)
    }
}

impl Service<SystemProxyPacRequest> for SystemProxyPacDisabledResolver {
    type Output = Option<ProxyRoutes>;
    type Error = std::convert::Infallible;

    async fn serve(&self, _request: SystemProxyPacRequest) -> Result<Self::Output, Self::Error> {
        Ok(None)
    }
}

/// Apply the operating system's proxy settings to client service inputs.
///
/// Existing [`ProxyRoute`] or [`ProxyRoutes`] extensions win by default. This
/// makes the layer safe to place below explicit CLI/application proxy layers:
/// a common priority chain is [`NoProxyEnvLayer`][crate::client::NoProxyEnvLayer],
/// an explicit option, [`ProxyEnvLayer`][crate::client::ProxyEnvLayer], then
/// this system layer. Use
/// [`with_overwrite`][Self::with_overwrite] only when the system policy must
/// replace a route already chosen by the caller.
///
/// Environment proxy variables are intentionally out of scope. Use
/// [`ProxyEnvLayer`][crate::client::ProxyEnvLayer] for proxy variables and
/// [`NoProxyEnvLayer`][crate::client::NoProxyEnvLayer] for bypass variables.
///
/// Configuration discovery is lazy. macOS, Windows, and Linux install a
/// private native change monitor with the first load; the cache TTL remains a
/// fallback on every platform. Applications can replace that monitor through
/// [`with_config_change_trigger`][Self::with_config_change_trigger], retain
/// TTL-only refreshes through
/// [`without_config_change_trigger`][Self::without_config_change_trigger], or
/// make the first snapshot immutable through
/// [`with_config_refresh(false)`][Self::with_config_refresh].
///
/// Fixed proxies and bypass decisions publish one [`ProxyRoute`]. PAC verdicts
/// retain their ordered [`ProxyRoutes`] plan even when it contains one entry.
/// Compose [`ProxyRoutesLayer`][crate::client::ProxyRoutesLayer] after all route
/// selectors and before route-aware middleware.
///
/// A configured PAC URI is used only after a service is supplied through
/// [`with_pac_service`][Self::with_pac_service]. Without one the layer uses a
/// fixed proxy from the same system snapshot when available, or leaves the
/// request unchanged. Factory, fetch, or evaluation errors fail the request
/// instead of silently bypassing the system proxy.
#[derive(Clone)]
pub struct SystemProxyLayer<P = SystemProxyPacDisabled> {
    config: Arc<SystemProxyConfigCache>,
    refresh: SystemProxyConfigRefresh,
    load_error_policy: LoadErrorPolicy,
    pac: P,
    pac_enabled: bool,
    overwrite: bool,
}

impl<P: fmt::Debug> fmt::Debug for SystemProxyLayer<P> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("SystemProxyLayer")
            .field("config", &self.config)
            .field("refresh", &self.refresh)
            .field("load_error_policy", &self.load_error_policy)
            .field("pac", &self.pac)
            .field("pac_enabled", &self.pac_enabled)
            .field("overwrite", &self.overwrite)
            .finish()
    }
}

impl SystemProxyLayer {
    /// Create a lazy system-proxy layer without reading platform settings.
    ///
    /// The first unrouted request loads the settings. Call
    /// [`warm_up`][Self::warm_up] to perform that asynchronous load eagerly.
    #[must_use]
    pub fn new() -> Self {
        Self::new_with_ttl_and_invalid_bypass_rule_policy(
            DEFAULT_SYSTEM_PROXY_CONFIG_TTL,
            SystemProxyInvalidBypassRulePolicy::Ignore,
        )
    }

    /// Create a lazy system-proxy layer with a custom cache TTL.
    #[must_use]
    pub fn new_with_ttl(ttl: Duration) -> Self {
        Self::new_with_ttl_and_invalid_bypass_rule_policy(
            ttl,
            SystemProxyInvalidBypassRulePolicy::Ignore,
        )
    }

    /// Create a lazy layer with explicit refresh and bypass-rule policies.
    #[must_use]
    pub fn new_with_ttl_and_invalid_bypass_rule_policy(
        ttl: Duration,
        policy: SystemProxyInvalidBypassRulePolicy,
    ) -> Self {
        Self::new_with_reader(ttl, system_proxy_config_reader(policy))
    }

    fn new_with_reader(ttl: Duration, reader: SystemProxyConfigReader) -> Self {
        Self {
            config: Arc::new(SystemProxyConfigCache::new(None, ttl, reader)),
            refresh: SystemProxyConfigRefresh::default(),
            load_error_policy: LoadErrorPolicy::Reject,
            pac: SystemProxyPacDisabled,
            pac_enabled: false,
            overwrite: false,
        }
    }

    /// Create a layer from a cached operating-system proxy snapshot.
    ///
    /// The supplied snapshot is used immediately and refreshed from the
    /// operating system after [`DEFAULT_SYSTEM_PROXY_CONFIG_TTL`]. Use
    /// [`try_from_system`][Self::try_from_system] to start with a fresh read.
    #[must_use]
    pub fn from_cached(config: SystemProxyConfig) -> Self {
        Self::from_cached_with_invalid_bypass_rule_policy(
            config,
            SystemProxyInvalidBypassRulePolicy::Ignore,
        )
    }

    /// Create a layer from a cached operating-system proxy snapshot with an
    /// explicit invalid bypass-rule policy for subsequent refreshes.
    #[must_use]
    pub fn from_cached_with_invalid_bypass_rule_policy(
        config: SystemProxyConfig,
        policy: SystemProxyInvalidBypassRulePolicy,
    ) -> Self {
        Self::from_cached_with_reader(
            config,
            DEFAULT_SYSTEM_PROXY_CONFIG_TTL,
            system_proxy_config_reader(policy),
        )
    }

    fn from_cached_with_reader(
        config: SystemProxyConfig,
        ttl: Duration,
        reader: SystemProxyConfigReader,
    ) -> Self {
        Self {
            config: Arc::new(SystemProxyConfigCache::new(Some(config), ttl, reader)),
            refresh: SystemProxyConfigRefresh::default(),
            load_error_policy: LoadErrorPolicy::Reject,
            pac: SystemProxyPacDisabled,
            pac_enabled: false,
            overwrite: false,
        }
    }

    /// Create a layer and asynchronously warm its system proxy snapshot.
    pub async fn try_from_system() -> Result<Self, BoxError> {
        Self::try_from_system_with_invalid_bypass_rule_policy(
            SystemProxyInvalidBypassRulePolicy::Ignore,
        )
        .await
    }

    /// Create a layer from the current operating system proxy settings using
    /// an explicit invalid bypass-rule policy.
    pub async fn try_from_system_with_invalid_bypass_rule_policy(
        policy: SystemProxyInvalidBypassRulePolicy,
    ) -> Result<Self, BoxError> {
        Self::try_from_system_with_ttl_and_invalid_bypass_rule_policy(
            DEFAULT_SYSTEM_PROXY_CONFIG_TTL,
            policy,
        )
        .await
    }

    /// Create a refreshing layer from the current operating system settings.
    ///
    /// The initial read is awaited. Once `ttl` has elapsed, one request awaits
    /// the refresh while concurrent requests continue using the prior
    /// snapshot. A failed refresh retains that snapshot and is retried after
    /// another `ttl` interval.
    pub async fn try_from_system_with_ttl(ttl: Duration) -> Result<Self, BoxError> {
        Self::try_from_system_with_ttl_and_invalid_bypass_rule_policy(
            ttl,
            SystemProxyInvalidBypassRulePolicy::Ignore,
        )
        .await
    }

    /// Create a refreshing layer with explicit refresh and invalid bypass-rule
    /// policies.
    pub async fn try_from_system_with_ttl_and_invalid_bypass_rule_policy(
        ttl: Duration,
        policy: SystemProxyInvalidBypassRulePolicy,
    ) -> Result<Self, BoxError> {
        Self::try_from_system_with_reader(ttl, system_proxy_config_reader(policy)).await
    }

    async fn try_from_system_with_reader(
        ttl: Duration,
        reader: SystemProxyConfigReader,
    ) -> Result<Self, BoxError> {
        let layer = Self::new_with_reader(ttl, reader);
        layer.warm_up().await?;
        Ok(layer)
    }
}

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

impl<P> SystemProxyLayer<P> {
    /// Load and return the current operating system proxy configuration.
    ///
    /// The first call performs lazy discovery. A native or custom change
    /// trigger can request an early refresh. Once the cache TTL expires, one
    /// caller awaits a refresh while concurrent callers use the stale
    /// snapshot.
    pub async fn config(&self) -> Result<Arc<SystemProxyConfig>, BoxError> {
        let refresh_request = self.refresh.requested().await;
        self.config
            .snapshot(
                self.refresh.enabled,
                &refresh_request,
                &self.load_error_policy,
            )
            .await
    }

    /// Return the cached snapshot without loading or refreshing it.
    #[must_use]
    pub fn cached_config(&self) -> Option<Arc<SystemProxyConfig>> {
        self.config.cached()
    }

    /// Asynchronously populate the cache before serving requests.
    pub async fn warm_up(&self) -> Result<(), BoxError> {
        self.config().await.map(drop)
    }

    /// Supply a PAC resolver factory.
    ///
    /// The factory can be consulted for every request selected for PAC
    /// evaluation. Implementations should therefore reuse resolver state for
    /// the same script URI. Factory and resolver errors fail the request.
    #[must_use]
    pub fn with_pac_service<Q>(self, pac: Q) -> SystemProxyLayer<Q> {
        SystemProxyLayer {
            config: self.config,
            refresh: self.refresh,
            load_error_policy: self.load_error_policy,
            pac,
            pac_enabled: true,
            overwrite: self.overwrite,
        }
    }

    generate_set_and_with! {
        /// Handle system configuration load errors with a sink.
        ///
        /// By default, an initial discovery failure rejects the request. With
        /// this opt-in policy, the error is sent to `error_sink` and an empty
        /// snapshot is cached for the configured TTL. Refresh failures retain
        /// the previous snapshot and are sent to the same sink.
        pub fn load_error_sink(mut self, error_sink: impl ErrorSink) -> Self {
            self.load_error_policy = LoadErrorPolicy::Handle(Arc::new(error_sink));
            self
        }
    }

    generate_set_and_with! {
        /// Enable periodic and change-triggered configuration refreshes.
        ///
        /// Disabling refresh keeps the first loaded snapshot immutable. A
        /// layer created with [`from_cached`][Self::from_cached] therefore
        /// performs no operating-system reads when refresh is disabled.
        pub fn config_refresh(mut self, config_refresh: bool) -> Self {
            self.refresh.enabled = config_refresh;
            self
        }
    }

    generate_set_and_with! {
        /// Replace the default platform configuration-change trigger.
        ///
        /// The service is polled before configuration access. Returning `true`
        /// requests an immediate refresh of an existing snapshot; returning
        /// `false` leaves the TTL as the fallback. Trigger errors are sent to the
        /// configured error sink and also fall back to the TTL.
        pub fn config_change_trigger(
            mut self,
            trigger: impl Service<(), Output = bool, Error: Into<BoxError>>,
        ) -> Self {
            self.refresh.trigger = Some(SystemProxyConfigChangeTrigger::Custom(BoxService::new(
                IntoBoxErrorService(trigger),
            )));
            self
        }
    }

    /// Disable early change notifications while retaining TTL refreshes.
    #[must_use]
    pub fn without_config_change_trigger(mut self) -> Self {
        self.refresh.trigger = None;
        self
    }

    /// Disable early change notifications while retaining TTL refreshes.
    pub fn unset_config_change_trigger(&mut self) -> &mut Self {
        self.refresh.trigger = None;
        self
    }

    generate_set_and_with! {
        /// Replace the sink for configuration-change trigger errors.
        pub fn config_change_trigger_error_sink(
            mut self,
            error_sink: impl ErrorSink,
        ) -> Self {
            self.refresh.trigger_error_sink = Arc::new(error_sink);
            self
        }
    }

    generate_set_and_with! {
        /// Replace an existing route decision (defaults to `false`).
        pub fn overwrite(mut self, overwrite: bool) -> Self {
            self.overwrite = overwrite;
            self
        }
    }
}

impl<S, P> Layer<S> for SystemProxyLayer<P>
where
    P: Clone,
{
    type Service = SystemProxyService<S, P>;

    fn layer(&self, inner: S) -> Self::Service {
        SystemProxyService {
            inner,
            layer: self.clone(),
        }
    }

    fn into_layer(self, inner: S) -> Self::Service {
        SystemProxyService { inner, layer: self }
    }
}

/// See [`SystemProxyLayer`].
#[derive(Debug, Clone)]
pub struct SystemProxyService<S, P = SystemProxyPacDisabled> {
    inner: S,
    layer: SystemProxyLayer<P>,
}

impl<S, P> SystemProxyService<S, P> {
    /// Borrow the wrapped service.
    #[must_use]
    pub const fn inner(&self) -> &S {
        &self.inner
    }

    /// Mutably borrow the wrapped service.
    #[must_use]
    pub fn inner_mut(&mut self) -> &mut S {
        &mut self.inner
    }

    /// Consume this service and return the wrapped service.
    #[must_use]
    pub fn into_inner(self) -> S {
        self.inner
    }
}

impl<S, P, Input> Service<Input> for SystemProxyService<S, P>
where
    S: Service<Input, Error: Into<BoxError>>,
    P: SystemProxyPacService,
    Input: UriInputExt + AuthorityInputExt + ProtocolInputExt + ExtensionsRef + Send + 'static,
{
    type Output = S::Output;
    type Error = BoxError;

    async fn serve(&self, input: Input) -> Result<Self::Output, Self::Error> {
        if !self.layer.overwrite && is_already_routed(&input) {
            return self.inner.serve(input).await.map_err(Into::into);
        }
        let config = self.layer.config().await?;
        if config.is_empty() {
            return self.inner.serve(input).await.map_err(Into::into);
        }

        let mut normalized_uri = None;
        let decision = if self.layer.pac_enabled && config.pac_uri().is_some() {
            let uri = absolute_uri(&input)?;
            let decision = config.decision(&uri);
            normalized_uri = Some(uri);
            decision
        } else {
            let protocol = request_protocol(&input);
            let authority = input
                .uri()
                .authority()
                .map(|authority| authority.into_owned().address)
                .or_else(|| input.authority());
            if let Some(authority) = authority {
                config
                    .fixed_route_for(
                        Some(&protocol),
                        authority.host.view(),
                        authority.port_u16().or_else(|| protocol.default_port()),
                    )
                    .map(SystemProxyDecision::Route)
                    .unwrap_or(SystemProxyDecision::None)
            } else {
                rama_core::telemetry::tracing::debug!(
                    "fixed system proxy cannot route an input without an authority"
                );
                SystemProxyDecision::None
            }
        };
        match decision {
            SystemProxyDecision::Pac(pac_uri) => {
                let Some(uri) = normalized_uri else {
                    return Err(BoxError::from_static_str(
                        "system PAC decision is missing its normalized request URI",
                    ));
                };
                let resolver = self
                    .layer
                    .pac
                    .serve(pac_uri)
                    .await
                    .context("create system PAC resolver")?;
                match resolver
                    .serve(SystemProxyPacRequest::new(
                        input.extensions().clone(),
                        uri.clone(),
                    )?)
                    .await
                    .context("resolve system PAC routes")?
                {
                    Some(routes) => {
                        input.extensions().insert(routes);
                    }
                    None => {
                        if let Some(route) = config.fixed_route(&uri) {
                            input.extensions().insert(route);
                        }
                    }
                }
            }
            SystemProxyDecision::Route(route) => {
                input.extensions().insert(route);
            }
            SystemProxyDecision::None => {}
        }
        self.inner.serve(input).await.map_err(Into::into)
    }
}

pub(super) fn absolute_uri<I>(input: &I) -> Result<Uri, BoxError>
where
    I: UriInputExt + AuthorityInputExt + ProtocolInputExt,
{
    let uri = input.uri();
    let protocol = request_protocol(input);
    proxy_request_uri(uri, input.authority(), protocol)
}

pub(super) fn request_protocol<I>(input: &I) -> Protocol
where
    I: UriInputExt + ProtocolInputExt,
{
    input
        .uri()
        .scheme()
        .cloned()
        // Authority-form is the request-target form of CONNECT. The tunnel is
        // opaque and overwhelmingly TLS, so match the HTTP PAC layer and show
        // it as HTTPS regardless of the named port.
        .or_else(|| input.uri().authority().map(|_| Protocol::HTTPS))
        .or_else(|| input.protocol().cloned())
        .unwrap_or(Protocol::HTTP)
}

/// Normalize a request target for fixed-proxy selection and PAC evaluation.
///
/// The result is absolute, has a root path when no path was supplied, and
/// omits the protocol's default port. The URI's own authority wins over the
/// fallback authority supplied by request metadata.
pub fn proxy_request_uri(
    uri: &Uri,
    fallback_authority: Option<HostWithOptPort>,
    protocol: Protocol,
) -> Result<Uri, BoxError> {
    let authority = uri
        .authority()
        .map(|authority| authority.into_owned().address)
        .or(fallback_authority)
        .ok_or_else(|| BoxError::from_static_str("request has no resolvable authority"))?
        .without_default_port_for(Some(&protocol));

    let mut uri = if uri.is_asterisk() {
        Uri::from_authority(protocol, authority)
    } else {
        uri.clone()
            .with_authority(Authority::from(authority))
            .with_scheme(protocol)
    };
    uri.ensure_path_or_root();
    Ok(uri)
}

pub(super) fn is_already_routed(input: &impl ExtensionsRef) -> bool {
    input.extensions().contains::<ProxyRoute>() || input.extensions().contains::<ProxyRoutes>()
}

#[cfg(any(
    test,
    target_vendor = "apple",
    target_os = "android",
    target_os = "linux",
    target_os = "freebsd",
    target_os = "netbsd",
    target_os = "openbsd",
    target_os = "dragonfly"
))]
pub(super) fn proxy_address(
    protocol: Protocol,
    host: impl AsRef<str>,
    port: u16,
) -> Result<ProxyAddress, BoxError> {
    let value = host.as_ref().trim();
    let host = match Host::try_from(value) {
        Ok(host) => host,
        Err(error) if value.contains("://") => value
            .parse::<Uri>()
            .context("parse system proxy host URI")?
            .host()
            .map(|host| host.into_owned())
            .ok_or(error)
            .context("parse system proxy host")?,
        Err(error) => return Err(error).context("parse system proxy host"),
    };
    Ok(ProxyAddress {
        protocol: Some(protocol),
        address: HostWithPort::new(host, port),
        credential: None,
    })
}

#[cfg(test)]
mod tests {
    use std::convert::Infallible;

    use parking_lot::Mutex;
    use rama_core::{
        extensions::{Extension, FromExtensions},
        service::service_fn,
    };

    use super::*;

    #[derive(Debug, Clone, Extension)]
    struct Marker(&'static str);

    #[derive(FromExtensions)]
    enum RecordedProxyDecision {
        Route(Arc<ProxyRoute>),
        Routes(Arc<ProxyRoutes>),
    }

    #[derive(Debug, Clone)]
    struct TestInput {
        uri: Uri,
        protocol: Option<Protocol>,
        authority: Option<crate::address::HostWithOptPort>,
        extensions: Extensions,
    }

    impl TestInput {
        fn new(uri: &str) -> Self {
            Self {
                uri: uri.parse().unwrap(),
                protocol: None,
                authority: None,
                extensions: Extensions::new(),
            }
        }

        fn origin_form(uri: &str, protocol: Protocol, authority: &str) -> Self {
            Self {
                uri: uri.parse().unwrap(),
                protocol: Some(protocol),
                authority: Some(authority.parse().unwrap()),
                extensions: Extensions::new(),
            }
        }

        fn authority_form(authority: &str) -> Self {
            Self {
                uri: Uri::parse_authority_form(authority).unwrap(),
                protocol: None,
                authority: None,
                extensions: Extensions::new(),
            }
        }
    }

    impl UriInputExt for TestInput {
        fn uri(&self) -> &Uri {
            &self.uri
        }
    }

    impl AuthorityInputExt for TestInput {
        fn authority(&self) -> Option<crate::address::HostWithOptPort> {
            self.authority.clone().or_else(|| {
                self.uri
                    .authority()
                    .map(|authority| authority.into_owned().address)
            })
        }
    }

    impl ProtocolInputExt for TestInput {
        fn protocol(&self) -> Option<&Protocol> {
            self.protocol.as_ref().or_else(|| self.uri.scheme())
        }
    }

    impl ExtensionsRef for TestInput {
        fn extensions(&self) -> &Extensions {
            &self.extensions
        }
    }

    fn proxy(protocol: Protocol, host: &'static str, port: u16) -> ProxyAddress {
        proxy_address(protocol, host, port).unwrap()
    }

    fn recorder() -> (
        impl Service<TestInput, Output = (), Error = Infallible> + Clone,
        Arc<Mutex<Vec<Option<ProxyRoutes>>>>,
    ) {
        let seen = Arc::new(Mutex::new(Vec::new()));
        let service = service_fn({
            let seen = seen.clone();
            move |input: TestInput| {
                let routes = match RecordedProxyDecision::from_extensions(&input.extensions) {
                    Some(RecordedProxyDecision::Route(route)) => {
                        Some(ProxyRoutes::from(route.as_ref().clone()))
                    }
                    Some(RecordedProxyDecision::Routes(routes)) => Some(routes.as_ref().clone()),
                    None => None,
                };
                seen.lock().push(routes);
                async { Ok::<_, Infallible>(()) }
            }
        });
        (service, seen)
    }

    #[tokio::test]
    async fn fixed_proxies_are_selected_by_destination_scheme() {
        let config = SystemProxyConfig::default()
            .with_http_proxy(proxy(Protocol::HTTP, "http.proxy", 8080))
            .with_https_proxy(proxy(Protocol::HTTP, "https.proxy", 8443));
        let (inner, seen) = recorder();
        let service = SystemProxyLayer::from_cached(config).into_layer(inner);

        service
            .serve(TestInput::new("http://example.com/"))
            .await
            .unwrap();
        service
            .serve(TestInput::new("https://example.com/"))
            .await
            .unwrap();
        service
            .serve(TestInput::new("ws://example.com/"))
            .await
            .unwrap();
        service
            .serve(TestInput::new("wss://example.com/"))
            .await
            .unwrap();

        let seen = seen.lock();
        assert_eq!(
            seen[0].as_ref().unwrap().as_slice()[0]
                .proxy_address()
                .unwrap()
                .address
                .host
                .to_str(),
            "http.proxy"
        );
        assert_eq!(
            seen[1].as_ref().unwrap().as_slice()[0]
                .proxy_address()
                .unwrap()
                .address
                .host
                .to_str(),
            "https.proxy"
        );
        assert_eq!(
            seen[2].as_ref().unwrap().as_slice()[0]
                .proxy_address()
                .unwrap()
                .address
                .host
                .to_str(),
            "http.proxy"
        );
        assert_eq!(
            seen[3].as_ref().unwrap().as_slice()[0]
                .proxy_address()
                .unwrap()
                .address
                .host
                .to_str(),
            "https.proxy"
        );
    }

    #[tokio::test]
    async fn fixed_and_bypass_decisions_publish_singular_routes() {
        let config = SystemProxyConfig::default().with_http_proxy(proxy(
            Protocol::HTTP,
            "system.proxy",
            8080,
        ));
        let service = SystemProxyLayer::from_cached(config).into_layer(service_fn(
            async |input: TestInput| Ok::<_, Infallible>(input),
        ));

        let proxied = service
            .serve(TestInput::new("http://example.com/"))
            .await
            .unwrap();
        assert_eq!(
            proxied
                .extensions
                .get_ref::<ProxyRoute>()
                .and_then(ProxyRoute::proxy_address)
                .map(|address| address.address.host.to_string()),
            Some("system.proxy".to_owned())
        );
        assert!(!proxied.extensions.contains::<ProxyRoutes>());

        let bypassed = service
            .serve(TestInput::new("http://localhost/"))
            .await
            .unwrap();
        assert_eq!(
            bypassed.extensions.get_ref::<ProxyRoute>(),
            Some(&ProxyRoute::Direct)
        );
        assert!(!bypassed.extensions.contains::<ProxyRoutes>());
    }

    #[tokio::test]
    async fn system_decisions_override_configured_route_defaults() {
        let config = SystemProxyConfig::default().with_http_proxy(proxy(
            Protocol::HTTP,
            "system.proxy",
            8080,
        ));
        let service = SystemProxyLayer::from_cached(config).into_layer(
            crate::client::ProxyRoutesLayer::with_routes(ProxyRoute::Proxy(proxy(
                Protocol::HTTP,
                "default.proxy",
                8080,
            )))
            .into_layer(service_fn(async |input: TestInput| {
                Ok::<_, Infallible>(input)
            })),
        );

        let proxied = service
            .serve(TestInput::new("http://example.com/"))
            .await
            .unwrap();
        assert_eq!(
            proxied
                .extensions
                .get_ref::<ProxyRoute>()
                .and_then(ProxyRoute::proxy_address)
                .map(|address| address.address.host.to_string()),
            Some("system.proxy".to_owned())
        );

        let bypassed = service
            .serve(TestInput::new("http://localhost/"))
            .await
            .unwrap();
        assert_eq!(
            bypassed.extensions.get_ref::<ProxyRoute>(),
            Some(&ProxyRoute::Direct)
        );
    }

    #[tokio::test]
    async fn socks_is_the_scheme_independent_fallback() {
        let config = SystemProxyConfig::default().with_socks5_proxy(proxy(
            Protocol::SOCKS5,
            "socks.proxy",
            1080,
        ));
        let (inner, seen) = recorder();
        let service = SystemProxyLayer::from_cached(config).into_layer(inner);

        service
            .serve(TestInput::new("https://example.com/"))
            .await
            .unwrap();
        service
            .serve(TestInput::new("ftp://example.com/file"))
            .await
            .unwrap();

        let seen = seen.lock();
        for routes in seen.iter() {
            let address = routes.as_ref().unwrap().as_slice()[0]
                .proxy_address()
                .unwrap();
            assert_eq!(address.protocol, Some(Protocol::SOCKS5));
        }
    }

    #[tokio::test]
    async fn scheme_specific_proxy_does_not_capture_other_protocols() {
        let config = SystemProxyConfig::default()
            .with_http_proxy(proxy(Protocol::HTTP, "http.proxy", 8080))
            .with_bypass(["example.com"]);
        let (inner, seen) = recorder();

        SystemProxyLayer::from_cached(config)
            .into_layer(inner)
            .serve(TestInput::new("ftp://example.com/file"))
            .await
            .unwrap();

        assert!(seen.lock()[0].is_none());
    }

    #[tokio::test]
    async fn empty_config_does_not_require_routing_metadata() {
        let (inner, seen) = recorder();

        SystemProxyLayer::from_cached(SystemProxyConfig::default())
            .into_layer(inner)
            .serve(TestInput::new("/relative"))
            .await
            .unwrap();

        assert!(seen.lock()[0].is_none());
    }

    #[tokio::test]
    async fn active_fixed_config_passes_input_without_an_authority() {
        let config = SystemProxyConfig::default().with_http_proxy(proxy(
            Protocol::HTTP,
            "system.proxy",
            8080,
        ));
        let (inner, seen) = recorder();

        SystemProxyLayer::from_cached(config)
            .into_layer(inner)
            .serve(TestInput::new("/relative"))
            .await
            .unwrap();

        assert!(seen.lock()[0].is_none());
    }

    #[tokio::test]
    async fn input_without_a_protocol_defaults_to_http() {
        let config = SystemProxyConfig::default().with_http_proxy(proxy(
            Protocol::HTTP,
            "system.proxy",
            8080,
        ));
        let (inner, seen) = recorder();
        let mut input = TestInput::new("/relative");
        input.authority = Some("example.com".parse().unwrap());

        SystemProxyLayer::from_cached(config)
            .into_layer(inner)
            .serve(input)
            .await
            .unwrap();

        assert!(matches!(
            seen.lock()[0].as_ref().unwrap().as_slice(),
            [ProxyRoute::Proxy(_)]
        ));
    }

    #[tokio::test]
    async fn existing_route_wins_unless_overwrite_is_enabled() {
        let config = SystemProxyConfig::default().with_http_proxy(proxy(
            Protocol::HTTP,
            "system.proxy",
            8080,
        ));
        let (inner, seen) = recorder();
        let request = TestInput::new("http://example.com/");
        request.extensions.insert(ProxyRoutes::from(proxy(
            Protocol::HTTP,
            "explicit.proxy",
            9000,
        )));

        SystemProxyLayer::from_cached(config.clone())
            .into_layer(inner.clone())
            .serve(request.clone())
            .await
            .unwrap();
        SystemProxyLayer::from_cached(config)
            .with_overwrite(true)
            .into_layer(inner)
            .serve(request)
            .await
            .unwrap();

        let seen = seen.lock();
        let hosts: Vec<_> = seen
            .iter()
            .map(|routes| {
                routes.as_ref().unwrap().as_slice()[0]
                    .proxy_address()
                    .unwrap()
                    .address
                    .host
                    .to_str()
                    .into_owned()
            })
            .collect();
        assert_eq!(hosts, ["explicit.proxy", "system.proxy"]);
    }

    #[tokio::test]
    async fn overwrite_route_takes_priority_over_an_existing_route() {
        let config = SystemProxyConfig::default().with_http_proxy(proxy(
            Protocol::HTTP,
            "system.proxy",
            8080,
        ));
        let request = TestInput::new("http://example.com/");
        request.extensions.insert(ProxyRoute::Direct);
        let (inner, seen) = recorder();

        SystemProxyLayer::from_cached(config)
            .with_overwrite(true)
            .into_layer(inner)
            .serve(request)
            .await
            .unwrap();

        let seen = seen.lock();
        let routes = seen[0].as_ref().unwrap();
        assert_eq!(
            routes.as_slice()[0]
                .proxy_address()
                .unwrap()
                .address
                .host
                .to_str(),
            "system.proxy"
        );
    }

    #[tokio::test]
    async fn pac_receives_full_uri_and_cloned_extensions() {
        let pac_uri: Uri = "http://config.example/proxy.pac".parse().unwrap();
        let factory_seen = Arc::new(Mutex::new(Vec::new()));
        let resolver_seen = Arc::new(Mutex::new(Vec::new()));
        let factory = service_fn({
            let factory_seen = factory_seen.clone();
            let resolver_seen = resolver_seen.clone();
            move |uri: Uri| {
                factory_seen.lock().push(uri);
                let resolver_seen = resolver_seen.clone();
                async move {
                    Ok::<_, Infallible>(service_fn(move |request: SystemProxyPacRequest| {
                        resolver_seen.lock().push((
                            request.uri.clone(),
                            request.extensions().get_ref::<Marker>().cloned(),
                        ));
                        async move {
                            Ok::<_, Infallible>(Some(ProxyRoutes::from(proxy(
                                Protocol::HTTP,
                                "pac.proxy",
                                8080,
                            ))))
                        }
                    }))
                }
            }
        });
        let config = SystemProxyConfig::default().with_pac_uri(pac_uri.clone());
        let request = TestInput::new("https://example.com/private?q=1");
        request.extensions.insert(Marker("kept"));
        let inner = service_fn(async |input: TestInput| Ok::<_, Infallible>(input));

        let output = SystemProxyLayer::from_cached(config)
            .with_pac_service(factory)
            .into_layer(inner)
            .serve(request)
            .await
            .unwrap();

        assert_eq!(factory_seen.lock().as_slice(), [pac_uri]);
        let resolved = resolver_seen.lock();
        assert_eq!(resolved[0].0.to_string(), "https://example.com/private?q=1");
        assert_eq!(resolved[0].1.as_ref().unwrap().0, "kept");
        assert_eq!(
            output
                .extensions
                .get_ref::<ProxyRoutes>()
                .unwrap()
                .as_slice()[0]
                .proxy_address()
                .unwrap()
                .address
                .host
                .to_str(),
            "pac.proxy"
        );
        assert!(output.extensions.get_ref::<ProxyRoute>().is_none());
    }

    #[tokio::test]
    async fn pac_factory_errors_fail_the_request_with_context() {
        let factory = service_fn(|_uri: Uri| async {
            Err::<SystemProxyPacDisabledResolver, _>(std::io::Error::other("PAC fetch failed"))
        });
        let config = SystemProxyConfig::default()
            .with_pac_uri("https://config.example/proxy.pac".parse().unwrap());
        let (inner, seen) = recorder();

        let error = SystemProxyLayer::from_cached(config)
            .with_pac_service(factory)
            .into_layer(inner)
            .serve(TestInput::new("https://example.com/"))
            .await
            .unwrap_err();

        assert!(error.to_string().contains("create system PAC resolver"));
        assert!(seen.lock().is_empty());
    }

    #[tokio::test]
    async fn pac_resolver_errors_fail_the_request_with_context() {
        let factory = service_fn(|_uri: Uri| async {
            Ok::<_, Infallible>(service_fn(|_request: SystemProxyPacRequest| async {
                Err::<Option<ProxyRoutes>, _>(std::io::Error::other("PAC evaluation failed"))
            }))
        });
        let config = SystemProxyConfig::default()
            .with_pac_uri("https://config.example/proxy.pac".parse().unwrap());
        let (inner, seen) = recorder();

        let error = SystemProxyLayer::from_cached(config)
            .with_pac_service(factory)
            .into_layer(inner)
            .serve(TestInput::new("https://example.com/"))
            .await
            .unwrap_err();

        assert!(error.to_string().contains("resolve system PAC routes"));
        assert!(seen.lock().is_empty());
    }

    #[tokio::test]
    async fn pac_receives_an_absolute_uri_for_origin_form_input() {
        let received = Arc::new(Mutex::new(None));
        let factory = service_fn({
            let received = received.clone();
            move |_uri: Uri| {
                let received = received.clone();
                async move {
                    Ok::<_, Infallible>(service_fn(move |request: SystemProxyPacRequest| {
                        *received.lock() = Some(request.uri);
                        async { Ok::<_, Infallible>(None) }
                    }))
                }
            }
        });
        let config = SystemProxyConfig::default()
            .with_pac_uri("https://config.example/proxy.pac".parse().unwrap());
        let (inner, _) = recorder();

        SystemProxyLayer::from_cached(config)
            .with_pac_service(factory)
            .into_layer(inner)
            .serve(TestInput::origin_form(
                "/private?q=1",
                Protocol::HTTPS,
                "example.com:8443",
            ))
            .await
            .unwrap();

        assert_eq!(
            received.lock().as_ref().unwrap().to_string(),
            "https://example.com:8443/private?q=1"
        );
    }

    #[tokio::test]
    async fn pac_normalizes_default_ports_with_an_unboxed_resolver() {
        let factory_calls = Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let received = Arc::new(Mutex::new(Vec::new()));
        let factory = service_fn({
            let factory_calls = factory_calls.clone();
            let received = received.clone();
            move |_uri: Uri| {
                factory_calls.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                let received = received.clone();
                async move {
                    Ok::<_, Infallible>(service_fn(move |request: SystemProxyPacRequest| {
                        received.lock().push(request.uri);
                        async { Ok::<_, Infallible>(None) }
                    }))
                }
            }
        });
        let config = SystemProxyConfig::default()
            .with_pac_uri("https://config.example/proxy.pac".parse().unwrap());
        let (inner, _) = recorder();
        let service = SystemProxyLayer::from_cached(config)
            .with_pac_service(factory)
            .into_layer(inner);

        for input in [
            TestInput::new("http://example.com:80/path"),
            TestInput::new("https://example.com:443/"),
            TestInput::new("http://example.com:8080/"),
            TestInput::authority_form("example.com:443"),
        ] {
            service.serve(input).await.unwrap();
        }

        assert_eq!(factory_calls.load(std::sync::atomic::Ordering::Relaxed), 4);
        assert_eq!(
            received
                .lock()
                .iter()
                .map(ToString::to_string)
                .collect::<Vec<_>>(),
            [
                "http://example.com/path",
                "https://example.com/",
                "http://example.com:8080/",
                "https://example.com/",
            ]
        );
    }

    #[tokio::test]
    async fn authority_form_selects_the_https_proxy() {
        let config = SystemProxyConfig::default().with_https_proxy(proxy(
            Protocol::HTTP,
            "https.proxy",
            8443,
        ));
        let (inner, seen) = recorder();

        SystemProxyLayer::from_cached(config)
            .into_layer(inner)
            .serve(TestInput::authority_form("example.com:443"))
            .await
            .unwrap();

        let routes = seen.lock();
        assert_eq!(
            routes[0].as_ref().unwrap().as_slice()[0]
                .proxy_address()
                .unwrap()
                .address
                .host
                .to_str(),
            "https.proxy"
        );
    }

    #[tokio::test]
    async fn pac_without_a_service_leaves_the_request_undecided() {
        let config = SystemProxyConfig::default()
            .with_pac_uri("http://config.example/proxy.pac".parse().unwrap());
        let (inner, seen) = recorder();

        SystemProxyLayer::from_cached(config)
            .into_layer(inner)
            .serve(TestInput::new("/relative"))
            .await
            .unwrap();

        assert!(seen.lock()[0].is_none());
    }

    #[tokio::test]
    async fn pac_without_a_service_uses_a_fixed_proxy_fallback() {
        let config = SystemProxyConfig::default()
            .with_http_proxy(proxy(Protocol::HTTP, "fixed.proxy", 8080))
            .with_pac_uri("http://config.example/proxy.pac".parse().unwrap());
        let (inner, seen) = recorder();

        SystemProxyLayer::from_cached(config)
            .into_layer(inner)
            .serve(TestInput::new("http://example.com/"))
            .await
            .unwrap();

        assert_eq!(
            seen.lock()[0].as_ref().unwrap().as_slice()[0]
                .proxy_address()
                .unwrap()
                .address
                .host
                .to_str(),
            "fixed.proxy"
        );
    }

    #[tokio::test]
    async fn active_pac_requires_a_resolvable_authority() {
        let factory = service_fn(|_uri: Uri| async {
            Ok::<_, Infallible>(service_fn(|_request| async { Ok::<_, Infallible>(None) }))
        });
        let config = SystemProxyConfig::default()
            .with_pac_uri("http://config.example/proxy.pac".parse().unwrap());
        let (inner, _) = recorder();

        SystemProxyLayer::from_cached(config)
            .with_pac_service(factory)
            .into_layer(inner)
            .serve(TestInput::new("/relative"))
            .await
            .unwrap_err();
    }

    #[tokio::test]
    async fn singular_route_also_prevents_pac_lookup() {
        let factory_calls = Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let factory = service_fn({
            let factory_calls = factory_calls.clone();
            move |_uri: Uri| {
                factory_calls.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                async move {
                    Ok::<_, Infallible>(service_fn(|_request| async { Ok::<_, Infallible>(None) }))
                }
            }
        });
        let config = SystemProxyConfig::default()
            .with_pac_uri("https://config.example/proxy.pac".parse().unwrap());
        let request = TestInput::new("https://example.com/");
        request.extensions.insert(ProxyRoute::Direct);
        let (inner, _) = recorder();

        SystemProxyLayer::from_cached(config)
            .with_pac_service(factory)
            .into_layer(inner)
            .serve(request)
            .await
            .unwrap();

        assert_eq!(factory_calls.load(std::sync::atomic::Ordering::Relaxed), 0);
    }

    #[tokio::test]
    async fn an_existing_route_prevents_system_config_refresh() {
        let calls = Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let reader = BoxService::new(service_fn({
            let calls = calls.clone();
            move |()| {
                calls.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                async {
                    Ok::<_, BoxError>(SystemProxyConfig::default().with_http_proxy(proxy(
                        Protocol::HTTP,
                        "system.proxy",
                        8080,
                    )))
                }
            }
        }));
        let layer = SystemProxyLayer::try_from_system_with_reader(Duration::ZERO, reader)
            .await
            .unwrap();
        let request = TestInput::new("http://example.com/");
        request.extensions.insert(ProxyRoute::Direct);
        let (inner, _) = recorder();

        layer.into_layer(inner).serve(request).await.unwrap();
        tokio::time::sleep(Duration::from_millis(50)).await;

        assert_eq!(calls.load(std::sync::atomic::Ordering::Relaxed), 1);
    }

    #[tokio::test]
    async fn bypass_and_inverted_bypass_select_direct_routes() {
        let base = SystemProxyConfig::default()
            .with_http_proxy(proxy(Protocol::HTTP, "system.proxy", 8080))
            .with_bypass([".example.com", "default-port.test:80"]);
        let (inner, seen) = recorder();
        let service = SystemProxyLayer::from_cached(base.clone()).into_layer(inner.clone());
        service
            .serve(TestInput::new("http://api.example.com/"))
            .await
            .unwrap();
        service
            .serve(TestInput::new("http://elsewhere.test/"))
            .await
            .unwrap();
        service
            .serve(TestInput::new("http://default-port.test/"))
            .await
            .unwrap();

        let inverted =
            SystemProxyLayer::from_cached(base.with_reversed_bypass(true)).into_layer(inner);
        inverted
            .serve(TestInput::new("http://api.example.com/"))
            .await
            .unwrap();
        inverted
            .serve(TestInput::new("http://elsewhere.test/"))
            .await
            .unwrap();

        let seen = seen.lock();
        assert!(matches!(
            seen[0].as_ref().unwrap().as_slice(),
            [ProxyRoute::Direct]
        ));
        assert!(matches!(
            seen[1].as_ref().unwrap().as_slice(),
            [ProxyRoute::Proxy(_)]
        ));
        assert!(matches!(
            seen[2].as_ref().unwrap().as_slice(),
            [ProxyRoute::Direct]
        ));
        assert!(matches!(
            seen[3].as_ref().unwrap().as_slice(),
            [ProxyRoute::Proxy(_)]
        ));
        assert!(matches!(
            seen[4].as_ref().unwrap().as_slice(),
            [ProxyRoute::Direct]
        ));
    }

    #[tokio::test]
    async fn simple_hostname_bypass_is_opt_in() {
        let config = SystemProxyConfig::default()
            .with_http_proxy(proxy(Protocol::HTTP, "system.proxy", 8080))
            .with_exclude_simple_hostnames(true);
        let (inner, seen) = recorder();
        let service = SystemProxyLayer::from_cached(config).into_layer(inner);

        service
            .serve(TestInput::new("http://printer/"))
            .await
            .unwrap();
        service
            .serve(TestInput::new("http://printer.example/"))
            .await
            .unwrap();
        service
            .serve(TestInput::new("http://[2001:db8::1]/"))
            .await
            .unwrap();

        let seen = seen.lock();
        assert!(matches!(
            seen[0].as_ref().unwrap().as_slice(),
            [ProxyRoute::Direct]
        ));
        assert!(matches!(
            seen[1].as_ref().unwrap().as_slice(),
            [ProxyRoute::Proxy(_)]
        ));
        assert!(matches!(
            seen[2].as_ref().unwrap().as_slice(),
            [ProxyRoute::Proxy(_)]
        ));
    }

    #[tokio::test]
    async fn inverted_simple_hostname_bypass_uses_only_simple_names() {
        let config = SystemProxyConfig::default()
            .with_http_proxy(proxy(Protocol::HTTP, "system.proxy", 8080))
            .with_exclude_simple_hostnames(true)
            .with_reversed_bypass(true);
        let (inner, seen) = recorder();
        let service = SystemProxyLayer::from_cached(config).into_layer(inner);

        service
            .serve(TestInput::new("http://printer/"))
            .await
            .unwrap();
        service
            .serve(TestInput::new("http://printer.example/"))
            .await
            .unwrap();

        let seen = seen.lock();
        assert!(matches!(
            seen[0].as_ref().unwrap().as_slice(),
            [ProxyRoute::Proxy(_)]
        ));
        assert!(matches!(
            seen[1].as_ref().unwrap().as_slice(),
            [ProxyRoute::Direct]
        ));
    }

    #[tokio::test]
    async fn fixed_system_proxies_implicitly_bypass_loopback() {
        let config = SystemProxyConfig::default()
            .with_http_proxy(proxy(Protocol::HTTP, "system.proxy", 8080))
            .with_bypass(["localhost", "127.0.0.0/8", "::1", "remote.example"])
            .with_reversed_bypass(true);
        let (inner, seen) = recorder();
        let service = SystemProxyLayer::from_cached(config).into_layer(inner);

        for uri in [
            "http://localhost/",
            "http://service.localhost/",
            "http://127.42.0.1/",
            "http://[::1]/",
            "http://remote.example/",
        ] {
            service.serve(TestInput::new(uri)).await.unwrap();
        }

        let seen = seen.lock();
        for routes in &seen[..4] {
            assert!(matches!(
                routes.as_ref().unwrap().as_slice(),
                [ProxyRoute::Direct]
            ));
        }
        assert!(matches!(
            seen[4].as_ref().unwrap().as_slice(),
            [ProxyRoute::Proxy(_)]
        ));
    }

    #[tokio::test]
    async fn pac_is_not_consulted_for_loopback() {
        let calls = Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let factory = service_fn({
            let calls = calls.clone();
            move |_uri: Uri| {
                calls.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                async {
                    Ok::<_, Infallible>(service_fn(|_request| async {
                        Ok::<_, Infallible>(Some(ProxyRoutes::from(ProxyRoute::Direct)))
                    }))
                }
            }
        });
        let config = SystemProxyConfig::default()
            .with_pac_uri("https://config.example/proxy.pac".parse().unwrap());
        let (inner, seen) = recorder();
        let service = SystemProxyLayer::from_cached(config)
            .with_pac_service(factory)
            .into_layer(inner);

        for uri in [
            "http://localhost/",
            "http://service.localhost/",
            "http://127.42.0.1/",
            "http://[::1]/",
        ] {
            service.serve(TestInput::new(uri)).await.unwrap();
        }

        assert_eq!(calls.load(std::sync::atomic::Ordering::Relaxed), 0);
        assert!(
            seen.lock()
                .iter()
                .all(|routes| matches!(routes.as_ref().unwrap().as_slice(), [ProxyRoute::Direct]))
        );
    }

    #[test]
    fn platform_bypass_precedence_controls_pac_decision() {
        let pac_uri: Uri = "https://config.example/proxy.pac".parse().unwrap();
        let uri: Uri = "https://bypass.example/".parse().unwrap();
        let mut config = SystemProxyConfig::default()
            .with_pac_uri(pac_uri.clone())
            .with_bypass(["bypass.example"]);

        assert!(matches!(
            config.decision(&uri),
            SystemProxyDecision::Pac(uri) if uri == pac_uri
        ));

        config.bypass_before_pac = true;
        assert!(matches!(
            config.decision(&uri),
            SystemProxyDecision::Route(ProxyRoute::Direct)
        ));
    }

    #[test]
    fn config_accessors_and_public_pac_request_fields_round_trip() {
        let http = proxy(Protocol::HTTP, "http.proxy", 8080);
        let https = proxy(Protocol::HTTP, "https.proxy", 8443);
        let socks = proxy(Protocol::SOCKS5, "socks.proxy", 1080);
        let pac: Uri = "https://config.example/proxy.pac".parse().unwrap();
        let config = SystemProxyConfig::default()
            .with_http_proxy(http.clone())
            .with_https_proxy(https.clone())
            .with_socks5_proxy(socks.clone())
            .with_pac_uri(pac.clone())
            .with_bypass(["localhost"])
            .with_exclude_simple_hostnames(true)
            .with_reversed_bypass(true)
            .with_auto_detect(true);

        assert!(!config.is_empty());
        assert_eq!(config.http_proxy(), Some(&http));
        assert_eq!(config.https_proxy(), Some(&https));
        assert_eq!(config.socks5_proxy(), Some(&socks));
        assert_eq!(config.pac_uri(), Some(&pac));
        assert_eq!(config.bypass().collect::<Vec<_>>(), ["localhost"]);
        assert!(config.exclude_simple_hostnames());
        assert!(config.reversed_bypass());
        assert!(config.auto_detect());

        let extensions = Extensions::new();
        extensions.insert(Marker("parts"));
        let request =
            SystemProxyPacRequest::new(extensions, "http://example.com/path".parse().unwrap())
                .unwrap();
        assert_eq!(
            UriInputExt::uri(&request).to_string(),
            "http://example.com/path"
        );
        assert_eq!(
            ExtensionsRef::extensions(&request)
                .get_ref::<Marker>()
                .unwrap()
                .0,
            "parts"
        );
        assert_eq!(request.extensions.get_ref::<Marker>().unwrap().0, "parts");
        assert_eq!(request.uri.to_string(), "http://example.com/path");
    }

    #[test]
    fn platform_proxy_host_accepts_a_scheme_prefix() {
        let proxy = proxy_address(Protocol::HTTP, "http://proxy.corp", 8080).unwrap();
        assert_eq!(proxy.to_string(), "http://proxy.corp:8080");
    }

    #[cfg(any(target_os = "macos", target_os = "windows", target_os = "linux"))]
    #[tokio::test]
    async fn native_system_proxy_snapshot_can_be_read() {
        SystemProxyConfig::try_from_system().await.unwrap();
    }

    #[test]
    fn every_proxy_source_independently_makes_config_non_empty() {
        assert!(SystemProxyConfig::default().is_empty());
        for config in [
            SystemProxyConfig::default().with_http_proxy(proxy(Protocol::HTTP, "http.proxy", 8080)),
            SystemProxyConfig::default().with_https_proxy(proxy(
                Protocol::HTTP,
                "https.proxy",
                8443,
            )),
            SystemProxyConfig::default().with_socks5_proxy(proxy(
                Protocol::SOCKS5,
                "socks.proxy",
                1080,
            )),
            SystemProxyConfig::default()
                .with_pac_uri("https://config.example/proxy.pac".parse().unwrap()),
            SystemProxyConfig::default().with_auto_detect(true),
        ] {
            assert!(!config.is_empty());
        }
    }

    #[test]
    fn pac_request_rejects_non_absolute_or_hostless_uri() {
        SystemProxyPacRequest::new(Extensions::new(), "/path".parse().unwrap()).unwrap_err();
        SystemProxyPacRequest::new(Extensions::new(), "data:text/plain,x".parse().unwrap())
            .unwrap_err();
    }

    #[test]
    fn bypass_patterns_cover_domains_ports_ip_ranges_and_local_names() {
        for (pattern, scheme, host, port, expected) in [
            ("*", None, "anything.example", None, true),
            ("<local>", None, "printer", None, true),
            ("<local>", None, "printer.example", None, false),
            ("<local>", None, "2001:db8::1", None, false),
            ("192.168.*", None, "192.168.10.20", None, true),
            ("*corp*", None, "api.corp.example", None, true),
            ("*.example.com", None, "api.example.com", None, true),
            ("*.example.com", None, "example.com", None, true),
            (".example.com", None, "api.example.com.", None, true),
            (".example.com", None, "notexample.com", None, false),
            (
                "api.example.com:8443",
                None,
                "api.example.com",
                Some(8443),
                true,
            ),
            (
                "api.example.com:8443",
                None,
                "api.example.com",
                Some(443),
                false,
            ),
            ("10.0.0.0/8", None, "10.2.3.4", None, true),
            ("10.0.0.0/8", None, "11.2.3.4", None, false),
            ("[::1]", None, "::1", None, true),
            ("::1", None, "::1", None, true),
            ("[::1]:8443", None, "::1", Some(8443), true),
            ("[::1]:8443", None, "::1", Some(443), false),
            ("2001:db8::/32", None, "2001:db8::1", None, true),
            (
                "https://secure.example:443",
                Some(Protocol::HTTPS),
                "secure.example",
                Some(443),
                true,
            ),
            (
                "https://secure.example:443",
                Some(Protocol::HTTP),
                "secure.example",
                Some(443),
                false,
            ),
        ] {
            let host = Host::try_from(host).unwrap();
            let host_text = host.to_string();
            assert_eq!(
                BypassRule::compile(pattern).unwrap().matches(
                    scheme.as_ref(),
                    (&host).into(),
                    port,
                ),
                expected,
                "{pattern} {host_text:?} {port:?}"
            );
        }
    }

    #[test]
    fn invalid_bypass_patterns_are_discarded() {
        let config =
            SystemProxyConfig::default().with_bypass(["example.com", ".not a valid domain", ""]);

        assert_eq!(config.bypass().collect::<Vec<_>>(), ["example.com"]);
    }

    #[test]
    fn invalid_bypass_policy_can_reject_an_update_atomically() {
        let mut config = SystemProxyConfig::default().with_bypass(["existing.example"]);

        let error = config
            .try_set_bypass(
                ["replacement.example", ".not a valid domain"],
                SystemProxyInvalidBypassRulePolicy::Reject,
            )
            .unwrap_err();

        assert!(
            error
                .to_string()
                .contains("parse system proxy bypass pattern")
        );
        assert_eq!(config.bypass().collect::<Vec<_>>(), ["existing.example"]);

        config
            .try_set_bypass(
                ["replacement.example", ".not a valid domain"],
                SystemProxyInvalidBypassRulePolicy::Ignore,
            )
            .unwrap();
        assert_eq!(config.bypass().collect::<Vec<_>>(), ["replacement.example"]);
    }

    #[tokio::test]
    async fn lazy_layer_construction_does_not_read_until_warmed() {
        let calls = Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let reader = BoxService::new(service_fn({
            let calls = calls.clone();
            move |()| {
                calls.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                async {
                    Ok::<_, BoxError>(SystemProxyConfig::default().with_http_proxy(proxy(
                        Protocol::HTTP,
                        "lazy.proxy",
                        8080,
                    )))
                }
            }
        }));
        let layer = SystemProxyLayer::new_with_reader(Duration::from_mins(1), reader);

        assert!(layer.cached_config().is_none());
        assert_eq!(calls.load(std::sync::atomic::Ordering::Relaxed), 0);

        layer.warm_up().await.unwrap();
        layer.warm_up().await.unwrap();

        let config = layer.cached_config().unwrap();
        assert_eq!(
            config.http_proxy().unwrap().address.host.to_str(),
            "lazy.proxy"
        );
        assert_eq!(calls.load(std::sync::atomic::Ordering::Relaxed), 1);
    }

    #[tokio::test]
    async fn change_trigger_refreshes_a_fresh_snapshot() {
        let calls = Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let changed = Arc::new(std::sync::atomic::AtomicBool::new(false));
        let reader = BoxService::new(service_fn({
            let calls = calls.clone();
            move |()| {
                let call = calls.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                async move {
                    let host = if call == 0 { "old.proxy" } else { "new.proxy" };
                    Ok::<_, BoxError>(SystemProxyConfig::default().with_http_proxy(proxy(
                        Protocol::HTTP,
                        host,
                        8080,
                    )))
                }
            }
        }));
        let trigger = service_fn({
            let changed = changed.clone();
            move |()| {
                let changed = changed.swap(false, std::sync::atomic::Ordering::AcqRel);
                async move { Ok::<_, std::convert::Infallible>(changed) }
            }
        });
        let layer = SystemProxyLayer::new_with_reader(Duration::from_mins(1), reader)
            .with_config_change_trigger(trigger);

        let old = layer.config().await.unwrap();
        assert_eq!(old.http_proxy().unwrap().address.host.to_str(), "old.proxy");
        changed.store(true, std::sync::atomic::Ordering::Release);
        let new = layer.config().await.unwrap();
        let still_new = layer.config().await.unwrap();

        assert_eq!(new.http_proxy().unwrap().address.host.to_str(), "new.proxy");
        assert!(Arc::ptr_eq(&new, &still_new));
        assert_eq!(calls.load(std::sync::atomic::Ordering::Relaxed), 2);
    }

    #[tokio::test]
    async fn change_during_refresh_remains_pending_for_the_next_request() {
        let reads = Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let changed = Arc::new(std::sync::atomic::AtomicBool::new(false));
        let refresh_started = Arc::new(tokio::sync::Notify::new());
        let release_refresh = Arc::new(tokio::sync::Notify::new());
        let reader = BoxService::new(service_fn({
            let reads = reads.clone();
            let refresh_started = refresh_started.clone();
            let release_refresh = release_refresh.clone();
            move |()| {
                let call = reads.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                let refresh_started = refresh_started.clone();
                let release_refresh = release_refresh.clone();
                async move {
                    if call == 0 {
                        refresh_started.notify_one();
                        release_refresh.notified().await;
                    }
                    let host = if call == 0 {
                        "first-refresh.proxy"
                    } else {
                        "second-refresh.proxy"
                    };
                    Ok::<_, BoxError>(SystemProxyConfig::default().with_http_proxy(proxy(
                        Protocol::HTTP,
                        host,
                        8080,
                    )))
                }
            }
        }));
        let trigger = service_fn({
            let changed = changed.clone();
            move |()| {
                let changed = changed.swap(false, std::sync::atomic::Ordering::AcqRel);
                async move { Ok::<_, Infallible>(changed) }
            }
        });
        let cached = SystemProxyConfig::default().with_http_proxy(proxy(
            Protocol::HTTP,
            "cached.proxy",
            8080,
        ));
        let layer =
            SystemProxyLayer::from_cached_with_reader(cached, Duration::from_mins(1), reader)
                .with_config_change_trigger(trigger);

        changed.store(true, std::sync::atomic::Ordering::Release);
        let first_layer = layer.clone();
        let first = tokio::spawn(async move { first_layer.config().await });
        refresh_started.notified().await;

        changed.store(true, std::sync::atomic::Ordering::Release);
        let stale = layer.config().await.unwrap();
        assert_eq!(stale.http_proxy().unwrap().address.host, "cached.proxy");

        release_refresh.notify_one();
        let first = first.await.unwrap().unwrap();
        assert_eq!(
            first.http_proxy().unwrap().address.host,
            "first-refresh.proxy"
        );
        let second = layer.config().await.unwrap();
        assert_eq!(
            second.http_proxy().unwrap().address.host,
            "second-refresh.proxy"
        );
        assert_eq!(reads.load(std::sync::atomic::Ordering::Relaxed), 2);
    }

    #[tokio::test]
    async fn cancelled_triggered_refresh_does_not_consume_the_request() {
        let reads = Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let changed = Arc::new(std::sync::atomic::AtomicBool::new(true));
        let refresh_started = Arc::new(tokio::sync::Notify::new());
        let reader = BoxService::new(service_fn({
            let reads = reads.clone();
            let refresh_started = refresh_started.clone();
            move |()| {
                let call = reads.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                let refresh_started = refresh_started.clone();
                async move {
                    if call == 0 {
                        refresh_started.notify_one();
                        std::future::pending::<()>().await;
                    }
                    Ok::<_, BoxError>(SystemProxyConfig::default().with_http_proxy(proxy(
                        Protocol::HTTP,
                        "refreshed.proxy",
                        8080,
                    )))
                }
            }
        }));
        let trigger = service_fn({
            let changed = changed.clone();
            move |()| {
                let changed = changed.swap(false, std::sync::atomic::Ordering::AcqRel);
                async move { Ok::<_, Infallible>(changed) }
            }
        });
        let cached = SystemProxyConfig::default().with_http_proxy(proxy(
            Protocol::HTTP,
            "cached.proxy",
            8080,
        ));
        let layer =
            SystemProxyLayer::from_cached_with_reader(cached, Duration::from_mins(1), reader)
                .with_config_change_trigger(trigger);

        let refresh_layer = layer.clone();
        let refresh = tokio::spawn(async move { refresh_layer.config().await });
        refresh_started.notified().await;
        assert_eq!(
            layer
                .config()
                .await
                .unwrap()
                .http_proxy()
                .unwrap()
                .address
                .host,
            "cached.proxy"
        );
        refresh.abort();
        refresh.await.unwrap_err();

        let refreshed = layer.config().await.unwrap();
        assert_eq!(
            refreshed.http_proxy().unwrap().address.host,
            "refreshed.proxy"
        );
        assert_eq!(reads.load(std::sync::atomic::Ordering::Relaxed), 2);
    }

    #[tokio::test]
    async fn failed_triggered_refresh_is_acknowledged_until_the_ttl() {
        let reads = Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let changed = Arc::new(std::sync::atomic::AtomicBool::new(true));
        let reader = BoxService::new(service_fn({
            let reads = reads.clone();
            move |()| {
                reads.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                async {
                    Err::<SystemProxyConfig, BoxError>(std::io::Error::other("offline").into())
                }
            }
        }));
        let trigger = service_fn({
            let changed = changed.clone();
            move |()| {
                let changed = changed.swap(false, std::sync::atomic::Ordering::AcqRel);
                async move { Ok::<_, Infallible>(changed) }
            }
        });
        let layer = SystemProxyLayer::from_cached_with_reader(
            SystemProxyConfig::default(),
            Duration::from_mins(1),
            reader,
        )
        .with_config_change_trigger(trigger);

        layer.config().await.unwrap();
        layer.config().await.unwrap();
        assert_eq!(reads.load(std::sync::atomic::Ordering::Relaxed), 1);
    }

    #[tokio::test]
    async fn disabled_change_trigger_retains_ttl_refresh() {
        let reads = Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let triggers = Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let reader = BoxService::new(service_fn({
            let reads = reads.clone();
            move |()| {
                reads.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                async { Ok::<_, BoxError>(SystemProxyConfig::default()) }
            }
        }));
        let trigger = service_fn({
            let triggers = triggers.clone();
            move |()| {
                triggers.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                async { Ok::<_, std::convert::Infallible>(true) }
            }
        });
        let layer = SystemProxyLayer::new_with_reader(Duration::ZERO, reader)
            .with_config_change_trigger(trigger)
            .without_config_change_trigger();

        layer.config().await.unwrap();
        layer.config().await.unwrap();

        assert_eq!(reads.load(std::sync::atomic::Ordering::Relaxed), 2);
        assert_eq!(triggers.load(std::sync::atomic::Ordering::Relaxed), 0);
    }

    #[tokio::test]
    async fn disabled_refresh_makes_a_cached_snapshot_immutable() {
        let reads = Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let reader = BoxService::new(service_fn({
            let reads = reads.clone();
            move |()| {
                reads.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                async { Ok::<_, BoxError>(SystemProxyConfig::default()) }
            }
        }));
        let cached = SystemProxyConfig::default().with_http_proxy(proxy(
            Protocol::HTTP,
            "cached.proxy",
            8080,
        ));
        let layer = SystemProxyLayer::from_cached_with_reader(cached, Duration::ZERO, reader)
            .with_config_refresh(false);

        for _ in 0..2 {
            assert_eq!(
                layer
                    .config()
                    .await
                    .unwrap()
                    .http_proxy()
                    .unwrap()
                    .address
                    .host
                    .to_str(),
                "cached.proxy"
            );
        }
        assert_eq!(reads.load(std::sync::atomic::Ordering::Relaxed), 0);
    }

    #[tokio::test]
    async fn change_trigger_errors_fall_back_to_the_ttl() {
        let reads = Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let errors = Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let reader = BoxService::new(service_fn({
            let reads = reads.clone();
            move |()| {
                reads.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                async { Ok::<_, BoxError>(SystemProxyConfig::default()) }
            }
        }));
        let trigger = service_fn(|()| async {
            Err::<bool, _>(std::io::Error::other("configuration watcher failed"))
        });
        let layer = SystemProxyLayer::new_with_reader(Duration::from_mins(1), reader)
            .with_config_change_trigger(trigger)
            .with_config_change_trigger_error_sink({
                let errors = errors.clone();
                move |_error: BoxError| {
                    errors.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                }
            });

        layer.config().await.unwrap();
        layer.config().await.unwrap();

        assert_eq!(reads.load(std::sync::atomic::Ordering::Relaxed), 1);
        assert_eq!(errors.load(std::sync::atomic::Ordering::Relaxed), 2);
    }

    #[tokio::test]
    async fn first_request_lazily_loads_and_applies_system_proxy() {
        let calls = Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let reader = BoxService::new(service_fn({
            let calls = calls.clone();
            move |()| {
                calls.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                async {
                    Ok::<_, BoxError>(SystemProxyConfig::default().with_http_proxy(proxy(
                        Protocol::HTTP,
                        "lazy.proxy",
                        8080,
                    )))
                }
            }
        }));
        let layer = SystemProxyLayer::new_with_reader(Duration::from_mins(1), reader);
        let (inner, seen) = recorder();
        let service = layer.into_layer(inner);

        assert_eq!(calls.load(std::sync::atomic::Ordering::Relaxed), 0);
        service
            .serve(TestInput::new("http://example.com/"))
            .await
            .unwrap();

        assert_eq!(calls.load(std::sync::atomic::Ordering::Relaxed), 1);
        assert_eq!(
            seen.lock()[0].as_ref().unwrap().as_slice()[0]
                .proxy_address()
                .unwrap()
                .address
                .host
                .to_str(),
            "lazy.proxy"
        );
    }

    #[tokio::test]
    async fn concurrent_cold_loads_share_one_async_read() {
        let calls = Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let reader = BoxService::new(service_fn({
            let calls = calls.clone();
            move |()| {
                calls.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                async {
                    tokio::time::sleep(Duration::from_millis(20)).await;
                    Ok::<_, BoxError>(SystemProxyConfig::default())
                }
            }
        }));
        let layer = SystemProxyLayer::new_with_reader(Duration::from_mins(1), reader);

        let (first, second, third) = tokio::join!(layer.config(), layer.config(), layer.config());

        first.unwrap();
        second.unwrap();
        third.unwrap();
        assert_eq!(calls.load(std::sync::atomic::Ordering::Relaxed), 1);
    }

    #[tokio::test]
    async fn failed_cold_load_remains_retryable() {
        let calls = Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let reader = BoxService::new(service_fn({
            let calls = calls.clone();
            move |()| {
                let call = calls.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                async move {
                    if call == 0 {
                        Err(std::io::Error::other("temporary platform read failure").into())
                    } else {
                        Ok(SystemProxyConfig::default())
                    }
                }
            }
        }));
        let layer = SystemProxyLayer::new_with_reader(Duration::from_mins(1), reader);

        layer.config().await.unwrap_err();
        assert!(layer.cached_config().is_none());
        layer.config().await.unwrap();
        assert_eq!(calls.load(std::sync::atomic::Ordering::Relaxed), 2);
    }

    #[tokio::test]
    async fn handled_cold_load_error_is_sunk_and_cached_for_the_ttl() {
        let reads = Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let errors = Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let reader = BoxService::new(service_fn({
            let reads = reads.clone();
            move |()| {
                reads.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                async {
                    Err::<SystemProxyConfig, BoxError>(
                        std::io::Error::other("platform read failed").into(),
                    )
                }
            }
        }));
        let layer = SystemProxyLayer::new_with_reader(Duration::from_mins(1), reader)
            .with_load_error_sink({
                let errors = errors.clone();
                move |error: BoxError| {
                    assert_eq!(error.to_string(), "platform read failed");
                    errors.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                }
            });

        assert!(layer.config().await.unwrap().is_empty());
        assert!(layer.config().await.unwrap().is_empty());
        assert_eq!(reads.load(std::sync::atomic::Ordering::Relaxed), 1);
        assert_eq!(errors.load(std::sync::atomic::Ordering::Relaxed), 1);
    }

    #[tokio::test]
    async fn native_change_trigger_is_initialized_only_when_polled() {
        let reader = || {
            BoxService::new(service_fn(|()| async {
                Ok::<_, BoxError>(SystemProxyConfig::default())
            }))
        };
        let trigger_initialized = |layer: &SystemProxyLayer| match &layer.refresh.trigger {
            Some(SystemProxyConfigChangeTrigger::Platform(trigger)) => trigger.is_initialized(),
            _ => panic!("expected the default platform change trigger"),
        };

        let disabled = SystemProxyLayer::from_cached_with_reader(
            SystemProxyConfig::default(),
            Duration::ZERO,
            reader(),
        )
        .with_config_refresh(false);
        assert!(!trigger_initialized(&disabled));
        disabled.config().await.unwrap();
        assert!(!trigger_initialized(&disabled));

        let enabled = SystemProxyLayer::new_with_reader(Duration::from_mins(1), reader());
        assert!(!trigger_initialized(&enabled));
        enabled.config().await.unwrap();
        assert!(trigger_initialized(&enabled));
    }

    #[tokio::test]
    async fn concurrent_cold_failure_is_shared_without_a_retry_convoy() {
        let calls = Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let read_started = Arc::new(tokio::sync::Notify::new());
        let release_read = Arc::new(tokio::sync::Notify::new());
        let reader = BoxService::new(service_fn({
            let calls = calls.clone();
            let read_started = read_started.clone();
            let release_read = release_read.clone();
            move |()| {
                let call = calls.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                let read_started = read_started.clone();
                let release_read = release_read.clone();
                async move {
                    if call == 0 {
                        read_started.notify_one();
                        release_read.notified().await;
                        Err(std::io::Error::other("temporary platform read failure").into())
                    } else {
                        Ok(SystemProxyConfig::default())
                    }
                }
            }
        }));
        let layer = SystemProxyLayer::new_with_reader(Duration::from_mins(1), reader);

        let release = async {
            read_started.notified().await;
            release_read.notify_one();
        };
        let (first, second, third, ()) = tokio::time::timeout(Duration::from_secs(5), async {
            tokio::join!(layer.config(), layer.config(), layer.config(), release,)
        })
        .await
        .expect("concurrent cold configuration load should complete");

        first.unwrap_err();
        second.unwrap_err();
        third.unwrap_err();
        assert_eq!(calls.load(std::sync::atomic::Ordering::Relaxed), 1);

        layer.config().await.unwrap();
        assert_eq!(calls.load(std::sync::atomic::Ordering::Relaxed), 2);
    }

    #[tokio::test]
    async fn cancelled_cold_load_releases_single_flight_lock() {
        let calls = Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let reader = BoxService::new(service_fn({
            let calls = calls.clone();
            move |()| {
                let call = calls.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                async move {
                    if call == 0 {
                        std::future::pending::<()>().await;
                    }
                    Ok::<_, BoxError>(SystemProxyConfig::default())
                }
            }
        }));
        let layer = SystemProxyLayer::new_with_reader(Duration::from_mins(1), reader);

        tokio::time::timeout(Duration::from_millis(10), layer.config())
            .await
            .unwrap_err();
        assert!(layer.cached_config().is_none());
        layer.config().await.unwrap();
        assert_eq!(calls.load(std::sync::atomic::Ordering::Relaxed), 2);
    }

    #[tokio::test]
    async fn cancelled_stale_refresh_releases_single_flight_lock() {
        let calls = Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let reader = BoxService::new(service_fn({
            let calls = calls.clone();
            move |()| {
                let call = calls.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                async move {
                    if call == 1 {
                        std::future::pending::<()>().await;
                    }
                    let host = if call == 0 { "old.proxy" } else { "new.proxy" };
                    Ok::<_, BoxError>(SystemProxyConfig::default().with_http_proxy(proxy(
                        Protocol::HTTP,
                        host,
                        8080,
                    )))
                }
            }
        }));
        let layer = SystemProxyLayer::try_from_system_with_reader(Duration::ZERO, reader)
            .await
            .unwrap();

        tokio::time::timeout(Duration::from_millis(10), layer.config())
            .await
            .unwrap_err();
        let fresh = layer.config().await.unwrap();

        assert_eq!(
            fresh.http_proxy().unwrap().address.host.to_str(),
            "new.proxy"
        );
        assert_eq!(calls.load(std::sync::atomic::Ordering::Relaxed), 3);
    }

    #[tokio::test]
    async fn stale_refresh_is_single_flight_and_concurrent_calls_use_stale_config() {
        let calls = Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let refresh_started = Arc::new(tokio::sync::Notify::new());
        let allow_refresh = Arc::new(tokio::sync::Notify::new());
        let reader = BoxService::new(service_fn({
            let calls = calls.clone();
            let refresh_started = refresh_started.clone();
            let allow_refresh = allow_refresh.clone();
            move |()| {
                let call = calls.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                let refresh_started = refresh_started.clone();
                let allow_refresh = allow_refresh.clone();
                async move {
                    if call > 0 {
                        refresh_started.notify_one();
                        allow_refresh.notified().await;
                    }
                    let host = if call == 0 { "old.proxy" } else { "new.proxy" };
                    Ok::<_, BoxError>(SystemProxyConfig::default().with_http_proxy(proxy(
                        Protocol::HTTP,
                        host,
                        8080,
                    )))
                }
            }
        }));
        let layer = SystemProxyLayer::try_from_system_with_reader(Duration::ZERO, reader)
            .await
            .unwrap();

        let refresh_layer = layer.clone();
        let refresh = tokio::spawn(async move { refresh_layer.config().await });
        tokio::time::timeout(Duration::from_secs(5), refresh_started.notified())
            .await
            .expect("stale configuration refresh should start");

        let stale = tokio::time::timeout(Duration::from_millis(100), layer.config())
            .await
            .unwrap()
            .unwrap();
        assert_eq!(
            stale.http_proxy().unwrap().address.host.to_str(),
            "old.proxy"
        );
        assert_eq!(calls.load(std::sync::atomic::Ordering::Relaxed), 2);

        allow_refresh.notify_one();
        let fresh = tokio::time::timeout(Duration::from_secs(5), refresh)
            .await
            .expect("stale configuration refresh should complete")
            .unwrap()
            .unwrap();
        assert_eq!(
            fresh.http_proxy().unwrap().address.host.to_str(),
            "new.proxy"
        );
    }

    #[tokio::test]
    async fn failed_system_config_refresh_retains_snapshot_and_remains_retryable() {
        let calls = Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let reader = BoxService::new(service_fn({
            let calls = calls.clone();
            move |()| {
                let call = calls.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                async move {
                    match call {
                        0 => Ok(SystemProxyConfig::default().with_http_proxy(proxy(
                            Protocol::HTTP,
                            "old.proxy",
                            8080,
                        ))),
                        1 => Err(std::io::Error::other("temporary platform read failure").into()),
                        _ => Ok(SystemProxyConfig::default().with_http_proxy(proxy(
                            Protocol::HTTP,
                            "new.proxy",
                            8080,
                        ))),
                    }
                }
            }
        }));
        let layer = SystemProxyLayer::try_from_system_with_reader(Duration::ZERO, reader)
            .await
            .unwrap();

        let stale = layer.config().await.unwrap();
        assert_eq!(
            stale.http_proxy().unwrap().address.host.to_str(),
            "old.proxy"
        );
        let fresh = layer.config().await.unwrap();
        assert_eq!(
            fresh.http_proxy().unwrap().address.host.to_str(),
            "new.proxy"
        );
        assert_eq!(calls.load(std::sync::atomic::Ordering::Relaxed), 3);
    }

    #[tokio::test]
    async fn a_pac_uri_discovered_by_refresh_is_used_by_the_existing_service() {
        let calls = Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let reader = BoxService::new(service_fn({
            let calls = calls.clone();
            move |()| {
                let call = calls.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                async move {
                    if call == 0 {
                        Ok::<_, BoxError>(SystemProxyConfig::default().with_http_proxy(proxy(
                            Protocol::HTTP,
                            "fixed.proxy",
                            8080,
                        )))
                    } else {
                        Ok(SystemProxyConfig::default()
                            .with_pac_uri("https://config.example/proxy.pac".parse().unwrap()))
                    }
                }
            }
        }));
        let layer = SystemProxyLayer::try_from_system_with_reader(Duration::from_mins(1), reader)
            .await
            .unwrap();
        let factory_calls = Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let factory = service_fn({
            let factory_calls = factory_calls.clone();
            move |_uri: Uri| {
                factory_calls.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                async move {
                    Ok::<_, Infallible>(service_fn(|_request| async move {
                        Ok::<_, Infallible>(Some(ProxyRoutes::from(proxy(
                            Protocol::HTTP,
                            "pac.proxy",
                            8080,
                        ))))
                    }))
                }
            }
        });
        let (inner, seen) = recorder();
        let service = layer.clone().with_pac_service(factory).into_layer(inner);

        service
            .serve(TestInput::new("http://example.com/first"))
            .await
            .unwrap();
        layer.config.refresh_after_nanos.store(0, Ordering::Release);
        service
            .serve(TestInput::new("http://example.com/second"))
            .await
            .unwrap();

        let seen = seen.lock();
        let hosts = seen
            .iter()
            .map(|routes| {
                routes.as_ref().unwrap().as_slice()[0]
                    .proxy_address()
                    .unwrap()
                    .address
                    .host
                    .to_str()
                    .into_owned()
            })
            .collect::<Vec<_>>();
        assert_eq!(hosts, ["fixed.proxy", "pac.proxy"]);
        assert_eq!(factory_calls.load(std::sync::atomic::Ordering::Relaxed), 1);
    }

    #[tokio::test]
    async fn system_config_cache_honors_a_custom_ttl() {
        let calls = Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let reader = BoxService::new(service_fn({
            let calls = calls.clone();
            move |()| {
                calls.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                async { Ok::<_, BoxError>(SystemProxyConfig::default()) }
            }
        }));
        let layer = SystemProxyLayer::try_from_system_with_reader(Duration::from_mins(1), reader)
            .await
            .unwrap();

        for _ in 0..10 {
            drop(layer.config().await.unwrap());
        }
        assert_eq!(calls.load(std::sync::atomic::Ordering::Relaxed), 1);
    }
}