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
//! Gateway builder and main orchestration
use crate::compression::CompressionConfig;
use crate::error::{GraphQLError, Result};
use crate::grpc_client::{GrpcClient, GrpcClientPool};
use crate::headers::HeaderPropagationConfig;
use crate::middleware::Middleware;
use crate::plugin::{Plugin, PluginRegistry};
use crate::request_collapsing::RequestCollapsingConfig;
use crate::rest_connector::{RestConnector, RestConnectorRegistry};
use crate::runtime::ServeMux;
use crate::schema::{DynamicSchema, SchemaBuilder};
use crate::shutdown::{run_with_graceful_shutdown, ShutdownConfig};
use axum::Router;
use std::path::Path;
use std::sync::Arc;
/// Main Gateway struct - entry point for the library
///
/// The `Gateway` orchestrates the GraphQL schema, gRPC clients, and HTTP/WebSocket server.
/// It is created via the [`GatewayBuilder`].
///
/// # Example
///
/// ```rust,no_run
/// use grpc_graphql_gateway::{Gateway, GrpcClient};
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let gateway = Gateway::builder()
/// // ... configuration ...
/// .build()?;
///
/// gateway.serve("0.0.0.0:8080").await?;
/// # Ok(())
/// # }
/// ```
pub struct Gateway {
mux: ServeMux,
client_pool: GrpcClientPool,
schema: DynamicSchema,
}
impl Gateway {
/// Create a new gateway builder
pub fn builder() -> GatewayBuilder {
GatewayBuilder::new()
}
/// Get the ServeMux
pub fn mux(&self) -> &ServeMux {
&self.mux
}
/// Access the built GraphQL schema
pub fn schema(&self) -> &DynamicSchema {
&self.schema
}
/// Get the client pool
pub fn client_pool(&self) -> &GrpcClientPool {
&self.client_pool
}
/// Convert gateway into Axum router
pub fn into_router(self) -> Router {
self.mux.into_router()
}
}
/// Builder for creating a Gateway
///
/// # Example
///
/// ```rust,no_run
/// use grpc_graphql_gateway::{Gateway, GrpcClient};
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let gateway = Gateway::builder()
/// .with_descriptor_set_file("path/to/descriptor.bin")?
/// .add_grpc_client("my.service", GrpcClient::new("http://localhost:50051").await?)
/// .build()?;
/// # Ok(())
/// # }
/// ```
pub struct GatewayBuilder {
client_pool: GrpcClientPool,
schema_builder: SchemaBuilder,
middlewares: Vec<Arc<dyn Middleware>>,
error_handler: Option<Arc<dyn Fn(Vec<GraphQLError>) + Send + Sync>>,
entity_resolver: Option<Arc<dyn crate::federation::EntityResolver>>,
service_allowlist: Option<std::collections::HashSet<String>>,
/// Enable health check endpoints
health_checks_enabled: bool,
/// Enable metrics endpoint
metrics_enabled: bool,
/// Enable OpenTelemetry tracing
tracing_enabled: bool,
/// APQ configuration
apq_config: Option<crate::persisted_queries::PersistedQueryConfig>,
/// Circuit breaker configuration
circuit_breaker_config: Option<crate::circuit_breaker::CircuitBreakerConfig>,
/// Graceful shutdown configuration
shutdown_config: Option<ShutdownConfig>,
/// Response cache configuration
cache_config: Option<crate::cache::CacheConfig>,
/// Compression configuration
compression_config: Option<CompressionConfig>,
/// Header propagation configuration
header_propagation_config: Option<HeaderPropagationConfig>,
/// Query whitelist configuration
query_whitelist_config: Option<crate::query_whitelist::QueryWhitelistConfig>,
/// REST connector registry
rest_connectors: RestConnectorRegistry,
/// Query analytics configuration
analytics_config: Option<crate::analytics::AnalyticsConfig>,
/// Request collapsing configuration
request_collapsing_config: Option<RequestCollapsingConfig>,
/// High-performance configuration
high_perf_config: Option<crate::high_performance::HighPerfConfig>,
/// @defer incremental delivery configuration
defer_config: Option<crate::defer::DeferConfig>,
/// Plugin registry
plugins: PluginRegistry,
}
impl GatewayBuilder {
/// Create a new gateway builder
pub fn new() -> Self {
Self {
client_pool: GrpcClientPool::new(),
schema_builder: SchemaBuilder::new(),
middlewares: Vec::new(),
error_handler: None,
entity_resolver: None,
service_allowlist: None,
health_checks_enabled: false,
metrics_enabled: false,
tracing_enabled: false,
apq_config: None,
circuit_breaker_config: None,
shutdown_config: None,
cache_config: None,
compression_config: None,
header_propagation_config: None,
query_whitelist_config: None,
rest_connectors: RestConnectorRegistry::new(),
analytics_config: None,
request_collapsing_config: None,
high_perf_config: None,
defer_config: None,
plugins: PluginRegistry::new(),
}
}
/// Add a gRPC client to the pool
///
/// # Arguments
///
/// * `name` - The service name (e.g., "my.package.Service")
/// * `client` - The `GrpcClient` instance
pub fn add_grpc_client(self, name: impl Into<String>, client: GrpcClient) -> Self {
self.client_pool.add(name, client);
self
}
/// Add many gRPC clients in one shot.
pub fn add_grpc_clients<I>(self, clients: I) -> Self
where
I: IntoIterator<Item = (String, GrpcClient)>,
{
for (name, client) in clients {
self.client_pool.add(name, client);
}
self
}
/// Add middleware
pub fn add_middleware<M: Middleware + 'static>(mut self, middleware: M) -> Self {
self.middlewares.push(Arc::new(middleware));
self
}
/// Register a plugin
pub fn register_plugin<P>(mut self, plugin: P) -> Self
where
P: Plugin + 'static,
P::Error: Into<Box<dyn std::error::Error + Send + Sync>>,
{
self.plugins.register(plugin);
self
}
/// Register a WASM plugin from a `.wasm` file.
///
/// The plugin runs in a sandboxed WebAssembly environment with configurable
/// memory limits and CPU fuel budgets. A faulty WASM module cannot crash
/// the host process.
///
/// # Example
///
/// ```rust,no_run
/// use grpc_graphql_gateway::{Gateway, WasmPluginConfig};
/// use std::path::PathBuf;
///
/// # fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let gateway = Gateway::builder()
/// .register_wasm_plugin(WasmPluginConfig {
/// name: "auth-plugin".to_string(),
/// path: PathBuf::from("plugins/auth.wasm"),
/// max_memory_bytes: 16 * 1024 * 1024,
/// max_fuel: 1_000_000,
/// config: serde_json::json!({"api_key_header": "X-API-Key"}),
/// })?
/// // ... other configuration
/// # ;
/// # Ok(())
/// # }
/// ```
#[cfg(feature = "wasm")]
pub fn register_wasm_plugin(
mut self,
config: crate::wasm_plugin::WasmPluginConfig,
) -> Result<Self> {
let engine = crate::wasm_plugin::WasmPluginEngine::new()?;
let plugin = engine.load_plugin(config)?;
self.plugins.register(plugin);
Ok(self)
}
/// Load all `.wasm` plugins from a directory.
///
/// Each `.wasm` file is loaded with the given default resource limits.
/// The plugin name is derived from the filename (e.g., `auth.wasm` → `"auth"`).
///
/// # Example
///
/// ```rust,no_run
/// use grpc_graphql_gateway::Gateway;
///
/// # fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let gateway = Gateway::builder()
/// .load_wasm_plugins_from_dir("./plugins", Default::default())?
/// // ... other configuration
/// # ;
/// # Ok(())
/// # }
/// ```
#[cfg(feature = "wasm")]
pub fn load_wasm_plugins_from_dir(
mut self,
dir: impl AsRef<std::path::Path>,
default_limits: crate::wasm_plugin::WasmResourceLimits,
) -> Result<Self> {
let dir = dir.as_ref();
// BB-11: Resolve the canonical path of the plugin directory so we can
// prevent symlink-based path traversal attacks below.
let canonical_dir = dir.canonicalize().map_err(|e| {
crate::error::Error::WasmPlugin(format!(
"Failed to canonicalize WASM plugin directory '{}': {}",
dir.display(),
e
))
})?;
let entries = std::fs::read_dir(dir).map_err(|e| {
crate::error::Error::WasmPlugin(format!(
"Failed to read WASM plugin directory '{}': {}",
dir.display(),
e
))
})?;
let engine = crate::wasm_plugin::WasmPluginEngine::new()?;
let mut count = 0;
// BB-13: Cap the number of plugins to prevent startup resource exhaustion.
const MAX_WASM_PLUGINS: usize = 50;
'outer: for entry in entries {
if count >= MAX_WASM_PLUGINS {
tracing::warn!(
directory = %dir.display(),
limit = MAX_WASM_PLUGINS,
"WASM plugin limit reached — remaining files in directory are skipped"
);
break 'outer;
}
let entry = entry.map_err(|e| {
crate::error::Error::WasmPlugin(format!("Failed to read directory entry: {}", e))
})?;
let path = entry.path();
if path.extension().and_then(|e| e.to_str()) != Some("wasm") {
continue;
}
// BB-11: Resolve the canonical path and verify it is still inside the
// plugin directory. This blocks symlinks that point outside the dir.
match path.canonicalize() {
Ok(canonical_path) => {
if !canonical_path.starts_with(&canonical_dir) {
tracing::warn!(
path = %path.display(),
canonical = %canonical_path.display(),
plugin_dir = %canonical_dir.display(),
"Skipping WASM plugin: resolved path is outside the plugin directory (symlink attack?)"
);
continue;
}
}
Err(e) => {
tracing::warn!(
path = %path.display(),
error = %e,
"Skipping WASM plugin: failed to resolve canonical path"
);
continue;
}
}
let name = path
.file_stem()
.and_then(|s| s.to_str())
.unwrap_or("unknown")
.to_string();
let config = crate::wasm_plugin::WasmPluginConfig {
name: name.clone(),
path: path.clone(),
max_memory_bytes: default_limits.max_memory_bytes,
max_fuel: default_limits.max_fuel,
config: serde_json::Value::Null,
};
match engine.load_plugin(config) {
Ok(plugin) => {
tracing::info!(
plugin = %name,
path = %path.display(),
"🧩 Loaded WASM plugin from directory"
);
self.plugins.register(plugin);
count += 1;
}
Err(e) => {
tracing::warn!(
plugin = %name,
path = %path.display(),
error = %e,
"⚠️ Failed to load WASM plugin, skipping"
);
}
}
}
tracing::info!(
directory = %dir.display(),
loaded_count = count,
"🧩 WASM plugin directory scan complete"
);
Ok(self)
}
/// Provide the primary protobuf descriptor set (bytes).
///
/// This clears any existing descriptors and sets this as the primary.
/// Use [`Self::add_descriptor_set_bytes`] to add additional descriptor sets for schema stitching.
///
/// # Example
///
/// ```rust,no_run
/// use grpc_graphql_gateway::Gateway;
///
/// const DESCRIPTORS: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/descriptor.bin"));
///
/// # fn example() {
/// let gateway = Gateway::builder()
/// .with_descriptor_set_bytes(DESCRIPTORS);
/// # }
/// ```
pub fn with_descriptor_set_bytes(mut self, bytes: impl AsRef<[u8]>) -> Self {
self.schema_builder = self.schema_builder.with_descriptor_set_bytes(bytes);
self
}
/// Add an additional protobuf descriptor set (bytes) for schema stitching.
///
/// Use this to combine multiple protobuf descriptor sets from different
/// microservices into a unified GraphQL schema.
///
/// # Example
///
/// ```rust,no_run
/// use grpc_graphql_gateway::Gateway;
///
/// const USERS_DESCRIPTORS: &[u8] = include_bytes!("path/to/users.bin");
/// const PRODUCTS_DESCRIPTORS: &[u8] = include_bytes!("path/to/products.bin");
/// const ORDERS_DESCRIPTORS: &[u8] = include_bytes!("path/to/orders.bin");
///
/// # fn example() {
/// let gateway = Gateway::builder()
/// .with_descriptor_set_bytes(USERS_DESCRIPTORS)
/// .add_descriptor_set_bytes(PRODUCTS_DESCRIPTORS)
/// .add_descriptor_set_bytes(ORDERS_DESCRIPTORS);
/// # }
/// ```
pub fn add_descriptor_set_bytes(mut self, bytes: impl AsRef<[u8]>) -> Self {
self.schema_builder = self.schema_builder.add_descriptor_set_bytes(bytes);
self
}
/// Provide a custom entity resolver for federation.
pub fn with_entity_resolver(
mut self,
resolver: Arc<dyn crate::federation::EntityResolver>,
) -> Self {
// BB-14: Store only one Arc reference; build() will pass it to schema_builder.
// Previously the Arc was cloned into self.entity_resolver AND moved into
// schema_builder, creating two independent registrations.
self.entity_resolver = Some(resolver);
self
}
/// Restrict the schema to the provided gRPC service full names.
pub fn with_services<I, S>(mut self, services: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
let set: std::collections::HashSet<String> = services.into_iter().map(Into::into).collect();
self.schema_builder = self.schema_builder.with_services(set.clone());
self.service_allowlist = Some(set);
self
}
/// Enable GraphQL federation features.
pub fn enable_federation(mut self) -> Self {
self.schema_builder = self.schema_builder.enable_federation();
self
}
/// Provide the primary protobuf descriptor set file.
///
/// This clears any existing descriptors and sets this as the primary.
/// Use [`Self::add_descriptor_set_file`] to add additional descriptor sets.
pub fn with_descriptor_set_file(mut self, path: impl AsRef<Path>) -> Result<Self> {
self.schema_builder = self.schema_builder.with_descriptor_set_file(path)?;
Ok(self)
}
/// Add an additional protobuf descriptor set file for schema stitching.
///
/// Use this to combine multiple protobuf descriptor sets from different
/// microservices into a unified GraphQL schema.
///
/// # Example
///
/// ```rust,no_run
/// use grpc_graphql_gateway::Gateway;
///
/// # fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let gateway = Gateway::builder()
/// .with_descriptor_set_file("path/to/users.bin")?
/// .add_descriptor_set_file("path/to/products.bin")?
/// .add_descriptor_set_file("path/to/orders.bin")?;
/// # Ok(())
/// # }
/// ```
pub fn add_descriptor_set_file(mut self, path: impl AsRef<Path>) -> Result<Self> {
self.schema_builder = self.schema_builder.add_descriptor_set_file(path)?;
Ok(self)
}
/// Provide a handler to inspect/augment GraphQL errors before they are returned.
pub fn with_error_handler<F>(mut self, handler: F) -> Self
where
F: Fn(Vec<GraphQLError>) + Send + Sync + 'static,
{
self.error_handler = Some(Arc::new(handler));
self
}
/// Set the maximum query depth (nesting level) allowed.
///
/// This is a critical DoS protection mechanism that prevents deeply nested queries
/// from overwhelming your gRPC backends. Queries exceeding this depth will return
/// an error: "Query is nested too deep".
///
/// # Example
///
/// ```rust,no_run
/// use grpc_graphql_gateway::Gateway;
///
/// # fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let gateway = Gateway::builder()
/// .with_query_depth_limit(10) // Max 10 levels of nesting
/// // ... other configuration
/// # ;
/// # Ok(())
/// # }
/// ```
///
/// # Recommended Values
///
/// - **5-10**: Strict, suitable for simple APIs
/// - **10-15**: Moderate, good for most production use cases
/// - **15-25**: Lenient, for complex nested schemas
pub fn with_query_depth_limit(mut self, max_depth: usize) -> Self {
self.schema_builder = self.schema_builder.with_query_depth_limit(max_depth);
self
}
/// Set the maximum query complexity allowed.
///
/// This is a critical DoS protection mechanism that limits the total "cost" of a query.
/// Each field in a query adds to the complexity (default: 1 per field).
/// Queries exceeding this limit will return an error: "Query is too complex".
///
/// # Example
///
/// ```rust,no_run
/// use grpc_graphql_gateway::Gateway;
///
/// # fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let gateway = Gateway::builder()
/// .with_query_complexity_limit(100) // Max complexity of 100
/// // ... other configuration
/// # ;
/// # Ok(())
/// # }
/// ```
///
/// # How Complexity is Calculated
///
/// - Each scalar field adds 1 to complexity
/// - Nested objects add their fields' complexity
/// - List fields multiply by the expected count
///
/// # Recommended Values
///
/// - **50-100**: Strict, suitable for public APIs
/// - **100-500**: Moderate, good for authenticated users
/// - **500-1000**: Lenient, for internal/trusted clients
pub fn with_query_complexity_limit(mut self, max_complexity: usize) -> Self {
self.schema_builder = self
.schema_builder
.with_query_complexity_limit(max_complexity);
self
}
/// Enable health check endpoints (`/health` and `/ready`).
///
/// These endpoints are essential for Kubernetes liveness and readiness probes.
///
/// # Endpoints
///
/// - `GET /health` - Liveness probe, returns 200 if server is running
/// - `GET /ready` - Readiness probe, checks gRPC client configuration
///
/// # Example
///
/// ```rust,no_run
/// use grpc_graphql_gateway::Gateway;
///
/// # fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let gateway = Gateway::builder()
/// .enable_health_checks()
/// // ... other configuration
/// # ;
/// # Ok(())
/// # }
/// ```
pub fn enable_health_checks(mut self) -> Self {
self.health_checks_enabled = true;
self
}
/// Enable Prometheus metrics endpoint (`/metrics`).
///
/// Exposes metrics for monitoring GraphQL request performance and gRPC backend health.
///
/// # Metrics Exposed
///
/// - `graphql_requests_total` - Total GraphQL requests by operation type
/// - `graphql_request_duration_seconds` - Request latency histogram
/// - `graphql_errors_total` - Total GraphQL errors
/// - `grpc_backend_requests_total` - Total gRPC backend calls
/// - `grpc_backend_duration_seconds` - gRPC backend latency histogram
///
/// # Example
///
/// ```rust,no_run
/// use grpc_graphql_gateway::Gateway;
///
/// # fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let gateway = Gateway::builder()
/// .enable_metrics()
/// // ... other configuration
/// # ;
/// # Ok(())
/// # }
/// ```
pub fn enable_metrics(mut self) -> Self {
self.metrics_enabled = true;
self
}
/// Enable OpenTelemetry distributed tracing.
///
/// Creates spans for GraphQL operations and gRPC backend calls,
/// enabling end-to-end visibility across your distributed system.
///
/// # Spans Created
///
/// - `graphql.query` / `graphql.mutation` - For GraphQL operations
/// - `grpc.call` - For gRPC backend calls
///
/// # Example
///
/// ```rust,no_run
/// use grpc_graphql_gateway::Gateway;
///
/// # fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let gateway = Gateway::builder()
/// .enable_tracing()
/// // ... other configuration
/// # ;
/// # Ok(())
/// # }
/// ```
pub fn enable_tracing(mut self) -> Self {
self.tracing_enabled = true;
self
}
/// Disable GraphQL introspection queries.
///
/// This is a security best practice for production environments to prevent
/// attackers from discovering your schema structure through `__schema` and `__type` queries.
///
/// # Example
///
/// ```rust,no_run
/// use grpc_graphql_gateway::Gateway;
///
/// # fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let gateway = Gateway::builder()
/// .disable_introspection()
/// // ... other configuration
/// # ;
/// # Ok(())
/// # }
/// ```
///
/// # Environment-Based Toggle
///
/// ```rust,no_run
/// use grpc_graphql_gateway::Gateway;
///
/// # fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let is_prod = std::env::var("ENV").map(|e| e == "production").unwrap_or(false);
///
/// let mut builder = Gateway::builder();
/// if is_prod {
/// builder = builder.disable_introspection();
/// }
/// # Ok(())
/// # }
/// ```
pub fn disable_introspection(mut self) -> Self {
self.schema_builder = self.schema_builder.disable_introspection();
self
}
/// Enable Automatic Persisted Queries (APQ).
///
/// APQ reduces bandwidth by allowing clients to send a hash of the query instead
/// of the full query string. Queries are cached on the server and retrieved by hash.
///
/// # How It Works
///
/// 1. Client sends hash only → Server returns "PersistedQueryNotFound"
/// 2. Client sends hash + query → Server caches and executes
/// 3. Subsequent requests send hash only → Server uses cached query
///
/// # Example
///
/// ```rust,no_run
/// use grpc_graphql_gateway::{Gateway, PersistedQueryConfig};
/// use std::time::Duration;
///
/// # fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let gateway = Gateway::builder()
/// .with_persisted_queries(PersistedQueryConfig {
/// cache_size: 1000,
/// ttl: Some(Duration::from_secs(3600)),
/// })
/// // ... other configuration
/// # ;
/// # Ok(())
/// # }
/// ```
///
/// # Default Configuration
///
/// Use `PersistedQueryConfig::default()` for sensible defaults:
/// - `cache_size`: 1000 queries
/// - `ttl`: None (no expiration)
pub fn with_persisted_queries(
mut self,
config: crate::persisted_queries::PersistedQueryConfig,
) -> Self {
self.apq_config = Some(config);
self
}
/// Enable Circuit Breaker for gRPC backend resilience.
///
/// The Circuit Breaker prevents cascading failures by "breaking" the circuit
/// when a backend service is unhealthy, giving it time to recover.
///
/// # States
///
/// - **Closed**: Normal operation, requests flow through
/// - **Open**: Service unhealthy, requests fail fast (returns error immediately)
/// - **Half-Open**: Testing recovery, limited requests allowed
///
/// # Example
///
/// ```rust,no_run
/// use grpc_graphql_gateway::{Gateway, CircuitBreakerConfig};
/// use std::time::Duration;
///
/// # fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let gateway = Gateway::builder()
/// .with_circuit_breaker(CircuitBreakerConfig {
/// failure_threshold: 5, // Open after 5 failures
/// recovery_timeout: Duration::from_secs(30), // Try recovery after 30s
/// half_open_max_requests: 3, // Allow 3 test requests
/// })
/// // ... other configuration
/// # ;
/// # Ok(())
/// # }
/// ```
///
/// # Default Configuration
///
/// Use `CircuitBreakerConfig::default()` for sensible defaults:
/// - `failure_threshold`: 5 consecutive failures
/// - `recovery_timeout`: 30 seconds
/// - `half_open_max_requests`: 3 test requests
pub fn with_circuit_breaker(
mut self,
config: crate::circuit_breaker::CircuitBreakerConfig,
) -> Self {
self.circuit_breaker_config = Some(config);
self
}
/// Enable response caching for GraphQL queries.
///
/// Response caching stores complete GraphQL responses in memory and serves
/// them directly for subsequent identical requests, dramatically reducing
/// latency and backend load.
///
/// # Features
///
/// - **LRU Eviction**: Oldest entries are removed when cache is full
/// - **TTL Expiration**: Entries expire after a configurable duration
/// - **Stale-While-Revalidate**: Serve stale content while refreshing in background
/// - **Mutation Invalidation**: Automatically invalidate cache when mutations run
/// - **Type/Entity Tracking**: Fine-grained invalidation by type or entity ID
/// - **Redis Support**: Distributed caching by setting `redis_url` in `CacheConfig`
///
/// # Example
///
/// ```rust,no_run
/// use grpc_graphql_gateway::{Gateway, CacheConfig};
/// use std::time::Duration;
///
/// # fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let gateway = Gateway::builder()
/// .with_response_cache(CacheConfig {
/// max_size: 10_000, // Max 10k cached responses
/// default_ttl: Duration::from_secs(60), // 1 minute TTL
/// stale_while_revalidate: Some(Duration::from_secs(30)), // Serve stale for 30s
/// invalidate_on_mutation: true, // Auto-invalidate on mutations
/// redis_url: Some("redis://127.0.0.1:6379".to_string()), // Use Redis
/// vary_headers: vec!["Authorization".to_string()], // Include auth in cache key
/// })
/// // ... other configuration
/// # ;
/// # Ok(())
/// # }
/// ```
///
/// # What Gets Cached
///
/// - ✅ Queries (GET and POST)
/// - ❌ Mutations (never cached, trigger invalidation)
/// - ❌ Subscriptions (streaming, not cacheable)
///
/// # Cache Key
///
/// The cache key is a SHA-256 hash of:
/// - Normalized query string
/// - Sorted variables JSON
/// - Operation name (if provided)
/// - Vary headers (e.g. Authorization)
pub fn with_response_cache(mut self, config: crate::cache::CacheConfig) -> Self {
self.cache_config = Some(config);
self
}
/// Enable high-performance optimizations for 100K+ RPS.
///
/// This enables features like SIMD-accelerated JSON parsing, lock-free
/// sharded caching, and optimized gRPC connection pool settings.
///
/// # Example
///
/// ```rust,no_run
/// use grpc_graphql_gateway::{Gateway, HighPerfConfig};
///
/// # fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let gateway = Gateway::builder()
/// .with_high_performance(HighPerfConfig::ultra_fast())
/// // ... other configuration
/// # ;
/// # Ok(())
/// # }
/// ```
pub fn with_high_performance(
mut self,
config: crate::high_performance::HighPerfConfig,
) -> Self {
self.high_perf_config = Some(config);
self
}
/// Enable response compression with gzip, brotli, and deflate.
///
/// Response compression reduces bandwidth usage by compressing HTTP response bodies
/// before sending them to clients. This is particularly beneficial for GraphQL responses
/// which are typically JSON and compress very well (50-90% size reduction).
///
/// # Supported Algorithms
///
/// - **Brotli** (`br`) - Best compression ratio, preferred for modern browsers
/// - **Gzip** (`gzip`) - Widely supported, good compression
/// - **Deflate** (`deflate`) - Legacy support
/// - **Zstd** (`zstd`) - Modern, fast compression
///
/// # Example
///
/// ```rust,no_run
/// use grpc_graphql_gateway::{Gateway, CompressionConfig, CompressionLevel};
///
/// # fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let gateway = Gateway::builder()
/// .with_compression(CompressionConfig {
/// enabled: true,
/// level: CompressionLevel::Default,
/// min_size_bytes: 1024, // Only compress responses > 1KB
/// algorithms: vec!["br".into(), "gzip".into()],
/// })
/// // ... other configuration
/// # ;
/// # Ok(())
/// # }
/// ```
///
/// # Preset Configurations
///
/// Use preset configs for common use cases:
///
/// ```rust,no_run
/// use grpc_graphql_gateway::{Gateway, CompressionConfig};
///
/// // Fast compression for low latency
/// # fn fast() { let _ =
/// Gateway::builder().with_compression(CompressionConfig::fast())
/// # ; }
///
/// // Best compression for bandwidth savings
/// # fn best() { let _ =
/// Gateway::builder().with_compression(CompressionConfig::best())
/// # ; }
///
/// // Default balanced configuration
/// # fn default() { let _ =
/// Gateway::builder().with_compression(CompressionConfig::default())
/// # ; }
/// ```
///
/// # Performance Considerations
///
/// - **CPU Cost**: Compression uses CPU. Use `CompressionLevel::Fast` for latency-sensitive apps.
/// - **Min Size**: Set `min_size_bytes` to skip compression for small responses.
/// - **Caching**: Compressed responses work well with the response cache.
pub fn with_compression(mut self, config: CompressionConfig) -> Self {
self.compression_config = Some(config);
self
}
/// Enable header propagation from GraphQL requests to gRPC backends.
///
/// This forwards specified HTTP headers from incoming GraphQL requests
/// to outgoing gRPC metadata. Essential for authentication, distributed
/// tracing, and context propagation.
///
/// # Security
///
/// Uses an **allowlist** approach - only explicitly configured headers
/// are forwarded to prevent accidental leakage of sensitive data.
///
/// # Example
///
/// ```rust,no_run
/// use grpc_graphql_gateway::{Gateway, HeaderPropagationConfig};
///
/// # fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let gateway = Gateway::builder()
/// .with_header_propagation(HeaderPropagationConfig::new()
/// .propagate("authorization")
/// .propagate("x-request-id")
/// .propagate("x-tenant-id"))
/// // ... other configuration
/// # ;
/// # Ok(())
/// # }
/// ```
///
/// # Common Headers
///
/// Use `HeaderPropagationConfig::common()` for a preset that includes:
/// - `authorization` - Bearer tokens
/// - `x-request-id`, `x-correlation-id` - Request tracking
/// - `traceparent`, `tracestate` - W3C Trace Context
/// - `x-b3-*` - Zipkin B3 headers
///
/// ```rust,no_run
/// use grpc_graphql_gateway::{Gateway, HeaderPropagationConfig};
///
/// # fn example() { let _ =
/// Gateway::builder().with_header_propagation(HeaderPropagationConfig::common())
/// # ; }
/// ```
pub fn with_header_propagation(mut self, config: HeaderPropagationConfig) -> Self {
self.header_propagation_config = Some(config);
self
}
/// Enable query whitelisting for production security.
///
/// Query whitelisting (also known as "Stored Operations" or "Persisted Operations")
/// restricts which GraphQL queries can be executed. This is a **critical security feature**
/// for public-facing GraphQL APIs that prevents malicious or arbitrary queries.
///
/// # Security Benefits
///
/// - **No Arbitrary Queries**: Only pre-approved queries can be executed
/// - **Reduced Attack Surface**: Prevents schema exploration and DoS attacks
/// - **Compliance**: Required for PCI-DSS and other security standards
/// - **Performance**: Known queries can be optimized and monitored
///
/// # Modes
///
/// - `WhitelistMode::Enforce` - Reject non-whitelisted queries (production)
/// - `WhitelistMode::Warn` - Log warnings but allow all queries (staging)
/// - `WhitelistMode::Disabled` - No whitelist checking (development)
///
/// # Example
///
/// ```rust,no_run
/// use grpc_graphql_gateway::{Gateway, QueryWhitelistConfig, WhitelistMode};
/// use std::collections::HashMap;
///
/// # fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let mut allowed_queries = HashMap::new();
/// allowed_queries.insert(
/// "getUserById".to_string(),
/// "query getUserById($id: ID!) { user(id: $id) { id name email } }".to_string()
/// );
/// allowed_queries.insert(
/// "listProducts".to_string(),
/// "query { products { id name price } }".to_string()
/// );
///
/// let gateway = Gateway::builder()
/// .with_query_whitelist(QueryWhitelistConfig {
/// mode: WhitelistMode::Enforce,
/// allowed_queries,
/// allow_introspection: true, // Allow introspection in dev/staging
/// })
/// // ... other configuration
/// # ;
/// # Ok(())
/// # }
/// ```
///
/// # Loading from File
///
/// ```rust,no_run
/// use grpc_graphql_gateway::{Gateway, QueryWhitelistConfig, WhitelistMode};
///
/// # fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let config = QueryWhitelistConfig::from_json_file(
/// "allowed_queries.json",
/// WhitelistMode::Enforce
/// )?;
///
/// let gateway = Gateway::builder()
/// .with_query_whitelist(config)
/// // ... other configuration
/// # ;
/// # Ok(())
/// # }
/// ```
///
/// # Builder Pattern
///
/// ```rust,no_run
/// use grpc_graphql_gateway::{Gateway, QueryWhitelistConfig, WhitelistMode};
///
/// # fn example() { let _ =
/// Gateway::builder()
/// .with_query_whitelist(
/// QueryWhitelistConfig::enforce()
/// .add_query("getUser".into(), "query { user { id } }".into())
/// .add_query("listPosts".into(), "query { posts { title } }".into())
/// .with_introspection(false) // Disable introspection in production
/// )
/// # ; }
/// ```
///
/// # How Validation Works
///
/// The whitelist validates queries by:
/// 1. **Operation ID**: If client provides an operation ID (via extensions), validate by ID
/// 2. **Query Hash**: Calculate SHA-256 hash of query and validate by hash
/// 3. **Introspection**: Optionally allow `__schema` and `__type` queries
///
/// # Client Integration
///
/// Clients can reference queries by ID using GraphQL extensions:
///
/// ```json
/// {
/// "operationName": "getUserById",
/// "variables": {"id": "123"},
/// "extensions": {
/// "operationId": "getUserById"
/// }
/// }
/// ```
///
/// # Works with APQ
///
/// Query whitelisting works alongside Automatic Persisted Queries (APQ):
/// - **APQ**: Caches any query after first use (bandwidth optimization)
/// - **Whitelist**: Only allows pre-approved queries (security)
///
/// Use both together for maximum security and performance.
pub fn with_query_whitelist(
mut self,
config: crate::query_whitelist::QueryWhitelistConfig,
) -> Self {
self.query_whitelist_config = Some(config);
self
}
/// Add a REST API connector for hybrid gRPC/REST architectures.
///
/// REST connectors allow you to resolve GraphQL fields from REST APIs
/// alongside gRPC services, enabling gradual migration or integration
/// with existing REST backends.
///
/// # Example
///
/// ```rust,no_run
/// use grpc_graphql_gateway::{Gateway, RestConnector, RestEndpoint, HttpMethod};
/// use std::time::Duration;
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let rest_connector = RestConnector::builder()
/// .base_url("https://api.example.com")
/// .timeout(Duration::from_secs(30))
/// .default_header("Accept", "application/json")
/// .add_endpoint(RestEndpoint::new("getUser", "/users/{id}")
/// .method(HttpMethod::GET)
/// .description("Fetch a user by ID"))
/// .add_endpoint(RestEndpoint::new("createUser", "/users")
/// .method(HttpMethod::POST)
/// .body_template(r#"{"name": "{name}", "email": "{email}"}"#))
/// .build()?;
///
/// let gateway = Gateway::builder()
/// .add_rest_connector("users_api", rest_connector)
/// // ... other configuration
/// # ;
/// # Ok(())
/// # }
/// ```
///
/// # Multiple Connectors
///
/// You can add multiple REST connectors for different services:
///
/// ```rust,no_run
/// use grpc_graphql_gateway::{Gateway, RestConnector, RestEndpoint};
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let users_api = RestConnector::builder()
/// .base_url("https://users.example.com")
/// .add_endpoint(RestEndpoint::new("getUser", "/users/{id}"))
/// .build()?;
///
/// let products_api = RestConnector::builder()
/// .base_url("https://products.example.com")
/// .add_endpoint(RestEndpoint::new("listProducts", "/products"))
/// .build()?;
///
/// let gateway = Gateway::builder()
/// .add_rest_connector("users", users_api)
/// .add_rest_connector("products", products_api)
/// // ... other configuration
/// # ;
/// # Ok(())
/// # }
/// ```
///
/// # Authentication
///
/// Use interceptors for authentication:
///
/// ```rust,no_run
/// use grpc_graphql_gateway::{RestConnector, RestEndpoint, BearerAuthInterceptor};
/// use std::sync::Arc;
///
/// # fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let connector = RestConnector::builder()
/// .base_url("https://api.example.com")
/// .interceptor(Arc::new(BearerAuthInterceptor::new("your-token")))
/// .add_endpoint(RestEndpoint::new("getUser", "/users/{id}"))
/// .build()?;
/// # Ok(())
/// # }
/// ```
///
/// # Use Cases
///
/// | Scenario | Description |
/// |----------|-------------|
/// | Hybrid Architecture | Mix gRPC and REST backends in one GraphQL API |
/// | Gradual Migration | Migrate from REST to gRPC incrementally |
/// | Third-Party APIs | Integrate external REST APIs into your schema |
/// | Legacy Systems | Bridge legacy REST services with modern gRPC |
pub fn add_rest_connector(mut self, name: impl Into<String>, connector: RestConnector) -> Self {
self.rest_connectors.register(name, connector);
self
}
/// Get a reference to the REST connector registry.
pub fn rest_connectors(&self) -> &RestConnectorRegistry {
&self.rest_connectors
}
/// Enable query analytics with the built-in dashboard.
///
/// Query analytics provides comprehensive insights into your GraphQL API usage:
/// - **Most Used Queries**: Track which queries are most popular
/// - **Slowest Queries**: Identify performance bottlenecks
/// - **Error Patterns**: Analyze common errors and their causes
/// - **Field Usage**: See which fields are requested most often
///
/// # Endpoints
///
/// When enabled, the following endpoints are added:
/// - `GET /analytics` - Interactive analytics dashboard
/// - `GET /analytics/api` - JSON API for analytics data
/// - `POST /analytics/reset` - Reset all analytics data
///
/// # Example
///
/// ```rust,no_run
/// use grpc_graphql_gateway::{Gateway, AnalyticsConfig};
///
/// # fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let gateway = Gateway::builder()
/// .enable_analytics(AnalyticsConfig::default())
/// // ... other configuration
/// # ;
/// # Ok(())
/// # }
/// ```
///
/// # Privacy-Conscious Configuration
///
/// For production environments where query text should not be stored:
///
/// ```rust,no_run
/// use grpc_graphql_gateway::{Gateway, AnalyticsConfig};
///
/// # fn example() { let _ =
/// Gateway::builder()
/// .enable_analytics(AnalyticsConfig::production())
/// # ; }
/// ```
///
/// # Preset Configurations
///
/// - `AnalyticsConfig::default()` - Balanced settings for most use cases
/// - `AnalyticsConfig::production()` - Privacy-focused, shorter retention
/// - `AnalyticsConfig::development()` - Verbose, longer retention for debugging
pub fn enable_analytics(mut self, config: crate::analytics::AnalyticsConfig) -> Self {
self.analytics_config = Some(config);
self
}
/// Enable request collapsing to deduplicate identical gRPC requests.
///
/// Request collapsing detects when multiple GraphQL fields in the same query
/// would trigger identical gRPC calls and collapses them into a single call,
/// sharing the response across all requesting fields.
///
/// # How It Works
///
/// When a GraphQL query contains multiple fields calling the same gRPC method
/// with the same arguments:
///
/// ```graphql
/// query {
/// user1: getUser(id: "1") { name }
/// user2: getUser(id: "2") { name }
/// user3: getUser(id: "1") { name } # Duplicate of user1
/// }
/// ```
///
/// - **Without collapsing**: 3 gRPC calls
/// - **With collapsing**: 2 gRPC calls (user1 and user3 share the same response)
///
/// # Example
///
/// ```rust,no_run
/// use grpc_graphql_gateway::{Gateway, RequestCollapsingConfig};
///
/// # fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let gateway = Gateway::builder()
/// .with_request_collapsing(RequestCollapsingConfig::default())
/// // ... other configuration
/// # ;
/// # Ok(())
/// # }
/// ```
///
/// # Preset Configurations
///
/// - `RequestCollapsingConfig::default()` - Balanced settings for most use cases
/// - `RequestCollapsingConfig::high_throughput()` - Longer coalesce window, more waiters
/// - `RequestCollapsingConfig::low_latency()` - Shorter coalesce window for speed
/// - `RequestCollapsingConfig::disabled()` - Disable collapsing entirely
///
/// # Configuration Options
///
/// ```rust,no_run
/// use grpc_graphql_gateway::RequestCollapsingConfig;
/// use std::time::Duration;
///
/// # fn example() {
/// let config = RequestCollapsingConfig::new()
/// .coalesce_window(Duration::from_millis(100)) // Wait up to 100ms for in-flight
/// .max_waiters(200) // Max 200 followers per leader
/// .max_cache_size(20000); // Track up to 20k in-flight requests
/// # }
/// ```
///
/// # When to Use
///
/// Request collapsing is most effective when:
/// - Queries frequently request the same data with aliases
/// - High-traffic scenarios where concurrent requests are common
/// - DataLoader is not applicable (e.g., non-entity resolvers)
///
/// # Relationship with Response Caching
///
/// - **Response Cache**: Caches complete responses for TTL duration
/// - **Request Collapsing**: Deduplicates in-flight requests during execution
///
/// Both features work together: collapsing handles concurrent requests,
/// while caching handles sequential repeated requests.
pub fn with_request_collapsing(mut self, config: RequestCollapsingConfig) -> Self {
self.request_collapsing_config = Some(config);
self
}
/// Enable `@defer` incremental delivery support.
///
/// When enabled, queries containing `@defer` directives will return an
/// initial payload immediately followed by incremental patches streamed
/// over a `multipart/mixed` HTTP response.
///
/// # Example
///
/// ```rust,no_run
/// use grpc_graphql_gateway::{Gateway, DeferConfig};
///
/// # fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let gateway = Gateway::builder()
/// .with_defer(DeferConfig::default())
/// // ... other configuration
/// # ;
/// # Ok(())
/// # }
/// ```
///
/// # Preset Configurations
///
/// - `DeferConfig::default()` — Balanced settings
/// - `DeferConfig::production()` — Strict limits
/// - `DeferConfig::development()` — Permissive
/// - `DeferConfig::disabled()` — Disabled (all fields resolved eagerly)
pub fn with_defer(mut self, config: crate::defer::DeferConfig) -> Self {
self.defer_config = Some(config);
self
}
/// Build the gateway
pub fn build(self) -> Result<Gateway> {
let mut schema_builder = self.schema_builder;
if let Some(resolver) = self.entity_resolver {
schema_builder = schema_builder.with_entity_resolver(resolver);
}
if let Some(services) = self.service_allowlist {
schema_builder = schema_builder.with_services(services);
}
if let Some(header_config) = self.header_propagation_config.as_ref() {
schema_builder = schema_builder.with_header_propagation(header_config.clone());
}
// Pass REST connectors to schema builder for GraphQL field generation
if !self.rest_connectors.is_empty() {
let mut registry = crate::rest_connector::RestConnectorRegistry::new();
for (name, connector) in self.rest_connectors.connectors() {
// Clone the connector into the registry (dereference Arc)
registry.register(name.clone(), (**connector).clone());
}
schema_builder = schema_builder.with_rest_connectors(registry);
}
// Plugin Hook: on_schema_build
// We need to clone plugins or pass a mutable reference. Since build consumes self,
// we can use the plugins directly but we need to deal with async in a synchronous build method.
// Wait, build is synchronous. Hooks are async.
//
// This is a problem. on_schema_build must be synchronous or build must be async.
// The Plugin trait defined on_schema_build as async.
//
// Let's check `GatewayBuilder::build` signature: public fn build(self) -> Result<Gateway>
// Use block_on to execute the async hook or change the signature?
// Changing signature is a breaking change.
//
// However, schema building is CPU intensive and usually done at startup.
// Let's use `futures::executor::block_on` or similar if available, or just tokio::task::block_in_place if inside runtime.
// But `build` might be called outside of runtime context (e.g. tests).
//
// Actually, `GatewayBuilder::serve` is async. But `build` is sync.
// Let's try to run it synchronously for now.
//
// Wait, I can't easily change the trait to be sync if it's already async in my definition.
// Let's make `on_schema_build` synchronous in the trait definition instead?
//
// Re-reading `src/plugin.rs`:
// async fn on_schema_build(&self, _builder: &mut crate::schema::SchemaBuilder) -> crate::error::Result<()> {
//
// It is async.
//
// I will use `futures::executor::block_on` to run the hooks.
// We need to add `futures` to dependencies or use `tokio::runtime::Handle::current().block_on(async { ... })`.
let plugins = self.plugins;
// BB-10: Run the async plugin hook from a synchronous `build()` without
// deadlocking the Tokio runtime.
//
// We move both `plugins` and `schema_builder` into a dedicated OS thread
// that owns its own mini single-thread Tokio runtime. After the hook
// completes, the (potentially modified) builder is sent back via a channel.
// This is safe on every Tokio runtime flavour because the spawned thread
// never touches the parent scheduler.
type HookResult = crate::error::Result<(PluginRegistry, crate::schema::SchemaBuilder)>;
let (tx, rx) = std::sync::mpsc::channel::<HookResult>();
std::thread::spawn(move || {
let result = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.map_err(|e| {
crate::error::Error::Internal(format!(
"Failed to create plugin hook runtime: {e}"
))
})
.and_then(|rt| {
rt.block_on(async move {
plugins.on_schema_build(&mut schema_builder).await?;
Ok((plugins, schema_builder))
})
});
let _ = tx.send(result);
});
let (plugins, schema_builder) = rx
.recv()
.map_err(|_| {
crate::error::Error::Internal(
"Plugin hook thread panicked before sending result".to_string(),
)
})
.and_then(|r| r)?;
let schema = schema_builder.build(&self.client_pool)?;
let mut mux = ServeMux::new(schema.clone());
mux.set_plugins(plugins);
// Add middlewares
for middleware in self.middlewares {
mux.add_middleware(middleware);
}
if let Some(handler) = self.error_handler {
mux.set_error_handler_arc(handler);
}
// Configure health checks
if self.health_checks_enabled {
mux.set_client_pool(self.client_pool.clone());
mux.enable_health_checks();
}
// Configure metrics
if self.metrics_enabled {
mux.enable_metrics();
}
// Configure APQ
if let Some(apq_config) = self.apq_config {
mux.enable_persisted_queries(apq_config);
}
// Configure Circuit Breaker
if let Some(cb_config) = self.circuit_breaker_config {
mux.enable_circuit_breaker(cb_config);
}
// Configure Response Cache
if let Some(cache_config) = self.cache_config {
mux.enable_response_cache(cache_config);
}
// Configure Compression
if let Some(compression_config) = self.compression_config {
mux.enable_compression(compression_config);
}
// Configure Query Whitelist
if let Some(whitelist_config) = self.query_whitelist_config {
mux.enable_query_whitelist(whitelist_config);
}
// Configure Analytics
if let Some(analytics_config) = self.analytics_config {
mux.enable_analytics(analytics_config);
}
// Configure Request Collapsing
if let Some(collapsing_config) = self.request_collapsing_config {
mux.enable_request_collapsing(collapsing_config);
}
// Configure High Performance mode
if let Some(high_perf_config) = self.high_perf_config {
mux.enable_high_performance(high_perf_config);
}
// Configure @defer support
if let Some(defer_config) = self.defer_config {
mux.enable_defer(defer_config);
}
Ok(Gateway {
mux,
client_pool: self.client_pool,
schema,
})
}
/// Build and start the gateway server
pub async fn serve(self, addr: impl Into<String>) -> Result<()> {
let shutdown_config = self.shutdown_config.clone();
// BB-15: Warn when health checks are disabled so operators are not silently
// left without Kubernetes liveness / readiness probes.
if !self.health_checks_enabled {
tracing::warn!(
"Health check endpoints are disabled. \
Call .enable_health_checks() to expose /health and /ready for Kubernetes probes."
);
}
let gateway = self.build()?;
let addr_str = addr.into();
// BB-12: Validate the bind address before attempting to bind.
// This prevents silent binding to unintended interfaces when the address
// is sourced from external configuration.
let socket_addr: std::net::SocketAddr = addr_str.parse().map_err(|e| {
crate::error::Error::Internal(format!("Invalid bind address '{}': {}", addr_str, e))
})?;
if socket_addr.ip().is_unspecified() {
tracing::warn!(
address = %socket_addr,
"Gateway is binding to all network interfaces (0.0.0.0 / ::). \
Consider restricting to a specific IP in production."
);
}
let listener = tokio::net::TcpListener::bind(socket_addr).await?;
tracing::info!(address = %socket_addr, "Gateway server listening");
let app = gateway.into_router();
// Use graceful shutdown if configured
if let Some(config) = shutdown_config {
run_with_graceful_shutdown(listener, app, config).await?;
} else {
axum::serve(listener, app).await?;
}
Ok(())
}
/// Enable graceful shutdown with the specified configuration.
///
/// When graceful shutdown is enabled, the server will:
/// 1. Stop accepting new connections on SIGTERM/SIGINT
/// 2. Wait for in-flight requests to complete (up to timeout)
/// 3. Clean up resources and exit
///
/// # Example
///
/// ```rust,no_run
/// use grpc_graphql_gateway::{Gateway, ShutdownConfig};
/// use std::time::Duration;
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// Gateway::builder()
/// .with_graceful_shutdown(ShutdownConfig {
/// timeout: Duration::from_secs(30),
/// ..Default::default()
/// })
/// .serve("0.0.0.0:8080")
/// .await?;
/// # Ok(())
/// # }
/// ```
///
/// # Default Configuration
///
/// Use `ShutdownConfig::default()` for sensible defaults:
/// - `timeout`: 30 seconds
/// - `handle_signals`: true (handles SIGTERM/SIGINT)
/// - `force_shutdown_delay`: 5 seconds
pub fn with_graceful_shutdown(mut self, config: ShutdownConfig) -> Self {
self.shutdown_config = Some(config);
self
}
/// Build and start the gateway server with explicit shutdown signal.
///
/// This method allows you to provide a custom shutdown future, giving
/// you full control over when the server shuts down.
///
/// # Example
///
/// ```rust,no_run
/// use grpc_graphql_gateway::Gateway;
/// use tokio::sync::oneshot;
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let (tx, rx) = oneshot::channel::<()>();
///
/// // Spawn a task that triggers shutdown after some condition
/// tokio::spawn(async move {
/// tokio::time::sleep(std::time::Duration::from_secs(60)).await;
/// let _ = tx.send(());
/// });
///
/// Gateway::builder()
/// // ... configuration ...
/// .serve_with_shutdown("0.0.0.0:8080", async { let _ = rx.await; })
/// .await?;
/// # Ok(())
/// # }
/// ```
pub async fn serve_with_shutdown<F>(
self,
addr: impl Into<String>,
shutdown_signal: F,
) -> Result<()>
where
F: std::future::Future<Output = ()> + Send + 'static,
{
let gateway = self.build()?;
let addr = addr.into();
let listener = tokio::net::TcpListener::bind(&addr).await?;
tracing::info!("Gateway server listening on {}", addr);
let app = gateway.into_router();
axum::serve(listener, app)
.with_graceful_shutdown(shutdown_signal)
.await?;
Ok(())
}
}
impl Default for GatewayBuilder {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::compression::CompressionLevel;
use std::time::Duration;
// Minimal descriptor for testing
const TEST_DESCRIPTOR: &[u8] = include_bytes!("generated/greeter_descriptor.bin");
#[tokio::test]
async fn test_builder_creation() {
let builder = GatewayBuilder::new();
let result = builder.build();
assert!(result.is_err());
}
#[tokio::test]
async fn test_builder_default() {
let builder1 = GatewayBuilder::new();
let builder2 = GatewayBuilder::default();
// Both should behave the same
assert!(builder1.build().is_err());
assert!(builder2.build().is_err());
}
#[tokio::test]
async fn test_gateway_builder() {
let builder = Gateway::builder();
assert!(builder.build().is_err()); // No descriptor set yet
}
#[tokio::test]
async fn test_grpc_client_pool() {
let pool = GrpcClientPool::new();
assert_eq!(pool.names().len(), 0);
}
#[tokio::test]
async fn test_builder_with_descriptor_bytes() {
let builder = GatewayBuilder::new().with_descriptor_set_bytes(TEST_DESCRIPTOR);
// Should not error with valid descriptor
let result = builder.build();
assert!(result.is_ok());
}
#[tokio::test]
async fn test_builder_add_descriptor_bytes() {
let builder = GatewayBuilder::new()
.with_descriptor_set_bytes(TEST_DESCRIPTOR)
.add_descriptor_set_bytes(TEST_DESCRIPTOR); // Add another
let result = builder.build();
assert!(result.is_ok());
}
#[tokio::test]
async fn test_builder_add_grpc_client() {
let client = GrpcClient::connect_lazy("http://localhost:50051", true).unwrap();
let builder = GatewayBuilder::new()
.with_descriptor_set_bytes(TEST_DESCRIPTOR)
.add_grpc_client("test.Service", client);
let gateway = builder.build().unwrap();
assert!(!gateway.client_pool().names().is_empty());
}
#[tokio::test]
async fn test_builder_add_grpc_clients() {
let client1 = GrpcClient::connect_lazy("http://localhost:50051", true).unwrap();
let client2 = GrpcClient::connect_lazy("http://localhost:50052", true).unwrap();
let clients = vec![
("service1".to_string(), client1),
("service2".to_string(), client2),
];
let builder = GatewayBuilder::new()
.with_descriptor_set_bytes(TEST_DESCRIPTOR)
.add_grpc_clients(clients);
let gateway = builder.build().unwrap();
assert!(gateway.client_pool().names().len() >= 2);
}
#[tokio::test]
async fn test_builder_with_services() {
let services = vec!["example.UserService".to_string()];
let builder = GatewayBuilder::new()
.with_descriptor_set_bytes(TEST_DESCRIPTOR)
.with_services(services);
let result = builder.build();
assert!(result.is_ok());
}
#[tokio::test]
async fn test_builder_enable_federation() {
let builder = GatewayBuilder::new()
.with_descriptor_set_bytes(TEST_DESCRIPTOR)
.enable_federation();
let result = builder.build();
assert!(result.is_ok());
}
#[tokio::test]
async fn test_builder_with_compression() {
let config = CompressionConfig::default();
let builder = GatewayBuilder::new()
.with_descriptor_set_bytes(TEST_DESCRIPTOR)
.with_compression(config);
let result = builder.build();
assert!(result.is_ok());
}
#[tokio::test]
async fn test_builder_with_compression_fast() {
let config = CompressionConfig::fast();
let builder = GatewayBuilder::new()
.with_descriptor_set_bytes(TEST_DESCRIPTOR)
.with_compression(config);
let result = builder.build();
assert!(result.is_ok());
}
#[tokio::test]
async fn test_builder_with_compression_best() {
let config = CompressionConfig::best();
let builder = GatewayBuilder::new()
.with_descriptor_set_bytes(TEST_DESCRIPTOR)
.with_compression(config);
let result = builder.build();
assert!(result.is_ok());
}
#[tokio::test]
async fn test_builder_with_header_propagation() {
let config = HeaderPropagationConfig::new()
.propagate("authorization")
.propagate("x-request-id");
let builder = GatewayBuilder::new()
.with_descriptor_set_bytes(TEST_DESCRIPTOR)
.with_header_propagation(config);
let result = builder.build();
assert!(result.is_ok());
}
#[tokio::test]
async fn test_builder_with_header_propagation_common() {
let config = HeaderPropagationConfig::common();
let builder = GatewayBuilder::new()
.with_descriptor_set_bytes(TEST_DESCRIPTOR)
.with_header_propagation(config);
let result = builder.build();
assert!(result.is_ok());
}
#[tokio::test]
async fn test_builder_with_query_depth_limit() {
let builder = GatewayBuilder::new()
.with_descriptor_set_bytes(TEST_DESCRIPTOR)
.with_query_depth_limit(10);
let result = builder.build();
assert!(result.is_ok());
}
#[tokio::test]
async fn test_builder_with_query_complexity_limit() {
let builder = GatewayBuilder::new()
.with_descriptor_set_bytes(TEST_DESCRIPTOR)
.with_query_complexity_limit(1000);
let result = builder.build();
assert!(result.is_ok());
}
#[tokio::test]
async fn test_builder_enable_health_checks() {
let builder = GatewayBuilder::new()
.with_descriptor_set_bytes(TEST_DESCRIPTOR)
.enable_health_checks();
let result = builder.build();
assert!(result.is_ok());
}
#[tokio::test]
async fn test_builder_enable_metrics() {
let builder = GatewayBuilder::new()
.with_descriptor_set_bytes(TEST_DESCRIPTOR)
.enable_metrics();
let result = builder.build();
assert!(result.is_ok());
}
#[tokio::test]
async fn test_builder_with_graceful_shutdown() {
let config = ShutdownConfig {
timeout: Duration::from_secs(30),
..Default::default()
};
let builder = GatewayBuilder::new()
.with_descriptor_set_bytes(TEST_DESCRIPTOR)
.with_graceful_shutdown(config);
let result = builder.build();
assert!(result.is_ok());
}
#[tokio::test]
async fn test_builder_chain_multiple_configs() {
let builder = GatewayBuilder::new()
.with_descriptor_set_bytes(TEST_DESCRIPTOR)
.with_compression(CompressionConfig::fast())
.with_header_propagation(HeaderPropagationConfig::common())
.with_query_depth_limit(15)
.with_query_complexity_limit(2000)
.enable_health_checks()
.enable_metrics();
let result = builder.build();
assert!(result.is_ok());
}
#[tokio::test]
async fn test_gateway_accessors() {
let gateway = GatewayBuilder::new()
.with_descriptor_set_bytes(TEST_DESCRIPTOR)
.build()
.unwrap();
// Test accessor methods
let _ = gateway.schema();
let _ = gateway.client_pool();
let _ = gateway.mux();
}
#[tokio::test]
async fn test_gateway_into_router() {
let gateway = GatewayBuilder::new()
.with_descriptor_set_bytes(TEST_DESCRIPTOR)
.build()
.unwrap();
let _router = gateway.into_router();
// Router created successfully
}
#[tokio::test]
async fn test_builder_empty_descriptor_fails() {
let builder = GatewayBuilder::new().with_descriptor_set_bytes([]);
let result = builder.build();
assert!(result.is_err());
}
#[tokio::test]
async fn test_builder_invalid_descriptor_fails() {
let builder = GatewayBuilder::new().with_descriptor_set_bytes([0xFF, 0xFF, 0xFF, 0xFF]);
let result = builder.build();
assert!(result.is_err());
}
#[tokio::test]
async fn test_builder_with_circuit_breaker() {
use crate::circuit_breaker::CircuitBreakerConfig;
let config = CircuitBreakerConfig::default();
let builder = GatewayBuilder::new()
.with_descriptor_set_bytes(TEST_DESCRIPTOR)
.with_circuit_breaker(config);
let result = builder.build();
assert!(result.is_ok());
}
#[tokio::test]
async fn test_builder_with_response_cache() {
use crate::cache::CacheConfig;
let config = CacheConfig {
max_size: 1000,
default_ttl: Duration::from_secs(60),
..Default::default()
};
let builder = GatewayBuilder::new()
.with_descriptor_set_bytes(TEST_DESCRIPTOR)
.with_response_cache(config);
let result = builder.build();
assert!(result.is_ok());
}
#[tokio::test]
async fn test_builder_enable_analytics() {
use crate::analytics::AnalyticsConfig;
let config = AnalyticsConfig::default();
let builder = GatewayBuilder::new()
.with_descriptor_set_bytes(TEST_DESCRIPTOR)
.enable_analytics(config);
let result = builder.build();
assert!(result.is_ok());
}
#[tokio::test]
async fn test_builder_with_request_collapsing() {
use crate::request_collapsing::RequestCollapsingConfig;
let config = RequestCollapsingConfig::default();
let builder = GatewayBuilder::new()
.with_descriptor_set_bytes(TEST_DESCRIPTOR)
.with_request_collapsing(config);
let result = builder.build();
assert!(result.is_ok());
}
#[tokio::test]
async fn test_builder_with_high_performance() {
use crate::high_performance::HighPerfConfig;
let config = HighPerfConfig::default();
let builder = GatewayBuilder::new()
.with_descriptor_set_bytes(TEST_DESCRIPTOR)
.with_high_performance(config);
let result = builder.build();
assert!(result.is_ok());
}
#[tokio::test]
async fn test_builder_with_query_whitelist() {
let config = crate::query_whitelist::QueryWhitelistConfig::warn();
let builder = GatewayBuilder::new()
.with_descriptor_set_bytes(TEST_DESCRIPTOR)
.with_query_whitelist(config);
let result = builder.build();
assert!(result.is_ok());
}
#[tokio::test]
async fn test_rest_connectors_empty() {
let builder = GatewayBuilder::new();
assert!(builder.rest_connectors().is_empty());
}
#[tokio::test]
async fn test_client_pool_operations() {
let pool = GrpcClientPool::new();
let client = GrpcClient::connect_lazy("http://localhost:50051", true).unwrap();
pool.add("service1", client.clone());
assert_eq!(pool.names().len(), 1);
assert!(pool.get("service1").is_some());
assert!(pool.get("nonexistent").is_none());
}
#[tokio::test]
async fn test_complete_configuration_stack() {
// Build a gateway with ALL features enabled
let builder = GatewayBuilder::new()
.with_descriptor_set_bytes(TEST_DESCRIPTOR)
.with_compression(CompressionConfig::best())
.with_header_propagation(HeaderPropagationConfig::common())
.with_query_depth_limit(20)
.with_query_complexity_limit(5000)
.enable_health_checks()
.enable_metrics()
.with_graceful_shutdown(ShutdownConfig::default())
.with_circuit_breaker(crate::circuit_breaker::CircuitBreakerConfig::default())
.with_response_cache(crate::cache::CacheConfig::default())
.with_high_performance(crate::high_performance::HighPerfConfig::default())
.with_query_whitelist(crate::query_whitelist::QueryWhitelistConfig::warn())
.enable_analytics(crate::analytics::AnalyticsConfig::default())
.with_request_collapsing(RequestCollapsingConfig::default());
let result = builder.build();
assert!(
result.is_ok(),
"Full configuration stack should build successfully"
);
}
#[tokio::test]
async fn test_multiple_descriptor_sets() {
let builder = GatewayBuilder::new()
.with_descriptor_set_bytes(TEST_DESCRIPTOR)
.add_descriptor_set_bytes(TEST_DESCRIPTOR)
.add_descriptor_set_bytes(TEST_DESCRIPTOR);
let result = builder.build();
assert!(result.is_ok());
}
#[tokio::test]
async fn test_gateway_schema_access() {
let gateway = GatewayBuilder::new()
.with_descriptor_set_bytes(TEST_DESCRIPTOR)
.build()
.unwrap();
let _schema = gateway.schema();
// Schema is accessible
}
#[tokio::test]
async fn test_compression_levels() {
for level in [
CompressionLevel::Fast,
CompressionLevel::Default,
CompressionLevel::Best,
CompressionLevel::Custom(5),
] {
let builder = GatewayBuilder::new()
.with_descriptor_set_bytes(TEST_DESCRIPTOR)
.with_compression(CompressionConfig::new().with_level(level));
assert!(builder.build().is_ok());
}
}
}