shardline-server 1.0.1

HTTP server boundary, runtime, and operator workflows for Shardline.
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
#![cfg(feature = "docker")]
#![allow(
    clippy::indexing_slicing,
    clippy::unwrap_used,
    clippy::let_underscore_must_use,
    clippy::shadow_unrelated,
    clippy::expect_used,
    clippy::panic,
    clippy::needless_borrows_for_generic_args,
    clippy::unnecessary_map_or,
    clippy::or_fun_call
)]

use futures_util::{StreamExt, stream};
use sha2::{Digest, Sha256};
use shardline_protocol::{RepositoryProvider, RepositoryScope, TokenClaims, TokenScope};
use shardline_server::{ServerConfig, ServerFrontend, ServerRole, app};
use shardline_server_core::{AuthProvider, auth::LocalHmacProvider};
use shardline_test_support::DockerLocalStack;
use std::{
    num::{NonZeroU64, NonZeroUsize},
    sync::Arc,
    time::Duration,
};
use tempfile::TempDir;
use tokio::net::TcpListener;
use tokio::sync::OnceCell;
use tower::ServiceExt;

// ---------------------------------------------------------------------------
// Shared Docker Postgres — one container for all tests.
// ---------------------------------------------------------------------------

static PG: OnceCell<(DockerLocalStack, String)> = OnceCell::const_new();

/// Ensure the global Docker Postgres is running with migrations applied.
/// Returns the connection URL.
async fn ensure_pg() -> &'static str {
    let (_, url) = PG
        .get_or_init(|| async {
            let stack = DockerLocalStack::builder()
                .with_postgres()
                .start()
                .unwrap()
                .expect("Docker postgres: is docker available?");
            let base = stack.postgres_url().unwrap();
            let url = format!("{base}?sslmode=disable");
            // Run migrations with retry (container may not accept connections immediately).
            let mut last_err = None;
            for _ in 0..5 {
                match sqlx::PgPool::connect(&url).await {
                    Ok(pool) => {
                        shardline_server::apply_database_migrations(&pool)
                            .await
                            .unwrap();
                        pool.close().await;
                        return (stack, url);
                    }
                    Err(e) => {
                        last_err = Some(e);
                        tokio::time::sleep(std::time::Duration::from_millis(500)).await;
                    }
                }
            }
            panic!("Failed to connect to Postgres after 5 retries: {last_err:?}");
        })
        .await;
    url
}

// ---------------------------------------------------------------------------
// Test server harness — starts a real HTTP server on a random port.
// ---------------------------------------------------------------------------

const TEST_SIGNING_KEY: &[u8] = b"0123456789abcdef0123456789abcdef";

struct TestServer {
    shutdown: Option<tokio::sync::oneshot::Sender<()>>,
    base_url: String,
    token: String,
    _tmp: TempDir,
}

impl TestServer {
    /// Starts a full shardline HTTP server with the given frontends, backed by
    /// the shared Docker Postgres instance.
    async fn start(frontends: &[ServerFrontend]) -> Self {
        let pg_url = ensure_pg().await;

        let tmp = TempDir::new().unwrap();
        let chunk_size = NonZeroUsize::new(65536).unwrap();

        let config = ServerConfig::new(
            "127.0.0.1:0".parse().unwrap(),
            "http://127.0.0.1:8080".to_owned(),
            tmp.path().to_path_buf(),
            chunk_size,
        )
        .with_server_role(ServerRole::All)
        .with_server_frontends(frontends.to_vec())
        .unwrap()
        .with_token_signing_key(TEST_SIGNING_KEY.to_vec())
        .unwrap()
        .with_index_postgres_url(pg_url.to_owned())
        .unwrap()
        .with_reconstruction_cache_disabled();

        config.validate_runtime_requirements().unwrap();

        // Build the router and start serving.
        let app = app::router(config).await.unwrap();

        // Bind to a random port via tokio's TcpListener.
        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        let base_url = format!("http://{addr}");

        let (shutdown_tx, shutdown_rx) = tokio::sync::oneshot::channel::<()>();

        tokio::spawn(async move {
            axum::serve(listener, app)
                .with_graceful_shutdown(async {
                    shutdown_rx.await.ok();
                })
                .await
                .ok();
        });

        // Give the server a moment to start.
        tokio::time::sleep(Duration::from_millis(100)).await;

        // Mint a bearer token with full scope.
        let provider = LocalHmacProvider::new(TEST_SIGNING_KEY).unwrap();
        let repo = RepositoryScope::new(RepositoryProvider::Generic, "test", "test", Some("main"))
            .unwrap();
        let claims =
            TokenClaims::new("shardline", "test", TokenScope::Write, repo, u64::MAX).unwrap();
        let token = provider.mint_token(&claims).unwrap();

        Self {
            shutdown: Some(shutdown_tx),
            base_url,
            token,
            _tmp: tmp,
        }
    }

    fn url(&self, path: &str) -> String {
        format!("{}{}", self.base_url, path)
    }

    fn auth_header(&self) -> &str {
        &self.token
    }
}

impl Drop for TestServer {
    fn drop(&mut self) {
        if let Some(tx) = self.shutdown.take() {
            let _ = tx.send(());
        }
    }
}

// ---------------------------------------------------------------------------
// TestServerBuilder — configurable test server for role-split / provider tests
// ---------------------------------------------------------------------------

struct TestServerBuilder {
    frontends: Vec<ServerFrontend>,
    role: ServerRole,
    provider_config: Option<(TempDir, std::path::PathBuf)>,
}

impl TestServerBuilder {
    fn new(frontends: &[ServerFrontend]) -> Self {
        Self {
            frontends: frontends.to_vec(),
            role: ServerRole::All,
            provider_config: None,
        }
    }

    fn with_provider(mut self) -> Self {
        // Create a temporary provider config file
        let tmp = TempDir::new().unwrap();
        let config_path = tmp.path().join("providers.json");
        let provider_config = serde_json::json!({
            "providers": [{
                "kind": "generic",
                "integration_subject": "test-app",
                "webhook_secret": "test-secret",
                "repositories": [{
                    "owner": "test",
                    "name": "test",
                    "visibility": "private",
                    "default_revision": "main",
                    "clone_url": "https://example.com/test/test.git",
                    "read_subjects": ["test-user"],
                    "write_subjects": ["test-user"]
                }]
            }]
        });
        std::fs::write(&config_path, serde_json::to_vec(&provider_config).unwrap()).unwrap();
        self.provider_config = Some((tmp, config_path));
        self
    }

    async fn start(&mut self) -> TestServer {
        let pg_url = ensure_pg().await;
        let tmp = TempDir::new().unwrap();
        let chunk_size = NonZeroUsize::new(65536).unwrap();

        let mut config = ServerConfig::new(
            "127.0.0.1:0".parse().unwrap(),
            "http://127.0.0.1:8080".to_owned(),
            tmp.path().to_path_buf(),
            chunk_size,
        )
        .with_server_role(self.role)
        .with_server_frontends(self.frontends.clone())
        .unwrap()
        .with_token_signing_key(TEST_SIGNING_KEY.to_vec())
        .unwrap()
        .with_index_postgres_url(pg_url.to_owned())
        .unwrap()
        .with_reconstruction_cache_disabled();

        if let Some((_provider_tmp, config_path)) = self.provider_config.as_ref() {
            config = config
                .with_provider_runtime(
                    config_path.clone(),
                    b"test-api-key".to_vec(),
                    "test-issuer".to_owned(),
                    NonZeroU64::new(3600).unwrap(),
                )
                .unwrap();
        }

        config.validate_runtime_requirements().unwrap();

        let app = app::router(config).await.unwrap();
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        let base_url = format!("http://{addr}");

        let (shutdown_tx, shutdown_rx) = tokio::sync::oneshot::channel::<()>();

        tokio::spawn(async move {
            axum::serve(listener, app)
                .with_graceful_shutdown(async {
                    shutdown_rx.await.ok();
                })
                .await
                .ok();
        });

        tokio::time::sleep(Duration::from_millis(100)).await;

        // Mint a bearer token with full scope.
        let provider = LocalHmacProvider::new(TEST_SIGNING_KEY).unwrap();
        let repo = RepositoryScope::new(RepositoryProvider::Generic, "test", "test", Some("main"))
            .unwrap();
        let claims =
            TokenClaims::new("shardline", "test", TokenScope::Write, repo, u64::MAX).unwrap();
        let token = provider.mint_token(&claims).unwrap();

        TestServer {
            shutdown: Some(shutdown_tx),
            base_url,
            token,
            _tmp: tmp,
        }
    }
}

// ===========================================================================
// Tests
// ===========================================================================

/// Helper: compute SHA-256 hex digest.
fn sha256_hex(data: &[u8]) -> String {
    hex::encode(Sha256::digest(data))
}

// ---------------------------------------------------------------------------
// 1. Health endpoint
// ---------------------------------------------------------------------------

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_healthz_returns_200() {
    let server = TestServer::start(&[ServerFrontend::Xet]).await;
    let client = reqwest::Client::new();

    let resp = client.get(server.url("/healthz")).send().await.unwrap();

    assert_eq!(resp.status(), 200);
    let json: serde_json::Value = resp.json().await.unwrap();
    assert_eq!(json["status"], "ok");
}

// ---------------------------------------------------------------------------
// 2. Ready endpoint — shows postgres backend
// ---------------------------------------------------------------------------

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_readyz_returns_postgres_backend() {
    let server = TestServer::start(&[ServerFrontend::Xet]).await;
    let client = reqwest::Client::new();

    let resp = client.get(server.url("/readyz")).send().await.unwrap();

    assert_eq!(resp.status(), 200);
    let json: serde_json::Value = resp.json().await.unwrap();
    assert_eq!(json["status"], "ok");
    assert_eq!(json["metadata_backend"], "postgres");
}

// ---------------------------------------------------------------------------
// 3. Stats endpoint — 401 without auth, 200 with auth
// ---------------------------------------------------------------------------

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_stats_without_auth_returns_401() {
    let server = TestServer::start(&[ServerFrontend::Xet]).await;
    let client = reqwest::Client::new();

    let resp = client.get(server.url("/v1/stats")).send().await.unwrap();

    assert_eq!(resp.status(), 401);
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_stats_with_auth_returns_200() {
    let server = TestServer::start(&[ServerFrontend::Xet]).await;
    let client = reqwest::Client::new();

    let resp = client
        .get(server.url("/v1/stats"))
        .header("Authorization", format!("Bearer {}", server.auth_header()))
        .send()
        .await
        .unwrap();

    assert_eq!(resp.status(), 200);
    let json: serde_json::Value = resp.json().await.unwrap();
    // Fresh backend has zero chunks and files.
    assert_eq!(json["chunks"], 0);
    assert_eq!(json["files"], 0);
}

// ---------------------------------------------------------------------------
// 4. LFS — PUT a file, GET it back, verify content
// ---------------------------------------------------------------------------

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_lfs_put_and_get() {
    let server = TestServer::start(&[ServerFrontend::Lfs]).await;
    let client = reqwest::Client::new();

    let content = b"Hello, LFS over HTTP!";
    let oid = sha256_hex(content);

    // PUT the object.
    let put_resp = client
        .put(server.url(&format!("/v1/lfs/objects/{oid}")))
        .header("Authorization", format!("Bearer {}", server.auth_header()))
        .header("Content-Type", "application/octet-stream")
        .body(content.to_vec())
        .send()
        .await
        .unwrap();
    assert!(
        put_resp.status().is_success(),
        "LFS PUT failed: {}",
        put_resp.status()
    );

    // GET the object back.
    let get_resp = client
        .get(server.url(&format!("/v1/lfs/objects/{oid}")))
        .header("Authorization", format!("Bearer {}", server.auth_header()))
        .send()
        .await
        .unwrap();
    assert_eq!(get_resp.status(), 200);
    let body = get_resp.bytes().await.unwrap();
    assert_eq!(body.as_ref(), content);
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_large_object_upload_http_e2e() {
    let server = TestServer::start(&[ServerFrontend::Lfs]).await;
    let client = reqwest::Client::new();

    // Create a ~5MB content
    let content = vec![0xAB_u8; 5 * 1024 * 1024];
    let oid = sha256_hex(&content);

    // PUT the large object
    let put_resp = client
        .put(server.url(&format!("/v1/lfs/objects/{oid}")))
        .header("Authorization", format!("Bearer {}", server.auth_header()))
        .header("Content-Type", "application/octet-stream")
        .body(content.clone())
        .send()
        .await
        .unwrap();
    assert!(
        put_resp.status().is_success(),
        "LFS large object PUT failed: {}",
        put_resp.status()
    );

    // GET the object back and verify
    let get_resp = client
        .get(server.url(&format!("/v1/lfs/objects/{oid}")))
        .header("Authorization", format!("Bearer {}", server.auth_header()))
        .send()
        .await
        .unwrap();
    assert_eq!(get_resp.status(), 200);
    let body = get_resp.bytes().await.unwrap();
    assert_eq!(body.len(), content.len(), "downloaded size differs");
    assert_eq!(
        body.as_ref(),
        content.as_slice(),
        "downloaded content differs"
    );
}

// ---------------------------------------------------------------------------
// 5. Bazel CAS — PUT content-addressed, GET back, verify
// ---------------------------------------------------------------------------

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_bazel_cas_put_and_get() {
    let server = TestServer::start(&[ServerFrontend::BazelHttp]).await;
    let client = reqwest::Client::new();

    let content = b"Bazel CAS content addressed!";
    let hash = sha256_hex(content);

    // PUT the CAS blob.
    let put_resp = client
        .put(server.url(&format!("/v1/bazel/cache/cas/{hash}")))
        .header("Authorization", format!("Bearer {}", server.auth_header()))
        .header("Content-Type", "application/octet-stream")
        .body(content.to_vec())
        .send()
        .await
        .unwrap();
    assert!(
        put_resp.status().is_success(),
        "Bazel CAS PUT failed: {}",
        put_resp.status()
    );

    // GET the blob back.
    let get_resp = client
        .get(server.url(&format!("/v1/bazel/cache/cas/{hash}")))
        .header("Authorization", format!("Bearer {}", server.auth_header()))
        .send()
        .await
        .unwrap();
    assert_eq!(get_resp.status(), 200);
    let body = get_resp.bytes().await.unwrap();
    assert_eq!(body.as_ref(), content);
}

// ---------------------------------------------------------------------------
// 6. OCI — session upload (POST -> PATCH -> PUT), verify
// ---------------------------------------------------------------------------

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_oci_v2_root_returns_200() {
    let server = TestServer::start(&[ServerFrontend::Oci]).await;
    let client = reqwest::Client::builder()
        .redirect(reqwest::redirect::Policy::none())
        .build()
        .unwrap();

    // GET /v2/ should return 200 OK (requires auth).
    let resp = client
        .get(server.url("/v2/"))
        .header("Authorization", format!("Bearer {}", server.auth_header()))
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), 200);
    assert_eq!(
        resp.headers()
            .get("Docker-Distribution-API-Version")
            .and_then(|v| v.to_str().ok()),
        Some("registry/2.0")
    );
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_oci_upload_session() {
    // OCI v2 root and token endpoints work via HTTP, but the wildcard route
    // `/v2/{*path}` has a routing issue with reqwest in this test setup.
    // The monolithic blob upload and blob GET use Axum's built-in
    // `tower::ServiceExt::oneshot` to bypass the HTTP layer and test the full
    // handler/backend stack directly. Health/ready metrics tests above already
    // validate the HTTP layer end-to-end.
    let content = b"OCI session upload content";
    let digest = sha256_hex(content);
    // Repository must match or be under the token scope owner/name (test/test).
    let repo = "test/test";

    // Build a fresh app for oneshot testing.
    let pg_url = ensure_pg().await;
    let tmp = TempDir::new().unwrap();
    let chunk_size = NonZeroUsize::new(65536).unwrap();
    let config = ServerConfig::new(
        "127.0.0.1:0".parse().unwrap(),
        "http://127.0.0.1:8080".to_owned(),
        tmp.path().to_path_buf(),
        chunk_size,
    )
    .with_server_role(ServerRole::All)
    .with_server_frontends([ServerFrontend::Oci])
    .unwrap()
    .with_token_signing_key(TEST_SIGNING_KEY.to_vec())
    .unwrap()
    .with_index_postgres_url(pg_url.to_owned())
    .unwrap()
    .with_reconstruction_cache_disabled();
    config.validate_runtime_requirements().unwrap();

    // Build the same app via the shared router function used by the server
    // binary. This tests the full handler/backend stack including auth,
    // Postgres backend, OCI path parsing, and write path.
    let app = app::router(config).await.unwrap();

    // Mint a token with the same signing key.
    let token = {
        let provider = LocalHmacProvider::new(TEST_SIGNING_KEY).unwrap();
        let repo = RepositoryScope::new(RepositoryProvider::Generic, "test", "test", Some("main"))
            .unwrap();
        let claims =
            TokenClaims::new("shardline", "test", TokenScope::Write, repo, u64::MAX).unwrap();
        provider.mint_token(&claims).unwrap()
    };

    // Monolithic upload via POST with ?digest= query parameter.
    let uri = format!("/v2/{repo}/blobs/uploads/?digest=sha256:{digest}");
    let request = axum::http::Request::builder()
        .method("POST")
        .uri(&uri)
        .header("Authorization", format!("Bearer {token}"))
        .header("Content-Type", "application/octet-stream")
        .body(axum::body::Body::from(content.to_vec()))
        .unwrap();
    let response = app.clone().oneshot(request).await.unwrap();
    let status = response.status();
    let body = axum::body::to_bytes(response.into_body(), usize::MAX)
        .await
        .unwrap();
    assert_eq!(
        status,
        201,
        "OCI monolithic upload (oneshot) failed: status={} body={:?}",
        status,
        String::from_utf8_lossy(&body)
    );

    // Verify: GET the blob and check content (digest needs sha256: prefix for OCI path parser).
    let get_uri = format!("/v2/{repo}/blobs/sha256:{digest}");
    let get_request = axum::http::Request::builder()
        .method("GET")
        .uri(&get_uri)
        .header("Authorization", format!("Bearer {token}"))
        .body(axum::body::Body::empty())
        .unwrap();
    let get_response = app.oneshot(get_request).await.unwrap();
    assert_eq!(get_response.status(), 200);
    let get_body = axum::body::to_bytes(get_response.into_body(), usize::MAX)
        .await
        .unwrap();
    assert_eq!(get_body.as_ref(), content);
}

// ---------------------------------------------------------------------------
// 7. Hub — whoami endpoint
// ---------------------------------------------------------------------------

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_hub_whoami_returns_200() {
    let server = TestServer::start(&[ServerFrontend::Hub]).await;
    let client = reqwest::Client::new();

    let resp = client
        .get(server.url("/api/whoami-v2"))
        .send()
        .await
        .unwrap();

    assert_eq!(resp.status(), 200);
}

// ---------------------------------------------------------------------------
// 8. Metrics — contains expected labels
// ---------------------------------------------------------------------------

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_metrics_contains_expected_content() {
    let server = TestServer::start(&[ServerFrontend::Xet]).await;
    let client = reqwest::Client::new();

    let resp = client.get(server.url("/metrics")).send().await.unwrap();

    assert_eq!(resp.status(), 200);
    let body = resp.text().await.unwrap();
    assert!(
        body.contains("shardline_up 1"),
        "metrics should contain shardline_up gauge"
    );
    assert!(body.contains("# HELP"), "metrics should contain HELP lines");
    assert!(body.contains("# TYPE"), "metrics should contain TYPE lines");
    assert!(
        body.contains("metadata_backend=\"postgres\""),
        "metrics should reference postgres backend: {body}"
    );
}

// ---------------------------------------------------------------------------
// 9. Auth rejection — verify 401 without token
// ---------------------------------------------------------------------------

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_auth_rejection_without_token() {
    let server = TestServer::start(&[ServerFrontend::Xet]).await;
    let client = reqwest::Client::new();

    // Endpoints that require auth should return 401 without a bearer token.
    // Only use endpoints registered by the Xet frontend.
    let endpoints = &[
        "/v1/stats",
        "/v1/reconstructions/nonexistent",
        "/v1/chunks/default/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
    ];

    for endpoint in endpoints {
        let resp = client.get(server.url(endpoint)).send().await.unwrap();
        assert_eq!(
            resp.status(),
            401,
            "endpoint {endpoint} should return 401 without auth, got {}",
            resp.status()
        );
    }
}

// ---------------------------------------------------------------------------
// 10. All frontends simultaneously — health/ready work with all frontends
// ---------------------------------------------------------------------------

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_all_frontends_health_and_ready() {
    let frontends = &[
        ServerFrontend::Xet,
        ServerFrontend::Lfs,
        ServerFrontend::BazelHttp,
        ServerFrontend::Oci,
        ServerFrontend::Hub,
    ];
    let server = TestServer::start(frontends).await;
    let client = reqwest::Client::new();

    // Health check.
    let resp = client.get(server.url("/healthz")).send().await.unwrap();
    assert_eq!(resp.status(), 200);
    let json: serde_json::Value = resp.json().await.unwrap();
    assert_eq!(json["status"], "ok");

    // Readiness check.
    let resp = client.get(server.url("/readyz")).send().await.unwrap();
    assert_eq!(resp.status(), 200);
    let json: serde_json::Value = resp.json().await.unwrap();
    assert_eq!(json["status"], "ok");
    assert_eq!(json["metadata_backend"], "postgres");
    assert!(json["server_frontends"].as_array().unwrap().len() >= 5);
}

// ===========================================================================
// 11. OCI Manifest + Tag operations (via oneshot — wildcard route limitation)
// ===========================================================================

/// Build a temporary OCI app for oneshot tests. Reuses ensure_pg().
async fn oci_oneshot_app() -> (axum::Router, String) {
    let pg_url = ensure_pg().await;
    let tmp = TempDir::new().unwrap();
    let chunk_size = NonZeroUsize::new(65536).unwrap();
    let config = ServerConfig::new(
        "127.0.0.1:0".parse().unwrap(),
        "http://127.0.0.1:8080".to_owned(),
        tmp.path().to_path_buf(),
        chunk_size,
    )
    .with_server_role(ServerRole::All)
    .with_server_frontends([ServerFrontend::Oci])
    .unwrap()
    .with_token_signing_key(TEST_SIGNING_KEY.to_vec())
    .unwrap()
    .with_index_postgres_url(pg_url.to_owned())
    .unwrap()
    .with_reconstruction_cache_disabled();
    config.validate_runtime_requirements().unwrap();
    let app = app::router(config).await.unwrap();

    let provider = LocalHmacProvider::new(TEST_SIGNING_KEY).unwrap();
    let repo_s =
        RepositoryScope::new(RepositoryProvider::Generic, "test", "test", Some("main")).unwrap();
    let claims =
        TokenClaims::new("shardline", "test", TokenScope::Write, repo_s, u64::MAX).unwrap();
    let token = provider.mint_token(&claims).unwrap();
    // Keep tmp alive by returning it — we leak it via a static or just let it
    // drop (the app already has the PathBuf, so it works for the test duration).
    let _ = Box::new(tmp);
    (app, token)
}

fn oci_digest_hex(data: &[u8]) -> String {
    sha256_hex(data)
}

/// Upload a blob via oneshot monolithic POST. Returns the hex digest.
async fn oci_upload_blob_oneshot(
    app: &axum::Router,
    token: &str,
    repo: &str,
    data: &[u8],
) -> String {
    let digest = oci_digest_hex(data);
    let uri = format!("/v2/{repo}/blobs/uploads/?digest=sha256:{digest}");
    let req = axum::http::Request::builder()
        .method("POST")
        .uri(&uri)
        .header("Authorization", format!("Bearer {token}"))
        .header("Content-Type", "application/octet-stream")
        .body(axum::body::Body::from(data.to_vec()))
        .unwrap();
    let resp = app.clone().oneshot(req).await.unwrap();
    assert_eq!(resp.status(), 201, "blob upload: status={}", resp.status());
    digest
}

fn oci_manifest_json(config_digest: &str, layer_digest: &str) -> String {
    serde_json::json!({
        "schemaVersion": 2,
        "mediaType": "application/vnd.oci.image.manifest.v1+json",
        "config": {
            "mediaType": "application/vnd.oci.image.config.v1+json",
            "size": 0,
            "digest": format!("sha256:{config_digest}")
        },
        "layers": [
            {
                "mediaType": "application/vnd.oci.image.layer.v1.tar+gzip",
                "size": 0,
                "digest": format!("sha256:{layer_digest}")
            }
        ]
    })
    .to_string()
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_oci_manifest_push_and_get_by_tag() {
    let (app, token) = oci_oneshot_app().await;
    let repo = "test/test";
    let tag = "v0.0.1";

    let config_data = b"{}";
    let layer_data = b"\x1f\x8b\x08\x00";
    let config_digest = oci_upload_blob_oneshot(&app, &token, repo, config_data).await;
    let layer_digest = oci_upload_blob_oneshot(&app, &token, repo, layer_data).await;

    let manifest_body = oci_manifest_json(&config_digest, &layer_digest);
    let manifest_digest = oci_digest_hex(manifest_body.as_bytes());

    // PUT manifest by tag
    let put_uri = format!("/v2/{repo}/manifests/{tag}");
    let put_req = axum::http::Request::builder()
        .method("PUT")
        .uri(&put_uri)
        .header("Authorization", format!("Bearer {token}"))
        .header("Content-Type", "application/vnd.oci.image.manifest.v1+json")
        .body(axum::body::Body::from(manifest_body.clone()))
        .unwrap();
    let put_resp = app.clone().oneshot(put_req).await.unwrap();
    assert_eq!(put_resp.status(), 201, "manifest PUT failed");
    let digest_header = put_resp
        .headers()
        .get("Docker-Content-Digest")
        .and_then(|v| v.to_str().ok())
        .map(|s| s.to_owned());
    assert!(digest_header.is_some(), "missing Docker-Content-Digest");
    assert!(
        digest_header.as_ref().unwrap().contains(&manifest_digest),
        "digest mismatch: {:?} vs {}",
        digest_header,
        manifest_digest
    );

    // GET manifest by tag
    let get_uri = format!("/v2/{repo}/manifests/{tag}");
    let get_req = axum::http::Request::builder()
        .method("GET")
        .uri(&get_uri)
        .header("Authorization", format!("Bearer {token}"))
        .body(axum::body::Body::empty())
        .unwrap();
    let get_resp = app.clone().oneshot(get_req).await.unwrap();
    assert_eq!(get_resp.status(), 200);
    let get_body_bytes = axum::body::to_bytes(get_resp.into_body(), usize::MAX)
        .await
        .unwrap();
    let get_json: serde_json::Value = serde_json::from_slice(&get_body_bytes).unwrap();
    assert_eq!(get_json["schemaVersion"], 2);
    assert_eq!(
        get_json["mediaType"],
        "application/vnd.oci.image.manifest.v1+json"
    );
    assert_eq!(
        get_json["config"]["digest"],
        format!("sha256:{config_digest}")
    );
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_oci_manifest_get_by_digest() {
    let (app, token) = oci_oneshot_app().await;
    let repo = "test/test";
    let tag = "digest-ref";

    let config_data = b"{}";
    let layer_data = b"digest-layer-data";
    let config_digest = oci_upload_blob_oneshot(&app, &token, repo, config_data).await;
    let layer_digest = oci_upload_blob_oneshot(&app, &token, repo, layer_data).await;

    let manifest_body = oci_manifest_json(&config_digest, &layer_digest);
    let manifest_digest = oci_digest_hex(manifest_body.as_bytes());

    // Push manifest
    let put_uri = format!("/v2/{repo}/manifests/{tag}");
    let put_req = axum::http::Request::builder()
        .method("PUT")
        .uri(&put_uri)
        .header("Authorization", format!("Bearer {token}"))
        .header("Content-Type", "application/vnd.oci.image.manifest.v1+json")
        .body(axum::body::Body::from(manifest_body))
        .unwrap();
    let put_resp = app.clone().oneshot(put_req).await.unwrap();
    assert_eq!(put_resp.status(), 201);

    // GET manifest by digest
    let get_uri = format!("/v2/{repo}/manifests/sha256:{manifest_digest}");
    let get_req = axum::http::Request::builder()
        .method("GET")
        .uri(&get_uri)
        .header("Authorization", format!("Bearer {token}"))
        .body(axum::body::Body::empty())
        .unwrap();
    let get_resp = app.clone().oneshot(get_req).await.unwrap();
    assert_eq!(get_resp.status(), 200);
    let get_body_bytes = axum::body::to_bytes(get_resp.into_body(), usize::MAX)
        .await
        .unwrap();
    let get_json: serde_json::Value = serde_json::from_slice(&get_body_bytes).unwrap();
    assert_eq!(get_json["schemaVersion"], 2);
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_oci_tags_list() {
    let (app, token) = oci_oneshot_app().await;
    let repo = "test/test";
    let tag = "list-me";

    // Push a manifest so a tag exists
    let config_data = b"{}";
    let layer_data = b"tags-layer";
    let config_digest = oci_upload_blob_oneshot(&app, &token, repo, config_data).await;
    let layer_digest = oci_upload_blob_oneshot(&app, &token, repo, layer_data).await;
    let manifest_body = oci_manifest_json(&config_digest, &layer_digest);

    let put_uri = format!("/v2/{repo}/manifests/{tag}");
    let put_req = axum::http::Request::builder()
        .method("PUT")
        .uri(&put_uri)
        .header("Authorization", format!("Bearer {token}"))
        .header("Content-Type", "application/vnd.oci.image.manifest.v1+json")
        .body(axum::body::Body::from(manifest_body))
        .unwrap();
    let put_resp = app.clone().oneshot(put_req).await.unwrap();
    assert_eq!(put_resp.status(), 201);

    // List tags
    let list_uri = format!("/v2/{repo}/tags/list");
    let list_req = axum::http::Request::builder()
        .method("GET")
        .uri(&list_uri)
        .header("Authorization", format!("Bearer {token}"))
        .body(axum::body::Body::empty())
        .unwrap();
    let list_resp = app.clone().oneshot(list_req).await.unwrap();
    assert_eq!(list_resp.status(), 200);
    let list_body: serde_json::Value = serde_json::from_slice(
        &axum::body::to_bytes(list_resp.into_body(), usize::MAX)
            .await
            .unwrap(),
    )
    .unwrap();
    assert_eq!(list_body["name"], repo);
    let tags = list_body["tags"].as_array().unwrap();
    assert!(
        tags.iter().any(|t| t == tag),
        "tag {tag} should appear in list: {tags:?}"
    );
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_oci_blob_head() {
    let (app, token) = oci_oneshot_app().await;
    let repo = "test/test";

    let content = b"head-blob-content";
    let digest = oci_upload_blob_oneshot(&app, &token, repo, content).await;

    // HEAD the blob
    let head_uri = format!("/v2/{repo}/blobs/sha256:{digest}");
    let head_req = axum::http::Request::builder()
        .method("HEAD")
        .uri(&head_uri)
        .header("Authorization", format!("Bearer {token}"))
        .body(axum::body::Body::empty())
        .unwrap();
    let head_resp = app.clone().oneshot(head_req).await.unwrap();
    assert_eq!(head_resp.status(), 200);
    let content_len: u64 = head_resp
        .headers()
        .get("content-length")
        .and_then(|v| v.to_str().ok())
        .and_then(|s| s.parse().ok())
        .unwrap_or(0);
    assert_eq!(content_len, content.len() as u64);
    // Docker-Content-Digest header should be present
    assert!(
        head_resp.headers().get("Docker-Content-Digest").is_some(),
        "missing Docker-Content-Digest header"
    );
}

// ===========================================================================
// 12. LFS edge cases
// ===========================================================================

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_lfs_batch_upload_existing() {
    let server = TestServer::start(&[ServerFrontend::Lfs]).await;
    let client = reqwest::Client::new();

    let content = b"lfs-batch-existing-test";
    let oid = sha256_hex(content);

    // Upload the object first
    let put_resp = client
        .put(server.url(&format!("/v1/lfs/objects/{oid}")))
        .header("Authorization", format!("Bearer {}", server.auth_header()))
        .header("Content-Type", "application/octet-stream")
        .body(content.to_vec())
        .send()
        .await
        .unwrap();
    assert!(put_resp.status().is_success());

    // Batch upload — should report no upload actions for existing object
    let batch_req = serde_json::json!({
        "operation": "upload",
        "objects": [{"oid": oid, "size": content.len() as u64}]
    });
    let batch_resp = client
        .post(server.url("/v1/lfs/objects/batch"))
        .header("Authorization", format!("Bearer {}", server.auth_header()))
        .header("Content-Type", "application/vnd.git-lfs+json")
        .json(&batch_req)
        .send()
        .await
        .unwrap();
    assert_eq!(batch_resp.status(), 200);
    let batch_json: serde_json::Value = batch_resp.json().await.unwrap();
    let obj = &batch_json["objects"][0];
    assert_eq!(obj["oid"], oid);
    // Existing object should NOT have upload actions
    assert!(
        obj.get("actions").is_none() || obj["actions"].as_object().map_or(true, |m| m.is_empty()),
        "existing object should not have upload actions"
    );
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_lfs_batch_download_missing() {
    let server = TestServer::start(&[ServerFrontend::Lfs]).await;
    let client = reqwest::Client::new();

    let fake_oid = "f".repeat(64);
    let batch_req = serde_json::json!({
        "operation": "download",
        "objects": [{"oid": fake_oid, "size": 42}]
    });
    let batch_resp = client
        .post(server.url("/v1/lfs/objects/batch"))
        .header("Authorization", format!("Bearer {}", server.auth_header()))
        .header("Content-Type", "application/vnd.git-lfs+json")
        .json(&batch_req)
        .send()
        .await
        .unwrap();
    assert_eq!(batch_resp.status(), 200);
    let batch_json: serde_json::Value = batch_resp.json().await.unwrap();
    let obj = &batch_json["objects"][0];
    assert_eq!(obj["oid"], fake_oid);
    // Missing object should have an error
    assert!(
        obj.get("error").is_some(),
        "missing object should have error field: {obj:?}"
    );
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_lfs_head_object() {
    let server = TestServer::start(&[ServerFrontend::Lfs]).await;
    let client = reqwest::Client::new();

    let content = b"lfs-head-test";
    let oid = sha256_hex(content);

    // Upload
    client
        .put(server.url(&format!("/v1/lfs/objects/{oid}")))
        .header("Authorization", format!("Bearer {}", server.auth_header()))
        .header("Content-Type", "application/octet-stream")
        .body(content.to_vec())
        .send()
        .await
        .unwrap();

    // HEAD
    let head_resp = client
        .head(server.url(&format!("/v1/lfs/objects/{oid}")))
        .header("Authorization", format!("Bearer {}", server.auth_header()))
        .send()
        .await
        .unwrap();
    assert_eq!(head_resp.status(), 200);
    let cl: u64 = head_resp
        .headers()
        .get("content-length")
        .and_then(|v| v.to_str().ok())
        .and_then(|s| s.parse().ok())
        .unwrap_or(0);
    assert_eq!(cl, content.len() as u64);
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_lfs_patch_object() {
    let server = TestServer::start(&[ServerFrontend::Lfs]).await;
    let client = reqwest::Client::new();

    let chunk1 = b"lfs-patch-initial-";
    let chunk2 = b"content";
    let full_content = [chunk1.to_vec(), chunk2.to_vec()].concat();
    let oid = sha256_hex(&full_content);
    let total = full_content.len() as u64;

    // PATCH chunk 1
    let range1 = format!("bytes 0-{}/{}", chunk1.len() as u64 - 1, total);
    let patch1 = client
        .patch(server.url(&format!("/v1/lfs/objects/{oid}")))
        .header("Authorization", format!("Bearer {}", server.auth_header()))
        .header("Content-Type", "application/octet-stream")
        .header("Content-Range", &range1)
        .body(chunk1.to_vec())
        .send()
        .await
        .unwrap();
    assert_eq!(patch1.status(), 200, "PATCH chunk1 failed");

    // PATCH chunk 2 (final)
    let range2 = format!("bytes {}-{}/{}", chunk1.len(), total - 1, total);
    let patch2 = client
        .patch(server.url(&format!("/v1/lfs/objects/{oid}")))
        .header("Authorization", format!("Bearer {}", server.auth_header()))
        .header("Content-Type", "application/octet-stream")
        .header("Content-Range", &range2)
        .body(chunk2.to_vec())
        .send()
        .await
        .unwrap();
    assert_eq!(patch2.status(), 200, "PATCH chunk2 failed");

    // GET and verify full content
    let get_resp = client
        .get(server.url(&format!("/v1/lfs/objects/{oid}")))
        .header("Authorization", format!("Bearer {}", server.auth_header()))
        .send()
        .await
        .unwrap();
    assert_eq!(get_resp.status(), 200);
    let body = get_resp.bytes().await.unwrap();
    assert_eq!(body.as_ref(), full_content.as_slice());
}

// ===========================================================================
// 17. Provider token tests
// ===========================================================================

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_provider_issue_token_with_valid_key() {
    let mut builder =
        TestServerBuilder::new(&[ServerFrontend::Xet, ServerFrontend::Oci]).with_provider();
    let server = builder.start().await;
    let client = reqwest::Client::new();

    let resp = client
        .post(server.url("/v1/providers/generic/tokens"))
        .header("x-shardline-provider-key", "test-api-key")
        .header("Content-Type", "application/json")
        .json(&serde_json::json!({
            "subject": "test-user",
            "owner": "test",
            "repo": "test",
            "revision": null,
            "scope": "Read"
        }))
        .send()
        .await
        .unwrap();
    let status = resp.status();
    let body_text = resp.text().await.unwrap_or_default();
    assert_eq!(status, 200, "token issue failed: body={}", body_text);
    let json: serde_json::Value = serde_json::from_str(&body_text).unwrap();
    assert!(!json["token"].as_str().unwrap().is_empty());
    assert_eq!(json["owner"], "test");
    assert_eq!(json["repo"], "test");
    assert_eq!(json["scope"], "Read");
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_provider_issue_token_without_api_key_returns_401() {
    let mut builder = TestServerBuilder::new(&[ServerFrontend::Xet]).with_provider();
    let server = builder.start().await;
    let client = reqwest::Client::new();

    let resp = client
        .post(server.url("/v1/providers/generic/tokens"))
        .header("Content-Type", "application/json")
        .json(&serde_json::json!({
            "subject": "test-user",
            "owner": "test",
            "repo": "test",
            "revision": null,
            "scope": "Read"
        }))
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), 401);
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_provider_issue_token_with_invalid_key_returns_403() {
    let mut builder = TestServerBuilder::new(&[ServerFrontend::Xet]).with_provider();
    let server = builder.start().await;
    let client = reqwest::Client::new();

    let resp = client
        .post(server.url("/v1/providers/generic/tokens"))
        .header("x-shardline-provider-key", "wrong-key")
        .header("Content-Type", "application/json")
        .json(&serde_json::json!({
            "subject": "test-user",
            "owner": "test",
            "repo": "test",
            "revision": null,
            "scope": "Read"
        }))
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), 403);
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_provider_git_lfs_authenticate() {
    let mut builder =
        TestServerBuilder::new(&[ServerFrontend::Xet, ServerFrontend::Oci]).with_provider();
    let server = builder.start().await;
    let client = reqwest::Client::new();

    let resp = client
        .post(server.url("/v1/providers/generic/git-lfs-authenticate"))
        .header("x-shardline-provider-key", "test-api-key")
        .header("Content-Type", "application/json")
        .json(&serde_json::json!({
            "subject": "test-user",
            "owner": "test",
            "repo": "test",
            "revision": null,
            "scope": "Read"
        }))
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), 200);
    let json: serde_json::Value = resp.json().await.unwrap();
    assert!(!json["href"].as_str().unwrap().is_empty());
    assert!(
        !json["header"]["X-Xet-Access-Token"]
            .as_str()
            .unwrap()
            .is_empty()
    );
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_provider_xet_read_token() {
    let mut builder = TestServerBuilder::new(&[ServerFrontend::Xet]).with_provider();
    let server = builder.start().await;
    let client = reqwest::Client::new();

    let resp = client
        .get(server.url("/api/generic/test/test/xet-read-token/main?subject=test-user"))
        .header("x-shardline-provider-key", "test-api-key")
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), 200);
    let json: serde_json::Value = resp.json().await.unwrap();
    assert!(!json["accessToken"].as_str().unwrap().is_empty());
    assert!(!json["casUrl"].as_str().unwrap().is_empty());
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_provider_xet_write_token() {
    let mut builder = TestServerBuilder::new(&[ServerFrontend::Xet]).with_provider();
    let server = builder.start().await;
    let client = reqwest::Client::new();

    let resp = client
        .get(server.url("/api/generic/test/test/xet-write-token/main?subject=test-user"))
        .header("x-shardline-provider-key", "test-api-key")
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), 200);
    let json: serde_json::Value = resp.json().await.unwrap();
    assert!(!json["accessToken"].as_str().unwrap().is_empty());
    assert!(!json["casUrl"].as_str().unwrap().is_empty());
}

// ===========================================================================
// 18. Role-split tests (OCI)
// ===========================================================================

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_oci_role_api_serves_manifest_but_not_blob_upload() {
    let pg_url = ensure_pg().await;
    let tmp = TempDir::new().unwrap();
    let chunk_size = NonZeroUsize::new(65536).unwrap();
    let config = ServerConfig::new(
        "127.0.0.1:0".parse().unwrap(),
        "http://127.0.0.1:8080".to_owned(),
        tmp.path().to_path_buf(),
        chunk_size,
    )
    .with_server_role(ServerRole::Api)
    .with_server_frontends([ServerFrontend::Oci])
    .unwrap()
    .with_token_signing_key(TEST_SIGNING_KEY.to_vec())
    .unwrap()
    .with_index_postgres_url(pg_url.to_owned())
    .unwrap()
    .with_reconstruction_cache_disabled();
    config.validate_runtime_requirements().unwrap();
    let app = app::router(config).await.unwrap();

    let token = {
        let provider = LocalHmacProvider::new(TEST_SIGNING_KEY).unwrap();
        let repo_s =
            RepositoryScope::new(RepositoryProvider::Generic, "test", "test", Some("main"))
                .unwrap();
        let claims =
            TokenClaims::new("shardline", "test", TokenScope::Write, repo_s, u64::MAX).unwrap();
        provider.mint_token(&claims).unwrap()
    };

    let repo = "test/test";
    let content = b"role-api-blob";
    let digest = sha256_hex(content);

    // Manifest endpoint should work (served by API role)
    let req = axum::http::Request::builder()
        .method("GET")
        .uri(&format!("/v2/{repo}/manifests/nonexistent"))
        .header("Authorization", format!("Bearer {token}"))
        .body(axum::body::Body::empty())
        .unwrap();
    let resp = app.clone().oneshot(req).await.unwrap();
    // 404 because manifest doesn't exist — but the route should be accessible
    assert!(
        resp.status() == 404,
        "API role should route manifest GET, got {}",
        resp.status()
    );

    // Blob upload POST should return 404 (not served by API role)
    let req = axum::http::Request::builder()
        .method("POST")
        .uri(&format!("/v2/{repo}/blobs/uploads/?digest=sha256:{digest}"))
        .header("Authorization", format!("Bearer {token}"))
        .header("Content-Type", "application/octet-stream")
        .body(axum::body::Body::from(content.to_vec()))
        .unwrap();
    let resp = app.clone().oneshot(req).await.unwrap();
    assert_eq!(
        resp.status(),
        404,
        "API role should NOT serve blob upload, got {}",
        resp.status()
    );
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_oci_role_transfer_serves_blob_upload_but_not_manifest() {
    let pg_url = ensure_pg().await;
    let tmp = TempDir::new().unwrap();
    let chunk_size = NonZeroUsize::new(65536).unwrap();
    let config = ServerConfig::new(
        "127.0.0.1:0".parse().unwrap(),
        "http://127.0.0.1:8080".to_owned(),
        tmp.path().to_path_buf(),
        chunk_size,
    )
    .with_server_role(ServerRole::Transfer)
    .with_server_frontends([ServerFrontend::Oci])
    .unwrap()
    .with_token_signing_key(TEST_SIGNING_KEY.to_vec())
    .unwrap()
    .with_index_postgres_url(pg_url.to_owned())
    .unwrap()
    .with_reconstruction_cache_disabled();
    config.validate_runtime_requirements().unwrap();
    let app = app::router(config).await.unwrap();

    let token = {
        let provider = LocalHmacProvider::new(TEST_SIGNING_KEY).unwrap();
        let repo_s =
            RepositoryScope::new(RepositoryProvider::Generic, "test", "test", Some("main"))
                .unwrap();
        let claims =
            TokenClaims::new("shardline", "test", TokenScope::Write, repo_s, u64::MAX).unwrap();
        provider.mint_token(&claims).unwrap()
    };

    let repo = "test/test";
    let content = b"role-transfer-blob";
    let digest = sha256_hex(content);

    // Blob upload POST should work (served by transfer role)
    let req = axum::http::Request::builder()
        .method("POST")
        .uri(&format!("/v2/{repo}/blobs/uploads/?digest=sha256:{digest}"))
        .header("Authorization", format!("Bearer {token}"))
        .header("Content-Type", "application/octet-stream")
        .body(axum::body::Body::from(content.to_vec()))
        .unwrap();
    let resp = app.clone().oneshot(req).await.unwrap();
    assert_eq!(
        resp.status(),
        201,
        "Transfer role should serve blob upload, got {}",
        resp.status()
    );

    // Manifest GET should return 404 (not served by transfer role)
    let req = axum::http::Request::builder()
        .method("GET")
        .uri(&format!("/v2/{repo}/manifests/nonexistent"))
        .header("Authorization", format!("Bearer {token}"))
        .body(axum::body::Body::empty())
        .unwrap();
    let resp = app.clone().oneshot(req).await.unwrap();
    assert_eq!(
        resp.status(),
        404,
        "Transfer role should NOT serve manifest GET, got {}",
        resp.status()
    );
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_oci_role_all_serves_both() {
    let pg_url = ensure_pg().await;
    let tmp = TempDir::new().unwrap();
    let chunk_size = NonZeroUsize::new(65536).unwrap();
    let config = ServerConfig::new(
        "127.0.0.1:0".parse().unwrap(),
        "http://127.0.0.1:8080".to_owned(),
        tmp.path().to_path_buf(),
        chunk_size,
    )
    .with_server_role(ServerRole::All)
    .with_server_frontends([ServerFrontend::Oci])
    .unwrap()
    .with_token_signing_key(TEST_SIGNING_KEY.to_vec())
    .unwrap()
    .with_index_postgres_url(pg_url.to_owned())
    .unwrap()
    .with_reconstruction_cache_disabled();
    config.validate_runtime_requirements().unwrap();
    let app = app::router(config).await.unwrap();

    let token = {
        let provider = LocalHmacProvider::new(TEST_SIGNING_KEY).unwrap();
        let repo_s =
            RepositoryScope::new(RepositoryProvider::Generic, "test", "test", Some("main"))
                .unwrap();
        let claims =
            TokenClaims::new("shardline", "test", TokenScope::Write, repo_s, u64::MAX).unwrap();
        provider.mint_token(&claims).unwrap()
    };

    let repo = "test/test";
    let content = b"role-all-blob";
    let digest = sha256_hex(content);

    // Blob upload should work
    let req = axum::http::Request::builder()
        .method("POST")
        .uri(&format!("/v2/{repo}/blobs/uploads/?digest=sha256:{digest}"))
        .header("Authorization", format!("Bearer {token}"))
        .header("Content-Type", "application/octet-stream")
        .body(axum::body::Body::from(content.to_vec()))
        .unwrap();
    let resp = app.clone().oneshot(req).await.unwrap();
    assert_eq!(
        resp.status(),
        201,
        "All role should serve blob upload, got {}",
        resp.status()
    );

    // Manifest GET should also be routable (return 404 because not found)
    let req = axum::http::Request::builder()
        .method("GET")
        .uri(&format!("/v2/{repo}/manifests/nonexistent"))
        .header("Authorization", format!("Bearer {token}"))
        .body(axum::body::Body::empty())
        .unwrap();
    let resp = app.clone().oneshot(req).await.unwrap();
    assert_eq!(
        resp.status(),
        404,
        "All role should route manifest GET, got {}",
        resp.status()
    );
}

// ===========================================================================
// 23. Reconstruction cache enabled — cold miss then hot hit
// ===========================================================================

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_reconstruction_cache_hit() {
    // Build app with reconstruction cache ENABLED (default is memory).
    let pg_url = ensure_pg().await;
    let tmp = TempDir::new().unwrap();
    let chunk_size = NonZeroUsize::new(65536).unwrap();
    let config = ServerConfig::new(
        "127.0.0.1:0".parse().unwrap(),
        "http://127.0.0.1:8080".to_owned(),
        tmp.path().to_path_buf(),
        chunk_size,
    )
    .with_server_role(ServerRole::All)
    .with_server_frontends([ServerFrontend::Lfs])
    .unwrap()
    .with_token_signing_key(TEST_SIGNING_KEY.to_vec())
    .unwrap()
    .with_index_postgres_url(pg_url.to_owned())
    .unwrap();
    // NOTE: No .with_reconstruction_cache_disabled() — default is memory cache.

    config.validate_runtime_requirements().unwrap();
    let app = app::router(config).await.unwrap();

    let provider = LocalHmacProvider::new(TEST_SIGNING_KEY).unwrap();
    let repo =
        RepositoryScope::new(RepositoryProvider::Generic, "test", "test", Some("main")).unwrap();
    let claims = TokenClaims::new("shardline", "test", TokenScope::Write, repo, u64::MAX).unwrap();
    let token = provider.mint_token(&claims).unwrap();

    let content = b"reconstruction-cache-hit-test";
    let oid = sha256_hex(content);

    // Upload via LFS.
    let put_req = axum::http::Request::builder()
        .method("PUT")
        .uri(&format!("/v1/lfs/objects/{oid}"))
        .header("Authorization", format!("Bearer {token}"))
        .header("Content-Type", "application/octet-stream")
        .body(axum::body::Body::from(content.to_vec()))
        .unwrap();
    let put_resp = app.clone().oneshot(put_req).await.unwrap();
    assert!(
        put_resp.status().is_success(),
        "LFS PUT failed: {}",
        put_resp.status()
    );

    // Read twice — cold miss then hot hit. Both should succeed.
    for i in 0..2 {
        let get_req = axum::http::Request::builder()
            .method("GET")
            .uri(&format!("/v1/lfs/objects/{oid}"))
            .header("Authorization", format!("Bearer {token}"))
            .body(axum::body::Body::empty())
            .unwrap();
        let get_resp = app.clone().oneshot(get_req).await.unwrap();
        assert_eq!(
            get_resp.status(),
            200,
            "GET iteration {i} failed with status {}",
            get_resp.status()
        );
        let body = axum::body::to_bytes(get_resp.into_body(), usize::MAX)
            .await
            .unwrap();
        assert_eq!(body.as_ref(), content, "GET iteration {i} body mismatch");
    }

    // Also verify /readyz reports the cache backend as "memory".
    let ready_req = axum::http::Request::builder()
        .uri("/readyz")
        .body(axum::body::Body::empty())
        .unwrap();
    let ready_resp = app.oneshot(ready_req).await.unwrap();
    assert_eq!(ready_resp.status(), 200);
    let ready_json: serde_json::Value = serde_json::from_slice(
        &axum::body::to_bytes(ready_resp.into_body(), usize::MAX)
            .await
            .unwrap(),
    )
    .unwrap();
    assert_eq!(
        ready_json["cache_backend"], "memory",
        "readyz should report memory cache backend"
    );
}

// ===========================================================================
// 24. 409 Conflict — duplicate Hub repo creation
// ===========================================================================

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_hub_create_same_repo_twice_returns_409() {
    let server = TestServer::start(&[ServerFrontend::Hub]).await;
    let client = reqwest::Client::new();
    let auth = || format!("Bearer {}", server.auth_header());

    let ns = "pg-conflict-team";
    let name = "pg-conflict-model";
    let model_path = format!("{ns}/{name}");

    // First create — should succeed.
    let create1 = client
        .post(server.url("/api/repos/create"))
        .header("Authorization", auth())
        .header("Content-Type", "application/json")
        .json(&serde_json::json!({"type": "model", "name": &model_path, "private": false}))
        .send()
        .await
        .unwrap();
    assert_eq!(create1.status(), 201);

    // Second create (same repo) — should return 409 Conflict.
    let create2 = client
        .post(server.url("/api/repos/create"))
        .header("Authorization", auth())
        .header("Content-Type", "application/json")
        .json(&serde_json::json!({"type": "model", "name": &model_path, "private": false}))
        .send()
        .await
        .unwrap();
    assert_eq!(
        create2.status(),
        409,
        "duplicate repo creation should return 409"
    );
}

// ===========================================================================
// 25. Wrong-repo auth scope — 403 Forbidden
// ===========================================================================

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_auth_wrong_repo_scope_returns_403() {
    // Build an OCI app (OCI validates repository scope against the token).
    let pg_url = ensure_pg().await;
    let tmp = TempDir::new().unwrap();
    let chunk_size = NonZeroUsize::new(65536).unwrap();
    let config = ServerConfig::new(
        "127.0.0.1:0".parse().unwrap(),
        "http://127.0.0.1:8080".to_owned(),
        tmp.path().to_path_buf(),
        chunk_size,
    )
    .with_server_role(ServerRole::All)
    .with_server_frontends([ServerFrontend::Oci])
    .unwrap()
    .with_token_signing_key(TEST_SIGNING_KEY.to_vec())
    .unwrap()
    .with_index_postgres_url(pg_url.to_owned())
    .unwrap()
    .with_reconstruction_cache_disabled();
    config.validate_runtime_requirements().unwrap();
    let app = app::router(config).await.unwrap();

    // Mint a token scoped to a different repo (other/other), not test/test.
    let provider = LocalHmacProvider::new(TEST_SIGNING_KEY).unwrap();
    let other_repo =
        RepositoryScope::new(RepositoryProvider::Generic, "other", "other", Some("main")).unwrap();
    let claims = TokenClaims::new(
        "shardline",
        "other",
        TokenScope::Write,
        other_repo,
        u64::MAX,
    )
    .unwrap();
    let wrong_token = provider.mint_token(&claims).unwrap();

    // Try POST blob upload to test/test with wrong-scoped token.
    // OCI blob upload validates repository scope against the token.
    // The OCI spec prefers 404 over 403 to avoid leaking repository existence.
    let content = b"wrong-scope-content";
    let digest = sha256_hex(content);
    let post_req = axum::http::Request::builder()
        .method("POST")
        .uri(&format!(
            "/v2/test/test/blobs/uploads/?digest=sha256:{digest}"
        ))
        .header("Authorization", format!("Bearer {wrong_token}"))
        .header("Content-Type", "application/octet-stream")
        .body(axum::body::Body::from(content.to_vec()))
        .unwrap();
    let post_resp = app.clone().oneshot(post_req).await.unwrap();

    // Token is scoped to other/other, not test/test → should fail auth/scope check.
    // The exact status depends on implementation: 403 (forbidden) or 404 (not found).
    assert!(
        post_resp.status() == 403 || post_resp.status() == 404,
        "wrong-repo-scope token should get 403 or 404, got {}",
        post_resp.status()
    );
}

// ===========================================================================
// 19. More OCI error paths
// ===========================================================================

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_oci_upload_invalid_digest_algorithm() {
    let (app, token) = oci_oneshot_app().await;
    let repo = "test/test";
    let content = b"some-content";

    // Use sha512 (unsupported) as the digest algorithm
    let req = axum::http::Request::builder()
        .method("POST")
        .uri(&format!(
            "/v2/{repo}/blobs/uploads/?digest=sha512:{}",
            sha256_hex(content)
        ))
        .header("Authorization", format!("Bearer {token}"))
        .header("Content-Type", "application/octet-stream")
        .body(axum::body::Body::from(content.to_vec()))
        .unwrap();
    let resp = app.clone().oneshot(req).await.unwrap();
    assert_eq!(
        resp.status(),
        400,
        "invalid digest algorithm should return 400, got {}",
        resp.status()
    );
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_oci_upload_body_hash_mismatch() {
    let (app, token) = oci_oneshot_app().await;
    let repo = "test/test";

    // Content does not match the digest
    let content = b"actual-content";
    let wrong_digest = sha256_hex(b"different-content");

    let req = axum::http::Request::builder()
        .method("POST")
        .uri(&format!(
            "/v2/{repo}/blobs/uploads/?digest=sha256:{wrong_digest}"
        ))
        .header("Authorization", format!("Bearer {token}"))
        .header("Content-Type", "application/octet-stream")
        .body(axum::body::Body::from(content.to_vec()))
        .unwrap();
    let resp = app.clone().oneshot(req).await.unwrap();
    assert_eq!(
        resp.status(),
        400,
        "body hash mismatch should return 400, got {}",
        resp.status()
    );
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_oci_patch_nonexistent_session() {
    let (app, token) = oci_oneshot_app().await;
    let repo = "test/test";

    let req = axum::http::Request::builder()
        .method("PATCH")
        .uri(&format!(
            "/v2/{repo}/blobs/uploads/00000000-0000-0000-0000-000000000000"
        ))
        .header("Authorization", format!("Bearer {token}"))
        .header("Content-Type", "application/octet-stream")
        .header("Content-Range", "0-63/64")
        .body(axum::body::Body::from(b"data".to_vec()))
        .unwrap();
    let resp = app.clone().oneshot(req).await.unwrap();
    let status = resp.status();
    let body_bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
        .await
        .unwrap();
    let body_str = String::from_utf8_lossy(&body_bytes);
    assert_eq!(
        status, 404,
        "PATCH non-existent session: status={} body={}",
        status, body_str
    );
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_oci_put_finalize_without_digest() {
    let (app, token) = oci_oneshot_app().await;
    let repo = "test/test";

    // PUT to blob uploads without ?digest= query parameter
    let req = axum::http::Request::builder()
        .method("PUT")
        .uri(&format!(
            "/v2/{repo}/blobs/uploads/00000000-0000-0000-0000-000000000000"
        ))
        .header("Authorization", format!("Bearer {token}"))
        .body(axum::body::Body::empty())
        .unwrap();
    let resp = app.clone().oneshot(req).await.unwrap();
    assert_eq!(
        resp.status(),
        400,
        "PUT without digest should return 400, got {}",
        resp.status()
    );
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_oci_get_nonexistent_blob() {
    let (app, token) = oci_oneshot_app().await;
    let repo = "test/test";
    let fake_digest = "a".repeat(64);

    let req = axum::http::Request::builder()
        .method("GET")
        .uri(&format!("/v2/{repo}/blobs/sha256:{fake_digest}"))
        .header("Authorization", format!("Bearer {token}"))
        .body(axum::body::Body::empty())
        .unwrap();
    let resp = app.clone().oneshot(req).await.unwrap();
    assert_eq!(
        resp.status(),
        404,
        "GET non-existent blob should return 404, got {}",
        resp.status()
    );
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_oci_delete_nonexistent_manifest() {
    let (app, token) = oci_oneshot_app().await;
    let repo = "test/test";

    let req = axum::http::Request::builder()
        .method("DELETE")
        .uri(&format!("/v2/{repo}/manifests/nonexistent-tag"))
        .header("Authorization", format!("Bearer {token}"))
        .body(axum::body::Body::empty())
        .unwrap();
    let resp = app.clone().oneshot(req).await.unwrap();
    assert_eq!(
        resp.status(),
        404,
        "DELETE non-existent manifest should return 404, got {}",
        resp.status()
    );
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_oci_push_manifest_with_nonexistent_blob() {
    let (app, token) = oci_oneshot_app().await;
    let repo = "test/test";

    let manifest_body = serde_json::json!({
        "schemaVersion": 2,
        "mediaType": "application/vnd.oci.image.manifest.v1+json",
        "config": {
            "mediaType": "application/vnd.oci.image.config.v1+json",
            "size": 0,
            "digest": "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
        },
        "layers": [
            {
                "mediaType": "application/vnd.oci.image.layer.v1.tar+gzip",
                "size": 0,
                "digest": "sha256:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"
            }
        ]
    })
    .to_string();

    let req = axum::http::Request::builder()
        .method("PUT")
        .uri(&format!("/v2/{repo}/manifests/nonexistent-blob-ref"))
        .header("Authorization", format!("Bearer {token}"))
        .header("Content-Type", "application/vnd.oci.image.manifest.v1+json")
        .body(axum::body::Body::from(manifest_body))
        .unwrap();
    let resp = app.clone().oneshot(req).await.unwrap();
    assert_eq!(
        resp.status(),
        400,
        "manifest referencing non-existent blob should return 400, got {}",
        resp.status()
    );
}

// ===========================================================================
// 20. More LFS edge cases
// ===========================================================================

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_lfs_verify_object() {
    let server = TestServer::start(&[ServerFrontend::Lfs]).await;
    let client = reqwest::Client::new();

    let content = b"verify-me-content";
    let oid = sha256_hex(content);

    // Upload
    client
        .put(server.url(&format!("/v1/lfs/objects/{oid}")))
        .header("Authorization", format!("Bearer {}", server.auth_header()))
        .header("Content-Type", "application/octet-stream")
        .body(content.to_vec())
        .send()
        .await
        .unwrap();

    // Verify
    let verify_resp = client
        .post(server.url(&format!("/v1/lfs/objects/{oid}/verify")))
        .header("Authorization", format!("Bearer {}", server.auth_header()))
        .send()
        .await
        .unwrap();
    assert_eq!(
        verify_resp.status(),
        200,
        "verify existing object should return 200, got {}",
        verify_resp.status()
    );
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_lfs_verify_nonexistent_object() {
    let server = TestServer::start(&[ServerFrontend::Lfs]).await;
    let client = reqwest::Client::new();

    let fake_oid = "f".repeat(64);

    let verify_resp = client
        .post(server.url(&format!("/v1/lfs/objects/{fake_oid}/verify")))
        .header("Authorization", format!("Bearer {}", server.auth_header()))
        .send()
        .await
        .unwrap();
    assert_eq!(
        verify_resp.status(),
        404,
        "verify non-existent should return 404, got {}",
        verify_resp.status()
    );
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_lfs_batch_mixed_existing_missing() {
    let server = TestServer::start(&[ServerFrontend::Lfs]).await;
    let client = reqwest::Client::new();

    let existing_content = b"existing-batch-content";
    let existing_oid = sha256_hex(existing_content);

    // Upload existing object
    client
        .put(server.url(&format!("/v1/lfs/objects/{existing_oid}")))
        .header("Authorization", format!("Bearer {}", server.auth_header()))
        .header("Content-Type", "application/octet-stream")
        .body(existing_content.to_vec())
        .send()
        .await
        .unwrap();

    let missing_oid = "c".repeat(64);

    // Batch with mixed
    let batch_req = serde_json::json!({
        "operation": "download",
        "objects": [
            {"oid": existing_oid, "size": existing_content.len() as u64},
            {"oid": missing_oid, "size": 42}
        ]
    });
    let batch_resp = client
        .post(server.url("/v1/lfs/objects/batch"))
        .header("Authorization", format!("Bearer {}", server.auth_header()))
        .header("Content-Type", "application/vnd.git-lfs+json")
        .json(&batch_req)
        .send()
        .await
        .unwrap();
    assert_eq!(batch_resp.status(), 200);
    let json: serde_json::Value = batch_resp.json().await.unwrap();
    let objects = json["objects"].as_array().unwrap();
    assert_eq!(objects.len(), 2);
    // Existing object should not have error
    assert!(
        objects[0].get("error").is_none() || objects[0]["error"].is_null(),
        "existing object should have no error: {:?}",
        objects[0]
    );
    // Missing object should have error
    assert!(
        objects[1].get("error").is_some(),
        "missing object should have error: {:?}",
        objects[1]
    );
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_lfs_upload_empty_file() {
    let server = TestServer::start(&[ServerFrontend::Lfs]).await;
    let client = reqwest::Client::new();

    let content = b"";
    let oid = sha256_hex(content);

    let put_resp = client
        .put(server.url(&format!("/v1/lfs/objects/{oid}")))
        .header("Authorization", format!("Bearer {}", server.auth_header()))
        .header("Content-Type", "application/octet-stream")
        .body(content.to_vec())
        .send()
        .await
        .unwrap();
    assert!(
        put_resp.status().is_success(),
        "empty file upload should succeed"
    );

    let get_resp = client
        .get(server.url(&format!("/v1/lfs/objects/{oid}")))
        .header("Authorization", format!("Bearer {}", server.auth_header()))
        .send()
        .await
        .unwrap();
    assert_eq!(get_resp.status(), 200);
    let body = get_resp.bytes().await.unwrap();
    assert_eq!(body.as_ref(), content);
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_lfs_batch_with_large_size() {
    let server = TestServer::start(&[ServerFrontend::Lfs]).await;
    let client = reqwest::Client::new();

    let content = b"large-header-content";
    let oid = sha256_hex(content);

    // Upload first
    client
        .put(server.url(&format!("/v1/lfs/objects/{oid}")))
        .header("Authorization", format!("Bearer {}", server.auth_header()))
        .header("Content-Type", "application/octet-stream")
        .body(content.to_vec())
        .send()
        .await
        .unwrap();

    // Batch with 100MB size declared
    let batch_req = serde_json::json!({
        "operation": "download",
        "objects": [{"oid": oid, "size": 100_000_000}]
    });
    let batch_resp = client
        .post(server.url("/v1/lfs/objects/batch"))
        .header("Authorization", format!("Bearer {}", server.auth_header()))
        .header("Content-Type", "application/vnd.git-lfs+json")
        .json(&batch_req)
        .send()
        .await
        .unwrap();
    assert_eq!(batch_resp.status(), 200);
}

// ===========================================================================
// 21. More Hub API routes (postgres only)
// ===========================================================================

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_hub_create_dataset_repo() {
    let server = TestServer::start(&[ServerFrontend::Hub]).await;
    let client = reqwest::Client::new();
    let auth = || format!("Bearer {}", server.auth_header());

    let ns = "ds-team";
    let name = "ds-repo";
    let ds_path = format!("{ns}/{name}");

    let create_resp = client
        .post(server.url("/api/repos/create"))
        .header("Authorization", auth())
        .header("Content-Type", "application/json")
        .json(&serde_json::json!({
            "type": "dataset",
            "name": &ds_path,
            "private": false,
        }))
        .send()
        .await
        .unwrap();
    assert_eq!(create_resp.status(), 201);

    let info_resp = client
        .get(server.url(&format!("/api/datasets/{ns}/{name}")))
        .header("Authorization", auth())
        .send()
        .await
        .unwrap();
    assert_eq!(info_resp.status(), 200);
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_hub_create_space_repo() {
    let server = TestServer::start(&[ServerFrontend::Hub]).await;
    let client = reqwest::Client::new();
    let auth = || format!("Bearer {}", server.auth_header());

    let ns = "space-team";
    let name = "space-app";
    let sp_path = format!("{ns}/{name}");

    let create_resp = client
        .post(server.url("/api/repos/create"))
        .header("Authorization", auth())
        .header("Content-Type", "application/json")
        .json(&serde_json::json!({
            "type": "space",
            "name": &sp_path,
            "private": false,
        }))
        .send()
        .await
        .unwrap();
    assert_eq!(create_resp.status(), 201);

    let info_resp = client
        .get(server.url(&format!("/api/spaces/{ns}/{name}")))
        .header("Authorization", auth())
        .send()
        .await
        .unwrap();
    assert_eq!(info_resp.status(), 200);
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_hub_revisions_list_json_array() {
    let server = TestServer::start(&[ServerFrontend::Hub]).await;
    let client = reqwest::Client::new();
    let auth = || format!("Bearer {}", server.auth_header());

    let ns = "rev-team";
    let name = "rev-model";
    let path = format!("{ns}/{name}");

    // Create repo
    client
        .post(server.url("/api/repos/create"))
        .header("Authorization", auth())
        .header("Content-Type", "application/json")
        .json(&serde_json::json!({"type": "model", "name": &path, "private": false}))
        .send()
        .await
        .unwrap();

    // Commit a file
    let content_b64 = base64::Engine::encode(
        &base64::engine::general_purpose::STANDARD,
        b"rev-test-content",
    );
    let ndjson = format!(
        "{{\"header\":{{\"message\":\"rev commit\",\"parentCommit\":\"\"}}}}\n\
         {{\"file\":{{\"path\":\"test.txt\",\"content\":\"{content_b64}\"}}}}"
    );
    let commit_resp = client
        .post(server.url(&format!("/api/models/{ns}/{name}/commit/main")))
        .header("Authorization", auth())
        .header("Content-Type", "application/x-ndjson")
        .body(ndjson)
        .send()
        .await
        .unwrap();
    assert_eq!(commit_resp.status(), 200);

    // Get revisions list — verify it returns a JSON object with "revisions" key
    let rev_resp = client
        .get(server.url(&format!("/api/models/{ns}/{name}/revisions")))
        .header("Authorization", auth())
        .send()
        .await
        .unwrap();
    assert_eq!(rev_resp.status(), 200);
    let rev_json: serde_json::Value = rev_resp.json().await.unwrap();
    // Revisions should be in a "revisions" array
    assert!(
        rev_json.get("revisions").is_some(),
        "revisions response should have 'revisions' key: {rev_json}"
    );
    let revisions = rev_json["revisions"].as_array().unwrap();
    assert!(!revisions.is_empty(), "should have at least one revision");
}

// ===========================================================================
// 22. More Bazel edge cases
// ===========================================================================

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_bazel_ac_put_and_get() {
    let server = TestServer::start(&[ServerFrontend::BazelHttp]).await;
    let client = reqwest::Client::new();

    let content = b"action-cache-content";
    let hash = sha256_hex(content);

    // PUT AC
    let put_resp = client
        .put(server.url(&format!("/v1/bazel/cache/ac/{hash}")))
        .header("Authorization", format!("Bearer {}", server.auth_header()))
        .header("Content-Type", "application/octet-stream")
        .body(content.to_vec())
        .send()
        .await
        .unwrap();
    assert!(
        put_resp.status().is_success(),
        "AC PUT failed: {}",
        put_resp.status()
    );

    // GET AC
    let get_resp = client
        .get(server.url(&format!("/v1/bazel/cache/ac/{hash}")))
        .header("Authorization", format!("Bearer {}", server.auth_header()))
        .send()
        .await
        .unwrap();
    assert_eq!(get_resp.status(), 200);
    let body = get_resp.bytes().await.unwrap();
    assert_eq!(body.as_ref(), content);
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_bazel_head_existing() {
    let server = TestServer::start(&[ServerFrontend::BazelHttp]).await;
    let client = reqwest::Client::new();

    let content = b"head-test-content";
    let hash = sha256_hex(content);

    // Upload first
    client
        .put(server.url(&format!("/v1/bazel/cache/cas/{hash}")))
        .header("Authorization", format!("Bearer {}", server.auth_header()))
        .header("Content-Type", "application/octet-stream")
        .body(content.to_vec())
        .send()
        .await
        .unwrap();

    // HEAD existing
    let head_resp = client
        .head(server.url(&format!("/v1/bazel/cache/cas/{hash}")))
        .header("Authorization", format!("Bearer {}", server.auth_header()))
        .send()
        .await
        .unwrap();
    assert_eq!(head_resp.status(), 200);
    let cl: u64 = head_resp
        .headers()
        .get("content-length")
        .and_then(|v| v.to_str().ok())
        .and_then(|s| s.parse().ok())
        .unwrap_or(0);
    assert_eq!(cl, content.len() as u64);
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_bazel_head_nonexistent() {
    let server = TestServer::start(&[ServerFrontend::BazelHttp]).await;
    let client = reqwest::Client::new();

    let fake_hash = "f".repeat(64);

    let head_resp = client
        .head(server.url(&format!("/v1/bazel/cache/cas/{fake_hash}")))
        .header("Authorization", format!("Bearer {}", server.auth_header()))
        .send()
        .await
        .unwrap();
    assert_eq!(
        head_resp.status(),
        404,
        "HEAD non-existent should return 404, got {}",
        head_resp.status()
    );
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_bazel_cas_content_hash_mismatch() {
    let server = TestServer::start(&[ServerFrontend::BazelHttp]).await;
    let client = reqwest::Client::new();

    let content = b"actual-body-data";
    let wrong_hash = sha256_hex(b"different-body");

    let put_resp = client
        .put(server.url(&format!("/v1/bazel/cache/cas/{wrong_hash}")))
        .header("Authorization", format!("Bearer {}", server.auth_header()))
        .header("Content-Type", "application/octet-stream")
        .body(content.to_vec())
        .send()
        .await
        .unwrap();
    assert_eq!(
        put_resp.status(),
        400,
        "content hash mismatch should return 400, got {}",
        put_resp.status()
    );
}

// ===========================================================================
// 13. Hub API routes beyond whoami
// ===========================================================================

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_hub_create_repo_and_commit() {
    let server = TestServer::start(&[ServerFrontend::Hub]).await;
    let client = reqwest::Client::new();
    let auth = || format!("Bearer {}", server.auth_header());

    let ns = "e2e-team";
    let name = "e2e-model";
    let model_path = format!("{ns}/{name}");

    // Create a model repo
    let create_resp = client
        .post(server.url("/api/repos/create"))
        .header("Authorization", auth())
        .header("Content-Type", "application/json")
        .json(&serde_json::json!({
            "type": "model",
            "name": &model_path,
            "private": false,
        }))
        .send()
        .await
        .unwrap();
    assert_eq!(create_resp.status(), 201);

    // Get repo info
    let info_resp = client
        .get(server.url(&format!("/api/models/{ns}/{name}")))
        .header("Authorization", auth())
        .send()
        .await
        .unwrap();
    assert_eq!(info_resp.status(), 200);
    let info_json: serde_json::Value = info_resp.json().await.unwrap();
    assert_eq!(info_json["id"], model_path);
    assert_eq!(info_json["type"], "model");

    // Commit a file using NDJSON
    let content_b64 = base64::Engine::encode(
        &base64::engine::general_purpose::STANDARD,
        b"Hello from e2e test!",
    );
    let ndjson = format!(
        "{{\"header\":{{\"message\":\"e2e commit\",\"parentCommit\":\"\"}}}}\n\
         {{\"file\":{{\"path\":\"hello.txt\",\"content\":\"{content_b64}\"}}}}"
    );
    let commit_resp = client
        .post(server.url(&format!("/api/models/{ns}/{name}/commit/main")))
        .header("Authorization", auth())
        .header("Content-Type", "application/x-ndjson")
        .body(ndjson)
        .send()
        .await
        .unwrap();
    assert_eq!(commit_resp.status(), 200);
    let commit_json: serde_json::Value = commit_resp.json().await.unwrap();
    assert!(
        commit_json
            .get("commitId")
            .and_then(|v| v.as_str())
            .is_some()
            || commit_json
                .get("commit_id")
                .and_then(|v| v.as_str())
                .is_some(),
        "commit response should contain commit_id: {commit_json}"
    );

    // Verify the commit created a new revision
    let rev_resp = client
        .get(server.url(&format!("/api/models/{ns}/{name}/revisions")))
        .header("Authorization", auth())
        .send()
        .await
        .unwrap();
    assert_eq!(rev_resp.status(), 200);
    let rev_json: serde_json::Value = rev_resp.json().await.unwrap();
    let revisions = rev_json["revisions"]
        .as_array()
        .unwrap_or(&rev_json.as_array().cloned().unwrap_or_default())
        .clone();
    // Should have at least one revision after the commit
    assert!(
        !revisions.is_empty(),
        "should have at least one revision after commit"
    );
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_hub_upload_lfs_and_batch() {
    let server = TestServer::start(&[ServerFrontend::Hub]).await;
    let client = reqwest::Client::new();
    let auth = || format!("Bearer {}", server.auth_header());

    let content = b"hub-lfs-e2e-content";
    let oid = sha256_hex(content);

    // Upload via Hub LFS route (not /v1/lfs — Hub has its own /lfs/objects/{oid})
    let put_resp = client
        .put(server.url(&format!("/lfs/objects/{oid}")))
        .header("Authorization", auth())
        .header("Content-Type", "application/octet-stream")
        .body(content.to_vec())
        .send()
        .await
        .unwrap();
    assert_eq!(put_resp.status(), 200);

    // Download back
    let get_resp = client
        .get(server.url(&format!("/lfs/objects/{oid}")))
        .header("Authorization", auth())
        .send()
        .await
        .unwrap();
    assert_eq!(get_resp.status(), 200);
    let body = get_resp.bytes().await.unwrap();
    assert_eq!(body.as_ref(), content);
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_hub_modelcard() {
    let server = TestServer::start(&[ServerFrontend::Hub]).await;
    let client = reqwest::Client::new();
    let auth = || format!("Bearer {}", server.auth_header());

    let ns = "card-team";
    let name = "card-model";
    let model_path = format!("{ns}/{name}");

    // Create a model repo
    let create_resp = client
        .post(server.url("/api/repos/create"))
        .header("Authorization", auth())
        .header("Content-Type", "application/json")
        .json(&serde_json::json!({
            "type": "model",
            "name": &model_path,
            "private": false,
        }))
        .send()
        .await
        .unwrap();
    assert_eq!(create_resp.status(), 201);

    // Before committing, modelcard should 404
    let card_resp = client
        .get(server.url(&format!("/api/models/{ns}/{name}/modelcard")))
        .header("Authorization", auth())
        .send()
        .await
        .unwrap();
    assert_eq!(card_resp.status(), 404);

    // Commit a README.md
    let readme_b64 = base64::Engine::encode(
        &base64::engine::general_purpose::STANDARD,
        b"# Model Card\n\nThis is a test model.",
    );
    let ndjson = format!(
        "{{\"header\":{{\"message\":\"add readme\",\"parentCommit\":\"\"}}}}\n\
         {{\"file\":{{\"path\":\"README.md\",\"content\":\"{readme_b64}\"}}}}"
    );
    let commit_resp = client
        .post(server.url(&format!("/api/models/{ns}/{name}/commit/main")))
        .header("Authorization", auth())
        .header("Content-Type", "application/x-ndjson")
        .body(ndjson)
        .send()
        .await
        .unwrap();
    assert_eq!(commit_resp.status(), 200);

    // Now modelcard should return the README
    let card_resp = client
        .get(server.url(&format!("/api/models/{ns}/{name}/modelcard")))
        .header("Authorization", auth())
        .send()
        .await
        .unwrap();
    assert_eq!(card_resp.status(), 200);
}

// ===========================================================================
// 14. Error / edge cases
// ===========================================================================

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_error_no_auth_on_protected_endpoints() {
    let server = TestServer::start(&[ServerFrontend::Lfs]).await;
    let client = reqwest::Client::new();

    // POST /v1/lfs/objects/batch without auth → 401
    let resp = client
        .post(server.url("/v1/lfs/objects/batch"))
        .header("Content-Type", "application/vnd.git-lfs+json")
        .json(&serde_json::json!({"operation":"download","objects":[]}))
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), 401);
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_error_invalid_token() {
    let server = TestServer::start(&[ServerFrontend::Xet]).await;
    let client = reqwest::Client::new();

    let resp = client
        .get(server.url("/v1/stats"))
        .header("Authorization", "Bearer invalid.token.here")
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), 401);
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_error_oci_manifest_not_found() {
    let (app, token) = oci_oneshot_app().await;

    let get_uri = "/v2/test/test/manifests/nonexistent-tag";
    let get_req = axum::http::Request::builder()
        .method("GET")
        .uri(get_uri)
        .header("Authorization", format!("Bearer {token}"))
        .body(axum::body::Body::empty())
        .unwrap();
    let get_resp = app.clone().oneshot(get_req).await.unwrap();
    assert_eq!(get_resp.status(), 404);
    let body = axum::body::to_bytes(get_resp.into_body(), usize::MAX)
        .await
        .unwrap();
    let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
    assert_eq!(json["errors"][0]["code"], "MANIFEST_UNKNOWN");
}

// ===========================================================================
// 15. Metrics after operations
// ===========================================================================

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_metrics_after_lfs_upload() {
    let server = TestServer::start(&[ServerFrontend::Lfs]).await;
    let client = reqwest::Client::new();

    // Check metrics baseline — after upload there should be some transfer counters
    let content = b"metrics-check-content";
    let oid = sha256_hex(content);

    // Upload via LFS
    let put_resp = client
        .put(server.url(&format!("/v1/lfs/objects/{oid}")))
        .header("Authorization", format!("Bearer {}", server.auth_header()))
        .header("Content-Type", "application/octet-stream")
        .body(content.to_vec())
        .send()
        .await
        .unwrap();
    assert!(put_resp.status().is_success());

    // Fetch metrics and verify it contains upload-related labels
    let metrics_resp = client.get(server.url("/metrics")).send().await.unwrap();
    assert_eq!(metrics_resp.status(), 200);
    let body = metrics_resp.text().await.unwrap();
    // The metrics should still have the basic shardline gauges
    assert!(
        body.contains("shardline_up 1"),
        "shardline_up should be present"
    );
}

// ===========================================================================
// 16. Cross-protocol: upload via LFS, read via OCI blob
// ===========================================================================

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_cross_protocol_lfs_to_oci() {
    let server = TestServer::start(&[ServerFrontend::Lfs, ServerFrontend::Oci]).await;
    let client = reqwest::Client::new();

    let content = b"cross-protocol-content";
    let oid = sha256_hex(content);

    // Upload via LFS (v1 API)
    let put_resp = client
        .put(server.url(&format!("/v1/lfs/objects/{oid}")))
        .header("Authorization", format!("Bearer {}", server.auth_header()))
        .header("Content-Type", "application/octet-stream")
        .body(content.to_vec())
        .send()
        .await
        .unwrap();
    assert!(put_resp.status().is_success());

    // Read the same object via a GET request (not OCI — just confirm it's there)
    let get_resp = client
        .get(server.url(&format!("/v1/lfs/objects/{oid}")))
        .header("Authorization", format!("Bearer {}", server.auth_header()))
        .send()
        .await
        .unwrap();
    assert_eq!(get_resp.status(), 200);
    let body = get_resp.bytes().await.unwrap();
    assert_eq!(body.as_ref(), content);
}

// ===========================================================================
// 23. Concurrent HTTP E2E tests
// ===========================================================================

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_concurrent_lfs_upload_same_oid() {
    let server = TestServer::start(&[ServerFrontend::Lfs]).await;
    let content = b"concurrent-same-oid-content-pg";
    let oid = sha256_hex(content);
    let url = server.url(&format!("/v1/lfs/objects/{oid}"));
    let token = server.auth_header().to_owned();

    // 5 concurrent PUTs of the same LFS OID — all should return 200
    let mut handles = Vec::new();
    for _ in 0..5 {
        let url = url.clone();
        let token = token.clone();
        let data = content.to_vec();
        handles.push(tokio::spawn(async move {
            let client = reqwest::Client::new();
            let resp = client
                .put(&url)
                .header("Authorization", format!("Bearer {token}"))
                .header("Content-Type", "application/octet-stream")
                .body(data)
                .send()
                .await
                .unwrap();
            resp.status()
        }));
    }

    for (i, handle) in handles.into_iter().enumerate() {
        let status = handle.await.unwrap();
        assert!(
            status.is_success(),
            "concurrent PUT {} returned {}",
            i,
            status
        );
    }

    // Verify the stored content is correct
    let client = reqwest::Client::new();
    let get_resp = client
        .get(server.url(&format!("/v1/lfs/objects/{oid}")))
        .header("Authorization", format!("Bearer {}", server.auth_header()))
        .send()
        .await
        .unwrap();
    assert_eq!(get_resp.status(), 200);
    assert_eq!(get_resp.bytes().await.unwrap().as_ref(), content);
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_concurrent_oci_manifest_push_and_pull() {
    let (app, token) = oci_oneshot_app().await;
    let repo = "test/test";
    let tag = "concurrent-manifest-pg";

    // Prepare data: upload config and layer blobs
    let config_data = b"{}";
    let layer_data = b"concurrent-layer-pg";
    let config_digest = oci_upload_blob_oneshot(&app, &token, repo, config_data).await;
    let layer_digest = oci_upload_blob_oneshot(&app, &token, repo, layer_data).await;
    let manifest_body = oci_manifest_json(&config_digest, &layer_digest);

    // Push the manifest first
    let put_uri = format!("/v2/{repo}/manifests/{tag}");
    let put_req = axum::http::Request::builder()
        .method("PUT")
        .uri(&put_uri)
        .header("Authorization", format!("Bearer {token}"))
        .header("Content-Type", "application/vnd.oci.image.manifest.v1+json")
        .body(axum::body::Body::from(manifest_body.clone()))
        .unwrap();
    let put_resp = app.clone().oneshot(put_req).await.unwrap();
    assert_eq!(put_resp.status(), 201, "manifest PUT failed");

    // Spawn 3 concurrent GETs
    let get_uri = format!("/v2/{repo}/manifests/{tag}");
    let g1 = {
        let app = app.clone();
        let token = token.clone();
        let uri = get_uri.clone();
        tokio::spawn(async move {
            let req = axum::http::Request::builder()
                .method("GET")
                .uri(&uri)
                .header("Authorization", format!("Bearer {token}"))
                .body(axum::body::Body::empty())
                .unwrap();
            app.clone().oneshot(req).await
        })
    };
    let g2 = {
        let app = app.clone();
        let token = token.clone();
        let uri = get_uri.clone();
        tokio::spawn(async move {
            let req = axum::http::Request::builder()
                .method("GET")
                .uri(&uri)
                .header("Authorization", format!("Bearer {token}"))
                .body(axum::body::Body::empty())
                .unwrap();
            app.clone().oneshot(req).await
        })
    };
    let g3 = {
        let app = app.clone();
        let token = token.clone();
        tokio::spawn(async move {
            let req = axum::http::Request::builder()
                .method("GET")
                .uri(&get_uri)
                .header("Authorization", format!("Bearer {token}"))
                .body(axum::body::Body::empty())
                .unwrap();
            app.clone().oneshot(req).await
        })
    };

    let (r1, r2, r3) = tokio::join!(g1, g2, g3);
    for (i, result) in [r1, r2, r3].iter().enumerate() {
        let resp = result.as_ref().unwrap().as_ref().unwrap();
        assert_eq!(resp.status(), 200, "concurrent manifest GET {} failed", i);
    }
}

// ===========================================================================
// 7. Overwrite prevention across protocols — all three protocols store
//    the same content under different key namespaces without shadowing.
// ===========================================================================

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_overwrite_prevention_across_lfs_oci_bazel() {
    let pg_url = ensure_pg().await;
    let tmp = TempDir::new().unwrap();
    let chunk_size = NonZeroUsize::new(65536).unwrap();
    let config = ServerConfig::new(
        "127.0.0.1:0".parse().unwrap(),
        "http://127.0.0.1:8080".to_owned(),
        tmp.path().to_path_buf(),
        chunk_size,
    )
    .with_server_role(ServerRole::All)
    .with_server_frontends([
        ServerFrontend::Lfs,
        ServerFrontend::BazelHttp,
        ServerFrontend::Oci,
    ])
    .unwrap()
    .with_token_signing_key(TEST_SIGNING_KEY.to_vec())
    .unwrap()
    .with_index_postgres_url(pg_url.to_owned())
    .unwrap()
    .with_reconstruction_cache_disabled();
    config.validate_runtime_requirements().unwrap();
    let app = app::router(config).await.unwrap();

    let token = {
        let provider = LocalHmacProvider::new(TEST_SIGNING_KEY).unwrap();
        let repo_s =
            RepositoryScope::new(RepositoryProvider::Generic, "test", "test", Some("main"))
                .unwrap();
        let claims =
            TokenClaims::new("shardline", "test", TokenScope::Write, repo_s, u64::MAX).unwrap();
        provider.mint_token(&claims).unwrap()
    };
    let _keep = Box::new(tmp);

    // Same content uploaded via each protocol.
    let content = b"cross-protocol-shadow-test-content";
    let hash = sha256_hex(content);
    let repo = "test/test";

    // 1. Upload via LFS
    let lfs_put = app
        .clone()
        .oneshot(
            axum::http::Request::builder()
                .method("PUT")
                .uri(&format!("/v1/lfs/objects/{hash}"))
                .header("Authorization", format!("Bearer {token}"))
                .header("Content-Type", "application/octet-stream")
                .body(axum::body::Body::from(content.to_vec()))
                .unwrap(),
        )
        .await
        .unwrap();
    assert!(
        lfs_put.status().is_success(),
        "LFS PUT failed: {}",
        lfs_put.status()
    );

    // 2. Upload via OCI (monolithic blob upload)
    let oci_put = app
        .clone()
        .oneshot(
            axum::http::Request::builder()
                .method("POST")
                .uri(&format!("/v2/{repo}/blobs/uploads/?digest=sha256:{hash}"))
                .header("Authorization", format!("Bearer {token}"))
                .header("Content-Type", "application/octet-stream")
                .body(axum::body::Body::from(content.to_vec()))
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(
        oci_put.status(),
        201,
        "OCI blob upload failed: {}",
        oci_put.status()
    );

    // 3. Upload via Bazel CAS
    let bazel_put = app
        .clone()
        .oneshot(
            axum::http::Request::builder()
                .method("PUT")
                .uri(&format!("/v1/bazel/cache/cas/{hash}"))
                .header("Authorization", format!("Bearer {token}"))
                .header("Content-Type", "application/octet-stream")
                .body(axum::body::Body::from(content.to_vec()))
                .unwrap(),
        )
        .await
        .unwrap();
    assert!(
        bazel_put.status().is_success(),
        "Bazel CAS PUT failed: {}",
        bazel_put.status()
    );

    // 4. Verify LFS read returns correct content
    let lfs_get = app
        .clone()
        .oneshot(
            axum::http::Request::builder()
                .method("GET")
                .uri(&format!("/v1/lfs/objects/{hash}"))
                .header("Authorization", format!("Bearer {token}"))
                .body(axum::body::Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(lfs_get.status(), 200, "LFS GET should succeed");
    let lfs_body = axum::body::to_bytes(lfs_get.into_body(), usize::MAX)
        .await
        .unwrap();
    assert_eq!(lfs_body.as_ref(), content, "LFS content mismatch");

    // 5. Verify OCI read returns correct content
    let oci_get = app
        .clone()
        .oneshot(
            axum::http::Request::builder()
                .method("GET")
                .uri(&format!("/v2/{repo}/blobs/sha256:{hash}"))
                .header("Authorization", format!("Bearer {token}"))
                .body(axum::body::Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(oci_get.status(), 200, "OCI GET should succeed");
    let oci_body = axum::body::to_bytes(oci_get.into_body(), usize::MAX)
        .await
        .unwrap();
    assert_eq!(oci_body.as_ref(), content, "OCI content mismatch");

    // 6. Verify Bazel CAS read returns correct content
    let bazel_get = app
        .clone()
        .oneshot(
            axum::http::Request::builder()
                .method("GET")
                .uri(&format!("/v1/bazel/cache/cas/{hash}"))
                .header("Authorization", format!("Bearer {token}"))
                .body(axum::body::Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(bazel_get.status(), 200, "Bazel CAS GET should succeed");
    let bazel_body = axum::body::to_bytes(bazel_get.into_body(), usize::MAX)
        .await
        .unwrap();
    assert_eq!(bazel_body.as_ref(), content, "Bazel CAS content mismatch");
}

// ===========================================================================
// 24. Cross-protocol content sharing
// ===========================================================================
//
// Each protocol uses its own storage key namespace:
//   LFS:  protocols/lfs/{namespace}/objects/{oid}
//   Bazel: protocols/bazel/{kind}/{namespace}/{hash}
//   OCI:   protocols/oci/{namespace}/{repository}/{digest}
//   Hub:   HubStore (separate SQLite/Postgres tables)
//
// Cross-protocol reads document namespace isolation (expect 404).
// Same-protocol reads verify the upload was successful.

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_cross_bazel_cas_to_lfs() {
    let server = TestServer::start(&[ServerFrontend::BazelHttp, ServerFrontend::Lfs]).await;
    let client = reqwest::Client::new();

    let content = b"bazel-cas-to-lfs-cross-pg";
    let hash = sha256_hex(content);

    // Upload via Bazel CAS
    let put_resp = client
        .put(server.url(&format!("/v1/bazel/cache/cas/{hash}")))
        .header("Authorization", format!("Bearer {}", server.auth_header()))
        .header("Content-Type", "application/octet-stream")
        .body(content.to_vec())
        .send()
        .await
        .unwrap();
    assert!(
        put_resp.status().is_success(),
        "Bazel CAS PUT failed: {}",
        put_resp.status()
    );

    // Verify same-protocol read works
    let bazel_get = client
        .get(server.url(&format!("/v1/bazel/cache/cas/{hash}")))
        .header("Authorization", format!("Bearer {}", server.auth_header()))
        .send()
        .await
        .unwrap();
    assert_eq!(bazel_get.status(), 200);
    assert_eq!(bazel_get.bytes().await.unwrap().as_ref(), content);

    // Cross-protocol read via LFS — different key namespace → 404
    let lfs_get = client
        .get(server.url(&format!("/v1/lfs/objects/{hash}")))
        .header("Authorization", format!("Bearer {}", server.auth_header()))
        .send()
        .await
        .unwrap();
    assert_eq!(
        lfs_get.status(),
        404,
        "LFS should not find data stored via Bazel CAS (separate key namespace)"
    );
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_cross_lfs_to_oci_blob() {
    // Use oneshot because OCI uses wildcard routes (/v2/{*path})
    let pg_url = ensure_pg().await;
    let tmp = TempDir::new().unwrap();
    let chunk_size = NonZeroUsize::new(65536).unwrap();
    let config = ServerConfig::new(
        "127.0.0.1:0".parse().unwrap(),
        "http://127.0.0.1:8080".to_owned(),
        tmp.path().to_path_buf(),
        chunk_size,
    )
    .with_server_role(ServerRole::All)
    .with_server_frontends([ServerFrontend::Lfs, ServerFrontend::Oci])
    .unwrap()
    .with_token_signing_key(TEST_SIGNING_KEY.to_vec())
    .unwrap()
    .with_index_postgres_url(pg_url.to_owned())
    .unwrap()
    .with_reconstruction_cache_disabled();
    config.validate_runtime_requirements().unwrap();
    let app = app::router(config).await.unwrap();

    let token = {
        let provider = LocalHmacProvider::new(TEST_SIGNING_KEY).unwrap();
        let repo_s =
            RepositoryScope::new(RepositoryProvider::Generic, "test", "test", Some("main"))
                .unwrap();
        let claims =
            TokenClaims::new("shardline", "test", TokenScope::Write, repo_s, u64::MAX).unwrap();
        provider.mint_token(&claims).unwrap()
    };
    let _keep = Box::new(tmp);

    let content = b"lfs-to-oci-cross-pg";
    let digest = sha256_hex(content);
    let repo = "test/test";

    // Upload via LFS
    let put_uri = format!("/v1/lfs/objects/{digest}");
    let put_req = axum::http::Request::builder()
        .method("PUT")
        .uri(&put_uri)
        .header("Authorization", format!("Bearer {token}"))
        .header("Content-Type", "application/octet-stream")
        .body(axum::body::Body::from(content.to_vec()))
        .unwrap();
    let put_resp = app.clone().oneshot(put_req).await.unwrap();
    assert!(
        put_resp.status().is_success(),
        "LFS PUT failed: {}",
        put_resp.status()
    );

    // Verify same-protocol read works
    let lfs_get = app
        .clone()
        .oneshot(
            axum::http::Request::builder()
                .method("GET")
                .uri(&put_uri)
                .header("Authorization", format!("Bearer {token}"))
                .body(axum::body::Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(
        lfs_get.status(),
        200,
        "LFS GET after LFS upload should work"
    );

    // Cross-protocol read via OCI — different key namespace → 404
    let get_uri = format!("/v2/{repo}/blobs/sha256:{digest}");
    let get_req = axum::http::Request::builder()
        .method("GET")
        .uri(&get_uri)
        .header("Authorization", format!("Bearer {token}"))
        .body(axum::body::Body::empty())
        .unwrap();
    let get_resp = app.clone().oneshot(get_req).await.unwrap();
    assert_eq!(
        get_resp.status(),
        404,
        "OCI should not find data stored via LFS (separate key namespace)"
    );
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_cross_hub_lfs_to_v1_lfs() {
    let server = TestServer::start(&[ServerFrontend::Hub, ServerFrontend::Lfs]).await;
    let client = reqwest::Client::new();
    let auth = || format!("Bearer {}", server.auth_header());

    let content = b"hub-lfs-to-v1-cross-pg";
    let oid = sha256_hex(content);

    // Upload via Hub's /lfs/objects/{oid}
    let put_resp = client
        .put(server.url(&format!("/lfs/objects/{oid}")))
        .header("Authorization", auth())
        .header("Content-Type", "application/octet-stream")
        .body(content.to_vec())
        .send()
        .await
        .unwrap();
    assert_eq!(
        put_resp.status(),
        200,
        "Hub LFS PUT failed: {}",
        put_resp.status()
    );

    // Verify same-protocol read via Hub LFS works
    let hub_get = client
        .get(server.url(&format!("/lfs/objects/{oid}")))
        .header("Authorization", auth())
        .send()
        .await
        .unwrap();
    assert_eq!(
        hub_get.status(),
        200,
        "Hub LFS GET should work after upload"
    );
    assert_eq!(hub_get.bytes().await.unwrap().as_ref(), content);

    // Cross-protocol read via V1 LFS — different storage backend → 404
    let v1_get = client
        .get(server.url(&format!("/v1/lfs/objects/{oid}")))
        .header("Authorization", auth())
        .send()
        .await
        .unwrap();
    assert_eq!(
        v1_get.status(),
        404,
        "V1 LFS should not find data stored via Hub LFS (separate storage)"
    );
}

// ===========================================================================
// 26. OCI v2 token with auth
// ===========================================================================

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_oci_v2_token_with_auth() {
    let mut builder = TestServerBuilder::new(&[ServerFrontend::Oci]);
    let server = builder.start().await;
    let client = reqwest::Client::new();

    // GET /v2/token with a valid bearer token + scope query
    let resp = client
        .get(server.url("/v2/token?scope=repository:test/test:pull&service=shardline"))
        .header("Authorization", format!("Bearer {}", server.auth_header()))
        .send()
        .await
        .unwrap();

    assert_eq!(
        resp.status(),
        200,
        "OCI v2 token endpoint should return 200 with valid auth"
    );
    let json: serde_json::Value = resp.json().await.unwrap();
    assert!(
        json["token"].as_str().map_or(false, |t| !t.is_empty()),
        "response should contain a non-empty 'token' field"
    );
    assert!(
        json["access_token"]
            .as_str()
            .map_or(false, |t| !t.is_empty()),
        "response should contain a non-empty 'access_token' field"
    );
    assert!(
        json["expires_in"].as_u64().unwrap_or(0) >= 60,
        "expires_in should be at least 60 seconds"
    );
}

// ===========================================================================
// 27. 413 Payload Too Large
// ===========================================================================

/// Helper: build a minimal oneshot app with a specific max body limit and
/// the given frontends. Returns (app, token).
async fn app_with_body_limit(
    frontends: &[ServerFrontend],
    max_body_bytes: usize,
) -> (axum::Router, String) {
    let pg_url = ensure_pg().await;
    let tmp = TempDir::new().unwrap();
    let chunk_size = NonZeroUsize::new(65536).unwrap();
    let config = ServerConfig::new(
        "127.0.0.1:0".parse().unwrap(),
        "http://127.0.0.1:8080".to_owned(),
        tmp.path().to_path_buf(),
        chunk_size,
    )
    .with_server_role(ServerRole::All)
    .with_server_frontends(frontends.to_vec())
    .unwrap()
    .with_token_signing_key(TEST_SIGNING_KEY.to_vec())
    .unwrap()
    .with_index_postgres_url(pg_url.to_owned())
    .unwrap()
    .with_max_request_body_bytes(NonZeroUsize::new(max_body_bytes).unwrap())
    .with_reconstruction_cache_disabled();
    config.validate_runtime_requirements().unwrap();
    let app = app::router(config).await.unwrap();

    let provider = LocalHmacProvider::new(TEST_SIGNING_KEY).unwrap();
    let repo =
        RepositoryScope::new(RepositoryProvider::Generic, "test", "test", Some("main")).unwrap();
    let claims = TokenClaims::new("shardline", "test", TokenScope::Write, repo, u64::MAX).unwrap();
    let token = provider.mint_token(&claims).unwrap();
    // Keep tmp alive
    let _ = Box::new(tmp);
    (app, token)
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_413_payload_too_large_lfs() {
    let (app, token) = app_with_body_limit(&[ServerFrontend::Lfs], 1024).await;
    let oid = sha256_hex(b"dummy");
    let large_body = vec![0u8; 2048]; // exceeds 1024 limit

    let req = axum::http::Request::builder()
        .method("PUT")
        .uri(&format!("/v1/lfs/objects/{oid}"))
        .header("Authorization", format!("Bearer {token}"))
        .header("Content-Type", "application/octet-stream")
        .body(axum::body::Body::from(large_body))
        .unwrap();
    let resp = app.clone().oneshot(req).await.unwrap();
    assert_eq!(
        resp.status(),
        413,
        "LFS PUT with oversized body should return 413"
    );
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_413_payload_too_large_bazel() {
    let (app, token) = app_with_body_limit(&[ServerFrontend::BazelHttp], 1024).await;
    let hash = sha256_hex(b"dummy");
    let large_body = vec![0u8; 2048]; // exceeds 1024 limit

    let req = axum::http::Request::builder()
        .method("PUT")
        .uri(&format!("/v1/bazel/cache/cas/{hash}"))
        .header("Authorization", format!("Bearer {token}"))
        .body(axum::body::Body::from(large_body))
        .unwrap();
    let resp = app.clone().oneshot(req).await.unwrap();
    assert_eq!(
        resp.status(),
        413,
        "Bazel CAS PUT with oversized body should return 413"
    );
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_413_payload_too_large_hub_commit() {
    // Hub routes have their own 64MB body limit (hardcoded in hub_routes).
    // Verifying the endpoint works — create repo and send valid commit.
    let (app, token) = app_with_body_limit(&[ServerFrontend::Hub], 1024).await;

    // Create a repo
    let create_body = serde_json::json!({
        "type": "model",
        "name": "pg-413-team/pg-413-model",
        "private": false,
    });
    let create_req = axum::http::Request::builder()
        .method("POST")
        .uri("/api/repos/create")
        .header("Authorization", format!("Bearer {token}"))
        .header("Content-Type", "application/json")
        .body(axum::body::Body::from(
            serde_json::to_vec(&create_body).unwrap(),
        ))
        .unwrap();
    let create_resp = app.clone().oneshot(create_req).await.unwrap();
    assert_eq!(create_resp.status(), 201);

    // Send valid commit — proves the full Hub commit pipeline works end-to-end.
    let content_b64 = base64::Engine::encode(
        &base64::engine::general_purpose::STANDARD,
        b"hub 413 test content",
    );
    let ndjson = format!(
        "{{\"header\":{{\"message\":\"hub 413 commit\",\"parentCommit\":\"\"}}}}\n\
         {{\"file\":{{\"path\":\"test.txt\",\"content\":\"{content_b64}\"}}}}"
    );
    let commit_req = axum::http::Request::builder()
        .method("POST")
        .uri("/api/models/pg-413-team/pg-413-model/commit/main")
        .header("Authorization", format!("Bearer {token}"))
        .header("Content-Type", "application/x-ndjson")
        .body(axum::body::Body::from(ndjson))
        .unwrap();
    let commit_resp = app.clone().oneshot(commit_req).await.unwrap();
    assert_eq!(
        commit_resp.status(),
        200,
        "Hub valid commit should return 200, got {}",
        commit_resp.status()
    );

    // The 413 Payload Too Large behavior is verified by the LFS and Bazel
    // tests above. Hub routes have their own hardcoded 64MB body limit that
    // cannot be driven to 413 without sending >64MB, which is impractical.
}

// ===========================================================================
// 28. 405 Method Not Allowed
// ===========================================================================

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_405_method_not_allowed() {
    let server = TestServer::start(&[ServerFrontend::Lfs]).await;
    let client = reqwest::Client::new();

    // GET to POST-only /v1/lfs/objects/batch
    let resp = client
        .get(server.url("/v1/lfs/objects/batch"))
        .header("Authorization", format!("Bearer {}", server.auth_header()))
        .send()
        .await
        .unwrap();

    assert_eq!(
        resp.status(),
        405,
        "GET to POST-only route should return 405"
    );
}

// ===========================================================================
// 29. CORS headers on Hub API
// ===========================================================================

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_cors_headers_hub_api() {
    let server = TestServer::start(&[ServerFrontend::Hub]).await;
    let client = reqwest::Client::new();

    let resp = client
        .get(server.url("/api/whoami-v2"))
        .header("Origin", "http://127.0.0.1:8080")
        .send()
        .await
        .unwrap();

    assert_eq!(resp.status(), 200);
    let cors_header = resp.headers().get("access-control-allow-origin");
    assert!(
        cors_header.is_some(),
        "Hub API response should include Access-Control-Allow-Origin header"
    );
    assert_eq!(
        cors_header.unwrap().to_str().unwrap(),
        "*",
        "Hub API should use the same allow-all CORS policy as the protocol frontends"
    );
}

// ===========================================================================
// 30. Very long URL path — server must not crash
// ===========================================================================

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_very_long_url_path_does_not_crash() {
    let server = TestServer::start(&[ServerFrontend::Lfs]).await;
    let client = reqwest::Client::new();

    // Build a 100KB path by repeating a path segment.
    let long_segment = "a".repeat(100_000);
    let uri = format!("/v1/lfs/objects/{long_segment}");

    // Send the request.  The server should not crash regardless of how hyper
    // / axum handles the oversized URI.  A 414 URI Too Long or a connection
    // reset are both acceptable — the server process must stay alive.
    let resp = client
        .get(server.url(&uri))
        .header("Authorization", format!("Bearer {}", server.auth_header()))
        .send()
        .await;

    match resp {
        Ok(r) => {
            // Hyper may reject the oversize URI before it reaches the handler,
            // returning 414 or 400.  The server stays alive.
            let status = r.status();
            assert!(
                status.is_server_error() || status.is_client_error() || status.is_redirection(),
                "unexpected success status for 100KB URL path: {status}"
            );
            // Verify the server is still healthy after handling the long URL.
            let health = client
                .get(server.url("/healthz"))
                .send()
                .await
                .expect("server should still be alive after long URL");
            assert_eq!(health.status(), 200);
        }
        Err(_e) => {
            // A connection error is also acceptable as long as the server
            // process is not killed.  Verify health still works.
            let health = client
                .get(server.url("/healthz"))
                .send()
                .await
                .expect("server should still be alive after long URL");
            assert_eq!(health.status(), 200);
        }
    }
}

// ===========================================================================
// 31. Concurrent Hub commit + revisions read
// ===========================================================================

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_concurrent_hub_commit_and_read() {
    let server = TestServer::start(&[ServerFrontend::Hub]).await;
    let client = reqwest::Client::new();
    let auth = || format!("Bearer {}", server.auth_header());
    let base_url = server.base_url.clone();

    // Create a repo
    let ns = "concurrent-team-pg";
    let name = "concurrent-model-pg";
    let model_path = format!("{ns}/{name}");

    let create_resp = client
        .post(format!("{base_url}/api/repos/create"))
        .header("Authorization", auth())
        .header("Content-Type", "application/json")
        .json(&serde_json::json!({
            "type": "model",
            "name": &model_path,
            "private": false,
        }))
        .send()
        .await
        .unwrap();
    assert_eq!(create_resp.status(), 201);

    // Spawn commit + revisions read concurrently
    let content_b64 = base64::Engine::encode(
        &base64::engine::general_purpose::STANDARD,
        b"concurrent content pg",
    );
    let ndjson = format!(
        "{{\"header\":{{\"message\":\"concurrent commit\",\"parentCommit\":\"\"}}}}\n\
         {{\"file\":{{\"path\":\"concurrent.txt\",\"content\":\"{content_b64}\"}}}}"
    );

    let commit_url = format!("{base_url}/api/models/{ns}/{name}/commit/main");
    let revisions_url = format!("{base_url}/api/models/{ns}/{name}/revisions");
    let token = server.auth_header().to_owned();

    let (r1, r2) = tokio::join!(
        async {
            let client = reqwest::Client::new();
            client
                .post(&commit_url)
                .header("Authorization", format!("Bearer {token}"))
                .header("Content-Type", "application/x-ndjson")
                .body(ndjson)
                .send()
                .await
                .unwrap()
        },
        async {
            let client = reqwest::Client::new();
            client
                .get(&revisions_url)
                .header("Authorization", format!("Bearer {token}"))
                .send()
                .await
                .unwrap()
        }
    );

    // Commit should succeed
    assert!(
        r1.status().is_success() || r1.status().is_client_error(),
        "concurrent commit status: {}",
        r1.status()
    );
    // Revisions list should succeed
    assert_eq!(
        r2.status(),
        200,
        "concurrent revisions list should return 200, got {}",
        r2.status()
    );
}

// ===========================================================================
// 31. Concurrent OCI session upload + cancel
// ===========================================================================

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_concurrent_session_upload_and_cancel() {
    let (app, token) = oci_oneshot_app().await;
    let repo = "test/test";

    // Create session
    let create_req = axum::http::Request::builder()
        .method("POST")
        .uri(&format!("/v2/{repo}/blobs/uploads/"))
        .header("Authorization", format!("Bearer {token}"))
        .header("Content-Length", "0")
        .body(axum::body::Body::empty())
        .unwrap();
    let create_resp = app.clone().oneshot(create_req).await.unwrap();
    assert_eq!(create_resp.status(), 202, "session creation should succeed");
    let location = create_resp
        .headers()
        .get("location")
        .unwrap()
        .to_str()
        .unwrap()
        .to_owned();

    // Spawn PATCH + DELETE concurrently
    let app1 = app.clone();
    let token1 = token.clone();
    let loc1 = location.clone();
    let (patch_res, delete_res) = tokio::join!(
        async {
            let req = axum::http::Request::builder()
                .method("PATCH")
                .uri(&loc1)
                .header("Authorization", format!("Bearer {token1}"))
                .header("Content-Type", "application/octet-stream")
                .header("Content-Range", "0-4")
                .body(axum::body::Body::from(b"hello".to_vec()))
                .unwrap();
            app1.clone().oneshot(req).await.unwrap()
        },
        async {
            let req = axum::http::Request::builder()
                .method("DELETE")
                .uri(&location)
                .header("Authorization", format!("Bearer {token}"))
                .body(axum::body::Body::empty())
                .unwrap();
            app.clone().oneshot(req).await.unwrap()
        }
    );

    // Both operations should complete (one may fail if the session is already
    // deleted by the other, but neither should panic or hang).
    assert!(
        patch_res.status().is_success() || patch_res.status().is_client_error(),
        "concurrent PATCH status: {}",
        patch_res.status()
    );
    assert!(
        delete_res.status().is_success() || delete_res.status() == 404,
        "concurrent DELETE status: {}",
        delete_res.status()
    );
}

// ===========================================================================
// 25. Hub API authenticated requests
// ===========================================================================

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_hub_whoami_with_auth() {
    let server = TestServer::start(&[ServerFrontend::Hub]).await;
    let client = reqwest::Client::new();

    let resp = client
        .get(server.url("/api/whoami-v2"))
        .header("Authorization", format!("Bearer {}", server.auth_header()))
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), 200);
    let json: serde_json::Value = resp.json().await.unwrap();
    // With a valid Write-scoped token, whoami returns the subject "test"
    assert_eq!(json["name"], "test", "whoami should return subject name");
    assert_eq!(
        json["auth"]["type"], "token",
        "auth.type should be 'token' with valid auth"
    );
    assert_eq!(
        json["auth"]["identity"]["account"]["name"], "test",
        "account name should match subject"
    );
    // The whoami response with auth should include auth details
    assert!(json.get("auth").is_some(), "auth block should be present");
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_hub_commit_with_auth() {
    let server = TestServer::start(&[ServerFrontend::Hub]).await;
    let client = reqwest::Client::new();
    let auth = || format!("Bearer {}", server.auth_header());

    let ns = "hub-auth-team-pg";
    let name = "hub-auth-model-pg";
    let model_path = format!("{ns}/{name}");

    // Create a model repo (requires Write scope)
    let create_resp = client
        .post(server.url("/api/repos/create"))
        .header("Authorization", auth())
        .header("Content-Type", "application/json")
        .json(&serde_json::json!({
            "type": "model",
            "name": &model_path,
            "private": false,
        }))
        .send()
        .await
        .unwrap();
    assert_eq!(
        create_resp.status(),
        201,
        "repo create should succeed with auth"
    );

    // Commit a file (requires Write scope)
    let content_b64 = base64::Engine::encode(
        &base64::engine::general_purpose::STANDARD,
        b"hub auth commit content pg",
    );
    let ndjson = format!(
        "{{\"header\":{{\"message\":\"auth commit\",\"parentCommit\":\"\"}}}}\n\
         {{\"file\":{{\"path\":\"auth.txt\",\"content\":\"{content_b64}\"}}}}"
    );
    let commit_resp = client
        .post(server.url(&format!("/api/models/{ns}/{name}/commit/main")))
        .header("Authorization", auth())
        .header("Content-Type", "application/x-ndjson")
        .body(ndjson)
        .send()
        .await
        .unwrap();
    assert_eq!(commit_resp.status(), 200, "commit should succeed with auth");
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_hub_xet_read_token_with_auth() {
    let server = TestServer::start(&[ServerFrontend::Hub]).await;
    let client = reqwest::Client::new();
    let auth = || format!("Bearer {}", server.auth_header());

    // Create a repo first
    let ns = "read-token-auth-pg";
    let name = "read-token-auth-repo";
    let model_path = format!("{ns}/{name}");

    let create_resp = client
        .post(server.url("/api/repos/create"))
        .header("Authorization", auth())
        .header("Content-Type", "application/json")
        .json(&serde_json::json!({
            "type": "model",
            "name": &model_path,
            "private": false,
        }))
        .send()
        .await
        .unwrap();
    assert_eq!(create_resp.status(), 201, "repo create should succeed");

    // Request xet-read-token (requires Read scope; our Write token allows Read)
    let token_resp = client
        .get(server.url(&format!("/api/models/{ns}/{name}/xet-read-token/main")))
        .header("Authorization", auth())
        .send()
        .await
        .unwrap();
    assert_eq!(
        token_resp.status(),
        200,
        "xet-read-token with valid auth should return 200"
    );
    let json: serde_json::Value = token_resp.json().await.unwrap();
    assert!(
        !json["token"].as_str().unwrap().is_empty(),
        "should return a token"
    );
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_hub_xet_write_token_with_auth() {
    let server = TestServer::start(&[ServerFrontend::Hub]).await;
    let client = reqwest::Client::new();
    let auth = || format!("Bearer {}", server.auth_header());

    // Create a repo first
    let ns = "write-token-auth-pg";
    let name = "write-token-auth-repo";
    let model_path = format!("{ns}/{name}");

    let create_resp = client
        .post(server.url("/api/repos/create"))
        .header("Authorization", auth())
        .header("Content-Type", "application/json")
        .json(&serde_json::json!({
            "type": "model",
            "name": &model_path,
            "private": false,
        }))
        .send()
        .await
        .unwrap();
    assert_eq!(create_resp.status(), 201, "repo create should succeed");

    // Request xet-write-token (requires Write scope)
    let token_resp = client
        .get(server.url(&format!("/api/models/{ns}/{name}/xet-write-token/main")))
        .header("Authorization", auth())
        .send()
        .await
        .unwrap();
    assert_eq!(
        token_resp.status(),
        200,
        "xet-write-token with valid auth should return 200"
    );
    let json: serde_json::Value = token_resp.json().await.unwrap();
    assert!(
        !json["token"].as_str().unwrap().is_empty(),
        "should return a token"
    );
}

// ===========================================================================
// Section 4: Boundary tests
// ===========================================================================

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_lfs_batch_exactly_max_objects() {
    // MAX_LFS_BATCH_OBJECTS = 1024. Sending exactly 1024 should succeed (not 422).
    let server = TestServer::start(&[ServerFrontend::Lfs]).await;
    let client = reqwest::Client::new();

    let objects: Vec<serde_json::Value> = (0..1024)
        .map(|i| serde_json::json!({"oid": format!("{:064x}", i), "size": 100}))
        .collect();
    let body = serde_json::json!({
        "operation": "download",
        "objects": objects
    });

    let resp = client
        .post(server.url("/v1/lfs/objects/batch"))
        .header("Authorization", format!("Bearer {}", server.auth_header()))
        .header("Content-Type", "application/vnd.git-lfs+json")
        .json(&body)
        .send()
        .await
        .unwrap();

    assert_eq!(
        resp.status(),
        200,
        "batch with exactly 1024 objects should succeed, got {}",
        resp.status()
    );
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_oci_tags_list_max_page_size() {
    // MAX_OCI_TAG_LIST_PAGE_SIZE = 256. Request ?n=256 → should return 200.
    let pg_url = ensure_pg().await;
    let tmp = TempDir::new().unwrap();
    let chunk_size = NonZeroUsize::new(65536).unwrap();
    let config = ServerConfig::new(
        "127.0.0.1:0".parse().unwrap(),
        "http://127.0.0.1:8080".to_owned(),
        tmp.path().to_path_buf(),
        chunk_size,
    )
    .with_server_role(ServerRole::All)
    .with_server_frontends([ServerFrontend::Oci])
    .unwrap()
    .with_token_signing_key(TEST_SIGNING_KEY.to_vec())
    .unwrap()
    .with_index_postgres_url(pg_url.to_owned())
    .unwrap()
    .with_reconstruction_cache_disabled();
    config.validate_runtime_requirements().unwrap();
    let app = app::router(config).await.unwrap();
    let _ = Box::new(tmp);

    let token = {
        let provider = LocalHmacProvider::new(TEST_SIGNING_KEY).unwrap();
        let repo_s =
            RepositoryScope::new(RepositoryProvider::Generic, "test", "test", Some("main"))
                .unwrap();
        let claims =
            TokenClaims::new("shardline", "test", TokenScope::Write, repo_s, u64::MAX).unwrap();
        provider.mint_token(&claims).unwrap()
    };

    // Push a few manifests so there's at least 1 tag to list
    let repo = "test/test";
    let config_data = b"{}";
    let layer_data = b"max-page-layer";

    // Upload blobs for manifest
    let config_digest = {
        let uri = format!(
            "/v2/{repo}/blobs/uploads/?digest=sha256:{}",
            sha256_hex(config_data)
        );
        let req = axum::http::Request::builder()
            .method("POST")
            .uri(&uri)
            .header("Authorization", format!("Bearer {token}"))
            .header("Content-Type", "application/octet-stream")
            .body(axum::body::Body::from(config_data.to_vec()))
            .unwrap();
        let resp = app.clone().oneshot(req).await.unwrap();
        assert_eq!(resp.status(), 201);
        sha256_hex(config_data)
    };
    let layer_digest = {
        let uri = format!(
            "/v2/{repo}/blobs/uploads/?digest=sha256:{}",
            sha256_hex(layer_data)
        );
        let req = axum::http::Request::builder()
            .method("POST")
            .uri(&uri)
            .header("Authorization", format!("Bearer {token}"))
            .header("Content-Type", "application/octet-stream")
            .body(axum::body::Body::from(layer_data.to_vec()))
            .unwrap();
        let resp = app.clone().oneshot(req).await.unwrap();
        assert_eq!(resp.status(), 201);
        sha256_hex(layer_data)
    };

    let manifest_body = serde_json::json!({
        "schemaVersion": 2,
        "mediaType": "application/vnd.oci.image.manifest.v1+json",
        "config": {
            "mediaType": "application/vnd.oci.image.config.v1+json",
            "size": 0,
            "digest": format!("sha256:{config_digest}")
        },
        "layers": [{
            "mediaType": "application/vnd.oci.image.layer.v1.tar+gzip",
            "size": 0,
            "digest": format!("sha256:{layer_digest}")
        }]
    })
    .to_string();

    let put_req = axum::http::Request::builder()
        .method("PUT")
        .uri(&format!("/v2/{repo}/manifests/max-page-tag"))
        .header("Authorization", format!("Bearer {token}"))
        .header("Content-Type", "application/vnd.oci.image.manifest.v1+json")
        .body(axum::body::Body::from(manifest_body))
        .unwrap();
    let put_resp = app.clone().oneshot(put_req).await.unwrap();
    assert_eq!(put_resp.status(), 201);

    // Request tags list with ?n=256 (max page size)
    let list_req = axum::http::Request::builder()
        .method("GET")
        .uri(&format!("/v2/{repo}/tags/list?n=256"))
        .header("Authorization", format!("Bearer {token}"))
        .body(axum::body::Body::empty())
        .unwrap();
    let list_resp = app.clone().oneshot(list_req).await.unwrap();
    assert_eq!(
        list_resp.status(),
        200,
        "tags list with n=256 should return 200, got {}",
        list_resp.status()
    );
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_provider_token_request_at_max_body() {
    // MAX_PROVIDER_TOKEN_REQUEST_BODY_BYTES = 16384. Send a body exactly at the limit.
    let mut builder = TestServerBuilder::new(&[ServerFrontend::Xet]).with_provider();
    let server = builder.start().await;
    let client = reqwest::Client::new();

    // Build a body near the 16384 byte limit.
    // Subject must be in the provider config's read_subjects: "test-user".
    // We pad with a long "extra" field that serde ignores.
    let base = serde_json::json!({
        "subject": "test-user",
        "owner": "test",
        "repo": "test",
        "revision": serde_json::Value::Null,
        "scope": "Read",
        "extra": "",
    });
    let base_str = serde_json::to_string(&base).unwrap();
    let pad_len = 16378usize.saturating_sub(base_str.len());
    let extra = "x".repeat(pad_len);
    let body = serde_json::json!({
        "subject": "test-user",
        "owner": "test",
        "repo": "test",
        "revision": serde_json::Value::Null,
        "scope": "Read",
        "extra": extra,
    });
    let body_str = serde_json::to_string(&body).unwrap();
    assert!(
        body_str.len() <= 16384,
        "body length {} should not exceed 16384",
        body_str.len()
    );
    assert!(
        body_str.len() >= 16370,
        "body length {} should be near the 16384 limit",
        body_str.len()
    );

    let resp = client
        .post(server.url("/v1/providers/generic/tokens"))
        .header("x-shardline-provider-key", "test-api-key")
        .header("Content-Type", "application/json")
        .body(body_str.clone())
        .send()
        .await
        .unwrap();

    assert_eq!(
        resp.status(),
        200,
        "provider token request at max body size should return 200, got {} (body len = {})",
        resp.status(),
        body_str.len()
    );
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_large_object_binary_content() {
    let server = TestServer::start(&[ServerFrontend::Lfs]).await;
    let client = reqwest::Client::new();

    // Upload 5MB of binary content (null bytes, non-UTF-8)
    let content: Vec<u8> = {
        let mut data = Vec::with_capacity(5 * 1024 * 1024);
        // Fill with null bytes interspersed with non-UTF-8 byte sequences
        for i in 0..(5 * 1024 * 1024) {
            match i % 4 {
                0 => data.push(0x00),
                1 => data.push(0xFF),
                2 => data.push(0xAB),
                _ => data.push(0x00),
            }
        }
        data
    };
    let oid = sha256_hex(&content);

    // PUT the binary content
    let put_resp = client
        .put(server.url(&format!("/v1/lfs/objects/{oid}")))
        .header("Authorization", format!("Bearer {}", server.auth_header()))
        .header("Content-Type", "application/octet-stream")
        .body(content.clone())
        .send()
        .await
        .unwrap();
    assert!(
        put_resp.status().is_success(),
        "binary 5MB LFS PUT failed: {}",
        put_resp.status()
    );

    // GET the content back and verify roundtrip
    let get_resp = client
        .get(server.url(&format!("/v1/lfs/objects/{oid}")))
        .header("Authorization", format!("Bearer {}", server.auth_header()))
        .send()
        .await
        .unwrap();
    assert_eq!(get_resp.status(), 200);
    let body = get_resp.bytes().await.unwrap();
    assert_eq!(body.len(), content.len(), "binary content size mismatch");
    assert_eq!(body.as_ref(), content.as_slice(), "binary content mismatch");
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_lfs_upload_zero_byte_file() {
    let server = TestServer::start(&[ServerFrontend::Lfs]).await;
    let client = reqwest::Client::new();

    let content = b"";
    let oid = sha256_hex(content);

    // PUT 0-byte file
    let put_resp = client
        .put(server.url(&format!("/v1/lfs/objects/{oid}")))
        .header("Authorization", format!("Bearer {}", server.auth_header()))
        .header("Content-Type", "application/octet-stream")
        .body(content.to_vec())
        .send()
        .await
        .unwrap();
    assert!(
        put_resp.status().is_success(),
        "0-byte LFS PUT failed: {}",
        put_resp.status()
    );

    // GET back and verify
    let get_resp = client
        .get(server.url(&format!("/v1/lfs/objects/{oid}")))
        .header("Authorization", format!("Bearer {}", server.auth_header()))
        .send()
        .await
        .unwrap();
    assert_eq!(get_resp.status(), 200);
    let body = get_resp.bytes().await.unwrap();
    assert_eq!(body.as_ref(), content, "0-byte file roundtrip failed");
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_lfs_upload_one_byte_file() {
    let server = TestServer::start(&[ServerFrontend::Lfs]).await;
    let client = reqwest::Client::new();

    let content = b"X";
    let oid = sha256_hex(content);

    // PUT 1-byte file
    let put_resp = client
        .put(server.url(&format!("/v1/lfs/objects/{oid}")))
        .header("Authorization", format!("Bearer {}", server.auth_header()))
        .header("Content-Type", "application/octet-stream")
        .body(content.to_vec())
        .send()
        .await
        .unwrap();
    assert!(
        put_resp.status().is_success(),
        "1-byte LFS PUT failed: {}",
        put_resp.status()
    );

    // GET back and verify
    let get_resp = client
        .get(server.url(&format!("/v1/lfs/objects/{oid}")))
        .header("Authorization", format!("Bearer {}", server.auth_header()))
        .send()
        .await
        .unwrap();
    assert_eq!(get_resp.status(), 200);
    let body = get_resp.bytes().await.unwrap();
    assert_eq!(body.len(), 1);
    assert_eq!(body.as_ref(), content, "1-byte file roundtrip failed");
}

// ===========================================================================
// Section 5: Concurrent tests
// ===========================================================================

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_concurrent_lfs_upload_idempotency() {
    let server = TestServer::start(&[ServerFrontend::Lfs]).await;
    let content = b"concurrent-idempotency-content-pg";
    let oid = sha256_hex(content);
    let url = server.url(&format!("/v1/lfs/objects/{oid}"));
    let token = server.auth_header().to_owned();

    // 5 concurrent PUTs to the same LFS OID — all should return 200
    let mut handles = Vec::new();
    for _ in 0..5 {
        let url = url.clone();
        let token = token.clone();
        let data = content.to_vec();
        handles.push(tokio::spawn(async move {
            let client = reqwest::Client::new();
            let resp = client
                .put(&url)
                .header("Authorization", format!("Bearer {token}"))
                .header("Content-Type", "application/octet-stream")
                .body(data)
                .send()
                .await
                .unwrap();
            resp.status()
        }));
    }

    for (i, handle) in handles.into_iter().enumerate() {
        let status = handle.await.unwrap();
        assert!(
            status.is_success(),
            "concurrent LFS PUT {} returned {}",
            i,
            status
        );
    }

    // Verify the stored content is correct
    let client = reqwest::Client::new();
    let get_resp = client
        .get(server.url(&format!("/v1/lfs/objects/{oid}")))
        .header("Authorization", format!("Bearer {}", server.auth_header()))
        .send()
        .await
        .unwrap();
    assert_eq!(get_resp.status(), 200);
    assert_eq!(get_resp.bytes().await.unwrap().as_ref(), content);
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_concurrent_hub_repo_creation() {
    let server = TestServer::start(&[ServerFrontend::Hub]).await;
    let _client = reqwest::Client::new();
    let base_url = server.base_url.clone();
    let token = server.auth_header().to_owned();

    let ns = "concurrent-create-pg";
    let name = "concurrent-create-repo";
    let model_path = format!("{ns}/{name}");

    // 5 concurrent POST /api/repos/create with the same name
    let mut handles = Vec::new();
    for _ in 0..5 {
        let url = format!("{base_url}/api/repos/create");
        let token = token.clone();
        let body = serde_json::json!({
            "type": "model",
            "name": &model_path,
            "private": false,
        });
        handles.push(tokio::spawn(async move {
            let client = reqwest::Client::new();
            let resp = client
                .post(&url)
                .header("Authorization", format!("Bearer {token}"))
                .header("Content-Type", "application/json")
                .json(&body)
                .send()
                .await
                .unwrap();
            resp.status()
        }));
    }

    let mut success_count = 0u32;
    let mut conflict_count = 0u32;
    for handle in handles {
        let status = handle.await.unwrap();
        match status.as_u16() {
            201 => success_count += 1,
            409 => conflict_count += 1,
            other => panic!("unexpected status code {other} for concurrent repo creation"),
        }
    }

    assert!(
        success_count >= 1,
        "at least 1 concurrent create should succeed (201), got {success_count}"
    );
    assert_eq!(
        success_count + conflict_count,
        5,
        "all 5 concurrent creates should return either 201 or 409"
    );
}

// ===========================================================================
// 36. OCI session state machine — invalid transitions
// ===========================================================================

/// Extracts the session ID from the Location header of an OCI upload session response.
fn oci_session_id(resp: &axum::http::Response<axum::body::Body>) -> String {
    let location = resp
        .headers()
        .get("location")
        .unwrap()
        .to_str()
        .unwrap()
        .to_owned();
    location.split('/').next_back().unwrap().to_owned()
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_oci_session_patch_after_complete() {
    let (app, token) = oci_oneshot_app().await;
    let repo = "test/test";

    // Full session: POST -> PATCH -> PUT
    let post_req = axum::http::Request::builder()
        .method("POST")
        .uri(&format!("/v2/{repo}/blobs/uploads/"))
        .header("Authorization", format!("Bearer {token}"))
        .header("Content-Length", "0")
        .body(axum::body::Body::empty())
        .unwrap();
    let post_resp = app.clone().oneshot(post_req).await.unwrap();
    assert_eq!(post_resp.status(), 202, "POST should create session");
    let session_id = oci_session_id(&post_resp);

    let data = b"session data";
    let patch_req = axum::http::Request::builder()
        .method("PATCH")
        .uri(&format!("/v2/{repo}/blobs/uploads/{session_id}"))
        .header("Authorization", format!("Bearer {token}"))
        .header("Content-Type", "application/octet-stream")
        .body(axum::body::Body::from(data.to_vec()))
        .unwrap();
    let patch_resp = app.clone().oneshot(patch_req).await.unwrap();
    assert_eq!(patch_resp.status(), 202, "PATCH should succeed");

    let digest = sha256_hex(data);
    let put_req = axum::http::Request::builder()
        .method("PUT")
        .uri(&format!(
            "/v2/{repo}/blobs/uploads/{session_id}?digest=sha256:{digest}"
        ))
        .header("Authorization", format!("Bearer {token}"))
        .body(axum::body::Body::empty())
        .unwrap();
    let put_resp = app.clone().oneshot(put_req).await.unwrap();
    assert_eq!(put_resp.status(), 201, "PUT should finalize session");

    // PATCH after complete -> 404
    let patch_after = axum::http::Request::builder()
        .method("PATCH")
        .uri(&format!("/v2/{repo}/blobs/uploads/{session_id}"))
        .header("Authorization", format!("Bearer {token}"))
        .header("Content-Type", "application/octet-stream")
        .body(axum::body::Body::from(b"extra".to_vec()))
        .unwrap();
    let patch_after_resp = app.clone().oneshot(patch_after).await.unwrap();
    assert_eq!(
        patch_after_resp.status(),
        404,
        "PATCH after complete should return 404"
    );
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_oci_session_put_after_complete() {
    let (app, token) = oci_oneshot_app().await;
    let repo = "test/test";

    let post_req = axum::http::Request::builder()
        .method("POST")
        .uri(&format!("/v2/{repo}/blobs/uploads/"))
        .header("Authorization", format!("Bearer {token}"))
        .header("Content-Length", "0")
        .body(axum::body::Body::empty())
        .unwrap();
    let post_resp = app.clone().oneshot(post_req).await.unwrap();
    assert_eq!(post_resp.status(), 202);
    let session_id = oci_session_id(&post_resp);

    let data = b"put-after-complete-data";
    let patch_req = axum::http::Request::builder()
        .method("PATCH")
        .uri(&format!("/v2/{repo}/blobs/uploads/{session_id}"))
        .header("Authorization", format!("Bearer {token}"))
        .header("Content-Type", "application/octet-stream")
        .body(axum::body::Body::from(data.to_vec()))
        .unwrap();
    let _ = app.clone().oneshot(patch_req).await.unwrap();

    let digest = sha256_hex(data);
    let put_req = axum::http::Request::builder()
        .method("PUT")
        .uri(&format!(
            "/v2/{repo}/blobs/uploads/{session_id}?digest=sha256:{digest}"
        ))
        .header("Authorization", format!("Bearer {token}"))
        .body(axum::body::Body::empty())
        .unwrap();
    let put_resp = app.clone().oneshot(put_req).await.unwrap();
    assert_eq!(put_resp.status(), 201);

    let put_again = axum::http::Request::builder()
        .method("PUT")
        .uri(&format!(
            "/v2/{repo}/blobs/uploads/{session_id}?digest=sha256:{digest}"
        ))
        .header("Authorization", format!("Bearer {token}"))
        .body(axum::body::Body::empty())
        .unwrap();
    let put_again_resp = app.clone().oneshot(put_again).await.unwrap();
    assert_eq!(
        put_again_resp.status(),
        404,
        "PUT after complete should return 404"
    );
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_oci_session_get_after_complete() {
    let (app, token) = oci_oneshot_app().await;
    let repo = "test/test";

    let post_req = axum::http::Request::builder()
        .method("POST")
        .uri(&format!("/v2/{repo}/blobs/uploads/"))
        .header("Authorization", format!("Bearer {token}"))
        .header("Content-Length", "0")
        .body(axum::body::Body::empty())
        .unwrap();
    let post_resp = app.clone().oneshot(post_req).await.unwrap();
    assert_eq!(post_resp.status(), 202);
    let session_id = oci_session_id(&post_resp);

    let data = b"get-after-complete";
    let patch_req = axum::http::Request::builder()
        .method("PATCH")
        .uri(&format!("/v2/{repo}/blobs/uploads/{session_id}"))
        .header("Authorization", format!("Bearer {token}"))
        .header("Content-Type", "application/octet-stream")
        .body(axum::body::Body::from(data.to_vec()))
        .unwrap();
    let _ = app.clone().oneshot(patch_req).await.unwrap();

    let digest = sha256_hex(data);
    let put_req = axum::http::Request::builder()
        .method("PUT")
        .uri(&format!(
            "/v2/{repo}/blobs/uploads/{session_id}?digest=sha256:{digest}"
        ))
        .header("Authorization", format!("Bearer {token}"))
        .body(axum::body::Body::empty())
        .unwrap();
    let put_resp = app.clone().oneshot(put_req).await.unwrap();
    assert_eq!(put_resp.status(), 201);

    let get_after = axum::http::Request::builder()
        .method("GET")
        .uri(&format!("/v2/{repo}/blobs/uploads/{session_id}"))
        .header("Authorization", format!("Bearer {token}"))
        .body(axum::body::Body::empty())
        .unwrap();
    let get_after_resp = app.clone().oneshot(get_after).await.unwrap();
    assert_eq!(
        get_after_resp.status(),
        404,
        "GET after complete should return 404"
    );
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_oci_session_patch_after_delete() {
    let (app, token) = oci_oneshot_app().await;
    let repo = "test/test";

    let post_req = axum::http::Request::builder()
        .method("POST")
        .uri(&format!("/v2/{repo}/blobs/uploads/"))
        .header("Authorization", format!("Bearer {token}"))
        .header("Content-Length", "0")
        .body(axum::body::Body::empty())
        .unwrap();
    let post_resp = app.clone().oneshot(post_req).await.unwrap();
    assert_eq!(post_resp.status(), 202);
    let session_id = oci_session_id(&post_resp);

    let delete_req = axum::http::Request::builder()
        .method("DELETE")
        .uri(&format!("/v2/{repo}/blobs/uploads/{session_id}"))
        .header("Authorization", format!("Bearer {token}"))
        .body(axum::body::Body::empty())
        .unwrap();
    let delete_resp = app.clone().oneshot(delete_req).await.unwrap();
    assert_eq!(delete_resp.status(), 204, "DELETE should succeed");

    let patch_after = axum::http::Request::builder()
        .method("PATCH")
        .uri(&format!("/v2/{repo}/blobs/uploads/{session_id}"))
        .header("Authorization", format!("Bearer {token}"))
        .header("Content-Type", "application/octet-stream")
        .body(axum::body::Body::from(b"data".to_vec()))
        .unwrap();
    let patch_after_resp = app.clone().oneshot(patch_after).await.unwrap();
    assert_eq!(
        patch_after_resp.status(),
        404,
        "PATCH after delete should return 404"
    );
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_oci_session_patch_empty_body() {
    let (app, token) = oci_oneshot_app().await;
    let repo = "test/test";

    let post_req = axum::http::Request::builder()
        .method("POST")
        .uri(&format!("/v2/{repo}/blobs/uploads/"))
        .header("Authorization", format!("Bearer {token}"))
        .header("Content-Length", "0")
        .body(axum::body::Body::empty())
        .unwrap();
    let post_resp = app.clone().oneshot(post_req).await.unwrap();
    assert_eq!(post_resp.status(), 202);
    let session_id = oci_session_id(&post_resp);

    let patch_empty = axum::http::Request::builder()
        .method("PATCH")
        .uri(&format!("/v2/{repo}/blobs/uploads/{session_id}"))
        .header("Authorization", format!("Bearer {token}"))
        .header("Content-Type", "application/octet-stream")
        .header("Content-Length", "0")
        .body(axum::body::Body::empty())
        .unwrap();
    let patch_empty_resp = app.clone().oneshot(patch_empty).await.unwrap();
    assert_eq!(
        patch_empty_resp.status(),
        202,
        "PATCH with empty body should return 202"
    );
}

// ===========================================================================
// 37. LFS state machine tests
// ===========================================================================

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_lfs_put_after_patch() {
    let server = TestServer::start(&[ServerFrontend::Lfs]).await;
    let client = reqwest::Client::new();

    let partial = b"partial-chunk-";
    let final_content = b"complete-content-from-put";
    let oid = sha256_hex(final_content);
    let total = final_content.len() as u64;

    let patch_range = format!("bytes 0-{}/{}", partial.len() as u64 - 1, total);
    let patch_resp = client
        .patch(server.url(&format!("/v1/lfs/objects/{oid}")))
        .header("Authorization", format!("Bearer {}", server.auth_header()))
        .header("Content-Type", "application/octet-stream")
        .header("Content-Range", &patch_range)
        .body(partial.to_vec())
        .send()
        .await
        .unwrap();
    assert_eq!(patch_resp.status(), 200, "PATCH should succeed");

    let put_resp = client
        .put(server.url(&format!("/v1/lfs/objects/{oid}")))
        .header("Authorization", format!("Bearer {}", server.auth_header()))
        .header("Content-Type", "application/octet-stream")
        .header("Content-Length", final_content.len().to_string())
        .body(final_content.to_vec())
        .send()
        .await
        .unwrap();
    assert!(put_resp.status().is_success(), "PUT should succeed");

    let get_resp = client
        .get(server.url(&format!("/v1/lfs/objects/{oid}")))
        .header("Authorization", format!("Bearer {}", server.auth_header()))
        .send()
        .await
        .unwrap();
    assert_eq!(get_resp.status(), 200);
    let body = get_resp.bytes().await.unwrap();
    assert_eq!(
        body.as_ref(),
        final_content,
        "GET should return PUT content"
    );
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_lfs_patch_after_put() {
    let server = TestServer::start(&[ServerFrontend::Lfs]).await;
    let client = reqwest::Client::new();

    let original = b"original-content-from-put";
    let oid = sha256_hex(original);

    let put_resp = client
        .put(server.url(&format!("/v1/lfs/objects/{oid}")))
        .header("Authorization", format!("Bearer {}", server.auth_header()))
        .header("Content-Type", "application/octet-stream")
        .body(original.to_vec())
        .send()
        .await
        .unwrap();
    assert!(put_resp.status().is_success(), "PUT should succeed");

    // PATCH additional bytes at a non-zero offset. The PATCH handler creates a
    // temp file, writes the chunk, and when the chunk is "final" it assembles
    // the file and stores it. Since the temp file starts sparse (null bytes at
    // the unfilled offsets), the assembled content's hash will not match the
    // OID — the PATCH finalize must reject with a 4xx.
    let extra = b"-patched";
    let total = (original.len() + extra.len()) as u64;
    let patch_range = format!("bytes {}-{}/{}", original.len(), total - 1, total);
    let patch_resp = client
        .patch(server.url(&format!("/v1/lfs/objects/{oid}")))
        .header("Authorization", format!("Bearer {}", server.auth_header()))
        .header("Content-Type", "application/octet-stream")
        .header("Content-Range", &patch_range)
        .body(extra.to_vec())
        .send()
        .await
        .unwrap();
    // The assembled temp file has null bytes from 0..original.len() plus
    // "-patched" at the end; the stored content under the canonical key
    // (from the PUT) does not match. The object store's put_if_absent
    // detects the mismatch via ensure_file_matches_bytes and returns an
    // error. Accept any non-success status.
    assert!(
        !patch_resp.status().is_success(),
        "PATCH after PUT should not succeed (content mismatch), got {}",
        patch_resp.status()
    );

    // Verify the stored content is still the original PUT content (unchanged).
    let get_resp = client
        .get(server.url(&format!("/v1/lfs/objects/{oid}")))
        .header("Authorization", format!("Bearer {}", server.auth_header()))
        .send()
        .await
        .unwrap();
    assert_eq!(get_resp.status(), 200);
    let body = get_resp.bytes().await.unwrap();
    assert_eq!(
        body.as_ref(),
        original,
        "stored content should remain unchanged after failed PATCH"
    );
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_lfs_patch_non_existent_oid() {
    let server = TestServer::start(&[ServerFrontend::Lfs]).await;
    let client = reqwest::Client::new();

    let content = b"new-oid-patch-content";
    let oid = sha256_hex(content);
    let total = content.len() as u64;

    let patch_range = format!("bytes 0-{}/{}", total - 1, total);
    let patch_resp = client
        .patch(server.url(&format!("/v1/lfs/objects/{oid}")))
        .header("Authorization", format!("Bearer {}", server.auth_header()))
        .header("Content-Type", "application/octet-stream")
        .header("Content-Range", &patch_range)
        .body(content.to_vec())
        .send()
        .await
        .unwrap();
    assert_eq!(
        patch_resp.status(),
        200,
        "PATCH on non-existent OID should succeed"
    );

    let get_resp = client
        .get(server.url(&format!("/v1/lfs/objects/{oid}")))
        .header("Authorization", format!("Bearer {}", server.auth_header()))
        .send()
        .await
        .unwrap();
    assert_eq!(get_resp.status(), 200);
    let body = get_resp.bytes().await.unwrap();
    assert_eq!(body.as_ref(), content);
}

// ===========================================================================
// 38. Bazel + OCI coexistence
// ===========================================================================

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_bazel_and_oci_coexist() {
    let pg_url = ensure_pg().await;
    let tmp = TempDir::new().unwrap();
    let chunk_size = NonZeroUsize::new(65536).unwrap();
    let config = ServerConfig::new(
        "127.0.0.1:0".parse().unwrap(),
        "http://127.0.0.1:8080".to_owned(),
        tmp.path().to_path_buf(),
        chunk_size,
    )
    .with_server_role(ServerRole::All)
    .with_server_frontends([ServerFrontend::BazelHttp, ServerFrontend::Oci])
    .unwrap()
    .with_token_signing_key(TEST_SIGNING_KEY.to_vec())
    .unwrap()
    .with_index_postgres_url(pg_url.to_owned())
    .unwrap()
    .with_reconstruction_cache_disabled();
    config.validate_runtime_requirements().unwrap();
    let app = app::router(config).await.unwrap();

    let token = {
        let provider = LocalHmacProvider::new(TEST_SIGNING_KEY).unwrap();
        let repo_s =
            RepositoryScope::new(RepositoryProvider::Generic, "test", "test", Some("main"))
                .unwrap();
        let claims =
            TokenClaims::new("shardline", "test", TokenScope::Write, repo_s, u64::MAX).unwrap();
        provider.mint_token(&claims).unwrap()
    };
    let _keep = Box::new(tmp);

    let repo = "test/test";
    let content = b"coexistence-test-content";
    let hash = sha256_hex(content);

    // Upload to Bazel CAS
    let bazel_put = axum::http::Request::builder()
        .method("PUT")
        .uri(&format!("/v1/bazel/cache/cas/{hash}"))
        .header("Authorization", format!("Bearer {token}"))
        .header("Content-Type", "application/octet-stream")
        .body(axum::body::Body::from(content.to_vec()))
        .unwrap();
    let bazel_put_resp = app.clone().oneshot(bazel_put).await.unwrap();
    assert!(
        bazel_put_resp.status().is_success(),
        "Bazel CAS PUT failed: {}",
        bazel_put_resp.status()
    );

    // Upload same content to OCI blob (different key namespace)
    let oci_put = axum::http::Request::builder()
        .method("POST")
        .uri(&format!("/v2/{repo}/blobs/uploads/?digest=sha256:{hash}"))
        .header("Authorization", format!("Bearer {token}"))
        .header("Content-Type", "application/octet-stream")
        .body(axum::body::Body::from(content.to_vec()))
        .unwrap();
    let oci_put_resp = app.clone().oneshot(oci_put).await.unwrap();
    assert_eq!(oci_put_resp.status(), 201, "OCI blob upload should succeed");

    // Bazel GET works
    let bazel_get = axum::http::Request::builder()
        .method("GET")
        .uri(&format!("/v1/bazel/cache/cas/{hash}"))
        .header("Authorization", format!("Bearer {token}"))
        .body(axum::body::Body::empty())
        .unwrap();
    let bazel_get_resp = app.clone().oneshot(bazel_get).await.unwrap();
    assert_eq!(bazel_get_resp.status(), 200, "Bazel CAS GET should work");
    let bazel_body = axum::body::to_bytes(bazel_get_resp.into_body(), usize::MAX)
        .await
        .unwrap();
    assert_eq!(bazel_body.as_ref(), content);

    // OCI GET works
    let oci_get = axum::http::Request::builder()
        .method("GET")
        .uri(&format!("/v2/{repo}/blobs/sha256:{hash}"))
        .header("Authorization", format!("Bearer {token}"))
        .body(axum::body::Body::empty())
        .unwrap();
    let oci_get_resp = app.clone().oneshot(oci_get).await.unwrap();
    assert_eq!(oci_get_resp.status(), 200, "OCI blob GET should work");
    let oci_body = axum::body::to_bytes(oci_get_resp.into_body(), usize::MAX)
        .await
        .unwrap();
    assert_eq!(oci_body.as_ref(), content);

    // Namespace isolation
    let different_hash = sha256_hex(b"different-content");
    let bazel_get_missing = axum::http::Request::builder()
        .method("GET")
        .uri(&format!("/v1/bazel/cache/cas/{different_hash}"))
        .header("Authorization", format!("Bearer {token}"))
        .body(axum::body::Body::empty())
        .unwrap();
    let bazel_missing_resp = app.clone().oneshot(bazel_get_missing).await.unwrap();
    assert_eq!(
        bazel_missing_resp.status(),
        404,
        "Bazel should not find non-Bazel content"
    );
}

// ===========================================================================
// 39. Hub + Xet + LFS triple coexistence
// ===========================================================================

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_hub_xet_lfs_triple_coexist() {
    let pg_url = ensure_pg().await;
    let tmp = TempDir::new().unwrap();
    let chunk_size = NonZeroUsize::new(65536).unwrap();
    let config = ServerConfig::new(
        "127.0.0.1:0".parse().unwrap(),
        "http://127.0.0.1:8080".to_owned(),
        tmp.path().to_path_buf(),
        chunk_size,
    )
    .with_server_role(ServerRole::All)
    .with_server_frontends([
        ServerFrontend::Hub,
        ServerFrontend::Xet,
        ServerFrontend::Lfs,
    ])
    .unwrap()
    .with_token_signing_key(TEST_SIGNING_KEY.to_vec())
    .unwrap()
    .with_index_postgres_url(pg_url.to_owned())
    .unwrap()
    .with_reconstruction_cache_disabled();
    config.validate_runtime_requirements().unwrap();
    let app = app::router(config).await.unwrap();

    let token = {
        let provider = LocalHmacProvider::new(TEST_SIGNING_KEY).unwrap();
        let repo_s =
            RepositoryScope::new(RepositoryProvider::Generic, "test", "test", Some("main"))
                .unwrap();
        let claims =
            TokenClaims::new("shardline", "test", TokenScope::Write, repo_s, u64::MAX).unwrap();
        provider.mint_token(&claims).unwrap()
    };
    let _keep = Box::new(tmp);

    let repo = "test/test";

    // 1. Create repo via Hub API
    let hub_create = axum::http::Request::builder()
        .method("POST")
        .uri("/api/repos/create")
        .header("Authorization", format!("Bearer {token}"))
        .header("Content-Type", "application/json")
        .body(axum::body::Body::from(
            serde_json::to_vec(&serde_json::json!({"name": repo, "type": "model"})).unwrap(),
        ))
        .unwrap();
    let create_resp = app.clone().oneshot(hub_create).await.unwrap();
    assert_eq!(
        create_resp.status(),
        201,
        "Hub repo creation should succeed: {}",
        create_resp.status()
    );

    // 2. LFS batch request via standard LFS frontend
    let lfs_batch = axum::http::Request::builder()
        .method("POST")
        .uri("/v1/lfs/objects/batch")
        .header("Authorization", format!("Bearer {token}"))
        .header("Content-Type", "application/vnd.git-lfs+json")
        .body(axum::body::Body::from(
            serde_json::to_vec(&serde_json::json!({
                "operation": "download",
                "objects": [],
                "transfers": ["basic"]
            }))
            .unwrap(),
        ))
        .unwrap();
    let lfs_resp = app.clone().oneshot(lfs_batch).await.unwrap();
    assert_eq!(
        lfs_resp.status(),
        200,
        "LFS batch should succeed: {}",
        lfs_resp.status()
    );

    // 3. Xet read token via Xet frontend
    let xet_read = axum::http::Request::builder()
        .method("GET")
        .uri("/api/generic/test/test/xet-read-token/main")
        .header("Authorization", format!("Bearer {token}"))
        .body(axum::body::Body::empty())
        .unwrap();
    let xet_resp = app.clone().oneshot(xet_read).await.unwrap();
    // Should not be a 500 (may 404 on missing shard, but not crash)
    assert!(
        !xet_resp.status().is_server_error(),
        "Xet read should not 500: {}",
        xet_resp.status()
    );

    // 4. Healthz
    let health = app
        .clone()
        .oneshot(
            axum::http::Request::builder()
                .uri("/healthz")
                .body(axum::body::Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(health.status(), 200);

    // 5. Hub list repos
    let hub_list = axum::http::Request::builder()
        .method("GET")
        .uri("/api/repos")
        .header("Authorization", format!("Bearer {token}"))
        .body(axum::body::Body::empty())
        .unwrap();
    let list_resp = app.clone().oneshot(hub_list).await.unwrap();
    assert_eq!(
        list_resp.status(),
        200,
        "Hub list should succeed: {}",
        list_resp.status()
    );
    let body_bytes = axum::body::to_bytes(list_resp.into_body(), 1024 * 1024)
        .await
        .unwrap();
    let body_str = String::from_utf8_lossy(&body_bytes);
    assert!(
        body_str.contains("test/test"),
        "Hub repo list should contain created repo: {body_str}"
    );
}

// ===========================================================================
// 40. Graceful shutdown with timeout
// ===========================================================================

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_graceful_shutdown_with_timeout() {
    let pg_url = ensure_pg().await;
    let tmp = TempDir::new().unwrap();
    let chunk_size = NonZeroUsize::new(65536).unwrap();

    let config = ServerConfig::new(
        "127.0.0.1:0".parse().unwrap(),
        "http://127.0.0.1:8080".to_owned(),
        tmp.path().to_path_buf(),
        chunk_size,
    )
    .with_server_role(ServerRole::All)
    .with_server_frontends([ServerFrontend::Xet])
    .unwrap()
    .with_token_signing_key(TEST_SIGNING_KEY.to_vec())
    .unwrap()
    .with_index_postgres_url(pg_url.to_owned())
    .unwrap()
    .with_reconstruction_cache_disabled()
    .with_shutdown_timeout(Duration::from_millis(500));

    config.validate_runtime_requirements().unwrap();
    let app = app::router(config).await.unwrap();
    let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();

    let (shutdown_tx, shutdown_rx) = tokio::sync::oneshot::channel::<()>();
    let (done_tx, done_rx) = tokio::sync::oneshot::channel::<()>();

    tokio::spawn(async move {
        axum::serve(listener, app)
            .with_graceful_shutdown(async {
                shutdown_rx.await.ok();
            })
            .await
            .ok();
        done_tx.send(()).ok();
    });

    // Give server a moment to start
    tokio::time::sleep(Duration::from_millis(100)).await;

    // Trigger shutdown
    shutdown_tx.send(()).ok();

    // Server should exit within timeout + margin
    tokio::time::timeout(Duration::from_secs(10), done_rx)
        .await
        .expect("timeout: server should shut down within 10s")
        .expect("server task should complete");
}

// ===========================================================================
// 41. Graceful shutdown interrupts active upload
// ===========================================================================

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_graceful_shutdown_during_upload() {
    let pg_url = ensure_pg().await;
    let tmp = TempDir::new().unwrap();
    let chunk_size = NonZeroUsize::new(65536).unwrap();

    let config = ServerConfig::new(
        "127.0.0.1:0".parse().unwrap(),
        "http://127.0.0.1:8080".to_owned(),
        tmp.path().to_path_buf(),
        chunk_size,
    )
    .with_server_role(ServerRole::All)
    .with_server_frontends([ServerFrontend::Lfs])
    .unwrap()
    .with_token_signing_key(TEST_SIGNING_KEY.to_vec())
    .unwrap()
    .with_index_postgres_url(pg_url.to_owned())
    .unwrap()
    .with_reconstruction_cache_disabled()
    .with_shutdown_timeout(Duration::from_millis(500));

    config.validate_runtime_requirements().unwrap();
    let app = app::router(config).await.unwrap();
    let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
    let addr = listener.local_addr().unwrap();
    let base_url = format!("http://{addr}");
    let token = {
        let provider = LocalHmacProvider::new(TEST_SIGNING_KEY).unwrap();
        let repository =
            RepositoryScope::new(RepositoryProvider::Generic, "test", "test", Some("main"))
                .unwrap();
        let claims =
            TokenClaims::new("shardline", "test", TokenScope::Write, repository, u64::MAX).unwrap();
        provider.mint_token(&claims).unwrap()
    };

    let (shutdown_tx, shutdown_rx) = tokio::sync::oneshot::channel::<()>();
    let (server_done_tx, server_done_rx) = tokio::sync::oneshot::channel::<()>();

    // Start the shutdown timeout only after the shutdown signal. After that
    // timeout, dropping the serve future force-closes in-flight connections.
    let shutdown_timeout = Duration::from_millis(500);
    let (shutdown_started_tx, shutdown_started_rx) = tokio::sync::oneshot::channel::<()>();
    tokio::spawn(async move {
        let serve = axum::serve(listener, app).with_graceful_shutdown(async {
            shutdown_rx.await.ok();
            shutdown_started_tx.send(()).ok();
        });
        tokio::select! {
            result = serve => { result.ok(); }
            () = async {
                if shutdown_started_rx.await.is_ok() {
                    tokio::time::sleep(shutdown_timeout).await;
                } else {
                    std::future::pending::<()>().await;
                }
            } => {
                // Dropped — connections force-closed
            }
        }
        server_done_tx.send(()).ok();
    });

    // Give server a moment to start.
    tokio::time::sleep(Duration::from_millis(100)).await;

    // Start a slow LFS upload. Yield an initial byte so the handler begins
    // consuming the request, then keep the stream pending to hold the upload
    // in flight while shutdown begins.
    let client = reqwest::Client::builder()
        // A force-closed connection should fail promptly after the server's
        // 500 ms shutdown deadline; do not let a stalled client hide that.
        .timeout(Duration::from_secs(3))
        .build()
        .unwrap();

    let (body_started_tx, body_started_rx) = tokio::sync::oneshot::channel::<()>();
    let slow_stream = stream::once(async move {
        body_started_tx.send(()).ok();
        Ok::<_, reqwest::Error>(bytes::Bytes::from_static(b"x"))
    })
    .chain(stream::once(async {
        tokio::time::sleep(Duration::from_secs(60)).await;
        Ok::<_, reqwest::Error>(bytes::Bytes::from_static(b"y"))
    }));

    let oid = sha256_hex(b"xy");
    let upload_handle = tokio::spawn(async move {
        client
            .put(&format!("{base_url}/v1/lfs/objects/{oid}"))
            .header("Authorization", format!("Bearer {token}"))
            .header("Content-Type", "application/octet-stream")
            .body(reqwest::Body::wrap_stream(slow_stream))
            .send()
            .await
    });

    tokio::time::timeout(Duration::from_secs(2), body_started_rx)
        .await
        .expect("upload request body should begin streaming")
        .expect("upload body stream should not be cancelled before shutdown");
    tokio::time::sleep(Duration::from_millis(50)).await;

    // Trigger shutdown while upload is in-flight.
    shutdown_tx.send(()).ok();

    // Server should exit within the select! timeout + margin.
    tokio::time::timeout(Duration::from_secs(10), server_done_rx)
        .await
        .expect("timeout: server should shut down within 10s")
        .expect("server task should complete");

    // The upload request should fail or get a server error since the connection
    // was force-closed when the serve future was dropped.
    let upload_result = upload_handle.await.unwrap();
    assert!(
        upload_result.is_err() || upload_result.as_ref().unwrap().status().is_server_error(),
        "upload should be interrupted by shutdown, got: {upload_result:?}"
    );
}

// ===========================================================================
// 42. CORS headers on LFS protocol frontend
// ===========================================================================

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_cors_headers_on_lfs_endpoint() {
    let pg_url = ensure_pg().await;
    let tmp = TempDir::new().unwrap();
    let chunk_size = NonZeroUsize::new(65536).unwrap();
    let config = ServerConfig::new(
        "127.0.0.1:0".parse().unwrap(),
        "http://127.0.0.1:8080".to_owned(),
        tmp.path().to_path_buf(),
        chunk_size,
    )
    .with_server_role(ServerRole::All)
    .with_server_frontends([ServerFrontend::Lfs])
    .unwrap()
    .with_token_signing_key(TEST_SIGNING_KEY.to_vec())
    .unwrap()
    .with_index_postgres_url(pg_url.to_owned())
    .unwrap()
    .with_reconstruction_cache_disabled();
    config.validate_runtime_requirements().unwrap();
    let app = app::router(config).await.unwrap();

    let _token = {
        let provider = LocalHmacProvider::new(TEST_SIGNING_KEY).unwrap();
        let repo_s =
            RepositoryScope::new(RepositoryProvider::Generic, "test", "test", Some("main"))
                .unwrap();
        let claims =
            TokenClaims::new("shardline", "test", TokenScope::Read, repo_s, u64::MAX).unwrap();
        provider.mint_token(&claims).unwrap()
    };
    let _keep = Box::new(tmp);

    // OPTIONS preflight request to LFS batch endpoint
    let resp = app
        .clone()
        .oneshot(
            axum::http::Request::builder()
                .method("OPTIONS")
                .uri("/v1/lfs/objects/batch")
                .header("Origin", "http://example.com")
                .header("Access-Control-Request-Method", "POST")
                .body(axum::body::Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();

    let cors_header = resp.headers().get("access-control-allow-origin");
    assert!(
        cors_header.is_some(),
        "LFS response should include Access-Control-Allow-Origin header"
    );
    assert_eq!(
        cors_header.unwrap().to_str().unwrap(),
        "*",
        "LFS should allow all origins"
    );

    // Also verify a normal GET request includes CORS headers
    let get_resp = app
        .clone()
        .oneshot(
            axum::http::Request::builder()
                .method("GET")
                .uri("/healthz")
                .header("Origin", "http://other-origin.com")
                .body(axum::body::Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    let health_cors = get_resp.headers().get("access-control-allow-origin");
    assert!(
        health_cors.is_some(),
        "Healthz should also include CORS headers"
    );
}

// ===========================================================================
// 43. Concurrent cross-protocol upload of same content
// ===========================================================================

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_concurrent_cross_protocol_upload_same_hash() {
    let pg_url = ensure_pg().await;
    let tmp = TempDir::new().unwrap();
    let chunk_size = NonZeroUsize::new(65536).unwrap();
    let config = ServerConfig::new(
        "127.0.0.1:0".parse().unwrap(),
        "http://127.0.0.1:8080".to_owned(),
        tmp.path().to_path_buf(),
        chunk_size,
    )
    .with_server_role(ServerRole::All)
    .with_server_frontends([ServerFrontend::Lfs, ServerFrontend::BazelHttp])
    .unwrap()
    .with_token_signing_key(TEST_SIGNING_KEY.to_vec())
    .unwrap()
    .with_index_postgres_url(pg_url.to_owned())
    .unwrap()
    .with_reconstruction_cache_disabled();
    config.validate_runtime_requirements().unwrap();
    let app = Arc::new(app::router(config).await.unwrap());

    let token = {
        let provider = LocalHmacProvider::new(TEST_SIGNING_KEY).unwrap();
        let repo_s =
            RepositoryScope::new(RepositoryProvider::Generic, "test", "test", Some("main"))
                .unwrap();
        let claims =
            TokenClaims::new("shardline", "test", TokenScope::Write, repo_s, u64::MAX).unwrap();
        provider.mint_token(&claims).unwrap()
    };
    let _keep = Box::new(tmp);

    let content = b"cross-protocol-race-content";
    let hash = sha256_hex(content);
    let token_arc = Arc::new(token);
    let hash_arc = Arc::new(hash);
    let content_arc = Arc::new(content.to_vec());

    // Fire both uploads concurrently
    let app1 = app.clone();
    let token1 = token_arc.clone();
    let hash1 = hash_arc.clone();
    let content1 = content_arc.clone();
    let bazel_handle = tokio::spawn(async move {
        let req = axum::http::Request::builder()
            .method("PUT")
            .uri(&format!("/v1/bazel/cache/cas/{hash1}"))
            .header("Authorization", format!("Bearer {token1}"))
            .header("Content-Type", "application/octet-stream")
            .body(axum::body::Body::from(content1.to_vec()))
            .unwrap();
        app1.as_ref().clone().oneshot(req).await
    });

    let app2 = app.clone();
    let token2 = token_arc.clone();
    let content2 = content_arc.clone();
    let hash2 = hash_arc.clone();
    let lfs_handle = tokio::spawn(async move {
        // Use LFS upload — PUT with the same content hash as Bazel
        let req = axum::http::Request::builder()
            .method("PUT")
            .uri(&format!("/v1/lfs/objects/{hash2}"))
            .header("Authorization", format!("Bearer {token2}"))
            .header("Content-Type", "application/octet-stream")
            .body(axum::body::Body::from(content2.to_vec()))
            .unwrap();
        app2.as_ref().clone().oneshot(req).await
    });

    let bazel_resp = bazel_handle.await.unwrap().unwrap();
    let lfs_resp = lfs_handle.await.unwrap().unwrap();

    assert!(
        bazel_resp.status().is_success(),
        "Bazel upload should succeed: {}",
        bazel_resp.status()
    );
    assert!(
        lfs_resp.status().is_success(),
        "LFS upload should succeed: {}",
        lfs_resp.status()
    );

    // Verify content is retrievable via Bazel CAS
    let get_req = axum::http::Request::builder()
        .method("GET")
        .uri(&format!("/v1/bazel/cache/cas/{hash_arc}"))
        .header("Authorization", format!("Bearer {token_arc}"))
        .body(axum::body::Body::empty())
        .unwrap();
    let get_resp = app.as_ref().clone().oneshot(get_req).await.unwrap();
    assert_eq!(
        get_resp.status(),
        200,
        "Bazel CAS GET should return content"
    );
    let get_body = axum::body::to_bytes(get_resp.into_body(), usize::MAX)
        .await
        .unwrap();
    assert_eq!(get_body.as_ref(), content_arc.as_slice());
}