camel-component-grpc 0.36.0

gRPC component for rust-camel (dynamic producer and consumer)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
use std::collections::HashMap;
use std::future::Future;
use std::pin::Pin;
use std::sync::{Arc, Mutex, OnceLock};
use std::task::{Context, Poll};
use std::time::Duration;

use arc_swap::ArcSwap;
use camel_api::CamelError;
use camel_api::backoff::{BackoffConfig, BackoffState};
use camel_component_api::tls_source::ServerTlsSource;
use futures::StreamExt;
use hyper::server::conn::http2;
use hyper::service::service_fn;
use hyper_util::rt::TokioIo;
use tokio::sync::{OnceCell, RwLock, mpsc};
use tokio_rustls::TlsAcceptor;
use tonic::body::Body as TonicBody;
use tonic::codec::Streaming;
use tonic::{Request, Response, Status};
use tower::Service;
use tracing::{debug, error};

use camel_api::security_policy::{AccessMode, RouteSecurityPlan};
use camel_auth::{AuthenticatedPrincipal, ProviderRegistry};
use camel_component_api::{RuntimeObservability, SecurityContext};

use crate::codec::RawBytesCodec;
use crate::config::{GrpcServerConfig, ServerTransport};
use crate::consumer::{GrpcReply, GrpcRequestEnvelope, GrpcStreamItem};
use crate::mode::GrpcMode;

pub(crate) type GrpcDispatchEntry = (
    mpsc::Sender<GrpcRequestEnvelope>,
    GrpcMode,
    Option<Arc<GrpcKernelAuth>>,
);

pub(crate) type GrpcDispatchTable = Arc<RwLock<HashMap<String, GrpcDispatchEntry>>>;

/// Kernel authentication state captured when a route's dispatch entry is
/// constructed (`unify-transport-auth`, Task 2.1).
///
/// Construction-order lifecycle: the compiled plan and the provider registry
/// arrive from the route's [`SecurityContext`] when the entry is inserted
/// into the dispatch table — before any request reaches the per-request
/// handlers. The interceptor is created with the plan already captured;
/// it never reads a post-hoc setter. A context lacking either piece leaves
/// the transport Public pass-through (no extraction); non-Public routes
/// without kernel state fail closed at the controller's strict dispatch.
pub(crate) struct GrpcKernelAuth {
    pub(crate) plan: RouteSecurityPlan,
    pub(crate) providers: Arc<ProviderRegistry>,
}

impl GrpcKernelAuth {
    /// Capture the kernel state from a route's security context.
    ///
    /// `None` unless both the compiled plan and the provider registry are
    /// present: a plan without providers can never mint a principal, and a
    /// registry without a plan has nothing to enforce. `None` means Public
    /// pass-through at this transport; the controller's strict dispatch
    /// check is what fails non-Public routes without kernel state closed.
    pub(crate) fn from_security_context(ctx: &SecurityContext) -> Option<Self> {
        Some(Self {
            plan: ctx.plan.clone()?,
            providers: ctx.providers.clone()?,
        })
    }
}

type ServerKey = (String, u16);

/// Shared, atomically-swappable TLS acceptor. `None` for plaintext.
/// Wrapping in ArcSwap lets the cert be hot-reloaded at runtime by calling
/// `.store()` on the inner ArcSwap (see Task 5 reload handler).
type SharedTlsAcceptor = Option<Arc<ArcSwap<TlsAcceptor>>>;

struct ServerHandle {
    dispatch: GrpcDispatchTable,
    task: tokio::task::JoinHandle<()>,
    transport: ServerTransport,
    tls_acceptor: SharedTlsAcceptor,
    tls_source: Option<ServerTlsSource>,
}

pub(crate) struct GrpcServerRegistry {
    inner: Mutex<HashMap<ServerKey, Arc<OnceCell<ServerHandle>>>>,
}

impl GrpcServerRegistry {
    pub(crate) fn global() -> &'static Self {
        static INSTANCE: OnceLock<GrpcServerRegistry> = OnceLock::new();
        INSTANCE.get_or_init(|| GrpcServerRegistry {
            inner: Mutex::new(HashMap::new()),
        })
    }

    pub(crate) async fn get_or_spawn(
        &'static self,
        host: &str,
        port: u16,
        config: GrpcServerConfig,
        runtime: Arc<dyn RuntimeObservability>,
    ) -> Result<GrpcDispatchTable, CamelError> {
        let host_owned = host.to_string();

        let cell = {
            let mut guard = self.inner.lock().map_err(|_| {
                CamelError::EndpointCreationFailed("GrpcServerRegistry lock poisoned".into())
            })?;
            let key = (host.to_string(), port);
            // Evict dead server so a fresh one can spawn (rc-4s65).
            if let Some(existing) = guard.get(&key)
                && let Some(handle) = existing.get()
                && handle.task.is_finished()
            {
                guard.remove(&key);
            }
            guard
                .entry(key)
                .or_insert_with(|| Arc::new(OnceCell::new()))
                .clone()
        };

        let handle = cell
            .get_or_try_init(|| async {
                let route_id = format!("grpc-server:{host_owned}:{port}");
                let (tls_acceptor, tls_source) = match build_tls_acceptor(&config.transport) {
                    Ok(v) => v,
                    Err(e) => {
                        runtime.health().force_unhealthy_for_route(
                            &route_id,
                            "g:grpc:tls-read",
                            &format!("{e}"),
                        );
                        // log-policy: outside-contract
                        error!(error = %e, "grpc TLS config build failed");
                        return Err(e);
                    }
                };
                let addr = format!("{host_owned}:{port}");
                let listener = tokio::net::TcpListener::bind(&addr).await.map_err(|e| {
                    CamelError::EndpointCreationFailed(format!(
                        "failed to bind gRPC server on {addr}: {e}"
                    ))
                })?;
                let dispatch: GrpcDispatchTable = Arc::new(RwLock::new(HashMap::new()));
                let rt = Arc::clone(&runtime);
                let task = tokio::spawn(run_grpc_server(
                    listener,
                    Arc::clone(&dispatch),
                    config.clone(),
                    tls_acceptor.clone(),
                    rt,
                ));
                let handle = ServerHandle {
                    dispatch,
                    task,
                    transport: config.transport.clone(),
                    tls_acceptor,
                    tls_source,
                };
                // Register reload handler (exactly-once: inside OnceCell init closure).
                // Note: gRPC servers are process-lifetime (no release/eviction path),
                // so handlers are never unregistered. If eviction is added later,
                // add TlsReloadRegistry::global().unregister() there.
                if let (Some(acceptor), Some(source)) =
                    (handle.tls_acceptor.as_ref(), handle.tls_source.as_ref())
                {
                    let handler = Arc::new(crate::tls_reload::GrpcReloadHandler::new(
                        acceptor.clone(),
                        source.clone(),
                        host_owned.clone(),
                        port,
                    ));
                    camel_component_api::tls_source::TlsReloadRegistry::global().register(handler);
                }
                Ok::<ServerHandle, CamelError>(handle)
            })
            .await?;

        validate_server_handle(handle, &config.transport, &host_owned, port)?;
        Ok(Arc::clone(&handle.dispatch))
    }

    pub(crate) async fn get_or_spawn_with_listener(
        &'static self,
        listener: tokio::net::TcpListener,
        host: &str,
        port: u16,
        config: GrpcServerConfig,
        runtime: Arc<dyn RuntimeObservability>,
    ) -> Result<GrpcDispatchTable, CamelError> {
        let host_owned = host.to_string();

        let cell = {
            let mut guard = self.inner.lock().map_err(|_| {
                CamelError::EndpointCreationFailed("GrpcServerRegistry lock poisoned".into())
            })?;
            let key = (host.to_string(), port);
            // Evict dead server so a fresh one can spawn (rc-4s65).
            if let Some(existing) = guard.get(&key)
                && let Some(handle) = existing.get()
                && handle.task.is_finished()
            {
                guard.remove(&key);
            }
            guard
                .entry(key)
                .or_insert_with(|| Arc::new(OnceCell::new()))
                .clone()
        };

        let handle = cell
            .get_or_try_init(|| async {
                let route_id = format!("grpc-server:{host_owned}:{port}");
                let (tls_acceptor, tls_source) = match build_tls_acceptor(&config.transport) {
                    Ok(v) => v,
                    Err(e) => {
                        runtime.health().force_unhealthy_for_route(
                            &route_id,
                            "g:grpc:tls-read",
                            &format!("{e}"),
                        );
                        // log-policy: outside-contract
                        error!(error = %e, "grpc TLS config build failed");
                        return Err(e);
                    }
                };
                let dispatch: GrpcDispatchTable = Arc::new(RwLock::new(HashMap::new()));
                let rt = Arc::clone(&runtime);
                let task = tokio::spawn(run_grpc_server(
                    listener,
                    Arc::clone(&dispatch),
                    config.clone(),
                    tls_acceptor.clone(),
                    rt,
                ));
                let handle = ServerHandle {
                    dispatch,
                    task,
                    transport: config.transport.clone(),
                    tls_acceptor,
                    tls_source,
                };
                // Register reload handler (exactly-once: inside OnceCell init closure).
                // Note: gRPC servers are process-lifetime (no release/eviction path),
                // so handlers are never unregistered. If eviction is added later,
                // add TlsReloadRegistry::global().unregister() there.
                if let (Some(acceptor), Some(source)) =
                    (handle.tls_acceptor.as_ref(), handle.tls_source.as_ref())
                {
                    let handler = Arc::new(crate::tls_reload::GrpcReloadHandler::new(
                        acceptor.clone(),
                        source.clone(),
                        host_owned.clone(),
                        port,
                    ));
                    camel_component_api::tls_source::TlsReloadRegistry::global().register(handler);
                }
                Ok::<ServerHandle, CamelError>(handle)
            })
            .await?;

        validate_server_handle(handle, &config.transport, &host_owned, port)?;
        Ok(Arc::clone(&handle.dispatch))
    }

    pub(crate) async fn unregister(&self, host: &str, port: u16, path: &str) {
        let key = (host.to_string(), port);
        let dispatch = {
            let guard = match self.inner.lock() {
                Ok(g) => g,
                Err(_) => return,
            };
            let Some(cell) = guard.get(&key) else {
                return;
            };
            let Some(handle) = cell.get() else {
                return;
            };
            Arc::clone(&handle.dispatch)
        };
        // Remove this route's path from the dispatch table. The shared
        // HTTP/2 server stays alive — gRPC servers are process-lifetime.
        let mut table = dispatch.write().await;
        table.remove(path);
    }
}

/// Validate a server handle after registry lookup: reject transport mismatches
/// (Plaintext↔Tls OR Tls(A)↔Tls(B)) and reap finished tasks.
fn validate_server_handle(
    handle: &ServerHandle,
    requested: &ServerTransport,
    host: &str,
    port: u16,
) -> Result<(), CamelError> {
    if &handle.transport != requested {
        return Err(CamelError::EndpointCreationFailed(format!(
            "gRPC server {host}:{port} already bound with transport={:?}; \
             requested {:?} — refusing to mix incompatible transport configs on one listener",
            handle.transport, requested,
        )));
    }
    if handle.task.is_finished() {
        return Err(CamelError::EndpointCreationFailed(
            "gRPC server task has terminated unexpectedly".into(),
        ));
    }
    Ok(())
}

/// Build a TlsAcceptor wrapped in ArcSwap from ServerTransport.
/// Returns (None, None) for Plaintext. Hard-errors on missing/invalid cert.
///
/// The acceptor is wrapped in `Arc<ArcSwap<TlsAcceptor>>` so the cert can be
/// hot-swapped at runtime by calling `.store()` on the ArcSwap (Task 5).
/// ALPN `h2` is set for HTTP/2 negotiation.
fn build_tls_acceptor(
    transport: &ServerTransport,
) -> Result<(SharedTlsAcceptor, Option<ServerTlsSource>), CamelError> {
    match transport {
        ServerTransport::Plaintext => Ok((None, None)),
        ServerTransport::Tls(cfg) => {
            let source = ServerTlsSource {
                cert_path: std::path::PathBuf::from(&cfg.server_cert_path),
                key_path: std::path::PathBuf::from(&cfg.server_key_path),
                client_ca_path: cfg.client_ca_path.as_ref().map(std::path::PathBuf::from),
            };
            let mut server_cfg = source.build_server_config()?;
            server_cfg.alpn_protocols = vec![b"h2".to_vec()];
            let acceptor = TlsAcceptor::from(Arc::new(server_cfg));
            Ok((
                Some(Arc::new(ArcSwap::from_pointee(acceptor))),
                Some(source),
            ))
        }
    }
}

/// Serve h2 over a concrete IO type. Generic so both plaintext (TcpStream)
/// and TLS (TlsStream<TcpStream>) call sites type-check.
async fn serve_h2<I>(io: I, dispatch: GrpcDispatchTable, config: GrpcServerConfig)
where
    I: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin + Send + 'static,
{
    let io = TokioIo::new(io);
    let service = service_fn(move |req| {
        let dispatch = dispatch.clone();
        handle_grpc_request(req, dispatch)
    });
    let mut builder = http2::Builder::new(hyper_util::rt::TokioExecutor::new());
    if let Some(max_len) = config.max_receive_message_len {
        let frame_size = max_len.clamp(16_384, 16_777_215) as u32;
        builder.max_frame_size(frame_size);
    }
    if let Err(e) = builder.serve_connection(io, service).await {
        debug!(error = %e, "gRPC connection error");
    }
}

/// Capped exponential backoff config for the gRPC accept loop.
/// Starts at 10ms, doubles each failure, caps at 5s.
fn accept_backoff_config() -> BackoffConfig {
    BackoffConfig {
        initial_delay: Duration::from_millis(10),
        multiplier: 2.0,
        max_delay: Duration::from_secs(5),
    }
}

async fn run_grpc_server(
    listener: tokio::net::TcpListener,
    dispatch: GrpcDispatchTable,
    config: GrpcServerConfig,
    tls_acceptor: SharedTlsAcceptor,
    runtime: Arc<dyn RuntimeObservability>,
) {
    // Q-B1: route_id derived from listener local address. The accept loop runs
    // below route dispatch — multiple GrpcEndpoints register on one shared
    // listener, so no single per-route route_id is correct. The local address
    // is stable, attributable, and meaningful to operators.
    let route_id = listener
        .local_addr()
        .map(|addr| format!("grpc-server:{addr}"))
        .unwrap_or_else(|_| "grpc-server:unknown".to_string());

    let mut backoff = BackoffState::new(accept_backoff_config());

    loop {
        let (stream, _) = match listener.accept().await {
            Ok(s) => {
                backoff.reset();
                s
            }
            Err(e) => {
                runtime
                    .metrics()
                    .increment_errors(&route_id, "e:grpc:accept");
                // log-policy: outside-contract
                error!(error = %e, "gRPC server accept error");
                let delay = backoff.next_delay();
                tokio::time::sleep(delay).await;
                continue;
            }
        };

        let tls_acceptor = tls_acceptor.clone();
        let config = config.clone();
        let dispatch = dispatch.clone();
        let rt_metrics = runtime.clone();
        let route_id_clone = route_id.clone();
        tokio::spawn(async move {
            match tls_acceptor.as_ref() {
                None => serve_h2(stream, dispatch, config).await,
                Some(swap) => {
                    // load_full() returns Arc<TlsAcceptor> — owned snapshot, await-safe.
                    // Re-reading per connection enables atomic cert hot-swap via .store().
                    let acceptor = swap.load_full();
                    match acceptor.accept(stream).await {
                        Ok(tls_stream) => serve_h2(tls_stream, dispatch, config).await,
                        Err(e) => {
                            rt_metrics
                                .metrics()
                                .increment_errors(&route_id_clone, "e:grpc:tls-accept");
                            debug!(error = %e, "gRPC TLS handshake error");
                        }
                    }
                }
            }
        });
    }
}

// ── Response stream type ───────────────────────────────────────────────────

type ResponseStream = Pin<Box<dyn futures::Stream<Item = Result<Vec<u8>, Status>> + Send>>;

// ── Manual stream implementation (no async-stream dep) ─────────────────────

struct GrpcItemStream {
    rx: mpsc::Receiver<GrpcStreamItem>,
}

impl futures::Stream for GrpcItemStream {
    type Item = Result<Vec<u8>, Status>;

    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        match self.rx.poll_recv(cx) {
            Poll::Ready(Some(GrpcStreamItem::Message(bytes))) => Poll::Ready(Some(Ok(bytes))),
            Poll::Ready(Some(GrpcStreamItem::Error(status))) => Poll::Ready(Some(Err(status))),
            Poll::Ready(Some(GrpcStreamItem::Done)) => Poll::Ready(None),
            Poll::Ready(None) => Poll::Ready(None),
            Poll::Pending => Poll::Pending,
        }
    }
}

// ── Authentication helper ──────────────────────────────────────────────────

/// Map an authentication error onto the transport denial idiom (`tonic::Status`).
fn auth_error_to_status(e: camel_api::CamelError) -> tonic::Status {
    match e {
        camel_api::CamelError::Unauthenticated(msg) => tonic::Status::unauthenticated(msg),
        camel_api::CamelError::AuthProviderUnavailable(msg) => tonic::Status::unavailable(msg),
        other => {
            // log-policy: system-broken
            tracing::error!(error = %other, "gRPC authentication error");
            tonic::Status::internal(other.to_string())
        }
    }
}

/// Per-request authentication at the gRPC boundary (kernel-only).
///
/// Kernel path (plan captured at dispatch-entry construction): an
/// `AccessMode::Public` plan skips extraction entirely — pass-through,
/// `kernel_authenticate` is never called. Any other mode extracts per
/// `plan.credential_sources` (authorization metadata + named headers) and
/// mints the sealed principal through the kernel. No local JWT parsing.
///
/// A context without a plan is Public pass-through: no extraction, no
/// error, no principal. Policy enforcement is not done here — it lives in
/// the pipeline layer plus the strict dispatch check.
///
/// Returns the sealed principal when the kernel minted one.
async fn authenticate_request(
    kernel: Option<&GrpcKernelAuth>,
    metadata: &tonic::metadata::MetadataMap,
) -> Result<Option<AuthenticatedPrincipal>, tonic::Status> {
    let Some(kernel) = kernel else {
        return Ok(None);
    };
    if matches!(kernel.plan.access_mode, AccessMode::Public) {
        return Ok(None);
    }
    let header_map = metadata_to_header_map(metadata);
    let uri = http::Uri::from_static("/");
    let extracted =
        camel_auth::extract_token_multi(&header_map, &uri, &kernel.plan.credential_sources)
            .ok_or_else(|| tonic::Status::unauthenticated("missing or malformed credentials"))?;
    let principal = camel_auth::kernel_authenticate(&kernel.plan, &kernel.providers, &extracted)
        .await
        .map_err(auth_error_to_status)?;
    Ok(Some(principal))
}

/// Convert tonic metadata into an `http::HeaderMap` for the shared extraction
/// helper. ASCII keys map to lowercase HTTP header names; binary keys
/// (`-bin` suffix) are skipped, as are values that fail header validation.
fn metadata_to_header_map(metadata: &tonic::metadata::MetadataMap) -> http::HeaderMap {
    use tonic::metadata::KeyAndValueRef;

    let mut headers = http::HeaderMap::new();
    for key_and_value in metadata.iter() {
        let KeyAndValueRef::Ascii(key, value) = key_and_value else {
            continue;
        };
        let Ok(header_name) = http::header::HeaderName::try_from(key.as_str()) else {
            continue;
        };
        let Ok(value_str) = value.to_str() else {
            continue;
        };
        let Ok(header_value) = http::header::HeaderValue::from_str(value_str) else {
            continue;
        };
        headers.append(header_name, header_value);
    }
    headers
}

// ── Mode-aware dispatch ────────────────────────────────────────────────────

async fn handle_grpc_request(
    req: hyper::Request<hyper::body::Incoming>,
    dispatch: GrpcDispatchTable,
) -> Result<hyper::Response<TonicBody>, std::convert::Infallible> {
    let path = req.uri().path().to_string();

    let entry = {
        let table = dispatch.read().await;
        table
            .get(&path)
            .map(|(tx, mode, kernel)| (tx.clone(), *mode, kernel.clone()))
    };

    let Some((sender, mode, kernel)) = entry else {
        let handler = UnimplementedHandler;
        let mut grpc = tonic::server::Grpc::new(RawBytesCodec);
        let response = grpc.unary(handler, req).await;
        return Ok(response);
    };

    let mut grpc = tonic::server::Grpc::new(RawBytesCodec);

    match mode {
        GrpcMode::Unary => {
            let handler = UnaryHandler { sender, kernel };
            let response = grpc.unary(handler, req).await;
            Ok(response)
        }
        GrpcMode::ServerStreaming => {
            let handler = ServerStreamingHandler { sender, kernel };
            let response = grpc.server_streaming(handler, req).await;
            Ok(response)
        }
        GrpcMode::ClientStreaming => {
            let handler = ClientStreamingHandler { sender, kernel };
            let response = grpc.client_streaming(handler, req).await;
            Ok(response)
        }
        GrpcMode::Bidi => {
            let handler = BidiHandler { sender, kernel };
            let response = grpc.streaming(handler, req).await;
            Ok(response)
        }
    }
}

// ── Unimplemented handler (fallback) ───────────────────────────────────────

struct UnimplementedHandler;

impl Service<Request<Vec<u8>>> for UnimplementedHandler {
    type Response = Response<Vec<u8>>;
    type Error = Status;
    type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;

    fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        Poll::Ready(Ok(()))
    }

    fn call(&mut self, _req: Request<Vec<u8>>) -> Self::Future {
        Box::pin(async { Err(Status::unimplemented("no handler for path")) })
    }
}

// ── Unary handler ──────────────────────────────────────────────────────────

struct UnaryHandler {
    sender: mpsc::Sender<GrpcRequestEnvelope>,
    kernel: Option<Arc<GrpcKernelAuth>>,
}

impl tonic::server::UnaryService<Vec<u8>> for UnaryHandler {
    type Response = Vec<u8>;
    type Future = Pin<Box<dyn Future<Output = Result<Response<Self::Response>, Status>> + Send>>;

    fn call(&mut self, req: Request<Vec<u8>>) -> Self::Future {
        let kernel = self.kernel.clone();
        let (reply_tx, reply_rx) = tokio::sync::oneshot::channel();
        let sender = self.sender.clone();

        Box::pin(async move {
            let kernel_principal = authenticate_request(kernel.as_deref(), req.metadata()).await?;

            let envelope = GrpcRequestEnvelope::Unary {
                metadata: req.metadata().clone(),
                body: req.into_inner(),
                reply_tx,
                kernel_principal,
            };
            sender
                .send(envelope)
                .await
                .map_err(|_| Status::unavailable("consumer stopped"))?;
            match reply_rx
                .await
                .map_err(|_| Status::internal("reply channel dropped"))?
            {
                GrpcReply::Ok(bytes) => Ok(Response::new(bytes)),
                GrpcReply::Err(status) => Err(status),
            }
        })
    }
}

// ── Server-streaming handler ───────────────────────────────────────────────

struct ServerStreamingHandler {
    sender: mpsc::Sender<GrpcRequestEnvelope>,
    kernel: Option<Arc<GrpcKernelAuth>>,
}

impl tonic::server::ServerStreamingService<Vec<u8>> for ServerStreamingHandler {
    type Response = Vec<u8>;
    type ResponseStream = ResponseStream;
    type Future =
        Pin<Box<dyn Future<Output = Result<Response<Self::ResponseStream>, Status>> + Send>>;

    fn call(&mut self, req: Request<Vec<u8>>) -> Self::Future {
        let kernel = self.kernel.clone();
        let (reply_tx, reply_rx) = mpsc::channel::<GrpcStreamItem>(64);
        let sender = self.sender.clone();

        Box::pin(async move {
            let kernel_principal = authenticate_request(kernel.as_deref(), req.metadata()).await?;

            let envelope = GrpcRequestEnvelope::ServerStreaming {
                metadata: req.metadata().clone(),
                body: req.into_inner(),
                reply_tx,
                kernel_principal,
            };
            sender
                .send(envelope)
                .await
                .map_err(|_| Status::unavailable("consumer stopped"))?;
            Ok(Response::new(
                Box::pin(GrpcItemStream { rx: reply_rx }) as ResponseStream
            ))
        })
    }
}

// ── Client-streaming handler ───────────────────────────────────────────────

struct ClientStreamingHandler {
    sender: mpsc::Sender<GrpcRequestEnvelope>,
    kernel: Option<Arc<GrpcKernelAuth>>,
}

impl tonic::server::ClientStreamingService<Vec<u8>> for ClientStreamingHandler {
    type Response = Vec<u8>;
    type Future = Pin<Box<dyn Future<Output = Result<Response<Self::Response>, Status>> + Send>>;

    fn call(&mut self, req: Request<Streaming<Vec<u8>>>) -> Self::Future {
        let kernel = self.kernel.clone();
        let (body_tx, body_rx) = mpsc::channel::<Vec<u8>>(64);
        let (reply_tx, reply_rx) = tokio::sync::oneshot::channel::<GrpcReply>();
        let sender = self.sender.clone();

        Box::pin(async move {
            let kernel_principal = authenticate_request(kernel.as_deref(), req.metadata()).await?;

            let envelope = GrpcRequestEnvelope::ClientStreaming {
                metadata: req.metadata().clone(),
                body_rx,
                reply_tx,
                kernel_principal,
            };

            let forward_handle = tokio::spawn(async move {
                let mut stream = req.into_inner();
                while let Some(result) = stream.next().await {
                    match result {
                        Ok(bytes) => {
                            if body_tx.send(bytes).await.is_err() {
                                break;
                            }
                        }
                        Err(status) => {
                            tracing::warn!(error = %status, "client streaming decode error");
                            return Some(status);
                        }
                    }
                }
                None
            });

            sender
                .send(envelope)
                .await
                .map_err(|_| Status::unavailable("consumer stopped"))?;

            let reply = reply_rx
                .await
                .map_err(|_| Status::internal("reply channel dropped"))?;

            // If the inbound stream had a decode error, propagate it instead of the consumer's reply.
            if let Ok(Some(status)) = forward_handle.await {
                return Err(status);
            }

            match reply {
                GrpcReply::Ok(bytes) => Ok(Response::new(bytes)),
                GrpcReply::Err(status) => Err(status),
            }
        })
    }
}

// ── Bidi handler ───────────────────────────────────────────────────────────

struct BidiHandler {
    sender: mpsc::Sender<GrpcRequestEnvelope>,
    kernel: Option<Arc<GrpcKernelAuth>>,
}

impl tonic::server::StreamingService<Vec<u8>> for BidiHandler {
    type Response = Vec<u8>;
    type ResponseStream = ResponseStream;
    type Future =
        Pin<Box<dyn Future<Output = Result<Response<Self::ResponseStream>, Status>> + Send>>;

    fn call(&mut self, req: Request<Streaming<Vec<u8>>>) -> Self::Future {
        let kernel = self.kernel.clone();
        let (body_tx, body_rx) = mpsc::channel::<Vec<u8>>(64);
        let (reply_tx, reply_rx) = mpsc::channel::<GrpcStreamItem>(64);
        let reply_tx_forward = reply_tx.clone();
        let sender = self.sender.clone();

        Box::pin(async move {
            let kernel_principal = authenticate_request(kernel.as_deref(), req.metadata()).await?;

            let envelope = GrpcRequestEnvelope::Bidi {
                metadata: req.metadata().clone(),
                body_rx,
                reply_tx,
                kernel_principal,
            };

            tokio::spawn(async move {
                let mut stream = req.into_inner();
                while let Some(result) = stream.next().await {
                    match result {
                        Ok(bytes) => {
                            if body_tx.send(bytes).await.is_err() {
                                break;
                            }
                        }
                        Err(status) => {
                            tracing::warn!(error = %status, "bidi streaming decode error");
                            let _ = reply_tx_forward.send(GrpcStreamItem::Error(status)).await;
                            break;
                        }
                    }
                }
            });

            sender
                .send(envelope)
                .await
                .map_err(|_| Status::unavailable("consumer stopped"))?;

            Ok(Response::new(
                Box::pin(GrpcItemStream { rx: reply_rx }) as ResponseStream
            ))
        })
    }
}

#[cfg(test)]
mod tests {
    use std::collections::HashMap;
    use std::sync::Mutex;
    use std::task::Poll;
    use std::time::Duration;

    use camel_api::MetricsCollector;
    use camel_api::security_policy::AuthPrincipal;
    use camel_auth::CredentialSource;
    use camel_component_api::HealthCheckRegistry;
    use futures::{Stream, StreamExt};
    use tokio::sync::mpsc;
    use tonic::Status;
    use tonic::server::{ServerStreamingService, UnaryService};
    use tower::Service;

    use super::*;
    use crate::consumer::{GrpcReply, GrpcStreamItem};

    // -----------------------------------------------------------------------
    // Recording metrics collector for testing increment_errors calls
    // -----------------------------------------------------------------------

    struct RecordingMetrics {
        errors: Arc<Mutex<Vec<(String, String)>>>,
    }

    impl MetricsCollector for RecordingMetrics {
        fn record_exchange_duration(&self, _: &str, _: Duration) {}
        fn increment_errors(&self, route_id: &str, error_type: &str) {
            self.errors
                .lock()
                .unwrap()
                .push((route_id.to_string(), error_type.to_string()));
        }
        fn increment_exchanges(&self, _: &str) {}
        fn set_queue_depth(&self, _: &str, _: usize) {}
        fn record_circuit_breaker_change(&self, _: &str, _: &str, _: &str) {}
    }

    struct RecordingRuntime {
        metrics_collector: Arc<RecordingMetrics>,
    }

    impl RecordingRuntime {
        fn new(errors: Arc<Mutex<Vec<(String, String)>>>) -> Self {
            Self {
                metrics_collector: Arc::new(RecordingMetrics { errors }),
            }
        }
    }

    impl RuntimeObservability for RecordingRuntime {
        fn metrics(&self) -> Arc<dyn MetricsCollector> {
            self.metrics_collector.clone() as Arc<dyn MetricsCollector>
        }
        fn health(&self) -> Arc<dyn HealthCheckRegistry> {
            panic!("RecordingRuntime::health not used in this test")
        }
    }

    #[test]
    fn test_global_registry_returns_singleton() {
        let first = GrpcServerRegistry::global();
        let second = GrpcServerRegistry::global();
        assert!(std::ptr::eq(first, second));
    }

    #[tokio::test]
    async fn test_grpc_item_stream_yields_message() {
        let (tx, rx) = mpsc::channel::<GrpcStreamItem>(4);
        let mut stream = GrpcItemStream { rx };
        tx.send(GrpcStreamItem::Message(vec![1, 2, 3]))
            .await
            .unwrap();
        drop(tx);
        let item = stream.next().await.unwrap().unwrap();
        assert_eq!(item, vec![1, 2, 3]);
        assert!(stream.next().await.is_none());
    }

    #[tokio::test]
    async fn test_grpc_item_stream_yields_error() {
        let (tx, rx) = mpsc::channel::<GrpcStreamItem>(4);
        let mut stream = GrpcItemStream { rx };
        let status = Status::internal("test error");
        tx.send(GrpcStreamItem::Error(status.clone()))
            .await
            .unwrap();
        drop(tx);
        let item = stream.next().await.unwrap();
        assert!(item.is_err());
        assert_eq!(item.unwrap_err().code(), status.code());
    }

    #[tokio::test]
    async fn test_grpc_item_stream_yields_done_as_none() {
        let (tx, rx) = mpsc::channel::<GrpcStreamItem>(4);
        let mut stream = GrpcItemStream { rx };
        tx.send(GrpcStreamItem::Done).await.unwrap();
        drop(tx);
        assert!(stream.next().await.is_none());
    }

    #[tokio::test]
    async fn test_grpc_item_stream_closed_channel() {
        let (tx, rx) = mpsc::channel::<GrpcStreamItem>(4);
        let mut stream = GrpcItemStream { rx };
        drop(tx);
        assert!(stream.next().await.is_none());
    }

    #[tokio::test]
    async fn test_grpc_item_stream_multiple_messages() {
        let (tx, rx) = mpsc::channel::<GrpcStreamItem>(4);
        let stream = GrpcItemStream { rx };
        tx.send(GrpcStreamItem::Message(vec![1])).await.unwrap();
        tx.send(GrpcStreamItem::Message(vec![2])).await.unwrap();
        tx.send(GrpcStreamItem::Message(vec![3])).await.unwrap();
        drop(tx);
        let results: Vec<_> = stream.collect().await;
        assert_eq!(results.len(), 3);
        assert_eq!(results[0].as_ref().unwrap(), &vec![1]);
        assert_eq!(results[1].as_ref().unwrap(), &vec![2]);
        assert_eq!(results[2].as_ref().unwrap(), &vec![3]);
    }

    #[tokio::test]
    async fn test_grpc_item_stream_poll_pending() {
        let (_tx, rx) = mpsc::channel::<GrpcStreamItem>(4);
        let stream = GrpcItemStream { rx };
        let waker = futures::task::noop_waker();
        let mut cx = Context::from_waker(&waker);
        let mut stream_pinned = std::pin::Pin::new(Box::new(stream));
        assert!(matches!(
            Stream::poll_next(stream_pinned.as_mut(), &mut cx),
            Poll::Pending
        ));
    }

    #[test]
    fn test_unimplemented_handler_poll_ready() {
        let mut handler = UnimplementedHandler;
        let waker = futures::task::noop_waker();
        let mut cx = Context::from_waker(&waker);
        assert!(matches!(handler.poll_ready(&mut cx), Poll::Ready(Ok(()))));
    }

    #[tokio::test]
    async fn test_unimplemented_handler_returns_unimplemented_status() {
        let mut handler = UnimplementedHandler;
        let req = Request::new(vec![1, 2, 3]);
        let result = Service::call(&mut handler, req).await;
        assert!(result.is_err());
        let status = result.unwrap_err();
        assert_eq!(status.code(), tonic::Code::Unimplemented);
        assert_eq!(status.message(), "no handler for path");
    }

    #[tokio::test]
    async fn test_unregister_removes_path_from_dispatch() {
        let dispatch: GrpcDispatchTable = Arc::new(RwLock::new(HashMap::new()));
        let (tx, _rx) = mpsc::channel::<GrpcRequestEnvelope>(4);
        {
            let mut table = dispatch.write().await;
            table.insert(
                "/test.Service/Method".to_string(),
                (tx, GrpcMode::Unary, None),
            );
        }
        assert!(dispatch.read().await.contains_key("/test.Service/Method"));
        {
            let mut table = dispatch.write().await;
            table.remove("/test.Service/Method");
        }
        assert!(!dispatch.read().await.contains_key("/test.Service/Method"));
    }

    #[tokio::test]
    async fn test_unregister_nonexistent_path_is_noop() {
        let registry = GrpcServerRegistry::global();
        let dispatch: GrpcDispatchTable = Arc::new(RwLock::new(HashMap::new()));
        registry
            .unregister("localhost", 50051, "/nonexistent.Path/Method")
            .await;
        assert!(dispatch.read().await.is_empty());
    }

    #[test]
    fn test_server_key_equality() {
        let key1: ServerKey = ("localhost".to_string(), 50051);
        let key2: ServerKey = ("localhost".to_string(), 50051);
        let key3: ServerKey = ("localhost".to_string(), 50052);
        let key4: ServerKey = ("remotehost".to_string(), 50051);
        assert_eq!(key1, key2);
        assert_ne!(key1, key3);
        assert_ne!(key1, key4);
    }

    #[tokio::test]
    async fn test_dispatch_table_insert_and_retrieve() {
        let dispatch: GrpcDispatchTable = Arc::new(RwLock::new(HashMap::new()));
        let (tx, _rx) = mpsc::channel::<GrpcRequestEnvelope>(4);
        let path = "/pkg.Service/Method".to_string();
        {
            let mut table = dispatch.write().await;
            table.insert(path.clone(), (tx, GrpcMode::ServerStreaming, None));
        }
        let table = dispatch.read().await;
        let (_, mode, _) = table.get(&path).unwrap();
        assert_eq!(*mode, GrpcMode::ServerStreaming);
    }

    #[tokio::test]
    async fn test_dispatch_table_remove_returns_entry() {
        let dispatch: GrpcDispatchTable = Arc::new(RwLock::new(HashMap::new()));
        let (tx, _rx) = mpsc::channel::<GrpcRequestEnvelope>(4);
        let path = "/pkg.Service/Method".to_string();
        {
            let mut table = dispatch.write().await;
            table.insert(path.clone(), (tx, GrpcMode::Bidi, None));
        }
        {
            let mut table = dispatch.write().await;
            let removed = table.remove(&path);
            assert!(removed.is_some());
            let (_, mode, _) = removed.unwrap();
            assert_eq!(mode, GrpcMode::Bidi);
        }
        assert!(dispatch.read().await.is_empty());
    }

    #[tokio::test]
    async fn test_dispatch_table_all_grpc_modes() {
        let dispatch: GrpcDispatchTable = Arc::new(RwLock::new(HashMap::new()));
        let modes = [
            GrpcMode::Unary,
            GrpcMode::ServerStreaming,
            GrpcMode::ClientStreaming,
            GrpcMode::Bidi,
        ];
        {
            let mut table = dispatch.write().await;
            for (i, mode) in modes.iter().enumerate() {
                let (tx, _rx) = mpsc::channel::<GrpcRequestEnvelope>(4);
                table.insert(format!("/svc/M{i}"), (tx, *mode, None));
            }
        }
        let table = dispatch.read().await;
        assert_eq!(table.len(), 4);
        for (i, expected_mode) in modes.iter().enumerate() {
            let (_, mode, _) = table.get(&format!("/svc/M{i}")).unwrap();
            assert_eq!(*mode, *expected_mode);
        }
    }

    #[test]
    fn test_grpc_reply_variants() {
        let ok_reply = GrpcReply::Ok(vec![4, 5, 6]);
        match ok_reply {
            GrpcReply::Ok(bytes) => assert_eq!(bytes, vec![4, 5, 6]),
            GrpcReply::Err(_) => panic!("expected Ok"),
        }
        let err_reply = GrpcReply::Err(Status::not_found("missing"));
        match err_reply {
            GrpcReply::Ok(_) => panic!("expected Err"),
            GrpcReply::Err(s) => assert_eq!(s.code(), tonic::Code::NotFound),
        }
    }

    #[tokio::test]
    async fn test_grpc_request_envelope_unary() {
        let (reply_tx, reply_rx) = tokio::sync::oneshot::channel();
        let mut metadata = tonic::metadata::MetadataMap::new();
        metadata.insert("x-test", "value".parse().unwrap());
        let body = vec![10, 20, 30];
        let envelope = GrpcRequestEnvelope::Unary {
            metadata: metadata.clone(),
            body: body.clone(),
            reply_tx,
            kernel_principal: None,
        };
        match envelope {
            GrpcRequestEnvelope::Unary {
                metadata: m,
                body: b,
                reply_tx: tx,
                ..
            } => {
                assert!(m.get("x-test").is_some());
                assert_eq!(b, body);
                let _ = tx.send(GrpcReply::Ok(vec![99]));
            }
            _ => panic!("expected Unary"),
        }
        let reply = reply_rx.await.unwrap();
        assert!(matches!(reply, GrpcReply::Ok(v) if v == vec![99]));
    }

    #[tokio::test]
    async fn test_grpc_request_envelope_server_streaming() {
        let (reply_tx, mut reply_rx) = mpsc::channel::<GrpcStreamItem>(4);
        let envelope = GrpcRequestEnvelope::ServerStreaming {
            metadata: tonic::metadata::MetadataMap::new(),
            body: vec![1],
            reply_tx,
            kernel_principal: None,
        };
        match envelope {
            GrpcRequestEnvelope::ServerStreaming { reply_tx: tx, .. } => {
                tx.send(GrpcStreamItem::Message(vec![42])).await.unwrap();
                tx.send(GrpcStreamItem::Done).await.unwrap();
            }
            _ => panic!("expected ServerStreaming"),
        }
        match reply_rx.recv().await {
            Some(GrpcStreamItem::Message(b)) => assert_eq!(b, vec![42]),
            _ => panic!("expected Message(42)"),
        }
        assert!(matches!(reply_rx.recv().await, Some(GrpcStreamItem::Done)));
    }

    #[tokio::test]
    async fn test_grpc_request_envelope_client_streaming() {
        let (body_tx, body_rx) = mpsc::channel::<Vec<u8>>(4);
        let (reply_tx, reply_rx) = tokio::sync::oneshot::channel();
        let envelope = GrpcRequestEnvelope::ClientStreaming {
            metadata: tonic::metadata::MetadataMap::new(),
            body_rx,
            reply_tx,
            kernel_principal: None,
        };
        let handle = tokio::spawn(async move {
            match envelope {
                GrpcRequestEnvelope::ClientStreaming {
                    body_rx: mut rx,
                    reply_tx: tx,
                    ..
                } => {
                    assert_eq!(rx.recv().await, Some(vec![1]));
                    assert_eq!(rx.recv().await, Some(vec![2]));
                    let _ = tx.send(GrpcReply::Ok(vec![99]));
                }
                _ => panic!("expected ClientStreaming"),
            }
        });
        body_tx.send(vec![1]).await.unwrap();
        body_tx.send(vec![2]).await.unwrap();
        drop(body_tx);
        handle.await.unwrap();
        let reply = reply_rx.await.unwrap();
        assert!(matches!(reply, GrpcReply::Ok(v) if v == vec![99]));
    }

    #[tokio::test]
    async fn test_grpc_request_envelope_bidi() {
        let (body_tx, body_rx) = mpsc::channel::<Vec<u8>>(4);
        let (reply_tx, mut reply_rx) = mpsc::channel::<GrpcStreamItem>(4);
        let envelope = GrpcRequestEnvelope::Bidi {
            metadata: tonic::metadata::MetadataMap::new(),
            body_rx,
            reply_tx,
            kernel_principal: None,
        };
        let handle = tokio::spawn(async move {
            match envelope {
                GrpcRequestEnvelope::Bidi {
                    body_rx: mut rx,
                    reply_tx: tx,
                    ..
                } => {
                    assert_eq!(rx.recv().await, Some(vec![10]));
                    tx.send(GrpcStreamItem::Message(vec![20])).await.unwrap();
                }
                _ => panic!("expected Bidi"),
            }
        });
        body_tx.send(vec![10]).await.unwrap();
        match reply_rx.recv().await {
            Some(GrpcStreamItem::Message(b)) => assert_eq!(b, vec![20]),
            _ => panic!("expected Message(20)"),
        }
        handle.await.unwrap();
    }

    #[tokio::test]
    async fn test_get_or_spawn_with_listener_success() {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let port = listener.local_addr().unwrap().port();
        let errors = Arc::new(Mutex::new(Vec::<(String, String)>::new()));
        let rt: Arc<dyn RuntimeObservability> = Arc::new(RecordingRuntime::new(errors));

        let dispatch = GrpcServerRegistry::global()
            .get_or_spawn_with_listener(
                listener,
                "127.0.0.1",
                port,
                GrpcServerConfig::default(),
                rt,
            )
            .await;
        assert!(dispatch.is_ok());
    }

    // Test-only: the std MutexGuard is held across yield/sleep awaits to
    // sequence the dead-task setup atomically. No real contention is possible
    // (fake handle), so the await-holding-lock lint is suppressed here.
    #[tokio::test]
    #[allow(clippy::await_holding_lock)]
    async fn test_dead_server_evicted_on_reuse() {
        let registry = GrpcServerRegistry::global();
        let port = 17899u16;

        // Insert a dead server handle into the registry.
        {
            let mut guard = registry.inner.lock().unwrap();
            let key = ("127.0.0.1".to_string(), port);
            let dispatch: GrpcDispatchTable = Arc::new(RwLock::new(HashMap::new()));
            let cell = Arc::new(OnceCell::new());
            let dead_task = tokio::spawn(async {});
            // Yield + sleep so the spawned task completes without consuming the handle.
            tokio::task::yield_now().await;
            tokio::time::sleep(std::time::Duration::from_millis(10)).await;
            assert!(dead_task.is_finished(), "task should be finished");
            cell.set(ServerHandle {
                dispatch,
                task: dead_task,
                transport: ServerTransport::Plaintext,
                tls_acceptor: None,
                tls_source: None,
            })
            .ok();
            guard.insert(key, cell);
        }

        // Now spawn a real server on the same port — the dead entry
        // must be evicted so a fresh server is created.
        let listener = tokio::net::TcpListener::bind("127.0.0.1:17899")
            .await
            .unwrap();
        let errors = Arc::new(Mutex::new(Vec::<(String, String)>::new()));
        let rt: Arc<dyn RuntimeObservability> = Arc::new(RecordingRuntime::new(errors));

        let result = registry
            .get_or_spawn_with_listener(
                listener,
                "127.0.0.1",
                port,
                GrpcServerConfig::default(),
                rt,
            )
            .await;

        assert!(result.is_ok(), "dead server should be evicted");
    }

    #[tokio::test]
    async fn test_unregister_from_global_registry() {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let port = listener.local_addr().unwrap().port();
        let errors = Arc::new(Mutex::new(Vec::<(String, String)>::new()));
        let rt: Arc<dyn RuntimeObservability> = Arc::new(RecordingRuntime::new(errors));

        let dispatch = GrpcServerRegistry::global()
            .get_or_spawn_with_listener(
                listener,
                "127.0.0.1",
                port,
                GrpcServerConfig::default(),
                rt,
            )
            .await
            .unwrap();

        let (tx, _rx) = mpsc::channel::<GrpcRequestEnvelope>(4);
        let path = "/test.Unregister/Method".to_string();
        {
            let mut table = dispatch.write().await;
            table.insert(path.clone(), (tx, GrpcMode::Unary, None));
        }
        assert!(dispatch.read().await.contains_key(&path));

        GrpcServerRegistry::global()
            .unregister("127.0.0.1", port, &path)
            .await;

        assert!(!dispatch.read().await.contains_key(&path));
    }

    #[test]
    fn test_unary_handler_is_constructable() {
        let (_tx, _rx) = mpsc::channel::<GrpcRequestEnvelope>(4);
        let _handler = UnaryHandler {
            sender: _tx,
            kernel: None,
        };
    }

    #[test]
    fn test_server_streaming_handler_is_constructable() {
        let (_tx, _rx) = mpsc::channel::<GrpcRequestEnvelope>(4);
        let _handler = ServerStreamingHandler {
            sender: _tx,
            kernel: None,
        };
    }

    #[test]
    fn test_client_streaming_handler_is_constructable() {
        let (_tx, _rx) = mpsc::channel::<GrpcRequestEnvelope>(4);
        let _handler = ClientStreamingHandler {
            sender: _tx,
            kernel: None,
        };
    }

    #[test]
    fn test_bidi_handler_is_constructable() {
        let (_tx, _rx) = mpsc::channel::<GrpcRequestEnvelope>(4);
        let _handler = BidiHandler {
            sender: _tx,
            kernel: None,
        };
    }

    #[tokio::test]
    async fn test_unary_handler_send_fails_when_consumer_stopped() {
        let (tx, rx) = mpsc::channel::<GrpcRequestEnvelope>(1);
        drop(rx);

        let mut handler = UnaryHandler {
            sender: tx,
            kernel: None,
        };
        let req = Request::new(vec![1, 2, 3]);
        let fut = handler.call(req);
        let handle = tokio::spawn(fut);

        let result = handle.await.unwrap();
        let err = result.unwrap_err();
        assert_eq!(err.code(), tonic::Code::Unavailable);
        assert!(err.message().contains("consumer stopped"));
    }

    #[tokio::test]
    async fn test_server_streaming_handler_send_fails_when_consumer_stopped() {
        let (tx, rx) = mpsc::channel::<GrpcRequestEnvelope>(1);
        drop(rx);

        let mut handler = ServerStreamingHandler {
            sender: tx,
            kernel: None,
        };
        let req = Request::new(vec![1, 2, 3]);
        let fut = handler.call(req);
        let handle = tokio::spawn(fut);

        match handle.await.unwrap() {
            Err(err) => {
                assert_eq!(err.code(), tonic::Code::Unavailable);
            }
            Ok(_) => panic!("expected error when consumer stopped"),
        }
    }

    #[tokio::test]
    async fn test_client_streaming_handler_send_fails_when_consumer_stopped() {
        let (tx, rx) = mpsc::channel::<GrpcRequestEnvelope>(1);
        drop(rx);

        let handler = ClientStreamingHandler {
            sender: tx,
            kernel: None,
        };
        assert!(handler.sender.is_closed());
    }

    #[tokio::test]
    async fn test_bidi_handler_send_fails_when_consumer_stopped() {
        let (tx, rx) = mpsc::channel::<GrpcRequestEnvelope>(1);
        drop(rx);

        let handler = BidiHandler {
            sender: tx,
            kernel: None,
        };
        assert!(handler.sender.is_closed());
    }

    #[tokio::test]
    async fn test_unary_handler_reply_channel_dropped() {
        let (tx, mut rx) = mpsc::channel::<GrpcRequestEnvelope>(4);

        let mut handler = UnaryHandler {
            sender: tx,
            kernel: None,
        };
        let req = Request::new(vec![1, 2, 3]);
        let fut = handler.call(req);

        let handle = tokio::spawn(fut);

        let envelope = rx.recv().await.unwrap();
        match envelope {
            GrpcRequestEnvelope::Unary { reply_tx, .. } => {
                drop(reply_tx);
            }
            _ => panic!("expected Unary"),
        }

        let result = handle.await.unwrap();
        let err = result.unwrap_err();
        assert_eq!(err.code(), tonic::Code::Internal);
        assert!(err.message().contains("reply channel dropped"));
    }

    #[tokio::test]
    async fn test_unary_handler_returns_ok_response() {
        let (tx, mut rx) = mpsc::channel::<GrpcRequestEnvelope>(4);

        let mut handler = UnaryHandler {
            sender: tx,
            kernel: None,
        };
        let req = Request::new(vec![10, 20, 30]);
        let fut = handler.call(req);
        let handle = tokio::spawn(fut);

        let envelope = rx.recv().await.unwrap();
        match envelope {
            GrpcRequestEnvelope::Unary { reply_tx, body, .. } => {
                assert_eq!(body, vec![10, 20, 30]);
                let _ = reply_tx.send(GrpcReply::Ok(vec![40, 50]));
            }
            _ => panic!("expected Unary"),
        }

        let result = handle.await.unwrap().unwrap();
        assert_eq!(result.into_inner(), vec![40, 50]);
    }

    #[tokio::test]
    async fn test_unary_handler_returns_error_response() {
        let (tx, mut rx) = mpsc::channel::<GrpcRequestEnvelope>(4);

        let mut handler = UnaryHandler {
            sender: tx,
            kernel: None,
        };
        let req = Request::new(vec![1]);
        let fut = handler.call(req);
        let handle = tokio::spawn(fut);

        let envelope = rx.recv().await.unwrap();
        match envelope {
            GrpcRequestEnvelope::Unary { reply_tx, .. } => {
                let _ = reply_tx.send(GrpcReply::Err(Status::not_found("not found")));
            }
            _ => panic!("expected Unary"),
        }

        let result = handle.await.unwrap();
        let err = result.unwrap_err();
        assert_eq!(err.code(), tonic::Code::NotFound);
    }

    #[tokio::test]
    async fn test_server_streaming_handler_success() {
        let (tx, mut rx) = mpsc::channel::<GrpcRequestEnvelope>(4);

        let mut handler = ServerStreamingHandler {
            sender: tx,
            kernel: None,
        };
        let req = Request::new(vec![1, 2]);
        let fut = handler.call(req);
        let handle = tokio::spawn(fut);

        let envelope = rx.recv().await.unwrap();
        match envelope {
            GrpcRequestEnvelope::ServerStreaming { reply_tx, body, .. } => {
                assert_eq!(body, vec![1, 2]);
                reply_tx
                    .send(GrpcStreamItem::Message(vec![100]))
                    .await
                    .unwrap();
                reply_tx.send(GrpcStreamItem::Done).await.unwrap();
            }
            _ => panic!("expected ServerStreaming"),
        }

        let result = handle.await.unwrap().unwrap();
        let mut stream = result.into_inner();
        assert_eq!(stream.next().await.unwrap().unwrap(), vec![100]);
        assert!(stream.next().await.is_none());
    }

    #[tokio::test]
    async fn test_server_streaming_handler_error_in_stream() {
        let (tx, mut rx) = mpsc::channel::<GrpcRequestEnvelope>(4);

        let mut handler = ServerStreamingHandler {
            sender: tx,
            kernel: None,
        };
        let req = Request::new(vec![1]);
        let fut = handler.call(req);
        let handle = tokio::spawn(fut);

        let envelope = rx.recv().await.unwrap();
        match envelope {
            GrpcRequestEnvelope::ServerStreaming { reply_tx, .. } => {
                reply_tx
                    .send(GrpcStreamItem::Error(Status::internal("stream error")))
                    .await
                    .unwrap();
            }
            _ => panic!("expected ServerStreaming"),
        }

        let result = handle.await.unwrap().unwrap();
        let mut stream = result.into_inner();
        let item = stream.next().await.unwrap();
        let err = item.unwrap_err();
        assert_eq!(err.code(), tonic::Code::Internal);
    }

    #[tokio::test]
    async fn test_bidi_handler_forwards_items() {
        let (tx, mut rx) = mpsc::channel::<GrpcRequestEnvelope>(4);
        let (reply_tx, _reply_rx) = mpsc::channel::<GrpcStreamItem>(4);

        let handler = BidiHandler {
            sender: tx,
            kernel: None,
        };
        let (body_tx, body_rx) = mpsc::channel::<Vec<u8>>(4);
        let envelope_for_test = GrpcRequestEnvelope::Bidi {
            metadata: tonic::metadata::MetadataMap::new(),
            body_rx,
            reply_tx,
            kernel_principal: None,
        };

        let send_result = handler.sender.send(envelope_for_test).await;
        assert!(send_result.is_ok());

        let received = rx.recv().await;
        assert!(received.is_some());

        body_tx.send(vec![10]).await.unwrap();
        body_tx.send(vec![20]).await.unwrap();
        drop(body_tx);
    }

    #[tokio::test]
    async fn test_grpc_stream_item_variants() {
        let msg = GrpcStreamItem::Message(vec![1, 2]);
        match msg {
            GrpcStreamItem::Message(b) => assert_eq!(b, vec![1, 2]),
            _ => panic!(),
        }

        let err = GrpcStreamItem::Error(Status::internal("err"));
        match err {
            GrpcStreamItem::Error(s) => assert_eq!(s.code(), tonic::Code::Internal),
            _ => panic!(),
        }

        let done = GrpcStreamItem::Done;
        match done {
            GrpcStreamItem::Done => {}
            _ => panic!(),
        }
    }

    #[derive(Debug)]
    struct MockAuthenticator {
        should_fail_unauthenticated: bool,
        should_fail_unavailable: bool,
    }

    #[async_trait::async_trait]
    impl camel_auth::TokenAuthenticator for MockAuthenticator {
        async fn authenticate_bearer(
            &self,
            _token: &str,
        ) -> Result<camel_api::security_policy::Principal, camel_api::CamelError> {
            if self.should_fail_unavailable {
                return Err(camel_api::CamelError::AuthProviderUnavailable(
                    "auth provider down".into(),
                ));
            }
            if self.should_fail_unauthenticated {
                return Err(camel_api::CamelError::Unauthenticated(
                    "invalid token".into(),
                ));
            }
            Ok(camel_api::security_policy::Principal {
                subject: "test-user".into(),
                issuer: "test-issuer".into(),
                audience: vec![],
                scopes: vec![],
                roles: vec![],
                claims: serde_json::json!({}),
            })
        }
    }

    #[test]
    fn grpc_plan_present_at_interceptor_construction() {
        // Task 2.1 lifecycle fix: the interceptor's kernel state must be
        // captured from the security context at construction time — the
        // plan and providers ride the dispatch entry, never a setter
        // patched on after the interceptor exists.
        let registry = Arc::new(ProviderRegistry::new());
        let plan = RouteSecurityPlan {
            access_mode: AccessMode::Authenticated,
            provider_ref: Some("idp-a".to_string()),
            transport: camel_api::security_policy::TransportId::Grpc,
            credential_sources: vec![CredentialSource::AuthorizationHeader],
            audience_binding: None,
        };

        let mut ctx = SecurityContext::new(GrantAllPolicy)
            .with_credential_sources(plan.credential_sources.clone())
            .with_plan(plan.clone())
            .with_providers(Arc::clone(&registry));

        let kernel = GrpcKernelAuth::from_security_context(&ctx).expect("kernel captured"); // allow-unwrap
        assert!(matches!(kernel.plan.access_mode, AccessMode::Authenticated));
        assert_eq!(kernel.plan.provider_ref.as_deref(), Some("idp-a"));
        assert!(matches!(
            kernel.plan.transport,
            camel_api::security_policy::TransportId::Grpc
        ));
        assert_eq!(kernel.plan.credential_sources, plan.credential_sources);
        // Providers captured by Arc identity — the same registry the
        // SecurityContext carries, not a copy.
        assert!(Arc::ptr_eq(&kernel.providers, &registry));

        // Without a plan there is no kernel state: the transport is Public
        // pass-through.
        ctx.plan = None;
        assert!(GrpcKernelAuth::from_security_context(&ctx).is_none());

        // Without providers a plan can never authenticate: no kernel either.
        ctx.plan = Some(plan);
        ctx.providers = None;
        assert!(GrpcKernelAuth::from_security_context(&ctx).is_none());
    }

    struct GrantAllPolicy;

    #[tonic::async_trait]
    impl camel_api::security_policy::SecurityPolicy for GrantAllPolicy {
        async fn evaluate(
            &self,
            _exchange: &mut camel_api::Exchange,
            _auth: &camel_api::security_policy::AuthContext<'_>,
        ) -> Result<camel_api::AuthorizationDecision, camel_api::CamelError> {
            Ok(camel_api::AuthorizationDecision::Granted {
                principal: camel_api::security_policy::Principal {
                    subject: "grant-all".into(),
                    issuer: "test".into(),
                    audience: vec![],
                    scopes: vec![],
                    roles: vec![],
                    claims: serde_json::Value::Null,
                },
            })
        }
    }

    /// Kernel fixture: dispatch-entry kernel state over a single mock
    /// provider (`mock-idp`). The deleted legacy arm threaded
    /// `authenticator_opt` + `credential_sources` through the handler;
    /// the kernel plan's sources and registry drive extraction and
    /// minting now.
    fn kernel_fixture(
        sources: Vec<CredentialSource>,
        authenticator: Arc<dyn camel_auth::TokenAuthenticator>,
    ) -> Arc<GrpcKernelAuth> {
        let registry = ProviderRegistry::new();
        registry.register(
            "mock-idp",
            camel_auth::ProviderEntry {
                authenticator,
                audience_binding: None,
            },
        );
        Arc::new(GrpcKernelAuth {
            plan: RouteSecurityPlan {
                access_mode: AccessMode::Authenticated,
                provider_ref: Some("mock-idp".to_string()),
                transport: camel_api::security_policy::TransportId::Grpc,
                credential_sources: sources,
                audience_binding: None,
            },
            providers: Arc::new(registry),
        })
    }

    fn ok_mock() -> Arc<MockAuthenticator> {
        Arc::new(MockAuthenticator {
            should_fail_unauthenticated: false,
            should_fail_unavailable: false,
        })
    }

    #[tokio::test]
    async fn test_grpc_auth_valid_token() {
        let (tx, mut rx) = mpsc::channel::<GrpcRequestEnvelope>(1);
        let mut handler = UnaryHandler {
            sender: tx,
            kernel: Some(kernel_fixture(
                vec![CredentialSource::AuthorizationHeader],
                ok_mock(),
            )),
        };

        let mut request = Request::new(vec![]);
        request
            .metadata_mut()
            .insert("authorization", "Bearer test-token".parse().unwrap());

        let handle = tokio::spawn(async move {
            let envelope = rx.recv().await.unwrap();
            match envelope {
                GrpcRequestEnvelope::Unary {
                    kernel_principal,
                    reply_tx,
                    ..
                } => {
                    let principal = kernel_principal.expect("kernel mints principal"); // allow-unwrap
                    assert_eq!(principal.principal().subject, "test-user");
                    assert_eq!(principal.principal().issuer, "test-issuer");
                    let _ = reply_tx.send(GrpcReply::Ok(vec![]));
                }
                _ => panic!("expected Unary"),
            }
        });

        let result = handler.call(request).await;
        assert!(result.is_ok());
        handle.await.unwrap();
    }

    #[tokio::test]
    async fn grpc_credential_sources_custom_header_authenticates() {
        let (tx, mut rx) = mpsc::channel::<GrpcRequestEnvelope>(1);
        let mut handler = UnaryHandler {
            sender: tx,
            kernel: Some(kernel_fixture(
                vec![CredentialSource::Header {
                    name: "x-api-key".to_string(),
                }],
                ok_mock(),
            )),
        };

        let mut request = Request::new(vec![]);
        request
            .metadata_mut()
            .insert("x-api-key", "secret-key".parse().unwrap());

        let handle = tokio::spawn(async move {
            let envelope = rx.recv().await.unwrap();
            match envelope {
                GrpcRequestEnvelope::Unary {
                    kernel_principal,
                    reply_tx,
                    ..
                } => {
                    let principal = kernel_principal.expect("kernel mints principal"); // allow-unwrap
                    assert_eq!(principal.principal().subject, "test-user");
                    let _ = reply_tx.send(GrpcReply::Ok(vec![]));
                }
                _ => panic!("expected Unary"),
            }
        });

        let result = handler.call(request).await;
        assert!(result.is_ok());
        handle.await.unwrap();
    }

    #[tokio::test]
    async fn grpc_credential_sources_default_bearer_unchanged() {
        let (tx, mut rx) = mpsc::channel::<GrpcRequestEnvelope>(1);
        let mut handler = UnaryHandler {
            sender: tx,
            kernel: Some(kernel_fixture(
                vec![CredentialSource::AuthorizationHeader],
                ok_mock(),
            )),
        };

        let mut request = Request::new(vec![]);
        request
            .metadata_mut()
            .insert("authorization", "Bearer test-token".parse().unwrap());

        let handle = tokio::spawn(async move {
            let envelope = rx.recv().await.unwrap();
            match envelope {
                GrpcRequestEnvelope::Unary {
                    kernel_principal,
                    reply_tx,
                    ..
                } => {
                    let principal = kernel_principal.expect("kernel mints principal"); // allow-unwrap
                    assert_eq!(principal.principal().subject, "test-user");
                    let _ = reply_tx.send(GrpcReply::Ok(vec![]));
                }
                _ => panic!("expected Unary"),
            }
        });

        let result = handler.call(request).await;
        assert!(result.is_ok());
        handle.await.unwrap();
    }

    #[tokio::test]
    async fn test_grpc_auth_missing_token() {
        let (tx, _rx) = mpsc::channel::<GrpcRequestEnvelope>(1);
        let mut handler = UnaryHandler {
            sender: tx,
            kernel: Some(kernel_fixture(
                vec![CredentialSource::AuthorizationHeader],
                ok_mock(),
            )),
        };

        let request = Request::new(vec![]);

        let result = handler.call(request).await;
        let status = result.expect_err("missing credential must deny"); // allow-unwrap
        assert_eq!(status.code(), tonic::Code::Unauthenticated);
    }

    #[tokio::test]
    async fn test_grpc_auth_invalid_token() {
        let (tx, _rx) = mpsc::channel::<GrpcRequestEnvelope>(1);
        let mut handler = UnaryHandler {
            sender: tx,
            kernel: Some(kernel_fixture(
                vec![CredentialSource::AuthorizationHeader],
                Arc::new(MockAuthenticator {
                    should_fail_unauthenticated: true,
                    should_fail_unavailable: false,
                }),
            )),
        };

        let mut request = Request::new(vec![]);
        request
            .metadata_mut()
            .insert("authorization", "Bearer bad-token".parse().unwrap());

        let result = handler.call(request).await;
        let status = result.expect_err("invalid credential must deny"); // allow-unwrap
        assert_eq!(status.code(), tonic::Code::Unauthenticated);
    }

    #[tokio::test]
    async fn test_grpc_auth_provider_unavailable() {
        let (tx, _rx) = mpsc::channel::<GrpcRequestEnvelope>(1);
        let mut handler = UnaryHandler {
            sender: tx,
            kernel: Some(kernel_fixture(
                vec![CredentialSource::AuthorizationHeader],
                Arc::new(MockAuthenticator {
                    should_fail_unauthenticated: false,
                    should_fail_unavailable: true,
                }),
            )),
        };

        let mut request = Request::new(vec![]);
        request
            .metadata_mut()
            .insert("authorization", "Bearer valid-token".parse().unwrap());

        let result = handler.call(request).await;
        let status = result.expect_err("unavailable provider must surface"); // allow-unwrap
        assert_eq!(status.code(), tonic::Code::Unavailable);
    }

    #[tokio::test]
    async fn test_grpc_no_auth_configured() {
        // No kernel state (plan-less route): Public pass-through — no
        // extraction, no error, no minted principal.
        let (tx, mut rx) = mpsc::channel::<GrpcRequestEnvelope>(1);
        let mut handler = UnaryHandler {
            sender: tx,
            kernel: None,
        };

        let request = Request::new(vec![]);

        let handle = tokio::spawn(async move {
            let envelope = rx.recv().await.unwrap();
            match envelope {
                GrpcRequestEnvelope::Unary {
                    kernel_principal,
                    reply_tx,
                    ..
                } => {
                    assert!(kernel_principal.is_none());
                    let _ = reply_tx.send(GrpcReply::Ok(vec![]));
                }
                _ => panic!("expected Unary"),
            }
        });

        let result = handler.call(request).await;
        assert!(result.is_ok());
        handle.await.unwrap();
    }

    #[tokio::test]
    async fn test_server_handle_struct() {
        let dispatch: GrpcDispatchTable = Arc::new(RwLock::new(HashMap::new()));
        let task = tokio::spawn(async {});
        let handle = ServerHandle {
            dispatch,
            task,
            transport: ServerTransport::Plaintext,
            tls_acceptor: None,
            tls_source: None,
        };
        let _ = handle;
    }

    // ── ADR-0012 (e) site regression test ──────────────────────────────────

    #[tokio::test]
    async fn test_run_grpc_server_route_id_derivation() {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let route_id = listener
            .local_addr()
            .map(|addr| format!("grpc-server:{addr}"))
            .unwrap_or_else(|_| "grpc-server:unknown".to_string());
        assert!(!route_id.is_empty(), "route_id must not be empty");
        assert!(
            route_id.starts_with("grpc-server:"),
            "route_id should start with 'grpc-server:': got {route_id}"
        );
    }

    #[tokio::test]
    async fn test_increment_errors_recording_works() {
        // This test validates the metrics recording machinery for the accept
        // error branch without driving the real accept loop into an error.
        //
        // Driving the real loop requires platform-specific fd manipulation
        // (dup+shutdown) that causes the accept to return EINVAL on every
        // iteration — the loop spins indefinitely recording spurious errors,
        // which cannot be precisely asserted. The error condition is not
        // single-shot; it persists after shutdown.
        //
        // The accept error BRANCH (server.rs:189-196) is exercised indirectly:
        //   - test_run_grpc_server_happy_path confirms the accept loop runs
        //     and records zero errors on success.
        //   - This test confirms the recording subsystem correctly captures
        //     the call signature (route_id + label) that the error branch
        //     would emit.
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let expected_route_id = listener
            .local_addr()
            .map(|addr| format!("grpc-server:{addr}"))
            .unwrap();
        let _dispatch: GrpcDispatchTable = Arc::new(RwLock::new(HashMap::new()));
        let errors = Arc::new(Mutex::new(Vec::<(String, String)>::new()));
        let rt: Arc<dyn RuntimeObservability> = Arc::new(RecordingRuntime::new(errors.clone()));

        // Simulate the accept-error branch: verify the metric call signature
        rt.metrics()
            .increment_errors(&expected_route_id, "e:grpc:accept");

        let recorded = errors.lock().unwrap();
        assert_eq!(recorded.len(), 1, "expected one error record");
        assert_eq!(recorded[0].0, expected_route_id, "route_id mismatch");
        assert_eq!(recorded[0].1, "e:grpc:accept", "error label mismatch");
    }

    #[tokio::test]
    async fn test_run_grpc_server_happy_path() {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        let _dispatch: GrpcDispatchTable = Arc::new(RwLock::new(HashMap::new()));
        let errors = Arc::new(Mutex::new(Vec::<(String, String)>::new()));
        let rt: Arc<dyn RuntimeObservability> = Arc::new(RecordingRuntime::new(errors.clone()));

        let handle = tokio::spawn(run_grpc_server(
            listener,
            _dispatch,
            GrpcServerConfig::default(),
            None,
            rt,
        ));

        // Connect to verify the accept loop handles clients
        let conn =
            tokio::time::timeout(Duration::from_secs(2), tokio::net::TcpStream::connect(addr))
                .await;
        assert!(conn.is_ok(), "server should accept connections");

        // Verify no accept errors recorded on happy path
        {
            let recorded = errors.lock().unwrap();
            assert!(
                recorded.is_empty(),
                "no accept errors expected on happy path"
            );
        }

        handle.abort();
        let _ = handle.await;
    }

    /// Regression: Registry transport-mismatch — cannot mix TLS/plaintext on same listener.
    /// This test verifies the behavioral fail-closed path: first bind plaintext, then
    /// attempt TLS on the same port → must error with "transport" in the message.
    #[tokio::test]
    async fn test_registry_transport_mismatch_errors() {
        use crate::config::ServerTlsConfig;

        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let port = listener.local_addr().unwrap().port();
        let errors = Arc::new(Mutex::new(Vec::<(String, String)>::new()));
        let rt: Arc<dyn RuntimeObservability> = Arc::new(RecordingRuntime::new(errors));

        // First, bind plaintext on this port
        let plaintext_config = GrpcServerConfig {
            max_receive_message_len: None,
            transport: ServerTransport::Plaintext,
        };
        let dispatch = GrpcServerRegistry::global()
            .get_or_spawn_with_listener(listener, "127.0.0.1", port, plaintext_config, rt.clone())
            .await;
        assert!(dispatch.is_ok(), "plaintext bind should succeed");

        // Now attempt TLS on the SAME port — MUST FAIL with transport mismatch
        let tls_config = GrpcServerConfig {
            max_receive_message_len: None,
            transport: ServerTransport::Tls(ServerTlsConfig {
                server_cert_path: "/nonexistent/cert.pem".to_string(),
                server_key_path: "/nonexistent/key.pem".to_string(),
                client_ca_path: None,
            }),
        };

        // Bind a new listener for the TLS attempt (will fail at validation, not bind)
        let listener2 = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();

        // Use the SAME port as the first bind to trigger mismatch
        let result = GrpcServerRegistry::global()
            .get_or_spawn_with_listener(listener2, "127.0.0.1", port, tls_config, rt)
            .await;

        assert!(
            result.is_err(),
            "TLS on port already serving plaintext must fail (transport-mismatch)"
        );
        match result {
            Err(e) => {
                let err = e.to_string();
                assert!(
                    err.contains("transport"),
                    "error must mention transport mismatch: {err}"
                );
            }
            Ok(_) => panic!("expected error, got Ok"),
        }
    }

    #[tokio::test]
    async fn test_unregister_last_route_keeps_server_alive() {
        let registry = GrpcServerRegistry::global();
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let port = listener.local_addr().unwrap().port();
        let errors = Arc::new(Mutex::new(Vec::<(String, String)>::new()));
        let rt: Arc<dyn RuntimeObservability> = Arc::new(RecordingRuntime::new(errors));

        // Register 2 routes on same (host, port)
        let _dispatch1 = registry
            .get_or_spawn_with_listener(
                listener,
                "127.0.0.1",
                port,
                GrpcServerConfig::default(),
                rt.clone(),
            )
            .await
            .unwrap();

        // Second route on same port (listener not used, server already spawned)
        let dummy_listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let _dispatch2 = registry
            .get_or_spawn_with_listener(
                dummy_listener,
                "127.0.0.1",
                port,
                GrpcServerConfig::default(),
                rt,
            )
            .await
            .unwrap();

        let key = ("127.0.0.1".to_string(), port);

        // Keep a reference to the cell to check task state after unregister
        let cell = {
            let guard = registry.inner.lock().unwrap();
            guard.get(&key).unwrap().clone()
        };

        // Unregister route 1 -> task still alive
        registry.unregister("127.0.0.1", port, "/route1").await;
        {
            let handle = cell.get().expect("handle should exist");
            assert!(
                !handle.task.is_finished(),
                "task should still be alive after first unregister"
            );
        }

        // Unregister route 2 -> server stays alive (process-lifetime)
        registry.unregister("127.0.0.1", port, "/route2").await;
        tokio::time::sleep(Duration::from_millis(10)).await;
        {
            let handle = cell.get().expect("handle should exist");
            assert!(
                !handle.task.is_finished(),
                "task should still be alive — server is process-lifetime"
            );
        }

        // Entry stays in registry for potential restart.
        {
            let guard = registry.inner.lock().unwrap();
            assert!(
                guard.get(&key).is_some(),
                "entry should remain in registry — server kept alive for restart"
            );
        }
    }

    #[test]
    fn test_accept_backoff_config_values() {
        let cfg = accept_backoff_config();
        assert_eq!(cfg.initial_delay, Duration::from_millis(10));
        assert_eq!(cfg.multiplier, 2.0);
        assert_eq!(cfg.max_delay, Duration::from_secs(5));
    }

    #[test]
    fn auth_error_to_status_provider_unavailable_is_unavailable() {
        let err =
            camel_api::CamelError::AuthProviderUnavailable("arbitrary wording no marker".into());
        let status = auth_error_to_status(err);
        assert_eq!(status.code(), tonic::Code::Unavailable);
        assert!(
            status.message().contains("arbitrary wording no marker"),
            "message should contain payload: {}",
            status.message()
        );
    }

    #[test]
    fn auth_error_to_status_generic_processor_error_is_internal() {
        let err = camel_api::CamelError::ProcessorError("auth provider unavailable".into());
        let status = auth_error_to_status(err);
        assert_eq!(status.code(), tonic::Code::Internal);
    }

    #[test]
    fn auth_error_to_status_unauthenticated_is_unauthenticated() {
        let err = camel_api::CamelError::Unauthenticated("bad".into());
        let status = auth_error_to_status(err);
        assert_eq!(status.code(), tonic::Code::Unauthenticated);
    }
}