goose 0.19.0

A load testing framework inspired by Locust.
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
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
//! # Goose
//!
//! Have you ever been attacked by a goose?
//!
//! Goose is a load testing framework inspired by [Locust](https://locust.io/).
//! User behavior is defined with standard Rust code.
//!
//! Goose load tests, called Goose Attacks, are built by creating an application
//! with Cargo, and declaring a dependency on the Goose library.
//!
//! Goose uses [`reqwest`](https://docs.rs/reqwest/) to provide a convenient HTTP
//! client.
//!
//! ## Documentation
//!
//! - [The Goose Book](https://book.goose.rs)
//! - [Developer documentation](https://docs.rs/goose/)
//! - [Blogs and more](https://tag1.com/goose/)
//!   - [Goose vs Locust and jMeter](https://www.tag1consulting.com/blog/jmeter-vs-locust-vs-goose)
//!   - [Real-life load testing with Goose](https://www.tag1consulting.com/blog/real-life-goose-load-testing)
//!   - [Optimizing Goose performance](https://www.tag1consulting.com/blog/golden-goose-egg-compile-time-adventure)
//!
//! ## License
//!
//! Copyright 2020-2023 Jeremy Andrews
//!
//! Licensed under the Apache License, Version 2.0 (the "License");
//! you may not use this file except in compliance with the License.
//! You may obtain a copy of the License at
//!
//! <http://www.apache.org/licenses/LICENSE-2.0>
//!
//! Unless required by applicable law or agreed to in writing, software
//! distributed under the License is distributed on an "AS IS" BASIS,
//! WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//! See the License for the specific language governing permissions and
//! limitations under the License.

#[macro_use]
extern crate log;

pub mod client;
pub mod config;
pub mod controller;
#[cfg(feature = "dashboard")]
mod dashboard;
pub mod goose;
mod graph;
pub mod logger;
pub mod metrics;
pub mod prelude;
mod report;
mod run_shape;
mod runs;
pub mod test_plan;
pub mod threshold;
mod throttle;
mod user;
pub mod util;

use lazy_static::lazy_static;
use rand::prelude::*;
use std::collections::{hash_map::DefaultHasher, BTreeMap, HashMap, HashSet};
use std::hash::{Hash, Hasher};
use std::sync::{atomic::AtomicUsize, Arc, Mutex, RwLock};
use std::time::{self, Duration};
use std::{fmt, io};

use crate::config::{GooseConfiguration, GooseDefaults};
use crate::controller::{ControlRequest, ControllerProtocol};
use crate::goose::{GooseUser, GooseUserCommand, Scenario, Transaction, TransactionName};
use crate::graph::GraphData;
use crate::logger::{GooseLoggerJoinHandle, GooseLoggerTx};
use crate::metrics::{
    GooseMetric, GooseMetrics, GooseRequestCounterRegistry, MetricsCommand, MetricsProcessor,
};
use crate::test_plan::{TestPlan, TestPlanHistory, TestPlanStepAction};

lazy_static! {
    // WORKER_ID is used to identify different works when running a gaggle.
    static ref WORKER_ID: AtomicUsize = AtomicUsize::new(0);
    // The reason the killswitch was first triggered (by Ctrl-C or by
    // `trigger_killswitch`), or None while it is not triggered. Reset each
    // time a load test starts.
    static ref CANCELED: Arc<RwLock<Option<String>>> = Arc::new(RwLock::new(None));
}

/// Trigger the killswitch to stop the load test run.
///
/// This function records the reason and marks the killswitch as triggered,
/// which will cause the test to stop gracefully at the next check point. Only
/// the first reason is kept; later calls change nothing until the killswitch
/// is reset when the next load test starts.
///
/// # Arguments
///
/// * `reason` - A string describing why the test is being stopped
///
/// # Example
///
/// ```
/// use goose::trigger_killswitch;
///
/// // Stop the test due to high error rate
/// trigger_killswitch("Error rate exceeded 50% threshold");
/// ```
pub fn trigger_killswitch(reason: &str) {
    let mut canceled = match CANCELED.write() {
        Ok(canceled) => canceled,
        // If the lock is poisoned, we can still write to it
        Err(poisoned) => poisoned.into_inner(),
    };
    if canceled.is_none() {
        info!("Killswitch triggered: {reason}");
        *canceled = Some(reason.to_string());
    }
}

/// Check if the killswitch has been triggered.
pub fn is_killswitch_triggered() -> bool {
    killswitch_reason().is_some()
}

/// The reason the killswitch was first triggered, if it has been.
pub(crate) fn killswitch_reason() -> Option<String> {
    match CANCELED.read() {
        Ok(canceled) => canceled.clone(),
        // If the lock is poisoned, we can still read from it
        Err(poisoned) => poisoned.into_inner().clone(),
    }
}

/// Clear the killswitch.
///
/// Goose clears it itself each time a load test starts, so a new run does not
/// inherit the previous run's cancel. A test that triggers the killswitch can
/// call this when it is done, so tests running after it in the same process
/// are not canceled.
pub fn reset_killswitch() {
    match CANCELED.write() {
        Ok(mut canceled) => *canceled = None,
        Err(poisoned) => *poisoned.into_inner() = None,
    }
}

/// Internal representation of a weighted transaction list.
type WeightedTransactions = Vec<(usize, TransactionName)>;

/// Internal representation of unsequenced transactions.
type UnsequencedTransactions = Vec<Transaction>;
/// Internal representation of sequenced transactions.
type SequencedTransactions = BTreeMap<usize, Vec<Transaction>>;

/// An enumeration of all errors a [`GooseAttack`](./struct.GooseAttack.html) can return.
#[derive(Debug)]
pub enum GooseError {
    /// Wraps a [`std::io::Error`](https://doc.rust-lang.org/std/io/struct.Error.html).
    Io(io::Error),
    /// Wraps a [`reqwest::Error`](https://docs.rs/reqwest/*/reqwest/struct.Error.html).
    Reqwest(reqwest::Error),
    /// Wraps a ['tokio::task::JoinError'](https://tokio-rs.github.io/tokio/doc/tokio/task/struct.JoinError.html).
    TokioJoin(tokio::task::JoinError),
    /// Wraps a ['serde_json::Error'](https://docs.rs/serde_json/*/serde_json/struct.Error.html).
    Serde(serde_json::Error),
    /// Failed attempt to use code that requires a compile-time feature be enabled.
    FeatureNotEnabled {
        /// The missing compile-time feature.
        feature: String,
        /// An optional explanation of the error.
        detail: String,
    },
    /// Failed to parse a hostname.
    InvalidHost {
        /// The invalid hostname that caused this error.
        host: String,
        /// An optional explanation of the error.
        detail: String,
        /// Wraps a [`url::ParseError`](https://docs.rs/url/*/url/enum.ParseError.html).
        parse_error: url::ParseError,
    },
    /// Invalid option or value specified, may only be invalid in context.
    InvalidOption {
        /// The invalid option that caused this error, may be only invalid in context.
        option: String,
        /// The invalid value that caused this error, may be only invalid in context.
        value: String,
        /// An optional explanation of the error.
        detail: String,
    },
    /// Invalid wait time specified.
    InvalidWaitTime {
        // The specified minimum wait time.
        min_wait: Duration,
        // The specified maximum wait time.
        max_wait: Duration,
        /// An optional explanation of the error.
        detail: String,
    },
    /// Invalid weight specified.
    InvalidWeight {
        // The specified weight.
        weight: usize,
        /// An optional explanation of the error.
        detail: String,
    },
    /// Invalid controller command. No longer returned: a Controller answers a
    /// command it refuses with a message, and the variant is kept for callers.
    InvalidControllerCommand {
        /// An optional explanation of the error.
        detail: String,
    },
    /// [`GooseAttack`](./struct.GooseAttack.html) has no [`Scenario`](./goose/struct.Scenario.html) defined.
    NoScenarios {
        /// An optional explanation of the error.
        detail: String,
    },
    /// The load test ran, and at least one `--threshold` failed. Every report was
    /// written first.
    ThresholdsFailed {
        /// The rules that failed, in the order they were given.
        failed: Vec<threshold::ThresholdResult>,
        /// The metrics of the run, as `execute()` returns them when every rule passes.
        metrics: ThresholdMetrics,
    },
}

/// The metrics of a run that failed a threshold, held by
/// [`GooseError::ThresholdsFailed`]. It reads as the [`GooseMetrics`] it holds, as in
/// `metrics.duration`, and its `Debug` leaves them out: a `main` that returns the
/// error prints it, and the metrics of a whole run would bury the rules that failed.
#[derive(Default)]
pub struct ThresholdMetrics(pub Box<GooseMetrics>);

impl std::ops::Deref for ThresholdMetrics {
    type Target = GooseMetrics;

    fn deref(&self) -> &GooseMetrics {
        &self.0
    }
}

impl fmt::Debug for ThresholdMetrics {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str("ThresholdMetrics { .. }")
    }
}
/// Implement a helper to provide a text description of all possible types of errors.
impl GooseError {
    fn describe(&self) -> &str {
        match *self {
            GooseError::Io(_) => "io::Error",
            GooseError::Reqwest(_) => "reqwest::Error",
            GooseError::Serde(_) => "serde_json::Error",
            GooseError::TokioJoin(_) => "tokio::task::JoinError",
            GooseError::FeatureNotEnabled { .. } => "required compile-time feature not enabled",
            GooseError::InvalidHost { .. } => "failed to parse hostname",
            GooseError::InvalidOption { .. } => "invalid option or value specified",
            GooseError::InvalidWaitTime { .. } => "invalid wait_time specified",
            GooseError::InvalidWeight { .. } => "invalid weight specified",
            GooseError::InvalidControllerCommand { .. } => "invalid controller command",
            GooseError::NoScenarios { .. } => "no scenarios defined",
            GooseError::ThresholdsFailed { .. } => "one or more thresholds failed",
        }
    }
}

/// Implement format trait to allow displaying errors.
impl fmt::Display for GooseError {
    // Implement display of error with `{}` marker.
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            GooseError::Io(ref source) => write!(f, "GooseError: {} ({})", self.describe(), source),
            GooseError::Reqwest(ref source) => {
                write!(f, "GooseError: {} ({})", self.describe(), source)
            }
            GooseError::TokioJoin(ref source) => {
                write!(f, "GooseError: {} ({})", self.describe(), source)
            }
            GooseError::InvalidHost {
                ref parse_error, ..
            } => write!(f, "GooseError: {} ({})", self.describe(), parse_error),
            GooseError::ThresholdsFailed { ref failed, .. } => {
                let failed = failed
                    .iter()
                    .map(|result| format!("{}, observed {}", result.rule, result.observed))
                    .collect::<Vec<_>>()
                    .join("; ");
                write!(f, "GooseError: {} ({})", self.describe(), failed)
            }
            _ => write!(f, "GooseError: {}", self.describe()),
        }
    }
}

// Define the lower level source of this error, if any.
impl std::error::Error for GooseError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match *self {
            GooseError::Io(ref source) => Some(source),
            GooseError::Reqwest(ref source) => Some(source),
            GooseError::TokioJoin(ref source) => Some(source),
            GooseError::InvalidHost {
                ref parse_error, ..
            } => Some(parse_error),
            _ => None,
        }
    }
}

/// Auto-convert Reqwest errors.
impl From<reqwest::Error> for GooseError {
    fn from(err: reqwest::Error) -> GooseError {
        GooseError::Reqwest(err)
    }
}

/// Auto-convert IO errors.
impl From<io::Error> for GooseError {
    fn from(err: io::Error) -> GooseError {
        GooseError::Io(err)
    }
}

/// Auto-convert TokioJoin errors.
impl From<tokio::task::JoinError> for GooseError {
    fn from(err: tokio::task::JoinError) -> GooseError {
        GooseError::TokioJoin(err)
    }
}

/// Auto-convert serde_json errors.
impl From<serde_json::Error> for GooseError {
    fn from(err: serde_json::Error) -> GooseError {
        GooseError::Serde(err)
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
/// A [`GooseAttack`](./struct.GooseAttack.html) load test operates in one (and only one)
/// of the following modes.
pub enum AttackMode {
    /// During early startup before one of the following modes gets assigned.
    Undefined,
    /// A single standalone process performing a load test.
    StandAlone,
}

#[derive(Copy, Clone, Debug, PartialEq, Eq)]
/// A [`GooseAttack`](./struct.GooseAttack.html) load test moves through each of the following
/// phases during a complete load test.
pub enum AttackPhase {
    /// No load test is running, configuration can be changed by a Controller.
    Idle,
    /// [`GooseUser`](./goose/struct.GooseUser.html)s are launching.
    Increase,
    /// [`GooseUser`](./goose/struct.GooseUser.html)s have been launched and are generating load.
    Maintain,
    /// [`GooseUser`](./goose/struct.GooseUser.html)s are stopping.
    Decrease,
    /// Exiting the load test.
    Shutdown,
}

/// Lowercase string for an [`AttackPhase`] (dashboard / control protocol).
pub(crate) fn attack_phase_str(phase: AttackPhase) -> &'static str {
    match phase {
        AttackPhase::Idle => "idle",
        AttackPhase::Increase => "increase",
        AttackPhase::Maintain => "maintain",
        AttackPhase::Decrease => "decrease",
        AttackPhase::Shutdown => "shutdown",
    }
}

/// The option a [`GooseError::InvalidOption`] names when no host is
/// configured; a refused Start reads its cause from it.
const NO_HOST_OPTION: &str = "--host";

/// The transactions that run with no scenario host, so need a default host.
const HOST_TRANSACTIONS: [&str; 2] = ["test_start", "test_stop"];

/// The detail of the [`NO_HOST_OPTION`] error refusing a run whose
/// `transaction`, one of [`HOST_TRANSACTIONS`], has no host; a refused Start
/// reads the transaction back from it.
fn no_transaction_host_detail(transaction: &str) -> String {
    format!(
        "A host must be defined via the --host option or the GooseAttack.set_default() function (no host defined for the {transaction} transaction)."
    )
}

/// The option a [`GooseError::InvalidOption`] names when there are no users
/// to start; a refused Start reads its cause from it.
const NO_USERS_OPTION: &str = "`configuration.users`";

/// Machine-readable outcome of a control action (soft success/failure).
///
/// Soft failures (expected rejections such as wrong phase or prepare failure)
/// are returned as `ok: false` with a stable `error` code. Hard failures (e.g.
/// `weight_scenario_users`, `reset_run_state` after a successful Start reply)
/// remain `Result::Err`.
///
/// Telnet and WebSocket show `ok` and `message`; the dashboard returns every
/// field.
#[derive(Debug, Clone)]
pub(crate) struct ControlOutcome {
    pub ok: bool,
    /// Stable code when !ok, for soft failures only: `invalid_phase`,
    /// `prepare_failed` or `conflicting_settings`, for example, and
    /// `invalid_report`, `report_busy` or `report_failed` from the report
    /// control routes.
    pub error: Option<&'static str>,
    /// Human message, the reply every front end shows.
    pub message: String,
    /// Attack phase *after* the soft attempt (lowercase).
    pub phase: String,
    /// From `GooseAttackRunState.active_users` at reply time.
    pub active_users: usize,
    /// Command-specific target user count when applicable.
    pub target_users: Option<usize>,
    /// The setting at fault in a refusal, when one is: `host`, `users`,
    /// `increase_rate`, `increase_time`, `decrease_rate`, `decrease_time`,
    /// `run_time` or `test_plan`.
    pub field: Option<&'static str>,
    /// The run settings after a dashboard settings command, applied or
    /// not, so the page that sent it has them before the next snapshot.
    #[cfg(feature = "dashboard")]
    pub settings: Option<Box<metrics::dashboard_snapshot::SnapshotSettings>>,
}

impl ControlOutcome {
    /// This outcome, naming `field` as the setting at fault.
    pub(crate) fn with_field(mut self, field: &'static str) -> Self {
        self.field = Some(field);
        self
    }
}

/// Result of the pre-reply portion of Start (Controller reply point).
///
/// Callers must reply to the client on either variant, then call
/// [`GooseAttack::control_start_finish`] only on [`ControlStartBegin::Accepted`].
pub(crate) enum ControlStartBegin {
    /// Soft rejection — do not change phase; reply false / ok:false.
    Rejected(ControlOutcome),
    /// Phase is already `Increase`; caller must reply success NOW, then call finish.
    Accepted(ControlOutcome),
}

#[derive(Clone, Debug, PartialEq, Eq)]
/// Used to define the order [`Scenario`](./goose/struct.Scenario.html)s and
/// [`Transaction`](./goose/struct.Transaction.html)s are allocated.
///
/// In order to configure the scheduler, and to see examples of the different scheduler
/// variants, review the
/// [`GooseAttack::set_scheduler`](./struct.GooseAttack.html#method.set_scheduler)
/// documentation.
pub enum GooseScheduler {
    /// Allocate one of each available type at a time (default).
    RoundRobin,
    /// Allocate in the order and weighting defined.
    Serial,
    /// Allocate in a random order.
    Random,
}

#[derive(Debug)]
/// Internal global run state for load test.
struct GooseAttackRunState {
    /// When the next [`GooseUser`](./goose/struct.GooseUser.html) is due to be
    /// increased or decreased: the time the first of the step was, plus one
    /// interval for each since.
    adjust_user_timer: std::time::Instant,
    /// How many milliseconds apart [`GooseUser`](./goose/struct.GooseUser.html)s
    /// are increased or decreased, at least 1 once a step has adjusted one; 0
    /// until then, so the step's first user is adjusted at once.
    adjust_user_in_ms: usize,
    /// A counter tracking how many [`GooseUser`](./goose/struct.GooseUser.html)s are running.
    active_users: usize,
    /// A counter tracking many users have been stopped.
    completed_users: usize,
    /// This variable accounts for time spent doing things which is then subtracted from
    /// the time sleeping to avoid an unintentional drift in events that are supposed to
    /// happen regularly.
    drift_timer: tokio::time::Instant,
    /// Unbounded sender used by all [`GooseUser`](./goose/struct.GooseUser.html)
    /// threads to send metrics to parent.
    all_threads_metrics_tx: flume::Sender<GooseMetric>,
    /// Sender for commands to the dedicated metrics processor task.
    metrics_cmd_tx: flume::Sender<MetricsCommand>,
    /// Handle for the dedicated metrics processor task.
    metrics_processor_handle: Option<tokio::task::JoinHandle<()>>,
    /// Unbounded sender used by all [`GooseUser`](./goose/struct.GooseUser.html)
    /// threads to alert the parent when they shutdown.
    all_threads_shutdown_tx: flume::Sender<usize>,
    /// Unbounded receiver used by [`GooseUser`](./goose.GooseUser.html) threads to notify
    /// the parent if they shut themselves down (for example if `--iterations` is reached).
    shutdown_rx: flume::Receiver<usize>,
    /// Optional unbounded receiver for logger thread, if enabled.
    logger_handle: GooseLoggerJoinHandle,
    /// Optional unbounded sender from all [`GooseUser`](./goose/struct.GooseUser.html)s
    /// to logger thread, if enabled.
    all_threads_logger_tx: GooseLoggerTx,
    /// Optional receiver for all [`GooseUser`](./goose/struct.GooseUser.html)s from
    /// throttle thread, if enabled.
    throttle_threads_tx: Option<flume::Sender<bool>>,
    /// Optional sender for throttle thread, if enabled.
    parent_to_throttle_tx: Option<flume::Sender<bool>>,
    /// The channel telnet and WebSocket send commands on, when either is
    /// enabled.
    controller_channel_rx: Option<flume::Receiver<ControlRequest>>,
    /// The channel dashboard control sends the same commands on, answered
    /// before the Controllers' so they can not delay it.
    dashboard_control_rx: Option<flume::Receiver<ControlRequest>>,
    /// Optional channel allowing the dashboard HTTP task to request snapshots.
    #[cfg(feature = "dashboard")]
    dashboard_channel_rx: Option<flume::Receiver<dashboard::DashboardRequest>>,
    /// Signals the dashboard SnapshotHub to emit SSE `event: closed` on final exit.
    #[cfg(feature = "dashboard")]
    dashboard_close_tx: Option<tokio::sync::watch::Sender<bool>>,
    /// Dashboard tabs connected to the event stream.
    #[cfg(feature = "dashboard")]
    dashboard_active_sse: Option<Arc<AtomicUsize>>,
    /// The folder of the run in progress, as the dashboard's report routes see it.
    #[cfg(feature = "dashboard")]
    dashboard_running_folder: Option<dashboard::RunningFolder>,
    /// The folder a bare `--goose-log` is open in, as the dashboard's report
    /// routes see it.
    #[cfg(feature = "dashboard")]
    dashboard_log_folder: Option<dashboard::RunningFolder>,
    /// The address the dashboard listens on, as logged at startup.
    #[cfg(feature = "dashboard")]
    dashboard_url: Option<String>,
    /// The dashboard HTTP server, stopped when the attack loop returns.
    #[cfg(feature = "dashboard")]
    dashboard_server: Option<dashboard::DashboardServer>,
    /// A flag tracking whether or not the header has been written when the metrics
    /// log is enabled.
    metrics_header_displayed: bool,
    /// When entering the idle phase use this flag to only display a message one time.
    idle_status_displayed: bool,
    /// Collection of all [`GooseUser`](./goose/struct.GooseUser.html) threads so they
    /// can be stopped later.
    users: Vec<tokio::task::JoinHandle<()>>,
    /// All unbounded senders to allow communication with
    /// [`GooseUser`](./goose/struct.GooseUser.html) threads.
    user_channels: Vec<flume::Sender<GooseUserCommand>>,
    /// The `(scenario index, user)` of the user each of `user_channels`
    /// reaches, so a metrics reset counts the users still running.
    running_users: Vec<(usize, usize)>,
    /// Timer tracking when to display running metrics, if enabled.
    running_metrics_timer: std::time::Instant,
    /// When the next `--threshold` check is due, or `None` while the thresholds are
    /// not checked: without any, under `--no-threshold-abort`, and before the run
    /// first enters Maintain.
    threshold_check_at: Option<std::time::Instant>,
    /// Boolean flag indicating if all [`GooseUser`](./goose/struct.GooseUser.html)s
    /// have been spawned.
    all_users_spawned: bool,
    /// Set of users that have shut themselves down.
    users_shutdown: HashSet<usize>,
    /// The telnet and WebSocket Controllers that bound their ports.
    listening_controllers: controller::ListeningControllers,
    /// Boolean flag indicating of Goose should shutdown after stopping a running load test.
    shutdown_after_stop: bool,
    /// Whether Ctrl-C has already started a cancel, so the main loop starts
    /// only one. Set once and never cleared: Ctrl-C always ends in Shutdown.
    canceling: bool,
    /// Whether a cancel (Stop, `shutdown`, Ctrl-C) is ramping this run down.
    /// Set in `cancel_attack` and cleared when the run reaches Idle, so a new
    /// Start begins without it; `canceling` above is set only on the Ctrl-C
    /// path and never cleared.
    stopping: bool,
    /// Shared registry of atomic request counters, keyed by `"METHOD path"`.
    /// User threads increment these directly; the parent reads them at report time.
    request_counter_registry: GooseRequestCounterRegistry,
    /// Shared epoch counter for coordinating batch validity across metrics resets.
    metrics_epoch: crate::metrics::MetricsEpoch,
}

impl GooseAttackRunState {
    /// Schedule the next user increase or decrease one `interval` after the
    /// last was due, or after now for the step's first, so a step adjusts its
    /// users at a steady rate from a fixed origin: a late wake up is caught up,
    /// never carried into every later user.
    fn schedule_next_adjust(&mut self, interval: Duration) {
        self.adjust_user_timer = if self.adjust_user_in_ms == 0 {
            std::time::Instant::now() + interval
        } else {
            self.adjust_user_timer + interval
        };
        self.adjust_user_in_ms = (interval.as_millis() as usize).max(1);
    }

    /// Whether the next user increase or decrease is due.
    fn adjust_due(&self) -> bool {
        self.adjust_user_in_ms == 0 || std::time::Instant::now() >= self.adjust_user_timer
    }

    /// Sleep until the next user increase or decrease is due, but never more
    /// than 500 ms, waking up at least twice a second to handle messages and
    /// allow for a quick shutdown if the load test is canceled.
    async fn sleep_until_adjust(&mut self) {
        let maximum_sleep = Duration::from_millis(500);
        let until_due = self
            .adjust_user_timer
            .saturating_duration_since(std::time::Instant::now());
        if until_due >= maximum_sleep {
            self.drift_timer = util::sleep_minus_drift(maximum_sleep, self.drift_timer).await;
        } else {
            debug!("sleeping {until_due:?}...");
            tokio::time::sleep(until_due).await;
            self.drift_timer = tokio::time::Instant::now();
        }
    }
}

/// Global internal state for the load test.
pub struct GooseAttack {
    /// An optional transaction that is run one time before starting GooseUsers and running Scenarios.
    test_start_transaction: Option<Transaction>,
    /// An optional transaction that is run one time after all GooseUsers have finished.
    test_stop_transaction: Option<Transaction>,
    /// A vector containing one copy of each Scenario defined by this load test.
    scenarios: Vec<Scenario>,
    /// A set of all registered scenario names.
    scenario_machine_names: HashSet<String>,
    /// A weighted vector containing a GooseUser object for each GooseUser that will run during this load test.
    weighted_users: Vec<GooseUser>,
    /// Optional default values for Goose run-time options.
    defaults: GooseDefaults,
    /// Configuration object holding options set when launching the load test.
    configuration: GooseConfiguration,
    /// The load test operates in only one of the following modes: StandAlone, Manager, or Worker.
    attack_mode: AttackMode,
    /// Which phase the load test is currently operating in.
    attack_phase: AttackPhase,
    /// Defines the order [`Scenario`](./goose/struct.Scenario.html)s and
    /// [`Transaction`](./goose/struct.Transaction.html)s are allocated.
    scheduler: GooseScheduler,
    /// When the load test started.
    ///
    /// Restarted after the increase→maintain metrics reset so running duration
    /// and report rate windows exclude ramp-up. Do **not** use this for the
    /// active-users series clock — see [`Self::series_started`].
    started: Option<time::Instant>,
    /// The seconds since `started`, to the microsecond, when `metrics.duration` was
    /// last set from them.
    elapsed: f64,
    /// Continuous clock for per-second graph series (especially active users).
    ///
    /// Set once when a run starts (`reset_run_state`) and **not** restarted on
    /// metrics reset, so ramp-up and later user changes stay on one timeline.
    series_started: Option<time::Instant>,
    /// Internal Goose test plan representation.
    test_plan: TestPlan,
    /// The shape of a running users ramp, `None` for a test plan and when
    /// no run is in progress.
    run_shape: Option<run_shape::RunShape>,
    /// The snapshot's run settings, but for the fields computed per
    /// snapshot; built when first asked for after a control command.
    #[cfg(feature = "dashboard")]
    settings: Option<metrics::dashboard_snapshot::SnapshotSettings>,
    /// When the current test plan step started.
    step_started: Option<time::Instant>,
    /// All metrics merged together.
    metrics: GooseMetrics,
    /// All data for report graphs.
    graph_data: GraphData,
    /// The client builder from the last `set_client_builder_with_cookies` or
    /// `set_client_builder_without_cookies` call; `None` builds each user's client
    /// from the configuration alone.
    client_builder: Option<client::ClientBuilderSettings>,
    /// How users get their clients when a client builder is set, built once when
    /// the load test starts, so a shared client is one client for the whole run.
    client_strategy: Option<client::ClientStrategy>,
    /// Set when a run starts and cleared once its reports are written, so a
    /// shutdown with no run since the last one writes nothing.
    run_in_progress: bool,
    /// How the current run ended, and the killswitch reason when canceled.
    /// The first cause recorded wins; unset means the plan completed.
    ended_by: Option<(runs::EndedBy, Option<String>)>,
    /// The run's folder and what Goose writes into it.
    output: runs::Output,
    /// The Chrome binary PDF reports run, found once at startup.
    #[cfg(feature = "pdf-reports")]
    chrome: tokio::sync::OnceCell<report::chrome::ResolvedChrome>,
}

/// Whether `--scenarios` pattern `pattern` selects the scenario with machine
/// name `machine_name`: exactly, or with `*` wildcards.
fn scenario_pattern_matches(pattern: &str, machine_name: &str) -> bool {
    if pattern.contains('*') {
        wildcard_match(pattern, machine_name)
    } else {
        machine_name == pattern
    }
}

/// Match a pattern containing `*` wildcards against text.
/// Each `*` matches zero or more characters.
fn wildcard_match(pattern: &str, text: &str) -> bool {
    let p = pattern.as_bytes();
    let t = text.as_bytes();
    let (mut pi, mut ti) = (0, 0);
    let (mut star_pi, mut star_ti) = (None::<usize>, 0);

    while ti < t.len() {
        if pi < p.len() && p[pi] == t[ti] {
            pi += 1;
            ti += 1;
        } else if pi < p.len() && p[pi] == b'*' {
            star_pi = Some(pi);
            star_ti = ti;
            pi += 1;
        } else if let Some(s) = star_pi {
            pi = s + 1;
            star_ti += 1;
            ti = star_ti;
        } else {
            return false;
        }
    }

    // Consume trailing stars.
    while pi < p.len() && p[pi] == b'*' {
        pi += 1;
    }

    pi == p.len()
}

/// Goose's internal global state.
impl GooseAttack {
    /// Load configuration and initialize a [`GooseAttack`](./struct.GooseAttack.html).
    ///
    /// # Example
    /// ```rust
    /// use goose::prelude::*;
    ///
    /// let mut goose_attack = GooseAttack::initialize();
    /// ```
    pub fn initialize() -> Result<GooseAttack, GooseError> {
        let configuration = GooseConfiguration::parse_args_default_or_exit();
        Ok(GooseAttack {
            test_start_transaction: None,
            test_stop_transaction: None,
            scenarios: Vec::new(),
            scenario_machine_names: HashSet::new(),
            weighted_users: Vec::new(),
            defaults: GooseDefaults::default(),
            configuration,
            attack_mode: AttackMode::Undefined,
            attack_phase: AttackPhase::Idle,
            scheduler: GooseScheduler::RoundRobin,
            started: None,
            elapsed: 0.0,
            series_started: None,
            test_plan: TestPlan::new(),
            run_shape: None,
            #[cfg(feature = "dashboard")]
            settings: None,
            step_started: None,
            metrics: GooseMetrics::default(),
            graph_data: GraphData::new(),
            client_builder: None,
            client_strategy: None,
            run_in_progress: false,
            ended_by: None,
            output: runs::Output::default(),
            #[cfg(feature = "pdf-reports")]
            chrome: tokio::sync::OnceCell::new(),
        })
    }

    /// Initialize a [`GooseAttack`](./struct.GooseAttack.html) with an already loaded
    /// configuration.
    ///
    /// This is generally used by Worker instances and tests.
    ///
    /// # Example
    /// ```rust
    /// use goose::GooseAttack;
    /// use goose::config::GooseConfiguration;
    ///
    /// let configuration = GooseConfiguration::parse_args_default_or_exit();
    /// let mut goose_attack = GooseAttack::initialize_with_config(configuration);
    /// ```
    pub fn initialize_with_config(
        configuration: GooseConfiguration,
    ) -> Result<GooseAttack, GooseError> {
        Ok(GooseAttack {
            test_start_transaction: None,
            test_stop_transaction: None,
            scenarios: Vec::new(),
            scenario_machine_names: HashSet::new(),
            weighted_users: Vec::new(),
            defaults: GooseDefaults::default(),
            configuration,
            attack_mode: AttackMode::Undefined,
            attack_phase: AttackPhase::Idle,
            scheduler: GooseScheduler::RoundRobin,
            started: None,
            elapsed: 0.0,
            series_started: None,
            test_plan: TestPlan::new(),
            run_shape: None,
            #[cfg(feature = "dashboard")]
            settings: None,
            step_started: None,
            metrics: GooseMetrics::default(),
            graph_data: GraphData::new(),
            client_builder: None,
            client_strategy: None,
            run_in_progress: false,
            ended_by: None,
            output: runs::Output::default(),
            #[cfg(feature = "pdf-reports")]
            chrome: tokio::sync::OnceCell::new(),
        })
    }

    /// Define the order [`Scenario`](./goose/struct.Scenario.html)s are
    /// allocated to new [`GooseUser`](./goose/struct.GooseUser.html)s as they are
    /// launched.
    ///
    /// By default, [`Scenario`](./goose/struct.Scenario.html)s are allocated
    /// to new [`GooseUser`](./goose/struct.GooseUser.html)s in a round robin style.
    /// For example, if Scenario A has a weight of 5, Scenario B has a weight of 3, and
    /// you launch 20 users, they will be launched in the following order:
    ///  A, B, A, B, A, B, A, A, A, B, A, B, A, B, A, A, A, B, A, B
    ///
    /// Note that the following pattern is repeated:
    ///  A, B, A, B, A, B, A, A
    ///
    /// If reconfigured to schedule serially, then they will instead be allocated in
    /// the following order:
    ///  A, A, A, A, A, B, B, B, A, A, A, A, A, B, B, B, A, A, A, A
    ///
    /// In the serial case, the following pattern is repeated:
    ///  A, A, A, A, A, B, B, B
    ///
    /// In the following example, [`Scenario`](./goose/struct.Scenario.html)s
    /// are allocated to launching [`GooseUser`](./goose/struct.GooseUser.html)s in a
    /// random order. This means running the test multiple times can generate
    /// different amounts of load, as depending on your weighting rules you may
    /// have a different number of [`GooseUser`](./goose/struct.GooseUser.html)s
    /// running each [`Scenario`](./goose/struct.Scenario.html) each time.
    ///
    /// # Example
    /// ```rust
    /// use goose::prelude::*;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), GooseError> {
    ///     GooseAttack::initialize()?
    ///         .set_scheduler(GooseScheduler::Random)
    ///         .register_scenario(scenario!("A Scenario")
    ///             .set_weight(5)?
    ///             .register_transaction(transaction!(a_transaction))
    ///         )
    ///         .register_scenario(scenario!("B Scenario")
    ///             .set_weight(3)?
    ///             .register_transaction(transaction!(b_transaction))
    ///         );
    ///
    ///     Ok(())
    /// }
    ///
    /// async fn a_transaction(user: &mut GooseUser) -> TransactionResult {
    ///     let _goose = user.get("/foo").await?;
    ///
    ///     Ok(())
    /// }
    ///
    /// async fn b_transaction(user: &mut GooseUser) -> TransactionResult {
    ///     let _goose = user.get("/bar").await?;
    ///
    ///     Ok(())
    /// }
    /// ```
    pub fn set_scheduler(mut self, scheduler: GooseScheduler) -> Self {
        self.scheduler = scheduler;
        self
    }

    /// A load test must contain one or more [`Scenario`](./goose/struct.Scenario.html)s
    /// be registered into Goose's global state with this method for it to run.
    ///
    /// # Example
    /// ```rust
    /// use goose::prelude::*;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), GooseError> {
    ///     GooseAttack::initialize()?
    ///         .register_scenario(scenario!("ExampleScenario")
    ///             .register_transaction(transaction!(example_transaction))
    ///         )
    ///         .register_scenario(scenario!("OtherScenario")
    ///             .register_transaction(transaction!(other_transaction))
    ///         );
    ///
    ///     Ok(())
    /// }
    ///
    /// async fn example_transaction(user: &mut GooseUser) -> TransactionResult {
    ///     let _goose = user.get("/foo").await?;
    ///
    ///     Ok(())
    /// }
    ///
    /// async fn other_transaction(user: &mut GooseUser) -> TransactionResult {
    ///     let _goose = user.get("/bar").await?;
    ///
    ///     Ok(())
    /// }
    /// ```
    pub fn register_scenario(mut self, mut scenario: Scenario) -> Self {
        scenario.scenarios_index = self.scenarios.len();
        // Machine names must be unique. If this machine name has already been seen, add an
        // integer at the end to differentiate.
        let mut conflicts: u32 = 0;
        let mut machine_name = scenario.machine_name.to_string();
        // Inserting into the scenario_machine_names hashset will fail if this is name was
        // already seen.
        while !self.scenario_machine_names.insert(machine_name) {
            // For each conflict increase the counter and try again.
            conflicts += 1;
            machine_name = format!("{}_{}", scenario.machine_name, conflicts);
        }
        // If there was a conflict, also update the scenario itself.
        if conflicts > 0 {
            scenario.machine_name = Arc::from(format!("{}_{}", scenario.machine_name, conflicts));
        }
        // Finally, register the scenario.
        self.scenarios.push(scenario);
        self
    }

    /// Optionally define a transaction to run before users are started and all transactions
    /// start running. This is would generally be used to set up anything required
    /// for the load test.
    ///
    /// The [`GooseUser`](./goose/struct.GooseUser.html) used to run the `test_start`
    /// transactions is not preserved and does not otherwise affect the subsequent
    /// [`GooseUser`](./goose/struct.GooseUser.html)s that run the rest of the load
    /// test. For example, if the [`GooseUser`](./goose/struct.GooseUser.html)
    /// logs in during `test_start`, subsequent [`GooseUser`](./goose/struct.GooseUser.html)
    /// do not retain this session and are therefor not already logged in.
    ///
    /// # Example
    /// ```rust
    /// use goose::prelude::*;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), GooseError> {
    ///     GooseAttack::initialize()?
    ///         .test_start(transaction!(setup));
    ///
    ///     Ok(())
    /// }
    ///
    /// async fn setup(user: &mut GooseUser) -> TransactionResult {
    ///     // do stuff to set up load test ...
    ///
    ///     Ok(())
    /// }
    /// ```
    pub fn test_start(mut self, transaction: Transaction) -> Self {
        self.test_start_transaction = Some(transaction);
        self
    }

    /// Optionally define a transaction to run after all users have finished running
    /// all defined transactions. This would generally be used to clean up anything
    /// that was specifically set up for the load test.
    ///
    /// # Example
    /// ```rust
    /// use goose::prelude::*;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), GooseError> {
    ///     GooseAttack::initialize()?
    ///         .test_stop(transaction!(teardown));
    ///
    ///     Ok(())
    /// }
    ///
    /// async fn teardown(user: &mut GooseUser) -> TransactionResult {
    ///     // do stuff to tear down the load test ...
    ///
    ///     Ok(())
    /// }
    /// ```
    pub fn test_stop(mut self, transaction: Transaction) -> Self {
        self.test_stop_transaction = Some(transaction);
        self
    }

    /// Build every user's HTTP client from `builder`, each user with its own client
    /// and its own cookie jar. The users that run the
    /// [`test_start`](#method.test_start) and [`test_stop`](#method.test_stop)
    /// transactions get one too.
    ///
    /// The builder's user agent replaces Goose's `goose/<version>`. The timeout,
    /// gzip and invalid certificate settings also have a configuration option
    /// (`--timeout`, `--no-gzip`, `--accept-invalid-certs`), and each comes from the
    /// first of:
    ///
    /// 1. the option, when it was given on the command line;
    /// 2. the builder, when it was given that setting;
    /// 3. a [`GooseDefault`](./config/enum.GooseDefault.html) for the option;
    /// 4. Goose's built in default: a 60 second timeout, gzip on, certificates
    ///    checked.
    ///
    /// A transaction can still give its user a different client with
    /// [`GooseUser::set_client_builder`](./goose/struct.GooseUser.html#method.set_client_builder).
    ///
    /// This and
    /// [`set_client_builder_without_cookies`](#method.set_client_builder_without_cookies)
    /// replace each other: calling either one again, or the other, means the last call
    /// wins.
    ///
    /// # Errors
    ///
    /// [`GooseError::FeatureNotEnabled`] when Goose is built without the `cookies`
    /// feature, as the clients could not store cookies.
    ///
    /// # Example
    /// ```rust
    /// # #[cfg(feature = "cookies")]
    /// # {
    /// use goose::prelude::*;
    /// use goose::client::GooseClientBuilder;
    /// use std::time::Duration;
    ///
    /// let custom_client = GooseClientBuilder::new()
    ///     .timeout(Duration::from_secs(30))
    ///     .user_agent("custom-agent");
    ///
    /// let _goose_attack = GooseAttack::initialize()?
    ///     .set_client_builder_with_cookies(custom_client)?;
    /// # }
    /// # Ok::<(), goose::GooseError>(())
    /// ```
    pub fn set_client_builder_with_cookies(
        mut self,
        builder: client::GooseClientBuilder<client::CookiesEnabled>,
    ) -> Result<Self, GooseError> {
        if !cfg!(feature = "cookies") {
            return Err(GooseError::FeatureNotEnabled {
                feature: "cookies".to_string(),
                detail: "`set_client_builder_with_cookies` needs the `cookies` feature to give each user a cookie jar (rebuild with `--features cookies`), or use `set_client_builder_without_cookies`".to_string(),
            });
        }
        self.client_builder = Some(builder.into_settings());
        Ok(self)
    }

    /// Build one HTTP client from `builder`, without a cookie store, and share it
    /// across every user.
    ///
    /// The client is built once, before any user starts, and each user gets a clone
    /// of it; clones of a [`reqwest::Client`] share one connection pool, so this suits
    /// a load test with many users that needs no cookies. Users a Controller adds
    /// later, and the users that run the [`test_start`](#method.test_start) and
    /// [`test_stop`](#method.test_stop) transactions, share it too. When building
    /// the client fails, the load test fails before any user starts, with that error.
    ///
    /// The builder's settings, and the command line options that win over them, are
    /// as for
    /// [`set_client_builder_with_cookies`](#method.set_client_builder_with_cookies).
    /// A transaction that calls
    /// [`GooseUser::set_client_builder`](./goose/struct.GooseUser.html#method.set_client_builder)
    /// moves its user off the shared client and onto a client of its own.
    ///
    /// This and
    /// [`set_client_builder_with_cookies`](#method.set_client_builder_with_cookies)
    /// replace each other: calling either one again, or the other, means the last call
    /// wins.
    ///
    /// # Errors
    ///
    /// None at present: the client is built when the load test starts, and an error
    /// building it is returned from
    /// [`execute`](#method.execute).
    ///
    /// # Example
    /// ```rust
    /// use goose::prelude::*;
    /// use goose::client::GooseClientBuilder;
    /// use std::time::Duration;
    ///
    /// let custom_client = GooseClientBuilder::new()
    ///     .without_cookies()
    ///     .timeout(Duration::from_secs(30))
    ///     .user_agent("custom-agent");
    ///
    /// let _goose_attack = GooseAttack::initialize()?
    ///     .set_client_builder_without_cookies(custom_client)?;
    /// # Ok::<(), goose::GooseError>(())
    /// ```
    pub fn set_client_builder_without_cookies(
        mut self,
        builder: client::GooseClientBuilder<client::CookiesDisabled>,
    ) -> Result<Self, GooseError> {
        self.client_builder = Some(builder.into_settings());
        Ok(self)
    }

    /// Resolve the client builder's settings against the configured
    /// configuration and build how users get their clients: a shared client is
    /// built here.
    fn build_client_strategy(
        &mut self,
        command_line_client_options: client::CommandLineClientOptions,
    ) -> Result<(), GooseError> {
        self.client_strategy = match &self.client_builder {
            Some(builder) => Some(
                builder
                    .resolve(command_line_client_options, &self.configuration)
                    .into_strategy()?,
            ),
            None => None,
        };
        Ok(())
    }

    /// The `--scenarios` patterns that match no scenario's machine name.
    fn unmatched_scenario_patterns(&self) -> Vec<&str> {
        self.configuration
            .scenarios()
            .iter()
            .filter(|pattern| {
                !self
                    .scenarios
                    .iter()
                    .any(|scenario| scenario_pattern_matches(pattern, &scenario.machine_name))
            })
            .map(String::as_str)
            .collect()
    }

    /// Internal helper to determine if the scenario is currently active.
    fn scenario_is_active(&self, scenario: &Scenario) -> bool {
        let patterns = self.configuration.scenarios();
        if patterns.is_empty() {
            return true;
        }
        patterns
            .iter()
            .any(|pattern| scenario_pattern_matches(pattern, &scenario.machine_name))
    }

    /// Use configured GooseScheduler to build out a properly weighted list of
    /// [`Scenario`](./goose/struct.Scenario.html)s to be assigned to
    /// [`GooseUser`](./goose/struct.GooseUser.html)s
    fn allocate_scenarios(&mut self) -> Vec<usize> {
        trace!("allocate_scenarios");

        let mut u: usize = 0;
        let mut v: usize;
        for scenario in &self.scenarios {
            if self.scenario_is_active(scenario) {
                if u == 0 {
                    u = scenario.weight;
                } else {
                    v = scenario.weight;
                    trace!("calculating greatest common denominator of {u} and {v}");
                    u = util::gcd(u, v);
                    trace!("inner gcd: {u}");
                }
            }
        }
        // 'u' will always be the greatest common divisor
        debug!("gcd: {u}");

        // Build a vector of vectors to be used to schedule users.
        let mut available_scenarios = Vec::with_capacity(self.scenarios.len());
        let mut total_scenarios = 0;
        for (index, scenario) in self.scenarios.iter().enumerate() {
            if self.scenario_is_active(scenario) {
                // divide by greatest common divisor so vector is as short as possible
                let weight = scenario.weight / u;
                trace!(
                    "{}: {} has weight of {} (reduced with gcd to {})",
                    index,
                    scenario.name,
                    scenario.weight,
                    weight
                );
                let weighted_sets = vec![index; weight];
                total_scenarios += weight;
                available_scenarios.push(weighted_sets);
            }
        }

        info!(
            "[scheduler]: allocating transactions and scenarios with {:?} scheduler",
            self.scheduler
        );

        // Now build the weighted list with the appropriate scheduler.
        let mut weighted_scenarios = Vec::new();
        match self.scheduler {
            GooseScheduler::RoundRobin => {
                // Allocate scenarios round robin.
                let scenarios_len = available_scenarios.len();
                loop {
                    for (scenario_index, scenarios) in available_scenarios
                        .iter_mut()
                        .enumerate()
                        .take(scenarios_len)
                    {
                        if let Some(scenario) = scenarios.pop() {
                            debug!("[scheduler]: allocating 1 user from Scenario {scenario_index}");
                            weighted_scenarios.push(scenario);
                        }
                    }
                    if weighted_scenarios.len() >= total_scenarios {
                        break;
                    }
                }
            }
            GooseScheduler::Serial => {
                // Allocate scenarios serially in the weighted order defined.
                for (scenario_index, scenarios) in available_scenarios.iter().enumerate() {
                    debug!(
                        "allocating all {} users from Scenario {}",
                        scenarios.len(),
                        scenario_index,
                    );
                    weighted_scenarios.append(&mut scenarios.clone());
                }
            }
            GooseScheduler::Random => {
                // Allocate scenarios randomly.
                loop {
                    let scenario = available_scenarios.choose_mut(&mut rand::rng());
                    match scenario {
                        Some(set) => {
                            if let Some(s) = set.pop() {
                                weighted_scenarios.push(s);
                            }
                        }
                        None => warn!("randomly allocating a Scenario failed, trying again"),
                    }
                    if weighted_scenarios.len() >= total_scenarios {
                        break;
                    }
                }
            }
        }
        weighted_scenarios
    }

    /// Pre-allocate a vector of weighted [`GooseUser`](./goose/struct.GooseUser.html)s.
    fn weight_scenario_users(&mut self, total_users: usize) -> Result<Vec<GooseUser>, GooseError> {
        trace!("weight_scenario_users");

        let weighted_scenarios = self.allocate_scenarios();

        // Allocate a state for each user that will be launched.
        info!(
            "[scheduler]: initializing {} user states...",
            self.test_plan.total_users()
        );

        // Gather the parameters needed for each user. This is cheap and must be
        // sequential to preserve the round-robin scenario assignment order (users
        // are later .pop()'d so ordering matters).
        let config_host = self.get_configuration_host();
        let defaults_host = self.defaults.host.clone();
        let mut user_params: Vec<(usize, Arc<str>, url::Url)> = Vec::with_capacity(total_users);
        let mut user_count = 0;
        loop {
            for scenarios_index in &weighted_scenarios {
                let base_url = goose::get_base_url(
                    config_host.clone(),
                    self.scenarios[*scenarios_index].host.clone(),
                    defaults_host.clone(),
                )?;
                user_params.push((
                    self.scenarios[*scenarios_index].scenarios_index,
                    self.scenarios[*scenarios_index].machine_name.clone(),
                    base_url,
                ));
                user_count += 1;
                if user_count == total_users {
                    break;
                }
            }
            if user_count == total_users {
                break;
            }
        }

        // Create GooseUser objects in parallel across available CPUs. Each user
        // gets its own reqwest client unless one is shared, and building it is
        // the expensive part. Chunks are collected back in order to preserve the
        // scenario assignment sequence.
        let configuration = &self.configuration;
        let client_strategy = &self.client_strategy;
        let metrics_hash = self.metrics.hash;
        let num_cpus = std::thread::available_parallelism()
            .map(|n| n.get())
            .unwrap_or(1);
        let chunk_size = total_users.div_ceil(num_cpus);

        let results: Vec<Result<Vec<GooseUser>, GooseError>> = std::thread::scope(|s| {
            let mut handles = Vec::with_capacity(num_cpus);
            for (chunk_idx, chunk) in user_params.chunks(chunk_size).enumerate() {
                let base = chunk_idx * chunk_size;
                handles.push(s.spawn(move || {
                    let mut users = Vec::with_capacity(chunk.len());
                    for (i, (scenarios_index, machine_name, base_url)) in chunk.iter().enumerate() {
                        debug!("creating user state: {} ({})", base + i, scenarios_index);
                        let reqwest_client = match client_strategy {
                            None => goose::create_reqwest_client(configuration)?,
                            Some(strategy) => strategy.user_client()?,
                        };
                        users.push(GooseUser::new(
                            *scenarios_index,
                            machine_name.clone(),
                            base_url.clone(),
                            configuration,
                            metrics_hash,
                            Some(reqwest_client),
                        )?);
                    }
                    Ok::<Vec<GooseUser>, GooseError>(users)
                }));
            }
            handles
                .into_iter()
                .map(|h| {
                    h.join().unwrap_or_else(|_| {
                        Err(GooseError::Io(io::Error::other(
                            "user initialization thread panicked",
                        )))
                    })
                })
                .collect()
        });

        let mut weighted_users = Vec::with_capacity(total_users);
        for result in results {
            weighted_users.extend(result?);
        }
        debug!(
            "[scheduler]: created {} weighted_users",
            weighted_users.len()
        );
        Ok(weighted_users)
    }

    // Change from one attack_phase to another.
    fn set_attack_phase(
        &mut self,
        goose_attack_run_state: &mut GooseAttackRunState,
        phase: AttackPhase,
    ) {
        // There's nothing to do if already in the specified phase.
        if self.attack_phase == phase {
            return;
        }

        // The drift timer starts at 0 any time the phase is changed.
        goose_attack_run_state.drift_timer = tokio::time::Instant::now();

        // Reaching Idle ends any cancel in progress, and the run's shape.
        if phase == AttackPhase::Idle {
            goose_attack_run_state.stopping = false;
            self.run_shape = None;
        }

        // Thresholds are checked from when the run first holds its users steady,
        // so a ramp up never fails a rule while the run goes.
        if goose_attack_run_state.threshold_check_at.is_none() && phase == AttackPhase::Maintain {
            self.start_threshold_checks(goose_attack_run_state);
        }

        // `rps` rules count only the time the run holds its users steady, in every
        // mode, so each entry to Maintain starts a hold and each exit ends it.
        let holds = |phase| phase == AttackPhase::Maintain;
        if holds(phase) != holds(self.attack_phase)
            && self
                .configuration
                .thresholds
                .iter()
                .any(threshold::Threshold::is_rps)
        {
            self.update_duration();
            let seconds = self.elapsed;
            let _ = goose_attack_run_state.metrics_cmd_tx.send(if holds(phase) {
                MetricsCommand::EnterMaintain { seconds }
            } else {
                MetricsCommand::LeaveMaintain { seconds }
            });
        }

        // Optional debug output.
        info!("entering GooseAttack phase: {:?}", phase);

        // Update the current phase.
        self.attack_phase = phase;
    }

    // Display all scenarios (sorted by machine name).
    fn print_scenarios(&self) {
        print!("{}", self.scenarios_list());
    }

    /// What `--scenarios-list` prints: each scenario's machine name, which
    /// `--scenarios` selects it by, and its name.
    fn scenarios_list(&self) -> String {
        let mut scenarios = BTreeMap::new();
        for scenario in &self.scenarios {
            scenarios.insert(scenario.machine_name.clone(), scenario.name.clone());
        }
        // Display sorted by machine_name.
        let mut list = "Scenarios:\n".to_string();
        for (key, name) in scenarios {
            list.push_str(&format!(" - {}: (\"{}\")\n", key, name));
        }
        list
    }

    /// Execute the [`GooseAttack`](./struct.GooseAttack.html) load test.
    ///
    /// # Example
    /// ```rust
    /// use goose::prelude::*;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), GooseError> {
    ///     let _goose_metrics = GooseAttack::initialize()?
    ///         .register_scenario(scenario!("ExampleTransaction")
    ///             .register_transaction(transaction!(example_transaction).set_weight(2)?)
    ///             .register_transaction(transaction!(another_example_transaction).set_weight(3)?)
    ///             // Goose must run against a host, point to localhost so test starts.
    ///             .set_host("http://localhost")
    ///         )
    ///         // Exit after one second so test doesn't run forever.
    ///         .set_default(GooseDefault::RunTime, 1)?
    ///         .execute()
    ///         .await?;
    ///
    ///     Ok(())
    /// }
    ///
    /// async fn example_transaction(user: &mut GooseUser) -> TransactionResult {
    ///     let _goose = user.get("/foo").await?;
    ///
    ///     Ok(())
    /// }
    ///
    /// async fn another_example_transaction(user: &mut GooseUser) -> TransactionResult {
    ///     let _goose = user.get("/bar").await?;
    ///
    ///     Ok(())
    /// }
    /// ```
    pub async fn execute(self) -> Result<GooseMetrics, GooseError> {
        /// Ends a gzipped Goose log's member on every way out of `execute()`:
        /// a return, a panic unwinding through it, or its future dropped.
        struct FinishGooseLog;
        impl Drop for FinishGooseLog {
            fn drop(&mut self) {
                logger::finish_goose_log();
            }
        }
        logger::start_goose_log();
        let _finish = FinishGooseLog;
        self.execute_load_test().await
    }

    /// [`Self::execute`], before the Goose log is finished.
    async fn execute_load_test(mut self) -> Result<GooseMetrics, GooseError> {
        // If version flag is set, display package name and version and exit.
        if self.configuration.version {
            println!("{} {}", env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION"));
            logger::finish_goose_log();
            std::process::exit(0);
        }

        // At least one scenario is required.
        if self.scenarios.is_empty() {
            return Err(GooseError::NoScenarios {
                detail: "No scenarios are defined.".to_string(),
            });
        }

        // Display scenarios and transactions, then exit.
        if self.configuration.list {
            println!("Available transactions:");
            for scenario in self.scenarios {
                println!(" - {} (weight: {})", scenario.name, scenario.weight);
                for transaction in scenario.transactions {
                    println!(
                        "    o {} (weight: {})",
                        transaction.name.name_for_transaction(),
                        transaction.weight
                    );
                }
            }
            logger::finish_goose_log();
            std::process::exit(0);
        }

        // Note which client options the command line gave before the defaults
        // are merged in: those win over a client builder, the defaults do not.
        let command_line_client_options =
            client::CommandLineClientOptions::from_command_line(&self.configuration);

        // Configure GooseConfiguration.
        self.configuration.configure(&self.defaults)?;

        // Validate GooseConfiguration.
        self.configuration.validate()?;
        self.output.save_report = self.configuration.save_report_at_start();
        self.output.graph_data = self.configuration.report_graph_data;

        // Write reports from a JSON report, then exit.
        if let Some(path) = self.configuration.render_report().map(str::to_string) {
            return self.render_report(&path).await;
        }

        // Display scenarios, then exit.
        if self.configuration.scenarios_list {
            self.print_scenarios();
            logger::finish_goose_log();
            std::process::exit(0);
        }

        // A pattern that names no scenario is most likely a mistyped name, as
        // `user_login` for the scenario `userlogin`.
        for pattern in self.unmatched_scenario_patterns() {
            warn!("--scenarios {pattern:?} matches no scenario; --scenarios-list prints the names");
        }

        // At least one scenario must be active.
        let mut active_scenario: bool = false;
        for scenario in &self.scenarios {
            if self.scenario_is_active(scenario) {
                active_scenario = true;
                break;
            }
        }
        if !active_scenario {
            self.print_scenarios();
            return Err(GooseError::NoScenarios {
                detail: "No scenarios are enabled.".to_string(),
            });
        }

        // Build TestPlan, and the shape of a users ramp.
        self.test_plan = TestPlan::build(&self.configuration)?;
        self.run_shape = run_shape::RunShape::for_configuration(&self.configuration);

        // A client builder gives users clients built from its settings. Build
        // them, or the one shared client, now: before any user starts, and once
        // for the whole run, so users a Controller adds later share it too.
        self.build_client_strategy(command_line_client_options)?;

        // With a validated GooseConfiguration, enter a run mode.
        self.attack_mode = AttackMode::StandAlone;

        // When --no-autostart is set, defer prepare_load_test() until the Controller
        // sends a Start command. Otherwise user states are initialized here and then
        // redundantly re-initialized when the Start command calls prepare_load_test().
        if self.configuration.no_autostart {
            if self.validate_host().is_err() {
                info!("host must be configured via Controller before starting load test");
            } else if let Some(host) = self.configuration.host() {
                info!("global host configured: {host}");
            }
        } else {
            // If configuration.host is empty, then it will fall back to per-scenario
            // defaults if set.
            if let Some(host) = self.configuration.host() {
                info!("global host configured: {host}");
            }
            self.prepare_load_test()?;
        }

        // Calculate a unique hash for the current load test.
        let mut s = DefaultHasher::new();
        self.scenarios.hash(&mut s);
        self.metrics.hash = s.finish();
        debug!("hash: {}", self.metrics.hash);

        self = self.start_attack().await?;

        if self.metrics.display_metrics {
            info!(
                "printing final metrics after {} seconds...",
                self.metrics.duration
            );
            print!("{}", self.metrics);
        }

        // Every report is written: fail the run when a threshold failed.
        let failed: Vec<threshold::ThresholdResult> = self
            .metrics
            .thresholds
            .iter()
            .filter(|result| !result.passed)
            .cloned()
            .collect();
        if !failed.is_empty() {
            for result in &failed {
                error!(
                    "threshold {} failed: observed {}",
                    result.rule, result.observed
                );
            }
            return Err(GooseError::ThresholdsFailed {
                failed,
                metrics: ThresholdMetrics(Box::new(self.metrics)),
            });
        }

        Ok(self.metrics)
    }

    /// Start checking the thresholds, the first check `--threshold-abort-delay`
    /// from now, when a failing one stops the run.
    pub(crate) fn start_threshold_checks(
        &mut self,
        goose_attack_run_state: &mut GooseAttackRunState,
    ) {
        if self.configuration.aborts_on_thresholds() {
            let delay = self.configuration.threshold_abort_delay_secs() as u64;
            goose_attack_run_state.threshold_check_at =
                std::time::Instant::now().checked_add(Duration::from_secs(delay));
        }
    }

    /// Once a second while the thresholds are checked, and only while users start
    /// or run, ask the metrics processor to check them (fire-and-forget). Nothing is
    /// sent without thresholds or under `--no-threshold-abort`.
    fn check_thresholds(&mut self, goose_attack_run_state: &mut GooseAttackRunState) {
        let Some(due) = goose_attack_run_state.threshold_check_at else {
            return;
        };
        if !matches!(
            self.attack_phase,
            AttackPhase::Increase | AttackPhase::Maintain
        ) {
            return;
        }
        let now = std::time::Instant::now();
        if now < due {
            return;
        }
        goose_attack_run_state.threshold_check_at = Some(now + Duration::from_secs(1));
        self.update_duration();
        let _ = goose_attack_run_state
            .metrics_cmd_tx
            .send(MetricsCommand::CheckThresholds {
                duration: self.metrics.duration,
                seconds: self.elapsed,
            });
    }

    // Returns OK(()) if there's a valid host, GooseError with details if not.
    // Every Start checks it before it replies: a scenario, and a test_start
    // or test_stop transaction, which run with no scenario host, each need
    // one.
    fn validate_host(&mut self) -> Result<(), GooseError> {
        if self.configuration.host().is_none() && self.defaults.host.is_none() {
            let transaction = if self.test_start_transaction.is_some() {
                Some(HOST_TRANSACTIONS[0])
            } else if self.test_stop_transaction.is_some() {
                Some(HOST_TRANSACTIONS[1])
            } else {
                None
            };
            if let Some(transaction) = transaction {
                return Err(GooseError::InvalidOption {
                    option: NO_HOST_OPTION.to_string(),
                    value: "".to_string(),
                    detail: no_transaction_host_detail(transaction),
                });
            }
        }
        if self.configuration.host().is_none() {
            for scenario in &self.scenarios {
                match &scenario.host {
                    Some(h) => {
                        if util::is_valid_host(h).is_ok() {
                            info!("host for {} configured: {}", scenario.name, h);
                        }
                    }
                    None => match &self.defaults.host {
                        Some(h) => {
                            if util::is_valid_host(h).is_ok() {
                                info!("host for {} configured: {}", scenario.name, h);
                            }
                        }
                        None => {
                            return Err(GooseError::InvalidOption {
                                option: NO_HOST_OPTION.to_string(),
                                value: "".to_string(),
                                detail: format!(
                                    "A host must be defined via the --host option, the GooseAttack.set_default() function, or the Scenario.set_host() function (no host defined for {}).",
                                    scenario.name
                                ),
                            });
                        }
                    },
                }
            }
        }
        Ok(())
    }

    // Create and schedule GooseUsers. This requires that the host that will be load tested
    // has been configured.
    fn prepare_load_test(&mut self) -> Result<(), GooseError> {
        // Be sure a valid host has been defined before building configuration.
        self.validate_host()?;

        // A load test with no users never starts: weighting zero users never ends.
        if self.test_plan.total_users() == 0 {
            return Err(GooseError::InvalidOption {
                option: NO_USERS_OPTION.to_string(),
                value: "0".to_string(),
                detail: "There are no users to start: configure users or a test plan.".to_string(),
            });
        }

        // Apply weights to transactions in each scenario.
        for scenario in &mut self.scenarios {
            let (
                weighted_on_start_transactions,
                weighted_transactions,
                weighted_on_stop_transactions,
            ) = allocate_transactions(scenario, &self.scheduler);
            scenario.weighted_on_start_transactions = weighted_on_start_transactions;
            scenario.weighted_transactions = weighted_transactions;
            scenario.weighted_on_stop_transactions = weighted_on_stop_transactions;
            debug!(
                "weighted {} on_start: {:?} transactions: {:?} on_stop: {:?}",
                scenario.name,
                scenario.weighted_on_start_transactions,
                scenario.weighted_transactions,
                scenario.weighted_on_stop_transactions
            );
        }

        // Stand-alone processes can display metrics.
        if !self.configuration.no_metrics && !self.configuration.no_print_metrics {
            self.metrics.display_metrics = true;
        }

        // Allocate a state for each of the users we are about to start.
        self.weighted_users = self.weight_scenario_users(self.test_plan.total_users())?;

        Ok(())
    }

    /// Helper to wrap configured host in `Option<>` if set.
    fn get_configuration_host(&self) -> Option<String> {
        self.configuration.host().map(str::to_string)
    }

    // Helper to spawn a throttle thread if configured. The throttle thread opens
    // a bounded channel to control how quickly [`GooseUser`](./goose/struct.GooseUser.html)
    // threads can make requests.
    async fn setup_throttle(
        &self,
    ) -> (
        // A channel used by [`GooseUser`](./goose/struct.GooseUser.html)s to throttle requests.
        Option<flume::Sender<bool>>,
        // A channel used by parent to tell throttle the load test is complete.
        Option<flume::Sender<bool>>,
    ) {
        // If the throttle isn't enabled, return immediately.
        let throttle_requests = self.configuration.throttle_requests();
        if throttle_requests == 0 {
            return (None, None);
        }

        // Create a bounded channel allowing single-sender multi-receiver to throttle
        // [`GooseUser`](./goose/struct.GooseUser.html) threads.
        let (all_threads_throttle, throttle_receiver): (
            flume::Sender<bool>,
            flume::Receiver<bool>,
        ) = flume::bounded(throttle_requests);

        // Create a channel allowing the parent to inform the throttle thread when the
        // load test is finished. Even though we only send one message, we can't use a
        // oneshot channel as we don't want to block waiting for a message.
        let (parent_to_throttle_tx, throttle_rx) = flume::bounded(1);

        // Launch a new thread for throttling, no need to rejoin it.
        let _ = Some(tokio::spawn(throttle::throttle_main(
            throttle_requests,
            throttle_receiver,
            throttle_rx,
        )));

        let sender = all_threads_throttle.clone();
        // We start from 1 instead of 0 to intentionally fill all but one slot in the
        // channel to avoid a burst of traffic during startup. The channel then provides
        // an implementation of the leaky bucket algorithm as a queue. Requests have to
        // add a token to the bucket before making a request, and are blocked until this
        // throttle thread "leaks out" a token thereby creating space. More information
        // can be found at: https://en.wikipedia.org/wiki/Leaky_bucket
        for _ in 1..throttle_requests {
            let _ = sender.send_async(true).await;
        }

        (Some(all_threads_throttle), Some(parent_to_throttle_tx))
    }

    // Helper to optionally spawn a telnet and/or WebSocket Controller thread. The Controller
    // threads send commands to the parent process on `control_tx`, each with a one-shot
    // channel for the reply.
    async fn setup_controllers(
        &self,
        control_tx: &flume::Sender<ControlRequest>,
    ) -> controller::ListeningControllers {
        let mut listening = controller::ListeningControllers::default();
        // Configured telnet Controller if not disabled.
        if !self.configuration.no_telnet {
            if let Some(listener) =
                controller::bind_controller(&self.configuration, ControllerProtocol::Telnet).await
            {
                // Spawn the initial controller thread to allow real-time control of the load test.
                // There is no need to rejoin this thread when the load test ends.
                tokio::spawn(controller::controller_main(
                    listener,
                    control_tx.clone(),
                    ControllerProtocol::Telnet,
                ));
                listening.telnet = true;
            }
        }

        // Configured WebSocket Controller if enabled with --websocket.
        if self.configuration.websocket {
            if let Some(listener) =
                controller::bind_controller(&self.configuration, ControllerProtocol::WebSocket)
                    .await
            {
                // Spawn the initial controller thread to allow real-time control of the load test.
                // There is no need to rejoin this thread when the load test ends.
                tokio::spawn(controller::controller_main(
                    listener,
                    control_tx.clone(),
                    ControllerProtocol::WebSocket,
                ));
                listening.websocket = true;
            }
        }
        listening
    }

    /// After an autostarted run, whether to stay up for the dashboard: Save
    /// report wrote the run's report, the run was not stopped or canceled on
    /// purpose, and any client is connected to the event stream.
    #[cfg(feature = "dashboard")]
    fn should_wait_for_dashboard(&self, goose_attack_run_state: &GooseAttackRunState) -> bool {
        let saved = self.output.last_report.is_some();
        let ended_on_its_own = matches!(
            self.ended_by,
            None | Some((runs::EndedBy::Completed, _)) | Some((runs::EndedBy::UsersExited, _))
        );
        let tab_open = goose_attack_run_state
            .dashboard_active_sse
            .as_ref()
            .is_some_and(|active| active.load(std::sync::atomic::Ordering::Relaxed) > 0);
        saved && ended_on_its_own && tab_open
    }

    /// Go Idle after an autostarted run instead of shutting down, as a
    /// dashboard Stop does, so Idle does not start the test again.
    #[cfg(feature = "dashboard")]
    fn start_dashboard_wait(&mut self, goose_attack_run_state: &mut GooseAttackRunState) {
        self.configuration.no_autostart = true;
        goose_attack_run_state.shutdown_after_stop = false;
        let address = goose_attack_run_state
            .dashboard_url
            .as_deref()
            .unwrap_or_default();
        if self.configuration.dashboard_control {
            println!(
                "Run finished. Download it from the dashboard at {address}. Press Quit in the dashboard or Ctrl-C to exit."
            );
        } else {
            println!(
                "Run finished. Download it from the dashboard at {address}. Press Ctrl-C to exit."
            );
        }
    }

    /// Shut down from Idle as a Controller `shutdown` does: no run to stop,
    /// so no metrics to print and no report to write.
    fn shutdown_from_idle(&mut self, goose_attack_run_state: &mut GooseAttackRunState) {
        self.metrics.display_metrics = false;
        goose_attack_run_state.shutdown_after_stop = true;
        self.stop_without_users(goose_attack_run_state);
    }

    /// Stop with no user running: refuse Users until the run stops, and leave
    /// a plan with nothing left to run, so the Decrease phase finds the load
    /// test fully stopped.
    fn stop_without_users(&mut self, goose_attack_run_state: &mut GooseAttackRunState) {
        goose_attack_run_state.stopping = true;
        self.run_shape = None;
        self.test_plan.steps = vec![(0, 0)];
        self.test_plan.current = 0;
        self.set_attack_phase(goose_attack_run_state, AttackPhase::Decrease);
    }

    /// Handle dashboard snapshot and series requests from the HTTP server task.
    ///
    /// Drains up to a small batch per main-loop iteration; at most one
    /// snapshot is forwarded per tick (latest wins). Dashboard control goes
    /// through [`Self::handle_control_requests`], called before this, so a
    /// snapshot forwarded here sees the phase a command in the same tick set.
    ///
    /// Snapshots are **non-blocking** for the attack loop: the parent forwards
    /// [`MetricsCommand::GetDashboardSnapshot`] with the hub's oneshot and does
    /// not await the metrics processor.
    ///
    /// When the metrics processor is unavailable (typical after control Stop
    /// merges final metrics and returns to Idle until the next Start), a
    /// snapshot is built from the main-loop [`GooseMetrics`] / [`GraphData`] so
    /// poll/SSE clients still observe `phase: "idle"` and can re-enable Start.
    #[cfg(feature = "dashboard")]
    async fn handle_dashboard_requests(
        &mut self,
        goose_attack_run_state: &mut GooseAttackRunState,
    ) -> Result<(), GooseError> {
        let mut series_requests = Vec::new();
        let mut pending_snapshot: Option<(
            tokio::sync::oneshot::Sender<metrics::DashboardSnapshot>,
            Option<metrics::dashboard_snapshot::HeatmapCursor>,
        )> = None;
        let mut disconnected = false;

        {
            let Some(rx) = goose_attack_run_state.dashboard_channel_rx.as_ref() else {
                return Ok(());
            };

            for _ in 0..controller::MAX_DRAIN {
                match rx.try_recv() {
                    Ok(dashboard::DashboardRequest::GetSnapshot {
                        respond,
                        heatmap_since,
                    }) => {
                        // Coalesce: only the latest snapshot request is kept.
                        pending_snapshot = Some((respond, heatmap_since));
                    }
                    Ok(dashboard::DashboardRequest::GetRequestSeries {
                        method,
                        name,
                        since,
                        respond,
                    }) => {
                        series_requests.push((method, name, since, respond));
                    }
                    Err(flume::TryRecvError::Empty) => break,
                    Err(flume::TryRecvError::Disconnected) => {
                        disconnected = true;
                        break;
                    }
                }
            }
        }

        if disconnected {
            goose_attack_run_state.dashboard_channel_rx = None;
        }

        // Forward at most one snapshot request without parking the attack loop.
        if let Some((respond, heatmap_since)) = pending_snapshot {
            if respond.is_closed() {
                debug!("[dashboard]: snapshot skipped; hub waiter disconnected");
            } else {
                self.update_duration();
                let phase = attack_phase_str(self.attack_phase).to_string();
                let active_users = goose_attack_run_state.active_users;
                let target_users = self.current_target_users();
                match goose_attack_run_state.metrics_cmd_tx.send(
                    MetricsCommand::GetDashboardSnapshot {
                        duration: self.metrics.duration,
                        total_users: self.metrics.total_users,
                        maximum_users: self.metrics.maximum_users,
                        active_users,
                        target_users,
                        series_elapsed_secs: self.series_elapsed_secs(),
                        phase: phase.clone(),
                        stopping: goose_attack_run_state.stopping,
                        series_window_secs: metrics::dashboard_snapshot::SERIES_WINDOW_SECS,
                        report: self.report_snapshot(),
                        settings: Box::new(self.snapshot_settings(goose_attack_run_state)),
                        heatmap_since,
                        respond,
                    },
                ) {
                    Ok(()) => {}
                    // Processor gone (e.g. Idle after control Stop): serve from
                    // main-loop state so the SPA can observe idle and re-Start.
                    Err(flume::SendError(MetricsCommand::GetDashboardSnapshot {
                        respond,
                        phase,
                        stopping,
                        active_users,
                        settings,
                        heatmap_since,
                        ..
                    })) => {
                        debug!(
                            "[dashboard]: metrics processor unavailable; serving local snapshot (phase={phase})"
                        );
                        let snapshot = self.build_local_dashboard_snapshot(
                            phase,
                            stopping,
                            active_users,
                            *settings,
                            heatmap_since,
                        );
                        let _ = respond.send(snapshot);
                    }
                    Err(_) => {
                        // Other command variants cannot appear here.
                        debug!("[dashboard]: metrics processor unavailable");
                    }
                }
            }
        }

        // Then each series request, also without waiting for the processor.
        for (method, name, since, respond) in series_requests {
            if respond.is_closed() {
                continue;
            }
            match goose_attack_run_state
                .metrics_cmd_tx
                .send(MetricsCommand::GetRequestSeries {
                    method,
                    name,
                    series_elapsed_secs: self.series_elapsed_secs(),
                    since,
                    respond,
                }) {
                Ok(()) => {}
                // Processor gone (e.g. Idle after control Stop): answer from
                // main-loop state, as for snapshots.
                Err(flume::SendError(MetricsCommand::GetRequestSeries {
                    method,
                    name,
                    series_elapsed_secs,
                    since,
                    respond,
                })) => {
                    let series = self.graph_data.export_request_series(
                        method,
                        name,
                        metrics::dashboard_snapshot::SERIES_WINDOW_SECS,
                        Some(series_elapsed_secs),
                        self.metrics
                            .coordinated_omission_metrics
                            .as_ref()
                            .is_some_and(|m| m.has_events()),
                        since,
                    );
                    let _ = respond.send(series);
                }
                Err(_) => {
                    // Other command variants cannot appear here.
                    debug!("[dashboard]: metrics processor unavailable");
                }
            }
        }

        Ok(())
    }

    /// Seconds on the continuous series clock (0 if the run has not started).
    fn series_elapsed_secs(&self) -> usize {
        self.series_started
            .map(|started| started.elapsed().as_secs() as usize)
            .unwrap_or(0)
    }

    /// Users the attack is currently increasing/decreasing toward.
    ///
    /// Prefers the active test-plan step target; falls back to the last plan
    /// step when `current` has advanced past the end (common after the final
    /// step / cancel), then to configured `--users` when the plan is empty.
    fn current_target_users(&self) -> usize {
        self.test_plan
            .steps
            .get(self.test_plan.current)
            .or_else(|| self.test_plan.steps.last())
            .map(|&(users, _)| users)
            .or(self.configuration.users)
            .unwrap_or_default()
    }

    /// Build a dashboard snapshot from main-loop metrics/graph state.
    ///
    /// Used when the dedicated metrics processor is not running (Idle after
    /// Stop) so clients still receive a coherent phase/users view.
    #[cfg(feature = "dashboard")]
    fn build_local_dashboard_snapshot(
        &mut self,
        phase: String,
        stopping: bool,
        active_users: usize,
        settings: metrics::dashboard_snapshot::SnapshotSettings,
        heatmap_since: Option<metrics::dashboard_snapshot::HeatmapCursor>,
    ) -> metrics::DashboardSnapshot {
        // Main-loop graph_data is usually empty until Shutdown merge. Export with
        // series-clock "now" so any retained users level holds to the right edge.
        let series = self.graph_data.export_series_window_with_heatmap(
            metrics::dashboard_snapshot::SERIES_WINDOW_SECS,
            Some(self.series_elapsed_secs()),
            self.metrics
                .coordinated_omission_metrics
                .as_ref()
                .is_some_and(|m| m.has_events()),
            heatmap_since,
        );
        metrics::dashboard_snapshot::build_dashboard_snapshot(
            metrics::dashboard_snapshot::DashboardSnapshotInput {
                metrics: &self.metrics,
                series,
                active_users,
                maximum_users: self.metrics.maximum_users,
                target_users: self.current_target_users(),
                total_users: self.metrics.total_users,
                phase,
                stopping,
                series_window_secs: metrics::dashboard_snapshot::SERIES_WINDOW_SECS,
                no_status_codes: self.configuration.no_status_codes,
                metrics_disabled: self.configuration.no_metrics,
                no_transaction_metrics: self.configuration.no_transaction_metrics,
                no_scenario_metrics: self.configuration.no_scenario_metrics,
                report: self.report_snapshot(),
                settings,
                percentiles_over_time: self.configuration.records_latency_series(),
                series_keys: self.graph_data.latency_series_keys(),
            },
        )
    }

    /// Where the run is: Idle, stopping (a cancel, or Shutdown), a running
    /// test plan, or a users ramp's stage from its shape.
    #[cfg(any(test, feature = "dashboard"))]
    fn stage(&self, goose_attack_run_state: &GooseAttackRunState) -> run_shape::Stage {
        match self.attack_phase {
            AttackPhase::Idle => run_shape::Stage::Idle,
            AttackPhase::Shutdown => run_shape::Stage::Stopping,
            _ if goose_attack_run_state.stopping => run_shape::Stage::Stopping,
            _ => self
                .run_shape
                .as_ref()
                .map_or(run_shape::Stage::TestPlan, run_shape::RunShape::stage),
        }
    }

    /// The snapshot's run settings: the configured settings, built once
    /// after each control command, plus the stage and the hold's countdown,
    /// computed for each snapshot.
    #[cfg(feature = "dashboard")]
    fn snapshot_settings(
        &mut self,
        goose_attack_run_state: &GooseAttackRunState,
    ) -> metrics::dashboard_snapshot::SnapshotSettings {
        let stage = self.stage(goose_attack_run_state);
        let hold_ends_in_secs = match stage {
            run_shape::Stage::Hold => self
                .run_shape
                .as_ref()
                .and_then(|shape| shape.hold_ends_in_secs(time::Instant::now())),
            _ => None,
        };
        let mut settings = match &self.settings {
            Some(settings) => settings.clone(),
            None => {
                let settings = self.configured_settings();
                self.settings = Some(settings.clone());
                settings
            }
        };
        settings.stage = stage.as_str().to_string();
        settings.hold_ends_in_secs = hold_ends_in_secs;
        settings
    }

    /// The configured run settings, without the stage and countdown.
    #[cfg(feature = "dashboard")]
    fn configured_settings(&self) -> metrics::dashboard_snapshot::SnapshotSettings {
        let configuration = &self.configuration;
        // Resolved per scenario as a Start resolves them, without
        // `get_base_url`: a scenario with no host from any source adds none.
        let hosts: std::collections::BTreeSet<String> = self
            .scenarios
            .iter()
            .filter_map(|scenario| {
                configuration
                    .host()
                    .or(scenario.host.as_deref())
                    .or(self.defaults.host.as_deref())
            })
            .filter_map(|host| url::Url::parse(host).ok())
            .map(|url| url.to_string())
            .collect();
        let rate = |rate: &Option<String>| rate.as_deref().and_then(|r| r.parse::<f64>().ok());
        let secs = |secs: usize| (secs > 0).then_some(secs as u64);
        metrics::dashboard_snapshot::SnapshotSettings {
            host: configuration.host().map(str::to_string),
            hosts: hosts.into_iter().collect(),
            users: configuration.users.map(|users| users as u64),
            increase_rate: rate(&configuration.increase_rate),
            increase_time_secs: secs(configuration.increase_time_secs()),
            decrease_rate: rate(&configuration.decrease_rate),
            decrease_time_secs: secs(configuration.decrease_time_secs()),
            run_time_secs: secs(configuration.run_time_secs()),
            test_plan: configuration.test_plan.as_ref().map(TestPlan::to_string),
            hold_ends_in_secs: None,
            stage: String::new(),
        }
    }

    // Invoke `test_start` transactions if existing.
    async fn run_test_start(&self) -> Result<(), GooseError> {
        // First run global test_start_transaction, if defined.
        if let Some(t) = &self.test_start_transaction {
            info!("running test_start_transaction");
            // Create a one-time-use User to run the test_start_transaction.
            let base_url = goose::get_base_url(
                self.get_configuration_host(),
                None,
                self.defaults.host.clone(),
            )?;
            let mut user = GooseUser::single_with_client(
                base_url,
                &self.configuration,
                self.client_strategy
                    .as_ref()
                    .map(client::ClientStrategy::user_client)
                    .transpose()?,
            )?;
            let function = &t.function;
            let _ = function(&mut user).await;
        }
        Ok(())
    }

    // Invoke `test_stop` transactions if existing.
    async fn run_test_stop(&self) -> Result<(), GooseError> {
        // First run global test_stop_transaction, if defined.
        if let Some(t) = &self.test_stop_transaction {
            info!("running test_stop_transaction");
            // Create a one-time-use User to run the test_stop_transaction.
            let base_url = goose::get_base_url(
                self.get_configuration_host(),
                None,
                self.defaults.host.clone(),
            )?;
            let mut user = GooseUser::single_with_client(
                base_url,
                &self.configuration,
                self.client_strategy
                    .as_ref()
                    .map(client::ClientStrategy::user_client)
                    .transpose()?,
            )?;
            let function = &t.function;
            let _ = function(&mut user).await;
        }
        Ok(())
    }

    // Create a GooseAttackRunState object and do all initialization required
    // to start a [`GooseAttack`](./struct.GooseAttack.html).
    async fn initialize_attack(&mut self) -> Result<GooseAttackRunState, GooseError> {
        trace!("initialize_attack");

        // Create a single channel used to send metrics from GooseUser threads
        // to the dedicated metrics processor task.
        let (all_threads_metrics_tx, metrics_rx): (
            flume::Sender<GooseMetric>,
            flume::Receiver<GooseMetric>,
        ) = flume::unbounded();

        // Create a channel for sending commands from the main loop to the
        // metrics processor task.
        let (metrics_cmd_tx, metrics_cmd_rx): (
            flume::Sender<MetricsCommand>,
            flume::Receiver<MetricsCommand>,
        ) = flume::unbounded();

        // Create a single channel to allow GooseUser threads to notify the
        // parent thread when they exit.
        let (all_threads_shutdown_tx, shutdown_rx): (flume::Sender<usize>, flume::Receiver<usize>) =
            flume::unbounded();

        // Telnet and WebSocket send commands to the parent on one channel, and
        // dashboard control on another, which the parent answers first.
        let (control_tx, controller_channel_rx) = (!self.configuration.no_telnet
            || self.configuration.websocket)
            .then(flume::unbounded)
            .unzip();
        #[cfg(feature = "dashboard")]
        let (dashboard_control_tx, dashboard_control_rx) = self
            .configuration
            .dashboard_control
            .then(flume::unbounded)
            .unzip();
        #[cfg(not(feature = "dashboard"))]
        let dashboard_control_rx = None;

        // Optionally spawn a telnet and/or Websocket Controller thread.
        let listening_controllers = match &control_tx {
            Some(control_tx) => self.setup_controllers(control_tx).await,
            None => controller::ListeningControllers::default(),
        };

        // Optionally spawn the read-only live dashboard HTTP server.
        // Bind failure aborts attack init when --dashboard is set.
        #[cfg(feature = "dashboard")]
        let (
            dashboard_channel_rx,
            dashboard_close_tx,
            dashboard_active_sse,
            dashboard_running_folder,
            dashboard_log_folder,
            dashboard_url,
            dashboard_server,
        ) = match dashboard::setup_dashboard(
            &self.configuration,
            dashboard_control_tx,
            listening_controllers,
        )
        .await?
        {
            Some(setup) => (
                Some(setup.request_rx),
                Some(setup.close_tx),
                Some(setup.active_sse),
                Some(setup.running_folder),
                Some(setup.log_folder),
                Some(setup.url),
                Some(setup.server),
            ),
            None => (None, None, None, None, None, None, None),
        };

        // Grab now() once from the standard library, used by multiple timers in
        // the run state.
        let std_now = std::time::Instant::now();

        // Create the shared atomic request counter registry.
        let request_counter_registry: crate::metrics::GooseRequestCounterRegistry =
            Arc::new(Mutex::new(HashMap::new()));

        // Create the shared batch epoch counter (starts at 0).
        let metrics_epoch: crate::metrics::MetricsEpoch =
            Arc::new(std::sync::atomic::AtomicU64::new(0));

        // Spawn the dedicated metrics processor task. It receives raw metrics
        // from user threads and commands from the main loop.
        let processor = MetricsProcessor::new(
            metrics_rx,
            metrics_cmd_rx,
            self.metrics.clone(),
            GraphData::for_metrics_processor(
                self.configuration.records_latency_series(),
                self.configuration.records_synthetic_latency(),
                self.records_latency_columns(),
            ),
            self.configuration.clone(),
            self.scenarios.clone(),
            self.defaults.clone(),
            request_counter_registry.clone(),
            // Logger not yet initialized; this processor is a short-lived
            // placeholder needed to service controller commands during the Idle
            // phase. It will be replaced by reset_run_state() (which initializes
            // the logger) before any user threads are spawned.
            None,
            metrics_epoch.clone(),
            self.keeps_full_graph(),
        );
        let metrics_processor_handle = Some(tokio::spawn(processor.run()));

        let goose_attack_run_state = GooseAttackRunState {
            adjust_user_timer: std_now,
            adjust_user_in_ms: 0,
            active_users: 0,
            completed_users: 0,
            drift_timer: tokio::time::Instant::now(),
            all_threads_metrics_tx,
            all_threads_shutdown_tx,
            metrics_cmd_tx,
            metrics_processor_handle,
            shutdown_rx,
            logger_handle: None,
            all_threads_logger_tx: None,
            throttle_threads_tx: None,
            parent_to_throttle_tx: None,
            controller_channel_rx,
            dashboard_control_rx,
            #[cfg(feature = "dashboard")]
            dashboard_channel_rx,
            #[cfg(feature = "dashboard")]
            dashboard_close_tx,
            #[cfg(feature = "dashboard")]
            dashboard_active_sse,
            #[cfg(feature = "dashboard")]
            dashboard_running_folder,
            #[cfg(feature = "dashboard")]
            dashboard_log_folder,
            #[cfg(feature = "dashboard")]
            dashboard_url,
            #[cfg(feature = "dashboard")]
            dashboard_server,
            metrics_header_displayed: false,
            idle_status_displayed: false,
            users: Vec::new(),
            user_channels: Vec::new(),
            running_users: Vec::new(),
            running_metrics_timer: std_now,
            threshold_check_at: None,
            users_shutdown: HashSet::new(),
            listening_controllers,
            all_users_spawned: false,
            shutdown_after_stop: !self.configuration.no_autostart,
            canceling: false,
            stopping: false,
            request_counter_registry,
            metrics_epoch,
        };

        // Catch ctrl-c to allow clean shutdown to display metrics.
        util::setup_ctrlc_handler();

        Ok(goose_attack_run_state)
    }

    // Determine how long has elapsed since this step started.
    fn step_elapsed(&mut self) -> u128 {
        if let Some(step_started) = self.step_started {
            step_started.elapsed().as_millis()
        } else if let Some(started) = self.started {
            started.elapsed().as_millis()
        } else {
            // An idle load test.
            0
        }
    }

    // Add delay before starting next step if there's time remaining.
    async fn end_of_step_delay(&mut self) {
        // Determine if there's remaining time in this step.
        let elapsed = self.step_elapsed() as u64;
        if elapsed < self.test_plan.steps[self.test_plan.current].1 as u64 {
            let remainder = self.test_plan.steps[self.test_plan.current].1 as u64 - elapsed;
            // Sleep 500ms, or all remaining time if less -- this will continue looping until all time remaining
            // on the current step runs out, waking up regularly to handle events like the load test being
            // canceled or a controller command.
            let maximum_sleep = 500;
            let sleep_duration = if remainder > maximum_sleep {
                Duration::from_millis(maximum_sleep)
            } else {
                Duration::from_millis(remainder)
            };
            tokio::time::sleep(sleep_duration).await
        }
    }

    // Increase the number of active [`GooseUser`](./goose/struct.GooseUser.html) threads in the
    // active [`GooseAttack`](./struct.GooseAttack.html).
    async fn increase_attack(
        &mut self,
        goose_attack_run_state: &mut GooseAttackRunState,
    ) -> Result<(), GooseError> {
        // Determine if enough users have been launched.
        let all_users_launched =
            goose_attack_run_state.active_users >= self.test_plan.steps[self.test_plan.current].0;

        if all_users_launched {
            // All users were increased, delay until test_plan step time has elapsed.
            self.end_of_step_delay().await;

            if self.step_elapsed() as usize >= self.test_plan.steps[self.test_plan.current].1 {
                // Automatically reset metrics if appropriate.
                self.reset_metrics(goose_attack_run_state).await?;

                // Moving to the next phase, reset adjust_user_in_ms.
                goose_attack_run_state.adjust_user_in_ms = 0;

                // Advance to the next TestPlan step.
                self.advance_test_plan(goose_attack_run_state);
            }
        } else {
            // If this is the first load plan step, then there were no previously started users.
            let previous_users = if self.test_plan.current == 0 {
                0
            // Otherwise retreive the number of users configured in the previous step.
            } else {
                self.test_plan.steps[self.test_plan.current - 1].0
            };

            // Sanity check: increase_attack can only be called if the number of users is increasing
            // in the current step.
            assert!(self.test_plan.steps[self.test_plan.current].0 > previous_users);

            // Divide the number of new users to launch by the time configured to launch them.
            let increase_rate: f32 = (self.test_plan.steps[self.test_plan.current].0 - previous_users)
                as f32
                / self.test_plan.steps[self.test_plan.current].1 as f32
                // Convert from milliseconds to seconds.
                * 1_000.0;

            // Determine if it's time to spawn a GooseUser.
            if goose_attack_run_state.adjust_due() {
                let mut thread_user = self
                    .weighted_users
                    .pop()
                    .expect("insufficent weighted_users");
                // The next GooseUser is due one interval, 1 second divided by the
                // increase_rate, after this one was.
                goose_attack_run_state
                    .schedule_next_adjust(Duration::from_secs_f64(1.0 / f64::from(increase_rate)));

                // Remember which task group this user is using.
                thread_user.weighted_users_index = self.metrics.total_users;

                // Create a per-thread channel allowing parent thread to control child threads.
                let (parent_sender, thread_receiver): (
                    flume::Sender<GooseUserCommand>,
                    flume::Receiver<GooseUserCommand>,
                ) = flume::unbounded();
                goose_attack_run_state.user_channels.push(parent_sender);
                goose_attack_run_state.running_users.push((
                    thread_user.scenarios_index,
                    thread_user.weighted_users_index,
                ));
                // The user runs its scenario from now, iteration or not.
                let _ = goose_attack_run_state
                    .metrics_cmd_tx
                    .send(MetricsCommand::UserStarted {
                        scenario_index: thread_user.scenarios_index,
                        user: thread_user.weighted_users_index,
                    });

                // Clone the logger_tx if enabled, otherwise is None.
                thread_user
                    .logger
                    .clone_from(&goose_attack_run_state.all_threads_logger_tx);

                // Copy the GooseUser-throttle receiver channel, used by all threads.
                thread_user.throttle = if self.configuration.throttle_requests() > 0 {
                    Some(goose_attack_run_state.throttle_threads_tx.clone().unwrap())
                } else {
                    None
                };

                // Copy the GooseUser-metrics sender channel, used by all threads.
                thread_user.metrics_channel =
                    Some(goose_attack_run_state.all_threads_metrics_tx.clone());

                // Initialize the per-user metrics batch accumulator.
                let epoch = goose_attack_run_state
                    .metrics_epoch
                    .load(std::sync::atomic::Ordering::Relaxed);
                thread_user.metrics_batch = Some(crate::metrics::GooseMetricBatch::new(epoch));
                thread_user.metrics_epoch = Some(goose_attack_run_state.metrics_epoch.clone());

                // Share the atomic request counter registry with this user thread.
                thread_user.request_counters =
                    Some(goose_attack_run_state.request_counter_registry.clone());

                // Copy the GooseUser-shutdown sender channel, used by all threads.
                thread_user.shutdown_channel =
                    Some(goose_attack_run_state.all_threads_shutdown_tx.clone());

                // Copy the appropriate task_set into the thread.
                let thread_scenario = self.scenarios[thread_user.scenarios_index].clone();

                // Start at 1 as this is human visible.
                let thread_number = self.metrics.total_users + 1;

                // Align request `elapsed` (graph second) with the continuous series
                // clock so RPS and active-users charts share one timeline. Weighted
                // users are often created before the run starts; mid-test increases
                // create users later — both must report seconds since series start.
                if let Some(series_started) = self.series_started {
                    thread_user.started = series_started;
                }

                // Launch a new user.
                let user = tokio::spawn(user::user_main(
                    thread_number,
                    thread_scenario,
                    thread_user,
                    thread_receiver,
                ));

                goose_attack_run_state.users.push(user);
                goose_attack_run_state.active_users += 1;
                self.metrics.total_users += 1;
                if goose_attack_run_state.active_users > self.metrics.maximum_users {
                    self.metrics.maximum_users = goose_attack_run_state.active_users;
                }

                if let Some(running_metrics) = self.configuration.running_metrics {
                    if util::ms_timer_expired(
                        goose_attack_run_state.running_metrics_timer,
                        running_metrics,
                    ) {
                        goose_attack_run_state.running_metrics_timer = time::Instant::now();
                        self.update_duration();
                        // Send display command to the metrics processor task.
                        let _ = goose_attack_run_state.metrics_cmd_tx.send(
                            MetricsCommand::DisplayRunning {
                                duration: self.metrics.duration,
                                total_users: self.metrics.total_users,
                                maximum_users: self.metrics.maximum_users,
                            },
                        );
                    }
                }
            } else {
                goose_attack_run_state.sleep_until_adjust().await;
            }
        }

        Ok(())
    }

    // Maintain the number of active [`GooseUser`](./goose/struct.GooseUser.html) threads in the
    // active [`GooseAttack`](./struct.GooseAttack.html).
    async fn maintain_attack(
        &mut self,
        goose_attack_run_state: &mut GooseAttackRunState,
    ) -> Result<(), GooseError> {
        // Determine if it's time to move to the next test plan step.
        if self.test_plan.current < self.test_plan.steps.len()
            && util::ms_timer_expired(
                self.step_started.unwrap(),
                self.test_plan.steps[self.test_plan.current].1,
            )
        {
            self.advance_test_plan(goose_attack_run_state);
        } else {
            // Subtract the time spent doing other things, running the main parent loop twice
            // per second.
            goose_attack_run_state.drift_timer = util::sleep_minus_drift(
                time::Duration::from_millis(500),
                goose_attack_run_state.drift_timer,
            )
            .await;
        }

        Ok(())
    }

    // Decrease the number of active [`GooseUser`](./goose/struct.GooseUser.html) threads in the
    // active [`GooseAttack`](./struct.GooseAttack.html).
    async fn decrease_attack(
        &mut self,
        goose_attack_run_state: &mut GooseAttackRunState,
    ) -> Result<(), GooseError> {
        // Sanity check: if there's more than one step the first step can't decrease the attack. If there's
        // only one step then an idle load test may be being shut down through the controller.
        if self.test_plan.steps.len() > 1 {
            assert!(self.test_plan.current > 0);
        }

        // If this is the last step of the load test and there are 0 users, shut down.
        if goose_attack_run_state.active_users == 0
            // Subtract 1 from len() as it starts at 1 while current starts at 0.
            && self.test_plan.current >= self.test_plan.steps.len() - 1
        {
            // If throttle is enabled, tell throttle thread the load test is over.
            if let Some(throttle_tx) = goose_attack_run_state.parent_to_throttle_tx.clone() {
                let _ = throttle_tx.send(false);
            }

            // Take the users vector out of the GooseAttackRunState object so it can be
            // consumed by futures::future::join_all().
            let users = std::mem::take(&mut goose_attack_run_state.users);
            futures::future::join_all(users).await;
            debug!("all users exited");

            // If the logger thread is enabled, tell it to flush and exit.
            if goose_attack_run_state.logger_handle.is_some() {
                if let Err(e) = goose_attack_run_state
                    .all_threads_logger_tx
                    .clone()
                    .unwrap()
                    .send(None)
                {
                    warn!("unexpected error telling logger thread to exit: {e}");
                };
                // Take logger out of the GooseAttackRunState object so it can be
                // consumed by tokio::join!().
                let logger = std::mem::take(&mut goose_attack_run_state.logger_handle);
                let _ = tokio::join!(logger.unwrap());
            }

            // Run test_stop and mark the metrics final, only when a run
            // happened since the last time: leaving Idle has nothing to stop,
            // and test_stop already ran when the run itself ended.
            if self.run_in_progress {
                self.stop_attack().await?;
            }

            // Record final users for the users-per-second graph before shutting
            // down the metrics processor. Use the continuous series clock so
            // this sample stays aligned with ramp history after metrics reset.
            if self.series_started.is_some() {
                let _ = goose_attack_run_state
                    .metrics_cmd_tx
                    .send(MetricsCommand::RecordUsers {
                        active_users: goose_attack_run_state.active_users,
                        elapsed_secs: self.series_elapsed_secs(),
                    });
            }

            // Tell the metrics processor to flush all remaining metrics and
            // return the final state for reporting. The processor may have
            // already been shut down (e.g., controller Stop followed by
            // Shutdown), so handle the send failure gracefully.
            // Note: do NOT call update_duration() here — the duration was already
            // set by the main loop iteration, and the shutdown work above (waiting
            // for users, flushing logger, stop_attack) adds extra time that would
            // inflate the duration past the expected value.
            let (respond_tx, respond_rx) = tokio::sync::oneshot::channel();
            if goose_attack_run_state
                .metrics_cmd_tx
                .send(MetricsCommand::Shutdown {
                    duration: self.metrics.duration,
                    total_users: self.metrics.total_users,
                    maximum_users: self.metrics.maximum_users,
                    respond: respond_tx,
                })
                .is_ok()
            {
                if let Ok((mut final_metrics, final_graph_data)) = respond_rx.await {
                    // Await the processor task to ensure clean shutdown.
                    if let Some(handle) = goose_attack_run_state.metrics_processor_handle.take() {
                        let _ = handle.await;
                    }

                    // Merge main-loop-only fields into the processor's metrics.
                    final_metrics.history = std::mem::take(&mut self.metrics.history);
                    final_metrics.hosts.clone_from(&self.metrics.hosts);
                    final_metrics.hash = self.metrics.hash;
                    final_metrics.display_metrics = self.metrics.display_metrics;
                    final_metrics.display_status_codes = self.metrics.display_status_codes;
                    final_metrics.final_metrics = self.metrics.final_metrics;
                    self.metrics = final_metrics;
                    self.graph_data = final_graph_data;
                }
            }
            // Judge every threshold on the final metrics, before any report is
            // written, so every report shows the results.
            if self.run_in_progress && !self.configuration.thresholds.is_empty() {
                self.metrics.thresholds = threshold::evaluate(
                    &self.configuration.thresholds,
                    &self.metrics,
                    threshold::Check::Final,
                    self.metrics
                        .threshold_abort
                        .as_ref()
                        .map(|(index, observed)| (*index, observed.as_str())),
                    self.elapsed,
                );
                for warning in
                    threshold::unknown_requests(&self.configuration.thresholds, &self.metrics)
                {
                    warn!("{warning}");
                }
            }
            // The load test is fully stopped at this point.
            self.metrics
                .history
                .push(TestPlanHistory::step(TestPlanStepAction::Finished, 0));
            // Write the --report-file reports and Save report's, only when a
            // run happened since the last time (not on a shutdown from Idle).
            let ran = self.run_in_progress;
            let reports = if ran {
                self.write_end_of_run(!goose_attack_run_state.shutdown_after_stop)
                    .await
            } else {
                Ok(())
            };
            self.run_in_progress = false;
            // A bare --goose-log stays open in the run's folder until the next
            // run starts, and the folder stays reserved while the log is open.
            if !self.goose_log_in_folder() {
                self.output.release_folder();
            }
            self.output.end_save_report_hold();
            // End the Goose log's gzip member, so the finished run's log is
            // whole while Idle; lines until the next run are whole members.
            logger::finish_goose_log();
            #[cfg(feature = "dashboard")]
            if let Some(running) = &goose_attack_run_state.dashboard_running_folder {
                running.set(None);
            }
            if let Err(e) = reports {
                // Print the final metrics before failing on a report.
                if self.metrics.display_metrics {
                    info!(
                        "printing final metrics after {} seconds...",
                        self.metrics.duration
                    );
                    print!("{}", self.metrics);
                }
                return Err(e);
            }
            // After an autostarted run, wait for a dashboard tab that is
            // open so the run's report can still be downloaded from it.
            #[cfg(feature = "dashboard")]
            let wait_for_dashboard = ran
                && goose_attack_run_state.shutdown_after_stop
                && self.should_wait_for_dashboard(goose_attack_run_state);
            #[cfg(not(feature = "dashboard"))]
            let wait_for_dashboard = false;
            // Shutdown Goose or go into an idle waiting state.
            if goose_attack_run_state.shutdown_after_stop && !wait_for_dashboard {
                self.set_attack_phase(goose_attack_run_state, AttackPhase::Shutdown);
            } else {
                // Print metrics, if enabled.
                if self.metrics.display_metrics {
                    println!("{}", self.metrics);
                }
                #[cfg(feature = "dashboard")]
                if wait_for_dashboard {
                    self.start_dashboard_wait(goose_attack_run_state);
                }
                // Return to an Idle state.
                self.set_attack_phase(goose_attack_run_state, AttackPhase::Idle);
            }
        // If this is not the last step of the load test and sufficient users decreased, move to next step.
        } else if goose_attack_run_state.active_users
            <= self.test_plan.steps[self.test_plan.current].0
        {
            // Be sure step takes as long as it was configured to.
            self.end_of_step_delay().await;

            // Then advance to next step.
            if self.step_elapsed() as usize >= self.test_plan.steps[self.test_plan.current].1 {
                // Moving to the next phase, reset adjust_user_in_ms.
                goose_attack_run_state.adjust_user_in_ms = 0;

                // Advance to the next TestPlan step.
                self.advance_test_plan(goose_attack_run_state);
            }
        // Otherwise, decrease a user when ready.
        } else {
            // Retreive the number of users configured in the previous step.
            let previous_users = self.test_plan.steps[self.test_plan.current - 1].0;

            // Divide the number of users to decrease by the time configured to decrease them.
            let decrease_rate: f32 = (previous_users - self.test_plan.steps[self.test_plan.current].0)
                as f32
                / self.test_plan.steps[self.test_plan.current].1 as f32
                // Convert from milliseconds to seconds.
                * 1_000.0;

            // Determine if it's time to decrease a GooseUser.
            if goose_attack_run_state.adjust_due() {
                // The next GooseUser is due to stop one interval, 1 second divided
                // by the decrease_rate, after this one was.
                goose_attack_run_state
                    .schedule_next_adjust(Duration::from_secs_f64(1.0 / f64::from(decrease_rate)));

                goose_attack_run_state.running_users.pop();
                if let Some(send_to_user) = goose_attack_run_state.user_channels.pop() {
                    match send_to_user.send(GooseUserCommand::Exit) {
                        Ok(_) => {
                            debug!(
                                "telling user {} to exit",
                                goose_attack_run_state.completed_users
                            );
                        }
                        Err(e) => {
                            // Error is expected if this user already shut down.
                            if !goose_attack_run_state
                                .users_shutdown
                                .contains(&goose_attack_run_state.completed_users)
                            {
                                info!(
                                    "failed to tell user {} to exit: {}",
                                    goose_attack_run_state.completed_users, e
                                );
                            }
                        }
                    }
                    goose_attack_run_state.completed_users += 1;
                    goose_attack_run_state.active_users -= 1;
                }
            } else {
                goose_attack_run_state.sleep_until_adjust().await;
            }
        }

        Ok(())
    }

    // ========================================================================
    // Staged control helpers (shared by Controllers and dashboard control)
    //
    // Soft vs hard errors:
    // - Soft: expected rejections → ControlOutcome { ok: false, error: Some(...) }
    // - Hard: Result::Err(GooseError) (weight_scenario_users on a users or test
    //   plan increase; reset_run_state in start finish; cancel_attack).
    // `GooseAttack::control` replies with the outcome, or `internal` on a hard
    // error before returning it, so every caller still waiting gets an answer.
    // ========================================================================

    /// Build a [`ControlOutcome`] snapshot from the current attack/run state.
    fn control_outcome(
        &self,
        goose_attack_run_state: &GooseAttackRunState,
        ok: bool,
        error: Option<&'static str>,
        message: impl Into<String>,
        target_users: Option<usize>,
    ) -> ControlOutcome {
        ControlOutcome {
            ok,
            error,
            message: message.into(),
            phase: attack_phase_str(self.attack_phase).to_string(),
            active_users: goose_attack_run_state.active_users,
            target_users,
            field: None,
            #[cfg(feature = "dashboard")]
            settings: None,
        }
    }

    /// Pre-reply Start work: validate Idle, build plan, prepare, enter Increase.
    ///
    /// Soft rejections: `invalid_phase`, `prepare_failed`.
    /// On [`ControlStartBegin::Accepted`], the caller must reply success immediately,
    /// then invoke [`Self::control_start_finish`].
    pub(crate) fn control_start_begin(
        &mut self,
        goose_attack_run_state: &mut GooseAttackRunState,
    ) -> Result<ControlStartBegin, GooseError> {
        // Can only start an idle load test.
        if self.attack_phase != AttackPhase::Idle {
            return Ok(ControlStartBegin::Rejected(self.control_outcome(
                goose_attack_run_state,
                false,
                Some("invalid_phase"),
                "unable to start load test, it is not idle",
                None,
            )));
        }

        let prepared = TestPlan::build(&self.configuration).and_then(|test_plan| {
            self.test_plan = test_plan;
            self.prepare_load_test()
        });
        // The shape is the run's: a refused Start leaves none.
        self.run_shape = prepared
            .is_ok()
            .then(|| run_shape::RunShape::for_configuration(&self.configuration))
            .flatten();
        if let Err(e) = prepared {
            // Soft: do not move to Increase if unable to prepare load test. Name
            // the cause: prepare_load_test refuses no host and no users itself,
            // with the options these constants name.
            let (reason, field) = match e {
                GooseError::InvalidOption { option, detail, .. } if option == NO_HOST_OPTION => {
                    let reason = match HOST_TRANSACTIONS
                        .iter()
                        .find(|transaction| detail == no_transaction_host_detail(transaction))
                    {
                        Some(transaction) => {
                            format!("no host is configured for the {transaction} transaction")
                        }
                        None => "no host is configured".to_string(),
                    };
                    (reason, Some("host"))
                }
                GooseError::InvalidOption { option, .. } if option == NO_USERS_OPTION => {
                    ("there are no users to start".to_string(), None)
                }
                GooseError::InvalidOption { detail, .. } => (detail, None),
                e => (e.to_string(), None),
            };
            let outcome = self.control_outcome(
                goose_attack_run_state,
                false,
                Some("prepare_failed"),
                format!("unable to start load test, {reason}"),
                None,
            );
            return Ok(ControlStartBegin::Rejected(match field {
                Some(field) => outcome.with_field(field),
                None => outcome,
            }));
        }

        self.set_attack_phase(goose_attack_run_state, AttackPhase::Increase);

        // Prefer configured users; fall back to first non-zero plan step.
        let target_users = self.configuration.users.or_else(|| {
            self.test_plan
                .steps
                .iter()
                .map(|(users, _)| *users)
                .find(|&u| u > 0)
        });

        Ok(ControlStartBegin::Accepted(self.control_outcome(
            goose_attack_run_state,
            true,
            None,
            "load test started",
            target_users,
        )))
    }

    /// Post-reply Start work: reset run state and push Increasing history.
    ///
    /// Hard errors only (`reset_run_state` / metrics init). Caller has already
    /// replied success to the client.
    pub(crate) async fn control_start_finish(
        &mut self,
        goose_attack_run_state: &mut GooseAttackRunState,
    ) -> Result<(), GooseError> {
        self.reset_run_state(goose_attack_run_state).await?;
        self.metrics
            .history
            .push(TestPlanHistory::step(TestPlanStepAction::Increasing, 0));
        Ok(())
    }

    /// Begin canceling a running load test (Increase/Maintain → Decrease/Canceling).
    ///
    /// Soft failure: `invalid_phase` when not Increase|Maintain (Decrease is not
    /// stoppable). Hard errors: `cancel_attack` if it returns Err.
    ///
    /// Success leaves phase as **decrease** (not idle); Idle is eventual after
    /// the cancel ramp completes with `shutdown_after_stop = false`.
    pub(crate) async fn control_stop(
        &mut self,
        goose_attack_run_state: &mut GooseAttackRunState,
    ) -> Result<ControlOutcome, GooseError> {
        if ![AttackPhase::Increase, AttackPhase::Maintain].contains(&self.attack_phase) {
            return Ok(self.control_outcome(
                goose_attack_run_state,
                false,
                Some("invalid_phase"),
                "load test not running, failed to stop",
                None,
            ));
        }

        // Don't shutdown when load test is stopped by controller; remain idle instead.
        goose_attack_run_state.shutdown_after_stop = false;
        // Don't automatically restart the load test.
        self.configuration.no_autostart = true;
        self.set_ended_by(runs::EndedBy::Stopped, None);
        self.cancel_attack(goose_attack_run_state).await?;

        Ok(self.control_outcome(
            goose_attack_run_state,
            true,
            None,
            "load test stopped",
            Some(0),
        ))
    }

    /// Shut Goose down from Idle (dashboard Quit), as Ctrl-C does there.
    ///
    /// Soft failure: `invalid_phase` in any phase but Idle, so a running load
    /// test must be stopped first.
    pub(crate) fn control_quit(
        &mut self,
        goose_attack_run_state: &mut GooseAttackRunState,
    ) -> ControlOutcome {
        if self.attack_phase != AttackPhase::Idle {
            return self.control_outcome(
                goose_attack_run_state,
                false,
                Some("invalid_phase"),
                "unable to quit, be sure the load test is idle",
                None,
            );
        }
        info!("[control]: quit, shutting down");
        self.shutdown_from_idle(goose_attack_run_state);
        self.control_outcome(
            goose_attack_run_state,
            true,
            None,
            "goose is shutting down",
            None,
        )
    }

    /// Refuse to reconfigure `what` (users or the test plan) while a cancel
    /// (Stop, `shutdown`, Ctrl-C) is in progress: rebuilding the plan then
    /// would replace its ramp to zero and leave the load test running. Also
    /// refused in Shutdown, where there is no plan left to change.
    fn refuse_reconfigure(
        &self,
        goose_attack_run_state: &GooseAttackRunState,
        what: &str,
    ) -> Option<ControlOutcome> {
        let message = if goose_attack_run_state.stopping {
            format!("load test is stopping, failed to reconfigure {what}")
        } else if self.attack_phase == AttackPhase::Shutdown {
            format!("load test not idle, failed to reconfigure {what}")
        } else {
            return None;
        };
        Some(self.control_outcome(
            goose_attack_run_state,
            false,
            Some("invalid_phase"),
            message,
            None,
        ))
    }

    /// Set absolute target user count (Controller `users` command), already
    /// bounded by [`ControllerCommand::users`](controller::ControllerCommand).
    ///
    /// Soft failure: `invalid_phase` as [`Self::refuse_reconfigure`] says, and
    /// while a test plan runs, as the plan sets users. In Idle, refused as
    /// `conflicting_settings` below 2 users while an increase or decrease
    /// time is set, as on the command line. A users ramp's own ramp down is
    /// not a cancel: a new count abandons it and holds until stopped.
    /// Hard error: `weight_scenario_users` when increasing while running.
    pub(crate) fn control_set_users(
        &mut self,
        goose_attack_run_state: &mut GooseAttackRunState,
        new_users: usize,
    ) -> Result<ControlOutcome, GooseError> {
        if let Some(refused) = self.refuse_reconfigure(goose_attack_run_state, "users") {
            return Ok(refused.with_field("users"));
        }
        if self.attack_phase == AttackPhase::Idle {
            if new_users < 2 {
                let time = if self.configuration.increase_time_secs() > 0 {
                    Some("increase_time")
                } else if self.configuration.decrease_time_secs() > 0 {
                    Some("decrease_time")
                } else {
                    None
                };
                if let Some(time) = time {
                    return Ok(self
                        .control_outcome(
                            goose_attack_run_state,
                            false,
                            Some("conflicting_settings"),
                            format!("failed to configure users, {time} needs at least 2 users"),
                            None,
                        )
                        .with_field("users"));
                }
            }
            // If the load test is idle, simply update the configuration.
            // Safe when `current` has advanced past the last plan step.
            let current_users = self.current_target_users();
            info!("changing users from {current_users:?} to {new_users}");
        } else {
            let Some(mut shape) = self.run_shape.take() else {
                // A test plan sets users itself.
                return Ok(self
                    .control_outcome(
                        goose_attack_run_state,
                        false,
                        Some("invalid_phase"),
                        "failed to reconfigure users, the test plan sets users: edit the plan, or stop and switch mode",
                        None,
                    )
                    .with_field("users"));
            };
            info!(
                "changing users from {} to {new_users}",
                goose_attack_run_state.active_users
            );
            // Determine how long has elapsed since this step started.
            let elapsed = self.step_elapsed() as usize;

            // Determine how many users to increase or decrease by.
            let user_difference = goose_attack_run_state.active_users.abs_diff(new_users);

            // Determine how quickly to adjust user count, using
            // increase_rate when adding users and decrease_rate when
            // removing users.
            let rate = if new_users > goose_attack_run_state.active_users {
                if let Some(increase_rate) = self.configuration.increase_rate.as_ref() {
                    util::parse_rate(Some(increase_rate.to_string()))
                } else {
                    util::parse_rate(None)
                }
            } else if let Some(decrease_rate) = self.configuration.decrease_rate.as_ref() {
                util::parse_rate(Some(decrease_rate.to_string()))
            } else if let Some(increase_rate) = self.configuration.increase_rate.as_ref() {
                util::parse_rate(Some(increase_rate.to_string()))
            } else {
                util::parse_rate(None)
            };
            let total_time = run_shape::ramp_ms(user_difference, rate);

            // Allocate more users if increasing users (hard Err on failure),
            // before anything changes.
            if new_users > goose_attack_run_state.active_users {
                let weighted = self.weight_scenario_users(user_difference);
                match weighted {
                    Ok(weighted) => self.weighted_users = weighted,
                    Err(e) => {
                        self.run_shape = Some(shape);
                        return Err(e);
                    }
                }
            }

            // The rest of the run, generated again from its shape: a ramp to
            // the new count, then the hold and ramp down still ahead.
            self.test_plan.steps = shape.retarget(
                goose_attack_run_state.active_users,
                elapsed,
                new_users,
                total_time,
            );
            self.run_shape = Some(shape);

            // Reset the current step to what was happening when reconfiguration happened.
            self.test_plan.current = 0;

            // Finally, advance to the next step to adjust user count.
            self.advance_test_plan(goose_attack_run_state);
        }
        // Clear configured test plan only when the command is accepted:
        // refusals must not destroy an existing plan. Also update the running
        // configuration (this impacts if the test is stopped and then
        // restarted through the controller).
        self.configuration.test_plan = None;
        self.configuration.users = Some(new_users);
        Ok(self.control_outcome(
            goose_attack_run_state,
            true,
            None,
            "users configured",
            Some(new_users),
        ))
    }

    /// Switch a running load test to `test_plan`, from its first step and
    /// the current user count, replacing a users ramp and its shape.
    ///
    /// Hard error: `weight_scenario_users`.
    pub(crate) fn run_test_plan(
        &mut self,
        goose_attack_run_state: &mut GooseAttackRunState,
        test_plan: TestPlan,
    ) -> Result<(), GooseError> {
        self.run_shape = None;
        self.test_plan = test_plan;
        // Reallocate users.
        self.weighted_users = self.weight_scenario_users(self.test_plan.total_users())?;
        // Insert the current state of the test plan before the new test plan.
        let elapsed = self.step_elapsed() as usize;
        self.test_plan
            .steps
            .insert(0, (goose_attack_run_state.active_users, elapsed));
        // Finally, advance to the next step to adjust user count.
        self.advance_test_plan(goose_attack_run_state);
        Ok(())
    }

    /// What would have no host with `configuration`: a `test_start` or
    /// `test_stop` transaction, or a scenario, as a Start checks them but
    /// without resolving a url.
    pub(crate) fn without_host(&self, configuration: &GooseConfiguration) -> Option<String> {
        if configuration.host().is_some() || self.defaults.host.is_some() {
            return None;
        }
        if self.test_start_transaction.is_some() {
            return Some(format!("the {} transaction", HOST_TRANSACTIONS[0]));
        }
        if self.test_stop_transaction.is_some() {
            return Some(format!("the {} transaction", HOST_TRANSACTIONS[1]));
        }
        self.scenarios
            .iter()
            .find(|scenario| scenario.host.is_none())
            .map(|scenario| format!("the {} scenario", scenario.name))
    }

    // Quickly abort and shut down an active [`GooseAttack`](./struct.GooseAttack.html).
    async fn cancel_attack(
        &mut self,
        goose_attack_run_state: &mut GooseAttackRunState,
    ) -> Result<(), GooseError> {
        if goose_attack_run_state.active_users == 0 {
            // A stop or Ctrl-C in the tick of its start, or a second shutdown from Idle:
            // a plan maintaining 0 users would never end.
            goose_attack_run_state.adjust_user_in_ms = 0;
            self.stop_without_users(goose_attack_run_state);
            self.metrics
                .history
                .push(TestPlanHistory::step(TestPlanStepAction::Canceling, 0));
            return Ok(());
        }

        // Determine how long has elapsed since this step started.
        let elapsed = self.step_elapsed() as usize;

        // Reset the test_plan to stop all users quickly.
        self.test_plan.steps = vec![
            // Record how many active users there are currently.
            (goose_attack_run_state.active_users, elapsed),
            // Record how long the attack ran in this step.
            (0, 0),
        ];
        // Reset the current step to what was happening when canceled.
        self.test_plan.current = 0;

        // Moving to the last phase, reset adjust_user_in_ms.
        goose_attack_run_state.adjust_user_in_ms = 0;

        // Refuse user count changes until the run reaches Idle; a cancel
        // ends the run's shape.
        goose_attack_run_state.stopping = true;
        self.run_shape = None;

        // Advance to the final decrease phase.
        self.advance_test_plan(goose_attack_run_state);

        // Load test isn't just decreasing, it's canceling.
        self.metrics
            .history
            .last_mut()
            .expect("tried to cancel load test with no history")
            .action = TestPlanStepAction::Canceling;

        Ok(())
    }

    // Cleanly shut down the [`GooseAttack`](./struct.GooseAttack.html).
    async fn stop_attack(&mut self) -> Result<(), GooseError> {
        // Run any configured test_stop() functions.
        self.run_test_stop().await?;

        // Percentile and errors are only displayed when the load test is finished.
        self.metrics.final_metrics = true;

        Ok(())
    }

    // Reset the GooseAttackRunState before starting a load test. This is to allow a Controller
    // to stop and start the load test multiple times, for example from a UI.
    async fn reset_run_state(
        &mut self,
        goose_attack_run_state: &mut GooseAttackRunState,
    ) -> Result<(), GooseError> {
        // A new run starts without the previous run's cancel.
        reset_killswitch();

        // Run any configured test_start() functions.
        self.run_test_start().await?;

        // Prepare to collect metrics, if enabled.
        self.metrics = GooseMetrics::default();
        if !self.configuration.no_metrics {
            self.metrics.initialize_transaction_metrics(
                &self.scenarios,
                &self.configuration,
                &self.defaults,
            )?;
            self.metrics
                .initialize_scenario_metrics(&self.scenarios, &self.configuration);
            if !self.configuration.no_print_metrics {
                self.metrics.display_metrics = true;
            }
            // Only display status codes if not disaled.
            self.metrics.display_status_codes = !self.configuration.no_status_codes;

            // Initialize CO tracker if mitigation is enabled
            if let Some(co_mitigation) = &self.configuration.co_mitigation {
                if co_mitigation != &metrics::GooseCoordinatedOmissionMitigation::Disabled {
                    self.metrics.coordinated_omission_metrics = Some(
                        metrics::CoordinatedOmissionMetrics::new(co_mitigation.clone()),
                    );
                }
            }
        }

        // Reset the run state.
        let std_now = std::time::Instant::now();
        goose_attack_run_state.adjust_user_timer = std_now;
        goose_attack_run_state.adjust_user_in_ms = 0;
        goose_attack_run_state.active_users = 0;
        goose_attack_run_state.drift_timer = tokio::time::Instant::now();
        goose_attack_run_state.metrics_header_displayed = false;
        goose_attack_run_state.idle_status_displayed = false;
        goose_attack_run_state.users = Vec::new();
        goose_attack_run_state.user_channels = Vec::new();
        goose_attack_run_state.running_users = Vec::new();
        goose_attack_run_state.running_metrics_timer = std_now;
        // The thresholds are checked from when the run first enters Maintain.
        goose_attack_run_state.threshold_check_at = None;
        goose_attack_run_state.shutdown_after_stop = !self.configuration.no_autostart;
        goose_attack_run_state.all_users_spawned = false;

        // Choose this run's folder, when it may need one, before any log opens
        // in it, and start the Goose log's gzip member for the run.
        self.start_run_folder()?;
        logger::start_goose_log();
        #[cfg(feature = "dashboard")]
        if let Some(running) = &goose_attack_run_state.dashboard_running_folder {
            running.set(
                self.output
                    .folder
                    .as_ref()
                    .map(|folder| folder.path.as_path()),
            );
        }
        // A bare --goose-log moved into this run's folder, and stays open there
        // after the run ends.
        #[cfg(feature = "dashboard")]
        if self.goose_log_in_folder() {
            if let (Some(log_folder), Some(folder)) = (
                &goose_attack_run_state.dashboard_log_folder,
                &self.output.folder,
            ) {
                log_folder.set(Some(&folder.path));
            }
        }

        // If enabled, spawn a logger thread.
        let (logger_handle, all_threads_logger_tx) = self
            .configuration
            .setup_loggers(&self.defaults, self.output.folder.as_ref())
            .await?;
        goose_attack_run_state.logger_handle = logger_handle;
        goose_attack_run_state.all_threads_logger_tx = all_threads_logger_tx;

        // If enabled, spawn a throttle thread.
        let (throttle_threads_tx, parent_to_throttle_tx) = self.setup_throttle().await;
        goose_attack_run_state.throttle_threads_tx = throttle_threads_tx;
        goose_attack_run_state.parent_to_throttle_tx = parent_to_throttle_tx;

        // A new run counts its requests from zero: the atomic counters
        // outlive the processor, and batches from the last run's users are
        // dropped.
        {
            let registry = goose_attack_run_state
                .request_counter_registry
                .lock()
                .expect("request_counter_registry mutex poisoned");
            for counters in registry.values() {
                counters.reset();
            }
        }
        goose_attack_run_state
            .metrics_epoch
            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);

        // Re-create the metrics channel and spawn a fresh processor. It reads
        // Save report as start_run_folder left it, so start_run_folder runs
        // first.
        // The old processor exits when its command channel closes.
        let (all_threads_metrics_tx, metrics_rx): (
            flume::Sender<GooseMetric>,
            flume::Receiver<GooseMetric>,
        ) = flume::unbounded();
        goose_attack_run_state.all_threads_metrics_tx = all_threads_metrics_tx;
        let (metrics_cmd_tx, metrics_cmd_rx) = flume::unbounded();
        let processor = MetricsProcessor::new(
            metrics_rx,
            metrics_cmd_rx,
            self.metrics.clone(),
            GraphData::for_metrics_processor(
                self.configuration.records_latency_series(),
                self.configuration.records_synthetic_latency(),
                self.records_latency_columns(),
            ),
            self.configuration.clone(),
            self.scenarios.clone(),
            self.defaults.clone(),
            goose_attack_run_state.request_counter_registry.clone(),
            goose_attack_run_state.all_threads_logger_tx.clone(),
            goose_attack_run_state.metrics_epoch.clone(),
            self.keeps_full_graph(),
        );
        goose_attack_run_state.metrics_cmd_tx = metrics_cmd_tx;
        if let Some(handle) = goose_attack_run_state.metrics_processor_handle.take() {
            let _ = handle.await;
        }
        goose_attack_run_state.metrics_processor_handle = Some(tokio::spawn(processor.run()));

        // Try to create the requested report files, to confirm access.
        self.create_reports().await?;

        self.run_in_progress = true;
        self.ended_by = None;

        // Record when the GooseAttack officially started. series_started is the
        // continuous graph clock and is not restarted on metrics reset.
        let now = time::Instant::now();
        self.started = Some(now);
        self.series_started = Some(now);
        // The same start, as the reports' record gives it.
        self.output.started = Some(chrono::Utc::now());
        // Align pre-created weighted users so request.elapsed matches series time.
        for user in &mut self.weighted_users {
            user.started = now;
        }

        Ok(())
    }

    // Called internally in local-mode and gaggle-mode.
    async fn start_attack(mut self) -> Result<GooseAttack, GooseError> {
        // The GooseAttackRunState is used while spawning and running the
        // GooseUser threads that generate the load test.
        // Propagate initialization errors (e.g. dashboard bind failure) as
        // `GooseError` rather than panicking — library callers of `execute()`
        // should get a structured Result.
        let mut goose_attack_run_state = self.initialize_attack().await?;

        // Without autostart, something has to be able to start the load test.
        if self.configuration.no_autostart
            && !goose_attack_run_state.listening_controllers.telnet
            && !goose_attack_run_state.listening_controllers.websocket
            && !self.configuration.dashboard_control
        {
            return Err(GooseError::InvalidOption {
                option: "`configuration.no_autostart`".to_string(),
                value: true.to_string(),
                detail: "`configuration.no_autostart` requires a Controller or dashboard control, and no Controller could listen on its port."
                    .to_string(),
            });
        }

        let result = self.run_attack(&mut goose_attack_run_state).await;

        // A run that ended early, on an error, leaves its logger running: end it,
        // so every line is written.
        if let Some(logger) = goose_attack_run_state.logger_handle.take() {
            if let Some(logger_tx) = goose_attack_run_state.all_threads_logger_tx.as_ref() {
                let _ = logger_tx.send(None);
            }
            let _ = logger.await;
        }

        // Stop the dashboard server on every return path, including errors
        // from the phase loop, and wait for it so the port is free when
        // `execute()` returns.
        #[cfg(feature = "dashboard")]
        if let Some(server) = goose_attack_run_state.dashboard_server.take() {
            server.shutdown().await;
        }

        result.map(|()| self)
    }

    /// The parent process GooseAttack loop: runs until Goose shuts down. Goose
    /// enters the loop in AttackPhase::Idle, and exits in AttackPhase::Shutdown.
    async fn run_attack(
        &mut self,
        goose_attack_run_state: &mut GooseAttackRunState,
    ) -> Result<(), GooseError> {
        loop {
            match self.attack_phase {
                // In the Idle phase the Goose configuration can be changed by a Controller,
                // and otherwise nothing happens but sleeping an checking for messages.
                AttackPhase::Idle => {
                    if self.configuration.no_autostart {
                        // Sleep then check for further instructions.
                        if goose_attack_run_state.idle_status_displayed {
                            let sleep_duration = Duration::from_millis(250);
                            debug!("sleeping {sleep_duration:?}...");
                            goose_attack_run_state.drift_timer = util::sleep_minus_drift(
                                sleep_duration,
                                goose_attack_run_state.drift_timer,
                            )
                            .await;
                        // Only display informational message about being idle one time.
                        } else {
                            info!("Goose is currently idle.");
                            goose_attack_run_state.idle_status_displayed = true;
                        }
                    } else {
                        // Prepare to start the load test, resetting timers and counters.
                        self.reset_run_state(goose_attack_run_state).await?;
                        self.metrics
                            .history
                            .push(TestPlanHistory::step(TestPlanStepAction::Increasing, 0));
                        //self.graph_data.set_starting(Utc::now());
                        self.set_attack_phase(goose_attack_run_state, AttackPhase::Increase);
                    }
                }
                // In the Increase phase, Goose launches GooseUser threads.
                AttackPhase::Increase => {
                    self.update_duration();
                    self.increase_attack(goose_attack_run_state).await?;
                }
                // In the Maintain phase, Goose continues runnning all launched GooseUser threads.
                AttackPhase::Maintain => {
                    self.update_duration();
                    self.maintain_attack(goose_attack_run_state).await?;
                }
                // In the Decrease phase, Goose stops GooseUser threads.
                AttackPhase::Decrease => {
                    // If displaying metrics, update internal state reflecting how long load test
                    // has been running.
                    self.update_duration();
                    // Reduce the number of GooseUsers running.
                    self.decrease_attack(goose_attack_run_state).await?;
                }
                // By reaching the Shutdown phase, break out of the GooseAttack loop.
                AttackPhase::Shutdown => {
                    // Proactively close SSE clients so browsers see `event: closed`
                    // without waiting for the next 1 Hz hub tick / flume disconnect.
                    #[cfg(feature = "dashboard")]
                    if let Some(close_tx) = goose_attack_run_state.dashboard_close_tx.take() {
                        let _ = close_tx.send(true);
                    }
                    break;
                }
            }

            // Record current users for the active-users graph (report + dashboard).
            // Use the continuous series clock — not `started`, which restarts on
            // metrics reset and would wipe/offset ramp history on the chart.
            if self.series_started.is_some() {
                let _ = goose_attack_run_state
                    .metrics_cmd_tx
                    .send(MetricsCommand::RecordUsers {
                        active_users: goose_attack_run_state.active_users,
                        elapsed_secs: self.series_elapsed_secs(),
                    });
            };

            // Check if it's time to display running metrics, sending a command
            // to the dedicated metrics processor task if so.
            self.sync_metrics(goose_attack_run_state);

            // Check if it's time to check the thresholds, sending a command to the
            // dedicated metrics processor task if so.
            self.check_thresholds(goose_attack_run_state);

            // Check if the dashboard or a Controller has sent a command.
            self.handle_control_requests(goose_attack_run_state).await?;

            // Check if the dashboard has requested a snapshot.
            #[cfg(feature = "dashboard")]
            self.handle_dashboard_requests(goose_attack_run_state)
                .await?;

            let mut message = goose_attack_run_state.shutdown_rx.try_recv();
            while message.is_ok() {
                goose_attack_run_state
                    .users_shutdown
                    .insert(message.expect("failed to wrap OK message"));

                // In Stand-alone mode, all users are started.
                if goose_attack_run_state.users_shutdown.len() == self.test_plan.total_users() {
                    self.set_ended_by(runs::EndedBy::UsersExited, None);
                    self.cancel_attack(goose_attack_run_state).await?;
                }

                message = goose_attack_run_state.shutdown_rx.try_recv();
            }

            // Gracefully exit loop if ctrl-c is caught.
            if self.attack_phase != AttackPhase::Shutdown
                && !goose_attack_run_state.canceling
                && is_killswitch_triggered()
            {
                // Shutdown after stopping as the load test was canceled.
                goose_attack_run_state.shutdown_after_stop = true;

                if self.attack_phase == AttackPhase::Idle {
                    // Nothing to cancel: canceling from Idle would leave a
                    // plan maintaining 0 users with no end.
                    self.shutdown_from_idle(goose_attack_run_state);
                } else {
                    self.set_ended_by(runs::EndedBy::Canceled, killswitch_reason());
                    // Cleanly stop the load test.
                    self.cancel_attack(goose_attack_run_state).await?;
                }

                // Load test is actively canceling.
                goose_attack_run_state.canceling = true;
            }
        }

        Ok(())
    }
}

/// Use the configured GooseScheduler to allocate all [`Transaction`](./goose/struct.Transaction.html)s
/// within the [`Scenario`](./goose/struct.Scenario.html) in the appropriate order. Returns
/// three set of ordered transactions: `on_start_transactions`, `transactions`, and `on_stop_transactions`.
/// The `on_start_transactions` are only run once when the [`GooseAttack`](./struct.GooseAttack.html) first
/// starts. Normal `transactions` are then run for the duration of the
/// [`GooseAttack`](./struct.GooseAttack.html). The `on_stop_transactions` finally are only run once when
/// the [`GooseAttack`](./struct.GooseAttack.html) stops.
fn allocate_transactions(
    scenario: &Scenario,
    scheduler: &GooseScheduler,
) -> (
    WeightedTransactions,
    WeightedTransactions,
    WeightedTransactions,
) {
    debug!("allocating Transactions on GooseUsers with {scheduler:?} scheduler");

    // A BTreeMap of Vectors allows us to group and sort transactions per sequence value.
    let mut sequenced_transactions: SequencedTransactions = BTreeMap::new();
    let mut sequenced_on_start_transactions: SequencedTransactions = BTreeMap::new();
    let mut sequenced_on_stop_transactions: SequencedTransactions = BTreeMap::new();
    let mut unsequenced_transactions: UnsequencedTransactions = Vec::new();
    let mut unsequenced_on_start_transactions: UnsequencedTransactions = Vec::new();
    let mut unsequenced_on_stop_transactions: UnsequencedTransactions = Vec::new();
    let mut u: usize = 0;
    let mut v: usize;

    // Find the greatest common divisor of all transactions in the scenario.
    for transaction in &scenario.transactions {
        if transaction.sequence > 0 {
            if transaction.on_start {
                if let Some(sequence) =
                    sequenced_on_start_transactions.get_mut(&transaction.sequence)
                {
                    // This is another transaction with this order value.
                    sequence.push(transaction.clone());
                } else {
                    // This is the first transaction with this order value.
                    sequenced_on_start_transactions
                        .insert(transaction.sequence, vec![transaction.clone()]);
                }
            }
            // Allow a transaction to be both on_start and on_stop.
            if transaction.on_stop {
                if let Some(sequence) =
                    sequenced_on_stop_transactions.get_mut(&transaction.sequence)
                {
                    // This is another transaction with this order value.
                    sequence.push(transaction.clone());
                } else {
                    // This is the first transaction with this order value.
                    sequenced_on_stop_transactions
                        .insert(transaction.sequence, vec![transaction.clone()]);
                }
            }
            if !transaction.on_start && !transaction.on_stop {
                if let Some(sequence) = sequenced_transactions.get_mut(&transaction.sequence) {
                    // This is another transaction with this order value.
                    sequence.push(transaction.clone());
                } else {
                    // This is the first transaction with this order value.
                    sequenced_transactions.insert(transaction.sequence, vec![transaction.clone()]);
                }
            }
        } else {
            if transaction.on_start {
                unsequenced_on_start_transactions.push(transaction.clone());
            }
            if transaction.on_stop {
                unsequenced_on_stop_transactions.push(transaction.clone());
            }
            if !transaction.on_start && !transaction.on_stop {
                unsequenced_transactions.push(transaction.clone());
            }
        }
        // Look for lowest common divisor amongst all transactions of any weight.
        if u == 0 {
            u = transaction.weight;
        } else {
            v = transaction.weight;
            trace!("calculating greatest common denominator of {u} and {v}");
            u = util::gcd(u, v);
            trace!("inner gcd: {u}");
        }
    }
    // 'u' will always be the greatest common divisor
    debug!("gcd: {u}");

    // Apply weights to sequenced transactions.
    let weighted_sequenced_on_start_transactions =
        weight_sequenced_transactions(&sequenced_on_start_transactions, u);
    let weighted_sequenced_transactions = weight_sequenced_transactions(&sequenced_transactions, u);
    let weighted_sequenced_on_stop_transactions =
        weight_sequenced_transactions(&sequenced_on_stop_transactions, u);

    // Apply weights to unsequenced transactions.
    let (weighted_unsequenced_on_start_transactions, total_unsequenced_on_start_transactions) =
        weight_unsequenced_transactions(&unsequenced_on_start_transactions, u);
    let (weighted_unsequenced_transactions, total_unsequenced_transactions) =
        weight_unsequenced_transactions(&unsequenced_transactions, u);
    let (weighted_unsequenced_on_stop_transactions, total_unsequenced_on_stop_transactions) =
        weight_unsequenced_transactions(&unsequenced_on_stop_transactions, u);

    // The Random scheduler shuffles only the transactions a user runs over and
    // over; its on_start and on_stop transactions run in Serial order.
    let start_stop_scheduler = match scheduler {
        GooseScheduler::Random => &GooseScheduler::Serial,
        _ => scheduler,
    };

    // Schedule sequenced transactions.
    let scheduled_sequenced_on_start_transactions = schedule_sequenced_transactions(
        &weighted_sequenced_on_start_transactions,
        start_stop_scheduler,
    );
    let scheduled_sequenced_transactions =
        schedule_sequenced_transactions(&weighted_sequenced_transactions, scheduler);
    let scheduled_sequenced_on_stop_transactions = schedule_sequenced_transactions(
        &weighted_sequenced_on_stop_transactions,
        start_stop_scheduler,
    );

    // Schedule unsequenced transactions.
    let scheduled_unsequenced_on_start_transactions = schedule_unsequenced_transactions(
        &weighted_unsequenced_on_start_transactions,
        total_unsequenced_on_start_transactions,
        start_stop_scheduler,
    );
    let scheduled_unsequenced_transactions = schedule_unsequenced_transactions(
        &weighted_unsequenced_transactions,
        total_unsequenced_transactions,
        scheduler,
    );
    let scheduled_unsequenced_on_stop_transactions = schedule_unsequenced_transactions(
        &weighted_unsequenced_on_stop_transactions,
        total_unsequenced_on_stop_transactions,
        start_stop_scheduler,
    );

    // Finally build a Vector of tuples: (transaction id, transaction name)
    let mut on_start_transactions = Vec::new();
    let mut transactions = Vec::new();
    let mut on_stop_transactions = Vec::new();

    // Sequenced transactions come first.
    for transaction in scheduled_sequenced_on_start_transactions.iter() {
        on_start_transactions.extend(vec![(
            *transaction,
            scenario.transactions[*transaction].name.clone(),
        )])
    }
    for transaction in scheduled_sequenced_transactions.iter() {
        transactions.extend(vec![(
            *transaction,
            scenario.transactions[*transaction].name.clone(),
        )])
    }
    for transaction in scheduled_sequenced_on_stop_transactions.iter() {
        on_stop_transactions.extend(vec![(
            *transaction,
            scenario.transactions[*transaction].name.clone(),
        )])
    }

    // Unsequenced transactions come last.
    for transaction in scheduled_unsequenced_on_start_transactions.iter() {
        on_start_transactions.extend(vec![(
            *transaction,
            scenario.transactions[*transaction].name.clone(),
        )])
    }
    for transaction in scheduled_unsequenced_transactions.iter() {
        transactions.extend(vec![(
            *transaction,
            scenario.transactions[*transaction].name.clone(),
        )])
    }
    for transaction in scheduled_unsequenced_on_stop_transactions.iter() {
        on_stop_transactions.extend(vec![(
            *transaction,
            scenario.transactions[*transaction].name.clone(),
        )])
    }

    // Return sequenced buckets of weighted usize pointers to and names of Transactions.
    (on_start_transactions, transactions, on_stop_transactions)
}

/// Build a weighted vector of vectors of unsequenced Transactions.
fn weight_unsequenced_transactions(
    unsequenced_transactions: &[Transaction],
    u: usize,
) -> (Vec<Vec<usize>>, usize) {
    // Build a vector of vectors to be used to schedule users.
    let mut available_unsequenced_transactions = Vec::with_capacity(unsequenced_transactions.len());
    let mut total_transactions = 0;
    for transaction in unsequenced_transactions.iter() {
        // divide by greatest common divisor so vector is as short as possible
        let weight = transaction.weight / u;
        trace!(
            "{}: {} has weight of {} (reduced with gcd to {})",
            transaction.transactions_index,
            transaction.name.name_for_transaction(),
            transaction.weight,
            weight
        );
        let weighted_transactions = vec![transaction.transactions_index; weight];
        available_unsequenced_transactions.push(weighted_transactions);
        total_transactions += weight;
    }
    (available_unsequenced_transactions, total_transactions)
}

/// Build a weighted vector of vectors of sequenced Transactions.
fn weight_sequenced_transactions(
    sequenced_transactions: &SequencedTransactions,
    u: usize,
) -> BTreeMap<usize, Vec<Vec<usize>>> {
    // Build a sequenced BTreeMap containing weighted vectors of Transactions.
    let mut available_sequenced_transactions = BTreeMap::new();
    // Step through sequences, each containing a bucket of all Transactions with the same
    // sequence value, allowing actual weighting to be done by weight_unsequenced_transactions().
    for (sequence, unsequenced_transactions) in sequenced_transactions.iter() {
        let (weighted_transactions, _total_weighted_transactions) =
            weight_unsequenced_transactions(unsequenced_transactions, u);
        available_sequenced_transactions.insert(*sequence, weighted_transactions);
    }

    available_sequenced_transactions
}

fn schedule_sequenced_transactions(
    available_sequenced_transactions: &BTreeMap<usize, Vec<Vec<usize>>>,
    scheduler: &GooseScheduler,
) -> Vec<usize> {
    let mut weighted_transactions: Vec<usize> = Vec::new();

    for transactions in available_sequenced_transactions.values() {
        let scheduled_transactions =
            schedule_unsequenced_transactions(transactions, transactions[0].len(), scheduler);
        weighted_transactions.extend(scheduled_transactions);
    }

    weighted_transactions
}

// Return a list of transactions in the order to be run.
fn schedule_unsequenced_transactions(
    available_unsequenced_transactions: &[Vec<usize>],
    total_transactions: usize,
    scheduler: &GooseScheduler,
) -> Vec<usize> {
    // Now build the weighted list with the appropriate scheduler.
    let mut weighted_transactions = Vec::new();

    match scheduler {
        GooseScheduler::RoundRobin => {
            // Allocate round robin.
            let transactions_len = available_unsequenced_transactions.len();
            let mut available_transactions = available_unsequenced_transactions.to_owned();
            loop {
                // Transactions are contained in a vector of vectors. The outer vectors each
                // contain a different Transaction, and the inner vectors contain each
                // instance of that specific Transaction.
                for (transaction_index, transactions) in available_transactions
                    .iter_mut()
                    .enumerate()
                    .take(transactions_len)
                {
                    if let Some(transaction) = transactions.pop() {
                        debug!("allocating transaction from Transaction {transaction_index}");
                        weighted_transactions.push(transaction);
                    }
                }
                if weighted_transactions.len() >= total_transactions {
                    break;
                }
            }
        }
        GooseScheduler::Serial | GooseScheduler::Random => {
            // Allocate serially in the weighted order defined.
            for (transaction_index, transactions) in
                available_unsequenced_transactions.iter().enumerate()
            {
                debug!(
                    "allocating all {} transactions from Transaction {}",
                    transactions.len(),
                    transaction_index
                );
                weighted_transactions.extend_from_slice(transactions);
            }
            // The Random scheduler then shuffles the whole list once. Each
            // Transaction's own vector holds only copies of its index, so
            // shuffling those changes nothing.
            if scheduler == &GooseScheduler::Random {
                weighted_transactions.shuffle(&mut rand::rng());
            }
        }
    }

    weighted_transactions
}

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

    /// The telnet Controller listens by default and the WebSocket Controller
    /// only with `--websocket`, and with no host given both listen on
    /// 127.0.0.1 only: a connection to this machine's own non-loopback
    /// address, where it has one, is refused.
    #[tokio::test]
    async fn websocket_controller_listens_only_when_asked_for() {
        /// A port nothing listens on, for now.
        fn free_port() -> String {
            let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
            listener.local_addr().unwrap().port().to_string()
        }
        for websocket in [false, true] {
            let (telnet_port, websocket_port) = (free_port(), free_port());
            let mut args = vec![
                "--telnet-port",
                &telnet_port,
                "--websocket-port",
                &websocket_port,
            ];
            if websocket {
                args.push("--websocket");
            }
            let configuration = GooseConfiguration::parse_args_default(&args).unwrap();
            let mut goose_attack = GooseAttack::initialize_with_config(configuration).unwrap();
            let defaults = goose_attack.defaults.clone();
            goose_attack.configuration.configure(&defaults).unwrap();
            goose_attack.configuration.validate().unwrap();
            let (control_tx, _control_rx) = flume::unbounded();
            let listening = goose_attack.setup_controllers(&control_tx).await;
            assert!(listening.telnet);
            assert_eq!(listening.websocket, websocket);
            let connects = |host: std::net::IpAddr, port: &str| {
                let address = std::net::SocketAddr::new(host, port.parse().unwrap());
                async move { tokio::net::TcpStream::connect(address).await.is_ok() }
            };
            let loopback = std::net::Ipv4Addr::LOCALHOST.into();
            assert!(connects(loopback, &telnet_port).await);
            if let Some(lan) = lan_address() {
                assert!(!connects(lan, &telnet_port).await, "telnet on {}", lan);
                assert!(
                    !connects(lan, &websocket_port).await,
                    "WebSocket on {}",
                    lan
                );
            }
            assert_eq!(
                connects(loopback, &websocket_port).await,
                websocket,
                "--websocket {}",
                websocket
            );
        }
    }

    /// This machine's address on the network a default route leads to, if it
    /// has one: a UDP connect picks the source address and sends nothing.
    fn lan_address() -> Option<std::net::IpAddr> {
        let socket = std::net::UdpSocket::bind("0.0.0.0:0").ok()?;
        socket.connect("192.0.2.1:9").ok()?;
        let ip = socket.local_addr().ok()?.ip();
        (!ip.is_loopback() && !ip.is_unspecified()).then_some(ip)
    }

    // Serial with every test that calls `initialize_attack`: installing the
    // Ctrl-C handler a second time resets the killswitch this test reads.
    #[tokio::test]
    #[serial_test::serial]
    async fn test_killswitch_functions() {
        // Reset the killswitch state for testing
        reset_killswitch();

        // Initially, killswitch should not be triggered
        assert!(
            !is_killswitch_triggered(),
            "Killswitch should initially be false"
        );

        // Trigger the killswitch with a reason
        trigger_killswitch("Test reason: threshold exceeded");

        // Verify killswitch is now triggered
        assert!(
            is_killswitch_triggered(),
            "Killswitch should be true after triggering"
        );

        // Trigger again with a different reason (should not log since already triggered)
        trigger_killswitch("Test reason: second trigger");

        // Verify it's still triggered
        assert!(is_killswitch_triggered(), "Killswitch should remain true");

        // Only the first reason is kept.
        assert_eq!(
            killswitch_reason().as_deref(),
            Some("Test reason: threshold exceeded")
        );

        // Reset for other tests
        reset_killswitch();

        assert!(
            !is_killswitch_triggered(),
            "Killswitch should be false after reset"
        );
    }

    /// Checking starts when the run first enters Maintain, through
    /// `set_attack_phase`. From there the main loop sends `CheckThresholds` at most
    /// once a second, in Maintain and in a later Increase but never in Decrease or
    /// Idle, once `--threshold-abort-delay` has passed since Maintain. Without a
    /// threshold that can stop the run it sends no check. With an `rps` rule, in
    /// every mode, each entry to Maintain and each exit from it is sent, for the
    /// holds `rps` rules count.
    #[tokio::test]
    #[serial_test::serial]
    async fn checks_start_when_the_run_first_enters_maintain() {
        /// An idle attack with `args`, whose metrics commands come out of the receiver.
        async fn attack(
            args: &[&str],
        ) -> (
            GooseAttack,
            GooseAttackRunState,
            flume::Receiver<MetricsCommand>,
        ) {
            let mut all = vec!["--no-telnet", "--no-websocket"];
            all.extend_from_slice(args);
            let configuration = GooseConfiguration::parse_args_default(&all).unwrap();
            let mut goose_attack = GooseAttack::initialize_with_config(configuration).unwrap();
            let defaults = goose_attack.defaults.clone();
            goose_attack.configuration.configure(&defaults).unwrap();
            let mut run_state = goose_attack.initialize_attack().await.unwrap();
            let (metrics_cmd_tx, metrics_cmd_rx) = flume::unbounded();
            run_state.metrics_cmd_tx = metrics_cmd_tx;
            assert_eq!(goose_attack.attack_phase, AttackPhase::Idle);
            (goose_attack, run_state, metrics_cmd_rx)
        }

        /// Enter `phase`, then take two loop turns in the same second: the checks,
        /// the entries to Maintain and the exits from it sent.
        fn enter(
            goose_attack: &mut GooseAttack,
            run_state: &mut GooseAttackRunState,
            commands: &flume::Receiver<MetricsCommand>,
            phase: AttackPhase,
        ) -> (usize, usize, usize) {
            goose_attack.set_attack_phase(run_state, phase);
            goose_attack.check_thresholds(run_state);
            goose_attack.check_thresholds(run_state);
            commands.try_iter().fold(
                (0, 0, 0),
                |(checks, enters, leaves), command| match command {
                    MetricsCommand::CheckThresholds { .. } => (checks + 1, enters, leaves),
                    MetricsCommand::EnterMaintain { .. } => (checks, enters + 1, leaves),
                    MetricsCommand::LeaveMaintain { .. } => (checks, enters, leaves + 1),
                    _ => (checks, enters, leaves),
                },
            )
        }

        let (mut goose_attack, mut run_state, commands) =
            attack(&["--threshold", "p95<500ms", "--threshold", "rps>=1"]).await;
        // Nothing while users start, before the run first holds them.
        assert_eq!(
            enter(
                &mut goose_attack,
                &mut run_state,
                &commands,
                AttackPhase::Increase
            ),
            (0, 0, 0)
        );
        // Checking starts in Maintain, once.
        assert_eq!(
            enter(
                &mut goose_attack,
                &mut run_state,
                &commands,
                AttackPhase::Maintain
            ),
            (1, 1, 0)
        );
        // A second later, a later Increase is checked, though it ends the hold,
        // and Decrease is not checked.
        run_state.threshold_check_at = Some(std::time::Instant::now());
        assert_eq!(
            enter(
                &mut goose_attack,
                &mut run_state,
                &commands,
                AttackPhase::Increase
            ),
            (1, 0, 1)
        );
        run_state.threshold_check_at = Some(std::time::Instant::now());
        assert_eq!(
            enter(
                &mut goose_attack,
                &mut run_state,
                &commands,
                AttackPhase::Decrease
            ),
            (0, 0, 0)
        );
        // Entering Maintain again starts a hold without starting checking again.
        let due = run_state.threshold_check_at;
        goose_attack.set_attack_phase(&mut run_state, AttackPhase::Maintain);
        assert_eq!(run_state.threshold_check_at, due);
        run_state.threshold_check_at = Some(std::time::Instant::now());
        // The hold was sent, and Idle ends it, sending no check.
        assert_eq!(
            enter(
                &mut goose_attack,
                &mut run_state,
                &commands,
                AttackPhase::Idle
            ),
            (0, 1, 1)
        );

        // The delay counts from Maintain. Without an `rps` rule no hold is sent.
        let (mut goose_attack, mut run_state, commands) =
            attack(&["--threshold", "p95<500ms", "--threshold-abort-delay", "3"]).await;
        assert_eq!(
            enter(
                &mut goose_attack,
                &mut run_state,
                &commands,
                AttackPhase::Increase
            ),
            (0, 0, 0)
        );
        let entered = std::time::Instant::now();
        assert_eq!(
            enter(
                &mut goose_attack,
                &mut run_state,
                &commands,
                AttackPhase::Maintain
            ),
            (0, 0, 0)
        );
        let due = run_state.threshold_check_at.expect("checking started");
        assert!(due >= entered + Duration::from_secs(3));
        assert!(due <= std::time::Instant::now() + Duration::from_secs(3));

        // No check without a threshold that can stop the run, but an `rps` rule
        // still counts its holds under `--no-threshold-abort`.
        for (args, holds) in [
            (&[][..], 0),
            (&["--threshold", "p95<500ms", "--no-threshold-abort"], 0),
            (&["--threshold", "rps>=1", "--no-threshold-abort"], 1),
        ] {
            let (mut goose_attack, mut run_state, commands) = attack(args).await;
            for (phase, expected) in [
                (AttackPhase::Increase, (0, 0, 0)),
                (AttackPhase::Maintain, (0, holds, 0)),
                (AttackPhase::Decrease, (0, 0, holds)),
            ] {
                assert_eq!(
                    enter(&mut goose_attack, &mut run_state, &commands, phase),
                    expected,
                    "{:?} {:?}",
                    args,
                    phase
                );
            }
            assert_eq!(run_state.threshold_check_at, None);
        }
    }

    /// A `main` that returns `ThresholdsFailed` prints the rules that failed, not
    /// the metrics of the whole run, which still read through the error.
    #[test]
    fn thresholds_failed_prints_only_the_rules() {
        let error = GooseError::ThresholdsFailed {
            failed: vec![threshold::ThresholdResult {
                rule: "p95<500ms".to_string(),
                observed: "812ms".to_string(),
                value: Some(812.0),
                passed: false,
                aborted: true,
            }],
            metrics: ThresholdMetrics(Box::new(GooseMetrics {
                duration: 7,
                ..Default::default()
            })),
        };
        assert_eq!(
            format!("{error:?}"),
            "ThresholdsFailed { failed: [ThresholdResult { rule: \"p95<500ms\", \
             observed: \"812ms\", value: Some(812.0), passed: false, aborted: true }], \
             metrics: ThresholdMetrics { .. } }"
        );
        assert_eq!(
            error.to_string(),
            "GooseError: one or more thresholds failed (p95<500ms, observed 812ms)"
        );
        let GooseError::ThresholdsFailed { metrics, .. } = error else {
            unreachable!()
        };
        assert_eq!(metrics.duration, 7);
        assert_eq!(metrics.0.duration, 7);
    }

    /// A refused Start names its one cause: not idle, no host, or no users.
    #[tokio::test]
    #[serial_test::serial]
    async fn test_control_start_refusal_names_cause() {
        async fn noop(_user: &mut GooseUser) -> crate::goose::TransactionResult {
            Ok(())
        }
        let configuration =
            GooseConfiguration::parse_args_default(&["--no-telnet", "--no-websocket"]).unwrap();
        let mut goose_attack = GooseAttack::initialize_with_config(configuration)
            .unwrap()
            .register_scenario(scenario!("NoHost").register_transaction(transaction!(noop)));
        let mut run_state = goose_attack.initialize_attack().await.unwrap();
        let mut refusal = |goose_attack: &mut GooseAttack| match goose_attack
            .control_start_begin(&mut run_state)
            .unwrap()
        {
            ControlStartBegin::Rejected(outcome) => (outcome.error, outcome.message),
            ControlStartBegin::Accepted(outcome) => panic!("accepted: {:?}", outcome),
        };

        goose_attack.configuration.users = Some(1);
        assert_eq!(
            refusal(&mut goose_attack),
            (
                Some("prepare_failed"),
                "unable to start load test, no host is configured".to_string()
            )
        );

        goose_attack.configuration.host = Some("http://127.0.0.1".to_string());
        goose_attack.configuration.users = None;
        goose_attack.configuration.test_plan = None;
        // With no scenario, a Start that got past the users check would fail
        // the test instead of weighting zero users forever.
        goose_attack.scenarios.clear();
        assert_eq!(
            refusal(&mut goose_attack),
            (
                Some("prepare_failed"),
                "unable to start load test, there are no users to start".to_string()
            )
        );

        goose_attack.attack_phase = AttackPhase::Maintain;
        assert_eq!(
            refusal(&mut goose_attack),
            (
                Some("invalid_phase"),
                "unable to start load test, it is not idle".to_string()
            )
        );
    }

    /// A Start with scenario hosts only, no default host and a `test_start`
    /// or `test_stop` transaction is refused before it replies, naming the
    /// host and the transaction; it used to panic after replying ok. An autostarted run fails
    /// at launch instead.
    #[tokio::test]
    #[serial_test::serial]
    async fn test_start_refused_without_host_for_test_start() {
        async fn noop(_user: &mut GooseUser) -> crate::goose::TransactionResult {
            Ok(())
        }
        for test_stop in [false, true] {
            let configuration = GooseConfiguration::parse_args_default(&[
                "--no-telnet",
                "--no-websocket",
                "--users",
                "1",
            ])
            .unwrap();
            let goose_attack = GooseAttack::initialize_with_config(configuration)
                .unwrap()
                .register_scenario(
                    scenario!("Hosted")
                        .set_host("http://127.0.0.1")
                        .register_transaction(transaction!(noop)),
                );
            let mut goose_attack = if test_stop {
                goose_attack.test_stop(transaction!(noop))
            } else {
                goose_attack.test_start(transaction!(noop))
            };
            let mut run_state = goose_attack.initialize_attack().await.unwrap();
            match goose_attack.control_start_begin(&mut run_state).unwrap() {
                ControlStartBegin::Rejected(outcome) => {
                    assert_eq!(outcome.error, Some("prepare_failed"));
                    assert_eq!(outcome.field, Some("host"));
                    let transaction = if test_stop { "test_stop" } else { "test_start" };
                    assert_eq!(
                        outcome.message,
                        format!(
                            "unable to start load test, no host is configured for the {transaction} transaction"
                        )
                    );
                }
                ControlStartBegin::Accepted(outcome) => panic!("accepted: {:?}", outcome),
            }
            assert_eq!(goose_attack.attack_phase, AttackPhase::Idle);

            // A default host is enough for the transaction.
            goose_attack.defaults.host = Some("http://127.0.0.1".to_string());
            assert!(matches!(
                goose_attack.control_start_begin(&mut run_state).unwrap(),
                ControlStartBegin::Accepted(_)
            ));
        }

        // Autostarted, the same configuration is a startup error.
        let configuration = GooseConfiguration::parse_args_default(&[
            "--no-telnet",
            "--no-websocket",
            "--users",
            "1",
            "--quiet",
        ])
        .unwrap();
        let error = GooseAttack::initialize_with_config(configuration)
            .unwrap()
            .register_scenario(
                scenario!("Hosted")
                    .set_host("http://127.0.0.1")
                    .register_transaction(transaction!(noop)),
            )
            .test_start(transaction!(noop))
            .execute()
            .await
            .unwrap_err();
        assert!(
            matches!(&error, GooseError::InvalidOption { option, .. } if option == NO_HOST_OPTION),
            "{}",
            error
        );
    }

    /// The snapshot's run settings: the configured values, hosts resolved
    /// per scenario without `get_base_url`, and the stage per snapshot.
    #[cfg(feature = "dashboard")]
    #[tokio::test]
    #[serial_test::serial]
    async fn test_snapshot_settings() {
        async fn noop(_user: &mut GooseUser) -> crate::goose::TransactionResult {
            Ok(())
        }
        let configuration = GooseConfiguration::parse_args_default(&[
            "--no-telnet",
            "--no-websocket",
            "--no-autostart",
            "--users",
            "100",
            "--increase-rate",
            "10",
            "--run-time",
            "10m",
            "--decrease-time",
            "30s",
        ])
        .unwrap();
        // With --no-autostart and no host, a scenario without one adds no
        // host, and nothing panics.
        let mut goose_attack = GooseAttack::initialize_with_config(configuration)
            .unwrap()
            .register_scenario(scenario!("NoHost").register_transaction(transaction!(noop)))
            .register_scenario(
                scenario!("Hosted")
                    .set_host("http://localhost")
                    .register_transaction(transaction!(noop)),
            )
            .register_scenario(
                scenario!("Again")
                    .set_host("http://localhost/")
                    .register_transaction(transaction!(noop)),
            );
        let mut run_state = goose_attack.initialize_attack().await.unwrap();
        let settings = goose_attack.snapshot_settings(&run_state);
        assert_eq!(
            settings,
            metrics::dashboard_snapshot::SnapshotSettings {
                host: None,
                hosts: vec!["http://localhost/".to_string()],
                users: Some(100),
                increase_rate: Some(10.0),
                increase_time_secs: None,
                decrease_rate: None,
                decrease_time_secs: Some(30),
                run_time_secs: Some(600),
                test_plan: None,
                hold_ends_in_secs: None,
                stage: "idle".to_string(),
            }
        );
        let json = serde_json::to_value(&settings).unwrap();
        assert_eq!(json["increase_rate"], serde_json::json!(10.0));

        // A default host fills in for the scenario with none, and --host
        // overrides them all; settings are rebuilt after a command.
        goose_attack.defaults.host = Some("https://example.com".to_string());
        goose_attack.settings = None;
        assert_eq!(
            goose_attack.snapshot_settings(&run_state).hosts,
            ["http://localhost/", "https://example.com/"]
        );
        assert!(
            controller::tests::control(
                &mut goose_attack,
                &mut run_state,
                "host https://override.test"
            )
            .await
        );
        let settings = goose_attack.snapshot_settings(&run_state);
        assert_eq!(settings.host.as_deref(), Some("https://override.test"));
        assert_eq!(settings.hosts, ["https://override.test/"]);

        // A test plan in canonical form, with no users.
        assert!(
            controller::tests::control(&mut goose_attack, &mut run_state, "testplan 10,1m30s;0,0")
                .await
        );
        let settings = goose_attack.snapshot_settings(&run_state);
        assert_eq!(settings.test_plan.as_deref(), Some("10,90;0,0"));
        assert_eq!(settings.users, None);
        assert_eq!(settings.run_time_secs, None);

        // Stages: a running test plan, then a cancel.
        goose_attack.set_attack_phase(&mut run_state, AttackPhase::Increase);
        assert_eq!(
            goose_attack.snapshot_settings(&run_state).stage,
            "test_plan"
        );
        run_state.stopping = true;
        assert_eq!(goose_attack.snapshot_settings(&run_state).stage, "stopping");
        goose_attack.set_attack_phase(&mut run_state, AttackPhase::Idle);
        assert_eq!(goose_attack.snapshot_settings(&run_state).stage, "idle");
    }

    /// Where the run is: Idle, a users ramp's stage, a running test plan,
    /// and stopping for a cancel or Shutdown.
    #[tokio::test]
    #[serial_test::serial]
    async fn test_stage() {
        use run_shape::Stage;
        let configuration = GooseConfiguration::parse_args_default(&[
            "--no-telnet",
            "--no-websocket",
            "--users",
            "4",
        ])
        .unwrap();
        let mut goose_attack = GooseAttack::initialize_with_config(configuration).unwrap();
        let mut run_state = goose_attack.initialize_attack().await.unwrap();
        assert_eq!(goose_attack.stage(&run_state), Stage::Idle);
        controller::tests::run_users_ramp(&mut goose_attack, &mut run_state, 4);
        assert_eq!(goose_attack.stage(&run_state), Stage::RampUp);
        goose_attack.run_shape = None;
        assert_eq!(goose_attack.stage(&run_state), Stage::TestPlan);
        run_state.stopping = true;
        assert_eq!(goose_attack.stage(&run_state), Stage::Stopping);
        run_state.stopping = false;
        goose_attack.set_attack_phase(&mut run_state, AttackPhase::Shutdown);
        assert_eq!(goose_attack.stage(&run_state), Stage::Stopping);
    }

    /// A new step schedules its users from its own start: a ramp a Controller
    /// left mid way leaves no due time behind, which the next ramp would catch
    /// up on in a burst.
    #[tokio::test]
    #[serial_test::serial]
    async fn test_new_step_forgets_the_last_due_time() {
        let configuration = GooseConfiguration::parse_args_default(&[
            "--no-telnet",
            "--no-websocket",
            "--users",
            "4",
        ])
        .unwrap();
        let mut goose_attack = GooseAttack::initialize_with_config(configuration).unwrap();
        let mut run_state = goose_attack.initialize_attack().await.unwrap();
        controller::tests::run_users_ramp(&mut goose_attack, &mut run_state, 4);
        // Mid ramp, with the next user due a minute ago.
        run_state.adjust_user_in_ms = 667;
        run_state.adjust_user_timer = std::time::Instant::now() - Duration::from_secs(60);
        goose_attack.advance_test_plan(&mut run_state);
        assert_eq!(run_state.adjust_user_in_ms, 0);
        assert!(run_state.adjust_due());
    }

    /// A refused Start leaves the run settings and target users as they were.
    #[cfg(feature = "dashboard")]
    #[tokio::test]
    #[serial_test::serial]
    async fn test_refused_start_leaves_settings() {
        async fn noop(_user: &mut GooseUser) -> crate::goose::TransactionResult {
            Ok(())
        }
        let configuration = GooseConfiguration::parse_args_default(&[
            "--no-telnet",
            "--no-websocket",
            "--users",
            "5",
        ])
        .unwrap();
        let mut goose_attack = GooseAttack::initialize_with_config(configuration)
            .unwrap()
            .register_scenario(scenario!("NoHost").register_transaction(transaction!(noop)));
        let mut run_state = goose_attack.initialize_attack().await.unwrap();
        let settings = goose_attack.snapshot_settings(&run_state);
        let target = goose_attack.current_target_users();
        assert!(!controller::tests::control(&mut goose_attack, &mut run_state, "start").await);
        assert_eq!(goose_attack.snapshot_settings(&run_state), settings);
        assert_eq!(goose_attack.current_target_users(), target);
        assert!(goose_attack.run_shape.is_none());
    }

    /// A Start with settings whose prepare fails puts every setting back:
    /// the run settings, the target users and the configuration are as they
    /// were, and no run shape is left.
    #[cfg(feature = "dashboard")]
    #[tokio::test]
    #[serial_test::serial]
    async fn test_refused_start_with_settings_leaves_settings() {
        async fn noop(_user: &mut GooseUser) -> crate::goose::TransactionResult {
            Ok(())
        }
        let configuration = GooseConfiguration::parse_args_default(&[
            "--no-telnet",
            "--no-websocket",
            "--users",
            "5",
            "--increase-rate",
            "2",
        ])
        .unwrap();
        let mut goose_attack = GooseAttack::initialize_with_config(configuration)
            .unwrap()
            .register_scenario(scenario!("NoHost").register_transaction(transaction!(noop)));
        let mut run_state = goose_attack.initialize_attack().await.unwrap();
        let settings = goose_attack.snapshot_settings(&run_state);
        let target = goose_attack.current_target_users();
        let configuration = format!("{:?}", goose_attack.configuration);
        let body = r#"{"users":8,"increase_time_secs":4,"run_time_secs":30,"decrease_rate":3}"#;
        let refused =
            controller::tests::settings(&mut goose_attack, &mut run_state, body, true).await;
        assert!(!refused.ok);
        assert_eq!(refused.error, Some("prepare_failed"));
        assert_eq!(refused.field, Some("host"));
        assert_eq!(refused.phase, "idle");
        assert_eq!(goose_attack.snapshot_settings(&run_state), settings);
        assert_eq!(refused.settings.as_deref(), Some(&settings));
        assert_eq!(goose_attack.current_target_users(), target);
        assert_eq!(format!("{:?}", goose_attack.configuration), configuration);
        assert!(goose_attack.run_shape.is_none());
    }

    /// Resolving a base url with no host from any source is an error, not a
    /// panic.
    #[test]
    fn get_base_url_without_host_is_an_error() {
        assert!(goose::get_base_url(None, None, None).is_err());
    }

    /// Users is refused while a cancel ramps the run down, accepted during a
    /// users ramp's own ramp down, and accepted again once the run is Idle.
    #[tokio::test]
    #[serial_test::serial]
    async fn test_set_users_refused_while_stopping() {
        let configuration =
            GooseConfiguration::parse_args_default(&["--no-telnet", "--no-websocket"]).unwrap();
        let mut goose_attack = GooseAttack::initialize_with_config(configuration).unwrap();
        let mut run_state = goose_attack.initialize_attack().await.unwrap();

        // A users ramp's own ramp down from 10 users to 0.
        goose_attack.configuration.users = Some(10);
        goose_attack.configuration.decrease_rate = Some("1".to_string());
        controller::tests::run_users_ramp(&mut goose_attack, &mut run_state, 10);
        goose_attack.advance_test_plan(&mut run_state);
        assert_eq!(goose_attack.attack_phase, AttackPhase::Decrease);
        assert!(!run_state.stopping);
        let outcome = goose_attack.control_set_users(&mut run_state, 5).unwrap();
        assert!(outcome.ok, "ramp down must accept users: {:?}", outcome);
        assert_eq!(outcome.target_users, Some(5));

        // A cancel, as Stop, `shutdown` and Ctrl-C all start one.
        goose_attack.cancel_attack(&mut run_state).await.unwrap();
        assert!(run_state.stopping);
        assert_eq!(goose_attack.attack_phase, AttackPhase::Decrease);
        let outcome = goose_attack.control_set_users(&mut run_state, 5).unwrap();
        assert!(!outcome.ok, "cancel must refuse users: {:?}", outcome);
        assert_eq!(outcome.error, Some("invalid_phase"));
        assert_eq!(outcome.phase, "decrease");
        assert_eq!(outcome.target_users, None);
        // The cancel's ramp to zero is left in place.
        assert_eq!(goose_attack.test_plan.steps.last(), Some(&(0, 0)));
        assert_eq!(goose_attack.attack_phase, AttackPhase::Decrease);

        // Reaching Idle ends the cancel, so a later run can change users.
        goose_attack.set_attack_phase(&mut run_state, AttackPhase::Idle);
        assert!(!run_state.stopping);
        let outcome = goose_attack.control_set_users(&mut run_state, 5).unwrap();
        assert!(outcome.ok, "idle must accept users: {:?}", outcome);
    }

    /// A Stop moves a running load test to Decrease, and a second Stop while
    /// it ramps down is refused as `invalid_phase` without touching the cancel.
    #[tokio::test]
    #[serial_test::serial]
    async fn test_second_stop_refused_while_decreasing() {
        let configuration =
            GooseConfiguration::parse_args_default(&["--no-telnet", "--no-websocket"]).unwrap();
        let mut goose_attack = GooseAttack::initialize_with_config(configuration).unwrap();
        let mut run_state = goose_attack.initialize_attack().await.unwrap();

        // A test plan maintaining 10 users.
        goose_attack.test_plan = TestPlan {
            steps: vec![(10, 0), (10, 10_000)],
            current: 0,
        };
        run_state.active_users = 10;
        goose_attack.advance_test_plan(&mut run_state);
        assert_eq!(goose_attack.attack_phase, AttackPhase::Maintain);

        let first = goose_attack.control_stop(&mut run_state).await.unwrap();
        assert!(first.ok, "maintain must accept stop: {:?}", first);
        assert_eq!(first.phase, "decrease");
        assert_eq!(goose_attack.attack_phase, AttackPhase::Decrease);
        assert!(run_state.stopping);
        let steps = goose_attack.test_plan.steps.clone();
        let current = goose_attack.test_plan.current;
        let history_len = goose_attack.metrics.history.len();

        let second = goose_attack.control_stop(&mut run_state).await.unwrap();
        assert!(!second.ok, "decrease must refuse stop: {:?}", second);
        assert_eq!(second.error, Some("invalid_phase"));
        assert_eq!(second.phase, "decrease");
        // The first Stop's ramp to zero is left in place.
        assert_eq!(goose_attack.test_plan.steps, steps);
        assert_eq!(goose_attack.test_plan.current, current);
        assert_eq!(goose_attack.metrics.history.len(), history_len);
        assert_eq!(goose_attack.attack_phase, AttackPhase::Decrease);
        assert!(run_state.stopping);
        assert!(goose_attack.configuration.no_autostart);
        assert!(!run_state.shutdown_after_stop);
    }

    /// Every snapshot the main loop serves carries the stopping flag: the one
    /// forwarded to the metrics processor, the local fallback when the
    /// processor is gone, and the one served in the tick of a command, which
    /// the stopping flag then refuses.
    #[cfg(feature = "dashboard")]
    #[tokio::test]
    #[serial_test::serial]
    async fn test_dashboard_snapshot_carries_stopping() {
        let configuration =
            GooseConfiguration::parse_args_default(&["--no-telnet", "--no-websocket"]).unwrap();
        let mut goose_attack = GooseAttack::initialize_with_config(configuration).unwrap();
        let mut run_state = goose_attack.initialize_attack().await.unwrap();
        let (dashboard_tx, dashboard_rx) = flume::unbounded();
        run_state.dashboard_channel_rx = Some(dashboard_rx);
        let (metrics_cmd_tx, metrics_cmd_rx) = flume::unbounded();
        run_state.metrics_cmd_tx = metrics_cmd_tx;
        run_state.stopping = true;

        // Forwarded to the metrics processor, with the hub's heatmap cursor.
        let cursor = metrics::dashboard_snapshot::HeatmapCursor {
            generation: 7,
            rev: 41,
        };
        let (respond, _snapshot_rx) = tokio::sync::oneshot::channel();
        dashboard_tx
            .send(dashboard::DashboardRequest::GetSnapshot {
                respond,
                heatmap_since: Some(cursor),
            })
            .unwrap();
        goose_attack
            .handle_dashboard_requests(&mut run_state)
            .await
            .unwrap();
        let Ok(MetricsCommand::GetDashboardSnapshot {
            stopping,
            heatmap_since,
            ..
        }) = metrics_cmd_rx.try_recv()
        else {
            panic!("expected a forwarded snapshot request");
        };
        assert!(stopping);
        assert_eq!(heatmap_since, Some(cursor));

        // Processor gone: served from main-loop state.
        drop(metrics_cmd_rx);
        let (respond, snapshot_rx) = tokio::sync::oneshot::channel();
        dashboard_tx
            .send(dashboard::DashboardRequest::GetSnapshot {
                respond,
                heatmap_since: None,
            })
            .unwrap();
        goose_attack
            .handle_dashboard_requests(&mut run_state)
            .await
            .unwrap();
        assert!(snapshot_rx.await.unwrap().stopping);

        // Served in the tick of a command, which then refuses Users.
        let (respond, snapshot_rx) = tokio::sync::oneshot::channel();
        dashboard_tx
            .send(dashboard::DashboardRequest::GetSnapshot {
                respond,
                heatmap_since: None,
            })
            .unwrap();
        goose_attack
            .handle_dashboard_requests(&mut run_state)
            .await
            .unwrap();
        assert!(snapshot_rx.await.unwrap().stopping);
        assert!(!controller::tests::control(&mut goose_attack, &mut run_state, "users 5").await);
    }

    /// A `--scenarios` pattern that matches no machine name is reported, as
    /// `load_test` is for the scenario `loadtest`.
    #[test]
    fn unmatched_scenario_patterns_are_named() {
        let configuration =
            GooseConfiguration::parse_args_default(&["--scenarios", "load_test,load*,nope*"])
                .unwrap();
        let goose_attack = GooseAttack::initialize_with_config(configuration)
            .unwrap()
            .register_scenario(Scenario::new("LoadTest"));
        assert_eq!(
            goose_attack.unmatched_scenario_patterns(),
            ["load_test", "nope*"]
        );
    }

    /// A run started after another, as a Controller start after stop does,
    /// counts its requests from zero.
    #[tokio::test]
    async fn a_new_run_counts_requests_from_zero() {
        let configuration = GooseConfiguration::parse_args_default(&[
            "--no-telnet",
            "--no-websocket",
            "--host",
            "http://localhost",
        ])
        .unwrap();
        let mut goose_attack = GooseAttack::initialize_with_config(configuration)
            .unwrap()
            .register_scenario(
                Scenario::new("LoadTest").register_transaction(Transaction::new(Arc::new(
                    |user: &mut GooseUser| Box::pin(async move { user.get("/").await.map(|_| ()) }),
                ))),
            );
        let defaults = goose_attack.defaults.clone();
        goose_attack.configuration.configure(&defaults).unwrap();
        let mut run_state = goose_attack.initialize_attack().await.unwrap();
        let counters = Arc::new(metrics::GooseRequestCounters::new());
        counters
            .success
            .fetch_add(5, std::sync::atomic::Ordering::Relaxed);
        counters
            .failure
            .fetch_add(2, std::sync::atomic::Ordering::Relaxed);
        run_state
            .request_counter_registry
            .lock()
            .unwrap()
            .insert("GET /".to_string(), counters.clone());
        let epoch = run_state
            .metrics_epoch
            .load(std::sync::atomic::Ordering::Relaxed);

        goose_attack.reset_run_state(&mut run_state).await.unwrap();

        assert_eq!(
            counters.success.load(std::sync::atomic::Ordering::Relaxed),
            0
        );
        assert_eq!(
            counters.failure.load(std::sync::atomic::Ordering::Relaxed),
            0
        );
        assert!(
            run_state
                .metrics_epoch
                .load(std::sync::atomic::Ordering::Relaxed)
                > epoch
        );
    }

    /// A duplicate scenario name, renamed `name_1`, selects only that
    /// scenario, and `--scenarios-list` names both.
    #[test]
    fn duplicate_scenario_name_can_be_selected() {
        let configuration =
            GooseConfiguration::parse_args_default(&["--scenarios", "loadtest_1"]).unwrap();
        let goose_attack = GooseAttack::initialize_with_config(configuration)
            .unwrap()
            .register_scenario(Scenario::new("LoadTest"))
            .register_scenario(Scenario::new("LoadTest"));
        let names: Vec<&str> = goose_attack
            .scenarios
            .iter()
            .map(|scenario| &*scenario.machine_name)
            .collect();
        assert_eq!(names, ["loadtest", "loadtest_1"]);
        assert!(!goose_attack.scenario_is_active(&goose_attack.scenarios[0]));
        assert!(goose_attack.scenario_is_active(&goose_attack.scenarios[1]));
        assert!(goose_attack.unmatched_scenario_patterns().is_empty());
        assert_eq!(
            goose_attack.scenarios_list(),
            "Scenarios:\n - loadtest: (\"LoadTest\")\n - loadtest_1: (\"LoadTest\")\n"
        );
    }

    #[test]
    fn test_wildcard_match_exact() {
        assert!(wildcard_match("scenarioa1", "scenarioa1"));
        assert!(!wildcard_match("scenarioa1", "scenarioa1extended"));
        assert!(!wildcard_match("scenarioa1", "prescenarioa1"));
        assert!(!wildcard_match("scenarioa1", "scenarioa2"));
    }

    #[test]
    fn test_wildcard_match_star() {
        // Prefix match.
        assert!(wildcard_match("scenario*", "scenarioa1"));
        assert!(wildcard_match("scenario*", "scenariob2"));
        assert!(!wildcard_match("scenario*", "other"));

        // Suffix match.
        assert!(wildcard_match("*a1", "scenarioa1"));
        assert!(!wildcard_match("*a1", "scenarioa2"));

        // Contains match.
        assert!(wildcard_match("*nario*", "scenarioa1"));
        assert!(!wildcard_match("*nario*", "other"));

        // Match all.
        assert!(wildcard_match("*", "anything"));
        assert!(wildcard_match("*", ""));

        // Multiple wildcards.
        assert!(wildcard_match("*a*b*", "xaxbx"));
        assert!(!wildcard_match("*a*b*", "xbxa"));
    }

    #[test]
    fn test_wildcard_match_issue_612() {
        // The exact bug: "put1024bytes" should NOT match "getput1024bytes".
        assert!(wildcard_match("put1024bytes", "put1024bytes"));
        assert!(!wildcard_match("put1024bytes", "getput1024bytes"));
        assert!(!wildcard_match("put1024bytes", "put1024bytesextra"));
    }

    /// Before the first Start no metrics processor has run, and the snapshot
    /// built from the main loop still says percentiles over time are on.
    #[cfg(feature = "dashboard")]
    #[test]
    fn local_dashboard_snapshot_reports_percentiles_over_time() {
        for (args, expected) in [
            (vec!["--dashboard"], true),
            (vec!["--dashboard", "--no-percentiles-over-time"], false),
        ] {
            let configuration = GooseConfiguration::parse_args_default(&args).unwrap();
            let mut goose_attack = GooseAttack::initialize_with_config(configuration).unwrap();
            let snapshot = goose_attack.build_local_dashboard_snapshot(
                "idle".to_string(),
                false,
                0,
                metrics::dashboard_snapshot::SnapshotSettings::idle(),
                None,
            );
            assert_eq!(snapshot.flags.percentiles_over_time, expected, "{args:?}");
            // No histograms are kept before the first test starts.
            assert_eq!(snapshot.series.heatmap, None);
        }
    }

    /// A real run's final metrics are marked final, so the summary printed
    /// when it ends carries the percentile table.
    #[tokio::test]
    #[serial_test::serial]
    async fn test_final_metrics_after_execute() {
        async fn get_index(user: &mut GooseUser) -> crate::goose::TransactionResult {
            let _goose = user.get("/").await?;
            Ok(())
        }
        let server = httpmock::MockServer::start();
        server.mock(|when, then| {
            when.method(httpmock::Method::GET).path("/");
            then.status(200);
        });
        let configuration = GooseConfiguration::parse_args_default(&[
            "--no-telnet",
            "--no-websocket",
            "--host",
            &server.base_url(),
            "--users",
            "1",
            "--run-time",
            "2",
        ])
        .unwrap();
        let goose_metrics = GooseAttack::initialize_with_config(configuration)
            .unwrap()
            .register_scenario(scenario!("Index").register_transaction(transaction!(get_index)))
            .execute()
            .await
            .unwrap();
        assert!(goose_metrics.final_metrics);
        let printed = goose_metrics.to_string();
        assert!(
            printed.contains("Slowest page load within specified percentile of requests (in ms):"),
            "{}",
            printed
        );
    }

    /// The transaction indexes `allocate_transactions` schedules for
    /// `scenario`, ignoring on_start and on_stop.
    fn scheduled(scenario: &Scenario, scheduler: &GooseScheduler) -> Vec<usize> {
        let (_, transactions, _) = allocate_transactions(scenario, scheduler);
        transactions.into_iter().map(|(index, _)| index).collect()
    }

    async fn noop_transaction(_user: &mut GooseUser) -> crate::goose::TransactionResult {
        Ok(())
    }

    /// The Random scheduler runs the Serial list in a random order: the same
    /// transactions, each as often, not in Serial order.
    #[test]
    fn test_random_scheduler_shuffles_transactions() {
        // Weights of 10 each reduce by their greatest common divisor to one
        // each, 3 orders of 6 being Serial in each run; weights of 10, 11 and
        // 12 do not reduce, and one in more than 10^14 orders is Serial.
        for weights in [[10, 10, 10], [10, 11, 12]] {
            let scenario = weights
                .iter()
                .fold(scenario!("Random"), |scenario, weight| {
                    scenario.register_transaction(
                        transaction!(noop_transaction).set_weight(*weight).unwrap(),
                    )
                });
            let serial = scheduled(&scenario, &GooseScheduler::Serial);
            let mut differs = false;
            for _ in 0..20 {
                let random = scheduled(&scenario, &GooseScheduler::Random);
                let mut sorted = random.clone();
                sorted.sort_unstable();
                assert_eq!(sorted, serial);
                differs |= random != serial;
            }
            assert!(
                differs,
                "Random scheduled transactions weighted {:?} in Serial order: {:?}",
                weights, serial
            );
        }
    }

    /// The Random scheduler shuffles within each sequence, and sequences keep
    /// their order.
    #[test]
    fn test_random_scheduler_keeps_sequence_order() {
        let scenario = scenario!("Sequenced")
            .register_transaction(
                transaction!(noop_transaction)
                    .set_sequence(2)
                    .set_weight(5)
                    .unwrap(),
            )
            .register_transaction(
                transaction!(noop_transaction)
                    .set_sequence(1)
                    .set_weight(5)
                    .unwrap(),
            )
            .register_transaction(
                transaction!(noop_transaction)
                    .set_sequence(1)
                    .set_weight(6)
                    .unwrap(),
            )
            .register_transaction(
                transaction!(noop_transaction)
                    .set_sequence(2)
                    .set_weight(6)
                    .unwrap(),
            );
        let serial = scheduled(&scenario, &GooseScheduler::Serial);
        assert_eq!(
            serial,
            [vec![1; 5], vec![2; 6], vec![0; 5], vec![3; 6]].concat()
        );
        let mut differs = false;
        for _ in 0..10 {
            let random = scheduled(&scenario, &GooseScheduler::Random);
            // Sequence 1, transactions 1 and 2, comes first, then sequence 2.
            let (first, second) = random.split_at(11);
            let mut first_sorted = first.to_vec();
            first_sorted.sort_unstable();
            assert_eq!(first_sorted, [vec![1; 5], vec![2; 6]].concat());
            let mut second_sorted = second.to_vec();
            second_sorted.sort_unstable();
            assert_eq!(second_sorted, [vec![0; 5], vec![3; 6]].concat());
            differs |= random != serial;
        }
        assert!(differs, "Random scheduled each sequence in Serial order");
    }

    /// The Random scheduler leaves on_start and on_stop transactions in Serial
    /// order.
    #[test]
    fn test_random_scheduler_keeps_on_start_and_on_stop_serial() {
        let scenario = (0..3).fold(scenario!("StartStop"), |scenario, _| {
            scenario.register_transaction(
                transaction!(noop_transaction)
                    .set_on_start()
                    .set_on_stop()
                    .set_weight(10)
                    .unwrap(),
            )
        });
        let scenario =
            scenario.register_transaction(transaction!(noop_transaction).set_weight(11).unwrap());
        let (serial_start, _, serial_stop) =
            allocate_transactions(&scenario, &GooseScheduler::Serial);
        let indexes = |list: WeightedTransactions| -> Vec<usize> {
            list.into_iter().map(|(index, _)| index).collect()
        };
        let (serial_start, serial_stop) = (indexes(serial_start), indexes(serial_stop));
        assert_eq!(serial_start.len(), 30);
        for _ in 0..10 {
            let (start, _, stop) = allocate_transactions(&scenario, &GooseScheduler::Random);
            assert_eq!(indexes(start), serial_start);
            assert_eq!(indexes(stop), serial_stop);
        }
    }

    /// Users weighted after the shared client is built, as a Controller adds them
    /// to a running load test, reuse that client: it is built once.
    #[test]
    fn test_shared_client_is_shared_by_users_added_later() {
        let configuration =
            GooseConfiguration::parse_args_default(&["--host", "http://127.0.0.1", "--quiet"])
                .unwrap();
        let mut goose_attack = GooseAttack::initialize_with_config(configuration)
            .unwrap()
            .register_scenario(
                scenario!("Shared").register_transaction(transaction!(noop_transaction)),
            )
            .set_client_builder_without_cookies(client::GooseClientBuilder::new().without_cookies())
            .unwrap();
        goose_attack
            .configuration
            .configure(&goose_attack.defaults)
            .unwrap();

        let builds = || client::SHARED_CLIENT_BUILDS.with(|builds| builds.get());
        let before = builds();
        goose_attack
            .build_client_strategy(client::CommandLineClientOptions::default())
            .unwrap();
        let mut users = goose_attack.weight_scenario_users(2).unwrap();
        users.extend(goose_attack.weight_scenario_users(2).unwrap());
        assert_eq!(users.len(), 4);
        assert_eq!(
            builds() - before,
            1,
            "users weighted later were given a newly built shared client"
        );
    }
}