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
//! Request matching, flow-id / scenario-state resolution, and form parsing.
//!
//! Part of the `Imposter` implementation; see `core/mod.rs` for the struct definition.
use super::*;
use crate::imposter::predicates::stub_matches_explained;
// The differential oracle below is the ONLY remaining caller of the boolean scan here — the live
// path asks for the failing predicate's index instead (and discards it when untraced).
use crate::extensions::flow_state::CasOutcome;
use crate::imposter::predicates::RequestHeaders;
#[cfg(test)]
use crate::imposter::predicates::stub_matches_inner;
use crate::imposter::probe::{Point, fire};
use crate::imposter::types::{MAX_TRIED_STUBS, MatchOutcome, TriedStub, TriedWhy};
/// The accumulating form of [`MatchOutcome`]'s `tried`/`triedOmitted`, built during the stub scan.
///
/// It exists separately from `MatchOutcome` because the verdict is not known until the scan ends:
/// the scan can only record the candidates it rejects, and whether the pass matched (and which
/// stub won) is supplied by [`Self::into_outcome`] afterwards. Only VISITED candidates land here —
/// stubs the Stage-1 index ruled out are never evaluated, so there is no verdict to report for
/// them.
#[derive(Debug, Default)]
pub(crate) struct MatchTrace {
tried: Vec<TriedStub>,
omitted: u32,
}
impl MatchTrace {
/// Record a rejected candidate, or — past the cap — count it.
fn reject(&mut self, stub_index: usize, stub: &Stub, why: TriedWhy) {
if self.tried.len() >= MAX_TRIED_STUBS {
self.omitted += 1;
return;
}
self.tried.push(TriedStub {
stub_index,
stub_id: stub.id.clone(),
why,
});
}
/// Seal the trace with the pass's verdict: `Some((stub, index))` is the winner, `None` a miss.
pub(crate) fn into_outcome(self, winner: Option<(&Stub, usize)>) -> MatchOutcome {
MatchOutcome {
matched: winner.is_some(),
stub_index: winner.map(|(_, index)| index),
stub_id: winner.and_then(|(stub, _)| stub.id.clone()),
tried: self.tried,
tried_omitted: self.omitted,
}
}
}
/// A matching pass's result and, when one was requested, the trace of the candidates it visited.
type TracedMatch = (Option<(Arc<StubState>, usize)>, Option<MatchTrace>);
/// How many times a write to a gating key decides again after its compare-and-set lost, before it
/// writes anyway. The bound keeps a key under constant writes from holding a request.
const MAX_SET_ATTEMPTS: usize = 16;
/// `current` with `scenario` stamped `at`. Keeps the higher stamp: nothing orders two transitions'
/// publishes, and a stalled one going back to a lower stamp would leave a client holding the higher
/// one on `304` until the next transition (issue #1779).
fn transitions_with(
current: &HashMap<String, chrono::DateTime<chrono::Utc>>,
scenario: &str,
at: chrono::DateTime<chrono::Utc>,
) -> HashMap<String, chrono::DateTime<chrono::Utc>> {
let mut next = HashMap::clone(current);
next.entry(scenario.to_string())
.and_modify(|stamp| *stamp = (*stamp).max(at))
.or_insert(at);
next
}
impl Imposter {
/// Find a matching stub for a request and return a cloned copy with its index.
/// `Err` means a backend consulted during matching failed (issue #318) — the caller
/// must surface it, never treat it as "no match".
pub fn find_matching_stub(
&self,
method: &str,
path: &str,
headers: &hyper::HeaderMap,
query: Option<&str>,
body: Option<&str>,
) -> anyhow::Result<Option<(Arc<StubState>, usize)>> {
// Call the extended version with no client info (backward compatible). This convenience
// wrapper still accepts a `HeaderMap` and converts once, via the shared collector (issue
// #1025) — the hot path (`handler.rs`) passes an already-built header map to
// `find_matching_stub_with_client` directly.
let headers_map: crate::util::OrderedMap<String, Vec<String>> =
crate::imposter::headers::collect_request_headers(
headers,
crate::behaviors::header_to_title_case,
);
self.find_matching_stub_with_client(method, path, &headers_map, query, body, None, None)
}
/// Find a matching stub with client address information (for requestFrom/ip predicates)
#[allow(clippy::too_many_arguments)]
pub fn find_matching_stub_with_client<H>(
&self,
method: &str,
path: &str,
headers_map: &H,
query: Option<&str>,
body: Option<&str>,
request_from: Option<&str>,
client_ip: Option<&str>,
) -> anyhow::Result<Option<(Arc<StubState>, usize)>>
where
H: RequestHeaders,
{
Ok(self
.find_matching_stub_with_client_inner(
method,
path,
headers_map,
query,
body,
request_from,
client_ip,
false,
self.script_scope(),
)?
.0)
}
/// Body of [`Self::find_matching_stub_with_client`], optionally recording WHY each visited
/// candidate fell out (see [`MatchTrace`]).
///
/// `want_trace` is a parameter rather than a separate scan so the traced and untraced paths
/// can never diverge on which stub wins: tracing observes the one scan, it does not repeat it.
/// With `want_trace: false` nothing is allocated and the pass is the pre-existing one.
#[allow(clippy::too_many_arguments)]
pub(crate) fn find_matching_stub_with_client_inner<H>(
&self,
method: &str,
path: &str,
headers_map: &H,
query: Option<&str>,
body: Option<&str>,
request_from: Option<&str>,
client_ip: Option<&str>,
want_trace: bool,
script_scope: crate::scripting::ScriptScope,
) -> anyhow::Result<TracedMatch>
where
H: RequestHeaders,
{
let mut trace = want_trace.then(MatchTrace::default);
let mut gate_states: HashMap<&str, String> = HashMap::new();
// Stage 1 (issues #292, #707): one wait-free load yields the stubs and the index built over
// those exact stubs, so they are consistent by construction. Every dimension over-
// approximates (stubs it can't index sit in its always-bits), so `candidates` is a superset
// of the true matches, ascending — Stage-2 first-match-wins is unchanged.
// Note: a stub some dimension rules out is no longer visited, so its
// `required_scenario_state` backend read (which could `Err`, #318) is skipped for that
// request — correct, since a stub that provably can't match should not be consulted.
let snapshot = self.snapshot();
let stubs = snapshot.stubs();
// `headers_map` is the Title-Case, multi-value header view already built once by the
// caller (#288, #1025) — no re-conversion from `HeaderMap` here. Generic over
// `RequestHeaders` so both that shape and a single-value map (tests, the debug path)
// serve the same matcher.
// Parse form data if Content-Type is application/x-www-form-urlencoded
let form = Self::parse_form_data(headers_map, body);
let script_files = self.script_file_access();
let flow_id = self.resolve_flow_id(headers_map);
// The request body as JSON, parsed at most once per request and shared across every stub's
// predicates (issue #290) — and only if a predicate or body dimension reads it (#1442).
let body_json = crate::behaviors::LazyJson::new(body);
// Likewise parse the query string once per request rather than per predicate (issue #480).
let query_map = crate::imposter::predicates::parse_query(query);
// Likewise the XML DOM (issue #711): lazily parsed on first XPath predicate touched, then
// shared across every remaining stub in this request's scan — one parse per request, not
// one per XPath predicate evaluation.
let xml_dom = body.map(crate::behaviors::LazyXmlDom::new);
for stub_idx in snapshot
.candidates_with_body(method, path, &body_json)
.iter()
{
let stub_state = &stubs[stub_idx];
let stub = &stub_state.stub;
// Correlated-isolation gate (issue #223, runs first): a space-scoped stub only
// participates in matching when the request's resolved flow_id equals its space.
// Unscoped stubs match any space (PerInstance default).
if let Some(space) = &stub.space
&& flow_id != *space
{
if let Some(trace) = trace.as_mut() {
trace.reject(stub_idx, stub, TriedWhy::SkippedSpace);
}
continue;
}
// Scenario FSM eligibility gate (before predicate precedence): a stub guarded by
// `requiredScenarioState` only participates in matching when the current
// (flow_id, scenario) state equals it.
if let Some(required) = &stub.required_scenario_state {
let scenario = stub.scenario_name.as_deref().unwrap_or("");
// One read per scenario per scan, so every stub is judged against one state: a
// transition during the scan must not make it miss every stub (issue #1781).
let state = match gate_states.entry(scenario) {
std::collections::hash_map::Entry::Occupied(known) => known.into_mut(),
std::collections::hash_map::Entry::Vacant(first) => {
first.insert(self.scenario_state(&flow_id, scenario)?)
}
};
self.probe_at(|port| Point::GateRead {
port,
stub_index: stub_idx,
});
if *state != *required {
if let Some(trace) = trace.as_mut() {
trace.reject(stub_idx, stub, TriedWhy::SkippedScenarioState);
}
continue;
}
}
// `stub_matches_inner` IS this call with the index discarded, so asking for the index
// unconditionally costs nothing and keeps one scan for both paths.
match stub_matches_explained(
&stub.predicates,
method,
path,
query,
headers_map,
body,
request_from,
client_ip,
form.as_ref(),
&script_scope,
&script_files,
&body_json,
xml_dom.as_ref(),
Some(&query_map),
)? {
None => {
// Bump the refcount instead of deep-cloning the whole `StubState` (issue #287).
// The caller (`handler.rs`) holds the returned `Arc<StubState>` across `.await`
// points, so the arc-swap load guard must be released before returning (issue #291);
// the `Arc` lets it do so without a copy. Response-cycling state stays shared: the
// `cycler` is itself an `Arc`, so advancing it via this handle is visible through
// the stored stub, and an in-place replace swaps a new `Arc` while in-flight
// requests keep serving their snapshot.
return Ok((Some((Arc::clone(stub_state), stub_idx)), trace));
}
Some(failed) => {
if let Some(trace) = trace.as_mut() {
trace.reject(stub_idx, stub, TriedWhy::FailedPredicate(failed));
}
}
}
}
Ok((None, trace))
}
/// As [`Self::find_matching_stub_with_client`], but bounded (issue #476): when the stub
/// snapshot contains an `inject` predicate — synchronous Boa JavaScript evaluated deep inside
/// the matcher — the whole matching pass runs on `spawn_blocking` under a wall-clock deadline,
/// so a slow or runaway predicate script cannot stall a tokio worker. Scriptless snapshots
/// (the overwhelmingly common case, gated by the precomputed `StubIndex::has_inject` flag)
/// take the exact inline path — no clones, no blocking-pool hop, no deadline.
///
/// No abort flag: Boa has no per-instruction interrupt, so after a timeout the loop-iteration
/// cap (issue #327) is what eventually frees the blocking thread.
#[allow(clippy::too_many_arguments)]
pub async fn find_matching_stub_with_client_bounded<H>(
self: &Arc<Self>,
method: &str,
path: &str,
headers_map: &H,
query: Option<&str>,
body: Option<&str>,
request_from: Option<&str>,
client_ip: Option<&str>,
timeout: std::time::Duration,
) -> anyhow::Result<Option<(Arc<StubState>, usize)>>
where
// `Clone + Send + 'static`: the `spawn_blocking` offload below clones `headers_map` into a
// `'static` worker closure when the snapshot needs offloading (inject/scenario-gate).
H: RequestHeaders + Clone + Send + 'static,
{
Ok(self
.find_matching_stub_with_client_bounded_inner(
method,
path,
headers_map,
query,
body,
request_from,
client_ip,
timeout,
false,
self.script_scope(),
)
.await?
.0)
}
/// Body of [`Self::find_matching_stub_with_client_bounded`], optionally returning the trace of
/// the candidates the pass visited (see [`MatchTrace`]).
///
/// Every bounding decision is unchanged — the same inline fast path, the same `spawn_blocking`
/// offload, the same deadline — because the trace is produced BY the scan rather than beside
/// it; it simply rides back out of the blocking task by value with the result.
#[allow(clippy::too_many_arguments)]
pub(crate) async fn find_matching_stub_with_client_bounded_inner<H>(
self: &Arc<Self>,
method: &str,
path: &str,
headers_map: &H,
query: Option<&str>,
body: Option<&str>,
request_from: Option<&str>,
client_ip: Option<&str>,
timeout: std::time::Duration,
want_trace: bool,
script_scope: crate::scripting::ScriptScope,
) -> anyhow::Result<TracedMatch>
where
H: RequestHeaders + Clone + Send + 'static,
{
let snapshot = self.snapshot();
let has_inject = snapshot.has_inject();
// A scenario-gated stub reads flow state inside the matching pass; on a blocking backend
// (a networked store) that read must not run on the tokio worker either (issue #475). A scenario-free
// snapshot on a blocking backend still takes the inline fast path — no gate read happens.
let needs_offload =
has_inject || (snapshot.has_scenario_gate() && self.flow_store.is_blocking());
drop(snapshot);
if !needs_offload {
return self.find_matching_stub_with_client_inner(
method,
path,
headers_map,
query,
body,
request_from,
client_ip,
want_trace,
script_scope,
);
}
let this = Arc::clone(self);
let method = method.to_string();
let path = path.to_string();
let headers_map = headers_map.clone();
let query = query.map(str::to_string);
let body = body.map(str::to_string);
let request_from = request_from.map(str::to_string);
let client_ip = client_ip.map(str::to_string);
// The scenario gate reads the store and inject scripts can too, so the offloaded work
// annotates on a thread with no task-local unless it carries its own scope (issue #987).
let handle = crate::extensions::decorate::spawn_blocking_annotated(move || {
this.find_matching_stub_with_client_inner(
&method,
&path,
&headers_map,
query.as_deref(),
body.as_deref(),
request_from.as_deref(),
client_ip.as_deref(),
want_trace,
script_scope,
)
});
// The wall-clock deadline exists to bound a runaway inject *script*. A blocking flow-store
// read is bounded by the backend's own connection/command timeout, so when the offload is
// purely for the scenario gate (no inject) we await the task without the script deadline.
if !has_inject {
return match handle.await {
Ok((result, annotations)) => {
crate::extensions::decorate::replay_annotations(annotations);
result
}
Err(join_err) => Err(anyhow::anyhow!("matching task panicked: {join_err}")),
};
}
match tokio::time::timeout(timeout, handle).await {
Ok(Ok((result, annotations))) => {
crate::extensions::decorate::replay_annotations(annotations);
result
}
Ok(Err(join_err)) => Err(anyhow::anyhow!("matching task panicked: {join_err}")),
Err(_elapsed) => {
tracing::warn!(
"predicate inject matching timed out after {}ms",
timeout.as_millis()
);
// This route is only taken when the snapshot contains an inject predicate, so
// the deadline firing is attributable to predicate injection — shape it as
// `ScriptTimeoutError` (issue #499) so the handler serves a 504 that a client can
// tell apart from a genuinely broken predicate (which stays a Mountebank-style 400).
Err(crate::scripting::ScriptTimeoutError {
hook: "predicate inject",
timeout_ms: u64::try_from(timeout.as_millis()).unwrap_or(u64::MAX),
}
.into())
}
}
}
/// Reference implementation: the pre-#292 linear scan over *all* stubs. Shares every request
/// derivation and gate with the indexed path above; only the iteration differs. Used solely by
/// the differential test to prove the index preserves Mountebank first-match-wins exactly.
#[cfg(test)]
#[allow(clippy::too_many_arguments)]
pub(crate) fn find_matching_stub_linear<H: RequestHeaders>(
&self,
method: &str,
path: &str,
headers_map: &H,
query: Option<&str>,
body: Option<&str>,
request_from: Option<&str>,
client_ip: Option<&str>,
) -> anyhow::Result<Option<(Arc<StubState>, usize)>> {
let snapshot = self.snapshot();
let stubs = snapshot.stubs();
let form = Self::parse_form_data(headers_map, body);
let script_scope = self.script_scope();
let script_files = self.script_file_access();
let flow_id = self.resolve_flow_id(headers_map);
let body_json = crate::behaviors::LazyJson::new(body);
let query_map = crate::imposter::predicates::parse_query(query);
let xml_dom = body.map(crate::behaviors::LazyXmlDom::new);
for (index, stub_state) in stubs.iter().enumerate() {
let stub = &stub_state.stub;
if let Some(space) = &stub.space
&& flow_id != *space
{
continue;
}
if let Some(required) = &stub.required_scenario_state {
let scenario = stub.scenario_name.as_deref().unwrap_or("");
if self.scenario_state(&flow_id, scenario)? != *required {
continue;
}
}
if stub_matches_inner(
&stub.predicates,
method,
path,
query,
headers_map,
body,
request_from,
client_ip,
form.as_ref(),
&script_scope,
&script_files,
&body_json,
xml_dom.as_ref(),
Some(&query_map),
)? {
return Ok(Some((Arc::clone(stub_state), index)));
}
}
Ok(None)
}
/// The configured `flow_id_source` (`"imposter_port"` or `"header:<Name>"`),
/// defaulting to `"imposter_port"`.
pub fn flow_id_source(&self) -> String {
self.config
.rift
.as_ref()
.and_then(|r| r.flow_state.as_ref())
.and_then(|fs| fs.flow_id_source.clone())
.unwrap_or_else(|| "imposter_port".to_string())
}
/// Resolve the correlation `flow_id` for a request, partitioning scenario state.
/// `"header:<Name>"` uses that (case-insensitive) header; `"imposter_port"` (the default,
/// and the fallback when the header is absent) uses the imposter port. A thin `&self` wrapper
/// over [`Self::flow_id_for`] (issue #1025) — now that the live path's header map is
/// multi-value too, the live and recorded resolutions share the exact same implementation.
pub fn resolve_flow_id<H: RequestHeaders>(&self, headers: &H) -> String {
Self::flow_id_for(
&self.flow_id_source(),
headers,
self.config.port.unwrap_or(0),
)
}
/// Resolve the correlation `flow_id` for an already-recorded request (multi-value headers).
pub fn resolve_flow_id_recorded(&self, headers: &crate::imposter::Headers) -> String {
Self::flow_id_for(
&self.flow_id_source(),
headers,
self.config.port.unwrap_or(0),
)
}
/// Pure flow_id resolution (no `&self`), so it can be reused over recorded requests.
/// A flow id derives from a single header value; the first is taken if multi-valued (#238).
/// Generic over [`RequestHeaders`] (issue #1025) so the live path's multi-value map and the
/// recorded/single-value shapes all resolve through the one implementation.
fn flow_id_for<H: RequestHeaders>(source: &str, headers: &H, port: u16) -> String {
match source.strip_prefix("header:") {
Some(name) => headers
.entries()
.find(|(k, _)| k.eq_ignore_ascii_case(name))
.and_then(|(_, v)| v.first().cloned())
.unwrap_or_else(|| port.to_string()),
None => port.to_string(),
}
}
/// Run a blocking flow-store closure off the tokio worker when the backend actually blocks
/// (a networked store), otherwise inline. This keeps a slow or pool-exhausted backend from
/// head-of-line-blocking the worker thread every request is multiplexed on (issue #475),
/// while adding zero overhead for the non-blocking in-memory store (the common case — the
/// closure runs directly on the caller with no task hop).
pub(crate) async fn run_flow_blocking<T, F>(self: &Arc<Self>, f: F) -> anyhow::Result<T>
where
T: Send + 'static,
F: FnOnce(&Self) -> anyhow::Result<T> + Send + 'static,
{
if self.flow_store.is_blocking() {
let imp = Arc::clone(self);
// A failing backend annotates the op it failed on, and the pool thread carries no
// task-locals — so the closure runs under its own scope and the annotations are
// replayed here, back on the request task (issue #987).
let (result, annotations) =
crate::extensions::decorate::spawn_blocking_annotated(move || f(&imp))
.await
.map_err(|e| anyhow::anyhow!("flow-store task panicked: {e}"))?;
crate::extensions::decorate::replay_annotations(annotations);
result
} else {
f(self)
}
}
/// Current scenario state for `(flow_id, scenario)`, or the initial state if absent.
/// A backend read error propagates (issue #318): defaulting to the initial state on a
/// failing store would mis-gate matching into a silent wrong match.
pub fn scenario_state(&self, flow_id: &str, scenario: &str) -> anyhow::Result<String> {
match self.flow_store.get(flow_id, scenario)? {
// A non-string here means the key was overwritten out-of-band (raw flow-state
// PUT): coercing it to the initial state would silently mis-gate matching.
Some(v) => match v.as_str() {
Some(state) => Ok(state.to_string()),
None => {
anyhow::bail!("scenario state for {flow_id}/{scenario} is not a string: {v}")
}
},
None => Ok(INITIAL_SCENARIO_STATE.to_string()),
}
}
/// Set scenario state for `(flow_id, scenario)`. Writing the state the scenario already has is
/// not a transition and leaves `Last-Modified` alone (issue #1307).
pub fn set_scenario_state(
&self,
flow_id: &str,
scenario: &str,
state: &str,
) -> anyhow::Result<()> {
let new = serde_json::Value::String(state.to_string());
// Read the current state only when a transition could matter to a conditional response.
if !self.is_conditional_gate(scenario) {
self.probe_at(|port| Point::ScenarioChangeRead {
port,
changed: false,
});
return self.flow_store.set(flow_id, scenario, new);
}
// Absence reads as the initial state. An unreadable value (a non-string written
// out-of-band) is what this write repairs, so it must not block it: count it as a change,
// which at worst costs a poller one extra `200`.
let moves = |current: Option<&serde_json::Value>| match current {
None => state != INITIAL_SCENARIO_STATE,
Some(value) => value.as_str() != Some(state),
};
if self.set_deciding_move(flow_id, scenario, new, moves)? {
self.stamp_scenario_transition(scenario);
}
Ok(())
}
/// Write `new` to `key`, and report whether the write moved it, decided against the value it
/// actually replaced: one read before a plain write could stamp nothing for a state it put back
/// (issue #1780). The loop is bounded, and an unreadable value or a key that keeps moving is
/// written anyway and counted as moved, which at worst costs a poller one extra `200`.
///
/// Only for a conditional gate: any other key keeps a plain `set`, with no extra read.
fn set_deciding_move(
&self,
flow_id: &str,
key: &str,
new: serde_json::Value,
moves: impl Fn(Option<&serde_json::Value>) -> bool,
) -> anyhow::Result<bool> {
if let Ok(mut current) = self.flow_store.get(flow_id, key) {
for _ in 0..MAX_SET_ATTEMPTS {
let changed = moves(current.as_ref());
self.probe_at(|port| Point::ScenarioChangeRead { port, changed });
match self.flow_store.compare_and_set(
flow_id,
key,
current.as_ref(),
new.clone(),
)? {
CasOutcome::Applied => return Ok(changed),
CasOutcome::Conflict(now) => current = now,
}
}
}
self.flow_store.set(flow_id, key, new)?;
Ok(true)
}
/// Delete `key`, and report whether there was a key to delete, decided with the delete (issue
/// #1780). `set_key_ttl` with a zero TTL does both in one step. A store that keeps its fail-loud
/// default is deleted from plainly and counts as moved, so it does not start failing deletes,
/// and a store that is really down still fails on the `delete`.
fn delete_deciding_move(&self, flow_id: &str, key: &str) -> anyhow::Result<bool> {
self.probe_at(|port| Point::ScenarioWriteNext { port });
match self.flow_store.set_key_ttl(flow_id, key, 0) {
Ok(existed) => Ok(existed),
Err(e) => {
debug!("set_key_ttl unavailable for a scenario delete: {e}");
self.flow_store.delete(flow_id, key)?;
Ok(true)
}
}
}
/// Delete a scenario's state for a flow (so it reads back as the initial state).
pub fn delete_scenario_state(&self, flow_id: &str, scenario: &str) -> anyhow::Result<()> {
if !self.is_conditional_gate(scenario) {
return self.flow_store.delete(flow_id, scenario);
}
if self.delete_deciding_move(flow_id, scenario)? {
self.stamp_scenario_transition(scenario);
}
Ok(())
}
/// Whether a transition of `scenario` can change which stub answers a conditional request.
fn is_conditional_gate(&self, scenario: &str) -> bool {
self.snapshot().is_conditional_gate(scenario)
}
/// Record that `scenario` changed state (issue #1307), after the store write: a request that
/// copied the stamps before matching then either saw the old state with the old stamps, or
/// the new state — never the old answer under the new stamp, which would leave its client on
/// `304` for the new one.
fn stamp_scenario_transition(&self, scenario: &str) {
let at = self.load_clock.next();
let stamp = at.timestamp();
self.probe_at(|port| Point::TransitionStampIssued { port, stamp });
self.scenario_transitions
.rcu(|current| transitions_with(current, scenario, at));
self.probe_at(|port| Point::TransitionStamped { port, stamp });
}
/// Fire the probe point `point` builds from this imposter's port, when a probe is installed.
#[inline]
pub(crate) fn probe_at(&self, point: impl FnOnce(u16) -> Point) {
if self.probe.is_some() {
fire(&self.probe, point(self.config.port.unwrap_or(0)));
}
}
/// The scenario transition stamps, copied before matching (issue #1307) — see
/// [`Self::served_load_stamp`].
pub(crate) fn scenario_transitions(
&self,
) -> Arc<HashMap<String, chrono::DateTime<chrono::Utc>>> {
self.scenario_transitions.load_full()
}
/// `Last-Modified: load` as served for the stub at `stub_index` (issues #1280, #1307): its own
/// load stamp, or the latest transition of a scenario gating it or any stub ahead of it,
/// whichever is later. The scenario gates run before predicates, so these are the gates that
/// can have changed which stub answers; counting every one ahead of the match, evaluated or
/// not, can only cost a poller one extra `200`. `transitions` must be the copy taken before
/// matching. The matched stub's own gate is added explicitly, so a concurrent stub edit that
/// shifts indices cannot drop it.
pub(crate) fn served_load_stamp(
&self,
stub_state: &StubState,
stub_index: usize,
transitions: &HashMap<String, chrono::DateTime<chrono::Utc>>,
) -> chrono::DateTime<chrono::Utc> {
let stamp = self.served_load_stamp_unprobed(stub_state, stub_index, transitions);
crate::imposter::probe::fire(
&self.probe,
crate::imposter::probe::Point::Served {
port: self.config.port.unwrap_or(0),
generation: self.generation,
stamp: stamp.timestamp(),
},
);
stamp
}
fn served_load_stamp_unprobed(
&self,
stub_state: &StubState,
stub_index: usize,
transitions: &HashMap<String, chrono::DateTime<chrono::Utc>>,
) -> chrono::DateTime<chrono::Utc> {
let own = stub_state.loaded_at();
if transitions.is_empty() {
return own;
}
let own_gate = stub_state
.stub
.required_scenario_state
.as_ref()
.map(|_| stub_state.stub.scenario_name.as_deref().unwrap_or(""));
let snapshot = self.snapshot();
snapshot
.conditional_gates_through(stub_index)
.chain(own_gate)
.filter_map(|scenario| transitions.get(scenario))
.fold(own, |latest, at| latest.max(*at))
}
/// Apply a matched stub's `newScenarioState` transition (no-op if unset). A backend
/// write error propagates (issue #318): a lost transition would silently desync the
/// FSM, so the request must fail loudly instead.
///
/// A gated stub (`requiredScenarioState`) transitions via compare-and-set expecting
/// the state its gate observed (issue #311): if the state moved underneath — a
/// concurrent request won — the stale write is dropped rather than clobbering the
/// newer state. Conflict is normal concurrency, not an error. Ungated stubs keep
/// today's unconditional overwrite (there is no gate read to race against).
pub fn apply_scenario_transition(&self, flow_id: &str, stub: &Stub) -> anyhow::Result<()> {
use crate::extensions::flow_state::CasOutcome;
let Some(next) = &stub.new_scenario_state else {
return Ok(());
};
let scenario = stub.scenario_name.as_deref().unwrap_or("");
let Some(required) = &stub.required_scenario_state else {
return self.set_scenario_state(flow_id, scenario, next);
};
let new_value = serde_json::Value::String(next.to_string());
let expected = serde_json::Value::String(required.to_string());
// Leaving a state for itself is not a transition (issue #1307).
let changes = required != next && self.is_conditional_gate(scenario);
let applied = || {
self.probe_at(|port| Point::CasApplied { port });
if changes {
self.stamp_scenario_transition(scenario);
}
Ok(())
};
match self.flow_store.compare_and_set(
flow_id,
scenario,
Some(&expected),
new_value.clone(),
)? {
CasOutcome::Applied => applied(),
// The initial state is normally stored as ABSENCE — retry expecting that
// representation before concluding the state moved.
CasOutcome::Conflict(None) if required == INITIAL_SCENARIO_STATE => {
match self
.flow_store
.compare_and_set(flow_id, scenario, None, new_value)?
{
CasOutcome::Applied => applied(),
CasOutcome::Conflict(current) => {
self.probe_at(|port| Point::CasConflict { port });
Self::log_dropped_transition(flow_id, scenario, required, next, ¤t);
Ok(())
}
}
}
CasOutcome::Conflict(current) => {
self.probe_at(|port| Point::CasConflict { port });
Self::log_dropped_transition(flow_id, scenario, required, next, ¤t);
Ok(())
}
}
}
/// A dropped transition is correct behavior but must not be invisible: without this,
/// "my scenario stopped advancing" under concurrency has zero diagnostic signal.
fn log_dropped_transition(
flow_id: &str,
scenario: &str,
required: &str,
next: &str,
current: &Option<serde_json::Value>,
) {
debug!(
"scenario transition dropped ({flow_id}/{scenario} {required} -> {next}): \
state moved underneath, current {current:?}"
);
}
/// Read a raw flow-state value (admin flow-state inspection).
pub fn flow_get(&self, flow_id: &str, key: &str) -> anyhow::Result<Option<serde_json::Value>> {
self.flow_store.get(flow_id, key)
}
/// Set a raw flow-state value (admin flow-state arrange). A scenario's state lives under its
/// name, so a write there is a transition like any other and is stamped as one (issue #1344).
pub fn flow_set(
&self,
flow_id: &str,
key: &str,
value: serde_json::Value,
) -> anyhow::Result<()> {
ScenarioStampingStore::new(self).set(flow_id, key, value)
}
/// Delete a raw flow-state value (admin flow-state teardown). Deleting a scenario's key returns
/// it to its initial state, which is stamped as a transition (issue #1344).
pub fn flow_delete(&self, flow_id: &str, key: &str) -> anyhow::Result<()> {
ScenarioStampingStore::new(self).delete(flow_id, key)
}
/// Clear every key under a flow (issue #530) — backs `DELETE /admin/imposters/:port/flow-state/
/// :flow_id`. Idempotent: clearing an absent flow succeeds. Every scenario the flow held a state
/// for returns to its initial state, and each one gating a conditional stub is stamped as a
/// transition (issue #1344).
pub fn flow_clear(&self, flow_id: &str) -> anyhow::Result<()> {
ScenarioStampingStore::new(self).clear_flow(flow_id)
}
/// Empty the built-in flow store (issue #1518), so every scenario is back at `Started` and
/// every flow as a fresh create would have it. Each scenario gating a conditional stub that a
/// flow held a state for is stamped as a transition. A
/// [`FlowStoreProvider`](crate::extensions::flow_state::FlowStoreProvider)'s store is left
/// alone: it belongs to the embedder, and a recreate would be handed it back.
pub(crate) fn restart_flow_state(&self) -> anyhow::Result<()> {
if !self.flow_store_is_default {
return Ok(());
}
let Some(flow_ids) = self.flow_store.flow_ids()? else {
anyhow::bail!("the built-in flow store cannot list its flows");
};
for flow_id in flow_ids {
self.flow_clear(&flow_id)?;
}
Ok(())
}
/// Whether writing `after` (`None`: deleting) to `key` changes what the flow holds. An unreadable
/// current value counts as a change, as in `set_scenario_state`: it is what the write repairs.
fn would_change(&self, flow_id: &str, key: &str, after: Option<&serde_json::Value>) -> bool {
!matches!(self.flow_store.get(flow_id, key), Ok(current) if current.as_ref() == after)
}
/// Distinct scenario names declared by this imposter's stubs (sorted).
pub fn scenario_names(&self) -> Vec<String> {
let mut names: Vec<String> = self
.snapshot()
.stubs()
.iter()
.filter_map(|s| s.stub.scenario_name.clone())
.collect();
names.sort();
names.dedup();
names
}
/// Stubs scoped to a given correlation space (issue #223).
pub fn space_stubs(&self, space: &str) -> Vec<Stub> {
self.snapshot()
.stubs()
.iter()
.filter(|s| s.stub.space.as_deref() == Some(space))
.map(|s| s.stub.clone())
.collect()
}
/// Tear down a correlation space (issue #223): remove its scoped stubs, drop its recorded
/// requests, and reset its named scenario states. Other spaces and the port are untouched.
pub fn teardown_space(&self, space: &str) -> anyhow::Result<()> {
// Snapshot scenario names BEFORE pruning stubs: a scenario declared only on this space's
// stubs would otherwise vanish from scenario_names() and its state would never be reset.
let scenarios = self.scenario_names();
self.mutate_stubs(|stubs| {
let first = stubs
.iter()
.position(|s| s.stub.space.as_deref() == Some(space));
stubs.retain(|s| s.stub.space.as_deref() != Some(space));
// The stubs that moved up may now answer this space's requests (issue #1303).
if let Some(i) = first
&& i < stubs.len()
{
restamp(stubs, i.., self.load_clock.next());
}
});
// Best-effort across the slice's clears so one failure doesn't leave later scenarios
// stale, but the first failure still surfaces (issues #318, #330) — never report a
// clean teardown while stale recorded requests or scenario state persist in the backend.
let mut first_err = None;
let (cleared, written) =
self.delete_recorded(|| self.journal.clear_flow(self.journal_port(), space));
// A rewrite of `{port}.requests.jsonl` that failed (issue #1608) is a clear a restart undoes.
let cleared = cleared.and_then(|()| {
written.map_err(|e| {
anyhow::Error::new(e).context("could not rewrite the recorded requests file")
})
});
if let Err(e) = cleared {
warn!("space teardown: failed to clear recorded requests for '{space}': {e:#}");
first_err.get_or_insert(e);
}
for scenario in scenarios {
if let Err(e) = self.delete_scenario_state(space, &scenario) {
warn!("space teardown: failed to reset scenario '{scenario}' for '{space}': {e:#}");
first_err.get_or_insert(e);
}
}
match first_err {
Some(e) => Err(e),
None => Ok(()),
}
}
/// Parse form-urlencoded data from body if Content-Type matches. Request-scoped and rebuilt
/// per request, so the return is `FastMap` (issue #704) regardless of the input header map's
/// hasher.
pub(crate) fn parse_form_data<H: RequestHeaders>(
headers: &H,
body: Option<&str>,
) -> Option<crate::util::MultiValueMap> {
// Header keys are Title-Case in the pre-built map, so match Content-Type case-insensitively
// (HeaderMap lookups were case-insensitive; preserve that). Generic over `RequestHeaders`
// (issue #1026) so the verify API can pass a recorded request's multi-value map straight
// through, rather than collapsing it to one value per name first.
//
// Content-Type is single-valued per RFC 9110, so a request carrying it twice is malformed:
// take the first value rather than let a stray second one decide whether the body parses.
let content_type = headers
.entries()
.find(|(k, _)| k.eq_ignore_ascii_case("content-type"))
.and_then(|(_, v)| v.first())
.map(String::as_str)
.unwrap_or("");
if content_type.contains("application/x-www-form-urlencoded")
&& let Some(body_str) = body
{
// The query parser: Mountebank builds `form` with the same `querystring.parse`, so a
// repeated key keeps every value (issue #1553).
return Some(crate::util::parse_query_string(body_str));
}
None
}
/// `request.form` as Mountebank builds it: present only for a non-empty urlencoded body
/// (`httpRequest.js`), parsed as the matcher parses it. Shared by predicate generators and every
/// script surface (issue #1451), so recording, matching and scripts agree on what a form is.
pub(crate) fn request_form<H: RequestHeaders>(
headers: &H,
body: Option<&str>,
) -> Option<crate::util::MultiValueMap> {
if body.is_none_or(str::is_empty) {
return None;
}
Self::parse_form_data(headers, body)
}
}
// =============================================================================================
// Issue #476: predicate `inject` runs deep inside the synchronous matcher, so the bounded path
// wraps the WHOLE matching pass in spawn_blocking + timeout — but only for imposters whose stub
// set actually contains an inject predicate (StubIndex::has_inject), so scriptless imposters
// keep the exact inline fast path.
// =============================================================================================
/// The imposter's flow store, seen through a scenario lens (issues #1344, #1388): a write to a key
/// that is a scenario gating a conditional stub is a scenario transition, and is stamped as one
/// after the write succeeds, so the changed answer is served under a later `Last-Modified` (#1307).
/// Writing the state a scenario already holds is not a transition. Every other key, and every
/// read, passes straight through. A TTL of zero or less deletes, so it is stamped like a delete;
/// a TTL that later expires on its own is no write and is not seen.
///
/// Every door that writes flow state goes through it: the admin flow-state methods above, a
/// response's `_rift.stateOps`, and a script's `ctx.state`. It is built per request, not wrapped
/// around the store for good: `I` borrows the imposter (`&Imposter`) or, for a script that needs a
/// `'static` store, shares it (`Arc<Imposter>`) for the script's run only.
pub(crate) struct ScenarioStampingStore<I> {
imposter: I,
}
impl<I: std::ops::Deref<Target = Imposter>> ScenarioStampingStore<I> {
pub(crate) fn new(imposter: I) -> Self {
Self { imposter }
}
fn store(&self) -> &dyn FlowStore {
self.imposter.flow_store.as_ref()
}
/// Run `clear`, which empties `flow_id`, then stamp every scenario gating a conditional stub
/// that the flow held a state for.
fn clearing(
&self,
flow_id: &str,
clear: impl FnOnce() -> anyhow::Result<()>,
) -> anyhow::Result<()> {
// The clear reports nothing, so a transition between the reads and the clear is found in
// the stamp map: a state moved since the reads is one the clear moved back (issue #1780).
// Loaded before the reads, so nothing falls between them.
let before = self.imposter.scenario_transitions();
let snapshot = self.imposter.snapshot();
let gates: std::collections::BTreeSet<&str> =
snapshot.conditional_gates_through(usize::MAX).collect();
let held: std::collections::BTreeSet<&str> = gates
.iter()
.copied()
.filter(|scenario| self.imposter.would_change(flow_id, scenario, None))
.collect();
self.imposter
.probe_at(|port| Point::ScenarioWriteNext { port });
clear()?;
let after = self.imposter.scenario_transitions();
for scenario in gates {
if held.contains(scenario) || before.get(scenario) != after.get(scenario) {
self.imposter.stamp_scenario_transition(scenario);
}
}
Ok(())
}
/// Run `write`, which always moves `key`, then stamp `key` when it gates a conditional stub.
fn stamped<T>(
&self,
key: &str,
write: impl FnOnce() -> anyhow::Result<T>,
) -> anyhow::Result<T> {
let stamp = self.imposter.is_conditional_gate(key);
self.imposter.probe_at(|port| Point::ScenarioChangeRead {
port,
changed: stamp,
});
let result = write()?;
if stamp {
self.imposter.stamp_scenario_transition(key);
}
Ok(result)
}
}
impl<I: std::ops::Deref<Target = Imposter> + Send + Sync> FlowStore for ScenarioStampingStore<I> {
fn get(&self, flow_id: &str, key: &str) -> anyhow::Result<Option<serde_json::Value>> {
self.store().get(flow_id, key)
}
fn set(&self, flow_id: &str, key: &str, value: serde_json::Value) -> anyhow::Result<()> {
if !self.imposter.is_conditional_gate(key) {
return self.store().set(flow_id, key, value);
}
let moves = |current: Option<&serde_json::Value>| current != Some(&value);
if self
.imposter
.set_deciding_move(flow_id, key, value.clone(), moves)?
{
self.imposter.stamp_scenario_transition(key);
}
Ok(())
}
fn exists(&self, flow_id: &str, key: &str) -> anyhow::Result<bool> {
self.store().exists(flow_id, key)
}
fn delete(&self, flow_id: &str, key: &str) -> anyhow::Result<()> {
if !self.imposter.is_conditional_gate(key) {
return self.store().delete(flow_id, key);
}
if self.imposter.delete_deciding_move(flow_id, key)? {
self.imposter.stamp_scenario_transition(key);
}
Ok(())
}
fn is_blocking(&self) -> bool {
self.store().is_blocking()
}
// A number is never a scenario state (`scenario_state` refuses one), so an increment of a
// scenario's key always moves it.
fn increment(&self, flow_id: &str, key: &str) -> anyhow::Result<i64> {
self.stamped(key, || self.store().increment(flow_id, key))
}
fn increment_by(&self, flow_id: &str, key: &str, by: i64) -> anyhow::Result<i64> {
self.stamped(key, || self.store().increment_by(flow_id, key, by))
}
// A TTL of zero or less drops the flow at once: a clear.
fn set_ttl(&self, flow_id: &str, ttl_seconds: i64) -> anyhow::Result<()> {
if ttl_seconds > 0 {
return self.store().set_ttl(flow_id, ttl_seconds);
}
self.clearing(flow_id, || self.store().set_ttl(flow_id, ttl_seconds))
}
// A TTL of zero or less deletes the key at once.
fn set_key_ttl(&self, flow_id: &str, key: &str, ttl_seconds: i64) -> anyhow::Result<bool> {
if ttl_seconds > 0 {
return self.store().set_key_ttl(flow_id, key, ttl_seconds);
}
let gate = self.imposter.is_conditional_gate(key);
let deleted = self.store().set_key_ttl(flow_id, key, ttl_seconds)?;
if gate && deleted {
self.imposter.stamp_scenario_transition(key);
}
Ok(deleted)
}
fn clear_flow(&self, flow_id: &str) -> anyhow::Result<()> {
self.clearing(flow_id, || self.store().clear_flow(flow_id))
}
fn entry_count(&self, flow_id: &str) -> anyhow::Result<Option<usize>> {
self.store().entry_count(flow_id)
}
fn compare_and_set(
&self,
flow_id: &str,
key: &str,
expected: Option<&serde_json::Value>,
new: serde_json::Value,
) -> anyhow::Result<CasOutcome> {
let moves = expected != Some(&new);
let gate = self.imposter.is_conditional_gate(key);
let outcome = self.store().compare_and_set(flow_id, key, expected, new)?;
if gate && moves && matches!(outcome, CasOutcome::Applied) {
self.imposter.stamp_scenario_transition(key);
}
Ok(outcome)
}
fn flow_ids(&self) -> anyhow::Result<Option<Vec<String>>> {
self.store().flow_ids()
}
}
#[cfg(test)]
mod bounded_matching_tests {
use super::*;
use serde_json::json;
use std::time::Duration;
#[test]
fn a_transition_stamp_never_goes_back() {
let at = |secs| chrono::DateTime::from_timestamp(secs, 0).expect("in range");
let first = transitions_with(&HashMap::new(), "S", at(10));
assert_eq!(first["S"], at(10));
let later = transitions_with(&first, "S", at(20));
assert_eq!(later["S"], at(20));
let stalled = transitions_with(&later, "S", at(15));
assert_eq!(stalled["S"], at(20), "a late lower stamp stays out");
let other = transitions_with(&stalled, "T", at(15));
assert_eq!((other["S"], other["T"]), (at(20), at(15)));
}
fn imposter(stubs: serde_json::Value) -> Arc<Imposter> {
let cfg = serde_json::from_value(json!({ "port": 0, "protocol": "http", "stubs": stubs }))
.expect("valid imposter config");
Arc::new(Imposter::new(cfg).expect("test imposter"))
}
fn no_headers() -> HashMap<String, String> {
HashMap::new()
}
/// The in-memory store, counting its reads.
struct CountingReads {
inner: crate::backends::InMemoryFlowStore,
reads: std::sync::atomic::AtomicUsize,
}
impl FlowStore for CountingReads {
fn get(&self, flow: &str, key: &str) -> anyhow::Result<Option<serde_json::Value>> {
self.reads.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
self.inner.get(flow, key)
}
fn set(&self, flow: &str, key: &str, value: serde_json::Value) -> anyhow::Result<()> {
self.inner.set(flow, key, value)
}
fn exists(&self, flow: &str, key: &str) -> anyhow::Result<bool> {
self.inner.exists(flow, key)
}
fn delete(&self, flow: &str, key: &str) -> anyhow::Result<()> {
self.inner.delete(flow, key)
}
fn increment(&self, flow: &str, key: &str) -> anyhow::Result<i64> {
self.inner.increment(flow, key)
}
fn set_ttl(&self, flow: &str, ttl_seconds: i64) -> anyhow::Result<()> {
self.inner.set_ttl(flow, ttl_seconds)
}
}
fn reads_of_one_scan(stubs: serde_json::Value) -> usize {
let cfg = serde_json::from_value(json!({ "port": 0, "protocol": "http", "stubs": stubs }))
.expect("valid imposter config");
let mut imp = Imposter::new(cfg).expect("test imposter");
let store = Arc::new(CountingReads {
inner: crate::backends::InMemoryFlowStore::new(300),
reads: std::sync::atomic::AtomicUsize::new(0),
});
imp.flow_store = store.clone();
let matched = imp
.find_matching_stub_with_client("GET", "/", &no_headers(), None, None, None, None)
.expect("scan");
assert!(matched.is_none(), "no stub is meant to match");
store.reads.load(std::sync::atomic::Ordering::SeqCst)
}
fn gated(scenario: &str, state: &str) -> serde_json::Value {
json!({
"scenarioName": scenario,
"requiredScenarioState": state,
"responses": [{ "is": { "body": "x" } }]
})
}
// Issue #1781: every gate of a scenario in a scan reads one state.
#[test]
fn a_scan_reads_each_scenario_once() {
assert_eq!(
reads_of_one_scan(json!([gated("S", "A"), gated("S", "B"), gated("S", "C")])),
1
);
assert_eq!(
reads_of_one_scan(json!([gated("S", "A"), gated("T", "A"), gated("S", "B")])),
2
);
}
// Issue #611: an undecodable percent-sequence in a form body must pass through raw rather than
// blank the key or value — the same decode convention the rest of the repo follows.
#[test]
fn parse_form_data_passes_through_undecodable_sequences() {
let headers = HashMap::from([(
"Content-Type".to_string(),
"application/x-www-form-urlencoded".to_string(),
)]);
let form = Imposter::parse_form_data(&headers, Some("k=%FF")).expect("form parsed");
assert_eq!(
form.get("k"),
Some(&vec!["%FF".to_string()]),
"an undecodable value must pass through raw, not become empty"
);
let form = Imposter::parse_form_data(&headers, Some("%FF=v")).expect("form parsed");
assert_eq!(
form.get("%FF"),
Some(&vec!["v".to_string()]),
"an undecodable key must pass through raw, not collapse to an empty key"
);
let form = Imposter::parse_form_data(&headers, Some("k=hello%20world")).expect("parsed");
assert_eq!(
form.get("k"),
Some(&vec!["hello world".to_string()]),
"valid sequences must still decode"
);
}
// Issue #1607: a form body decodes `+` as a space, as Node's `querystring.parse` does. Same
// table as `parse_query_string_tests::a_plus_is_a_space_in_keys_and_values`.
#[test]
fn parse_form_data_decodes_a_plus_as_a_space() {
let headers = HashMap::from([(
"Content-Type".to_string(),
"application/x-www-form-urlencoded".to_string(),
)]);
let cases = [
("q=x+y%21", "q", "x y!"),
("a+b=1", "a b", "1"),
("q=1%2B1", "q", "1+1"),
("q=1+1", "q", "1 1"),
("q=%2B+%20", "q", "+ "),
("r=a+%ZZ", "r", "a %ZZ"),
("k=%FF", "k", "%FF"),
];
for (body, key, expected) in cases {
let form = Imposter::parse_form_data(&headers, Some(body)).expect("form parsed");
assert_eq!(
form.get(key),
Some(&vec![expected.to_string()]),
"body {body:?}"
);
}
}
// Issue #1026: `parse_form_data` is generic over `RequestHeaders` so the verify API can hand it
// a recorded request's multi-value header map directly, instead of collapsing it last-wins
// first. Both impls must behave identically for a well-formed request.
#[test]
fn parse_form_data_accepts_the_multi_value_header_shape() {
fn header(name: &str, values: &[&str]) -> crate::imposter::Headers {
crate::imposter::Headers::from([(
name.to_string(),
values.iter().map(|v| (*v).to_string()).collect(),
)])
}
const FORM: &str = "application/x-www-form-urlencoded";
let form = Imposter::parse_form_data(&header("Content-Type", &[FORM]), Some("a=1&b=2"))
.expect("form parsed");
assert_eq!(form.get("a"), Some(&vec!["1".to_string()]));
assert_eq!(form.get("b"), Some(&vec!["2".to_string()]));
// Content-Type is single-valued (RFC 9110), so a repeated one is a malformed request:
// take the first value rather than let a stray second one suppress the parse.
assert_eq!(
Imposter::parse_form_data(&header("Content-Type", &[FORM, "text/plain"]), Some("a=1"))
.expect("first Content-Type wins")
.get("a"),
Some(&vec!["1".to_string()])
);
// The header NAME lookup stays case-insensitive on this shape too.
assert!(Imposter::parse_form_data(&header("content-type", &[FORM]), Some("a=1")).is_some());
// A non-form Content-Type, and a name carrying no values at all, both yield None.
assert!(
Imposter::parse_form_data(&header("Content-Type", &["application/json"]), Some("a=1"))
.is_none()
);
assert!(Imposter::parse_form_data(&header("Content-Type", &[]), Some("a=1")).is_none());
}
// Issue #1451: `request.form` as Mountebank's `httpRequest.transform` builds it for scripts —
// present only for a non-empty urlencoded body.
#[test]
fn request_form_is_present_only_for_a_non_empty_urlencoded_body() {
let form_headers = HashMap::from([(
"Content-Type".to_string(),
"application/x-www-form-urlencoded".to_string(),
)]);
let json_headers =
HashMap::from([("Content-Type".to_string(), "application/json".to_string())]);
assert_eq!(Imposter::request_form(&form_headers, Some("")), None);
assert_eq!(Imposter::request_form(&form_headers, None), None);
assert_eq!(Imposter::request_form(&json_headers, Some("a=1")), None);
let form = Imposter::request_form(&form_headers, Some("a=1&b=2")).expect("form");
let expected: crate::util::MultiValueMap = [
("a".to_string(), vec!["1".to_string()]),
("b".to_string(), vec!["2".to_string()]),
]
.into_iter()
.collect();
assert_eq!(form, expected);
let charset = HashMap::from([(
"Content-Type".to_string(),
"application/x-www-form-urlencoded; charset=utf-8".to_string(),
)]);
let form = Imposter::request_form(&charset, Some("a=1")).expect("form with a charset");
assert_eq!(
form.get("a").and_then(|v| v.first()).map(String::as_str),
Some("1")
);
let form = Imposter::request_form(&form_headers, Some("a%20b=1")).expect("form");
assert_eq!(
form.get("a b").and_then(|v| v.first()).map(String::as_str),
Some("1"),
"{form:?}"
);
}
// Issue #475: run_flow_blocking must be transparent — on the default (non-blocking) backend it
// runs the closure inline and returns its result faithfully (Ok value, Err propagated), and it
// hands the closure a usable &Imposter so a real flow-store call works through it.
#[tokio::test]
async fn run_flow_blocking_is_transparent_inline() {
let imp = imposter(json!([]));
assert!(
!imp.flow_store.is_blocking(),
"default backend is non-blocking"
);
let value = imp
.run_flow_blocking(|_| Ok(42_i64))
.await
.expect("closure ok");
assert_eq!(value, 42);
let err = imp
.run_flow_blocking(|_| Err::<i64, _>(anyhow::anyhow!("boom")))
.await
.expect_err("closure err propagates");
assert!(err.to_string().contains("boom"));
// The closure receives a working &Imposter: an unset scenario reads the initial state.
let state = imp
.run_flow_blocking(|i| i.scenario_state("flow-1", "sc"))
.await
.expect("scenario_state through helper");
assert_eq!(state, INITIAL_SCENARIO_STATE);
}
// Issue #480: the query is parsed once per request in the hot path (find_matching_stub_with_client)
// and threaded into predicate matching. Drive a VALUE-based query predicate through that real
// entry point to prove the threaded map carries the right keys AND values — not merely presence.
#[test]
fn hot_path_value_query_predicate_matches() {
let imp = imposter(json!([
{ "predicates": [{ "equals": { "query": { "status": "active" } } }],
"responses": [{ "is": { "statusCode": 200 } }] }
]));
let headers = no_headers();
let hit = imp
.find_matching_stub_with_client(
"GET",
"/x",
&headers,
Some("status=active"),
None,
None,
None,
)
.expect("no backend error");
assert_eq!(
hit.map(|(_, i)| i),
Some(0),
"a value-based query predicate must match via the once-per-request hoisted query map"
);
let miss = imp
.find_matching_stub_with_client(
"GET",
"/x",
&headers,
Some("status=inactive"),
None,
None,
None,
)
.expect("no backend error");
assert!(
miss.is_none(),
"the hoisted map must carry query VALUES, not just keys — a wrong value must not match"
);
}
/// A FlowStore that reports `is_blocking() == true` (delegating storage to an in-memory store)
/// so the spawn_blocking dispatch path and the blocking-backend offload decision are exercised
/// without a real networked store (issue #475).
struct BlockingProbeStore {
inner: crate::backends::inmemory::InMemoryFlowStore,
}
impl BlockingProbeStore {
fn new() -> Self {
Self {
inner: crate::backends::inmemory::InMemoryFlowStore::new(300),
}
}
}
impl crate::extensions::flow_state::FlowStore for BlockingProbeStore {
fn is_blocking(&self) -> bool {
true
}
fn get(&self, flow_id: &str, key: &str) -> anyhow::Result<Option<serde_json::Value>> {
self.inner.get(flow_id, key)
}
fn set(&self, flow_id: &str, key: &str, value: serde_json::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<&serde_json::Value>,
new: serde_json::Value,
) -> anyhow::Result<crate::extensions::flow_state::CasOutcome> {
self.inner.compare_and_set(flow_id, key, expected, new)
}
}
fn imposter_with_store(
stubs: serde_json::Value,
store: Arc<dyn crate::extensions::flow_state::FlowStore>,
) -> Arc<Imposter> {
let cfg = serde_json::from_value(json!({ "port": 0, "protocol": "http", "stubs": stubs }))
.expect("valid imposter config");
let mut imp = Imposter::new(cfg).expect("test imposter");
imp.flow_store = store;
Arc::new(imp)
}
/// A blocking store whose `get` annotates the way a networked store's error mapper does.
/// The point is the pairing: a store that annotates is also the kind that reports `is_blocking() == true` (issue #987).
struct AnnotatingBlockingStore {
inner: crate::backends::inmemory::InMemoryFlowStore,
}
impl AnnotatingBlockingStore {
fn new() -> Self {
Self {
inner: crate::backends::inmemory::InMemoryFlowStore::new(300),
}
}
}
impl crate::extensions::flow_state::FlowStore for AnnotatingBlockingStore {
fn is_blocking(&self) -> bool {
true
}
fn get(&self, flow_id: &str, key: &str) -> anyhow::Result<Option<serde_json::Value>> {
crate::extensions::decorate::annotate("flowStore.get", "probe".to_string());
self.inner.get(flow_id, key)
}
fn set(&self, flow_id: &str, key: &str, value: serde_json::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<&serde_json::Value>,
new: serde_json::Value,
) -> anyhow::Result<crate::extensions::flow_state::CasOutcome> {
self.inner.compare_and_set(flow_id, key, expected, new)
}
}
// Issue #987, AC3 + edge case 10: an annotation made by the store on the blocking pool thread
// must reach the request's annotation scope. Red before the fix: `annotate` runs on a thread
// with no task-local, so the scope collects nothing.
#[tokio::test]
async fn run_flow_blocking_replays_annotations_from_the_blocking_thread() {
use crate::extensions::decorate::with_annotation_scope;
let imp = imposter_with_store(json!([]), Arc::new(AnnotatingBlockingStore::new()));
assert!(imp.flow_store.is_blocking());
let (result, notes) = with_annotation_scope(async {
imp.run_flow_blocking(|i| i.flow_store.get("flow-1", "k"))
.await
})
.await;
assert!(result.is_ok(), "the read itself must still succeed");
assert_eq!(
notes,
vec![("flowStore.get", "probe".to_string())],
"an annotation made on the blocking thread must reach the request scope"
);
}
// Edge case 9: the inline (non-blocking) path annotates directly and must not be double-counted
// by the replay. Green before and after — it guards the fix against over-collecting.
#[tokio::test]
async fn inline_path_annotates_exactly_once() {
use crate::extensions::decorate::with_annotation_scope;
struct AnnotatingInlineStore {
inner: crate::backends::inmemory::InMemoryFlowStore,
}
impl crate::extensions::flow_state::FlowStore for AnnotatingInlineStore {
fn is_blocking(&self) -> bool {
false
}
fn get(&self, flow_id: &str, key: &str) -> anyhow::Result<Option<serde_json::Value>> {
crate::extensions::decorate::annotate("flowStore.get", "inline".to_string());
self.inner.get(flow_id, key)
}
fn set(
&self,
flow_id: &str,
key: &str,
value: serde_json::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<&serde_json::Value>,
new: serde_json::Value,
) -> anyhow::Result<crate::extensions::flow_state::CasOutcome> {
self.inner.compare_and_set(flow_id, key, expected, new)
}
}
let imp = imposter_with_store(
json!([]),
Arc::new(AnnotatingInlineStore {
inner: crate::backends::inmemory::InMemoryFlowStore::new(300),
}),
);
assert!(!imp.flow_store.is_blocking());
let ((), notes) = with_annotation_scope(async {
let _ = imp
.run_flow_blocking(|i| i.flow_store.get("flow-1", "k"))
.await;
})
.await;
assert_eq!(
notes,
vec![("flowStore.get", "inline".to_string())],
"the inline path must annotate exactly once — no replay double-count"
);
}
// Issue #475: on a blocking backend, run_flow_blocking must dispatch the closure to a
// spawn_blocking pool thread (off the caller) and still round-trip its result / propagate a
// panic as a JoinError-shaped error. This covers the spawn_blocking arm the inline test can't.
#[tokio::test]
async fn run_flow_blocking_dispatches_off_thread_on_blocking_backend() {
let imp = imposter_with_store(json!([]), Arc::new(BlockingProbeStore::new()));
assert!(imp.flow_store.is_blocking());
let caller_thread = std::thread::current().id();
let ran_on = imp
.run_flow_blocking(|_| Ok(std::thread::current().id()))
.await
.expect("ok");
assert_ne!(
ran_on, caller_thread,
"a blocking backend must run the closure off the caller thread"
);
assert_eq!(imp.run_flow_blocking(|_| Ok(7_i64)).await.expect("ok"), 7);
let err = imp
.run_flow_blocking(|_| -> anyhow::Result<i64> { panic!("boom-in-task") })
.await
.expect_err("panic in the blocking task must surface as an error");
assert!(
err.to_string().contains("flow-store task panicked"),
"got: {err}"
);
}
// Issue #475: a scenario-gated stub on a blocking backend must still match — the bounded
// matcher's `has_scenario_gate && is_blocking` decision offloads the whole pass (incl. the gate
// read) to spawn_blocking, taking the no-deadline branch. This is the crux the fix protects.
#[tokio::test]
async fn scenario_gated_stub_matches_through_blocking_offload() {
let imp = imposter_with_store(
json!([{
"predicates": [{ "equals": { "path": "/x" } }],
"scenarioName": "sc",
"requiredScenarioState": INITIAL_SCENARIO_STATE,
"responses": [{ "is": { "statusCode": 200 } }]
}]),
Arc::new(BlockingProbeStore::new()),
);
assert!(imp.snapshot().has_scenario_gate());
assert!(imp.flow_store.is_blocking());
let matched = imp
.find_matching_stub_with_client_bounded(
"GET",
"/x",
&no_headers(),
None,
None,
None,
None,
std::time::Duration::from_secs(5),
)
.await
.expect("matching ok");
assert!(
matched.is_some(),
"scenario-gated stub at its initial state must match via the blocking offload path"
);
}
// AC3 (happy): an inject predicate matches/misses correctly through the bounded path.
#[cfg(feature = "javascript")]
#[tokio::test]
async fn inject_predicate_matching_bounded_matches() {
let imp = imposter(json!([{
"predicates": [{ "inject": "function (config) { return config.request.path === '/hit'; }" }],
"responses": [{ "is": { "statusCode": 200 } }]
}]));
let matched = imp
.find_matching_stub_with_client_bounded(
"GET",
"/hit",
&no_headers(),
None,
None,
None,
None,
// Never-fire sentinel: this asserts the inject *outcome*, not latency. It is 600s
// (not a round 60s) because this trivial inject can queue behind the process-global
// mb_js_pool workers (js_engine.rs:393, 4 on CI) while concurrent runaway-script
// tests park every worker until the 10M-iteration loop cap throws — tens of seconds
// on a loaded/unoptimized-build runner. A genuine hang is still bounded (the CI job
// timeout backstops); don't tidy this back down. See #726.
Duration::from_millis(600_000),
)
.await
.expect("matcher must not error");
assert!(
matched.is_some(),
"inject predicate returning true must match"
);
let missed = imp
.find_matching_stub_with_client_bounded(
"GET",
"/miss",
&no_headers(),
None,
None,
None,
None,
Duration::from_millis(600_000), // never-fire sentinel, see the note above (#726)
)
.await
.expect("matcher must not error");
assert!(
missed.is_none(),
"inject predicate returning false must not match"
);
}
// AC3: a runaway inject predicate times out near the deadline instead of blocking a
// runtime worker for its full duration.
#[cfg(feature = "javascript")]
#[tokio::test]
async fn inject_predicate_matching_times_out() {
let imp = imposter(json!([{
"predicates": [{ "inject": "function (config) { var i = 0; while (i < 100000000) { i += 1; } return true; }" }],
"responses": [{ "is": { "statusCode": 200 } }]
}]));
let start = std::time::Instant::now();
let res = imp
.find_matching_stub_with_client_bounded(
"GET",
"/hang",
&no_headers(),
None,
None,
None,
None,
Duration::from_millis(25),
)
.await;
let Err(err) = res else {
panic!("a runaway inject predicate must error, not hang the matching pass")
};
let timeout = err
.downcast_ref::<crate::scripting::ScriptTimeoutError>()
.unwrap_or_else(|| {
panic!(
"a matching timeout must be shaped as ScriptTimeoutError so the handler \
serves a 504 the client can tell apart from a broken predicate; got: {err}"
)
});
assert_eq!(timeout.hook, "predicate inject");
assert_eq!(timeout.timeout_ms, 25, "reports the configured deadline");
assert!(
start.elapsed() < Duration::from_secs(3),
"must return near the configured deadline, not after the loop cap"
);
}
// AC3 (fast path): a scriptless imposter never routes through spawn_blocking — the gate is
// the precomputed has_inject flag, and matching succeeds through the bounded entry point.
#[tokio::test]
async fn scriptless_matching_bounded_stays_inline() {
let imp = imposter(json!([{
"predicates": [{ "equals": { "path": "/plain" } }],
"responses": [{ "is": { "statusCode": 200 } }]
}]));
assert!(
!imp.snapshot().has_inject(),
"a scriptless stub set must not set the has_inject gate"
);
let matched = imp
.find_matching_stub_with_client_bounded(
"GET",
"/plain",
&no_headers(),
None,
None,
None,
None,
// Scriptless: takes the inline path and never arms the deadline. Kept at the same
// 600s never-fire sentinel as the inject tests above for uniformity (#726).
Duration::from_millis(600_000),
)
.await
.expect("matcher must not error");
assert!(matched.is_some());
}
// ---- issue #711: parse the XML DOM once per request, compile selectors once ----------
use crate::behaviors::counters;
// Each stub extracts a DIFFERENT node via its own XPath selector, then `equals`-checks the
// extracted (effective) body against the fixed string "MATCH". In the body below only item 19
// holds "MATCH"; items 0..18 hold "x". So every stub's XPath predicate is *evaluated* (each
// extracts and compares — that's the DOM touch), but only stub 19 matches. Crucially this means
// first-match-wins does NOT short-circuit before stub 19, so all 20 XPath evaluations run —
// which is what makes the DOM-parse count meaningful: 20 parses before #711, one after.
fn xpath_stub(i: usize) -> serde_json::Value {
json!({
"predicates": [{ "equals": { "body": "MATCH" },
"xpath": { "selector": format!("//item[@id='{i}']") } }],
"responses": [{ "is": { "statusCode": 200 } }]
})
}
// AC1: the XML body is parsed into a DOM exactly ONCE per request, no matter how many XPath
// predicates/stubs evaluate it. Before #711 every XPath predicate evaluation re-parsed the body
// (N stubs sharing a path = N DOM parses); the whole point is one parse shared across the match.
#[test]
fn one_dom_parse_per_request_many_xpath_stubs() {
let stubs: Vec<serde_json::Value> = (0..20).map(xpath_stub).collect();
let imp = imposter(json!(stubs));
// Only item 19 holds "MATCH"; the rest hold "x", so stubs 0..18 evaluate their XPath (a DOM
// touch) but don't match, and evaluation continues to stub 19.
let body = format!(
"<root>{}</root>",
(0..20)
.map(|i| format!(
"<item id='{i}'>{}</item>",
if i == 19 { "MATCH" } else { "x" }
))
.collect::<String>()
);
let headers = no_headers();
counters::reset();
let hit = imp
.find_matching_stub_with_client("POST", "/x", &headers, None, Some(&body), None, None)
.expect("no backend error");
assert_eq!(
hit.map(|(_, i)| i),
Some(19),
"only the last XPath stub matches; the earlier 19 evaluate their XPath but don't match"
);
assert_eq!(
counters::dom_parses(),
1,
"the DOM must be parsed exactly once for the whole request, not once per XPath predicate"
);
}
// Issue #1257 on the request path: an XPath predicate whose selector picks several nodes
// matches when any of them satisfies it, against the request's shared DOM (parsed once).
#[test]
fn xpath_predicate_matches_any_selected_node_on_the_shared_dom() {
let imp = imposter(json!([
{ "predicates": [{ "equals": { "body": "bob" }, "xpath": { "selector": "//user/name" } }],
"responses": [{ "is": { "statusCode": 200 } }] }
]));
let body = "<users><user><name>ann</name></user><user><name>bob</name></user></users>";
let headers = no_headers();
counters::reset();
let hit = imp
.find_matching_stub_with_client("POST", "/x", &headers, None, Some(body), None, None)
.expect("no backend error");
assert_eq!(hit.map(|(_, i)| i), Some(0));
assert_eq!(counters::dom_parses(), 1);
}
// AC1 boundary: a request that touches no XPath predicate must not parse a DOM at all — the
// parse is lazy, paid only when an XPath predicate is actually evaluated.
#[test]
fn no_dom_parse_when_no_xpath_touched() {
let imp = imposter(json!([
{ "predicates": [{ "equals": { "path": "/a" } }],
"responses": [{ "is": { "statusCode": 200 } }] }
]));
let headers = no_headers();
counters::reset();
let _ = imp
.find_matching_stub_with_client("GET", "/a", &headers, None, Some("<r/>"), None, None)
.expect("no backend error");
assert_eq!(
counters::dom_parses(),
0,
"no XPath predicate touched → the DOM must never be parsed"
);
}
// Issue #1442: a JSON request body no stub reads is never parsed — matching used to parse every
// body up front, so a large one cost its whole tree even against path-only stubs.
#[test]
fn no_json_parse_when_no_stub_reads_the_body() {
let imp = imposter(json!([
{ "predicates": [{ "equals": { "path": "/a" } }],
"responses": [{ "is": { "statusCode": 200 } }] }
]));
let headers = no_headers();
counters::reset();
let hit = imp
.find_matching_stub_with_client(
"POST",
"/a",
&headers,
None,
Some(r#"{"k":1}"#),
None,
None,
)
.expect("no backend error");
assert_eq!(hit.map(|(_, i)| i), Some(0));
assert_eq!(
counters::json_parses(),
0,
"no stub reads the body: never parsed"
);
}
// Issue #1442: a string body predicate compares text, so it needs no parse tree either.
#[test]
fn no_json_parse_for_string_body_predicates() {
let imp = imposter(json!([
{ "predicates": [{ "contains": { "body": "nope" } }],
"responses": [{ "is": { "statusCode": 200 } }] },
{ "predicates": [{ "matches": { "body": "^x" } }],
"responses": [{ "is": { "statusCode": 200 } }] },
{ "predicates": [{ "equals": { "body": r#"{"k":1}"# } }],
"responses": [{ "is": { "statusCode": 200 } }] }
]));
let headers = no_headers();
counters::reset();
let hit = imp
.find_matching_stub_with_client(
"POST",
"/a",
&headers,
None,
Some(r#"{"k":1}"#),
None,
None,
)
.expect("no backend error");
assert_eq!(hit.map(|(_, i)| i), Some(2));
assert_eq!(
counters::json_parses(),
0,
"string body predicates never parse"
);
}
// Issue #1442 with #290: once a stub does read the body it is parsed, and only once, however
// many body predicates (and the deepEquals body dimension) look at it afterwards.
#[test]
fn a_body_read_by_later_stubs_is_parsed_once() {
let imp = imposter(json!([
{ "predicates": [{ "equals": { "path": "/other" } }],
"responses": [{ "is": { "statusCode": 200 } }] },
{ "predicates": [{ "equals": { "body": { "k": 2 } } }],
"responses": [{ "is": { "statusCode": 200 } }] },
{ "predicates": [{ "deepEquals": { "body": { "k": 3 } } }],
"responses": [{ "is": { "statusCode": 200 } }] },
{ "predicates": [{ "equals": { "body": { "k": 1 } } }, { "exists": { "body": { "k": true } } }],
"responses": [{ "is": { "statusCode": 200 } }] }
]));
let headers = no_headers();
counters::reset();
let hit = imp
.find_matching_stub_with_client(
"POST",
"/a",
&headers,
None,
Some(r#"{"k":1}"#),
None,
None,
)
.expect("no backend error");
assert_eq!(hit.map(|(_, i)| i), Some(3));
assert_eq!(
counters::json_parses(),
1,
"parsed once for the whole request"
);
}
// AC2: an XPath selector is compiled once and reused across requests — the per-request compile
// (Factory::build) is gone. Drive the same XPath stub through several requests; after the first
// warms the cache, no further compiles occur.
#[test]
fn xpath_compiled_once_across_requests() {
let imp = imposter(json!([xpath_stub(7)]));
let body = "<root><item id='7'>v7</item></root>";
let headers = no_headers();
counters::reset();
for _ in 0..5 {
let _ = imp
.find_matching_stub_with_client(
"POST",
"/x",
&headers,
None,
Some(body),
None,
None,
)
.expect("no backend error");
}
assert!(
counters::xpath_compiles() <= 1,
"the XPath selector must be compiled at most once across 5 identical requests, not per \
request (saw {})",
counters::xpath_compiles()
);
}
// AC2: same for JSONPath — the selector string is compiled once, not re-parsed per request.
#[test]
fn jsonpath_compiled_once_across_requests() {
let imp = imposter(json!([
{ "predicates": [{ "equals": { "body": "42" },
"jsonpath": { "selector": "$.a.b" } }],
"responses": [{ "is": { "statusCode": 200 } }] }
]));
let body = r#"{"a":{"b":42}}"#;
let headers = no_headers();
counters::reset();
for _ in 0..5 {
let _ = imp
.find_matching_stub_with_client(
"POST",
"/x",
&headers,
None,
Some(body),
None,
None,
)
.expect("no backend error");
}
assert!(
counters::jsonpath_compiles() <= 1,
"the JSONPath selector must be compiled at most once across 5 identical requests (saw {})",
counters::jsonpath_compiles()
);
}
// Semantics unchanged: the parse-once / compile-once XPath path returns exactly what a
// per-call parse would. A namespaced selector is included because the namespace map is part of
// the XPath cache key — a cache that ignored it would cross-contaminate.
#[test]
fn xpath_dom_once_matches_per_call_semantics() {
let imp = imposter(json!([
{ "predicates": [{ "equals": { "body": "found" },
"xpath": { "selector": "//x:v", "ns": { "x": "urn:e" } } }],
"responses": [{ "is": { "statusCode": 200 } }] },
{ "predicates": [{ "equals": { "body": "other" },
"xpath": { "selector": "//v" } }],
"responses": [{ "is": { "statusCode": 200 } }] },
]));
let headers = no_headers();
let ns_body = r#"<r xmlns:x="urn:e"><x:v>found</x:v></r>"#;
let plain_body = "<r><v>other</v></r>";
assert_eq!(
imp.find_matching_stub_with_client(
"POST",
"/x",
&headers,
None,
Some(ns_body),
None,
None
)
.expect("no error")
.map(|(_, i)| i),
Some(0),
"namespaced XPath resolves against its ns map"
);
assert_eq!(
imp.find_matching_stub_with_client(
"POST",
"/x",
&headers,
None,
Some(plain_body),
None,
None
)
.expect("no error")
.map(|(_, i)| i),
Some(1),
"plain XPath still resolves — the ns-keyed cache did not cross-contaminate"
);
}
// Fix 3: JSONPath predicate matching reuses the once-parsed request body and still returns the
// correct extraction. (The distinct concern — that the *effective body* after extraction is not
// the raw parse — stays guarded by `deep_equals_with_jsonpath_selector_uses_extracted_body_not_raw_parse`
// in predicates::mod.)
#[test]
fn jsonpath_reuses_parsed_body() {
let imp = imposter(json!([
{ "predicates": [{ "equals": { "body": "hello" },
"jsonpath": { "selector": "$.msg" } }],
"responses": [{ "is": { "statusCode": 200 } }] }
]));
let headers = no_headers();
let hit = imp
.find_matching_stub_with_client(
"POST",
"/x",
&headers,
None,
Some(r#"{"msg":"hello"}"#),
None,
None,
)
.expect("no error");
assert_eq!(hit.map(|(_, i)| i), Some(0));
}
}
/// Issue #1388: which writes through [`ScenarioStampingStore`] are stamped as a transition of a
/// scenario gating a conditional stub.
#[cfg(test)]
mod scenario_stamping_tests {
use super::*;
use serde_json::json;
/// An imposter whose scenario `S1` gates a conditional stub.
fn imposter() -> Imposter {
Imposter::new(
serde_json::from_value(json!({
"port": 0,
"protocol": "http",
"_rift": { "flowState": { "flowIdSource": "header:X-Session" } },
"stubs": [{
"scenarioName": "S1", "requiredScenarioState": "A",
"responses": [{
"is": { "body": "q" },
"_rift": { "conditional": { "etag": false, "lastModified": "load" } }
}]
}],
}))
.expect("valid imposter config"),
)
.expect("test imposter")
}
fn stamped(imp: &Imposter) -> bool {
imp.scenario_transitions().contains_key("S1")
}
// Absence reads as the initial state, so writing `Started` over nothing moves nothing.
#[test]
fn setting_the_initial_state_over_an_absent_key_is_not_a_transition() {
let imp = imposter();
imp.set_scenario_state("f", "S1", INITIAL_SCENARIO_STATE)
.expect("set");
assert!(!stamped(&imp));
}
#[test]
fn setting_the_state_a_scenario_has_is_not_a_transition() {
let imp = imposter();
imp.set_scenario_state("f", "S1", "A").expect("set");
assert!(stamped(&imp), "absent to `A` moved");
let first = imp.scenario_transitions();
imp.set_scenario_state("f", "S1", "A").expect("set");
assert_eq!(imp.scenario_transitions().get("S1"), first.get("S1"));
}
// A non-string state is what the write repairs, as `set_scenario_state` has always counted it.
#[test]
fn setting_over_an_unreadable_state_is_a_transition() {
let imp = imposter();
imp.flow_store.set("f", "S1", json!(7)).expect("seed");
imp.set_scenario_state("f", "S1", "A").expect("set");
assert!(stamped(&imp));
}
/// A store whose `set_key_ttl` keeps the trait's fail-loud default.
#[derive(Default)]
struct NoKeyTtl {
keys: parking_lot::Mutex<HashMap<(String, String), serde_json::Value>>,
}
impl FlowStore for NoKeyTtl {
fn get(&self, flow: &str, key: &str) -> anyhow::Result<Option<serde_json::Value>> {
Ok(self.keys.lock().get(&(flow.into(), key.into())).cloned())
}
fn set(&self, flow: &str, key: &str, value: serde_json::Value) -> anyhow::Result<()> {
self.keys.lock().insert((flow.into(), key.into()), value);
Ok(())
}
fn exists(&self, flow: &str, key: &str) -> anyhow::Result<bool> {
Ok(self.keys.lock().contains_key(&(flow.into(), key.into())))
}
fn delete(&self, flow: &str, key: &str) -> anyhow::Result<()> {
self.keys.lock().remove(&(flow.into(), key.into()));
Ok(())
}
fn increment(&self, _: &str, _: &str) -> anyhow::Result<i64> {
Ok(0)
}
fn set_ttl(&self, _: &str, _: i64) -> anyhow::Result<()> {
Ok(())
}
}
// A third-party store must not start failing deletes: it deletes, and over-approximates.
#[test]
fn a_delete_on_a_store_without_key_ttl_still_deletes_and_stamps() {
let mut imp = imposter();
let store = Arc::new(NoKeyTtl::default());
store.set("f", "S1", json!("A")).expect("seed");
imp.flow_store = store.clone();
imp.delete_scenario_state("f", "S1").expect("delete");
assert!(!store.exists("f", "S1").expect("exists"));
assert!(stamped(&imp));
}
/// A store whose reads fail, or whose compare-and-set always loses.
#[derive(Default)]
struct Stubborn {
inner: NoKeyTtl,
unreadable: bool,
cas_tries: std::sync::atomic::AtomicUsize,
}
impl FlowStore for Stubborn {
fn get(&self, flow: &str, key: &str) -> anyhow::Result<Option<serde_json::Value>> {
if self.unreadable {
anyhow::bail!("unreadable");
}
self.inner.get(flow, key)
}
fn set(&self, flow: &str, key: &str, value: serde_json::Value) -> anyhow::Result<()> {
self.inner.set(flow, key, value)
}
fn exists(&self, flow: &str, key: &str) -> anyhow::Result<bool> {
self.inner.exists(flow, key)
}
fn delete(&self, flow: &str, key: &str) -> anyhow::Result<()> {
self.inner.delete(flow, key)
}
fn increment(&self, _: &str, _: &str) -> anyhow::Result<i64> {
Ok(0)
}
fn set_ttl(&self, _: &str, _: i64) -> anyhow::Result<()> {
Ok(())
}
fn compare_and_set(
&self,
_: &str,
_: &str,
_: Option<&serde_json::Value>,
_: serde_json::Value,
) -> anyhow::Result<CasOutcome> {
self.cas_tries
.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
Ok(CasOutcome::Conflict(Some(json!("A"))))
}
}
// A key that keeps moving is written anyway, and counted as moved, after a bounded number of tries.
#[test]
fn a_set_that_keeps_losing_writes_and_stamps_after_its_cap() {
let mut imp = imposter();
let store = Arc::new(Stubborn::default());
imp.flow_store = store.clone();
imp.set_scenario_state("f", "S1", "A").expect("set");
assert_eq!(
store.cas_tries.load(std::sync::atomic::Ordering::SeqCst),
MAX_SET_ATTEMPTS
);
assert_eq!(store.get("f", "S1").expect("get"), Some(json!("A")));
assert!(stamped(&imp));
}
// An unreadable value is what the write repairs, so it must not block it.
#[test]
fn a_set_over_an_unreadable_store_writes_and_stamps() {
let mut imp = imposter();
let store = Arc::new(Stubborn {
unreadable: true,
..Stubborn::default()
});
imp.flow_store = store.clone();
imp.set_scenario_state("f", "S1", "A").expect("set");
assert_eq!(store.cas_tries.load(std::sync::atomic::Ordering::SeqCst), 0);
assert_eq!(store.inner.get("f", "S1").expect("get"), Some(json!("A")));
assert!(stamped(&imp));
}
// A delete that found nothing moved nothing.
#[test]
fn deleting_an_absent_key_is_not_a_transition() {
let imp = imposter();
imp.delete_scenario_state("f", "S1").expect("delete");
ScenarioStampingStore::new(&imp)
.delete("f", "S1")
.expect("delete");
assert!(!stamped(&imp));
}
#[test]
fn a_compare_and_set_that_loses_is_not_a_transition() {
let imp = imposter();
let store = ScenarioStampingStore::new(&imp);
let outcome = store
.compare_and_set("f", "S1", Some(&json!("B")), json!("A"))
.expect("cas");
assert!(matches!(outcome, CasOutcome::Conflict(_)));
assert!(!stamped(&imp));
}
#[test]
fn a_compare_and_set_that_applies_is_a_transition() {
let imp = imposter();
let store = ScenarioStampingStore::new(&imp);
let outcome = store
.compare_and_set("f", "S1", None, json!("A"))
.expect("cas");
assert!(matches!(outcome, CasOutcome::Applied));
assert!(stamped(&imp));
}
#[test]
fn an_increment_of_a_scenario_key_is_a_transition() {
let imp = imposter();
ScenarioStampingStore::new(&imp)
.increment("f", "S1")
.expect("increment");
assert!(stamped(&imp));
}
// A zero TTL deletes at once, so it is a delete.
#[test]
fn a_zero_key_ttl_on_a_scenario_key_is_a_transition() {
let imp = imposter();
imp.flow_store.set("f", "S1", json!("A")).expect("seed");
let deleted = ScenarioStampingStore::new(&imp)
.set_key_ttl("f", "S1", 0)
.expect("ttl");
assert!(deleted);
assert!(stamped(&imp));
}
#[test]
fn a_zero_flow_ttl_clears_and_is_a_transition() {
let imp = imposter();
imp.flow_store.set("f", "S1", json!("A")).expect("seed");
ScenarioStampingStore::new(&imp)
.set_ttl("f", 0)
.expect("ttl");
assert_eq!(imp.flow_store.get("f", "S1").expect("read"), None);
assert!(stamped(&imp));
}
// A positive TTL only schedules expiry: nothing changes now, so nothing is stamped.
#[test]
fn a_positive_ttl_is_not_a_transition() {
let imp = imposter();
imp.flow_store.set("f", "S1", json!("A")).expect("seed");
let store = ScenarioStampingStore::new(&imp);
store.set_key_ttl("f", "S1", 60).expect("key ttl");
store.set_ttl("f", 60).expect("flow ttl");
assert!(!stamped(&imp));
}
#[test]
fn reads_and_counts_pass_through() {
let imp = imposter();
imp.flow_store.set("f", "k", json!(1)).expect("seed");
let store = ScenarioStampingStore::new(&imp);
assert_eq!(store.get("f", "k").expect("get"), Some(json!(1)));
assert!(store.exists("f", "k").expect("exists"));
assert_eq!(
store.entry_count("f").expect("count"),
imp.flow_store.entry_count("f").expect("count")
);
assert!(!stamped(&imp));
}
}