grpc_graphql_gateway 1.2.4

A Rust implementation of gRPC-GraphQL gateway - generates GraphQL execution code from gRPC services
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
//! Runtime support for GraphQL gateway - HTTP and WebSocket integration.

use crate::analytics::{AnalyticsConfig, SharedQueryAnalytics};
use crate::cache::{CacheConfig, CacheLookupResult, SharedResponseCache};
use crate::circuit_breaker::{CircuitBreakerConfig, SharedCircuitBreakerRegistry};
use crate::compression::{create_compression_layer, CompressionConfig};
use crate::defer::{
    extract_deferred_fragments, format_initial_part, format_subsequent_part, has_defer_directive,
    strip_defer_directives, DeferConfig, DeferredExecution, DeferredPart, MULTIPART_CONTENT_TYPE,
};
use crate::error::{GraphQLError, Result};
use crate::grpc_client::GrpcClientPool;
use crate::health::{health_handler, readiness_handler, HealthState};
use crate::high_performance::{
    pin_to_core, recommended_workers, FastJsonParser, HighPerfConfig, PerfMetrics,
    ResponseTemplates, ShardedCache,
};
use crate::metrics::GatewayMetrics;
use crate::middleware::{Context, Middleware};
use crate::persisted_queries::{
    process_apq_request, PersistedQueryConfig, PersistedQueryError, SharedPersistedQueryStore,
};
use crate::plugin::PluginRegistry;
use crate::query_whitelist::{QueryWhitelistConfig, SharedQueryWhitelist};
use crate::request_collapsing::{RequestCollapsingConfig, SharedRequestCollapsingRegistry};
use crate::schema::{DynamicSchema, GrpcResponseCache};
use async_graphql::{futures_util::stream::BoxStream, Data, ServerError};
use async_graphql_axum::{GraphQLProtocol, GraphQLRequest, GraphQLResponse, GraphQLWebSocket};
use axum::{
    extract::{
        ws::{Message, WebSocket, WebSocketUpgrade},
        State,
    },
    http::HeaderMap,
    response::{Html, IntoResponse, Json},
    routing::{get, post},
    Extension, Router,
};
use bytes::Bytes;
use futures::{SinkExt, StreamExt};
use std::any::TypeId;
use std::collections::HashSet;
use std::sync::Arc;
use std::time::{Duration, Instant};

/// ServeMux - main gateway handler
///
/// The `ServeMux` handles the routing of GraphQL requests, executing middlewares,
/// and invoking the dynamic schema. It can be converted into an Axum router.
pub struct ServeMux {
    schema: DynamicSchema,
    middlewares: Vec<Arc<dyn Middleware>>,
    error_handler: Option<Arc<dyn Fn(Vec<GraphQLError>) + Send + Sync>>,
    /// gRPC client pool for health checks
    client_pool: Option<GrpcClientPool>,
    /// Enable health check endpoints
    health_checks_enabled: bool,
    /// Enable metrics endpoint
    metrics_enabled: bool,
    /// Enable GraphQL Playground
    playground_enabled: bool,
    /// APQ store for persisted queries
    apq_store: Option<SharedPersistedQueryStore>,
    /// Circuit breaker registry
    circuit_breaker: Option<SharedCircuitBreakerRegistry>,
    /// Response cache
    response_cache: Option<SharedResponseCache>,
    /// Response compression configuration
    compression_config: Option<CompressionConfig>,
    /// Query whitelist for security
    query_whitelist: Option<SharedQueryWhitelist>,
    /// Query analytics engine
    analytics: Option<SharedQueryAnalytics>,
    /// Request collapsing registry for deduplication
    request_collapsing: Option<SharedRequestCollapsingRegistry>,
    /// High-performance configuration
    high_perf_config: Option<HighPerfConfig>,
    /// Fast JSON parser (SIMD-accelerated)
    json_parser: Arc<FastJsonParser>,
    /// High-performance sharded cache
    sharded_cache: Option<Arc<ShardedCache<Bytes>>>,
    /// Performance metrics tracking
    perf_metrics: Arc<PerfMetrics>,
    /// Pre-computed response templates
    response_templates: Arc<ResponseTemplates>,
    /// @defer incremental delivery configuration
    defer_config: Option<DeferConfig>,
    /// Plugin registry for extension hooks
    plugins: PluginRegistry,
}

const STRICT_API_CSP: &str =
    "default-src 'none'; frame-ancestors 'none'; base-uri 'none'; form-action 'none'";
const PLAYGROUND_CSP: &str = "default-src 'self'; script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net https://unpkg.com; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self' ws: wss:; object-src 'none'; base-uri 'self'; frame-ancestors 'none'; form-action 'self'";

fn parse_cors_allowed_origin(raw: Option<&str>) -> Option<axum::http::HeaderValue> {
    let origin = raw?.trim();
    if origin.is_empty() {
        return None;
    }

    if origin != "*" {
        let parsed = reqwest::Url::parse(origin).ok()?;
        if !matches!(parsed.scheme(), "http" | "https") {
            return None;
        }
        if parsed.host_str().is_none()
            || !parsed.username().is_empty()
            || parsed.password().is_some()
        {
            return None;
        }
        if parsed.path() != "/" || parsed.query().is_some() || parsed.fragment().is_some() {
            return None;
        }
    }

    axum::http::HeaderValue::from_str(origin).ok()
}

fn configured_cors_allow_origin() -> Option<axum::http::HeaderValue> {
    parse_cors_allowed_origin(std::env::var("CORS_ALLOWED_ORIGIN").ok().as_deref())
}

fn content_security_policy(playground_enabled: bool) -> &'static str {
    if playground_enabled {
        PLAYGROUND_CSP
    } else {
        STRICT_API_CSP
    }
}

#[derive(Clone, Debug)]
struct WebSocketSessionHeaders {
    headers: HeaderMap,
}

#[derive(Clone, Copy, Debug)]
struct LiveQueryRequestMarker;

fn is_forbidden_ws_connection_header(name: &str) -> bool {
    matches!(
        name.to_ascii_lowercase().as_str(),
        "connection"
            | "content-length"
            | "forwarded"
            | "host"
            | "origin"
            | "sec-websocket-extensions"
            | "sec-websocket-key"
            | "sec-websocket-protocol"
            | "sec-websocket-version"
            | "upgrade"
            | "x-forwarded-for"
            | "x-real-ip"
    )
}

fn json_value_to_header_string(value: &serde_json::Value) -> Option<String> {
    match value {
        serde_json::Value::String(s) => Some(s.clone()),
        serde_json::Value::Number(n) => Some(n.to_string()),
        serde_json::Value::Bool(b) => Some(b.to_string()),
        _ => None,
    }
}

fn merge_ws_connection_header_values(
    headers: &mut HeaderMap,
    values: &serde_json::Map<String, serde_json::Value>,
) {
    for (key, value) in values {
        if is_forbidden_ws_connection_header(key) {
            continue;
        }

        let Some(value_str) = json_value_to_header_string(value) else {
            continue;
        };

        let Ok(header_name) = axum::http::HeaderName::from_bytes(key.as_bytes()) else {
            continue;
        };
        let Ok(header_value) = axum::http::HeaderValue::from_str(&value_str) else {
            continue;
        };

        headers.insert(header_name, header_value);
    }
}

fn merge_ws_connection_init_headers(
    base_headers: &HeaderMap,
    payload: &serde_json::Value,
) -> HeaderMap {
    let mut headers = base_headers.clone();
    let Some(payload_obj) = payload.as_object() else {
        return headers;
    };

    if let Some(nested_headers) = payload_obj
        .get("headers")
        .and_then(|value| value.as_object())
    {
        merge_ws_connection_header_values(&mut headers, nested_headers);
    }

    merge_ws_connection_header_values(&mut headers, payload_obj);

    headers
}

fn ws_session_headers(session_data: Option<&Arc<Data>>) -> HeaderMap {
    session_data
        .and_then(|data| data.get(&TypeId::of::<WebSocketSessionHeaders>()))
        .and_then(|value| value.downcast_ref::<WebSocketSessionHeaders>())
        .map(|session| session.headers.clone())
        .unwrap_or_default()
}

#[derive(Clone)]
struct SubscriptionExecutor {
    mux: Arc<ServeMux>,
}

impl SubscriptionExecutor {
    fn new(mux: Arc<ServeMux>) -> Self {
        Self { mux }
    }
}

#[async_trait::async_trait]
impl async_graphql::Executor for SubscriptionExecutor {
    async fn execute(&self, request: async_graphql::Request) -> async_graphql::Response {
        self.mux.schema.execute(request).await
    }

    fn execute_stream(
        &self,
        request: async_graphql::Request,
        session_data: Option<Arc<Data>>,
    ) -> BoxStream<'static, async_graphql::Response> {
        let mux = self.mux.clone();

        Box::pin(async_stream::stream! {
            let headers = ws_session_headers(session_data.as_ref());

            let request = match mux.prepare_graphql_request(request) {
                Ok(request) => request,
                Err(response) => {
                    yield response;
                    return;
                }
            };

            let ctx = match mux.prepare_execution_context(&headers).await {
                Ok(ctx) => ctx,
                Err(err) => {
                    yield async_graphql::Response::from_errors(vec![ServerError::new(err.to_string(), None)]);
                    return;
                }
            };

            if let Err(err) = mux.plugins.on_request(&ctx, &request).await {
                yield async_graphql::Response::from_errors(vec![ServerError::new(err.to_string(), None)]);
                return;
            }

            let request = request
                .data(ctx.clone())
                .data(mux.plugins.clone())
                .data(GrpcResponseCache::default());

            let schema_executor = mux.schema.executor();
            let stream =
                async_graphql::Executor::execute_stream(&schema_executor, request, session_data);
            futures::pin_mut!(stream);

            while let Some(response) = stream.next().await {
                if let Err(err) = mux.plugins.on_response(&ctx, &response).await {
                    yield async_graphql::Response::from_errors(vec![ServerError::new(err.to_string(), None)]);
                    break;
                }

                yield response;
            }
        })
    }
}

impl ServeMux {
    /// Create a new ServeMux with an already built schema
    pub fn new(schema: DynamicSchema) -> Self {
        Self {
            schema,
            middlewares: Vec::new(),
            error_handler: None,
            client_pool: None,
            health_checks_enabled: false,
            metrics_enabled: false,
            playground_enabled: std::env::var("ENABLE_GRAPHQL_PLAYGROUND")
                .map(|v| v == "true" || v == "1")
                .unwrap_or(false),
            apq_store: None,
            circuit_breaker: None,
            response_cache: None,
            compression_config: None,
            query_whitelist: None,
            analytics: None,
            request_collapsing: None,
            high_perf_config: None,
            json_parser: Arc::new(FastJsonParser::default()),
            sharded_cache: None,
            perf_metrics: Arc::new(PerfMetrics::default()),
            response_templates: Arc::new(ResponseTemplates::new()),
            defer_config: None,
            plugins: PluginRegistry::new(),
        }
    }

    /// Set the gRPC client pool (needed for health checks)
    pub fn set_client_pool(&mut self, pool: GrpcClientPool) {
        self.client_pool = Some(pool);
    }

    /// Enable health check endpoints
    pub fn enable_health_checks(&mut self) {
        self.health_checks_enabled = true;
    }

    /// Enable metrics endpoint
    pub fn enable_metrics(&mut self) {
        self.metrics_enabled = true;
    }

    /// Enable GraphQL Playground
    pub fn enable_playground(&mut self) {
        self.playground_enabled = true;
    }

    /// Enable Automatic Persisted Queries (APQ)
    pub fn enable_persisted_queries(&mut self, config: PersistedQueryConfig) {
        self.apq_store = Some(crate::persisted_queries::create_apq_store(config));
    }

    /// Enable Circuit Breaker for gRPC backend resilience
    pub fn enable_circuit_breaker(&mut self, config: CircuitBreakerConfig) {
        self.circuit_breaker = Some(crate::circuit_breaker::create_circuit_breaker_registry(
            config,
        ));
    }

    /// Get the circuit breaker registry (if enabled)
    pub fn circuit_breaker(&self) -> Option<&SharedCircuitBreakerRegistry> {
        self.circuit_breaker.as_ref()
    }

    /// Enable response caching
    pub fn enable_response_cache(&mut self, config: CacheConfig) {
        self.response_cache = Some(crate::cache::create_response_cache(config));
    }

    /// Get the response cache (if enabled)
    pub fn response_cache(&self) -> Option<&SharedResponseCache> {
        self.response_cache.as_ref()
    }

    /// Enable response compression
    pub fn enable_compression(&mut self, config: CompressionConfig) {
        self.compression_config = Some(config);
    }

    /// Get the compression config (if enabled)
    pub fn compression_config(&self) -> Option<&CompressionConfig> {
        self.compression_config.as_ref()
    }

    /// Enable query whitelist
    pub fn enable_query_whitelist(&mut self, config: QueryWhitelistConfig) {
        self.query_whitelist = Some(Arc::new(crate::query_whitelist::QueryWhitelist::new(
            config,
        )));
    }

    /// Get the query whitelist (if enabled)
    pub fn query_whitelist(&self) -> Option<&SharedQueryWhitelist> {
        self.query_whitelist.as_ref()
    }

    /// Enable query analytics
    pub fn enable_analytics(&mut self, config: AnalyticsConfig) {
        self.analytics = Some(crate::analytics::create_analytics(config));
    }

    /// Get the analytics engine (if enabled)
    pub fn analytics(&self) -> Option<&SharedQueryAnalytics> {
        self.analytics.as_ref()
    }

    /// Enable request collapsing for deduplicating identical gRPC calls
    pub fn enable_request_collapsing(&mut self, config: RequestCollapsingConfig) {
        self.request_collapsing =
            Some(crate::request_collapsing::create_request_collapsing_registry(config));
    }

    /// Get the request collapsing registry (if enabled)
    pub fn request_collapsing(&self) -> Option<&SharedRequestCollapsingRegistry> {
        self.request_collapsing.as_ref()
    }

    /// Enable high-performance optimizations for 100K+ RPS
    pub fn enable_high_performance(&mut self, config: HighPerfConfig) {
        self.json_parser = Arc::new(FastJsonParser::new(config.buffer_pool_size));
        self.sharded_cache = Some(Arc::new(ShardedCache::new(
            config.cache_shards,
            config.max_entries_per_shard,
        )));

        // Optional CPU affinity pinning
        if config.cpu_affinity {
            let num_cores = recommended_workers();
            for i in 0..num_cores {
                // Pinning usually happens in thread creation, but we can try for current
                let _ = pin_to_core(i);
            }
        }

        self.high_perf_config = Some(config);
    }

    /// Get high-performance metrics
    pub fn perf_metrics(&self) -> &PerfMetrics {
        &self.perf_metrics
    }

    /// Enable `@defer` incremental delivery
    pub fn enable_defer(&mut self, config: DeferConfig) {
        self.defer_config = Some(config);
    }

    /// Get the defer config (if enabled)
    pub fn defer_config(&self) -> Option<&DeferConfig> {
        self.defer_config.as_ref()
    }

    /// Add middleware to the execution pipeline
    ///
    /// Middlewares are executed in the order they are added.
    pub fn add_middleware(&mut self, middleware: Arc<dyn Middleware>) {
        self.middlewares.push(middleware);
    }

    /// Use middleware (builder pattern)
    pub fn with_middleware(mut self, middleware: Arc<dyn Middleware>) -> Self {
        self.add_middleware(middleware);
        self
    }

    /// Set error handler from an `Arc` for cases where the caller already shares ownership.
    pub fn set_error_handler_arc(&mut self, handler: Arc<dyn Fn(Vec<GraphQLError>) + Send + Sync>) {
        self.error_handler = Some(handler);
    }

    /// Set error handler
    pub fn set_error_handler<F>(&mut self, handler: F)
    where
        F: Fn(Vec<GraphQLError>) + Send + Sync + 'static,
    {
        self.set_error_handler_arc(Arc::new(handler));
    }

    pub fn set_plugins(&mut self, plugins: PluginRegistry) {
        self.plugins = plugins;
    }

    async fn prepare_execution_context(&self, headers: &HeaderMap) -> Result<Context> {
        let mut ctx = Context {
            headers: headers.clone(),
            extensions: std::collections::HashMap::new(),
            request_start: std::time::Instant::now(),
            request_id: headers
                .get("x-request-id")
                .and_then(|v| v.to_str().ok())
                .map(String::from)
                .unwrap_or_else(|| uuid::Uuid::new_v4().to_string()),
            client_ip: headers
                .get("x-forwarded-for")
                .and_then(|v| v.to_str().ok())
                .and_then(|s| s.split(',').next())
                .map(|s| s.trim().to_string())
                .filter(|ip| ip.parse::<std::net::IpAddr>().is_ok())
                .or_else(|| {
                    headers
                        .get("x-real-ip")
                        .and_then(|v| v.to_str().ok())
                        .map(String::from)
                        .filter(|ip| ip.parse::<std::net::IpAddr>().is_ok())
                }),
            encryption_key: None,
        };

        for middleware in &self.middlewares {
            middleware.call(&mut ctx).await?;
        }

        Ok(ctx)
    }

    fn prepare_graphql_request(
        &self,
        request: async_graphql::Request,
    ) -> std::result::Result<async_graphql::Request, async_graphql::Response> {
        let processed_request = if let Some(ref apq_store) = self.apq_store {
            match self.process_apq_request(apq_store, request) {
                Ok(req) => req,
                Err(apq_err) => {
                    return Err(self.apq_error_response(apq_err));
                }
            }
        } else {
            request
        };

        if let Err(err) = crate::waf::validate_request(&processed_request) {
            tracing::warn!("WAF blocked request: {}", err);
            let mut server_err = ServerError::new(err.to_string(), None);
            server_err.extensions = Some({
                let mut ext = async_graphql::ErrorExtensionValues::default();
                ext.set("code", "VALIDATION_ERROR");
                ext
            });
            return Err(async_graphql::Response::from_errors(vec![server_err]));
        }

        if let Some(ref whitelist) = self.query_whitelist {
            let operation_id = processed_request
                .extensions
                .get("operationId")
                .and_then(|v| serde_json::to_value(v).ok())
                .and_then(|v| v.as_str().map(String::from));

            if let Err(err) =
                whitelist.validate_query(&processed_request.query, operation_id.as_deref())
            {
                tracing::warn!("Query whitelist validation failed: {}", err);
                let mut server_err = ServerError::new(err.to_string(), None);
                server_err.extensions = Some({
                    let mut ext = async_graphql::ErrorExtensionValues::default();
                    ext.set("code", "QUERY_NOT_WHITELISTED");
                    ext
                });
                return Err(async_graphql::Response::from_errors(vec![server_err]));
            }
        }

        Ok(processed_request)
    }

    async fn execute_with_middlewares(
        &self,
        headers: HeaderMap,
        request: async_graphql::Request,
    ) -> Result<async_graphql::Response> {
        let ctx = self.prepare_execution_context(&headers).await?;

        // Plugin Hook: on_request
        self.plugins.on_request(&ctx, &request).await?;

        let mut gql_request = request;
        // Make context available to resolvers via data
        gql_request = gql_request.data(ctx.clone());
        gql_request = gql_request.data(self.plugins.clone());
        gql_request = gql_request.data(GrpcResponseCache::default());

        let response = self.schema.execute(gql_request).await;

        // Plugin Hook: on_response
        self.plugins.on_response(&ctx, &response).await?;

        Ok(response)
    }

    /// Handle GraphQL HTTP request
    ///
    /// This method executes the request pipeline:
    /// 1. Process APQ (if enabled) - lookup/cache query by hash
    /// 2. Check response cache (if enabled) - return cached response if available
    /// 3. Creates a context from headers
    /// 4. Runs all middlewares
    /// 5. Executes the GraphQL query against the schema
    /// 6. Caches response (if cacheable)
    /// 7. Handles any errors
    pub async fn handle_http(
        &self,
        headers: HeaderMap,
        request: async_graphql::Request,
    ) -> async_graphql::Response {
        let mut processed_request = match self.prepare_graphql_request(request) {
            Ok(request) => request,
            Err(response) => return response,
        };

        // Handle @live directive - detect and strip before execution
        // The @live directive indicates the client wants live/reactive updates
        let is_live_query = crate::live_query::has_live_directive(&processed_request.query)
            || processed_request
                .data
                .contains_key(&TypeId::of::<LiveQueryRequestMarker>());
        if crate::live_query::has_live_directive(&processed_request.query) {
            // Strip the @live directive so async-graphql doesn't reject it
            let stripped_query = crate::live_query::strip_live_directive(&processed_request.query);
            tracing::debug!(
                is_live = is_live_query,
                "Live query detected, stripping @live directive"
            );
            let mut rebuilt_request = async_graphql::Request::new(stripped_query);
            rebuilt_request.operation_name = processed_request.operation_name;
            rebuilt_request.variables = processed_request.variables;
            rebuilt_request.uploads = processed_request.uploads;
            rebuilt_request.data = processed_request.data;
            rebuilt_request.extensions = processed_request.extensions;
            rebuilt_request.introspection_mode = processed_request.introspection_mode;
            processed_request = rebuilt_request;
        }

        // Live queries must always observe fresh state. Caching them causes stale
        // re-executions after invalidation events, which breaks the update stream.
        let bypass_response_cache = is_live_query;

        // Check if this is a mutation (mutations are never cached and trigger invalidation)
        let is_mutation = crate::cache::is_mutation(&processed_request.query);
        let operation_type = if is_mutation { "mutation" } else { "query" };

        // Store analytics info before processing
        let analytics_query = processed_request.query.clone();
        let analytics_op_name = processed_request.operation_name.clone();
        let request_start = Instant::now();

        // Extract vary headers for cache key generation
        let vary_header_values = if let Some(ref cache) = self.response_cache {
            cache
                .config
                .vary_headers
                .iter()
                .map(|h| {
                    let val = headers.get(h).and_then(|v| v.to_str().ok()).unwrap_or("");
                    format!("{}:{}", h, val)
                })
                .collect::<Vec<_>>()
        } else {
            Vec::new()
        };

        // Try cache lookup for non-mutations
        if !is_mutation && !bypass_response_cache {
            if let Some(ref cache) = self.response_cache {
                let cache_key = crate::cache::ResponseCache::generate_cache_key(
                    &processed_request.query,
                    Some(&serde_json::to_value(&processed_request.variables).unwrap_or_default()),
                    processed_request.operation_name.as_deref(),
                    &vary_header_values,
                );

                match cache.get(&cache_key).await {
                    CacheLookupResult::Hit(cached) => {
                        tracing::debug!("Response cache hit");
                        // Track cache hit in analytics
                        if let Some(ref analytics) = self.analytics {
                            analytics.record_cache_access(true);
                            analytics.record_query(
                                &analytics_query,
                                analytics_op_name.as_deref(),
                                operation_type,
                                request_start.elapsed(),
                                false,
                                None,
                            );
                        }
                        return self.cached_to_response(cached.data);
                    }
                    CacheLookupResult::Stale(cached) => {
                        // Return stale immediately, could trigger background revalidation
                        // For simplicity, we just return stale data
                        tracing::debug!("Response cache stale hit");
                        // Track stale hit as a hit
                        if let Some(ref analytics) = self.analytics {
                            analytics.record_cache_access(true);
                            analytics.record_query(
                                &analytics_query,
                                analytics_op_name.as_deref(),
                                operation_type,
                                request_start.elapsed(),
                                false,
                                None,
                            );
                        }
                        return self.cached_to_response(cached.data);
                    }
                    CacheLookupResult::Miss => {
                        // Track cache miss
                        if let Some(ref analytics) = self.analytics {
                            analytics.record_cache_access(false);
                        }
                    }
                }
            }
        }

        // Store query info for potential caching (need this before moving processed_request)
        let cache_query_info =
            if self.response_cache.is_some() && !is_mutation && !bypass_response_cache {
                Some((
                    processed_request.query.clone(),
                    serde_json::to_value(&processed_request.variables).unwrap_or_default(),
                    processed_request.operation_name.clone(),
                ))
            } else {
                None
            };

        // Execute the query
        match self
            .execute_with_middlewares(headers, processed_request)
            .await
        {
            Ok(resp) => {
                let duration = request_start.elapsed();
                let had_error = !resp.errors.is_empty();

                // Track in analytics
                if let Some(ref analytics) = self.analytics {
                    let error_details = if had_error {
                        resp.errors.first().map(|e| {
                            let code = e
                                .extensions
                                .as_ref()
                                .and_then(|ext| ext.get("code"))
                                .map(|c| c.to_string())
                                .unwrap_or_else(|| "GRAPHQL_ERROR".to_string());
                            (code, e.message.clone())
                        })
                    } else {
                        None
                    };

                    analytics.record_query(
                        &analytics_query,
                        analytics_op_name.as_deref(),
                        operation_type,
                        duration,
                        had_error,
                        error_details
                            .as_ref()
                            .map(|(c, m)| (c.as_str(), m.as_str())),
                    );
                }

                // Handle mutation cache invalidation
                if is_mutation {
                    if let Some(ref cache) = self.response_cache {
                        if let Ok(resp_json) = serde_json::to_value(&resp) {
                            cache.invalidate_for_mutation(&resp_json).await;
                        }
                    }
                    if let Some(ref sharded) = self.sharded_cache {
                        sharded.clear(); // Simple invalidation for sharded cache on mutation
                    }
                } else if let Some((query, vars, op_name)) = cache_query_info {
                    // Cache the response for queries
                    if let Some(ref cache) = self.response_cache {
                        let cache_key = crate::cache::ResponseCache::generate_cache_key(
                            &query,
                            Some(&vars),
                            op_name.as_deref(),
                            &vary_header_values,
                        );

                        if let Ok(resp_json) = serde_json::to_value(&resp) {
                            // Extract types and entities for invalidation tracking
                            let types = extract_types_from_response(&resp_json);
                            let entities = extract_entities_from_response(&resp_json);
                            cache
                                .put(cache_key.clone(), resp_json.clone(), types, entities)
                                .await;

                            // Explicitly cache entities (Cache by Field result)
                            cache.put_all_entities(&resp_json, None).await;

                            // Also cache in sharded cache if enabled
                            if let Some(ref sharded) = self.sharded_cache {
                                if let Ok(resp_bytes) = self.json_parser.serialize(&resp) {
                                    sharded.insert(&cache_key, resp_bytes, Duration::from_secs(60));
                                }
                            }
                        }
                    }
                }
                resp
            }
            Err(err) => {
                let duration = request_start.elapsed();
                let gql_err: GraphQLError = err.into();

                // Track error in analytics
                if let Some(ref analytics) = self.analytics {
                    analytics.record_query(
                        &analytics_query,
                        analytics_op_name.as_deref(),
                        operation_type,
                        duration,
                        true,
                        Some(("INTERNAL_ERROR", &gql_err.message)),
                    );
                }

                if let Some(handler) = &self.error_handler {
                    handler(vec![gql_err.clone()]);
                }
                let server_err = ServerError::new(gql_err.message.clone(), None);
                async_graphql::Response::from_errors(vec![server_err])
            }
        }
    }

    /// High-performance GraphQL handler for maximum throughput
    pub async fn handle_fast(&self, headers: HeaderMap, body: Bytes) -> axum::response::Response {
        let start = Instant::now();

        // 1. SIMD JSON parsing
        let request_val = match self.json_parser.parse_bytes(&body) {
            Ok(v) => v,
            Err(err) => {
                tracing::warn!("Failed to parse JSON with SIMD: {}", err);
                return (
                    axum::http::StatusCode::BAD_REQUEST,
                    [(axum::http::header::CONTENT_TYPE, "application/json")],
                    self.response_templates
                        .errors
                        .get("PARSE_ERROR")
                        .cloned()
                        .unwrap_or_else(|| {
                            Bytes::from(r#"{"errors":[{"message":"Invalid JSON"}]}"#)
                        }),
                )
                    .into_response();
            }
        };

        let query = request_val["query"].as_str().unwrap_or("");
        let variables = &request_val["variables"];
        let operation_name = request_val["operationName"].as_str();

        // 2. High-performance cache lookup
        if let Some(ref sharded) = self.sharded_cache {
            let vary_header_values: Vec<String> = if let Some(ref cache) = self.response_cache {
                cache
                    .config
                    .vary_headers
                    .iter()
                    .map(|h| {
                        format!(
                            "{}:{}",
                            h,
                            headers.get(h).and_then(|v| v.to_str().ok()).unwrap_or("")
                        )
                    })
                    .collect()
            } else {
                Vec::new()
            };

            let cache_key = crate::cache::ResponseCache::generate_cache_key(
                query,
                Some(variables),
                operation_name,
                &vary_header_values,
            );

            if let Some(cached_bytes) = sharded.get(&cache_key) {
                self.perf_metrics
                    .record(start.elapsed().as_nanos() as u64, true);
                return (
                    [(axum::http::header::CONTENT_TYPE, "application/json")],
                    cached_bytes,
                )
                    .into_response();
            }
        }

        // 3. Fallback to normal execution for cache miss
        // Convert to async_graphql::Request
        let mut gql_req = async_graphql::Request::new(query);
        if !variables.is_null() {
            if let Ok(vars) = serde_json::from_value(variables.clone()) {
                gql_req = gql_req.variables(vars);
            }
        }
        if let Some(op) = operation_name {
            gql_req = gql_req.operation_name(op);
        }

        let resp = self.handle_http(headers, gql_req).await;

        // Record metrics
        self.perf_metrics
            .record(start.elapsed().as_nanos() as u64, false);

        GraphQLResponse::from(resp).into_response()
    }

    /// Convert cached JSON to GraphQL response
    fn cached_to_response(&self, data: serde_json::Value) -> async_graphql::Response {
        // Try to deserialize as Response, or create a simple data response
        match serde_json::from_value::<async_graphql::Response>(data.clone()) {
            Ok(resp) => resp,
            Err(_) => {
                // Fallback: wrap in a simple response
                async_graphql::Response::new(
                    serde_json::from_value::<async_graphql::Value>(data)
                        .unwrap_or(async_graphql::Value::Null),
                )
            }
        }
    }

    /// Process APQ for a request
    fn process_apq_request(
        &self,
        store: &SharedPersistedQueryStore,
        mut request: async_graphql::Request,
    ) -> std::result::Result<async_graphql::Request, PersistedQueryError> {
        // Get the query and extensions from the request
        let query = if request.query.is_empty() {
            None
        } else {
            Some(request.query.as_str())
        };

        // Convert extensions to serde_json::Value for APQ processing
        let extensions_value = if request.extensions.is_empty() {
            None
        } else {
            serde_json::to_value(&request.extensions).ok()
        };

        // Process APQ
        match process_apq_request(store, query, extensions_value.as_ref())? {
            Some(resolved_query) => {
                request.query = resolved_query;
                Ok(request)
            }
            None => {
                // No query (shouldn't happen if APQ processing succeeded)
                Err(PersistedQueryError::NotFound)
            }
        }
    }

    /// Create an error response for APQ errors
    fn apq_error_response(&self, err: PersistedQueryError) -> async_graphql::Response {
        let error_extensions = err.to_extensions();
        let code = error_extensions
            .get("code")
            .and_then(|v| v.as_str())
            .unwrap_or("PERSISTED_QUERY_ERROR");

        let mut server_err = ServerError::new(err.to_string(), None);
        server_err.extensions = Some({
            let mut ext = async_graphql::ErrorExtensionValues::default();
            ext.set("code", code);
            ext
        });

        async_graphql::Response::from_errors(vec![server_err])
    }

    /// Convert to Axum router
    ///
    /// # Security Features
    ///
    /// - Request body limit (1MB default) to prevent memory exhaustion
    /// - Security headers (X-Content-Type-Options, X-Frame-Options)
    /// - GraphQL Playground disabled by default (enable with ENABLE_GRAPHQL_PLAYGROUND=true)
    /// - Analytics endpoints require ANALYTICS_API_KEY for access
    pub fn into_router(self) -> Router {
        use axum::middleware as axum_mw;
        use axum::response::Response;

        let health_checks_enabled = self.health_checks_enabled;
        let metrics_enabled = self.metrics_enabled;
        let analytics_enabled = self.analytics.is_some();
        let client_pool = self.client_pool.clone();
        let compression_config = self.compression_config.clone();

        // SECURITY: Check if playground should be enabled (default: disabled)
        let playground_enabled = self.playground_enabled;
        let cors_allow_origin = configured_cors_allow_origin();
        let content_security_policy = content_security_policy(playground_enabled);

        let state = Arc::new(self);
        let use_fast_path = state.high_perf_config.is_some();

        let router = Router::new();
        let router = if use_fast_path {
            // When fast path is enabled, still route @defer queries through the standard handler
            router.route("/graphql", post(handle_graphql_fast_or_defer))
        } else {
            router.route("/graphql", post(handle_graphql_post))
        };

        let router = if playground_enabled {
            router.route("/graphql", get(graphql_playground))
        } else {
            router
        };

        let mut router = router
            .route("/graphql/ws", get(handle_graphql_ws))
            .route("/graphql/live", get(handle_live_query_ws))
            .route("/graphql/defer", post(handle_graphql_defer))
            .layer(Extension(state.schema.executor()))
            .with_state(state.clone());

        // SECURITY: Add request body limit (1MB) to prevent memory exhaustion
        router = router.layer(axum::extract::DefaultBodyLimit::max(1024 * 1024));

        // SECURITY: Add security headers using axum middleware
        router = router.layer(axum_mw::from_fn(
            move |req: axum::http::Request<axum::body::Body>, next: axum_mw::Next| {
                let cors_allow_origin = cors_allow_origin.clone();
                async move {
                    if req.method() == axum::http::Method::OPTIONS {
                        let mut response = Response::builder()
                            .status(axum::http::StatusCode::NO_CONTENT)
                            .body(axum::body::Body::empty())
                            .unwrap();

                        if let Some(origin) = &cors_allow_origin {
                            let headers = response.headers_mut();
                            headers.insert(
                                axum::http::header::ACCESS_CONTROL_ALLOW_ORIGIN,
                                origin.clone(),
                            );
                            headers.insert(
                                axum::http::header::ACCESS_CONTROL_ALLOW_METHODS,
                                axum::http::HeaderValue::from_static("GET, POST, OPTIONS"),
                            );
                            headers.insert(
                                axum::http::header::ACCESS_CONTROL_ALLOW_HEADERS,
                                axum::http::HeaderValue::from_static(
                                    "Content-Type, Authorization, X-Request-ID",
                                ),
                            );
                            headers.insert(
                                axum::http::header::ACCESS_CONTROL_MAX_AGE,
                                axum::http::HeaderValue::from_static("86400"),
                            );
                        }

                        return response;
                    }

                    let mut response = next.run(req).await;
                    let headers = response.headers_mut();

                    // Core security headers
                    headers.insert(
                        axum::http::header::X_CONTENT_TYPE_OPTIONS,
                        axum::http::HeaderValue::from_static("nosniff"),
                    );
                    headers.insert(
                        axum::http::header::X_FRAME_OPTIONS,
                        axum::http::HeaderValue::from_static("DENY"),
                    );

                    // HSTS (Strict-Transport-Security) - tells browsers to only use HTTPS
                    // max-age=31536000 (1 year), includeSubDomains for comprehensive protection
                    headers.insert(
                        axum::http::header::STRICT_TRANSPORT_SECURITY,
                        axum::http::HeaderValue::from_static("max-age=31536000; includeSubDomains"),
                    );

                    // Prevent caching of sensitive responses
                    headers.insert(
                        axum::http::header::CACHE_CONTROL,
                        axum::http::HeaderValue::from_static("no-store, no-cache, must-revalidate"),
                    );

                    // XSS Protection (legacy but still useful for older browsers)
                    headers.insert(
                        axum::http::header::HeaderName::from_static("x-xss-protection"),
                        axum::http::HeaderValue::from_static("1; mode=block"),
                    );

                    headers.insert(
                        axum::http::header::CONTENT_SECURITY_POLICY,
                        axum::http::HeaderValue::from_static(content_security_policy),
                    );

                    // Referrer Policy - limit referrer information leakage
                    headers.insert(
                        axum::http::header::REFERRER_POLICY,
                        axum::http::HeaderValue::from_static("strict-origin-when-cross-origin"),
                    );

                    // Permissions Policy - Limit browser features
                    headers.insert(
                    axum::http::header::HeaderName::from_static("permissions-policy"),
                    axum::http::HeaderValue::from_static(
                        "camera=(), microphone=(), geolocation=(), browsing-topics=(), payment=()",
                    ),
                );

                    // DNS Prefetch Control - Privacy
                    headers.insert(
                        axum::http::header::HeaderName::from_static("x-dns-prefetch-control"),
                        axum::http::HeaderValue::from_static("off"),
                    );

                    // Cross-Origin policies
                    headers.insert(
                        axum::http::header::HeaderName::from_static("cross-origin-opener-policy"),
                        axum::http::HeaderValue::from_static("same-origin"),
                    );
                    headers.insert(
                        axum::http::header::HeaderName::from_static("cross-origin-embedder-policy"),
                        axum::http::HeaderValue::from_static("require-corp"),
                    );
                    headers.insert(
                        axum::http::header::HeaderName::from_static("cross-origin-resource-policy"),
                        axum::http::HeaderValue::from_static("same-origin"),
                    );

                    if let Some(origin) = cors_allow_origin {
                        headers.insert(axum::http::header::ACCESS_CONTROL_ALLOW_ORIGIN, origin);
                    }

                    response
                }
            },
        ));

        // Add compression layer if enabled
        if let Some(ref config) = compression_config {
            if config.enabled {
                // Add standard compression (brotli, gzip, etc.)
                router = router.layer(create_compression_layer(config));

                // Add custom ultra-fast compression (LZ4, GBP-LZ4)
                if config.lz4_enabled() || config.gbp_lz4_enabled() {
                    router = router.layer(axum::middleware::from_fn(
                        crate::lz4_compression::lz4_compression_middleware,
                    ));
                }
            }
        }

        // Add health check routes if enabled
        if health_checks_enabled {
            let health_state = Arc::new(HealthState::new(client_pool.unwrap_or_default()));
            router = router
                .route("/health", get(health_handler))
                .route("/ready", get(readiness_handler).with_state(health_state));
        }

        // Add metrics route if enabled (consider adding auth in production)
        if metrics_enabled {
            router = router.route("/metrics", get(metrics_handler));
        }

        // Add analytics routes if enabled (protected by API key)
        if analytics_enabled {
            router = router
                .route("/analytics", get(analytics_dashboard_handler))
                .route(
                    "/analytics/api",
                    get(analytics_api_handler).with_state(state.clone()),
                )
                .route(
                    "/analytics/reset",
                    post(analytics_reset_handler).with_state(state),
                );
        }

        router
    }
}

impl Clone for ServeMux {
    fn clone(&self) -> Self {
        Self {
            schema: self.schema.clone(),
            middlewares: self.middlewares.clone(),
            error_handler: self.error_handler.clone(),
            client_pool: self.client_pool.clone(),
            health_checks_enabled: self.health_checks_enabled,
            metrics_enabled: self.metrics_enabled,
            playground_enabled: self.playground_enabled,
            apq_store: self.apq_store.clone(),
            circuit_breaker: self.circuit_breaker.clone(),
            response_cache: self.response_cache.clone(),
            compression_config: self.compression_config.clone(),
            query_whitelist: self.query_whitelist.clone(),
            analytics: self.analytics.clone(),
            request_collapsing: self.request_collapsing.clone(),
            high_perf_config: self.high_perf_config.clone(),
            json_parser: self.json_parser.clone(),
            sharded_cache: self.sharded_cache.clone(),
            perf_metrics: self.perf_metrics.clone(),
            response_templates: self.response_templates.clone(),
            defer_config: self.defer_config.clone(),
            plugins: self.plugins.clone(),
        }
    }
}

/// Extract type names from __typename fields in response
fn extract_types_from_response(response: &serde_json::Value) -> HashSet<String> {
    let mut types = HashSet::new();
    extract_types_recursive(response, &mut types);
    types
}

fn extract_types_recursive(value: &serde_json::Value, types: &mut HashSet<String>) {
    match value {
        serde_json::Value::Object(map) => {
            if let Some(serde_json::Value::String(type_name)) = map.get("__typename") {
                types.insert(type_name.clone());
            }
            for v in map.values() {
                extract_types_recursive(v, types);
            }
        }
        serde_json::Value::Array(arr) => {
            for item in arr {
                extract_types_recursive(item, types);
            }
        }
        _ => {}
    }
}

/// Extract entity keys (Type#id) from response
fn extract_entities_from_response(response: &serde_json::Value) -> HashSet<String> {
    let mut entities = HashSet::new();
    extract_entities_recursive(response, &mut entities);
    entities
}

fn extract_entities_recursive(value: &serde_json::Value, entities: &mut HashSet<String>) {
    match value {
        serde_json::Value::Object(map) => {
            let type_name = map.get("__typename").and_then(|t| t.as_str());
            let id = map
                .get("id")
                .and_then(|i| i.as_str())
                .or_else(|| map.get("_id").and_then(|i| i.as_str()));

            if let (Some(tn), Some(id_val)) = (type_name, id) {
                entities.insert(format!("{}#{}", tn, id_val));
            }

            for v in map.values() {
                extract_entities_recursive(v, entities);
            }
        }
        serde_json::Value::Array(arr) => {
            for item in arr {
                extract_entities_recursive(item, entities);
            }
        }
        _ => {}
    }
}

/// Handler for POST requests to /graphql
///
/// This handler also supports `@defer` — when a query contains `@defer` and
/// the `Accept` header includes `multipart/mixed`, the response is streamed
/// as incremental delivery. Otherwise, a regular JSON response is returned.
async fn handle_graphql_post(
    State(mux): State<Arc<ServeMux>>,
    headers: HeaderMap,
    request: GraphQLRequest,
) -> axum::response::Response {
    let gql_request = request.into_inner();

    // Check if the client accepts multipart/mixed and the query contains @defer
    let accepts_multipart = headers
        .get("accept")
        .and_then(|v| v.to_str().ok())
        .is_some_and(|v| v.contains("multipart/mixed"));

    if accepts_multipart && has_defer_directive(&gql_request.query) {
        if let Some(config) = mux.defer_config().cloned() {
            if config.enabled {
                let query = gql_request.query.clone();
                let fragments = extract_deferred_fragments(&query);

                if fragments.len() <= config.max_deferred_fragments {
                    let stripped_query = strip_defer_directives(&query);
                    let mut eager_request = async_graphql::Request::new(stripped_query)
                        .variables(gql_request.variables);
                    if let Some(op_name) = gql_request.operation_name {
                        eager_request = eager_request.operation_name(op_name);
                    }

                    let full_response = mux.handle_http(headers, eager_request).await;
                    let full_json = serde_json::to_value(&full_response).unwrap_or_else(|_| {
                        serde_json::json!({"data": null, "errors": [{"message": "Serialization failed"}]})
                    });

                    let boundary = config.multipart_boundary.clone();
                    let (exec, mut rx) = DeferredExecution::new(config, fragments);

                    tokio::spawn(async move {
                        if let Err(e) = exec.execute(full_json).await {
                            tracing::warn!(error = %e, "Deferred execution failed");
                        }
                    });

                    let stream = async_stream::stream! {
                        while let Some(part) = rx.recv().await {
                            match part {
                                DeferredPart::Initial(payload) => {
                                    yield Ok::<_, std::convert::Infallible>(
                                        format_initial_part(&payload, &boundary)
                                    );
                                }
                                DeferredPart::Subsequent(payload) => {
                                    let is_last = !payload.has_next;
                                    yield Ok::<_, std::convert::Infallible>(
                                        format_subsequent_part(&payload, &boundary)
                                    );
                                    if is_last {
                                        break;
                                    }
                                }
                            }
                        }
                    };

                    let body = axum::body::Body::from_stream(stream);
                    return axum::response::Response::builder()
                        .header("Content-Type", MULTIPART_CONTENT_TYPE)
                        .header("Transfer-Encoding", "chunked")
                        .header("Cache-Control", "no-cache")
                        .body(body)
                        .unwrap_or_else(|_| {
                            axum::response::Response::builder()
                                .status(500)
                                .body(axum::body::Body::from("Internal Server Error"))
                                .unwrap()
                        });
                }
            }
        }
    }

    // Default: regular JSON response
    GraphQLResponse::from(mux.handle_http(headers, gql_request).await).into_response()
}

/// Handler for high-performance POST requests to /graphql
#[allow(dead_code)]
async fn handle_graphql_fast(
    State(mux): State<Arc<ServeMux>>,
    headers: HeaderMap,
    body: Bytes,
) -> impl IntoResponse {
    mux.handle_fast(headers, body).await
}

/// Combined handler: fast path for normal queries, standard path for @defer.
///
/// When `Accept: multipart/mixed` is present, the request is parsed as a
/// GraphQL request and routed through `handle_graphql_post` which handles
/// `@defer`. Otherwise, the high-performance fast path is used.
async fn handle_graphql_fast_or_defer(
    State(mux): State<Arc<ServeMux>>,
    headers: HeaderMap,
    body: Bytes,
) -> axum::response::Response {
    let accepts_multipart = headers
        .get("accept")
        .and_then(|v| v.to_str().ok())
        .is_some_and(|v| v.contains("multipart/mixed"));

    if accepts_multipart && mux.defer_config().is_some_and(|c| c.enabled) {
        // Parse the body as a GraphQL request and handle with defer support
        if let Ok(gql_request) = serde_json::from_slice::<async_graphql::Request>(&body) {
            if has_defer_directive(&gql_request.query) {
                let config = mux.defer_config().unwrap().clone();
                let query = gql_request.query.clone();
                let fragments = extract_deferred_fragments(&query);

                if fragments.len() <= config.max_deferred_fragments {
                    let stripped_query = strip_defer_directives(&query);
                    let mut eager_request = async_graphql::Request::new(stripped_query)
                        .variables(gql_request.variables);
                    if let Some(op_name) = gql_request.operation_name {
                        eager_request = eager_request.operation_name(op_name);
                    }

                    let full_response = mux.handle_http(headers, eager_request).await;
                    let full_json = serde_json::to_value(&full_response).unwrap_or_else(|_| {
                        serde_json::json!({"data": null, "errors": [{"message": "Serialization failed"}]})
                    });

                    let boundary = config.multipart_boundary.clone();
                    let (exec, mut rx) = DeferredExecution::new(config, fragments);

                    tokio::spawn(async move {
                        if let Err(e) = exec.execute(full_json).await {
                            tracing::warn!(error = %e, "Deferred execution failed");
                        }
                    });

                    let stream = async_stream::stream! {
                        while let Some(part) = rx.recv().await {
                            match part {
                                DeferredPart::Initial(payload) => {
                                    yield Ok::<_, std::convert::Infallible>(
                                        format_initial_part(&payload, &boundary)
                                    );
                                }
                                DeferredPart::Subsequent(payload) => {
                                    let is_last = !payload.has_next;
                                    yield Ok::<_, std::convert::Infallible>(
                                        format_subsequent_part(&payload, &boundary)
                                    );
                                    if is_last {
                                        break;
                                    }
                                }
                            }
                        }
                    };

                    let body = axum::body::Body::from_stream(stream);
                    return axum::response::Response::builder()
                        .header("Content-Type", MULTIPART_CONTENT_TYPE)
                        .header("Transfer-Encoding", "chunked")
                        .header("Cache-Control", "no-cache")
                        .body(body)
                        .unwrap_or_else(|_| {
                            axum::response::Response::builder()
                                .status(500)
                                .body(axum::body::Body::from("Internal Server Error"))
                                .unwrap()
                        });
                }
            }
        }
    }

    mux.handle_fast(headers, body).await.into_response()
}

async fn handle_graphql_ws(
    protocol: GraphQLProtocol,
    ws: WebSocketUpgrade,
    State(mux): State<Arc<ServeMux>>,
    headers: HeaderMap,
) -> impl IntoResponse {
    let handshake_headers = headers.clone();
    let executor = SubscriptionExecutor::new(mux);

    ws.protocols(async_graphql::http::ALL_WEBSOCKET_PROTOCOLS)
        .on_upgrade(move |stream| async move {
            let connection_headers = handshake_headers;

            GraphQLWebSocket::new(stream, executor, protocol)
                .on_connection_init(move |payload| {
                    let connection_headers = connection_headers.clone();
                    async move {
                        let mut data = Data::default();
                        data.insert(WebSocketSessionHeaders {
                            headers: merge_ws_connection_init_headers(
                                &connection_headers,
                                &payload,
                            ),
                        });
                        Ok(data)
                    }
                })
                .serve()
                .await;
        })
}

/// Handler for POST requests to /graphql/defer — `@defer` incremental delivery
///
/// This endpoint supports the `@defer` directive by returning a
/// `multipart/mixed` response. The first part contains the eagerly-resolved
/// initial payload and subsequent parts contain incremental patches for
/// deferred fragments.
///
/// If the query does not contain `@defer`, or if defer is disabled in the
/// gateway configuration, it falls back to a regular JSON response.
///
/// # Multipart Response Format
///
/// ```text
/// Content-Type: multipart/mixed; boundary="-"
///
/// ---
/// Content-Type: application/json; charset=utf-8
///
/// {"data":{"user":{"id":"1","name":"Alice"}},"hasNext":true}
/// ---
/// Content-Type: application/json; charset=utf-8
///
/// {"incremental":[{"data":{"email":"alice@example.com"},"path":["user"],"label":"details"}],"hasNext":false}
/// -----
/// ```
async fn handle_graphql_defer(
    State(mux): State<Arc<ServeMux>>,
    headers: HeaderMap,
    request: GraphQLRequest,
) -> axum::response::Response {
    let gql_request = request.into_inner();
    let query = gql_request.query.clone();

    // Check if @defer is present and enabled
    let defer_config = mux.defer_config().cloned();
    let is_deferred = has_defer_directive(&query);

    if !is_deferred || defer_config.as_ref().is_none_or(|c| !c.enabled) {
        // No @defer or disabled — fall back to normal execution
        let resp = mux.handle_http(headers, gql_request).await;
        return GraphQLResponse::from(resp).into_response();
    }

    let config = defer_config.unwrap();

    // Extract deferred fragments from the original query
    let fragments = extract_deferred_fragments(&query);

    // Validate fragment count
    if fragments.len() > config.max_deferred_fragments {
        let err = ServerError::new(
            format!(
                "Too many @defer fragments ({}/{})",
                fragments.len(),
                config.max_deferred_fragments
            ),
            None,
        );
        let resp = async_graphql::Response::from_errors(vec![err]);
        return GraphQLResponse::from(resp).into_response();
    }

    // Strip @defer directives and execute the full query eagerly
    let stripped_query = strip_defer_directives(&query);
    let mut eager_request =
        async_graphql::Request::new(stripped_query).variables(gql_request.variables);
    if let Some(op_name) = gql_request.operation_name {
        eager_request = eager_request.operation_name(op_name);
    }

    tracing::debug!(
        deferred_fragments = fragments.len(),
        "Executing @defer query with eager resolution"
    );

    // Execute the full query
    let full_response = mux.handle_http(headers, eager_request).await;

    // Convert to serde_json::Value for splitting
    let full_json = serde_json::to_value(&full_response).unwrap_or_else(
        |_| serde_json::json!({"data": null, "errors": [{"message": "Serialization failed"}]}),
    );

    // Create the deferred execution engine
    let boundary = config.multipart_boundary.clone();
    let (exec, mut rx) = DeferredExecution::new(config, fragments);

    // Spawn the deferred execution in the background
    tokio::spawn(async move {
        if let Err(e) = exec.execute(full_json).await {
            tracing::warn!(error = %e, "Deferred execution failed");
        }
    });

    // Build a streaming body from the receiver
    let stream = async_stream::stream! {
        while let Some(part) = rx.recv().await {
            match part {
                DeferredPart::Initial(payload) => {
                    yield Ok::<_, std::convert::Infallible>(
                        format_initial_part(&payload, &boundary)
                    );
                }
                DeferredPart::Subsequent(payload) => {
                    let is_last = !payload.has_next;
                    yield Ok::<_, std::convert::Infallible>(
                        format_subsequent_part(&payload, &boundary)
                    );
                    if is_last {
                        break;
                    }
                }
            }
        }
    };

    let body = axum::body::Body::from_stream(stream);

    axum::response::Response::builder()
        .header("Content-Type", MULTIPART_CONTENT_TYPE)
        .header("Transfer-Encoding", "chunked")
        .header("Cache-Control", "no-cache")
        .header("Connection", "keep-alive")
        .body(body)
        .unwrap_or_else(|_| {
            axum::response::Response::builder()
                .status(500)
                .body(axum::body::Body::from("Internal Server Error"))
                .unwrap()
        })
}

/// Serve the GraphQL Playground UI for ad-hoc exploration.
///
/// # Security
///
/// This endpoint is only available when ENABLE_GRAPHQL_PLAYGROUND=true.
/// It should be disabled in production to prevent schema exploration.
async fn graphql_playground() -> impl IntoResponse {
    Html(async_graphql::http::playground_source(
        async_graphql::http::GraphQLPlaygroundConfig::new("/graphql")
            .subscription_endpoint("/graphql/ws"),
    ))
}

/// Handler for Prometheus metrics endpoint
///
/// # Security
///
/// DENY-BY-DEFAULT: Requires METRICS_API_KEY env var to be set.
/// If the variable is absent the endpoint returns 403 — this prevents
/// accidental exposure on new deployments.
async fn metrics_handler(headers: HeaderMap) -> axum::response::Response {
    // SECURITY: Deny-by-default — require an API key to be configured.
    // If METRICS_API_KEY is not set, the endpoint rejects all requests.
    let required_key = match std::env::var("METRICS_API_KEY") {
        Ok(k) if !k.is_empty() => k,
        _ => {
            return (
                axum::http::StatusCode::FORBIDDEN,
                "Metrics endpoint requires METRICS_API_KEY to be configured",
            )
                .into_response();
        }
    };

    let provided_key = headers
        .get("x-metrics-key")
        .and_then(|v| v.to_str().ok())
        .unwrap_or("");

    // SECURITY: Constant-time comparison to prevent timing attacks
    if !constant_time_eq(provided_key.as_bytes(), required_key.as_bytes()) {
        return (
            axum::http::StatusCode::UNAUTHORIZED,
            "Unauthorized: Valid x-metrics-key header required",
        )
            .into_response();
    }

    let metrics = GatewayMetrics::global();
    let body = metrics.render();
    (
        [(
            axum::http::header::CONTENT_TYPE,
            "text/plain; charset=utf-8",
        )],
        body,
    )
        .into_response()
}

/// Handler for analytics dashboard HTML
///
/// # Security
///
/// DENY-BY-DEFAULT: Requires ANALYTICS_API_KEY env var to be set.
async fn analytics_dashboard_handler(headers: HeaderMap) -> axum::response::Response {
    // SECURITY: Deny-by-default — require an API key to be configured.
    let required_key = match std::env::var("ANALYTICS_API_KEY") {
        Ok(k) if !k.is_empty() => k,
        _ => {
            return (
                axum::http::StatusCode::FORBIDDEN,
                "Analytics endpoint requires ANALYTICS_API_KEY to be configured",
            )
                .into_response();
        }
    };

    let provided_key = headers
        .get("x-analytics-key")
        .and_then(|v| v.to_str().ok())
        .unwrap_or("");

    // SECURITY: Constant-time comparison to prevent timing attacks
    if !constant_time_eq(provided_key.as_bytes(), required_key.as_bytes()) {
        return (
            axum::http::StatusCode::UNAUTHORIZED,
            "Unauthorized: Valid x-analytics-key header required",
        )
            .into_response();
    }
    Html(crate::analytics::analytics_dashboard_html()).into_response()
}

/// Handler for analytics API endpoint (JSON)
///
/// # Security
///
/// DENY-BY-DEFAULT: Requires ANALYTICS_API_KEY env var. If absent, returns 403.
async fn analytics_api_handler(
    State(mux): State<Arc<ServeMux>>,
    headers: HeaderMap,
) -> impl IntoResponse {
    // SECURITY: Deny-by-default — require an API key to be configured.
    let required_key = match std::env::var("ANALYTICS_API_KEY") {
        Ok(k) if !k.is_empty() => k,
        _ => {
            return Json(serde_json::json!({
                "error": "Forbidden",
                "message": "Analytics endpoint requires ANALYTICS_API_KEY to be configured"
            }));
        }
    };

    let provided_key = headers
        .get("x-analytics-key")
        .and_then(|v| v.to_str().ok())
        .unwrap_or("");

    // SECURITY: Constant-time comparison to prevent timing attacks
    if !constant_time_eq(provided_key.as_bytes(), required_key.as_bytes()) {
        return Json(serde_json::json!({
            "error": "Unauthorized",
            "message": "Valid x-analytics-key header required"
        }));
    }

    if let Some(ref analytics) = mux.analytics {
        let snapshot = analytics.get_snapshot();
        Json(
            serde_json::to_value(snapshot)
                .unwrap_or_else(|_| serde_json::json!({"error": "Failed to serialize analytics"})),
        )
    } else {
        Json(serde_json::json!({"error": "Analytics not enabled"}))
    }
}

/// Handler for analytics reset endpoint
///
/// # Security
///
/// DENY-BY-DEFAULT: Requires ANALYTICS_API_KEY. This endpoint resets all analytics
/// data and must not be publicly accessible.
async fn analytics_reset_handler(
    State(mux): State<Arc<ServeMux>>,
    headers: HeaderMap,
) -> impl IntoResponse {
    // SECURITY: Deny-by-default — require an API key to be configured.
    let required_key = match std::env::var("ANALYTICS_API_KEY") {
        Ok(k) if !k.is_empty() => k,
        _ => {
            return Json(serde_json::json!({
                "error": "Forbidden",
                "message": "Analytics endpoint requires ANALYTICS_API_KEY to be configured"
            }));
        }
    };

    let provided_key = headers
        .get("x-analytics-key")
        .and_then(|v| v.to_str().ok())
        .unwrap_or("");

    // SECURITY: Constant-time comparison to prevent timing attacks
    if !constant_time_eq(provided_key.as_bytes(), required_key.as_bytes()) {
        return Json(serde_json::json!({
            "error": "Unauthorized",
            "message": "Valid x-analytics-key header required"
        }));
    }

    if let Some(ref analytics) = mux.analytics {
        analytics.reset();
        Json(serde_json::json!({"status": "ok", "message": "Analytics reset successfully"}))
    } else {
        Json(serde_json::json!({"error": "Analytics not enabled"}))
    }
}

// =============================================================================
// SO_REUSEPORT Multi-Listener Server (High-Throughput)
// =============================================================================

/// Constant-time byte comparison to prevent timing side-channel attacks.
///
/// Unlike `==`, this function always compares every byte regardless of position,
/// preventing attackers from brute-forcing API keys byte-by-byte.
fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
    if a.len() != b.len() {
        return false;
    }
    let mut result: u8 = 0;
    for (x, y) in a.iter().zip(b.iter()) {
        result |= x ^ y;
    }
    result == 0
}

/// Build a TCP listener with performance-oriented socket options.
///
/// Sets:
/// - `TCP_NODELAY`: Disables Nagle's algorithm for lower latency.
/// - `SO_REUSEADDR`: Allows reuse of the address after restart.
/// - `SO_REUSEPORT` (Linux/macOS): Allows multiple sockets on the same port
///   so the kernel can distribute `accept()` load across threads.
/// - Large backlog (4096): Handles burst connection queues without dropping.
///
/// # Platform
///
/// `SO_REUSEPORT` is supported on Linux ≥ 3.9 and macOS ≥ 10.9.
/// On other platforms this falls back to a regular `TcpListener`.
pub fn build_tcp_listener_tuned(addr: &str) -> std::io::Result<std::net::TcpListener> {
    use std::net::SocketAddr;

    let addr: SocketAddr = addr.parse().map_err(|e| {
        std::io::Error::new(
            std::io::ErrorKind::InvalidInput,
            format!("invalid addr: {e}"),
        )
    })?;

    let socket = socket2::Socket::new(
        if addr.is_ipv6() {
            socket2::Domain::IPV6
        } else {
            socket2::Domain::IPV4
        },
        socket2::Type::STREAM,
        None,
    )?;

    socket.set_reuse_address(true)?;

    #[cfg(any(target_os = "linux", target_os = "macos"))]
    socket.set_reuse_port(true)?;

    socket.set_nodelay(true)?;
    socket.set_nonblocking(true)?;
    socket.bind(&addr.into())?;
    // Large backlog for burst connection handling
    socket.listen(4096)?;

    Ok(socket.into())
}

/// High-throughput server using one `SO_REUSEPORT` listener per worker.
///
/// Creates `num_workers` independent `TcpListener`s bound to the same address
/// with `SO_REUSEPORT`. The kernel load-balances incoming connections across
/// them at the socket level — eliminating the single shared `accept()` queue
/// bottleneck that exists with a single listener.
///
/// # Performance Impact
///
/// - Eliminates accept-queue lock contention at high connection rates.
/// - Enables true per-core connection handling (same technique used by nginx).
/// - Best combined with `HighPerfConfig::ultra_fast()` and `mimalloc`.
///
/// # Example
///
/// ```rust,no_run
/// use grpc_graphql_gateway::runtime::serve_reuseport;
/// use axum::Router;
///
/// # async fn example() -> anyhow::Result<()> {
/// let app = Router::new();
/// serve_reuseport("0.0.0.0:8080", 8, app).await?;
/// # Ok(())
/// # }
/// ```
pub async fn serve_reuseport(
    addr: &str,
    num_workers: usize,
    app: axum::Router,
) -> crate::error::Result<()> {
    let mut handles = Vec::with_capacity(num_workers);
    let addr_owned = addr.to_string();

    for i in 0..num_workers {
        let std_listener = build_tcp_listener_tuned(addr).map_err(|e| {
            crate::error::Error::Internal(format!(
                "Failed to bind worker {i} listener on {addr}: {e}"
            ))
        })?;

        std_listener
            .set_nonblocking(true)
            .map_err(|e| crate::error::Error::Internal(format!("set_nonblocking failed: {e}")))?;

        let listener = tokio::net::TcpListener::from_std(std_listener)
            .map_err(|e| crate::error::Error::Internal(format!("from_std failed: {e}")))?;

        let app = app.clone();
        let addr_clone = addr_owned.clone();
        let handle = tokio::spawn(async move {
            tracing::info!("Worker {i} accepting on {addr_clone} (SO_REUSEPORT)");
            if let Err(e) = axum::serve(listener, app).await {
                tracing::error!("Worker {i} server error: {e}");
            }
        });

        handles.push(handle);
    }

    // Wait for all workers
    for handle in handles {
        let _ = handle.await;
    }

    Ok(())
}

/// WebSocket handler for live queries
///
/// This endpoint handles `@live` queries by:
/// 1. Executing the query as a regular GraphQL query
/// 2. Returning the initial result immediately
/// 3. Keeping the connection open to push updates when data changes
///
/// Protocol (same as graphql-transport-ws):
/// - Client sends: `{"type": "connection_init"}`
/// - Server responds: `{"type": "connection_ack"}`
/// - Client sends: `{"type": "subscribe", "id": "1", "payload": {"query": "query @live { ... }"}}`
/// - Server responds: `{"type": "next", "id": "1", "payload": {"data": {...}}}`
/// - Server can send more `next` messages when data updates
/// - Client or server sends: `{"type": "complete", "id": "1"}` to end
async fn handle_live_query_ws(
    ws: WebSocketUpgrade,
    State(mux): State<Arc<ServeMux>>,
) -> impl IntoResponse {
    ws.protocols(["graphql-transport-ws"])
        .on_upgrade(move |socket| handle_live_socket(socket, mux))
}

/// Handle the live query WebSocket connection with auto-push updates and GBP compression
async fn handle_live_socket(socket: WebSocket, mux: Arc<ServeMux>) {
    use std::collections::HashMap;
    use tokio::sync::mpsc;

    let (sender, mut receiver) = socket.split();

    #[derive(serde::Deserialize)]
    struct WsMessage {
        #[serde(rename = "type")]
        msg_type: String,
        id: Option<String>,
        payload: Option<serde_json::Value>,
    }

    #[derive(serde::Serialize, Clone)]
    struct WsResponse {
        #[serde(rename = "type")]
        msg_type: String,
        #[serde(skip_serializing_if = "Option::is_none")]
        id: Option<String>,
        #[serde(skip_serializing_if = "Option::is_none")]
        payload: Option<serde_json::Value>,
    }

    // Track active live subscriptions
    #[derive(Clone)]
    struct LiveSubscription {
        id: String,
        query: String,
        variables: Option<serde_json::Value>,
        operation_name: Option<String>,
        triggers: Vec<String>,
        is_live: bool,
    }

    // Track compression preference (negotiated during connection_init)
    let use_gbp_compression = Arc::new(parking_lot::RwLock::new(false));

    let mut connection_initialized = false;
    let active_subscriptions: Arc<parking_lot::RwLock<HashMap<String, LiveSubscription>>> =
        Arc::new(parking_lot::RwLock::new(HashMap::new()));

    // Channel to send messages to the WebSocket
    let (ws_tx, mut ws_rx) = mpsc::channel::<WsResponse>(100);

    // Get live query store for invalidation events
    let live_query_store = crate::live_query::create_live_query_store();
    let mut invalidation_rx = live_query_store.subscribe_invalidations();

    // Spawn task to forward messages to WebSocket
    let _ws_tx_clone = ws_tx.clone();
    let sender = Arc::new(tokio::sync::Mutex::new(sender));
    let sender_clone = sender.clone();

    let use_compression_clone = use_gbp_compression.clone();
    let forward_task = tokio::spawn(async move {
        while let Some(msg) = ws_rx.recv().await {
            let mut sender = sender_clone.lock().await;

            // Check if GBP compression is enabled for this connection
            if *use_compression_clone.read() {
                // Use GBP binary compression
                if let Some(payload) = &msg.payload {
                    match crate::gbp::GbpEncoder::new().encode_lz4(payload) {
                        Ok(compressed) => {
                            // Create envelope: {type, id, compressed_payload}
                            let envelope = serde_json::json!({
                                "type": msg.msg_type,
                                "id": msg.id,
                                "compressed": true
                            });
                            let envelope_json = serde_json::to_string(&envelope).unwrap();

                            // Send envelope + binary payload as separate frames
                            // Frame 1: JSON envelope
                            if sender
                                .send(Message::Text(envelope_json.into()))
                                .await
                                .is_err()
                            {
                                break;
                            }
                            // Frame 2: Binary GBP payload
                            if sender
                                .send(Message::Binary(compressed.into()))
                                .await
                                .is_err()
                            {
                                break;
                            }
                        }
                        Err(e) => {
                            tracing::warn!(
                                "Failed to compress with GBP, falling back to JSON: {}",
                                e
                            );
                            // Fallback to JSON
                            let json = serde_json::to_string(&msg).unwrap();
                            if sender.send(Message::Text(json.into())).await.is_err() {
                                break;
                            }
                        }
                    }
                } else {
                    // No payload, send as JSON
                    let json = serde_json::to_string(&msg).unwrap();
                    if sender.send(Message::Text(json.into())).await.is_err() {
                        break;
                    }
                }
            } else {
                // Use standard JSON (backward compatible)
                let json = serde_json::to_string(&msg).unwrap();
                if sender.send(Message::Text(json.into())).await.is_err() {
                    break;
                }
            }
        }
    });

    // Spawn task to handle invalidation events and push updates
    let subscriptions_clone = active_subscriptions.clone();
    let mux_clone = mux.clone();
    let ws_tx_for_invalidation = ws_tx.clone();

    let invalidation_task = tokio::spawn(async move {
        loop {
            match invalidation_rx.recv().await {
                Ok(event) => {
                    let trigger_pattern = format!("{}.{}", event.type_name, event.action);

                    // Find subscriptions that match this invalidation
                    let matching_subs: Vec<LiveSubscription> = {
                        let subs = subscriptions_clone.read();
                        subs.values()
                            .filter(|sub| {
                                sub.is_live
                                    && sub.triggers.iter().any(|t| {
                                        t == &trigger_pattern
                                            || t == &format!("{}.*", event.type_name)
                                            || t == &format!("*.{}", event.action)
                                            || t == "*.*"
                                    })
                            })
                            .cloned()
                            .collect()
                    };

                    // Re-execute and push updates for matching subscriptions
                    for sub in matching_subs {
                        tracing::info!(
                            subscription_id = %sub.id,
                            trigger = %trigger_pattern,
                            "Re-executing live query due to invalidation"
                        );

                        // Build request
                        let mut gql_request = async_graphql::Request::new(&sub.query);
                        if let Some(vars) = &sub.variables {
                            if let Ok(variables) = serde_json::from_value(vars.clone()) {
                                gql_request = gql_request.variables(variables);
                            }
                        }
                        if let Some(op_name) = &sub.operation_name {
                            gql_request = gql_request.operation_name(op_name);
                        }
                        if sub.is_live {
                            gql_request = gql_request.data(LiveQueryRequestMarker);
                        }

                        // Execute
                        let response = mux_clone.handle_http(HeaderMap::new(), gql_request).await;
                        let response_json = serde_json::to_value(&response).unwrap_or_default();

                        // Send update
                        let update = WsResponse {
                            msg_type: "next".to_string(),
                            id: Some(sub.id.clone()),
                            payload: Some(response_json),
                        };

                        if ws_tx_for_invalidation.send(update).await.is_err() {
                            break;
                        }
                    }
                }
                Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {
                    // Missed some events, continue
                    continue;
                }
                Err(tokio::sync::broadcast::error::RecvError::Closed) => {
                    break;
                }
            }
        }
    });

    // Main message loop
    while let Some(msg) = receiver.next().await {
        let msg = match msg {
            Ok(Message::Text(text)) => text,
            Ok(Message::Close(_)) => break,
            _ => continue,
        };

        let parsed: WsMessage = match serde_json::from_str(&msg) {
            Ok(m) => m,
            Err(e) => {
                tracing::warn!("Failed to parse WebSocket message: {}", e);
                continue;
            }
        };

        match parsed.msg_type.as_str() {
            "connection_init" => {
                connection_initialized = true;

                // Check if client requests GBP compression
                if let Some(payload) = &parsed.payload {
                    if let Some(compression) = payload.get("compression").and_then(|c| c.as_str()) {
                        if compression == "gbp-lz4" || compression == "gbp" {
                            *use_gbp_compression.write() = true;
                            tracing::info!("GBP compression enabled for live query connection");
                        }
                    }
                }

                let mut ack_payload = serde_json::json!({});
                if *use_gbp_compression.read() {
                    ack_payload["compression"] = serde_json::json!("gbp-lz4");
                    ack_payload["compressionInfo"] = serde_json::json!({
                        "algorithm": "GBP Ultra + LZ4",
                        "expectedReduction": "90-99%",
                        "format": "binary"
                    });
                }

                let ack = WsResponse {
                    msg_type: "connection_ack".to_string(),
                    id: None,
                    payload: if ack_payload.as_object().unwrap().is_empty() {
                        None
                    } else {
                        Some(ack_payload)
                    },
                };
                if ws_tx.send(ack).await.is_err() {
                    break;
                }
            }

            "ping" => {
                let pong = WsResponse {
                    msg_type: "pong".to_string(),
                    id: None,
                    payload: None,
                };
                let _ = ws_tx.send(pong).await;
            }

            "subscribe" => {
                if !connection_initialized {
                    tracing::warn!("Received subscribe before connection_init");
                    continue;
                }

                // SECURITY: Cap subscriptions per connection to prevent memory DoS.
                // An attacker sending unlimited subscribe messages without completing
                // them would grow the map without bound.
                const MAX_SUBSCRIPTIONS_PER_CONNECTION: usize = 100;
                if active_subscriptions.read().len() >= MAX_SUBSCRIPTIONS_PER_CONNECTION {
                    tracing::warn!(
                        max = MAX_SUBSCRIPTIONS_PER_CONNECTION,
                        "WebSocket subscription limit reached, rejecting new subscription"
                    );
                    let err_msg = WsResponse {
                        msg_type: "error".to_string(),
                        id: parsed.id.clone(),
                        payload: Some(serde_json::json!({
                            "message": format!(
                                "Subscription limit ({}) exceeded for this connection",
                                MAX_SUBSCRIPTIONS_PER_CONNECTION
                            )
                        })),
                    };
                    let _ = ws_tx.send(err_msg).await;
                    continue;
                }

                let id = parsed.id.clone().unwrap_or_default();

                // Extract query from payload
                let query = parsed
                    .payload
                    .as_ref()
                    .and_then(|p| p.get("query"))
                    .and_then(|q| q.as_str())
                    .unwrap_or("");

                // Check for @live directive
                let is_live = crate::live_query::has_live_directive(query);

                // Strip @live directive and convert subscription to query for live queries
                let clean_query = if is_live {
                    let stripped = crate::live_query::strip_live_directive(query);
                    // Convert "subscription" to "query" because standard GraphQL doesn't allow
                    // Subscription operations without a Subscription root in the schema
                    if stripped.trim_start().starts_with("subscription") {
                        stripped.replacen("subscription", "query", 1)
                    } else {
                        stripped
                    }
                } else {
                    query.to_string()
                };

                let variables = parsed
                    .payload
                    .as_ref()
                    .and_then(|p| p.get("variables"))
                    .cloned();
                let operation_name = parsed
                    .payload
                    .as_ref()
                    .and_then(|p| p.get("operationName"))
                    .and_then(|n| n.as_str())
                    .map(|s| s.to_string());

                tracing::info!(
                    subscription_id = %id,
                    is_live = is_live,
                    "Live query subscription started"
                );

                // Build and execute the GraphQL request
                let mut gql_request = async_graphql::Request::new(&clean_query);

                if let Some(vars) = &variables {
                    if let Ok(v) = serde_json::from_value(vars.clone()) {
                        gql_request = gql_request.variables(v);
                    }
                }

                if let Some(ref op_name) = operation_name {
                    gql_request = gql_request.operation_name(op_name);
                }
                if is_live {
                    gql_request = gql_request.data(LiveQueryRequestMarker);
                }

                // Execute initial query
                let response = mux.handle_http(HeaderMap::new(), gql_request).await;
                let response_json = serde_json::to_value(&response).unwrap_or_default();

                // Send initial result
                let next_msg = WsResponse {
                    msg_type: "next".to_string(),
                    id: Some(id.clone()),
                    payload: Some(response_json),
                };

                if ws_tx.send(next_msg).await.is_err() {
                    break;
                }

                if is_live {
                    // Improve trigger detection using Schema Config
                    let configs = mux.schema.live_query_configs();
                    let mut triggers = std::collections::HashSet::new();

                    if !configs.is_empty() {
                        // SECURITY: Use word-boundary matching instead of raw `contains()`
                        // to avoid false-positives where one field name is a substring of
                        // another (e.g. "getUser" matching inside "getUserById").
                        // We look for the op_name surrounded by non-alphanumeric boundaries.
                        for (op_name, config) in configs {
                            let matched = {
                                // Find all occurrences and check surrounding characters
                                let mut found = false;
                                let query_bytes = clean_query.as_bytes();
                                let name_bytes = op_name.as_bytes();
                                let qlen = query_bytes.len();
                                let nlen = name_bytes.len();
                                if nlen > 0 && qlen >= nlen {
                                    for i in 0..=(qlen - nlen) {
                                        if &query_bytes[i..i + nlen] == name_bytes {
                                            // Check left boundary
                                            let left_ok = i == 0
                                                || !query_bytes[i - 1].is_ascii_alphanumeric()
                                                    && query_bytes[i - 1] != b'_';
                                            // Check right boundary
                                            let right_ok = i + nlen == qlen
                                                || !query_bytes[i + nlen].is_ascii_alphanumeric()
                                                    && query_bytes[i + nlen] != b'_';
                                            if left_ok && right_ok {
                                                found = true;
                                                break;
                                            }
                                        }
                                    }
                                }
                                found
                            };
                            if matched {
                                for trigger in &config.triggers {
                                    triggers.insert(trigger.clone());
                                }
                                tracing::info!(
                                    operation = %op_name,
                                    found_triggers = ?config.triggers,
                                    "Configured live query triggers found"
                                );
                            }
                        }
                    }

                    // Fallback to defaults if no config found or no triggers specified
                    if triggers.is_empty() {
                        tracing::debug!("No configured triggers found, using defaults");
                        triggers.insert("User.create".to_string());
                        triggers.insert("User.update".to_string());
                        triggers.insert("User.delete".to_string());
                        triggers.insert("*.*".to_string());
                    }

                    let subscription = LiveSubscription {
                        id: id.clone(),
                        query: clean_query,
                        variables,
                        operation_name,
                        triggers: triggers.into_iter().collect(),
                        is_live: true,
                    };

                    active_subscriptions
                        .write()
                        .insert(id.clone(), subscription);
                    tracing::info!(subscription_id = %id, "Live subscription registered for updates");
                } else {
                    // Non-live query: send complete immediately
                    let complete_msg = WsResponse {
                        msg_type: "complete".to_string(),
                        id: Some(id),
                        payload: None,
                    };
                    if ws_tx.send(complete_msg).await.is_err() {
                        break;
                    }
                }
            }

            "complete" => {
                if let Some(id) = parsed.id {
                    active_subscriptions.write().remove(&id);
                    tracing::debug!(subscription_id = %id, "Client completed subscription");
                }
            }

            _ => {
                tracing::debug!("Unknown message type: {}", parsed.msg_type);
            }
        }
    }

    // Cleanup
    forward_task.abort();
    invalidation_task.abort();
    tracing::debug!("Live query WebSocket connection closed");
}

#[cfg(test)]
mod tests {
    use super::*;
    use axum::{
        body::{to_bytes, Body},
        http::{Request, StatusCode},
    };
    use tower::ServiceExt;

    const GREETER_DESCRIPTOR: &[u8] = include_bytes!("generated/greeter_descriptor.bin");

    fn build_router_mux() -> ServeMux {
        let schema = crate::schema::SchemaBuilder::new()
            .with_descriptor_set_bytes(GREETER_DESCRIPTOR)
            .build(&crate::grpc_client::GrpcClientPool::new())
            .expect("schema builds");

        ServeMux::new(schema)
    }

    #[tokio::test]
    async fn playground_served_on_get() {
        let mut mux = build_router_mux();
        mux.enable_playground();
        let app = mux.into_router();

        // ... rest of test
        let response = app
            .oneshot(
                Request::builder()
                    .uri("/graphql")
                    .body(Body::empty())
                    .expect("build request"),
            )
            .await
            .expect("receive response");

        assert_eq!(response.status(), StatusCode::OK);

        let body = to_bytes(response.into_body(), 1024 * 1024)
            .await
            .expect("read body");
        let body_str = String::from_utf8(body.to_vec()).expect("utf8 body");

        assert!(
            body_str.contains("GraphQL Playground"),
            "playground HTML should be returned"
        );
        assert!(
            body_str.contains("/graphql/ws"),
            "websocket endpoint should be linked"
        );
    }

    // Category 1: Configuration Tests (Quick Wins!)

    #[tokio::test]
    async fn test_servemux_new() {
        let mux = build_router_mux();
        // Basic creation should work
        assert!(mux.circuit_breaker().is_none());
        assert!(mux.response_cache().is_none());
    }

    #[tokio::test]
    async fn test_servemux_clone() {
        let mux = build_router_mux();
        let cloned = mux.clone();
        // Should be able to clone
        let _router1 = mux.into_router();
        let _router2 = cloned.into_router();
    }

    #[tokio::test]
    async fn test_enable_health_checks() {
        let mut mux = build_router_mux();
        mux.set_client_pool(crate::grpc_client::GrpcClientPool::new());
        mux.enable_health_checks();
        // Health checks enabled (verified by endpoint test below)
    }

    #[tokio::test]
    async fn test_enable_metrics() {
        let mut mux = build_router_mux();
        mux.enable_metrics();
        // Metrics enabled (verified by endpoint test below)
    }

    #[tokio::test]
    async fn test_enable_circuit_breaker() {
        let mut mux = build_router_mux();
        let config = crate::circuit_breaker::CircuitBreakerConfig::default();
        mux.enable_circuit_breaker(config);
        assert!(mux.circuit_breaker().is_some());
    }

    #[tokio::test]
    async fn test_enable_response_cache() {
        let mut mux = build_router_mux();
        let config = crate::cache::CacheConfig::default();
        mux.enable_response_cache(config);
        assert!(mux.response_cache().is_some());
    }

    #[tokio::test]
    async fn test_enable_compression() {
        let mut mux = build_router_mux();
        let config = crate::compression::CompressionConfig::default();
        mux.enable_compression(config);
        assert!(mux.compression_config().is_some());
    }

    #[tokio::test]
    async fn test_enable_query_whitelist() {
        let mut mux = build_router_mux();
        let config = crate::query_whitelist::QueryWhitelistConfig::warn();
        mux.enable_query_whitelist(config);
        assert!(mux.query_whitelist().is_some());
    }

    #[tokio::test]
    async fn test_enable_analytics() {
        let mut mux = build_router_mux();
        let config = crate::analytics::AnalyticsConfig::default();
        mux.enable_analytics(config);
        assert!(mux.analytics().is_some());
    }

    #[tokio::test]
    async fn test_enable_request_collapsing() {
        let mut mux = build_router_mux();
        let config = crate::request_collapsing::RequestCollapsingConfig::default();
        mux.enable_request_collapsing(config);
        assert!(mux.request_collapsing().is_some());
    }

    #[tokio::test]
    async fn test_enable_high_performance() {
        let mut mux = build_router_mux();
        let config = crate::high_performance::HighPerfConfig::default();
        mux.enable_high_performance(config);
        // High perf enabled
    }

    #[tokio::test]
    async fn test_perf_metrics() {
        let mux = build_router_mux();
        let _metrics = mux.perf_metrics();
        // Metrics accessible
    }

    // Category 2: Health & Metrics Endpoints

    #[tokio::test]
    async fn test_health_endpoint() {
        let mut mux = build_router_mux();
        mux.set_client_pool(crate::grpc_client::GrpcClientPool::new());
        mux.enable_health_checks();
        let app = mux.into_router();

        let response = app
            .oneshot(
                Request::builder()
                    .uri("/health")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
    }

    #[tokio::test]
    async fn test_readiness_endpoint() {
        let mut mux = build_router_mux();
        mux.set_client_pool(crate::grpc_client::GrpcClientPool::new());
        mux.enable_health_checks();
        let app = mux.into_router();

        let response = app
            .oneshot(
                Request::builder()
                    .uri("/ready")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        // Should return some status
        assert!(response.status().is_success() || response.status().is_server_error());
    }

    #[tokio::test]
    async fn test_metrics_endpoint() {
        let mut mux = build_router_mux();
        mux.enable_metrics();
        let app = mux.into_router();

        // SECURITY: Without METRICS_API_KEY set the endpoint must return 403
        let response = app
            .clone()
            .oneshot(
                Request::builder()
                    .uri("/metrics")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(response.status(), StatusCode::FORBIDDEN);

        // With the correct key configured and supplied the endpoint returns 200
        // Safety: single-threaded test environment; key is removed immediately after.
        unsafe { std::env::set_var("METRICS_API_KEY", "test-metrics-secret") };
        let response = app
            .oneshot(
                Request::builder()
                    .uri("/metrics")
                    .header("x-metrics-key", "test-metrics-secret")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        unsafe { std::env::remove_var("METRICS_API_KEY") };
        assert_eq!(response.status(), StatusCode::OK);
    }

    #[tokio::test]
    async fn test_analytics_endpoint() {
        let mut mux = build_router_mux();
        mux.enable_analytics(crate::analytics::AnalyticsConfig::default());
        let app = mux.into_router();

        // SECURITY: Without ANALYTICS_API_KEY set the endpoint must return 403
        let response = app
            .clone()
            .oneshot(
                Request::builder()
                    .uri("/analytics")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(response.status(), StatusCode::FORBIDDEN);

        // With the correct key configured and supplied the endpoint returns 200
        unsafe { std::env::set_var("ANALYTICS_API_KEY", "test-analytics-secret") };
        let response = app
            .oneshot(
                Request::builder()
                    .uri("/analytics")
                    .header("x-analytics-key", "test-analytics-secret")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        unsafe { std::env::remove_var("ANALYTICS_API_KEY") };
        assert_eq!(response.status(), StatusCode::OK);
    }

    // Category 3: GraphQL Request Handling

    #[tokio::test]
    async fn test_graphql_post_query() {
        let mux = build_router_mux();
        let app = mux.into_router();

        let query = r#"{ __schema { queryType { name } } }"#;
        let request_body = serde_json::json!({
            "query": query
        });

        let response = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/graphql")
                    .header("content-type", "application/json")
                    .body(Body::from(serde_json::to_string(&request_body).unwrap()))
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
    }

    #[tokio::test]
    async fn test_graphql_post_introspection() {
        let mux = build_router_mux();
        let app = mux.into_router();

        let query = r#"{ __schema { types { name } } }"#;
        let request_body = serde_json::json!({
            "query": query
        });

        let response = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/graphql")
                    .header("content-type", "application/json")
                    .body(Body::from(serde_json::to_string(&request_body).unwrap()))
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
    }

    #[tokio::test]
    async fn test_graphql_post_empty_body() {
        let mux = build_router_mux();
        let app = mux.into_router();

        let response = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/graphql")
                    .header("content-type", "application/json")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        // Should return error status
        assert!(!response.status().is_success());
    }

    #[tokio::test]
    async fn test_graphql_post_invalid_json() {
        let mux = build_router_mux();
        let app = mux.into_router();

        let response = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/graphql")
                    .header("content-type", "application/json")
                    .body(Body::from("{invalid json"))
                    .unwrap(),
            )
            .await
            .unwrap();

        // Should return error status
        assert!(!response.status().is_success());
    }

    #[tokio::test]
    async fn test_graphql_with_variables() {
        let mux = build_router_mux();
        let app = mux.into_router();

        let query = r#"query Test($name: String!) { __type(name: $name) { name } }"#;
        let request_body = serde_json::json!({
            "query": query,
            "variables": { "name": "String" }
        });

        let response = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/graphql")
                    .header("content-type", "application/json")
                    .body(Body::from(serde_json::to_string(&request_body).unwrap()))
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
    }

    #[tokio::test]
    async fn test_graphql_with_operation_name() {
        let mux = build_router_mux();
        let app = mux.into_router();

        let query = r#"
            query First { __schema { queryType { name } } }
            query Second { __schema { mutationType { name } } }
        "#;
        let request_body = serde_json::json!({
            "query": query,
            "operationName": "First"
        });

        let response = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/graphql")
                    .header("content-type", "application/json")
                    .body(Body::from(serde_json::to_string(&request_body).unwrap()))
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
    }

    // Category 4: Builder Pattern

    #[tokio::test]
    async fn test_with_middleware_builder() {
        let mux = build_router_mux();
        // Should not panic
        let _router = mux.into_router();
    }

    #[tokio::test]
    async fn test_multiple_configurations() {
        let mut mux = build_router_mux();

        // Enable multiple features
        mux.enable_metrics();
        mux.enable_playground();
        mux.enable_analytics(crate::analytics::AnalyticsConfig::default());
        mux.enable_compression(crate::compression::CompressionConfig::default());

        let app = mux.into_router();

        // SECURITY: Without METRICS_API_KEY the metrics endpoint must return 403 (denied by default)
        let response = app
            .oneshot(
                Request::builder()
                    .uri("/metrics")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        let status = response.status();
        assert!(
            status == StatusCode::FORBIDDEN || status == StatusCode::UNAUTHORIZED,
            "Expected 403 or 401 but got {}",
            status
        );
    }

    #[tokio::test]
    async fn test_into_router_consumes_mux() {
        let mux = build_router_mux();
        let _router = mux.into_router();
        // mux is consumed, can't use it again (compile-time check)
    }

    // Category 5: Security

    #[tokio::test]
    async fn test_security_headers_present() {
        let mux = build_router_mux();
        let app = mux.into_router();

        let response = app
            .oneshot(
                Request::builder()
                    .uri("/health")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        let headers = response.headers();

        // Check core security headers are present and have correct values
        assert_eq!(
            headers
                .get("x-content-type-options")
                .unwrap()
                .to_str()
                .unwrap(),
            "nosniff"
        );
        assert_eq!(
            headers.get("x-frame-options").unwrap().to_str().unwrap(),
            "DENY"
        );
        assert_eq!(
            headers.get("x-xss-protection").unwrap().to_str().unwrap(),
            "1; mode=block"
        );

        // Check new 0.9.0 security headers
        assert_eq!(
            headers
                .get("strict-transport-security")
                .unwrap()
                .to_str()
                .unwrap(),
            "max-age=31536000; includeSubDomains"
        );
        assert_eq!(
            headers.get("cache-control").unwrap().to_str().unwrap(),
            "no-store, no-cache, must-revalidate"
        );
        assert_eq!(
            headers.get("referrer-policy").unwrap().to_str().unwrap(),
            "strict-origin-when-cross-origin"
        );
        assert_eq!(
            headers
                .get("x-dns-prefetch-control")
                .unwrap()
                .to_str()
                .unwrap(),
            "off"
        );

        // Check Permissions-Policy
        let p_policy = headers.get("permissions-policy").unwrap().to_str().unwrap();
        assert!(p_policy.contains("camera=()"));
        assert!(p_policy.contains("microphone=()"));
        assert!(p_policy.contains("geolocation=()"));

        // Check Content-Security-Policy
        let csp = headers
            .get("content-security-policy")
            .unwrap()
            .to_str()
            .unwrap();
        assert!(csp.contains("default-src 'none'"));
        assert!(csp.contains("base-uri 'none'"));
        assert!(csp.contains("frame-ancestors 'none'"));
        assert!(csp.contains("form-action 'none'"));

        // Check Isolation Headers
        assert_eq!(
            headers
                .get("cross-origin-opener-policy")
                .unwrap()
                .to_str()
                .unwrap(),
            "same-origin"
        );
        assert_eq!(
            headers
                .get("cross-origin-embedder-policy")
                .unwrap()
                .to_str()
                .unwrap(),
            "require-corp"
        );
        assert_eq!(
            headers
                .get("cross-origin-resource-policy")
                .unwrap()
                .to_str()
                .unwrap(),
            "same-origin"
        );
    }

    #[tokio::test]
    async fn test_cors_headers_absent_by_default() {
        let mux = build_router_mux();
        let app = mux.into_router();

        let response = app
            .oneshot(
                Request::builder()
                    .uri("/health")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        let headers = response.headers();
        assert!(headers.get("access-control-allow-origin").is_none());
    }

    #[test]
    fn test_parse_cors_allowed_origin_rejects_empty_values() {
        assert!(parse_cors_allowed_origin(None).is_none());
        assert!(parse_cors_allowed_origin(Some("")).is_none());
        assert!(parse_cors_allowed_origin(Some("   ")).is_none());
        assert!(parse_cors_allowed_origin(Some("javascript:alert(1)")).is_none());
        assert!(parse_cors_allowed_origin(Some("https://app.example.com/path")).is_none());
    }

    #[test]
    fn test_content_security_policy_switches_for_playground() {
        let api_csp = content_security_policy(false);
        let playground_csp = content_security_policy(true);

        assert!(api_csp.contains("default-src 'none'"));
        assert!(playground_csp.contains("default-src 'self'"));
        assert!(playground_csp.contains("https://cdn.jsdelivr.net"));
    }

    #[test]
    fn test_merge_ws_connection_init_headers_rejects_forwarded_ip_overrides() {
        let mut base_headers = HeaderMap::new();
        base_headers.insert(
            axum::http::header::AUTHORIZATION,
            axum::http::HeaderValue::from_static("Bearer handshake"),
        );

        let merged = merge_ws_connection_init_headers(
            &base_headers,
            &serde_json::json!({
                "headers": {
                    "authorization": "Bearer init-token",
                    "x-forwarded-for": "203.0.113.10"
                }
            }),
        );

        assert_eq!(
            merged
                .get(axum::http::header::AUTHORIZATION)
                .unwrap()
                .to_str()
                .unwrap(),
            "Bearer init-token"
        );
        assert!(merged.get("x-forwarded-for").is_none());
    }

    #[tokio::test]
    async fn test_prepare_execution_context_runs_middlewares_for_ws_requests() {
        let mut mux = build_router_mux();
        let auth = crate::middleware::EnhancedAuthMiddleware::with_fn(
            crate::middleware::AuthConfig::required(),
            |token| {
                let accepted = token == "ws-secret";
                Box::pin(async move {
                    if accepted {
                        Ok(crate::middleware::AuthClaims {
                            sub: Some("user-1".to_string()),
                            ..Default::default()
                        })
                    } else {
                        Err(crate::error::Error::Unauthorized("bad token".to_string()))
                    }
                })
            },
        );
        mux.add_middleware(std::sync::Arc::new(auth));

        let mut headers = HeaderMap::new();
        headers.insert(
            axum::http::header::AUTHORIZATION,
            axum::http::HeaderValue::from_static("Bearer ws-secret"),
        );

        let ctx = mux
            .prepare_execution_context(&headers)
            .await
            .expect("middleware-authenticated websocket context");

        assert_eq!(
            ctx.get("auth.authenticated"),
            Some(&serde_json::json!(true))
        );
        assert_eq!(ctx.user_id().as_deref(), Some("user-1"));
    }

    #[tokio::test]
    async fn test_live_queries_bypass_response_cache() {
        let mut mux = build_router_mux();
        mux.enable_response_cache(crate::cache::CacheConfig::default());

        let stripped_query = "query { __schema { queryType { name } } }";
        let request = async_graphql::Request::new(stripped_query).data(LiveQueryRequestMarker);

        let response = mux.handle_http(HeaderMap::new(), request).await;
        assert!(
            response.errors.is_empty(),
            "live query should execute successfully"
        );

        let cache_key = crate::cache::ResponseCache::generate_cache_key(
            stripped_query,
            Some(&serde_json::json!({})),
            None,
            &[],
        );

        let cache_lookup = mux
            .response_cache()
            .expect("response cache enabled")
            .get(&cache_key)
            .await;

        assert!(
            matches!(cache_lookup, crate::cache::CacheLookupResult::Miss),
            "live query responses must not be cached"
        );
    }
}