rift-mock-core 0.25.0

Rift core engine: imposter lifecycle, matching, behaviors, scripting and flow-state — usable in-process without the CLI or admin server.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
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
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
//! Request handling logic for imposters.
//!
//! This module handles incoming HTTP requests to imposters, including
//! debug mode, proxy handling, inject execution, and response generation.

use super::behavior_pipeline::{BehaviorOutcome, BehaviorRun, ServedParts, aborted_response};
use super::conditional::{self, ConditionalSpec};
use super::core::Imposter;
use super::core::{ProxiedResponse, ProxyBody, ProxyOutcome};
use super::headers::sanitize_header_value;
use super::predicates::parse_query_string;
use super::response::{
    body_text, complete_from_default, execute_stub_response_with_rift, get_rift_script_config,
    served_is,
};
use super::status::{invalid_status_response, resolve as resolve_status};
use super::types::{
    DebugMatchResult, DebugRequest, DebugResponse, IsResponse, ProxyResponse, RecordedRequest,
    ResponseMode, StubResponse, UpstreamTarget,
};
use crate::behaviors::{
    CsvCache, LookupLoadError, Spliced, SplicedHeaders, authored_headers, header_to_title_case,
    plain_headers,
};
use crate::extensions::decorate::{
    ResponseDecorator, ResponsePhase, backend_error_response, with_annotation_scope,
};
use crate::extensions::exchange_inspector::{InspectRequest, InspectResponse, InspectVerdict};
use crate::extensions::no_match::{NoMatchContext, NoMatchDirective};
use crate::extensions::template::{RequestData, has_template_variables, process_template_spliced};
use crate::scripting::{
    FaultDecision, ScriptCtxExtras, ScriptRequest, ScriptStubContext, resolve_script_timeout_ms,
    should_inject_bounded_with_ctx, should_inject_bounded_with_ctx_traced,
};
#[cfg(feature = "javascript")]
use crate::scripting::{MountebankRequest, execute_mountebank_inject_bounded};
use crate::util::build_response_with_headers;
use base64::Engine;
use bytes::Bytes;
use http_body_util::{BodyExt, Full};
use hyper::body::Incoming;
use hyper::{Request, Response, StatusCode};

use rand::RngExt;
use std::convert::Infallible;
use std::net::SocketAddr;
use std::sync::Arc;
use std::time::{Duration, Instant};
use tracing::{debug, trace, warn};

use super::body_limits::{BodyReadError, CollectedBody};
use super::content_encoding::{Coding, Decoded};

/// Pair the request's bytes with their string form for the proxy (issue #1321). `raw` is what the
/// client sent, still encoded; `text` is the decoded form, or `None` for a body that did not decode
/// (issue #1584), whose bytes are forwarded all the same.
fn proxy_body<'a>(raw: Option<&'a Bytes>, text: Option<&'a str>) -> Option<ProxyBody<'a>> {
    raw.map(|raw| ProxyBody { raw, text })
}

/// Decode a `gzip` / `br` request body into the imposter's body budget, off the async worker:
/// inflating up to the ceiling is CPU work proportional to the decoded size (issue #1584). `Err` is
/// only the blocking task dying.
async fn decode_request_body(
    imposter: &Imposter,
    coding: Coding,
    raw: Bytes,
) -> Result<Result<Decoded, BodyReadError>, tokio::task::JoinError> {
    let out = match imposter.body_guard.start(None).await {
        Ok(out) => out,
        Err(e) => return Ok(Err(e)),
    };
    tokio::task::spawn_blocking(move || super::content_encoding::decode(coding, &raw, out)).await
}

/// The `500` for a decode task that died (a panic in the decoder): a server fault, not the client's.
fn decode_failed_response(e: &tokio::task::JoinError) -> Response<Full<Bytes>> {
    tracing::error!("request body decoding task failed: {e}");
    build_response_with_headers(
        StatusCode::INTERNAL_SERVER_ERROR,
        [
            ("x-rift-imposter", "true"),
            ("content-type", "application/json"),
        ],
        crate::response::error_body(
            StatusCode::INTERNAL_SERVER_ERROR,
            "Request body decoding failed",
        ),
    )
}

/// The `413` and `503` doors for a body the limits refuse (issue #1439). Both close the
/// connection: the client may still be writing a body this listener will not read, and leaving it
/// unread on a kept-alive connection would be parsed as the next request. Both ask for a lingering
/// close ([`LingerOnClose`](super::fault_io::LingerOnClose), issue #1460), so that close does not
/// reset the connection under the answer.
fn body_refused_response(e: &BodyReadError) -> Response<Full<Bytes>> {
    let status = match e {
        BodyReadError::BudgetExhausted => {
            // An expected overload state, not a server fault: a warning, not an error.
            warn!("refused a request body: {e}");
            StatusCode::SERVICE_UNAVAILABLE
        }
        _ => StatusCode::PAYLOAD_TOO_LARGE,
    };
    let mut response = limits_response(status, &e.to_string(), true);
    // The close must not discard this answer while the client is still sending (issue #1460).
    response
        .extensions_mut()
        .insert(super::fault_io::LingerOnClose);
    response
}

/// The `503` + `Retry-After` for a `lookup` whose CSV file the body memory budget cannot hold now
/// (issue #1654): the same answer as a request body the budget refuses, except that the
/// connection is kept, since the request's body has been read in full.
pub(crate) fn lookup_budget_response(e: &LookupLoadError) -> Response<Full<Bytes>> {
    // An expected overload state, not a server fault: a warning, not an error.
    warn!("refused a lookup: {e}");
    limits_response(StatusCode::SERVICE_UNAVAILABLE, &e.to_string(), false)
}

/// The body-limits answer: `status` with the canonical error body, `Retry-After: 1` on a `503`,
/// and `Connection: close` when `close`.
fn limits_response(status: StatusCode, message: &str, close: bool) -> Response<Full<Bytes>> {
    let mut response = build_response_with_headers(
        status,
        [
            ("x-rift-imposter", "true"),
            ("content-type", "application/json"),
        ],
        crate::response::error_body(status, message),
    );
    if close {
        response.headers_mut().insert(
            hyper::header::CONNECTION,
            hyper::header::HeaderValue::from_static("close"),
        );
    }
    if status == StatusCode::SERVICE_UNAVAILABLE {
        response.headers_mut().insert(
            hyper::header::RETRY_AFTER,
            hyper::header::HeaderValue::from_static("1"),
        );
    }
    response
}

/// The `400` door for a request body that could not be read (issue #694). Logs the real cause —
/// previously this failure was silent — then serves the canonical envelope. A read failure is the
/// client's transmission going wrong, so it is a `400`, distinct from the `413` size-cap door; a
/// `5xx` here would blame the server for the client's dropped connection.
fn body_read_error_response(e: &dyn std::error::Error) -> Response<Full<Bytes>> {
    warn!("failed to read request body: {e}");
    build_response_with_headers(
        StatusCode::BAD_REQUEST,
        [
            ("x-rift-imposter", "true"),
            ("content-type", "application/json"),
        ],
        crate::response::error_body(StatusCode::BAD_REQUEST, "Failed to read request body"),
    )
}

/// Process-wide cache for `lookup` behavior CSV data sources, shared across all
/// imposters so a file is parsed once and reused on subsequent requests.
fn csv_cache() -> &'static CsvCache {
    static CSV_CACHE: std::sync::OnceLock<CsvCache> = std::sync::OnceLock::new();
    CSV_CACHE.get_or_init(CsvCache::new)
}

/// Marker header (issue #499) attached to every timeout-mapped response: a 504 carrying this
/// header means a script hook exceeded its wall-clock deadline (transient/retry-worthy), as
/// distinct from a broken-script 400/500 (a permanent config error).
pub(super) const SCRIPT_TIMEOUT_HEADER: &str = "x-rift-script-timeout";

/// Build the 504 response for a timed-out response/predicate `inject` (issue #499): the Mountebank
/// `{"errors":[{code,message}]}` envelope with a timeout-specific `code`, plus the shared
/// `x-rift-inject-error` marker and the [`SCRIPT_TIMEOUT_HEADER`] that tells a timeout apart from a
/// genuinely broken inject (which stays a 400).
/// On this door `code` is already a slug, so `type` is the same string (issue #797 invariant 3) —
/// taking the kind rather than a `&str` is what keeps the two from drifting apart.
fn inject_timeout_response(
    kind: crate::response::ErrorKind,
    message: &str,
) -> Response<Full<Bytes>> {
    let body = serde_json::json!({
        "errors": [{ "code": kind.slug(), "type": kind.slug(), "message": message }]
    })
    .to_string();
    build_response_with_headers(
        StatusCode::GATEWAY_TIMEOUT,
        [
            ("x-rift-imposter", "true"),
            ("x-rift-inject-error", "true"),
            (SCRIPT_TIMEOUT_HEADER, "true"),
            ("content-type", "application/json"),
        ],
        body,
    )
}

/// Build the 500 for a failed `{{ }}` render (issue #359). Split out from the request path — as
/// `debug_serialize_or_500` was for #611 — so this door can be pinned by a test: it fires only
/// under `RIFT_DEBUG`, a process-global a shared-process test cannot set without racing its
/// siblings, so end-to-end coverage is not available to it.
fn template_error_response(e: &str) -> Response<Full<Bytes>> {
    build_response_with_headers(
        StatusCode::INTERNAL_SERVER_ERROR,
        [
            ("x-rift-imposter", "true"),
            ("x-rift-template-error", "true"),
            ("content-type", "application/json"),
        ],
        crate::response::error_body(
            StatusCode::INTERNAL_SERVER_ERROR,
            &format!("template rendering failed: {e}"),
        ),
    )
}

/// Build the 500 for a failed `_rift.stateOps` operation (issue #969), debug mode only —
/// `execute_state_ops`'s `debug` policy is the only case that returns `Err`, and it names the
/// failing op in `e`. Same envelope and imposter marker as [`template_error_response`], with its
/// own `x-rift-state-ops-error` marker so the two failure kinds are distinguishable at the header
/// level.
fn state_ops_error_response(e: &str) -> Response<Full<Bytes>> {
    build_response_with_headers(
        StatusCode::INTERNAL_SERVER_ERROR,
        [
            ("x-rift-imposter", "true"),
            ("x-rift-state-ops-error", "true"),
            ("content-type", "application/json"),
        ],
        crate::response::error_body(
            StatusCode::INTERNAL_SERVER_ERROR,
            &format!("state operation failed: {e}"),
        ),
    )
}

// The debug-endpoint doors (issue #695). The debug success path answers JSON (`X-Rift-Debug-Response`),
// so these error paths do too — plain text here was the same-endpoint gap #687 closed elsewhere.
// Split out from the match arms so each can be pinned by a test: neither is safely provokable
// end-to-end (a task panic must be injected; a timeout needs a busy-loop that starves the shared
// script pool). The caller keeps its own `warn!` — these build the response only.

/// A `_rift`-debug matching task that panicked → 500, canonical envelope.
fn debug_matching_error_response() -> Response<Full<Bytes>> {
    build_response_with_headers(
        StatusCode::INTERNAL_SERVER_ERROR,
        [
            ("x-rift-imposter", "true"),
            ("content-type", "application/json"),
        ],
        crate::response::error_body(StatusCode::INTERNAL_SERVER_ERROR, "Debug matching failed"),
    )
}

/// A debug matching run that missed the `_rift.scriptEngine.timeoutMs` deadline → 504 + the timeout
/// marker (issues #476/#499), like every other script deadline. It was a 500 before #695, which
/// contradicted that transient-vs-permanent contract.
fn debug_matching_timeout_response() -> Response<Full<Bytes>> {
    build_response_with_headers(
        StatusCode::GATEWAY_TIMEOUT,
        [
            ("x-rift-imposter", "true"),
            (SCRIPT_TIMEOUT_HEADER, "true"),
            ("content-type", "application/json"),
        ],
        crate::response::error_body(StatusCode::GATEWAY_TIMEOUT, "Debug matching timed out"),
    )
}

/// The terminal 500 for a response whose own header/body hyper rejected (issue #695) — a bad
/// upstream/inject/script/stub header value that fails `.body(...)`. Serves the canonical envelope
/// so the last-resort door matches every other imposter error door instead of a bare string, and
/// logs the caller's `what` context so the failing door is named. Safe as a terminal fallback:
/// `error_body` is infallible by construction and `build_response_with_headers` with literal headers
/// falls back to `internal_error_fallback` — the chain cannot itself panic.
fn build_failure_response(e: &hyper::http::Error, log_context: &str) -> Response<Full<Bytes>> {
    warn!("{log_context}: {e}");
    build_response_with_headers(
        StatusCode::INTERNAL_SERVER_ERROR,
        [
            ("x-rift-imposter", "true"),
            ("content-type", "application/json"),
        ],
        crate::response::error_body(StatusCode::INTERNAL_SERVER_ERROR, "Response build error"),
    )
}

/// The first of `names` that is not a valid header name (issue #1583): a `copy` or `lookup`
/// token whose source had no value stays in the name, as authored.
fn invalid_header_name<'a>(names: impl IntoIterator<Item = &'a str>) -> Option<&'a str> {
    names
        .into_iter()
        .find(|name| hyper::header::HeaderName::from_bytes(name.as_bytes()).is_err())
}

/// The 500 for a response header name hyper refuses (issue #1583) — Mountebank answers 500
/// `ERR_INVALID_HTTP_TOKEN` for it. The same door as [`build_failure_response`], but the message
/// names the header, so the author can see which token was left in it. Truncated, because a name
/// can hold request text a `copy` inserted.
fn invalid_header_name_response(name: &str) -> Response<Full<Bytes>> {
    let message = format!(
        "Response build error: invalid header name {:?}",
        super::response::truncate_with_ellipsis(name, 256)
    );
    warn!("stub response build failed: {message}");
    build_response_with_headers(
        StatusCode::INTERNAL_SERVER_ERROR,
        [
            ("x-rift-imposter", "true"),
            ("content-type", "application/json"),
        ],
        crate::response::error_body(StatusCode::INTERNAL_SERVER_ERROR, &message),
    )
}

/// Whether a requested response behavior that fails should serve a 500 rather than its fallback
/// (issue #375): per imposter (`strictBehaviors`) or process-wide (`RIFT_STRICT_BEHAVIORS`).
///
/// One definition, read by every site that serves a behavior-dependent body, because the defect
/// in issue #1151 was a site that had never picked this up — it lived as a local in the
/// matched-stub block and the default-response site could not see it.
fn strict_behaviors_for(config: &super::types::ImposterConfig) -> bool {
    config.strict_behaviors || crate::util::strict_behaviors_env()
}

/// Outcome of decoding a `_mode: "binary"` body (issues #323 / #375 / #1151).
///
/// A variant rather than a `bool` so the lenient failure cannot be served without the caller
/// seeing it: `RawFallback` exists precisely so the site must decide what to attach, and the
/// contract is that it attaches `x-rift-binary-error: true`. The two sites that decode a binary
/// body drifted apart once already — one had the header and the strict path, the other had
/// neither — and a shared helper returning a plain `Bytes` would let that happen again.
pub(super) enum BinaryBody {
    Decoded(Bytes),
    /// The body did not decode; these are its raw (still-encoded) bytes, served under the lenient
    /// #269/#323 contract.
    RawFallback(Bytes),
}

/// Decode a binary-mode body. `Err` carries the ready-made strict-mode 500 — the failure is
/// already a response by then, so the caller returns it as-is. Boxed because a `Response` is large
/// and this is the rare path; the `Ok` path stays small.
///
/// Every character outside the base64 alphabet is dropped before the decode, as Mountebank's
/// `postProcess` does (`baseHttpServer.js:53-57`, `/[^A-Za-z0-9=+/]+/g`), so a body wrapped at 76
/// columns decodes (#1554). A body that still fails keeps its original text for the fallback.
/// `rift-lint`'s W015 applies the same filter, so the two cannot disagree on what decodes.
pub(super) fn decode_binary_body(
    body: String,
    strict: bool,
) -> Result<BinaryBody, Box<Response<Full<Bytes>>>> {
    let decoded =
        base64::engine::general_purpose::STANDARD.decode(strip_non_base64(&body).as_bytes());
    match decoded {
        Ok(decoded) => Ok(BinaryBody::Decoded(Bytes::from(decoded))),
        Err(e) if strict => {
            warn!("Failed to decode base64 body: {e}; failing loud (strictBehaviors)");
            Err(Box::new(build_response_with_headers(
                StatusCode::INTERNAL_SERVER_ERROR,
                [
                    ("x-rift-imposter", "true"),
                    ("x-rift-binary-error", "true"),
                    ("content-type", "application/json"),
                ],
                crate::response::error_body_typed(
                    StatusCode::INTERNAL_SERVER_ERROR,
                    crate::response::ErrorKind::BehaviorError,
                    &format!("binary base64 decode failed (strictBehaviors): {e}"),
                ),
            )))
        }
        Err(e) => {
            warn!("Failed to decode base64 body: {e}, using raw body");
            Ok(BinaryBody::RawFallback(Bytes::from(body)))
        }
    }
}

/// `body` with every character outside `A-Za-z0-9+/=` removed (#1554). Borrowed when there is
/// nothing to remove, which is the common single-line case.
fn strip_non_base64(body: &str) -> std::borrow::Cow<'_, str> {
    let in_alphabet = |c: char| c.is_ascii_alphanumeric() || matches!(c, '+' | '/' | '=');
    if body.chars().all(in_alphabet) {
        std::borrow::Cow::Borrowed(body)
    } else {
        std::borrow::Cow::Owned(body.chars().filter(|&c| in_alphabet(c)).collect())
    }
}

/// Map a matcher error (`find_matching_stub_with_client`) to its response.
///
/// A predicate-`inject` failure (issue #440 — an object-build failure or the script itself
/// throwing) is Mountebank-shaped error parity with the response-inject case: a 500 (issue
/// #1581; `baseHttpServer.js:150-155` answers an `InjectionError` so) with
/// `{"errors":[{"code":"invalid predicate injection","message":"...","data":"..."}]}`. A predicate-matching *deadline* (issue #499) is instead a 504 `predicate injection
/// timeout` a client can retry — checked first, since it too surfaces during matching. Every other
/// matcher error (e.g. a scenario-state backend failure, issue #318) keeps the existing
/// [`backend_error_response`] 5xx mapping.
/// Log a failure with its whole cause chain (issue #679).
///
/// `{e:#}` is anyhow's alternate Display: the entire chain on one line, which is what a log pipeline
/// wants (`{e:?}` renders a multi-line `Caused by:` block for a terminal). Plain `{}` renders only
/// the outermost context — which is how a DNS failure, a certificate rejection and a refused
/// connection all became the same opaque line, on a 502 whose only job is to say why the upstream
/// did not answer. `rift-ffi`'s CA setup path reaches for `{err:#}` for exactly this reason.
///
/// Every site that logs an `anyhow` failure here routes through this function, so the chain cannot
/// be dropped again one `warn!` at a time.
fn log_upstream_failure(context: &str, e: &anyhow::Error) {
    warn!("{context}: {e:#}");
}

/// The 502 for an upstream a proxy response could not reach, plus the log line that explains it.
///
/// Issue #679: the two audiences get different detail, deliberately. The operator gets the whole
/// chain (see [`log_upstream_failure`]); the client gets `client_prefix` plus the outermost context
/// only, since a chain can name internal hosts and resolver detail that is none of the caller's
/// business — and the operator already has it in the log.
///
/// The body goes through the crate's canonical Mountebank builder rather than a JSON string
/// literal, which produced invalid JSON the moment a message held a quote (the #611 class), and
/// which left this door emitting a legacy `{"error"}` shape that 0.13.6 had already unified
/// everywhere else.
fn upstream_error_response(
    e: &anyhow::Error,
    log_context: &str,
    marker: &'static str,
    client_prefix: &str,
) -> Response<Full<Bytes>> {
    log_upstream_failure(log_context, e);
    build_response_with_headers(
        StatusCode::BAD_GATEWAY,
        [
            ("x-rift-imposter", "true"),
            (marker, "true"),
            ("content-type", "application/json"),
        ],
        // The client's message is built here, from a prefix, rather than taken ready-made: `{e}`
        // and `{e:#}` differ by exactly the chain, so a caller that formatted its own message could
        // leak it with a one-character edit and no test would notice. Taking a prefix leaves the
        // caller nothing to get wrong.
        crate::response::error_body(StatusCode::BAD_GATEWAY, &format!("{client_prefix}: {e}")),
    )
}

/// The response for a failed proxy leg — the stub-proxy and `defaultForward` arms share it so the
/// door is one function rather than two that drift.
///
/// A [`BackendUnavailable`](crate::extensions::decorate::BackendUnavailable) anywhere in the chain
/// means the proxy-recording store *refused* the claim and the request was never forwarded, so the
/// upstream is not at fault and there is nothing to log as an upstream failure: it answers `503`
/// through the #318 door, naming the backend. Everything else is a genuine upstream failure and
/// keeps the `502` it has always had.
fn proxy_leg_error_response(
    e: &anyhow::Error,
    log_context: &str,
    marker: &'static str,
    client_prefix: &str,
) -> Response<Full<Bytes>> {
    if e.downcast_ref::<crate::extensions::decorate::BackendUnavailable>()
        .is_some()
    {
        return backend_error_response(e);
    }
    upstream_error_response(e, log_context, marker, client_prefix)
}

/// Mountebank's answer to an XPath selector that fails when it runs, in a predicate or a `copy`
/// (issue #1585): `500` with `{"errors":[{"code":"bad data","message":"malformed xpath predicate
/// selector"}]}`, as its HTTP server writes the `ValidationError` `xpathSelect` throws. `code`
/// reuses the frozen `bad data` slug, as the `wait` door reuses `invalid injection`; `source` (the
/// selector), `inner`, `name` and `stack` are left out, as on every Rift error envelope, and the
/// selector and the cause go to the log instead.
pub(crate) fn xpath_selector_error_response(
    e: &crate::behaviors::XPathSelectorError,
) -> Response<Full<Bytes>> {
    tracing::warn!("{e}");
    let kind = crate::response::ErrorKind::BadData.slug();
    build_response_with_headers(
        StatusCode::INTERNAL_SERVER_ERROR,
        [
            ("x-rift-imposter", "true"),
            ("content-type", "application/json"),
        ],
        serde_json::json!({
            "errors": [{
                "code": kind,
                "type": kind,
                "message": "malformed xpath predicate selector",
            }]
        })
        .to_string(),
    )
}

/// Mountebank's answer to a proxy request whose `predicateGenerators` injection failed while
/// recording (issue #1708): `500` with the body the create-time dry run answers `400` with
/// ([`generator_injection_error_body`](crate::response::generator_injection_error_body)), after the
/// request was forwarded. `x-rift-generator-error` keeps the failure's token as a marker.
pub(crate) fn generator_injection_error_response(
    source: &str,
    data: Option<&str>,
    token: &str,
) -> Response<Full<Bytes>> {
    build_response_with_headers(
        StatusCode::INTERNAL_SERVER_ERROR,
        [
            ("x-rift-imposter", "true"),
            ("content-type", "application/json"),
            ("x-rift-generator-error", token),
        ],
        crate::response::generator_injection_error_body(source, data),
    )
}

/// The `500` for a proxy request whose `predicateGenerators` injection could not run at all (issue
/// #1708): the script pool failed or the generator's task panicked. A Rift-only failure, so it is a
/// Rift internal error rather than Mountebank's `invalid injection`.
pub(crate) fn generator_unavailable_response(token: &str) -> Response<Full<Bytes>> {
    build_response_with_headers(
        StatusCode::INTERNAL_SERVER_ERROR,
        [
            ("x-rift-imposter", "true"),
            ("content-type", "application/json"),
            ("x-rift-generator-error", token),
        ],
        crate::response::error_body_typed(
            StatusCode::INTERNAL_SERVER_ERROR,
            crate::response::ErrorKind::InternalError,
            "could not run a predicateGenerator injection",
        ),
    )
}

#[cfg(feature = "javascript")]
/// The `{"errors":[...]}` body of a throwing `inject`: `message` is Rift's text, `data` is
/// Mountebank's (the thrown error's `message`), left out when the script threw no message.
fn inject_failure_body(
    kind: crate::response::ErrorKind,
    message: &str,
    data: Option<&str>,
) -> String {
    let mut error = serde_json::json!({
        "code": kind.slug(),
        "type": kind.slug(),
        "message": message,
    });
    if let Some(data) = data {
        error["data"] = serde_json::Value::String(data.to_owned());
    }
    serde_json::json!({ "errors": [error] }).to_string()
}

fn matcher_error_response(e: &anyhow::Error) -> Response<Full<Bytes>> {
    if let Some(xpath) = e.downcast_ref::<crate::behaviors::XPathSelectorError>() {
        return xpath_selector_error_response(xpath);
    }
    if let Some(t) = e.downcast_ref::<crate::scripting::ScriptTimeoutError>() {
        return inject_timeout_response(
            crate::response::ErrorKind::PredicateInjectionTimeout,
            &t.to_string(),
        );
    }
    #[cfg(feature = "javascript")]
    {
        if let Some(pred_err) = e.downcast_ref::<crate::scripting::PredicateInjectionError>() {
            let body = inject_failure_body(
                crate::response::ErrorKind::InvalidPredicateInjection,
                &pred_err.to_string(),
                pred_err.data(),
            );
            return build_response_with_headers(
                StatusCode::INTERNAL_SERVER_ERROR,
                [
                    ("x-rift-imposter", "true"),
                    ("x-rift-inject-error", "true"),
                    ("content-type", "application/json"),
                ],
                body,
            );
        }
    }
    backend_error_response(e)
}

/// The request-side view handed to an installed [`ExchangeInspector`](crate::extensions::exchange_inspector::ExchangeInspector)
/// (issue #966), owned so it survives past `handle_request_inner` into the response-side hook in
/// `handle_imposter_request`. Filled only when `imposter.exchange_inspector.is_some()` — an
/// imposter with no inspector pays nothing beyond that one check.
struct Inspection {
    method: String,
    path: String,
    query: String,
    headers: hyper::HeaderMap,
    body: Option<String>,
    mode: ResponseMode,
}

/// Map an [`InspectVerdict::Reject`]'s `status` to a `StatusCode`, falling back to `502 Bad
/// Gateway` for a value outside the valid HTTP status range (an inspector bug, not a request the
/// client can be blamed for) and logging it so the fallback is visible rather than silently wrong.
fn inspector_reject_status(status: u16) -> StatusCode {
    StatusCode::from_u16(status).unwrap_or_else(|_| {
        tracing::warn!(
            status,
            "exchange inspector rejected with an out-of-range status code; using 502"
        );
        StatusCode::BAD_GATEWAY
    })
}

impl Inspection {
    /// Borrow this exchange's request view for a hook call, with the imposter's own `port`
    /// (the same value the no-match hook's [`NoMatchContext`] uses).
    fn view(&self, port: u16) -> InspectRequest<'_> {
        InspectRequest {
            port,
            method: &self.method,
            path: &self.path,
            query: &self.query,
            headers: &self.headers,
            body: self.body.as_deref(),
            mode: &self.mode,
        }
    }
}

/// [`handle_imposter_request`] inside a per-request annotation scope, with the configured
/// [`ResponseDecorator`](crate::extensions::decorate::ResponseDecorator) applied (phase
/// `DataPlane`, the imposter's `port`) before the response is written (issue #318). This
/// is the serve-loop wrapper; it is public so custom listeners can reuse the exact
/// production wiring.
pub async fn handle_imposter_request_decorated(
    req: Request<Incoming>,
    imposter: Arc<Imposter>,
    client_addr: SocketAddr,
    port: u16,
    decorator: Option<Arc<dyn ResponseDecorator>>,
) -> Result<Response<Full<Bytes>>, Infallible> {
    let (response, annotations) =
        with_annotation_scope(handle_imposter_request(req, imposter, client_addr)).await;
    let mut response = response?;
    if let Some(decorator) = decorator {
        decorator.decorate(
            ResponsePhase::DataPlane,
            Some(port),
            &annotations,
            response.headers_mut(),
        );
    }
    Ok(response)
}

/// Handle a request to an imposter
pub async fn handle_imposter_request(
    req: Request<Incoming>,
    imposter: Arc<Imposter>,
    client_addr: SocketAddr,
) -> Result<Response<Full<Bytes>>, Infallible> {
    // Read before `req` is consumed; the echo is applied to the finished response below (#1555).
    let cors_preflight = if imposter.config.allow_cors.enabled() {
        CorsPreflight::of(&req)
    } else {
        None
    };
    // Capture the method before `req` is consumed so we can record the request metric (issue #269).
    let method = req.method().to_string();
    /*
     * Issue #364. The journal entry is written inside `handle_request_inner`, before matching and
     * long before a response exists, so the status and the elapsed time can only be attached from
     * out here — where the finished response is, and where the clock started.
     *
     * The index travels out through an out-parameter rather than the return type because `inner`
     * returns from eight places. Widening its return would touch every one of them to carry a
     * value only this caller reads, and each extra site is a chance to drop it.
     *
     * Every return reaches the attach, so what is NOT an answer is decided here from the response
     * itself (`is_served_answer`, #1227), never by which path produced it.
     */
    let started = Instant::now();
    // The request's own instant (issue #1754): its `X-Rift-Now` under
    // `_rift.scriptEngine.clock: "header"`. A malformed one is refused rather than read as wall
    // time, which would make the test silently wrong; the refusal still leaves through the funnel
    // below, so it is counted and gets the CORS echo like any answer.
    let (request_now, refused) = match crate::imposter::clock::resolve_request_now(
        imposter.config.clock_source(),
        req.headers()
            .get(crate::imposter::clock::NOW_HEADER)
            .map(|v| v.to_str().unwrap_or("<not visible ASCII>")),
    ) {
        Ok(now) => (now, None),
        Err(bad) => (
            None,
            Some(build_response_with_headers(
                StatusCode::BAD_REQUEST,
                [
                    ("x-rift-imposter", "true"),
                    ("content-type", "application/json"),
                ],
                crate::response::error_body_typed(
                    StatusCode::BAD_REQUEST,
                    crate::response::ErrorKind::BadData,
                    &bad.to_string(),
                ),
            )),
        ),
    };
    let mut journal_index = None;
    let mut inspection: Option<Inspection> = None;
    // Boxed: the task-local scope nests the whole request future one level deeper, past the
    // compiler's layout depth for the serve loop's future (issue #1754).
    let request_rng = imposter.request_rng();
    let inner = Box::pin(crate::imposter::rng::with_request_rng(
        request_rng,
        crate::imposter::clock::with_imposter_clock(
            Arc::clone(&imposter.clock),
            crate::imposter::clock::with_request_override(
                request_now,
                handle_request_inner(
                    req,
                    Arc::clone(&imposter),
                    client_addr,
                    &mut journal_index,
                    &mut inspection,
                ),
            ),
        ),
    ));
    /*
     * Issue #1643: a delete or replace cancels the generation (and a plain `PUT /imposters` the
     * runtime generation of an imposter it keeps, #1799), and every request it is still
     * computing — in a `wait`, on a proxy upstream, in a `shellTransform`, in an inject — is cut
     * off here, at the one funnel every door shares, as Mountebank destroys every socket of a
     * deleted imposter. Dropping `inner` drops the upstream request, the `shellTransform` join
     * handle and the script pool's reply channel with it. A response this returned before the
     * cancel is written under hyper's graceful shutdown (#207).
     *
     * The cancel is polled first, so `inner` is not polled again once a wake sees it. Level-
     * triggered, so a request that arrived before the delete still sees it. An aborted request is
     * not offered to the exchange inspector: a `Reject` verdict would make the deleted imposter
     * answer after all.
     */
    // Loaded once: a request that loads it before a runtime restart swaps it is cut by that restart
    // (issue #1799); one that loads it after belongs to the new generation.
    let in_flight = imposter.in_flight.load_full();
    let computed = match refused {
        // Never polled: the refused request is not matched.
        Some(refusal) => {
            drop(inner);
            Some(refusal)
        }
        None => tokio::select! {
            biased;
            () = in_flight.cancelled() => None,
            response = inner => Some(response?),
        },
    };
    let mut response = match computed {
        Some(response) => response,
        None => {
            inspection = None;
            aborted_response()
        }
    };

    // Issue #966: the response-side hook of an installed exchange inspector runs HERE — the one
    // funnel every path shares (the serve loop, the `/__rift/` gateway and an embedder's
    // in-process dispatch all call `handle_imposter_request`), after the response is built and
    // before the metric below, the journal outcome, the CORS echo and the decorator, so the
    // journal and the client agree on the status actually served. A CORS preflight is no early
    // exit (#1555): it is matched and inspected like any request. Skipped when `inspection` is
    // absent: no inspector installed, an early exit before there was anything to inspect, or the
    // request-side hook already replaced the response itself (a verdict the inspector produced is
    // not offered back to it for a second opinion).
    if let Some(inspector) = &imposter.exchange_inspector
        && let Some(seen) = inspection.as_ref()
    {
        let port = imposter.config.port.unwrap_or(0);
        let (parts, body) = response.into_parts();
        let bytes = match body.collect().await {
            Ok(collected) => collected.to_bytes(),
            // `Full<Bytes>`'s `Body::Error` is `Infallible` — this arm can never run; matching it
            // out explicitly (rather than `.unwrap()`) keeps that a checked fact, not an assumed
            // one.
            Err(never) => match never {},
        };
        let resp_view = InspectResponse {
            status: parts.status.as_u16(),
            headers: &parts.headers,
            body: &bytes,
        };
        response = match inspector.inspect_response(&seen.view(port), &resp_view) {
            InspectVerdict::Proceed => Response::from_parts(parts, Full::new(bytes)),
            InspectVerdict::Reject {
                status,
                content_type,
                body,
            } => build_response_with_headers(
                inspector_reject_status(status),
                [
                    ("content-type", content_type.as_str()),
                    ("x-rift-imposter", "true"),
                ],
                body,
            ),
        };
    }

    // Record `rift_requests_total` once per request the imposter serves (issue #269). The imposter
    // serve path recorded no Prometheus metrics before; the recording proxy engine
    // (`proxy/handler.rs`) is a disjoint path, so there is no double-count.
    crate::extensions::record_request(&method, response.status().as_u16());
    if let Some(index) = journal_index
        && is_served_answer(&response)
    {
        // Measured before the CORS echo below, which is a header edit this node performs after
        // the imposter has finished — counting it would report the engine as slower than it was.
        imposter.attach_response_outcome(
            index,
            response.status().as_u16(),
            // Saturating rather than `as`: a request parked long enough to overflow `u64`
            // milliseconds is not reachable, but a silent wrap would report it as instant.
            u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX),
        );
    }
    if let Some(preflight) = cors_preflight {
        preflight.apply(response.headers_mut());
    }
    // The last header edit on the funnel, after the CORS echo, so nothing after it can make the
    // length stale again (#1554). The serve loop's `ResponseDecorator` runs later but edits only
    // an embedder's own headers.
    reconcile_content_length(&mut response);
    Ok(response)
}

/// Correct a `Content-Length` the response carries to the body's real byte length (#1554).
///
/// Mountebank does this in `postProcess` (`baseHttpServer.js:63-65`), after behaviors, for every
/// response that has the header: `is`, `inject`, `decorate`, `copy`, `lookup`, `shellTransform`
/// and `defaultResponse` alike. A response without the header is left alone, and hyper frames it
/// from the body as before. Without this, hyper writes the stub's value verbatim beside a body
/// framed by its real length (`proto/h1/role.rs`, "we are just going to trust that the values
/// match"): too large hangs the client, too small truncates the body and leaves the rest on the
/// connection, and a debug build panics on the mismatch.
///
/// The header is removed instead when:
/// - the response also sets `Transfer-Encoding`. RFC 9112 §6.2 forbids sending both, and hyper
///   cancels such a response, so the client got nothing at all. Mountebank sends both; the body
///   the client reads is the same.
/// - the status is 1xx or 204, which RFC 9110 §8.6 says must not carry one. hyper omits it there
///   itself when no header is set, so this is what the same stub without the header gets.
/// - the body's length is not known exactly. `Full<Bytes>` always knows it; this keeps an unknown
///   length from being guessed.
///
/// A HEAD response keeps its full body here (hyper drops the bytes), so its corrected value is the
/// GET length, as RFC 9110 §9.3.2 asks.
fn reconcile_content_length(response: &mut Response<Full<Bytes>>) {
    use hyper::body::Body as _;
    use hyper::header::{CONTENT_LENGTH, HeaderValue, TRANSFER_ENCODING};

    if !response.headers().contains_key(CONTENT_LENGTH) {
        return;
    }
    let status = response.status();
    let length = if response.headers().contains_key(TRANSFER_ENCODING)
        || status.is_informational()
        || status == StatusCode::NO_CONTENT
    {
        None
    } else {
        response.body().size_hint().exact()
    };
    match length {
        // `insert` replaces every value, so a header given twice ends up with one.
        Some(length) => {
            response
                .headers_mut()
                .insert(CONTENT_LENGTH, HeaderValue::from(length));
        }
        None => {
            response.headers_mut().remove(CONTENT_LENGTH);
        }
    }
}

/// Marks a response that reports *on* a request instead of answering it: the `X-Rift-Debug` match
/// report and its two failure doors. The journal must not record its status as the stub's (#1227).
#[derive(Clone, Copy, Debug)]
struct DebugReport;

/// Whether `response` is what the client receives as the imposter's answer — the only thing a
/// journal entry's `status`/`latencyMs` may describe (#1227). Not a debug report, and not a TCP-fault
/// carrier, which the serve loop discards in favour of aborting the connection.
fn is_served_answer<B>(response: &Response<B>) -> bool {
    response.extensions().get::<DebugReport>().is_none()
        && super::fault_io::tcp_fault_carrier(response).is_none()
}

/// A CORS preflight on an `allowCORS` imposter, as Mountebank recognises one
/// (`baseHttpServer.js:39-51`, issue #1555): an `OPTIONS` whose `Origin`,
/// `Access-Control-Request-Method` and `Access-Control-Request-Headers` are all present and
/// non-empty (JavaScript truthiness). Any other request gets no CORS headers at all.
#[derive(Debug)]
struct CorsPreflight {
    origin: hyper::header::HeaderValue,
    method: hyper::header::HeaderValue,
    headers: hyper::header::HeaderValue,
}

impl CorsPreflight {
    fn of<B>(req: &Request<B>) -> Option<Self> {
        use hyper::header::{
            ACCESS_CONTROL_REQUEST_HEADERS, ACCESS_CONTROL_REQUEST_METHOD, HeaderName, ORIGIN,
        };
        if req.method() != hyper::Method::OPTIONS {
            return None;
        }
        // The first value of a repeated header. Node would join duplicates with `, `, which no
        // browser sends on a preflight.
        let present = |name: &HeaderName| {
            req.headers()
                .get(name)
                .filter(|value| !value.is_empty())
                .cloned()
        };
        Some(Self {
            origin: present(&ORIGIN)?,
            method: present(&ACCESS_CONTROL_REQUEST_METHOD)?,
            headers: present(&ACCESS_CONTROL_REQUEST_HEADERS)?,
        })
    }

    /// Echo the request's values, verbatim, over whatever the stub or `defaultResponse` set:
    /// Mountebank's `headersMap.set` overwrites a stub's own value.
    fn apply(self, headers: &mut hyper::HeaderMap) {
        use hyper::header::{
            ACCESS_CONTROL_ALLOW_HEADERS, ACCESS_CONTROL_ALLOW_METHODS, ACCESS_CONTROL_ALLOW_ORIGIN,
        };
        headers.insert(ACCESS_CONTROL_ALLOW_HEADERS, self.headers);
        headers.insert(ACCESS_CONTROL_ALLOW_METHODS, self.method);
        headers.insert(ACCESS_CONTROL_ALLOW_ORIGIN, self.origin);
    }
}

/// The outcome of a `_rift.templated` render.
///
/// A failed `{{ }}` and a failed *offload* are different events with different answers — a 500
/// `x-rift-template-error` versus a backend-unavailable response — so they get different variants
/// rather than one error channel the caller has to disambiguate by inspecting the message.
#[derive(Debug)]
enum TemplateRender {
    /// Carries which bytes each token substituted (issue #1203), so the passes after it never
    /// expand a token that arrived inside request text.
    Rendered {
        body: Spliced,
        headers: SplicedHeaders,
    },
    /// A `{{ }}` expression failed to render (debug mode). Carries the message
    /// `render_templated` produced.
    Failed(String),
}

/// The render itself, independent of *where* it runs. Both arms of
/// [`render_templated_response`] call this, so the fast path and the offloaded path are the same
/// code rather than two copies that have to be kept in step.
///
/// Renders the body first, then every header value, repairing what each header token *substituted*
/// and leaving the author's literal text alone; the first failure wins and is returned as
/// [`TemplateRender::Failed`]. Pure over its inputs, which is what lets it run either on the
/// request task or on a blocking thread.
fn render_template_parts(
    imposter: &Imposter,
    request_data: &RequestData,
    flow_id: &str,
    body: String,
    headers: crate::imposter::Headers,
    debug: bool,
    stub: super::headers::StubRef<'_>,
) -> TemplateRender {
    let template_ctx = crate::extensions::template_fn::TemplateContext {
        request: request_data,
        flow_id,
        flow_store: imposter.flow_store.as_ref(),
        previous_value: None,
    };

    let body = match crate::extensions::template_fn::render_templated_spliced(
        &body,
        &template_ctx,
        debug,
        |value| value,
    ) {
        Ok(rendered) => rendered,
        Err(e) => return TemplateRender::Failed(e),
    };

    let mut rendered_headers =
        SplicedHeaders::with_capacity_and_hasher(headers.len(), Default::default());
    for (name, values) in headers {
        let mut rendered_values = Vec::with_capacity(values.len());
        for v in values {
            // Issue #359 B3 (header injection): a token can resolve to attacker-controlled request
            // data containing CR/LF, so what it substitutes is repaired before it ever reaches the
            // header map and a warning names what was removed.
            //
            // Repaired per substitution, not over the whole value (issue #1073): the literal text
            // the author wrote around a token is theirs, and a control character in it is an
            // authoring bug that must still fail the response — the same boundary `${request.*}`,
            // `copy` and `lookup` draw. Repairing it here would silently fix their typo and blame
            // the client for it in the log.
            match crate::extensions::template_fn::render_templated_spliced(
                &v,
                &template_ctx,
                debug,
                |substituted| sanitize_header_value(&substituted, stub),
            ) {
                Ok(rendered) => rendered_values.push(rendered),
                Err(e) => return TemplateRender::Failed(e),
            }
        }
        rendered_headers.insert(name.into(), rendered_values);
    }

    TemplateRender::Rendered {
        body,
        headers: rendered_headers,
    }
}

/// Render the `_rift.templated` body and header values (issue #359), off the tokio worker when the
/// flow store blocks (issue #971) — and not at all when nothing here can reach the store (#986).
///
/// `{{ state.<key> }}` reads the flow store, and doing that inline on the request task
/// head-of-line-blocks the worker for the backend round trip on a blocking backend (a networked store, or an
/// embedder's store that parks on an owner RPC) — the same defect issue #475 removed for the
/// scenario FSM and #969 for `_rift.stateOps`. On a current-thread runtime whose store is served by
/// that same runtime it does not merely stall: it deadlocks until the store times out and the token
/// renders empty. `run_flow_blocking` is the existing seam for exactly this, and it is transparent
/// on the default in-memory store — the closure runs inline there, with no task hop.
///
/// The render is pure over its inputs, so it moves wholesale: `RequestData` and the flow id are
/// owned, and the `TemplateContext` is rebuilt on the far side from the imposter's own store.
///
/// `Err` carries **only** a transport failure (a panicked blocking task); a template failure is
/// `Ok(TemplateRender::Failed)`.
async fn render_templated_response(
    imposter: &Arc<Imposter>,
    request_data: RequestData,
    flow_id: String,
    body: String,
    headers: crate::imposter::Headers,
    debug: bool,
    stub: super::headers::StubRef<'_>,
) -> anyhow::Result<TemplateRender> {
    // `{{ state.<key> }}` is the only head that reaches the flow store, so a template without one
    // has nothing to offload — and on a blocking backend that hop is pure cost (issue #986). The
    // predicate over-approximates toward offloading: a false positive is merely today's behaviour,
    // while a false negative would put a blocking read back on the worker (issue #971).
    let reads_state = crate::extensions::template_fn::reads_flow_state(&body)
        || headers
            .values()
            .flatten()
            .any(|v| crate::extensions::template_fn::reads_flow_state(v));

    if !reads_state {
        return Ok(render_template_parts(
            imposter,
            &request_data,
            &flow_id,
            body,
            headers,
            debug,
            stub,
        ));
    }

    // `stub` borrows `id` from the caller's stub, but `run_flow_blocking`'s closure must be
    // `'static` (it can hop to a `spawn_blocking` pool thread). Take the identity apart into
    // owned pieces here — once per offloaded request, not once per header value — and rebuild the
    // borrowed `StubRef` on the far side.
    let port = stub.port;
    let index = stub.index;
    let id = stub.id.map(str::to_string);
    imposter
        .run_flow_blocking(move |imp| {
            let stub = super::headers::StubRef {
                port,
                index,
                id: id.as_deref(),
            };
            Ok(render_template_parts(
                imp,
                &request_data,
                &flow_id,
                body,
                headers,
                debug,
                stub,
            ))
        })
        .await
}

/// The identity a serve-time repair log line is attributed to (issue #1075).
///
/// One function rather than the same struct literal at four call sites: the whole value of the
/// fields is that they name the *real* stub, so a field transposed at one site would point an
/// operator at the wrong config and nothing would catch it.
fn stub_ref<'a>(
    imposter: &Imposter,
    stub_index: usize,
    stub: &'a super::types::Stub,
) -> super::headers::StubRef<'a> {
    super::headers::StubRef {
        port: imposter.bound_port(),
        index: stub_index,
        id: stub.id.as_deref(),
    }
}

/// `journal_index` is an out-parameter: the index of the entry this request was recorded under, so
/// the caller can attach the status and elapsed time once the response exists (issue #364). Left
/// `None` when nothing was recorded — recording off, or a backend with no stable indices.
async fn handle_request_inner(
    req: Request<Incoming>,
    imposter: Arc<Imposter>,
    client_addr: SocketAddr,
    journal_index: &mut Option<u64>,
    inspection: &mut Option<Inspection>,
) -> Result<Response<Full<Bytes>>, Infallible> {
    // Check if enabled
    if !imposter.is_enabled() {
        return Ok(build_response_with_headers(
            StatusCode::SERVICE_UNAVAILABLE,
            [
                ("x-rift-imposter-disabled", "true"),
                ("content-type", "application/json"),
            ],
            crate::response::error_body_typed(
                StatusCode::SERVICE_UNAVAILABLE,
                crate::response::ErrorKind::ImposterDisabled,
                "Imposter is disabled",
            ),
        ));
    }

    // Increment request count
    imposter.increment_request_count();

    // Extract parts we need before consuming the request body. `into_parts()` (issue #561) hands
    // back owned `method`/`uri`/`headers` for free — no `.clone()` needed, unlike the old
    // `req.headers().clone()`. The raw map is kept only for the exchange inspector, which reports
    // the wire bytes; everything else reads `request_headers` below (issue #1040).
    let (parts, body) = req.into_parts();
    let method = parts.method.to_string();
    let uri = parts.uri;
    let raw_headers = parts.headers;
    // Request-scoped, built from a single request and dropped at response — a foldhash map (issue
    // #704); see `crate::util::fastmap` for the HashDoS policy. Insertion-ordered (issue #1606):
    // the journal, scripts and `MB_REQUEST` list the headers in the order the client sent them. One multi-value collector shared
    // with the intercept listener (issue #1025) now serves matching, proxy forwarding, flow id,
    // debug, inject and scripts, the recorded request below, AND — since issue #1040 — the
    // behaviors' request context and template substitution. Those last two used to make their own
    // second pass over the raw `HeaderMap` with a worse rule, so one request could answer
    // differently depending on which surface asked.
    let request_headers: crate::util::OrderedMap<String, Vec<String>> =
        crate::imposter::headers::collect_request_headers(&raw_headers, header_to_title_case);
    let path = uri.path().to_string();
    let query_str = uri.query().unwrap_or("").to_string();

    // Collect the body under the shared limits (issue #1439): over the ceiling is a 413, the
    // in-flight budget exhausted a 503. A transport failure mid-read (connection reset, truncated
    // stream) is the client's problem — a 400 — not a size error (issue #694). `_body_reservation`
    // holds this body's share of the budget until the response is built: the bytes stay in memory
    // throughout matching.
    let _body_reservation: CollectedBody = match imposter.body_guard.collect(body).await {
        Ok(collected) => collected,
        Err(BodyReadError::Read(e)) => {
            return Ok(body_read_error_response(e.as_ref()));
        }
        Err(e) => return Ok(body_refused_response(&e)),
    };
    // What the client sent, as sent: the proxy forwards these bytes, still encoded (issue #1584).
    let wire_bytes = Some(_body_reservation.bytes().clone()).filter(|bytes| !bytes.is_empty());
    // A `gzip` / `br` body is decoded before anything reads it, as Mountebank decodes it (issue
    // #1584). The decoded bytes hold their own share of the body budget, alongside the raw body's,
    // until the response is built. A body that does not decode is `body_undefined`: no text, and
    // every consumer below sees the body as missing rather than empty.
    let (_decoded_reservation, body_undefined) = match Coding::of(&raw_headers) {
        None => (None, false),
        Some(coding) => {
            match decode_request_body(&imposter, coding, _body_reservation.bytes().clone()).await {
                Ok(Ok(Decoded::Body(decoded))) => (Some(decoded), false),
                Ok(Ok(Decoded::Undefined)) => (None, true),
                Ok(Err(e)) => return Ok(body_refused_response(&e)),
                Err(e) => return Ok(decode_failed_response(&e)),
            }
        }
    };
    let body_bytes = match &_decoded_reservation {
        Some(decoded) => Some(decoded.bytes().clone()),
        None if body_undefined => None,
        None => wire_bytes.clone(),
    }
    .filter(|bytes| !bytes.is_empty());
    // Borrow the body as UTF-8 without forcing an allocation for the common valid-UTF-8 case
    // (issue #561): valid UTF-8 stays `Cow::Borrowed`, so only genuinely invalid UTF-8 pays a
    // copy here. `body_bytes` stays alive for the rest of the function so this borrow remains
    // valid; callers that need an owned `String` (`RecordedRequest`, `ScriptRequest`,
    // thread-moved debug/inject requests) materialize one at that boundary.
    //
    // Invalid UTF-8 (a binary body: protobuf, gzip, an image upload) used to go through
    // `from_utf8_lossy`, which silently replaces the offending bytes with U+FFFD — the recorded
    // request, predicate matches, and script/inject bodies then no longer reflect what the
    // client sent, irreversibly (issue #636). Base64-encode it instead, mirroring the response
    // side's `encode_body_for_stub` (issue #117): every consumer below gets a lossless string
    // representation, and `mode` tells them which kind they have.
    let (body_string, body_mode): (Option<std::borrow::Cow<'_, str>>, ResponseMode) =
        match body_bytes.as_deref() {
            None => (None, ResponseMode::Text),
            Some(bytes) => match std::str::from_utf8(bytes) {
                Ok(text) => (Some(std::borrow::Cow::Borrowed(text)), ResponseMode::Text),
                Err(_) => (
                    Some(std::borrow::Cow::Owned(
                        base64::engine::general_purpose::STANDARD.encode(bytes),
                    )),
                    ResponseMode::Binary,
                ),
            },
        };

    // Record request if enabled. The journal index is kept (not discarded as before) so this
    // request's match outcome can be attached to that exact entry once matching has finished;
    // `None` means there is no entry to annotate — recording is off, or the backend has no stable
    // indices.
    *journal_index = if imposter.config.record_requests {
        let arrived_at = crate::imposter::clock::recorded_instant(&imposter.clock);
        let recorded = RecordedRequest {
            body_omitted: false,
            request_from: client_addr.to_string(),
            method: method.clone(),
            path: path.clone(),
            // `RecordedRequest.query` is the fixed std-hasher journal/serde boundary (out of scope
            // for #704); the parsed map is re-hashed at this edge, keeping request order (issue
            // #1596). Every value of a repeated key is kept, as Mountebank records it (#1553).
            query: parse_query_string(&query_str).into_iter().collect(),
            // `RecordedRequest.headers` is the fixed std-hasher journal/serde boundary (out of
            // scope for #704) — the request-scoped map is converted here, at the one place
            // recording is actually enabled, rather than built twice (issue #1025). Both keep the
            // client's order (issue #1606).
            headers: request_headers
                .iter()
                .map(|(k, v)| (k.clone(), v.clone()))
                .collect(),
            // A request without a body is recorded as `""`, as Mountebank records it (issue
            // #1365). Still an `Option`, so journals written before decode unchanged. A body that
            // did not decode has no `body` key at all, as `JSON.stringify` drops Mountebank's
            // undefined body (issue #1584).
            body: (!body_undefined).then(|| body_string.as_deref().unwrap_or_default().to_string()),
            mode: body_mode.clone(),
            timestamp: super::types::journal_timestamp(chrono::Utc::now()),
            // Its place on the imposter's timeline, when that is not the wall (issue #1796).
            clock_ms: arrived_at.map(|(ms, _)| ms),
            clock_source: arrived_at.map(|(_, source)| source),
            // Filled in after the match, via `attach_match_outcome` below.
            match_outcome: None,
            // Filled in after the response exists, by `attach_response_outcome` in the caller.
            status: None,
            latency_ms: None,
            // Never set here: this engine is one node and has no name for itself. A clustered
            // journal stamps it in its own `record` (issue #364).
            node: None,
        };
        imposter.record_request(recorded)
    } else {
        None
    };

    // Issue #966: the request-side hook of an installed exchange inspector runs HERE — after
    // journaling (the request already arrived; hiding it would falsify `savedRequests`, and its
    // entry carries the rejection's status like any other, attached by the caller once the
    // response exists) and before stub matching, so a rejection never advances a cycler, a
    // scenario FSM or a match counter — the only defensible semantics for "this request was
    // off-policy". The owned view handed out through `inspection` survives into the response-side
    // hook in `handle_imposter_request`.
    if let Some(inspector) = &imposter.exchange_inspector {
        let port = imposter.config.port.unwrap_or(0);
        let req_view = InspectRequest {
            port,
            method: &method,
            path: &path,
            query: &query_str,
            headers: &raw_headers,
            body: body_string.as_deref(),
            mode: &body_mode,
        };
        match inspector.inspect_request(&req_view) {
            // A rejection answers the exchange right here; `inspection` stays `None`, which is
            // what tells the response-side hook there is nothing further to show.
            InspectVerdict::Reject {
                status,
                content_type,
                body,
            } => {
                return Ok(build_response_with_headers(
                    inspector_reject_status(status),
                    [
                        ("content-type", content_type.as_str()),
                        ("x-rift-imposter", "true"),
                    ],
                    body,
                ));
            }
            // Materialised only here, and only on `Proceed` — an imposter with no inspector clones
            // nothing, and a rejected request has no response-side hook to carry this into.
            InspectVerdict::Proceed => {
                *inspection = Some(Inspection {
                    method: method.clone(),
                    path: path.clone(),
                    query: query_str.clone(),
                    headers: raw_headers.clone(),
                    body: body_string.as_deref().map(str::to_string),
                    mode: body_mode.clone(),
                });
            }
        }
    }

    // A request-keyed random stream (issue #1795), before anything the request runs draws and
    // after the inspector, so a request it rejects takes no occurrence of its key.
    rekey_request_stream(
        &imposter,
        &method,
        &path,
        &request_headers,
        &query_str,
        body_string.as_deref(),
    );

    // Find matching stub
    let method_str = method.as_str();
    let path_str = path.as_str();
    let query_opt = if query_str.is_empty() {
        None
    } else {
        Some(query_str.as_str())
    };

    // Check for X-Rift-Debug header (Rift extension)
    // If present, return match information instead of processing the request
    let is_debug_mode = request_headers
        .get("X-Rift-Debug")
        .or_else(|| request_headers.get("x-rift-debug"))
        .and_then(|v| v.first())
        .map(|v| v.eq_ignore_ascii_case("true") || v == "1")
        .unwrap_or(false);

    // Every script execution below (debug-mode matching, predicate inject during matching,
    // response inject, decorate) shares the imposter's `_rift.scriptEngine.timeoutMs`
    // wall-clock budget (issue #476), like `_rift.script`.
    let script_timeout = std::time::Duration::from_millis(
        crate::scripting::resolve_script_timeout_ms(&imposter.config),
    );

    if is_debug_mode {
        // Debug matching evaluates the full predicate set — inject predicates included — so it
        // runs off the async worker under the script deadline like the data-plane matcher
        // (issue #476). Unconditional spawn_blocking: this is an opt-in diagnostic path.
        let debug_imposter = Arc::clone(&imposter);
        let (dbg_method, dbg_path, dbg_query) = (method.clone(), path.clone(), query_str.clone());
        let dbg_headers = request_headers.clone();
        // Materialize an owned copy here (issue #561): `body_string` borrows from `body_bytes`,
        // which does not outlive this `spawn_blocking` closure's `'static` bound.
        let dbg_body = body_string.as_deref().map(str::to_string);
        // Debug matching runs the same sync matcher the data plane offloads, so it reaches the
        // flow store (scenario gate, inject scripts) and a failing backend annotates there —
        // on a pool thread with no task-local unless the closure carries its own scope (#987).
        let handle = crate::extensions::decorate::spawn_blocking_annotated(move || {
            handle_debug_request(
                &debug_imposter,
                &dbg_method,
                &dbg_path,
                &dbg_query,
                &dbg_headers,
                &dbg_body,
                client_addr,
            )
        });
        let mut report = match tokio::time::timeout(script_timeout, handle).await {
            Ok(Ok((response, annotations))) => {
                crate::extensions::decorate::replay_annotations(annotations);
                response?
            }
            Ok(Err(join_err)) => {
                warn!("debug matching task panicked: {join_err}");
                debug_matching_error_response()
            }
            Err(_elapsed) => {
                warn!(
                    "debug matching timed out after {}ms",
                    script_timeout.as_millis()
                );
                debug_matching_timeout_response()
            }
        };
        report.extensions_mut().insert(DebugReport);
        return Ok(report);
    }

    // Get client address info for requestFrom, ip predicates
    let request_from = client_addr.to_string();
    let client_ip = client_addr.ip().to_string();
    // Trace the scan only when there is a journal entry to attach the outcome to: with no entry
    // the trace would be built and thrown away. That also means an imposter with recording off
    // pays exactly what it paid before.
    let want_trace = journal_index.is_some();
    // Before the scenario gates are read, so a transition landing mid-request cannot stamp the
    // answer it replaced (issue #1307).
    let scenario_transitions = imposter.scenario_transitions();
    // One state cell for the whole request, every hook on it: a restart mid-request takes effect
    // from the next request (issue #1784). A plain `PUT /imposters` also cuts this request off
    // (issue #1799), so on the engine this holds even for a request the cut misses. `script_file_access` stays per site on purpose: a
    // stub write narrows it for a request about to run a script (#1645).
    let script_scope = imposter.script_scope();
    let (mut matched, mut trace) = match imposter
        .find_matching_stub_with_client_bounded_inner(
            method_str,
            path_str,
            &request_headers,
            query_opt,
            body_string.as_deref(),
            Some(&request_from),
            Some(&client_ip),
            script_timeout,
            want_trace,
            script_scope.clone(),
        )
        .await
    {
        Ok(traced) => traced,
        // A backend consulted during matching failed (issue #318), or a predicate-`inject`
        // errored (issue #440): surface it, never fall through to "no match" (which would
        // serve the wrong response). No outcome is attached — the pass produced no verdict, and
        // an absent outcome says exactly that.
        Err(e) => return Ok(matcher_error_response(&e)),
    };

    // Issue #819: on a genuine no-match, give a registered interceptor one last chance before
    // falling through to defaultForward/defaultResponse/empty-200 — deliberately even when a
    // default IS configured, since under replication lag the right stub may be momentarily
    // missing and the request would otherwise be misdirected upstream (rescue outranks
    // forwarding). A `RetryMatch` re-runs matching exactly once with the identical arguments; a
    // rescued hit is indistinguishable from a first-try match to everything downstream. A second
    // miss falls through exactly as `Proceed` would.
    if matched.is_none()
        && let Some(interceptor) = &imposter.no_match_interceptor
    {
        let ctx = NoMatchContext {
            port: imposter.config.port.unwrap_or(0),
            method: method_str,
            path: path_str,
        };
        if interceptor.on_no_match(ctx).await == NoMatchDirective::RetryMatch {
            // The retry's own trace replaces the first pass's: a rescued request is served as a
            // normal match, so the outcome must describe the scan that actually decided it.
            (matched, trace) = match imposter
                .find_matching_stub_with_client_bounded_inner(
                    method_str,
                    path_str,
                    &request_headers,
                    query_opt,
                    body_string.as_deref(),
                    Some(&request_from),
                    Some(&client_ip),
                    script_timeout,
                    want_trace,
                    script_scope.clone(),
                )
                .await
            {
                Ok(traced) => traced,
                Err(e) => return Ok(matcher_error_response(&e)),
            };
        }
    }

    // Attach once, from the FINAL match state — after any rescue, and never on the paths that
    // returned above (the debug branch and a matcher error), where absence of an outcome is the
    // honest report that none was reached.
    if let (Some(index), Some(trace)) = (*journal_index, trace) {
        let winner = matched.as_ref().map(|(state, i)| (&state.stub, *i));
        imposter.attach_match_outcome(index, trace.into_outcome(winner));
    }

    if let Some((stub_state, stub_index)) = matched {
        // Scenario FSM: apply the matched stub's newScenarioState transition (no-op unless set).
        // Resolve flow_id from the same header map the matcher used (`request_headers`) so the
        // transition writes the exact key the gate read.
        let scenario_flow_id = imposter.resolve_flow_id(&request_headers);
        // Offload the FSM transition to spawn_blocking on a blocking backend (a networked store) so it can't
        // stall the tokio worker; inline on the in-memory backend (issue #475).
        //
        // Guarded on `new_scenario_state` because that is the identical check
        // `apply_scenario_transition` makes as its own first statement: with no transition set it
        // returns `Ok(())` having touched nothing. A stub without one is the common case, so
        // without this guard a blocking backend paid a spawn_blocking hop on every matched request
        // to run a function that does nothing (issue #986).
        if stub_state.stub.new_scenario_state.is_some() {
            let transition = {
                let flow_id = scenario_flow_id.clone();
                let stub_state = Arc::clone(&stub_state);
                imposter
                    .run_flow_blocking(move |imp| {
                        imp.apply_scenario_transition(&flow_id, &stub_state.stub)
                    })
                    .await
            };
            if let Err(e) = transition {
                return Ok(backend_error_response(&e));
            }
        }

        // Advance the shared response cycler exactly ONCE for this matched request and dispatch on
        // the returned response. Previously each response type was classified by a non-advancing
        // peek and then advanced through a separate cycler call, so a concurrent request could move
        // the cursor between the peek and the advance and serve the wrong branch — or a bogus empty
        // `x-rift-no-match` 200 (issue #559). A consequence of advancing once up front: the cursor
        // now advances even when proxy/inject/script handling fails (a shared atomic cursor cannot
        // be safely un-advanced under concurrency), whereas before a failed handling left the
        // cursor for the next request to retry.
        let response: Option<&StubResponse> = match imposter.next_stub_response(&stub_state) {
            Ok(r) => r,
            Err(e) => return Ok(backend_error_response(&e)),
        };

        // Check if this is a proxy response
        if let Some(StubResponse::Proxy {
            proxy: proxy_config,
            behaviors_parsed,
            ..
        }) = response
        {
            // A `repeat`-only block transforms nothing, so the upstream response is relayed as is —
            // headers in order, `content-length` kept.
            let run = behaviors_parsed
                .as_deref()
                .filter(|parsed| parsed.transforms_response())
                .map(|parsed| BehaviorRun {
                    behaviors: parsed,
                    method: &method,
                    uri: &uri,
                    request_headers: &request_headers,
                    request_body: body_string.as_deref(),
                    request_body_undefined: body_undefined,
                    client_addr: Some(client_addr),
                    script_scope: script_scope.clone(),
                    script_files: imposter.script_file_access(),
                    stub: stub_ref(&imposter, stub_index, &stub_state.stub),
                    csv_cache: csv_cache(),
                    body_guard: &imposter.body_guard,
                    script_timeout,
                    strict: strict_behaviors_for(&imposter.config),
                    default_response: imposter.config.default_response.as_ref(),
                });
            // Per-request entry announcement — `trace!` so it compiles out of release (issue #706);
            // the outcome (status/latency) is captured by metrics and the response's x-rift-* headers.
            trace!("Handling proxy request to {}", proxy_config.to);
            match imposter
                .handle_proxy_request(
                    proxy_config,
                    UpstreamTarget::Origin,
                    method_str,
                    &uri,
                    &request_headers,
                    proxy_body(wire_bytes.as_ref(), body_string.as_deref()),
                    run.as_ref(),
                    Some(stub_state.slot),
                    client_addr,
                )
                .await
            {
                Ok(ProxyOutcome::StrictFailure(response)) => return Ok(response),
                Ok(ProxyOutcome::Served(ProxiedResponse {
                    status,
                    headers: response_headers,
                    body,
                    latency_ms: latency,
                })) => {
                    let mut response = Response::builder().status(status);

                    for (k, v) in &response_headers {
                        if !crate::util::is_hop_by_hop_header(k) {
                            response = response.header(k, v);
                        }
                    }

                    response = response.header("x-rift-imposter", "true");
                    response = response.header("x-rift-proxy", "true");

                    if let Some(ms) = latency {
                        response = response.header("x-rift-proxy-latency", ms.to_string());
                    }

                    return Ok(response
                        .body(Full::new(Bytes::from(body)))
                        .unwrap_or_else(|e| {
                            build_failure_response(
                                &e,
                                "proxy response build failed (bad upstream header?)",
                            )
                        }));
                }
                Err(e) => {
                    return Ok(proxy_leg_error_response(
                        &e,
                        "Proxy request failed",
                        "x-rift-proxy-error",
                        "Proxy error",
                    ));
                }
            }
        }

        // Check if this is an inject response (JavaScript function)
        #[cfg(feature = "javascript")]
        if let Some(StubResponse::Inject {
            inject: inject_fn,
            behaviors_parsed,
            ..
        }) = response
        {
            trace!("Handling inject response");

            // Build request for inject function
            let mb_request = MountebankRequest {
                method: method.clone(),
                path: path.clone(),
                // A repeated key or header reaches the script as an array (issue #1629).
                query: parse_query_string(&query_str),
                // Owned boundary: the inject job is submitted to a `'static` worker closure.
                headers: request_headers.clone(),
                // Owned boundary (issue #561): the inject job is submitted to a `'static` worker
                // closure, so `body_string`'s borrow can't cross it.
                body: body_string.as_deref().map(str::to_string),
                body_undefined,
                mode: Some(body_mode.clone()),
                request_from: Some(client_addr.to_string()),
                ip: Some(client_addr.ip().to_string()),
                form: Imposter::request_form(&request_headers, body_string.as_deref()),
                is_dry_run: false,
            };

            match execute_mountebank_inject_bounded(
                inject_fn.clone(),
                mb_request,
                script_scope.clone(),
                stub_state.stub.id.clone(),
                imposter.script_file_access(),
                script_timeout,
            )
            .await
            {
                Ok(inject_response) => {
                    // An inject's output is the author's text, like a decorate's (issue #1203). What
                    // the function did not return is completed from `defaultResponse` (issue #1369),
                    // or is `200`, no headers and an empty body when there is none.
                    let authored = IsResponse::decoded(
                        inject_response.status_code.map(|status| match status {
                            crate::behaviors::ResponseStatus::Code(code) => {
                                super::types::StatusValue::Code(code)
                            }
                            // Read when the response is written, as an `is` string is (#1635).
                            crate::behaviors::ResponseStatus::Text(text) => {
                                super::types::StatusValue::from_text(text)
                            }
                        }),
                        inject_response.headers.map(|headers| {
                            headers.into_iter().map(|(k, v)| (k, vec![v])).collect()
                        }),
                        inject_response.body.map(serde_json::Value::String),
                        None,
                    );
                    let mut parts = ServedParts::completed(
                        &authored,
                        imposter.config.default_response.as_ref(),
                    );
                    // Mountebank runs a response's behaviors on the injected response too
                    // (issue #1188). A failed inject never gets here, so it runs none of them —
                    // as in Mountebank, which throws before executing behaviors.
                    if let Some(parsed_behaviors) = behaviors_parsed {
                        let run = BehaviorRun {
                            behaviors: parsed_behaviors,
                            method: &method,
                            uri: &uri,
                            request_headers: &request_headers,
                            request_body: body_string.as_deref(),
                            request_body_undefined: body_undefined,
                            client_addr: Some(client_addr),
                            script_scope: script_scope.clone(),
                            script_files: imposter.script_file_access(),
                            stub: stub_ref(&imposter, stub_index, &stub_state.stub),
                            csv_cache: csv_cache(),
                            body_guard: &imposter.body_guard,
                            script_timeout,
                            strict: strict_behaviors_for(&imposter.config),
                            default_response: imposter.config.default_response.as_ref(),
                        };
                        match run.apply(parts).await {
                            BehaviorOutcome::Applied { parts: applied, .. } => parts = applied,
                            BehaviorOutcome::StrictFailure(response) => return Ok(response),
                        }
                    }

                    let served = match resolve_status(
                        parts.status,
                        parts.status_text.as_ref().map(Spliced::as_str),
                        imposter.config.default_response.as_ref(),
                    ) {
                        Ok(served) => served,
                        Err(value) => return Ok(invalid_status_response(&value)),
                    };
                    let mut response = Response::builder().status(served);
                    for (k, values) in &parts.headers {
                        for v in values {
                            response = response.header(k.as_str(), v.as_str());
                        }
                    }

                    response = response.header("x-rift-imposter", "true");
                    response = response.header("x-rift-inject", "true");

                    return Ok(response
                        .body(Full::new(Bytes::from(parts.body.into_text())))
                        .unwrap_or_else(|e| {
                            match invalid_header_name(parts.headers.keys().map(|k| k.as_str())) {
                                Some(name) => invalid_header_name_response(name),
                                None => build_failure_response(
                                    &e,
                                    "inject response build failed (bad injected header?)",
                                ),
                            }
                        }));
                }
                Err(e) => {
                    log_upstream_failure("Inject function failed", &e);
                    // A deadline miss (issue #499) is a transient 504 a client can retry, not the
                    // permanent-config 400 below — distinguish it before the parity mapping.
                    if let Some(t) = e.downcast_ref::<crate::scripting::ScriptTimeoutError>() {
                        return Ok(inject_timeout_response(
                            crate::response::ErrorKind::InjectionTimeout,
                            &t.to_string(),
                        ));
                    }
                    // Mountebank-shaped error parity (issues #355 Item 5, #1581): a failing
                    // inject is a 500 with `{"errors":[{"code":"invalid injection","message":
                    // "...","data":"<thrown message>"}]}`, as `baseHttpServer.js:150-155` answers
                    // an `InjectionError`. (#355 had assumed 400; Mountebank's status is 500.)
                    let data = e
                        .downcast_ref::<crate::scripting::InjectionFailure>()
                        .and_then(|f| f.data.as_deref());
                    let body = inject_failure_body(
                        crate::response::ErrorKind::InvalidInjection,
                        &format!("{e}"),
                        data,
                    );
                    return Ok(build_response_with_headers(
                        StatusCode::INTERNAL_SERVER_ERROR,
                        [
                            ("x-rift-imposter", "true"),
                            ("x-rift-inject-error", "true"),
                            ("content-type", "application/json"),
                        ],
                        body,
                    ));
                }
            }
        }

        // Check if this is a RiftScript response (_rift.script)
        if let Some(script_config) = response.and_then(get_rift_script_config) {
            // `code` is populated by the config-time resolve-scripts pass (issue #356), which
            // runs before an imposter carrying `file:`/`ref:` scripts is ever created. A `None`
            // here means that pass was skipped (e.g. a stub added through a sub-resource
            // endpoint that doesn't resolve scripts) — surface it as a clear error instead of
            // silently running an empty script.
            // A `component` reference (issue #1757) resolves from the manager's registry now, not
            // at admission: a replayed config whose component this node lacks still loads, and
            // answers a script error here.
            let held_component = match script_config.component.as_deref() {
                None => None,
                Some(reference) => {
                    let entry = reference
                        .parse::<crate::imposter::components::ComponentId>()
                        .ok()
                        .and_then(|id| imposter.components.get(&id));
                    match entry {
                        Some(entry) => Some(entry),
                        None => {
                            return Ok(build_response_with_headers(
                                StatusCode::INTERNAL_SERVER_ERROR,
                                [
                                    ("x-rift-imposter", "true"),
                                    ("x-rift-script-error", "true"),
                                    ("content-type", "application/json"),
                                ],
                                crate::response::error_body(
                                    StatusCode::INTERNAL_SERVER_ERROR,
                                    &format!(
                                        "Script error: unknown component {reference}; upload it with POST /components"
                                    ),
                                ),
                            ));
                        }
                    }
                }
            };
            let code = held_component
                .as_ref()
                .map(|entry| &*entry.code)
                .or(script_config.code.as_deref());
            let Some(code) = code else {
                return Ok(build_response_with_headers(
                    StatusCode::INTERNAL_SERVER_ERROR,
                    [
                        ("x-rift-imposter", "true"),
                        ("x-rift-script-error", "true"),
                        ("content-type", "application/json"),
                    ],
                    crate::response::error_body(
                        StatusCode::INTERNAL_SERVER_ERROR,
                        "script not resolved: `file:`/`ref:` sources must be resolved before serving",
                    ),
                ));
            };
            // Resolution writes the engine into every script it sees; a door that does not resolve
            // (the C-ABI create) reaches here engine-less, and gets the same default (#1159).
            let engine = match (&script_config.engine, &held_component) {
                (Some(engine), _) => engine.clone(),
                (None, Some(_)) => "wasm".to_owned(),
                (None, None) => imposter.config.default_script_engine().to_owned(),
            };
            // A component is wasm (issue #1757). A door that does not validate (the C-ABI create,
            // a replay) can still carry `component` with another engine: never run its bytes as
            // Rhai or JavaScript.
            if held_component.is_some() && !crate::scripting::ScriptEngineKind::is_wasm(&engine) {
                return Ok(build_response_with_headers(
                    StatusCode::INTERNAL_SERVER_ERROR,
                    [
                        ("x-rift-imposter", "true"),
                        ("x-rift-script-error", "true"),
                        ("content-type", "application/json"),
                    ],
                    crate::response::error_body(
                        StatusCode::INTERNAL_SERVER_ERROR,
                        &format!(
                            "Script error: `component` is a wasm component; engine must be \"wasm\", not \"{engine}\""
                        ),
                    ),
                ));
            }
            trace!("Handling Rift script response (engine: {})", engine);

            // Build script request. Expose headers with lowercase keys so scripts can read
            // them case-insensitively (e.g. `request.headers["x-flow-id"]`) regardless of the
            // wire casing; this matches the engine docs and HTTP header semantics.
            let script_request = ScriptRequest {
                // Owned boundary (issue #561): `ScriptRequest` is moved into the script engine's
                // worker job, so the body must be materialized here rather than borrowed.
                raw_body: Some(body_string.as_deref().unwrap_or_default().to_string()),
                mode: body_mode.clone(),
                method: method.clone(),
                path: path.clone(),
                // Every value (issue #1629): a script sees a repeated header as an array, as every
                // other scripting boundary (inject, decorate, predicateGenerators) does.
                headers: request_headers
                    .iter()
                    .filter(|(_, v)| !v.is_empty())
                    .map(|(k, v)| (k.to_ascii_lowercase(), v.clone()))
                    .collect(),
                // Domain-optional parse: a request body may legitimately not be JSON, and the
                // script contract exposes that as `null` rather than an error (issue #611).
                body: body_string
                    .as_deref()
                    .and_then(|s| serde_json::from_str(s).ok())
                    .unwrap_or(serde_json::Value::Null),
                // A repeated key reaches the script as an array (issue #1629).
                query: parse_query_string(&query_str),
                // Issue #433: populate path params from the matched stub's route pattern, if any.
                path_params: stub_state
                    .stub
                    .route_pattern
                    .as_deref()
                    .map(|pattern| {
                        crate::extensions::template::extract_path_params(pattern, &path)
                            .into_iter()
                            .collect()
                    })
                    .unwrap_or_default(),
            };

            // Execute the script off the async worker under a wall-clock deadline (issue
            // #308): a runaway script is interrupted at `_rift.scriptEngine.timeoutMs`
            // (default 5s) instead of wedging the whole engine.
            let timeout_ms = resolve_script_timeout_ms(&imposter.config);
            // Scenario-key writes stamp a transition (issue #1388).
            let flow_store: Arc<dyn crate::extensions::flow_state::FlowStore> = Arc::new(
                super::core::ScenarioStampingStore::new(Arc::clone(&imposter)),
            );

            // ctx.stub (issue #357 Item 1): thread the matched stub's identity through, resolving
            // its current scenario state (if it belongs to a scenario) the same way the FSM gate
            // already does. A backend failure here must surface, not silently drop to `None`
            // (this epic's "nothing fails silently" principle).
            let scenario_state = match &stub_state.stub.scenario_name {
                Some(name) => {
                    // Same spawn_blocking offload as the FSM gate/transition (issue #475).
                    let flow_id = scenario_flow_id.clone();
                    let name = name.clone();
                    match imposter
                        .run_flow_blocking(move |imp| imp.scenario_state(&flow_id, &name))
                        .await
                    {
                        Ok(s) => Some(s),
                        Err(e) => return Ok(backend_error_response(&e)),
                    }
                }
                None => None,
            };
            let ctx_extra = ScriptCtxExtras {
                flow_id: Some(scenario_flow_id.clone()),
                stub: ScriptStubContext {
                    scenario_name: stub_state.stub.scenario_name.clone(),
                    scenario_state,
                    stub_id: stub_state.stub.id.clone(),
                },
                port: imposter.config.port.unwrap_or(0),
                raw_query: Some(query_str.clone()),
                https: imposter.config.protocol.eq_ignore_ascii_case("https"),
            };

            // Debug-mode script trace (issue #360 Item 3): which hook ran, its decision,
            // duration, and ctx.logger lines, so "why didn't my script run the way I expected"
            // is answerable from the response alone. Zero-cost when debug mode is off — the
            // capturing-subscriber/Instant path in the `_traced` variant is only ever built when
            // this flag is set, so the hot (non-debug) path calls the original, unchanged
            // `should_inject_bounded_with_ctx`.
            // Issue #999: the duration is threaded out of both branches rather than measured
            // around the whole `if`, so debug mode reports the same script time as the hot path —
            // an outer timer would also count the trace's JSON serialization below.
            let script_started = std::time::Instant::now();
            let script_duration_ms: u64;
            // An `export: "http"` component's whole response (issue #1758), served as it is;
            // `script_result` then carries its status for the metrics below.
            let mut wasm_http: Option<crate::scripting::WasmResponse> = None;
            let (script_result, trace_header): (Result<FaultDecision, anyhow::Error>, _) =
                if crate::scripting::ScriptEngineKind::is_wasm(&engine) {
                    // A component runs on this task under its epoch deadline (issue #1751), and
                    // borrows its code: no per-request copy of the component's text.
                    // The request's `X-Rift-Now`, else the imposter's clock (issue #1754).
                    let script_clock = match crate::imposter::clock::request_override() {
                        Some(ms) => crate::scripting::ScriptClock::Fixed(ms),
                        None => {
                            crate::scripting::ScriptClock::Imposter(Arc::clone(&imposter.clock))
                        }
                    };
                    let script = crate::scripting::WasmScript {
                        code,
                        export: script_config.export.as_deref(),
                        knobs: script_config.knobs.as_ref(),
                        limits: imposter.config.wasm_limits(),
                        clock: Some(&script_clock),
                        instance: script_config.instance.as_deref(),
                        instances: Some(&imposter.wasm_instances),
                    };
                    let rule_id = format!("rift_script_{stub_index}");
                    let timeout = Duration::from_millis(timeout_ms);
                    // A kept instance's call outlives this request (issue #1793): once a restart
                    // or a delete cuts the request, the call no longer reaches the imposter's state.
                    let flow_store: Arc<dyn crate::extensions::flow_state::FlowStore> =
                        Arc::new(crate::extensions::flow_state::CutOffStore::new(
                            flow_store,
                            imposter.in_flight.load_full(),
                        ));
                    let (result, header) = if crate::util::rift_debug_env() {
                        let (result, mut entry) = crate::scripting::should_inject_wasm_traced(
                            script,
                            &rule_id,
                            &script_request,
                            flow_store,
                            timeout,
                            &ctx_extra,
                        )
                        .await;
                        entry.logs = crate::scripting::cap_trace_logs(entry.logs);
                        let header = serde_json::to_string(&[entry])
                            .inspect_err(|e| {
                                warn!("failed to serialize x-rift-script-trace: {}", e)
                            })
                            .ok();
                        (result, header)
                    } else {
                        let result = crate::scripting::should_inject_wasm(
                            script,
                            &rule_id,
                            &script_request,
                            flow_store,
                            timeout,
                            &ctx_extra,
                        )
                        .await;
                        (result, None)
                    };
                    script_duration_ms =
                        u64::try_from(script_started.elapsed().as_millis()).unwrap_or(u64::MAX);
                    let result = match result {
                        Ok(crate::scripting::WasmAnswer::Decision(decision)) => Ok(decision),
                        Ok(crate::scripting::WasmAnswer::Response(response)) => {
                            let status = response.status;
                            wasm_http = Some(response);
                            Ok(FaultDecision::Error {
                                status,
                                body: String::new(),
                                rule_id,
                                headers: std::collections::HashMap::new(),
                            })
                        }
                        Err(e) => Err(e),
                    };
                    (result, header)
                } else if crate::util::rift_debug_env() {
                    let (result, mut entry) = should_inject_bounded_with_ctx_traced(
                        engine.clone(),
                        code.to_owned(),
                        format!("rift_script_{stub_index}"),
                        script_request,
                        flow_store,
                        Duration::from_millis(timeout_ms),
                        ctx_extra,
                    )
                    .await;
                    // Cap a chatty script's logger output: the trace ships on a response header,
                    // which must stay bounded (issue #360).
                    entry.logs = crate::scripting::cap_trace_logs(entry.logs);
                    // `ScriptTraceEntry` is plain strings/numbers, so this can't realistically
                    // fail — but on the off chance it does, trace the failure instead of
                    // silently dropping the header.
                    let traced_ms = entry.duration_ms;
                    let header = serde_json::to_string(&[entry])
                        .inspect_err(|e| warn!("failed to serialize x-rift-script-trace: {}", e))
                        .ok();
                    script_duration_ms = traced_ms;
                    (result, header)
                } else {
                    let result = should_inject_bounded_with_ctx(
                        engine.clone(),
                        code.to_owned(),
                        format!("rift_script_{stub_index}"),
                        script_request,
                        flow_store,
                        Duration::from_millis(timeout_ms),
                        ctx_extra,
                    )
                    .await;
                    script_duration_ms =
                        u64::try_from(script_started.elapsed().as_millis()).unwrap_or(u64::MAX);
                    (result, None)
                };

            // Issue #999: `_rift.script` execution and any fault it decides are reported here.
            // `source="script"` distinguishes these from `_rift.fault` decisions, which carry
            // `source="rift"`; `rule_id` is the imposter port on both paths.
            {
                let rule_id = imposter.bound_port().to_string();
                let outcome = match &script_result {
                    Ok(FaultDecision::None) => "pass",
                    Ok(_) => "fault",
                    Err(_) => "error",
                };
                crate::extensions::metrics::record_script_execution(
                    &rule_id,
                    script_duration_ms as f64,
                    outcome,
                );
                match &script_result {
                    Ok(FaultDecision::Error { .. }) => {
                        crate::extensions::metrics::record_script_fault("error", &rule_id, None);
                    }
                    Ok(FaultDecision::Latency { duration_ms, .. }) => {
                        // Carries the delay so a script-decided latency lands in the same
                        // histogram as a `_rift.fault` one.
                        crate::extensions::metrics::record_script_fault(
                            "latency",
                            &rule_id,
                            Some(*duration_ms),
                        );
                    }
                    Ok(FaultDecision::Reset { .. }) => {
                        crate::extensions::metrics::record_script_fault("tcp", &rule_id, None);
                    }
                    Ok(FaultDecision::None) => {}
                    Err(e) => {
                        // The only distinction the error channel actually carries: a deadline miss
                        // is transient, anything else is a broken script. Coarse on purpose.
                        let error_type = if e
                            .downcast_ref::<crate::scripting::ScriptTimeoutError>()
                            .is_some()
                        {
                            "timeout"
                        } else {
                            "runtime"
                        };
                        crate::extensions::metrics::record_script_error(&rule_id, error_type);
                    }
                }
            }

            if let Some(response) = wasm_http {
                return Ok(wasm_http_response(response, &engine, trace_header));
            }
            match script_result {
                Ok(FaultDecision::Error {
                    status,
                    body,
                    headers,
                    ..
                }) => {
                    let mut response = Response::builder().status(status);
                    for (k, v) in &headers {
                        response = response.header(k, v);
                    }
                    response = response.header("x-rift-imposter", "true");
                    response = response.header("x-rift-script", &engine);
                    if let Some(trace) = &trace_header {
                        response = response.header("x-rift-script-trace", trace.as_str());
                    }

                    return Ok(response
                        .body(Full::new(Bytes::from(body)))
                        .unwrap_or_else(|e| {
                            build_failure_response(
                                &e,
                                "script response build failed (bad script header?)",
                            )
                        }));
                }
                Ok(FaultDecision::Latency { duration_ms, .. }) => {
                    // Apply latency then return 200 OK
                    tokio::time::sleep(Duration::from_millis(duration_ms)).await;
                    let mut headers = vec![
                        ("x-rift-imposter".to_string(), "true".to_string()),
                        ("x-rift-script".to_string(), engine.clone()),
                        ("x-rift-latency-ms".to_string(), duration_ms.to_string()),
                    ];
                    if let Some(trace) = trace_header {
                        headers.push(("x-rift-script-trace".to_string(), trace));
                    }
                    return Ok(build_response_with_headers(
                        StatusCode::OK,
                        headers,
                        Bytes::new(),
                    ));
                }
                Ok(FaultDecision::None) => {
                    // Script says no fault - return 200 OK
                    let mut headers = vec![
                        ("x-rift-imposter".to_string(), "true".to_string()),
                        ("x-rift-script".to_string(), engine.clone()),
                    ];
                    if let Some(trace) = trace_header {
                        headers.push(("x-rift-script-trace".to_string(), trace));
                    }
                    return Ok(build_response_with_headers(
                        StatusCode::OK,
                        headers,
                        Bytes::new(),
                    ));
                }
                Ok(FaultDecision::Reset { .. }) => {
                    // v2 `reset()` result constructor (issue #357 Item 3): a connection reset,
                    // applied the same real way as `_rift.fault.tcp` / a top-level `fault` (see
                    // `handle_fault_response`) — attach the parsed TcpFaultKind as a response
                    // extension; the serve loop's FaultIo aborts the connection before this
                    // carrier response is ever sent, so its status/body are never observed.
                    let mut headers = vec![
                        ("x-rift-imposter".to_string(), "true".to_string()),
                        ("x-rift-script".to_string(), engine.clone()),
                        // The marker the other two carrier sites (`handle_fault_response` and the
                        // `_rift.fault.tcp` path) already stamp. Nothing in-tree reads it — new
                        // consumers use `tcp_fault_carrier`, which reads the extension — but a
                        // header-based consumer written before that seam existed saw two of the
                        // three carrier sites and silently missed this one (issue #965).
                        ("x-rift-fault".to_string(), "reset".to_string()),
                    ];
                    if let Some(trace) = trace_header {
                        headers.push(("x-rift-script-trace".to_string(), trace));
                    }
                    let mut response =
                        build_response_with_headers(StatusCode::BAD_GATEWAY, headers, Bytes::new());
                    response
                        .extensions_mut()
                        .insert(super::fault_io::TcpFaultKind::Reset);
                    return Ok(response);
                }
                Err(e) => {
                    log_upstream_failure("Rift script execution failed", &e);
                    // A deadline miss (issue #499) is a transient 504 + `x-rift-script-timeout`,
                    // distinct from the permanent 500 a broken script produces.
                    let timed_out = e
                        .downcast_ref::<crate::scripting::ScriptTimeoutError>()
                        .is_some();
                    let mut headers = vec![
                        ("x-rift-imposter".to_string(), "true".to_string()),
                        ("x-rift-script-error".to_string(), "true".to_string()),
                    ];
                    if timed_out {
                        headers.push((SCRIPT_TIMEOUT_HEADER.to_string(), "true".to_string()));
                    }
                    if let Some(trace) = trace_header {
                        headers.push(("x-rift-script-trace".to_string(), trace));
                    }
                    headers.push(("content-type".to_string(), "application/json".to_string()));
                    let (status, body) = if timed_out {
                        (
                            StatusCode::GATEWAY_TIMEOUT,
                            crate::response::error_body_typed(
                                StatusCode::GATEWAY_TIMEOUT,
                                crate::response::ErrorKind::ScriptTimeout,
                                &format!("Script timeout: {e}"),
                            ),
                        )
                    } else {
                        (
                            StatusCode::INTERNAL_SERVER_ERROR,
                            crate::response::error_body_typed(
                                StatusCode::INTERNAL_SERVER_ERROR,
                                crate::response::ErrorKind::ScriptError,
                                &format!("Script error: {e}"),
                            ),
                        )
                    };
                    return Ok(build_response_with_headers(status, headers, body));
                }
            }
        }

        // Issue #703 fast path: a fully static `is` response was materialized at construction, so
        // serve it as a status copy + refcounted `HeaderMap`/`Bytes` clones — skipping the execute()
        // header/body clone, per-request header re-parsing, and all template/behavior/date scanning
        // below. `prepared` is `Some` only when nothing about the response depends on the request
        // (see `PreparedResponse::try_build`); request recording and the scenario FSM already ran
        // above, so nothing request-visible is skipped.
        //
        // A `defaultResponse` (issue #1369) completes whatever the response omits, and `prepared` is
        // built per stub without it: such a response is served from the slow path below. Without a
        // default, or with nothing to complete, the fast path is untouched.
        if let Some(StubResponse::Is {
            is,
            prepared: Some(prepared),
            ..
        }) = response
            && imposter
                .config
                .default_response
                .as_ref()
                .is_none_or(|default| !is.needs_default(default))
        {
            return Ok(prepared
                .serve_request(&method, &request_headers, || {
                    imposter.served_load_stamp(&stub_state, stub_index, &scenario_transitions)
                })
                .unwrap_or_else(|e| {
                    build_failure_response(&e, "stub response build failed (bad Last-Modified?)")
                }));
        }

        if let Some((
            mut status,
            mut headers,
            mut body,
            behaviors,
            rift_ext,
            mut response_mode,
            is_fault,
        )) = response.and_then(execute_stub_response_with_rift)
        {
            // A `statusCode` string (issue #1558): the behaviors substitute into it, and it is read
            // when the response is written.
            let mut status_text = match response {
                Some(StubResponse::Is { is, .. }) => is
                    .status_text
                    .as_deref()
                    .map(|text| Spliced::authored(text.to_string())),
                _ => None,
            };
            // Issue #1369: complete the authored response from `defaultResponse` before templating
            // and behaviors run, so a default body expands like a stub body.
            // `served_is` (issue #1685): a script-less `_rift`-only response is completed as the
            // `is: {}` it is served as.
            if let (Some(is), Some(default)) = (
                response.and_then(served_is),
                imposter.config.default_response.as_ref(),
            ) && is.needs_default(default)
            {
                // Mountebank merges the default's status after the behaviors, so a token in it is
                // never substituted (issue #1558).
                if is.omitted.status_code {
                    status_text = default
                        .status_text
                        .as_deref()
                        .map(|text| Spliced::supplied(text.to_string()));
                }
                complete_from_default(
                    is,
                    default,
                    &mut status,
                    &mut headers,
                    &mut body,
                    &mut response_mode,
                );
            }
            // Handle faults - simulate connection errors. A name Rift does not know is ignored, as
            // in Mountebank (issue #1556): the stub's answer is an empty response completed by
            // `defaultResponse`. No behavior or `_rift` runs on it, and `repeat` already counted.
            if is_fault {
                return Ok(handle_fault_response(&body).unwrap_or_else(|| {
                    ignored_fault_response(
                        imposter.config.default_response.as_ref(),
                        strict_behaviors_for(&imposter.config),
                    )
                }));
            }

            // Apply _rift.fault extensions (probabilistic faults)
            if let Some(rift) = rift_ext
                && let Some(ref fault_config) = rift.fault
                && let Some(response) =
                    apply_rift_fault(fault_config, &mut status, &mut body, imposter.bound_port())
                        .await
            {
                return Ok(response);
            }

            // Issue #375: strict mode makes a requested response behavior that fails serve a 500
            // (still carrying the #323 signal header) instead of the fallback body. Enabled
            // per-imposter (`strictBehaviors`) or process-wide (`RIFT_STRICT_BEHAVIORS`). Default
            // false preserves the lenient #269/#323 contract in the Err arms below.
            let strict_behaviors = strict_behaviors_for(&imposter.config);

            // Declarative response templating (issue #359): opt-in via `_rift.templated`. This
            // `{{ }}` render runs FIRST — on the *config-authored* body/headers — and BEFORE the
            // `${request.*}` reflection substitution below (issue #359 B1, security). Ordering is
            // load-bearing: because `${request.*}` injects reflected request data only *after* this
            // pass, any `{{ }}` that arrives inside reflected request data is never scanned or
            // evaluated here — it is served verbatim. Evaluating reflected `{{ }}` would be a
            // template-injection hole (an unauthenticated caller could reach `state.*`/force errors)
            // and would also break the module's "a literal `{{` is served verbatim" promise for
            // reflected text. Off by default so recorded fixtures with a literal `{{` are untouched.
            // Every pass below splices request text into the response, and each would otherwise
            // search the previous one's output — so text the engine inserted carries its byte
            // ranges (`Spliced`, issue #1203) and no later pass expands a token lying wholly inside
            // it. Built only when a pass can run: a response with no templating and no behaviors
            // never converts its headers.
            let templated = rift_ext.is_some_and(|r| r.templated);
            let reflects = has_template_variables(&body)
                || headers
                    .values()
                    .flatten()
                    .any(|v| has_template_variables(v));
            if templated || reflects || behaviors.is_some() {
                // Declarative response templating (issue #359): opt-in via `_rift.templated`. This
                // `{{ }}` render runs FIRST — on the *config-authored* body/headers — and BEFORE
                // the `${request.*}` reflection substitution below (issue #359 B1, security).
                // Because `${request.*}` injects reflected request data only *after* this pass, any
                // `{{ }}` that arrives inside reflected request data is never scanned or evaluated
                // here — it is served verbatim. Evaluating reflected `{{ }}` would be a
                // template-injection hole (an unauthenticated caller could reach
                // `state.*`/force errors). Off by default so recorded fixtures with a literal `{{`
                // are untouched.
                let (mut spliced_body, mut spliced_headers) = if templated {
                    let request_data = RequestData::new(
                        method_str,
                        path_str,
                        query_opt,
                        &request_headers,
                        body_string.as_deref(),
                    )
                    .with_route_pattern(stub_state.stub.route_pattern.as_deref());
                    // In debug mode (`RIFT_DEBUG`), a malformed/unknown/failed `{{ }}` token fails
                    // the request loudly instead of silently degrading to an empty string (issue
                    // #359 AC3).
                    let template_debug = crate::util::rift_debug_env();
                    // Offloaded when the store blocks (issue #971); inline on the in-memory
                    // default. `body`/`headers` move into the render and come back rendered.
                    match render_templated_response(
                        &imposter,
                        request_data,
                        scenario_flow_id.clone(),
                        std::mem::take(&mut body),
                        std::mem::take(&mut headers),
                        template_debug,
                        stub_ref(&imposter, stub_index, &stub_state.stub),
                    )
                    .await
                    {
                        Ok(TemplateRender::Rendered { body, headers }) => (body, headers),
                        Ok(TemplateRender::Failed(e)) => {
                            warn!("Response template rendering failed: {e}");
                            return Ok(template_error_response(&e));
                        }
                        // Not a template failure: the blocking task itself died, so this is the
                        // same backend-transport door the FSM transition and `_rift.stateOps` use.
                        // Answering `template_error_response` here would blame the config for an
                        // outage.
                        Err(e) => return Ok(backend_error_response(&e)),
                    }
                } else {
                    (
                        Spliced::authored(std::mem::take(&mut body)),
                        authored_headers(std::mem::take(&mut headers)),
                    )
                };

                // Expand `${request.*}` request templates (issue #269) BEFORE behaviors, so
                // `shellTransform`/`decorate` operate on the expanded body. Header values are
                // templated too (the static path's AC1 requirement). Serve-time date templates
                // ({{NOW}}/{{DAYS+N}}) are expanded later, at body finalization. Runs AFTER the
                // `{{ }}` pass above, and skips any `${...}` lying wholly inside what that pass
                // substituted (issue #1203): otherwise a client could send
                // `${request.headers.<name>}` and read a header an ingress added.
                let need_body = has_template_variables(spliced_body.as_str());
                let need_headers = spliced_headers
                    .values()
                    .flatten()
                    .any(|v| has_template_variables(v.as_str()));
                if need_body || need_headers {
                    let request_data = RequestData::new(
                        method_str,
                        path_str,
                        query_opt,
                        &request_headers,
                        body_string.as_deref(),
                    )
                    .with_route_pattern(stub_state.stub.route_pattern.as_deref());
                    if need_body {
                        process_template_spliced(&mut spliced_body, &request_data, |value| value);
                    }
                    let stub_ref = stub_ref(&imposter, stub_index, &stub_state.stub);
                    for values in spliced_headers.values_mut() {
                        for v in values.iter_mut() {
                            if has_template_variables(v.as_str()) {
                                // Issue #1067: `request.query` is percent-decoded and
                                // `request.body` is the raw body, so a client can substitute a
                                // byte a header value cannot carry — without repair it reaches
                                // `Builder::header` and 500s a stub the author cannot fix.
                                // Only the substituted text is repaired; a control character the
                                // author typed into the header itself is left to fail loudly.
                                process_template_spliced(v, &request_data, |substituted| {
                                    sanitize_header_value(&substituted, stub_ref)
                                });
                            }
                        }
                    }
                }

                // Apply behaviors if present. Issue #479: `behaviors` is the precomputed
                // `Option<Arc<BehaviorProgram>>` (parsed once at stub construction, see
                // `StubResponse::new_is`).
                if let Some(ref parsed_behaviors) = behaviors {
                    let run = BehaviorRun {
                        behaviors: parsed_behaviors,
                        method: &method,
                        uri: &uri,
                        request_headers: &request_headers,
                        request_body: body_string.as_deref(),
                        request_body_undefined: body_undefined,
                        client_addr: Some(client_addr),
                        script_scope: script_scope.clone(),
                        script_files: imposter.script_file_access(),
                        stub: stub_ref(&imposter, stub_index, &stub_state.stub),
                        csv_cache: csv_cache(),
                        body_guard: &imposter.body_guard,
                        script_timeout,
                        strict: strict_behaviors,
                        default_response: imposter.config.default_response.as_ref(),
                    };
                    // The body as written, which a shellTransform reads as `MB_RESPONSE.body`
                    // while the body is still its rendering (issue #1639). A body the default
                    // supplied is text, as before: Mountebank merges the default after behaviors.
                    let typed_body = match response {
                        Some(StubResponse::Is { is, .. }) => {
                            ServedParts::typed_body_of(is.body.as_ref(), &response_mode)
                        }
                        _ => None,
                    };
                    match run
                        .apply(ServedParts {
                            status,
                            status_text: status_text.take(),
                            headers: spliced_headers,
                            body: spliced_body,
                            typed_body,
                        })
                        .await
                    {
                        BehaviorOutcome::Applied { parts, .. } => {
                            status = parts.status;
                            status_text = parts.status_text;
                            spliced_headers = parts.headers;
                            spliced_body = parts.body;
                        }
                        BehaviorOutcome::StrictFailure(response) => return Ok(response),
                    }
                }
                body = spliced_body.into_text();
                headers = plain_headers(spliced_headers);
            }
            // Read the status as Mountebank writes it (issue #1558): a falsy one takes the
            // default's, and one Node refuses answers 500.
            let status = match resolve_status(
                status,
                status_text.as_ref().map(Spliced::as_str),
                imposter.config.default_response.as_ref(),
            ) {
                Ok(status) => status,
                Err(value) => return Ok(invalid_status_response(&value)),
            };
            // `_rift.conditional` (issue #1280), decided on the status behaviors left. Its
            // validators replace any the response declares.
            let conditional =
                ConditionalSpec::from_config(rift_ext.and_then(|r| r.conditional.as_ref()))
                    .filter(|_| conditional::applies(&method, status.as_u16()));
            let mut response = Response::builder().status(status);

            // One header line per value (issue #238 multi-value headers, e.g. multiple Set-Cookie).
            for (k, values) in &headers {
                if conditional.is_some() && conditional::is_validator(k) {
                    continue;
                }
                for v in values {
                    response = response.header(k, v);
                }
            }

            response = response.header("x-rift-imposter", "true");

            let body_bytes = match response_mode {
                ResponseMode::Binary => match decode_binary_body(body, strict_behaviors) {
                    Ok(BinaryBody::Decoded(bytes)) => bytes,
                    // Signal a failed decode so serving the raw (still-encoded) body isn't silent (#323).
                    Ok(BinaryBody::RawFallback(bytes)) => {
                        response = response.header("x-rift-binary-error", "true");
                        bytes
                    }
                    Err(strict_failure) => return Ok(*strict_failure),
                },
                // Expand serve-time date templates ({{DAYS+N}}/{{MONTHS+N}}/{{NOW}}, issue #195).
                ResponseMode::Text => Bytes::from(crate::extensions::apply_date_templates(&body)),
            };

            // Declarative post-response state writes (issue #969): opt-in via `_rift.stateOps`.
            // Deliberately LAST — after templating and behaviors have rendered `body`/`headers`
            // and after `body_bytes` above was finalized from that rendered `body` — so a body
            // reading `{{ state.<key> }}` in the *same* response sees the value from *before*
            // this request's ops (the semantics `state_ops`'s module doc pins: "show the count,
            // then bump it"). Ops run sequentially, in array order. `run_flow_blocking` offloads
            // the store calls onto a blocking backend exactly like the FSM transition above
            // (issue #475's blocking-store rule): inline on the in-memory store, off the tokio worker on a
            // backend that actually blocks.
            if let Some(ops) = rift_ext.map(|r| &r.state_ops).filter(|ops| !ops.is_empty()) {
                let request_data = RequestData::new(
                    method_str,
                    path_str,
                    query_opt,
                    &request_headers,
                    body_string.as_deref(),
                )
                .with_route_pattern(stub_state.stub.route_pattern.as_deref());
                let ops = ops.clone();
                let flow_id = scenario_flow_id.clone();
                let state_ops_debug = crate::util::rift_debug_env();
                let outcome = imposter
                    .run_flow_blocking(move |imp| {
                        crate::extensions::execute_state_ops(
                            &ops,
                            &super::core::ScenarioStampingStore::new(imp),
                            &flow_id,
                            &request_data,
                            state_ops_debug,
                        )
                        .map_err(|e| anyhow::anyhow!(e))
                    })
                    .await;
                if let Err(e) = outcome {
                    // Two distinct failure sources reach here, and only one of them is a
                    // stateOps failure: in debug mode `execute_state_ops` itself returns the
                    // `Err` it built (`"stateOps: <op> failed: ..."`, see its doc) — surface that
                    // the same way a failed `{{ }}` render does (#359). Outside debug mode it
                    // never returns `Err` (warn + continue is the policy), so any failure reaching
                    // here is instead a `run_flow_blocking` *transport* failure (e.g. a panicked
                    // blocking task) — the same door the FSM transition above uses, not the
                    // stateOps one, since it has nothing to do with a stateOps op failing.
                    let message = e.to_string();
                    return Ok(if state_ops_debug && message.starts_with("stateOps:") {
                        state_ops_error_response(&message)
                    } else {
                        backend_error_response(&e)
                    });
                }
            }

            // After the fault and `stateOps`, so a fault still wins and a 304 still writes state;
            // the ETag is over the final bytes, after templating, behaviors and date tokens.
            if let Some(spec) = &conditional {
                let etag = spec
                    .wants_etag()
                    .then(|| conditional::etag_for(&body_bytes));
                let validators = spec.validators(
                    etag,
                    imposter.served_load_stamp(&stub_state, stub_index, &scenario_transitions),
                );
                if validators.not_modified(&request_headers) {
                    let kept = headers
                        .iter()
                        .filter(|(name, _)| conditional::kept_on_304(name))
                        .flat_map(|(name, values)| {
                            values.iter().map(move |v| (name.as_str(), v.as_str()))
                        });
                    return Ok(validators.not_modified_response(kept).unwrap_or_else(|e| {
                        build_failure_response(&e, "304 response build failed (bad stub header?)")
                    }));
                }
                for (name, value) in validators.headers() {
                    response = response.header(name, value);
                }
            }

            return Ok(response.body(Full::new(body_bytes)).unwrap_or_else(|e| {
                match invalid_header_name(headers.keys().map(String::as_str)) {
                    Some(name) => invalid_header_name_response(name),
                    None => {
                        build_failure_response(&e, "stub response build failed (bad stub header?)")
                    }
                }
            }));
        }
    }

    // No matching rule. Issue #196: if `defaultForward` is set, transparently forward the
    // request to the configured upstream before falling back to a static default. A
    // defaultForward-only imposter runs in ProxyTransparent mode, so the upstream response is
    // never cached/replayed. (The request still appears in the audit log when `recordRequests`
    // is enabled — that is the separate, opt-in recording feature.)
    if let Some(upstream) = &imposter.config.default_forward {
        // Explicitly transparent: an omitted mode is proxyOnce (issue #1314), and a stub's
        // recording mode must not reach the fallback.
        let proxy_config = ProxyResponse {
            to: upstream.clone(),
            mode: "proxyTransparent".to_string(),
            ..Default::default()
        };
        return match imposter
            .handle_proxy_request(
                &proxy_config,
                UpstreamTarget::Base,
                method_str,
                &uri,
                &request_headers,
                proxy_body(wire_bytes.as_ref(), body_string.as_deref()),
                None,
                None,
                client_addr,
            )
            .await
        {
            // No stub response, so no behaviors: a strict failure cannot happen here.
            Ok(ProxyOutcome::StrictFailure(response)) => Ok(response),
            Ok(ProxyOutcome::Served(ProxiedResponse {
                status,
                headers: response_headers,
                body,
                ..
            })) => {
                let mut response = Response::builder().status(status);
                for (k, v) in &response_headers {
                    if !crate::util::is_hop_by_hop_header(k) {
                        response = response.header(k, v);
                    }
                }
                response = response.header("x-rift-imposter", "true");
                response = response.header("x-rift-default-forward", "true");
                Ok(response
                    .body(Full::new(Bytes::from(body)))
                    .unwrap_or_else(|e| {
                        build_failure_response(
                            &e,
                            "defaultForward response build failed (bad upstream header?)",
                        )
                    }))
            }
            Err(e) => Ok(proxy_leg_error_response(
                &e,
                &format!("defaultForward proxy to {upstream} failed"),
                "x-rift-default-forward-error",
                "defaultForward upstream error",
            )),
        };
    }

    // No matching rule — return the configured `defaultResponse`, else fall through to a 200
    // with an empty body below (Mountebank parity — Rift never returns 404 for an unmatched
    // request). A `defaultForward` upstream, if configured, was already handled above.
    if let Some(ref default) = imposter.config.default_response {
        return Ok(build_default_completed(
            default,
            strict_behaviors_for(&imposter.config),
            Some("x-rift-default-response"),
        ));
    }

    // No match and no default - Mountebank returns 200 with empty body
    Ok(build_response_with_headers(
        StatusCode::OK,
        [("x-rift-imposter", "true"), ("x-rift-no-match", "true")],
        Bytes::new(),
    ))
}

/// Handle debug mode request
#[allow(clippy::too_many_arguments)]
fn handle_debug_request(
    imposter: &Arc<Imposter>,
    method: &str,
    path: &str,
    query_str: &str,
    // Private helper, single call site (the debug-mode `spawn_blocking` job below), which always
    // passes the request-scoped `FastMap` header view (issue #704, #1025).
    headers_clone: &crate::util::OrderedMap<String, Vec<String>>,
    body_string: &Option<String>,
    client_addr: SocketAddr,
) -> Result<Response<Full<Bytes>>, Infallible> {
    debug!("Debug mode enabled for request {} {}", method, path);

    // Build debug request info. `DebugRequest.headers` is single-valued (issue #1025): a
    // repeated header shows its first value, matching the other debug/scripting boundaries.
    let debug_request = DebugRequest {
        method: method.to_string(),
        path: path.to_string(),
        query: if query_str.is_empty() {
            None
        } else {
            Some(query_str.to_string())
        },
        headers: headers_clone
            .iter()
            .filter(|(k, _)| !k.eq_ignore_ascii_case("x-rift-debug"))
            .filter_map(|(k, v)| v.first().map(|first| (k.clone(), first.clone())))
            .collect(),
        body: body_string.clone(),
    };

    // Get imposter info
    let debug_imposter = imposter.get_debug_imposter_info();

    // Find matching stub for debug info (with client address)
    let request_from = client_addr.to_string();
    let client_ip = client_addr.ip().to_string();
    let query_opt = if query_str.is_empty() {
        None
    } else {
        Some(query_str)
    };

    let matched = match imposter.find_matching_stub_with_client(
        method,
        path,
        headers_clone,
        query_opt,
        body_string.as_deref(),
        Some(&request_from),
        Some(&client_ip),
    ) {
        Ok(matched) => matched,
        Err(e) => return Ok(matcher_error_response(&e)),
    };
    let match_result = if let Some((stub_state, stub_index)) = matched {
        // Match found
        let response_preview = match imposter.get_response_preview(&stub_state) {
            Ok(preview) => preview,
            Err(e) => return Ok(backend_error_response(&e)),
        };
        DebugMatchResult {
            matched: true,
            stub_index: Some(stub_index),
            stub_id: stub_state.stub.id.clone(),
            predicates: Some(stub_state.stub.predicates.clone()),
            response_preview: Some(response_preview),
            all_stubs: None,
            reason: None,
        }
    } else {
        // No match - return all stubs for inspection
        let all_stubs = imposter.get_all_stubs_info();
        let reason = if all_stubs.is_empty() {
            "No stubs configured for this imposter".to_string()
        } else {
            "No stub predicates matched the request".to_string()
        };
        DebugMatchResult {
            matched: false,
            stub_index: None,
            stub_id: None,
            predicates: None,
            response_preview: None,
            all_stubs: Some(all_stubs),
            reason: Some(reason),
        }
    };

    let debug_response = DebugResponse {
        debug: true,
        request: debug_request,
        imposter: debug_imposter,
        match_result,
    };

    let (status, json_body) = debug_serialize_or_500(&debug_response);

    Ok(build_response_with_headers(
        status,
        [
            ("Content-Type", "application/json"),
            ("X-Rift-Debug-Response", "true"),
        ],
        json_body,
    ))
}

/// Serialize a debug payload into the `(status, body)` the debug endpoint should answer with.
/// Split out from `handle_debug_request` so the serde error path — unreachable with the real
/// `DebugResponse` — can be pinned by a test (issue #611).
fn debug_serialize_or_500<T: serde::Serialize>(payload: &T) -> (StatusCode, String) {
    match serde_json::to_string_pretty(payload) {
        Ok(body) => (StatusCode::OK, body),
        Err(e) => {
            tracing::error!(error = %e, "failed to serialize debug response");
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                crate::response::error_body(
                    StatusCode::INTERNAL_SERVER_ERROR,
                    "Failed to serialize debug response",
                ),
            )
        }
    }
}

/// Handle a top-level `fault` response type. A Mountebank `fault` is a transport-level event, so
/// it reuses the real `_rift.fault.tcp` path (issue #309): the parsed [`TcpFaultKind`] is attached
/// as a response extension that the serve loop's `FaultIo` applies as a real reset/close/etc.,
/// instead of framing a clean HTTP 502 (which a migrated Mountebank config would not expect).
///
/// `None` for a name Rift does not know: that is no fault at all, and the caller serves
/// [`ignored_fault_response`] (issue #1556).
fn handle_fault_response(fault_type: &str) -> Option<Response<Full<Bytes>>> {
    let kind = super::fault_io::TcpFaultKind::parse(fault_type)?;
    // Carrier response: `FaultIo` aborts the connection before this is sent, so the status/body
    // here are never observed by the client (mirrors the `_rift.fault.tcp` path).
    let mut response = build_response_with_headers(
        StatusCode::BAD_GATEWAY,
        [("x-rift-fault", fault_type)],
        Bytes::new(),
    );
    response.extensions_mut().insert(kind);
    Some(response)
}

/// The answer to a `fault` whose name Rift does not know (issue #1556). Mountebank logs
/// `Unexpected fault type`, writes nothing (`helpers.js:104-106`) and then serves the
/// post-processed response, which `postProcess` fills from `defaultResponse`
/// (`baseHttpServer.js:21-29`). So it is an empty response completed by `default`, else `200` with
/// an empty body. A stub matched, so it is no default-response answer and carries no
/// `x-rift-default-response`; no fault fired, so it carries no `x-rift-fault` either.
fn ignored_fault_response(default: Option<&IsResponse>, strict: bool) -> Response<Full<Bytes>> {
    match default {
        Some(default) => build_default_completed(default, strict, None),
        None => {
            build_response_with_headers(StatusCode::OK, [("x-rift-imposter", "true")], Bytes::new())
        }
    }
}

/// An empty response completed by `default` — the answer to an unmatched request, and to an
/// ignored `fault` (issue #1556). It is the same completion a stub's `is` gets, applied to a
/// response that writes nothing, so the paths cannot drift (issue #1369). `marker`, when set, is a
/// header stamped `true` on the response and on a strict decode failure, so a client or operator can
/// tell which door answered.
fn build_default_completed(
    default: &IsResponse,
    strict: bool,
    marker: Option<&'static str>,
) -> Response<Full<Bytes>> {
    let empty = IsResponse::empty();
    let default = empty.completed_by(default);
    let body_str = body_text(default.body.as_ref());

    // The same decode — and so the same contract — as a stub's `is` body (issue #1151). This site
    // used to re-implement it inline, without the #323 header and without #375's strict path, so a
    // bad binary default body was served as its own raw text with only a log line.
    let mut binary_decode_failed = false;
    let body_bytes = match default.mode {
        ResponseMode::Binary => match decode_binary_body(body_str, strict) {
            Ok(BinaryBody::Decoded(bytes)) => bytes,
            Ok(BinaryBody::RawFallback(bytes)) => {
                binary_decode_failed = true;
                bytes
            }
            // The shared helper builds the same 500 for every door; the marker says which.
            Err(strict_failure) => {
                let mut strict_failure = *strict_failure;
                if let Some(marker) = marker {
                    strict_failure
                        .headers_mut()
                        .insert(marker, hyper::header::HeaderValue::from_static("true"));
                }
                return strict_failure;
            }
        },
        ResponseMode::Text => Bytes::from(crate::extensions::apply_date_templates(&body_str)),
    };

    // A string status is read as Mountebank writes it (issue #1558); a default's is never
    // substituted, so a token in it answers 500.
    let status = match resolve_status(default.status_code, default.status_text.as_deref(), None) {
        Ok(status) => status,
        Err(value) => {
            let mut refused = invalid_status_response(&value);
            if let Some(marker) = marker {
                refused
                    .headers_mut()
                    .insert(marker, hyper::header::HeaderValue::from_static("true"));
            }
            return refused;
        }
    };
    let mut response = Response::builder().status(status);
    if binary_decode_failed {
        response = response.header("x-rift-binary-error", "true");
    }
    for (k, values) in &default.headers {
        for v in values {
            response = response.header(k, v);
        }
    }
    response = response.header("x-rift-imposter", "true");
    if let Some(marker) = marker {
        response = response.header(marker, "true");
    }
    response.body(Full::new(body_bytes)).unwrap_or_else(|e| {
        build_failure_response(&e, "defaultResponse build failed (bad default header?)")
    })
}

/// Apply Rift fault configuration (probabilistic faults)
/// `port` is the imposter's port, used as the `rule_id` metric label (issue #999): the imposter
/// path has no named rules, so the port is what identifies the source of an injected fault.
async fn apply_rift_fault(
    fault_config: &super::types::RiftFaultConfig,
    _status: &mut u16,
    _body: &mut String,
    port: u16,
) -> Option<Response<Full<Bytes>>> {
    let rule_id = port.to_string();
    // Every roll draws from the request's stream (issue #1755), so a seeded imposter replays; a
    // caller outside a request (unit tests) gets a stream of its own.
    let mut rng =
        crate::imposter::rng::current().unwrap_or_else(crate::imposter::rng::RequestRng::unseeded);
    let (apply_latency, latency_delay_ms) = {
        if let Some(ref latency) = fault_config.latency {
            if rng.random::<f64>() < latency.probability {
                let delay_ms = if let Some(fixed_ms) = latency.ms {
                    fixed_ms
                } else if latency.max_ms > latency.min_ms {
                    rng.random_range(latency.min_ms..=latency.max_ms)
                } else {
                    latency.min_ms
                };
                (true, delay_ms)
            } else {
                (false, 0)
            }
        } else {
            (false, 0)
        }
    };

    let apply_error = {
        if let Some(ref error) = fault_config.error {
            rng.random::<f64>() < error.probability
        } else {
            false
        }
    };

    // A `tcp` fault fires with its own probability (issue #531): the bare string form is always
    // 1.0; the object form carries a chosen probability. When the roll fails the fault is treated
    // as absent for this request, falling through to the `error` fault and normal response — the
    // same semantics `latency`/`error` already use.
    let apply_tcp = {
        fault_config
            .tcp
            .as_ref()
            .is_some_and(|tcp| rng.random::<f64>() < tcp.probability())
    };

    // Apply latency fault (this is async)
    if apply_latency && latency_delay_ms > 0 {
        debug!("Applying _rift.fault latency: {}ms", latency_delay_ms);
        // Counted here, not where the probability roll succeeded: a roll that passes with a zero
        // delay injects nothing, and `rift_faults_injected_total` promises faults injected.
        // One call — the helper counts the fault itself, so a second call would double it.
        crate::extensions::metrics::record_latency_injection(&rule_id, latency_delay_ms, "rift");
        tokio::time::sleep(Duration::from_millis(latency_delay_ms)).await;
    }

    // Check for TCP fault before the HTTP error fault. A `tcp` fault is a transport-level event:
    // the connection is reset before any HTTP response can be written, so it must win over an
    // `error` fault — otherwise a configured `tcp` is silently dropped whenever `error` also fires
    // (issue #271). Latency above still applies first, keeping delay-then-drop coherent.
    if apply_tcp && let Some(ref tcp_fault) = fault_config.tcp {
        if let Some(kind) = super::fault_io::TcpFaultKind::parse(tcp_fault.kind()) {
            debug!("Applying _rift.fault.tcp: {:?}", kind);
            if apply_error {
                debug!("_rift.fault.error preempted by tcp fault (connection reset)");
            }
            // Carrier response: the serve loop's `FaultIo` aborts the connection before this is
            // ever sent. The `TcpFaultKind` extension tells it which real transport fault to apply
            // (issue #239) — the status/body here are never observed by the client.
            let mut response = build_response_with_headers(
                StatusCode::BAD_GATEWAY,
                [("x-rift-fault", tcp_fault.kind())],
                Bytes::new(),
            );
            response.extensions_mut().insert(kind);
            // Only counted on the branch that actually resets the connection — an unparsable
            // kind falls through to the error fault below and must not count as a tcp fault.
            crate::extensions::metrics::record_fault_injection("tcp", &rule_id, "rift");
            return Some(response);
        }
        warn!("Unknown TCP fault type: {}", tcp_fault.kind());
    }

    // Apply error fault
    if apply_error && let Some(ref error) = fault_config.error {
        debug!("Applying _rift.fault error: status {}", error.status);

        let mut response = Response::builder().status(error.status);

        // Apply custom headers
        for (k, v) in &error.headers {
            response = response.header(k, v);
        }

        response = response.header("x-rift-imposter", "true");
        response = response.header("x-rift-fault", "error");

        crate::extensions::metrics::record_error_injection(&rule_id, error.status, "rift");

        let error_body = error.body.clone().unwrap_or_default();
        return Some(
            response
                .body(Full::new(Bytes::from(error_body)))
                .unwrap_or_else(|e| {
                    build_failure_response(
                        &e,
                        "error-fault response build failed (bad fault header?)",
                    )
                }),
        );
    }

    None
}

// Issue #500: `matcher_error_response` splits a matcher failure two ways — a predicate-`inject`
// error (`PredicateInjectionError`) is a Mountebank-shaped 500, while every other matcher error
// (e.g. a scenario-state backend failure) keeps the 5xx backend mapping. The end-to-end handler
// tests exercise the 400 branch over the wire; this pins the "other error → 5xx" branch directly,
// since it needs a non-predicate error that a listener test can't easily provoke.
#[cfg(all(test, feature = "javascript"))]
mod matcher_error_response_tests {
    use super::{inject_timeout_response, matcher_error_response};
    use hyper::StatusCode;

    // Issue #499: the shared builder for a timed-out response/predicate `inject` — a 504 with the
    // Mountebank error envelope (timeout-specific code) plus the inject-error + script-timeout
    // markers. The Boa `inject` timeout paths route through this; they are unit-tested here rather
    // than end-to-end because a real Boa busy-loop parks a shared-pool worker (see the note in
    // tests/handler_error_responses.rs).
    #[tokio::test]
    async fn inject_timeout_response_is_504_with_code_and_markers() {
        use http_body_util::BodyExt;
        let resp = inject_timeout_response(
            crate::response::ErrorKind::InjectionTimeout,
            "inject timed out after 1ms",
        );
        assert_eq!(resp.status(), StatusCode::GATEWAY_TIMEOUT);
        assert!(resp.headers().contains_key("x-rift-inject-error"));
        assert!(
            resp.headers().contains_key("x-rift-script-timeout"),
            "the timeout marker distinguishes a deadline miss from a broken inject"
        );
        // Issue #687: this door's 400 sibling (`matcher_error_response`) declares the envelope it
        // serves, so the 504 must too — the two are one contract, reached by one predicate failing
        // two different ways.
        assert_eq!(
            resp.headers()["content-type"],
            "application/json",
            "the inject-timeout 504 serves the JSON envelope, so it must declare it"
        );
        let bytes = resp.into_body().collect().await.expect("body").to_bytes();
        let body = String::from_utf8(bytes.to_vec()).expect("utf8");
        assert!(
            body.contains("\"code\":\"injection timeout\""),
            "body must carry the timeout-specific code, got: {body}"
        );
        // Issue #797 invariant 3: `type` mirrors the slug `code` on this door.
        assert!(
            body.contains("\"type\":\"injection timeout\""),
            "body must carry the matching type slug, got: {body}"
        );
    }

    // The predicate-side sibling of the door above. It has no end-to-end coverage (a real Boa
    // busy-loop parks a shared-pool worker), so its envelope is pinned here — otherwise
    // `ErrorKind::PredicateInjectionTimeout` would ship with no test at all.
    #[tokio::test]
    async fn predicate_inject_timeout_response_carries_matching_code_and_type() {
        use http_body_util::BodyExt;
        let resp = inject_timeout_response(
            crate::response::ErrorKind::PredicateInjectionTimeout,
            "predicate inject timed out after 1ms",
        );
        assert_eq!(resp.status(), StatusCode::GATEWAY_TIMEOUT);
        let bytes = resp.into_body().collect().await.expect("body").to_bytes();
        let body = String::from_utf8(bytes.to_vec()).expect("utf8");
        assert!(
            body.contains("\"code\":\"predicate injection timeout\""),
            "code must stay the 0.14.0 slug, got: {body}"
        );
        assert!(
            body.contains("\"type\":\"predicate injection timeout\""),
            "type must mirror it, got: {body}"
        );
    }

    #[test]
    fn predicate_inject_error_maps_to_500() {
        let err: anyhow::Error = crate::scripting::PredicateInjectionError(
            "bad predicate".to_string(),
            Some("bad".to_string()),
        )
        .into();
        let resp = matcher_error_response(&err);
        assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
        assert!(
            resp.headers().contains_key("x-rift-inject-error"),
            "a predicate-inject error must carry the inject-error marker"
        );
    }

    #[test]
    fn other_matcher_error_maps_to_5xx() {
        let err = anyhow::anyhow!("scenario-state backend read failed");
        let resp = matcher_error_response(&err);
        assert_eq!(
            resp.status(),
            StatusCode::INTERNAL_SERVER_ERROR,
            "a non-predicate matcher error keeps the 5xx backend mapping, not a 400"
        );
        assert!(
            !resp.headers().contains_key("x-rift-inject-error"),
            "a generic backend error is not an inject error"
        );
    }

    // Issue #499: a predicate-matching deadline is a 504 with the timeout marker, distinct from
    // the broken-predicate 400 above — so a client can tell a retry-worthy timeout apart.
    #[test]
    fn predicate_inject_timeout_maps_to_504() {
        let err: anyhow::Error = crate::scripting::ScriptTimeoutError {
            hook: "predicate inject",
            timeout_ms: 50,
        }
        .into();
        let resp = matcher_error_response(&err);
        assert_eq!(resp.status(), StatusCode::GATEWAY_TIMEOUT);
        assert!(
            resp.headers().contains_key("x-rift-script-timeout"),
            "a matching timeout must carry the script-timeout marker"
        );
        assert!(
            resp.headers().contains_key("x-rift-inject-error"),
            "a predicate-inject timeout keeps the inject-error marker"
        );
    }
}

#[cfg(test)]
mod template_error_tests {
    use super::template_error_response;
    use http_body_util::BodyExt;
    use hyper::StatusCode;

    // Issue #687: the template door fires only under `RIFT_DEBUG` (a process-global this binary's
    // parallel tests cannot toggle safely), so its contract is pinned here instead of end-to-end.
    #[tokio::test]
    async fn template_error_response_is_500_with_marker_and_json_envelope() {
        let resp = template_error_response("template error in `{{ nope }}`: unknown token");
        assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
        assert!(resp.headers().contains_key("x-rift-template-error"));
        assert_eq!(
            resp.headers()["content-type"],
            "application/json",
            "the template door serves the JSON envelope, so it must declare it"
        );
        let bytes = resp.into_body().collect().await.expect("body").to_bytes();
        let body = String::from_utf8(bytes.to_vec()).expect("utf8");
        let v: serde_json::Value = serde_json::from_str(&body).expect("body must be valid JSON");
        assert_eq!(v["errors"][0]["code"], "500", "envelope code is the status");
        assert!(
            v["errors"][0]["message"]
                .as_str()
                .is_some_and(|m| m.contains("template rendering failed")),
            "the 500 must name the render failure, got: {body}"
        );
    }
}

#[cfg(test)]
mod state_ops_error_tests {
    use super::state_ops_error_response;
    use http_body_util::BodyExt;
    use hyper::StatusCode;

    // Issue #969: like the template door (#687), the `_rift.stateOps` debug-mode 500 fires only
    // under `RIFT_DEBUG` — a process-global that `crate::util::rift_debug_env` additionally caches
    // in a `OnceLock` for the life of the process, so no later test in this binary can toggle it at
    // all, not merely race it. The contract is pinned here instead of end-to-end.
    #[tokio::test]
    async fn state_ops_error_response_is_500_with_marker_and_json_envelope() {
        let resp = state_ops_error_response("stateOps: set \"a\" failed: template error");
        assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
        assert!(resp.headers().contains_key("x-rift-state-ops-error"));
        assert_eq!(
            resp.headers()["content-type"],
            "application/json",
            "the stateOps error door serves the JSON envelope, so it must declare it"
        );
        let bytes = resp.into_body().collect().await.expect("body").to_bytes();
        let body = String::from_utf8(bytes.to_vec()).expect("utf8");
        let v: serde_json::Value = serde_json::from_str(&body).expect("body must be valid JSON");
        assert_eq!(v["errors"][0]["code"], "500", "envelope code is the status");
        assert!(
            v["errors"][0]["message"]
                .as_str()
                .is_some_and(|m| m.contains("set \"a\"")),
            "the 500 must name the failing op, got: {body}"
        );
    }
}

#[cfg(test)]
mod body_collect_tests {
    use super::super::body_limits::{BodyGuard, BodyLimits};
    use super::{BodyReadError, body_read_error_response, body_refused_response};
    use bytes::Bytes;
    use http_body_util::{BodyExt, Full};
    use hyper::StatusCode;
    use std::pin::Pin;
    use std::task::{Context, Poll};
    use tracing_test::traced_test;

    // A body that fails mid-read — the shape of a connection reset or a truncated chunked stream,
    // distinct from a body that merely exceeds the size cap.
    struct FailingBody;
    impl hyper::body::Body for FailingBody {
        type Data = Bytes;
        type Error = std::io::Error;
        fn poll_frame(
            self: Pin<&mut Self>,
            _: &mut Context<'_>,
        ) -> Poll<Option<Result<hyper::body::Frame<Self::Data>, Self::Error>>> {
            Poll::Ready(Some(Err(std::io::Error::new(
                std::io::ErrorKind::ConnectionReset,
                "connection reset by peer",
            ))))
        }
    }

    fn guard() -> BodyGuard {
        BodyGuard::new(BodyLimits::new(4096, None).expect("valid limits"))
    }

    #[tokio::test]
    async fn oversize_is_flagged_too_large_not_read() {
        let body = Full::new(Bytes::from(vec![b'x'; 4097]));
        let err = guard().collect(body).await.expect_err("over limit");
        assert!(
            matches!(err, BodyReadError::TooLarge { limit: 4096 }),
            "a size-cap hit must be TooLarge, not a Read"
        );
    }

    // Issue #694: a transport failure must be classified Read — not silently folded into the 413
    // cap door — and the boxed cause preserved (not stringified) so the log can name it.
    #[tokio::test]
    async fn transport_failure_is_flagged_read_with_cause_preserved() {
        let err = guard()
            .collect(FailingBody)
            .await
            .expect_err("transport failure");
        match err {
            BodyReadError::Read(e) => assert!(
                e.to_string().contains("connection reset"),
                "the underlying cause must survive to the sink, got: {e}"
            ),
            other => panic!("a transport failure is not a limit refusal: {other:?}"),
        }
    }

    // Issue #1439: the ceiling is a 413 and the exhausted budget a 503 with `Retry-After`; both
    // close the connection, since the client may still be writing a body nobody will read.
    #[tokio::test]
    async fn the_limit_doors_are_413_and_503_and_close_the_connection() {
        let too_large = body_refused_response(&BodyReadError::TooLarge { limit: 4096 });
        assert_eq!(too_large.status(), StatusCode::PAYLOAD_TOO_LARGE);
        assert_eq!(too_large.headers()["connection"], "close");
        assert!(!too_large.headers().contains_key("retry-after"));
        // Issue #1460: both ask the listener to drain the unread body before closing.
        assert!(
            too_large
                .extensions()
                .get::<super::super::fault_io::LingerOnClose>()
                .is_some()
        );

        let exhausted = body_refused_response(&BodyReadError::BudgetExhausted);
        assert_eq!(exhausted.status(), StatusCode::SERVICE_UNAVAILABLE);
        assert_eq!(exhausted.headers()["connection"], "close");
        assert_eq!(exhausted.headers()["retry-after"], "1");
        assert!(
            exhausted
                .extensions()
                .get::<super::super::fault_io::LingerOnClose>()
                .is_some()
        );
        let body = exhausted
            .into_body()
            .collect()
            .await
            .expect("body")
            .to_bytes();
        let json: serde_json::Value = serde_json::from_slice(&body).expect("json envelope");
        assert_eq!(json["errors"][0]["code"], "503", "{json}");
        assert_eq!(json["errors"][0]["type"], "unavailable", "{json}");
    }

    #[traced_test]
    #[tokio::test]
    async fn read_error_door_is_400_envelope_and_logs_the_cause() {
        let e = std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "truncated chunked body");
        let resp = body_read_error_response(&e);
        assert_eq!(
            resp.status(),
            StatusCode::BAD_REQUEST,
            "a read failure is the client's 400, not the 413 cap door nor a 500"
        );
        assert_eq!(resp.headers()["content-type"], "application/json");
        assert!(resp.headers().contains_key("x-rift-imposter"));
        let bytes = resp.into_body().collect().await.expect("body").to_bytes();
        let v: serde_json::Value = serde_json::from_slice(&bytes).expect("valid JSON envelope");
        assert_eq!(v["errors"][0]["code"], "400", "envelope code is the status");
        assert!(
            v["errors"][0]["message"]
                .as_str()
                .is_some_and(|m| m.contains("Failed to read request body")),
            "got: {v}"
        );
        assert!(
            logs_contain("truncated chunked body"),
            "the previously-silent read failure must now be logged with its cause"
        );
    }
}

#[cfg(test)]
mod plaintext_door_tests {
    use super::{
        SCRIPT_TIMEOUT_HEADER, build_failure_response, debug_matching_error_response,
        debug_matching_timeout_response,
    };
    use http_body_util::BodyExt;
    use hyper::StatusCode;
    use tracing_test::traced_test;

    async fn envelope(
        resp: hyper::Response<http_body_util::Full<bytes::Bytes>>,
    ) -> serde_json::Value {
        let bytes = resp.into_body().collect().await.expect("body").to_bytes();
        serde_json::from_slice(&bytes).expect("body must be the canonical JSON envelope")
    }

    // Issue #695: the debug endpoint's success path already answers JSON (`X-Rift-Debug-Response`),
    // so its error path must too — plain text was the same-endpoint gap #687 closed elsewhere.
    #[tokio::test]
    async fn debug_matching_error_door_is_500_envelope() {
        let resp = debug_matching_error_response();
        assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
        assert_eq!(resp.headers()["content-type"], "application/json");
        assert!(resp.headers().contains_key("x-rift-imposter"));
        let v = envelope(resp).await;
        assert_eq!(v["errors"][0]["code"], "500");
        assert!(
            v["errors"][0]["message"]
                .as_str()
                .is_some_and(|m| m.contains("Debug matching failed")),
            "got: {v}"
        );
    }

    // The timeout door is a miss of the same `_rift.scriptEngine.timeoutMs` budget every other
    // script deadline maps to 504 + the timeout marker (#499/#476) — not the 500 it used to answer.
    #[tokio::test]
    async fn debug_matching_timeout_door_is_504_with_timeout_marker() {
        let resp = debug_matching_timeout_response();
        assert_eq!(
            resp.status(),
            StatusCode::GATEWAY_TIMEOUT,
            "a debug-matching deadline miss is a 504, like every other script timeout"
        );
        assert!(
            resp.headers().contains_key(SCRIPT_TIMEOUT_HEADER),
            "the timeout marker distinguishes a deadline miss from a permanent failure"
        );
        assert_eq!(resp.headers()["content-type"], "application/json");
        assert!(resp.headers().contains_key("x-rift-imposter"));
        let v = envelope(resp).await;
        assert_eq!(
            v["errors"][0]["code"], "504",
            "envelope code tracks the status"
        );
        assert!(
            v["errors"][0]["message"]
                .as_str()
                .is_some_and(|m| m.contains("Debug matching timed out")),
            "got: {v}"
        );
    }

    // The terminal fallback shared by all seven response-build sites: it must answer the canonical
    // envelope (not a bare string) and still log the caller's context so the failing door is named.
    #[traced_test]
    #[tokio::test]
    async fn build_failure_response_is_500_envelope_and_logs_context() {
        let e = hyper::Response::builder()
            .header("x-bad", "line1\nline2")
            .body(())
            .expect_err("an invalid header value must be a build error");
        let resp = build_failure_response(&e, "stub response build failed (bad stub header?)");
        assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
        assert_eq!(resp.headers()["content-type"], "application/json");
        assert!(resp.headers().contains_key("x-rift-imposter"));
        let v = envelope(resp).await;
        assert_eq!(v["errors"][0]["code"], "500");
        assert!(
            v["errors"][0]["message"]
                .as_str()
                .is_some_and(|m| m.contains("Response build error")),
            "got: {v}"
        );
        assert!(
            logs_contain("stub response build failed"),
            "the failing door's context must still be logged"
        );
    }
}

#[cfg(test)]
mod debug_serialize_tests {
    use super::debug_serialize_or_500;
    use hyper::StatusCode;
    use serde::{Serialize, Serializer};

    /// A payload whose `Serialize` always fails — the only way to drive serde's error path, since
    /// the real `DebugResponse` is plain structs of strings and JSON values (issue #611, mirroring
    /// the #606 technique in `admin_api/types.rs`).
    struct Unserializable;
    impl Serialize for Unserializable {
        fn serialize<S: Serializer>(&self, _: S) -> Result<S::Ok, S::Error> {
            Err(serde::ser::Error::custom("nope"))
        }
    }

    // Issue #611: a serialize failure used to be answered as `200 OK` carrying an error string —
    // the #606 shape one endpoint over. It is a server fault and must be a 500.
    #[test]
    fn debug_serialize_failure_maps_to_500() {
        let (status, body) = debug_serialize_or_500(&Unserializable);
        assert_eq!(
            status,
            StatusCode::INTERNAL_SERVER_ERROR,
            "a serialize failure must be a 500, not a 200 carrying an error string"
        );
        // Issue #682: the body is the canonical envelope now, not a hand-built `{"error"}` literal.
        let v: serde_json::Value = serde_json::from_str(&body).expect("body must be valid JSON");
        assert_eq!(v["errors"][0]["code"], "500", "envelope code is the status");
    }

    #[test]
    fn debug_serialize_success_keeps_200_and_the_payload() {
        let (status, body) = debug_serialize_or_500(&serde_json::json!({"debug": true}));
        assert_eq!(status, StatusCode::OK);
        let parsed: serde_json::Value = serde_json::from_str(&body).expect("valid JSON");
        assert_eq!(parsed["debug"], serde_json::json!(true));
    }
}

#[cfg(test)]
mod fault_precedence_tests {
    use super::super::fault_io::{TcpFaultKind, tcp_fault_carrier};
    use super::super::types::{RiftErrorFault, RiftFaultConfig, RiftLatencyFault, RiftTcpFault};
    use super::{
        Bytes, Full, Response, StatusCode, apply_rift_fault, handle_fault_response,
        ignored_fault_response,
    };
    use std::time::Instant;

    // Issue #309: a top-level `fault` response must reset/close the connection (via the same
    // TcpFaultKind extension the serve loop's FaultIo reads for `_rift.fault.tcp`), not return a
    // framed HTTP 502. Before the fix `handle_fault_response` attached no extension.
    #[test]
    fn top_level_fault_carries_real_tcp_fault_extension() {
        let reset = handle_fault_response("CONNECTION_RESET_BY_PEER").expect("a known fault");
        assert_eq!(
            reset.extensions().get::<TcpFaultKind>().copied(),
            Some(TcpFaultKind::Reset),
            "CONNECTION_RESET_BY_PEER must carry a real TCP-reset fault, not a plain 502"
        );

        let random = handle_fault_response("RANDOM_DATA_THEN_CLOSE").expect("a known fault");
        assert_eq!(
            random.extensions().get::<TcpFaultKind>().copied(),
            Some(TcpFaultKind::RandomData),
            "RANDOM_DATA_THEN_CLOSE must carry a real random-data-then-close fault"
        );

        // The two remaining WireMock kinds also route to a real transport fault (unified on the
        // same parser as `_rift.fault.tcp`), not ignored as an unknown name.
        let empty = handle_fault_response("EMPTY_RESPONSE").expect("a known fault");
        assert_eq!(
            empty.extensions().get::<TcpFaultKind>().copied(),
            Some(TcpFaultKind::Empty)
        );
        let malformed = handle_fault_response("MALFORMED_RESPONSE_CHUNK").expect("a known fault");
        assert_eq!(
            malformed.extensions().get::<TcpFaultKind>().copied(),
            Some(TcpFaultKind::MalformedChunk)
        );

        // An unrecognized fault type is no transport fault: the caller ignores it (issue #1556).
        assert!(handle_fault_response("NOT_A_FAULT").is_none());
    }

    /// Issue #965, carrier site A. `x-rift-fault` echoes whatever the config author typed, which is
    /// why an embedder had to mirror the whole alias list to interpret it; the seam collapses every
    /// alias onto the one canonical name so that list can be deleted.
    #[test]
    fn carrier_seam_maps_a_top_level_fault_alias_to_one_canonical_name() {
        let alias = handle_fault_response("garbage").expect("a known fault");
        assert_eq!(
            alias.headers().get("x-rift-fault").unwrap(),
            "garbage",
            "the header still echoes the raw input — that is the thing the seam replaces"
        );
        assert_eq!(tcp_fault_carrier(&alias), Some("RANDOM_DATA_THEN_CLOSE"));

        let canonical = handle_fault_response("RANDOM_DATA_THEN_CLOSE").expect("a known fault");
        assert_eq!(
            tcp_fault_carrier(&canonical),
            Some("RANDOM_DATA_THEN_CLOSE")
        );
    }

    /// Issue #1556: an unknown fault type is ignored, as in Mountebank. Its answer is an empty
    /// response the client really receives — not a carrier, and with no `x-rift-fault`, since no
    /// fault fired.
    #[test]
    fn carrier_seam_rejects_an_unknown_top_level_fault() {
        let unknown = ignored_fault_response(None, false);
        assert_eq!(unknown.status(), StatusCode::OK);
        assert!(unknown.headers().get("x-rift-fault").is_none());
        assert_eq!(unknown.headers().get("x-rift-imposter").unwrap(), "true");
        assert_eq!(tcp_fault_carrier(&unknown), None);
    }

    /// Issue #1556: with a `defaultResponse`, the ignored fault is completed by it, and carries
    /// no default-response marker, since a stub matched.
    #[test]
    fn an_ignored_fault_is_completed_by_the_default_response() {
        let default: super::IsResponse = serde_json::from_value(serde_json::json!({
            "statusCode": 418, "headers": { "X-D": "1" }, "body": "dflt"
        }))
        .expect("is");
        let ignored = ignored_fault_response(Some(&default), false);
        assert_eq!(ignored.status().as_u16(), 418);
        assert_eq!(ignored.headers().get("x-d").unwrap(), "1");
        assert!(ignored.headers().get("x-rift-default-response").is_none());
        assert!(ignored.headers().get("x-rift-fault").is_none());
        assert_eq!(tcp_fault_carrier(&ignored), None);
    }

    /// Issue #965, carrier site B: the `_rift.fault.tcp` path.
    #[tokio::test]
    async fn carrier_seam_reports_a_rift_tcp_fault() {
        let config = RiftFaultConfig {
            latency: None,
            error: None,
            tcp: Some(RiftTcpFault::Kind("garbage".to_string())),
        };
        let response = apply(&config).await;
        assert_eq!(tcp_fault_carrier(&response), Some("RANDOM_DATA_THEN_CLOSE"));
    }

    /// The fail-open case the header cannot distinguish: `_rift.fault.error` sets
    /// `x-rift-fault: error` with no extension, and is a real response, not a carrier.
    #[tokio::test]
    async fn carrier_seam_ignores_an_error_fault() {
        let config = RiftFaultConfig {
            latency: None,
            error: Some(error_fault(503)),
            tcp: None,
        };
        let response = apply(&config).await;
        assert_eq!(response.headers().get("x-rift-fault").unwrap(), "error");
        assert_eq!(
            tcp_fault_carrier(&response),
            None,
            "an error fault is a framed response the client receives, never a TCP carrier"
        );
    }

    fn error_fault(status: u16) -> RiftErrorFault {
        RiftErrorFault {
            probability: 1.0,
            status,
            body: None,
            headers: Default::default(),
        }
    }

    fn latency_fault(ms: u64) -> RiftLatencyFault {
        RiftLatencyFault {
            probability: 1.0,
            min_ms: 0,
            max_ms: 0,
            ms: Some(ms),
        }
    }

    async fn apply(config: &RiftFaultConfig) -> Response<Full<Bytes>> {
        let mut status = 200;
        let mut body = String::new();
        apply_rift_fault(config, &mut status, &mut body, 0)
            .await
            .expect("a fault response")
    }

    /// A configured `tcp` fault must win over a certain `error` fault: the response is the TCP
    /// carrier (parsed `TcpFaultKind` in extensions), never the HTTP error status (issue #271).
    #[tokio::test]
    async fn tcp_takes_precedence_over_error() {
        let config = RiftFaultConfig {
            latency: Some(latency_fault(0)),
            error: Some(error_fault(503)),
            tcp: Some(RiftTcpFault::Kind("CONNECTION_RESET_BY_PEER".to_string())),
        };
        let response = apply(&config).await;

        assert_eq!(
            response.extensions().get::<TcpFaultKind>().copied(),
            Some(TcpFaultKind::Reset),
            "tcp carrier must drive the connection reset"
        );
        assert_ne!(
            response.status(),
            503,
            "error fault must not win over the tcp fault"
        );
        assert_eq!(
            response.headers().get("x-rift-fault").unwrap(),
            "CONNECTION_RESET_BY_PEER"
        );
    }

    /// With no `tcp` fault, a certain `error` fault still produces the HTTP error response.
    #[tokio::test]
    async fn error_fault_applies_when_no_tcp() {
        let config = RiftFaultConfig {
            latency: Some(latency_fault(0)),
            error: Some(error_fault(503)),
            tcp: None,
        };
        let response = apply(&config).await;

        assert_eq!(response.status(), 503);
        assert_eq!(response.headers().get("x-rift-fault").unwrap(), "error");
        assert!(response.extensions().get::<TcpFaultKind>().is_none());
    }

    /// An unparseable `tcp` string must not swallow a configured `error` fault: it warns and falls
    /// through to the HTTP error response (guards the path most adjacent to the issue #271 drop).
    #[tokio::test]
    async fn unparseable_tcp_falls_through_to_error() {
        let config = RiftFaultConfig {
            latency: None,
            error: Some(error_fault(503)),
            tcp: Some(RiftTcpFault::Kind("NONSENSE".to_string())),
        };
        let response = apply(&config).await;

        assert_eq!(response.status(), 503);
        assert_eq!(response.headers().get("x-rift-fault").unwrap(), "error");
        assert!(response.extensions().get::<TcpFaultKind>().is_none());
    }

    /// A `tcp` fault on its own still resets (regression guard).
    #[tokio::test]
    async fn tcp_fault_alone_resets() {
        let config = RiftFaultConfig {
            latency: None,
            error: None,
            tcp: Some(RiftTcpFault::Kind("CONNECTION_RESET_BY_PEER".to_string())),
        };
        let response = apply(&config).await;

        assert_eq!(
            response.extensions().get::<TcpFaultKind>().copied(),
            Some(TcpFaultKind::Reset)
        );
    }

    /// Latency is still applied before the tcp fault wins (delay-then-drop stays coherent).
    #[tokio::test]
    async fn latency_applies_before_tcp() {
        let config = RiftFaultConfig {
            latency: Some(latency_fault(60)),
            error: Some(error_fault(503)),
            tcp: Some(RiftTcpFault::Kind("CONNECTION_RESET_BY_PEER".to_string())),
        };
        let start = Instant::now();
        let response = apply(&config).await;

        assert!(
            start.elapsed().as_millis() >= 50,
            "latency must be applied before the tcp reset"
        );
        assert_eq!(
            response.extensions().get::<TcpFaultKind>().copied(),
            Some(TcpFaultKind::Reset)
        );
    }

    /// Issue #531: a `tcp` fault with `probability: 0.0` must never reset — with no other fault it
    /// falls through to the normal response (no fault response at all).
    #[tokio::test]
    async fn tcp_object_probability_zero_never_resets() {
        let config = RiftFaultConfig {
            latency: None,
            error: None,
            tcp: Some(RiftTcpFault::Probabilistic {
                probability: 0.0,
                kind: "CONNECTION_RESET_BY_PEER".to_string(),
            }),
        };
        let (mut status, mut body) = (200, String::new());
        for _ in 0..200 {
            let response = apply_rift_fault(&config, &mut status, &mut body, 0).await;
            assert!(
                response.is_none(),
                "probability 0.0 tcp fault must never fire"
            );
        }
    }

    /// A `probability: 0.0` tcp fault falls through to a certain `error` fault (treated as absent).
    #[tokio::test]
    async fn tcp_object_probability_zero_falls_through_to_error() {
        let config = RiftFaultConfig {
            latency: None,
            error: Some(error_fault(503)),
            tcp: Some(RiftTcpFault::Probabilistic {
                probability: 0.0,
                kind: "CONNECTION_RESET_BY_PEER".to_string(),
            }),
        };
        let response = apply(&config).await;
        assert_eq!(response.status(), 503);
        assert!(response.extensions().get::<TcpFaultKind>().is_none());
    }

    /// The object form with `probability: 1.0` behaves exactly like the bare string.
    #[tokio::test]
    async fn tcp_object_probability_one_matches_bare_string() {
        let config = RiftFaultConfig {
            latency: None,
            error: Some(error_fault(503)),
            tcp: Some(RiftTcpFault::Probabilistic {
                probability: 1.0,
                kind: "CONNECTION_RESET_BY_PEER".to_string(),
            }),
        };
        let response = apply(&config).await;
        assert_eq!(
            response.extensions().get::<TcpFaultKind>().copied(),
            Some(TcpFaultKind::Reset)
        );
        assert_ne!(response.status(), 503);
        assert_eq!(
            response.headers().get("x-rift-fault").unwrap(),
            "CONNECTION_RESET_BY_PEER"
        );
    }

    /// Statistical gate: a `probability: 0.3` tcp fault fires at roughly the configured rate.
    #[tokio::test]
    async fn tcp_object_fires_at_configured_probability() {
        let config = RiftFaultConfig {
            latency: None,
            error: None,
            tcp: Some(RiftTcpFault::Probabilistic {
                probability: 0.3,
                kind: "CONNECTION_RESET_BY_PEER".to_string(),
            }),
        };
        let iterations = 4000;
        let mut resets = 0;
        let (mut status, mut body) = (200, String::new());
        for _ in 0..iterations {
            if apply_rift_fault(&config, &mut status, &mut body, 0)
                .await
                .and_then(|r| r.extensions().get::<TcpFaultKind>().copied())
                .is_some()
            {
                resets += 1;
            }
        }
        let observed = f64::from(resets) / f64::from(iterations);
        assert!(
            (observed - 0.3).abs() < 0.05,
            "expected ~0.3 reset rate, got {observed}"
        );
    }
}

// Issue #679: an upstream failure logged only its outermost context, so a DNS failure, a cert
// rejection and a refused connection were the same opaque line — the cause was captured by
// `.with_context()` and then dropped by the `{}` format specifier. The 502 body had the same
// hole, plus the string-interpolated JSON of the #611 class.
#[cfg(test)]
mod upstream_error_tests {
    use super::{log_upstream_failure, proxy_leg_error_response, upstream_error_response};
    use http_body_util::BodyExt;
    use hyper::StatusCode;
    use tracing_test::traced_test;

    /// A three-level chain shaped like the real one from the issue: the outermost context is what
    /// the client may see, the root cause is the operator's alone.
    fn chained_error() -> anyhow::Error {
        anyhow::anyhow!("failed to lookup address information: Name does not resolve")
            .context("dns error")
            .context("Failed to send proxy request to https://upstream.internal/")
    }

    async fn body_of(response: hyper::Response<http_body_util::Full<bytes::Bytes>>) -> String {
        let bytes = response
            .into_body()
            .collect()
            .await
            .expect("collect")
            .to_bytes();
        String::from_utf8(bytes.to_vec()).expect("utf8")
    }

    /// A proxy-recording store that refused the claim: the request never reached the upstream,
    /// so the proxy leg must answer `503` through the #318 door rather than the `502` that blames
    /// an upstream nobody called. Mirrors what `handle_proxy_request` returns for
    /// `ProxyStoreError::Refused` — a `BackendUnavailable` under one `.context()`.
    fn refusal_error() -> anyhow::Error {
        anyhow::Error::new(crate::extensions::decorate::BackendUnavailable {
            feature: "proxyOnce",
            detail: "owner is isolated from the cluster".to_owned(),
        })
        .context("proxyOnce claim refused; request not forwarded")
    }

    #[tokio::test]
    async fn proxy_leg_refusal_answers_503_naming_the_backend() {
        let response = proxy_leg_error_response(
            &refusal_error(),
            "Proxy request failed",
            "x-rift-proxy-error",
            "Proxy error",
        );
        assert_eq!(
            response.status(),
            StatusCode::SERVICE_UNAVAILABLE,
            "a refused claim is a backend outage, not an upstream failure"
        );
        let body = body_of(response).await;
        assert!(
            body.contains(crate::response::ErrorKind::BackendUnavailable.slug()),
            "the #318 envelope's type slug must survive: {body}"
        );
        assert!(
            body.contains("proxyOnce"),
            "the body must name which backend refused: {body}"
        );
    }

    #[tokio::test]
    async fn proxy_leg_upstream_failure_still_answers_502() {
        let response = proxy_leg_error_response(
            &chained_error(),
            "Proxy request failed",
            "x-rift-proxy-error",
            "Proxy error",
        );
        assert_eq!(
            response.status(),
            StatusCode::BAD_GATEWAY,
            "a genuine upstream failure keeps the 502 it has always had"
        );
    }

    /// The refusal must not be logged as an upstream failure: no upstream was called, so
    /// "Proxy request failed" in the log would send an operator to the wrong system.
    #[traced_test]
    #[tokio::test]
    async fn proxy_leg_refusal_is_not_logged_as_an_upstream_failure() {
        let _ = proxy_leg_error_response(
            &refusal_error(),
            "Proxy request failed",
            "x-rift-proxy-error",
            "Proxy error",
        );
        assert!(
            !logs_contain("Proxy request failed"),
            "a refused claim never reached the upstream; blaming it misdirects the operator"
        );
    }

    // Covers all four anyhow log sites at once: they share this function, so none of them can
    // regress to a bare `{}` without failing here.
    #[traced_test]
    #[tokio::test]
    async fn log_upstream_failure_names_the_whole_chain() {
        log_upstream_failure("Inject function failed", &chained_error());
        assert!(
            logs_contain("Inject function failed"),
            "context must survive"
        );
        assert!(
            logs_contain("dns error"),
            "the log must name the CAUSE — that is the whole point of #679"
        );
        assert!(
            logs_contain("Name does not resolve"),
            "the log must reach the ROOT cause, not stop one level down"
        );
    }

    #[traced_test]
    #[tokio::test]
    async fn upstream_error_response_logs_the_whole_chain() {
        let _ = upstream_error_response(
            &chained_error(),
            "Proxy request failed",
            "x-rift-proxy-error",
            "Proxy error",
        );
        assert!(logs_contain("Proxy request failed"));
        assert!(
            logs_contain("Name does not resolve"),
            "the 502 path must log the root cause, not just build the body"
        );
    }

    #[tokio::test]
    async fn upstream_error_body_is_the_canonical_envelope() {
        let response =
            upstream_error_response(&chained_error(), "l", "x-rift-proxy-error", "Proxy error");
        let body = body_of(response).await;
        let v: serde_json::Value = serde_json::from_str(&body).expect("body must be valid JSON");
        // The shape the standalone proxy door already emits via crate::response::error_response —
        // matching it is what makes 0.13.6's "all proxy modes emit one envelope" actually true.
        assert_eq!(v["errors"][0]["code"], "502", "envelope code is the status");
        assert!(
            v["errors"][0]["message"]
                .as_str()
                .expect("message is a string")
                .contains("Proxy error: Failed to send proxy request"),
            "the client keeps the prefix and the outermost context: {body}"
        );
        assert!(
            v.get("error").is_none(),
            "the legacy {{\"error\"}} shape must be gone"
        );
    }

    // The helper — not the caller — decides what the client sees, so this test is load-bearing:
    // it hands over a full chain and asserts the boundary holds.
    #[tokio::test]
    async fn upstream_error_body_withholds_the_cause_chain() {
        let response =
            upstream_error_response(&chained_error(), "l", "x-rift-proxy-error", "Proxy error");
        let body = body_of(response).await;
        assert!(
            !body.contains("dns error"),
            "cause chain must not cross to the client: {body}"
        );
        assert!(
            !body.contains("Name does not resolve"),
            "root cause must not cross to the client: {body}"
        );
    }

    #[tokio::test]
    async fn a_quote_in_the_upstream_error_still_yields_valid_json() {
        // Issue #611's class: interpolating into a JSON string literal breaks the instant the
        // message holds a quote. The quote has to ride on the error's *outermost* context — that is
        // what reaches the body — and a target URL is caller-supplied config, so this is not
        // hypothetical.
        let e = anyhow::anyhow!("root cause")
            .context(r#"Failed to send proxy request to https://x/?q="a""#);
        let response = upstream_error_response(&e, "l", "x-rift-proxy-error", "Proxy error");
        let body = body_of(response).await;
        let v: serde_json::Value = serde_json::from_str(&body)
            .unwrap_or_else(|err| panic!("a quote must not break the body: {err}\nbody: {body}"));
        assert!(
            v["errors"][0]["message"]
                .as_str()
                .expect("message is a string")
                .contains(r#"?q="a""#),
            "the quoted text must survive escaping, not be mangled: {body}"
        );
    }

    #[tokio::test]
    async fn upstream_error_keeps_status_and_rift_markers() {
        let response = upstream_error_response(
            &chained_error(),
            "l",
            "x-rift-default-forward-error",
            "defaultForward upstream error",
        );
        assert_eq!(response.status(), StatusCode::BAD_GATEWAY);
        assert_eq!(response.headers()["x-rift-imposter"], "true");
        assert_eq!(
            response.headers()["x-rift-default-forward-error"],
            "true",
            "the per-door marker must survive"
        );
        assert_eq!(response.headers()["content-type"], "application/json");
    }
}

// =========================================================================
// Issue #971: the `_rift.templated` render must offload to a blocking thread on a blocking
// FlowStore, exactly as the scenario FSM (#475) and `_rift.stateOps` (#969) already do.
// =========================================================================
#[cfg(test)]
mod templated_offload_tests {
    use super::{TemplateRender, render_templated_response, stub_ref};
    use crate::extensions::flow_state::{CasOutcome, FlowStore};
    use crate::extensions::template::RequestData;
    use crate::imposter::core::Imposter;
    use crate::imposter::headers::StubRef;
    use crate::imposter::types::ImposterConfig;
    use parking_lot::Mutex;
    use serde_json::{Value, json};

    /// Fixture identity for tests that only care about the render itself, not which stub
    /// triggered it.
    const FIXTURE_STUB: StubRef<'static> = StubRef {
        port: 0,
        index: 0,
        id: None,
    };
    use std::sync::Arc;
    use std::thread::ThreadId;

    /// An in-memory store that records which thread served `get`, and lies about `is_blocking`
    /// on demand. The recorded thread id is the whole point: it is the only direct evidence that
    /// the render did (or did not) leave the caller's thread.
    struct ThreadProbeStore {
        inner: crate::backends::inmemory::InMemoryFlowStore,
        blocking: bool,
        get_thread: Arc<Mutex<Option<ThreadId>>>,
        panic_on_get: bool,
    }

    impl ThreadProbeStore {
        fn new(blocking: bool) -> Self {
            Self {
                inner: crate::backends::inmemory::InMemoryFlowStore::new(300),
                blocking,
                get_thread: Arc::new(Mutex::new(None)),
                panic_on_get: false,
            }
        }

        fn panicking() -> Self {
            Self {
                panic_on_get: true,
                ..Self::new(true)
            }
        }
    }

    impl FlowStore for ThreadProbeStore {
        fn is_blocking(&self) -> bool {
            self.blocking
        }
        fn get(&self, flow_id: &str, key: &str) -> anyhow::Result<Option<Value>> {
            assert!(!self.panic_on_get, "induced blocking-store panic");
            *self.get_thread.lock() = Some(std::thread::current().id());
            self.inner.get(flow_id, key)
        }
        fn set(&self, flow_id: &str, key: &str, value: Value) -> anyhow::Result<()> {
            self.inner.set(flow_id, key, value)
        }
        fn exists(&self, flow_id: &str, key: &str) -> anyhow::Result<bool> {
            self.inner.exists(flow_id, key)
        }
        fn delete(&self, flow_id: &str, key: &str) -> anyhow::Result<()> {
            self.inner.delete(flow_id, key)
        }
        fn increment(&self, flow_id: &str, key: &str) -> anyhow::Result<i64> {
            self.inner.increment(flow_id, key)
        }
        fn set_ttl(&self, flow_id: &str, ttl_seconds: i64) -> anyhow::Result<()> {
            self.inner.set_ttl(flow_id, ttl_seconds)
        }
        fn compare_and_set(
            &self,
            flow_id: &str,
            key: &str,
            expected: Option<&Value>,
            new: Value,
        ) -> anyhow::Result<CasOutcome> {
            self.inner.compare_and_set(flow_id, key, expected, new)
        }
    }

    /// An imposter wired to `store`, with `state.hits` pre-seeded to `seed` on flow `flow-1`.
    fn imposter_with(store: Arc<ThreadProbeStore>, seed: Option<Value>) -> Arc<Imposter> {
        let cfg: ImposterConfig =
            serde_json::from_value(json!({ "port": 0, "protocol": "http", "stubs": [] }))
                .expect("valid imposter config");
        if let Some(seed) = seed {
            store.set("flow-1", "hits", seed).expect("seed");
        }
        let mut imp = Imposter::new(cfg).expect("test imposter");
        imp.flow_store = store;
        Arc::new(imp)
    }

    /// Issue #1075: the four call sites all build their `StubRef` through `stub_ref`, so this is
    /// the one place a transposed field could hide. Asserted against an imposter and stub built
    /// here, not against literals also written into the struct.
    #[test]
    fn stub_ref_reads_the_port_index_and_id_from_the_right_places() {
        let imp = imposter_with(Arc::new(ThreadProbeStore::new(false)), None);
        let stub: crate::imposter::types::Stub =
            serde_json::from_value(json!({ "id": "checkout", "responses": [{ "is": {} }] }))
                .expect("valid stub");

        let r = stub_ref(&imp, 7, &stub);

        assert_eq!(
            r.port,
            imp.bound_port(),
            "port is the imposter's bound port"
        );
        assert_eq!(r.index, 7, "index is the matched stub's index");
        assert_eq!(r.id, Some("checkout"), "id is the matched stub's id");

        let anonymous: crate::imposter::types::Stub =
            serde_json::from_value(json!({ "responses": [{ "is": {} }] })).expect("valid stub");
        assert_eq!(stub_ref(&imp, 0, &anonymous).id, None);
    }

    fn request() -> RequestData {
        RequestData::new("GET", "/x", None, &headers(&[]), None)
    }

    fn headers(pairs: &[(&str, &str)]) -> crate::imposter::Headers {
        pairs
            .iter()
            .map(|(k, v)| ((*k).to_string(), vec![(*v).to_string()]))
            .collect()
    }

    async fn render(
        imp: &Arc<Imposter>,
        body: &str,
        hdrs: crate::imposter::Headers,
        debug: bool,
    ) -> anyhow::Result<TemplateRender> {
        render_templated_response(
            imp,
            request(),
            "flow-1".to_string(),
            body.to_string(),
            hdrs,
            debug,
            FIXTURE_STUB,
        )
        .await
    }

    fn rendered(outcome: TemplateRender) -> (String, crate::imposter::Headers) {
        match outcome {
            TemplateRender::Rendered { body, headers } => {
                (body.into_text(), crate::behaviors::plain_headers(headers))
            }
            TemplateRender::Failed(e) => panic!("expected a rendered response, got Failed({e})"),
        }
    }

    /// Counts how many times the seam consulted `is_blocking()`. `run_flow_blocking` is the only
    /// thing on these paths that calls it, so a count of 0 proves the offload was skipped
    /// entirely rather than merely taken and returned quickly.
    struct OffloadCountingStore {
        inner: crate::backends::inmemory::InMemoryFlowStore,
        seam_entries: Arc<std::sync::atomic::AtomicUsize>,
    }

    impl OffloadCountingStore {
        fn new() -> Self {
            Self {
                inner: crate::backends::inmemory::InMemoryFlowStore::new(300),
                seam_entries: Arc::new(std::sync::atomic::AtomicUsize::new(0)),
            }
        }
    }

    impl FlowStore for OffloadCountingStore {
        fn is_blocking(&self) -> bool {
            self.seam_entries
                .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
            true
        }
        fn get(&self, flow_id: &str, key: &str) -> anyhow::Result<Option<Value>> {
            self.inner.get(flow_id, key)
        }
        fn set(&self, flow_id: &str, key: &str, value: Value) -> anyhow::Result<()> {
            self.inner.set(flow_id, key, value)
        }
        fn exists(&self, flow_id: &str, key: &str) -> anyhow::Result<bool> {
            self.inner.exists(flow_id, key)
        }
        fn delete(&self, flow_id: &str, key: &str) -> anyhow::Result<()> {
            self.inner.delete(flow_id, key)
        }
        fn increment(&self, flow_id: &str, key: &str) -> anyhow::Result<i64> {
            self.inner.increment(flow_id, key)
        }
        fn set_ttl(&self, flow_id: &str, ttl_seconds: i64) -> anyhow::Result<()> {
            self.inner.set_ttl(flow_id, ttl_seconds)
        }
        fn compare_and_set(
            &self,
            flow_id: &str,
            key: &str,
            expected: Option<&Value>,
            new: Value,
        ) -> anyhow::Result<crate::extensions::flow_state::CasOutcome> {
            self.inner.compare_and_set(flow_id, key, expected, new)
        }
    }

    fn counting_imposter(store: Arc<OffloadCountingStore>) -> Arc<Imposter> {
        let cfg: ImposterConfig =
            serde_json::from_value(json!({ "port": 0, "protocol": "http", "stubs": [] }))
                .expect("valid imposter config");
        let mut imp = Imposter::new(cfg).expect("test imposter");
        imp.flow_store = store;
        Arc::new(imp)
    }

    // Edge case 12: a template with no `state.` head must never reach the seam. Red before the
    // fix: 1 entry.
    #[tokio::test]
    async fn state_free_template_never_reaches_the_seam() {
        let store = Arc::new(OffloadCountingStore::new());
        let seam = store.seam_entries.clone();
        let imp = counting_imposter(store);

        let (body, hdrs) = rendered(
            render_templated_response(
                &imp,
                request(),
                "flow-1".to_string(),
                "path={{ request.path }}".to_string(),
                headers(&[("x-when", "{{ now }}")]),
                false,
                FIXTURE_STUB,
            )
            .await
            .expect("no transport failure"),
        );

        assert_eq!(body, "path=/x", "the render itself must still be correct");
        assert!(!hdrs["x-when"][0].is_empty(), "{{ now }} still rendered");
        assert_eq!(
            seam.load(std::sync::atomic::Ordering::SeqCst),
            0,
            "a store-free template must not consult the offload seam at all"
        );
    }

    // Edge case 14: only a HEADER reads state. Guards against a body-only pre-check, which would
    // put a blocking read back on the worker.
    #[tokio::test]
    async fn a_state_read_in_a_header_alone_still_offloads() {
        let store = Arc::new(OffloadCountingStore::new());
        let seam = store.seam_entries.clone();
        store.set("flow-1", "hits", json!(9)).expect("seed");
        let imp = counting_imposter(store);

        let (body, hdrs) = rendered(
            render_templated_response(
                &imp,
                request(),
                "flow-1".to_string(),
                "no state here".to_string(),
                headers(&[("x-hits", "{{ state.hits }}")]),
                false,
                FIXTURE_STUB,
            )
            .await
            .expect("no transport failure"),
        );

        assert_eq!(body, "no state here");
        assert_eq!(hdrs["x-hits"], vec!["9".to_string()]);
        assert!(
            seam.load(std::sync::atomic::Ordering::SeqCst) > 0,
            "a state read in a header value must still take the offload"
        );
    }

    // Edge case 13: the body-reads-state case still offloads (the #971 behaviour is preserved).
    #[tokio::test]
    async fn a_state_read_in_the_body_still_offloads() {
        let store = Arc::new(OffloadCountingStore::new());
        let seam = store.seam_entries.clone();
        store.set("flow-1", "hits", json!(4)).expect("seed");
        let imp = counting_imposter(store);

        let (body, _) = rendered(
            render_templated_response(
                &imp,
                request(),
                "flow-1".to_string(),
                "n={{ state.hits }}".to_string(),
                crate::imposter::Headers::new(),
                false,
                FIXTURE_STUB,
            )
            .await
            .expect("no transport failure"),
        );

        assert_eq!(body, "n=4");
        assert!(seam.load(std::sync::atomic::Ordering::SeqCst) > 0);
    }

    // Edge case 1 + 13: on a blocking backend the store read happens off the caller thread, and
    // the token still resolves to the stored value (the render is not skipped or emptied).
    #[tokio::test]
    async fn blocking_store_renders_state_off_the_caller_thread() {
        let store = Arc::new(ThreadProbeStore::new(true));
        let probe = store.get_thread.clone();
        let imp = imposter_with(store, Some(json!(7)));
        let caller = std::thread::current().id();

        let (body, _) = rendered(
            render(
                &imp,
                "hits={{ state.hits }}",
                crate::imposter::Headers::new(),
                false,
            )
            .await
            .expect("no transport failure"),
        );

        assert_eq!(body, "hits=7");
        assert_ne!(
            probe.lock().expect("the store must have been read"),
            caller,
            "a blocking backend must not read the store on the tokio worker"
        );
    }

    // Edge case 2: the #475 transparency guarantee — the default in-memory store keeps the render
    // inline, with no task hop.
    #[tokio::test]
    async fn non_blocking_store_renders_state_inline_on_the_caller_thread() {
        let store = Arc::new(ThreadProbeStore::new(false));
        let probe = store.get_thread.clone();
        let imp = imposter_with(store, Some(json!(7)));
        let caller = std::thread::current().id();

        let (body, _) = rendered(
            render(
                &imp,
                "hits={{ state.hits }}",
                crate::imposter::Headers::new(),
                false,
            )
            .await
            .expect("no transport failure"),
        );

        assert_eq!(body, "hits=7");
        assert_eq!(
            probe.lock().expect("the store must have been read"),
            caller,
            "the in-memory store must stay inline — no task hop"
        );
    }

    // Edge case 4 + 3: header values are rendered too, not just the body.
    #[tokio::test]
    async fn header_values_are_rendered() {
        let store = Arc::new(ThreadProbeStore::new(true));
        let imp = imposter_with(store, Some(json!(42)));

        let (body, hdrs) = rendered(
            render(
                &imp,
                "static",
                headers(&[("x-hits", "{{ state.hits }}")]),
                false,
            )
            .await
            .expect("no transport failure"),
        );

        assert_eq!(body, "static", "an untemplated body is served verbatim");
        assert_eq!(hdrs["x-hits"], vec!["42".to_string()]);
    }

    // Edge case 6: issue #359 B3 must not regress — a rendered header value carrying CR/LF is
    // stripped before it can inject a header line.
    #[tokio::test]
    async fn rendered_header_values_are_control_char_sanitized() {
        let store = Arc::new(ThreadProbeStore::new(true));
        let imp = imposter_with(store, Some(json!("a\r\nx-evil: injected")));

        let (_, hdrs) = rendered(
            render(&imp, "", headers(&[("x-echo", "{{ state.hits }}")]), false)
                .await
                .expect("no transport failure"),
        );

        let value = &hdrs["x-echo"][0];
        assert!(
            !value.contains('\r') && !value.contains('\n'),
            "control characters must be stripped, got: {value:?}"
        );
    }

    // Edge case 8: a bad `{{ }}` is a template failure, NOT a transport failure — it must not
    // reach the caller as an Err and be answered as a backend outage.
    #[tokio::test]
    async fn a_bad_token_is_a_template_failure_not_a_transport_failure() {
        let store = Arc::new(ThreadProbeStore::new(true));
        let imp = imposter_with(store, None);

        let outcome = render(
            &imp,
            "{{ nope.nothing }}",
            crate::imposter::Headers::new(),
            true,
        )
        .await
        .expect("a bad token must not surface as a transport failure");

        assert!(
            matches!(outcome, TemplateRender::Failed(_)),
            "expected TemplateRender::Failed for an unknown token"
        );
    }

    // Edge case 7: the failure is detected in a header value too, not only in the body.
    #[tokio::test]
    async fn a_bad_token_in_a_header_is_reported() {
        let store = Arc::new(ThreadProbeStore::new(true));
        let imp = imposter_with(store, None);

        let outcome = render(
            &imp,
            "fine",
            headers(&[("x-bad", "{{ nope.nothing }}")]),
            true,
        )
        .await
        .expect("a bad token must not surface as a transport failure");

        assert!(
            matches!(outcome, TemplateRender::Failed(_)),
            "a bad token in a header value must fail the render"
        );
    }

    // Edge case 9: a panicking blocking store IS a transport failure and must surface as Err, so
    // the caller can answer backend_error_response rather than template_error_response.
    #[tokio::test]
    async fn a_panicking_blocking_store_surfaces_as_a_transport_failure() {
        let imp = imposter_with(Arc::new(ThreadProbeStore::panicking()), None);

        let err = render(
            &imp,
            "{{ state.hits }}",
            crate::imposter::Headers::new(),
            false,
        )
        .await
        .expect_err("a panicked blocking task must surface as Err");

        assert!(
            err.to_string().contains("flow-store task panicked"),
            "got: {err}"
        );
    }

    // Edge case 10: the offload must be output-transparent — the same input renders byte-identically
    // whether or not the store claims to block. This is what makes the change a pure perf fix.
    #[tokio::test]
    async fn output_is_identical_on_both_paths() {
        let hdrs = headers(&[("x-hits", "{{ state.hits }}"), ("x-static", "plain")]);

        let blocking = imposter_with(Arc::new(ThreadProbeStore::new(true)), Some(json!(5)));
        let inline = imposter_with(Arc::new(ThreadProbeStore::new(false)), Some(json!(5)));

        let a = rendered(
            render(&blocking, "n={{ state.hits }}", hdrs.clone(), false)
                .await
                .expect("no transport failure"),
        );
        let b = rendered(
            render(&inline, "n={{ state.hits }}", hdrs, false)
                .await
                .expect("no transport failure"),
        );

        assert_eq!(a.0, "n=5");
        assert_eq!(a, b, "the blocking and inline paths must agree exactly");
    }

    // Edge case 11: nothing to render is not an error.
    #[tokio::test]
    async fn empty_body_and_no_headers_render_cleanly() {
        let imp = imposter_with(Arc::new(ThreadProbeStore::new(true)), None);

        let (body, hdrs) = rendered(
            render(&imp, "", crate::imposter::Headers::new(), false)
                .await
                .expect("no transport failure"),
        );

        assert_eq!(body, "");
        assert!(hdrs.is_empty());
    }

    // Edge case 12: `previousValue` is a stateOps-only binding (#969); outside a stateOps `set` it
    // renders empty rather than erroring, and the offload must not change that.
    #[tokio::test]
    async fn previous_value_renders_empty_outside_state_ops() {
        let imp = imposter_with(Arc::new(ThreadProbeStore::new(true)), None);

        let (body, _) = rendered(
            render(
                &imp,
                "[{{ previousValue }}]",
                crate::imposter::Headers::new(),
                false,
            )
            .await
            .expect("no transport failure"),
        );

        assert_eq!(body, "[]");
    }
}

// =========================================================================
// Issue #986: the FSM transition must not pay a spawn_blocking hop to run a no-op. This is the
// dominant half of the issue — a stub without `newScenarioState` is the common case, and on a
// blocking backend it paid the hop on EVERY matched request.
// =========================================================================
#[cfg(test)]
mod fsm_offload_tests {
    use crate::extensions::flow_state::{CasOutcome, FlowStore};
    use crate::imposter::core::Imposter;
    use crate::imposter::handler::handle_imposter_request;
    use crate::imposter::types::ImposterConfig;
    use hyper::server::conn::http1;
    use hyper::service::service_fn;
    use hyper_util::rt::TokioIo;
    use serde_json::{Value, json};
    use std::sync::Arc;
    use std::sync::atomic::{AtomicUsize, Ordering};

    /// Counts seam entries (`is_blocking()`) and store writes, so a test can tell "never offloaded"
    /// apart from "offloaded and did nothing".
    struct SeamCountingStore {
        inner: crate::backends::inmemory::InMemoryFlowStore,
        seam_entries: Arc<AtomicUsize>,
        writes: Arc<AtomicUsize>,
    }

    impl SeamCountingStore {
        fn new() -> Self {
            Self {
                inner: crate::backends::inmemory::InMemoryFlowStore::new(300),
                seam_entries: Arc::new(AtomicUsize::new(0)),
                writes: Arc::new(AtomicUsize::new(0)),
            }
        }
    }

    impl FlowStore for SeamCountingStore {
        fn is_blocking(&self) -> bool {
            self.seam_entries.fetch_add(1, Ordering::SeqCst);
            true
        }
        fn get(&self, flow_id: &str, key: &str) -> anyhow::Result<Option<Value>> {
            self.inner.get(flow_id, key)
        }
        fn set(&self, flow_id: &str, key: &str, value: Value) -> anyhow::Result<()> {
            self.writes.fetch_add(1, Ordering::SeqCst);
            self.inner.set(flow_id, key, value)
        }
        fn exists(&self, flow_id: &str, key: &str) -> anyhow::Result<bool> {
            self.inner.exists(flow_id, key)
        }
        fn delete(&self, flow_id: &str, key: &str) -> anyhow::Result<()> {
            self.inner.delete(flow_id, key)
        }
        fn increment(&self, flow_id: &str, key: &str) -> anyhow::Result<i64> {
            self.inner.increment(flow_id, key)
        }
        fn set_ttl(&self, flow_id: &str, ttl_seconds: i64) -> anyhow::Result<()> {
            self.inner.set_ttl(flow_id, ttl_seconds)
        }
        fn compare_and_set(
            &self,
            flow_id: &str,
            key: &str,
            expected: Option<&Value>,
            new: Value,
        ) -> anyhow::Result<CasOutcome> {
            self.writes.fetch_add(1, Ordering::SeqCst);
            self.inner.compare_and_set(flow_id, key, expected, new)
        }
    }

    /// Serve one request against `stubs` on a blocking counting store; return
    /// `(seam_entries, writes, status)`.
    async fn serve_once(stubs: Value, path: &str) -> (usize, usize, u16) {
        let cfg: ImposterConfig =
            serde_json::from_value(json!({ "port": 0, "protocol": "http", "stubs": stubs }))
                .expect("valid imposter config");
        let store = Arc::new(SeamCountingStore::new());
        let seam = store.seam_entries.clone();
        let writes = store.writes.clone();
        let mut imp = Imposter::new(cfg).expect("test imposter");
        imp.flow_store = store;
        let imposter = Arc::new(imp);

        let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
            .await
            .expect("bind");
        let addr = listener.local_addr().expect("local addr");
        let imp = imposter.clone();
        tokio::spawn(async move {
            let Ok((stream, peer)) = listener.accept().await else {
                return;
            };
            let service = service_fn(move |req| {
                let imp = imp.clone();
                async move { handle_imposter_request(req, imp, peer).await }
            });
            let _ = http1::Builder::new()
                .serve_connection(TokioIo::new(stream), service)
                .await;
        });

        let resp = reqwest::get(format!("http://{addr}{path}"))
            .await
            .expect("request");
        let status = resp.status().as_u16();
        (
            seam.load(Ordering::SeqCst),
            writes.load(Ordering::SeqCst),
            status,
        )
    }

    // Edge case 16: a plain stub — no scenario, no transition — must not enter the seam at all.
    // Red before the fix: 1 entry, spent running a function that returns immediately.
    #[tokio::test]
    async fn a_stub_with_no_transition_never_reaches_the_seam() {
        let (seam, writes, status) = serve_once(
            json!([{
                "predicates": [{ "equals": { "path": "/plain" } }],
                "responses": [{ "is": { "statusCode": 200, "body": "ok" } }]
            }]),
            "/plain",
        )
        .await;

        assert_eq!(status, 200, "the request must still be served normally");
        assert_eq!(writes, 0, "a stub with no transition writes nothing");
        assert_eq!(
            seam, 0,
            "a stub with no newScenarioState must not pay a spawn_blocking hop to run a no-op"
        );
    }

    // Edge case 17: the other direction — a stub that DOES transition must still offload and must
    // still apply the transition. Without this, "skip the offload" could be implemented by
    // skipping the transition itself and the test above would still pass.
    #[tokio::test]
    async fn a_stub_with_a_transition_still_offloads_and_still_writes() {
        let (seam, writes, status) = serve_once(
            json!([{
                "scenarioName": "order",
                "newScenarioState": "Placed",
                "predicates": [{ "equals": { "path": "/place" } }],
                "responses": [{ "is": { "statusCode": 200, "body": "ok" } }]
            }]),
            "/place",
        )
        .await;

        assert_eq!(status, 200);
        assert!(
            seam > 0,
            "a stub with newScenarioState must still take the offload"
        );
        assert!(
            writes > 0,
            "the transition must still be applied — skipping the offload must not mean \
             skipping the write"
        );
    }
}

#[cfg(test)]
mod decode_binary_body_tests {
    use super::*;

    // Issue #1151: the three outcomes of the one decode both binary sites now share.

    #[test]
    fn a_valid_body_decodes() {
        let Ok(BinaryBody::Decoded(bytes)) = decode_binary_body("aGVsbG8=".to_string(), false)
        else {
            panic!("valid base64 must decode");
        };
        assert_eq!(bytes.as_ref(), b"hello");
    }

    // Lenient: the raw bytes come back as a *distinct* variant, so the caller cannot serve them
    // without having to decide what to attach — that is what keeps the #323 header from being
    // forgotten at a site again.
    #[test]
    fn a_bad_body_is_a_raw_fallback_when_lenient() {
        let Ok(BinaryBody::RawFallback(bytes)) =
            decode_binary_body("not!valid!base64!".to_string(), false)
        else {
            panic!("an undecodable body must be a RawFallback in lenient mode");
        };
        assert_eq!(bytes.as_ref(), b"not!valid!base64!");
    }

    #[test]
    fn a_bad_body_is_a_ready_made_500_when_strict() {
        let Err(response) = decode_binary_body("not!valid!base64!".to_string(), true) else {
            panic!("strict mode must refuse an undecodable body");
        };
        assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
        assert_eq!(
            response
                .headers()
                .get("x-rift-binary-error")
                .and_then(|v| v.to_str().ok()),
            Some("true"),
            "the strict 500 still carries the #323 signal header"
        );
    }

    // #1554: Mountebank drops every non-base64 character before decoding, so the multiline PNG of
    // mbTest `httpStubTest.js:317` decodes to its 274 bytes instead of falling back to raw text.
    #[test]
    fn a_body_with_line_breaks_decodes_as_mountebank_decodes_it() {
        let png = "iVBORw0KGgoAAAANSUhEUgAAAGQAAAAyBAMAAABYG2ONAAAAFVBMVEUAAAD///9/f39fX1+fn58f\nHx8/Pz8rYiDqAAAACXBIWXMAAA7EAAAOxAGVKw4bAAAAo0lEQVRIie2Qyw7CIBBFb2DwO5q+1o0L\n1w0NrrHRPQnV//8EAUl0ga1ujIs5CZAz4YYZAIZhmN/QQOkjzq3LLuv6xUrQHmTJGphcEGE9rUQ3\nY4bqqrDjAlgQoJK9Z8YBmFy8Gp8DeSeTfRSBCf2I6/JN5ORiRfrNiIfqh9S9SVPL27A1C0G4EX2e\nJR7J1iI7rbG0Vf4x0UwPW0Uh3i0bwzD/yR11mBj1DIKiVwAAAABJRU5ErkJggg==\n";
        let Ok(BinaryBody::Decoded(bytes)) = decode_binary_body(png.to_string(), true) else {
            panic!("a base64 body wrapped with line breaks must decode");
        };
        assert_eq!(bytes.len(), 274);
        assert_eq!(&bytes[..4], b"\x89PNG");
    }

    // A body that is still not base64 once the stray characters are gone falls back with its
    // original text, not the filtered one.
    #[test]
    fn a_body_still_bad_after_the_filter_falls_back_with_its_original_text() {
        let Ok(BinaryBody::RawFallback(bytes)) =
            decode_binary_body("aGVsbG8\n!".to_string(), false)
        else {
            panic!("`aGVsbG8` (no padding) must not decode");
        };
        assert_eq!(bytes.as_ref(), b"aGVsbG8\n!");
    }

    // Strict mode must not turn a *valid* body into a failure.
    #[test]
    fn a_valid_body_decodes_under_strict_too() {
        assert!(matches!(
            decode_binary_body("aGVsbG8=".to_string(), true),
            Ok(BinaryBody::Decoded(_))
        ));
    }
}

#[cfg(test)]
mod served_answer_tests {
    use super::super::fault_io::TcpFaultKind;
    use super::*;

    fn plain() -> Response<Full<Bytes>> {
        build_response_with_headers(StatusCode::OK, [("x-a", "b")], Bytes::new())
    }

    #[test]
    fn an_ordinary_response_is_the_served_answer() {
        assert!(is_served_answer(&plain()));
    }

    #[test]
    fn a_debug_report_is_not_the_served_answer() {
        let mut report = plain();
        report.extensions_mut().insert(DebugReport);
        assert!(!is_served_answer(&report));
    }

    #[test]
    fn a_tcp_fault_carrier_is_not_the_served_answer() {
        let mut carrier = plain();
        carrier.extensions_mut().insert(TcpFaultKind::Reset);
        assert!(!is_served_answer(&carrier));
    }
}

/// Move the request's random handle onto a stream of its own (issue #1795) when the imposter has a
/// `seed` and an `rngKey` whose parts this request carries: the seed, the key's digest and how many
/// earlier requests had that key pick the stream, so concurrent requests draw the same values
/// whatever order they arrive in. Otherwise the request keeps the imposter's stream (#1755).
fn rekey_request_stream(
    imposter: &Imposter,
    method: &str,
    path: &str,
    headers: &crate::util::OrderedMap<String, Vec<String>>,
    query_str: &str,
    body: Option<&str>,
) {
    use crate::imposter::rng::{ImposterRng, KeySource, Seed, key_digest, keyed_state};
    let Some(engine) = imposter
        .config
        .rift
        .as_ref()
        .and_then(|r| r.script_engine.as_ref())
    else {
        return;
    };
    let (Some(seed), Some(key)) = (
        engine.seed.as_ref().and_then(Seed::value),
        engine.rng_key.as_ref(),
    ) else {
        return;
    };
    // A key admission would refuse reached here only by replay; it was logged when the imposter
    // was built, and the request keeps the imposter's stream.
    let Ok(parts) = key.parts() else {
        return;
    };
    let Some(handle) = crate::imposter::rng::current() else {
        return;
    };
    let query = parse_query_string(query_str);
    let header = |name: &str| {
        headers
            .iter()
            .find(|(k, _)| k.eq_ignore_ascii_case(name))
            .and_then(|(_, v)| v.first().cloned())
    };
    let query_value = |name: &str| query.get(name).and_then(|v| v.first().cloned());
    let source = KeySource {
        method,
        path,
        header: &header,
        query: &query_value,
        body,
    };
    let Some(digest) = key_digest(&parts, &source) else {
        return;
    };
    let occurrence = imposter.rng.load().next_occurrence(digest);
    handle.rekey(ImposterRng::new(Some(keyed_state(
        seed, digest, occurrence,
    ))));
}

/// An `export: "http"` component's response (issue #1758): its status, its body's bytes and every
/// header value it set, with Rift's markers. Framing headers are Rift's own: hyper frames the body.
fn wasm_http_response(
    answer: crate::scripting::WasmResponse,
    engine: &str,
    trace: Option<String>,
) -> Response<Full<Bytes>> {
    use hyper::header::{CONNECTION, CONTENT_LENGTH, TRANSFER_ENCODING};
    let mut builder = Response::builder().status(answer.status);
    for (name, value) in &answer.headers {
        if name == CONNECTION
            || name == CONTENT_LENGTH
            || name == TRANSFER_ENCODING
            || name == "keep-alive"
        {
            continue;
        }
        builder = builder.header(name, value);
    }
    builder = builder
        .header("x-rift-imposter", "true")
        .header("x-rift-script", engine);
    if let Some(trace) = &trace {
        builder = builder.header("x-rift-script-trace", trace.as_str());
    }
    builder
        .body(Full::new(answer.body))
        .unwrap_or_else(|e| build_failure_response(&e, "wasm http response build failed"))
}