mothership 0.0.100

Process supervisor with HTTP exposure - wrap, monitor, and expose your fleet
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
//! Communications relay
//!
//! Routes external traffic to fleet ships and bays.
//! Supports multiple named binds and WASM payload processing.
//! Uses circuit breakers to protect against slow/failing backends.

use std::collections::HashMap;
use std::convert::Infallible;
use std::sync::Arc;
use std::time::Duration;

use breaker_machines::CircuitBreaker;
use rama::{
    Layer, Service,
    extensions::ExtensionsRef,
    http::{
        Body, Request, Response, StatusCode, Uri,
        client::{EasyHttpWebClient, HttpConnector},
        header::{HOST, HeaderName, HeaderValue},
        io::upgrade,
        layer::{compression::CompressionLayer, trace::TraceLayer},
        server::HttpServer,
        service::fs::ServeDir,
        ws::{
            AsyncWebSocket,
            handshake::{client::HttpClientWebSocketExt, server::WebSocketMatcher},
            protocol::Role,
        },
    },
    matcher::Matcher,
    net::{
        client::{ConnectorService, EstablishedClientConnection},
        fingerprint::Ja4H,
        stream::{SocketInfo, layer::http::BodyLimitLayer},
    },
    proxy::haproxy::server::HaProxyLayer,
    rt::Executor,
    service::service_fn,
    tcp::server::TcpListener,
    ua::{UserAgent, layer::classifier::UserAgentClassifierLayer},
    unix::client::UnixConnector,
};
use regex::Regex;
use throttle_machines::token_bucket;
use tokio::sync::{Mutex, RwLock};
use tracing::{debug, error, info, warn};

use super::cors_cache::{CorsCache, CorsCacheKey};
use super::sensors::MetricsRegistry;
use crate::charter::{Bind, Manifest, StaticDirConfig, UaFilter};
use crate::docking::{Boarding, Cargo, Disembark, DockingConnector, next_conn_id};
use crate::payload::{ModuleAction, ModuleRuntime, RequestInfo, ResponseInfo};

/// Build a blocking response from ModuleAction::Block
fn build_block_response(
    status: u16,
    body: String,
    headers: Option<HashMap<String, String>>,
) -> Response {
    let mut builder =
        Response::builder().status(StatusCode::from_u16(status).unwrap_or(StatusCode::FORBIDDEN));
    if let Some(hdrs) = headers {
        for (key, value) in hdrs {
            if let Ok(name) = key.parse::<HeaderName>() {
                builder = builder.header(name, value);
            }
        }
    }
    builder.body(Body::from(body)).unwrap()
}

/// Resolved backend target for routing
#[derive(Clone)]
enum BackendTarget {
    /// TCP backend with HTTP base URI (e.g., "http://127.0.0.1:3000")
    Tcp { base_uri: String },
    /// Unix socket backend with socket path (e.g., "/tmp/app.sock")
    Unix { socket_path: String },
    /// Docked bay using docking protocol
    Docked { bay_name: String },
}

impl std::fmt::Display for BackendTarget {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            BackendTarget::Tcp { base_uri } => write!(f, "{}", base_uri),
            BackendTarget::Unix { socket_path } => write!(f, "unix://{}", socket_path),
            BackendTarget::Docked { bay_name } => write!(f, "docked://{}", bay_name),
        }
    }
}

/// Route configuration for a specific bind
#[derive(Clone)]
struct Route {
    /// Pattern to match (regex)
    pattern: Regex,
    /// Backend target (TCP or Unix socket)
    backend: BackendTarget,
    /// Ship name (for logging)
    ship_name: String,
    /// Route key for metrics (bind:pattern)
    route_key: String,
    /// Circuit breaker for this backend
    circuit_breaker: Arc<Mutex<CircuitBreaker>>,
    /// Prefix to strip from path before forwarding
    strip_prefix: Option<String>,
    /// User-Agent filter for route matching
    ua_filter: Option<UaFilter>,
}

/// Default circuit breaker settings
fn create_circuit_breaker(name: &str) -> CircuitBreaker {
    CircuitBreaker::builder(name)
        .failure_threshold(5) // Open after 5 failures
        .failure_window_secs(60.0) // Within 60 seconds
        .half_open_timeout_secs(30.0) // Try again after 30 seconds
        .success_threshold(2) // Close after 2 successes
        .on_open(|name| warn!(backend = %name, "Circuit breaker opened"))
        .on_close(|name| info!(backend = %name, "Circuit breaker closed"))
        .build()
}

/// Rate limiter state for token bucket algorithm
#[derive(Debug, Clone)]
struct RateLimitState {
    tokens: f64,
    last_refill: f64,
}

impl Default for RateLimitState {
    fn default() -> Self {
        Self {
            tokens: 0.0,
            last_refill: 0.0,
        }
    }
}

/// Global and per-IP rate limiting
struct RateLimiter {
    /// Global rate limit state (1000 req/s)
    global_state: Arc<Mutex<RateLimitState>>,
    /// Per-IP rate limit state (100 req/min per IP)
    per_ip_states: Arc<dashmap::DashMap<String, RateLimitState>>,
    /// Global limit: 1000 requests per second
    global_capacity: f64,
    global_refill_rate: f64,
    /// Per-IP limit: 100 requests per minute (1.666... req/s)
    per_ip_capacity: f64,
    per_ip_refill_rate: f64,
}

impl RateLimiter {
    /// Create a new rate limiter with specified settings
    fn new(global_rps: Option<f64>, per_ip_rpm: Option<f64>) -> Self {
        let global_capacity = global_rps.unwrap_or(f64::INFINITY);
        let global_refill_rate = global_rps.unwrap_or(f64::INFINITY);
        let per_ip_capacity = per_ip_rpm.unwrap_or(f64::INFINITY);
        let per_ip_refill_rate = per_ip_rpm.map(|rpm| rpm / 60.0).unwrap_or(f64::INFINITY);

        Self {
            global_state: Arc::new(Mutex::new(RateLimitState {
                tokens: global_capacity, // Start with full capacity
                last_refill: 0.0,
            })),
            per_ip_states: Arc::new(dashmap::DashMap::new()),
            global_capacity,
            global_refill_rate,
            per_ip_capacity,
            per_ip_refill_rate,
        }
    }

    /// Check if a request should be allowed (global + per-IP check)
    /// Returns Ok(()) if allowed, Err(retry_after) if rate limited
    async fn check_request(&self, client_ip: &str) -> Result<(), f64> {
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_secs_f64();

        // Check global rate limit first
        {
            let mut state = self.global_state.lock().await;
            let result = token_bucket::check(
                state.tokens,
                state.last_refill,
                now,
                self.global_capacity,
                self.global_refill_rate,
            );

            if !result.allowed {
                warn!(
                    retry_after = result.retry_after,
                    "Global rate limit exceeded"
                );
                return Err(result.retry_after);
            }

            // Update state
            state.tokens = result.new_tokens;
            state.last_refill = now;
        }

        // Check per-IP rate limit
        let mut ip_state = self
            .per_ip_states
            .entry(client_ip.to_string())
            .or_insert_with(|| RateLimitState {
                tokens: self.per_ip_capacity, // Start with full capacity for new IPs
                last_refill: now,
            });

        let result = token_bucket::check(
            ip_state.tokens,
            ip_state.last_refill,
            now,
            self.per_ip_capacity,
            self.per_ip_refill_rate,
        );

        if !result.allowed {
            warn!(
                client_ip = %client_ip,
                retry_after = result.retry_after,
                "Per-IP rate limit exceeded"
            );
            return Err(result.retry_after);
        }

        // Update state
        ip_state.tokens = result.new_tokens;
        ip_state.last_refill = now;

        Ok(())
    }

    /// Periodic cleanup of stale IP entries (LRU eviction)
    /// Call this periodically to prevent unbounded memory growth
    #[allow(dead_code)]
    async fn cleanup_stale_entries(&self, max_entries: usize) {
        if self.per_ip_states.len() > max_entries {
            // Simple strategy: remove oldest 10% when capacity exceeded
            let to_remove = (self.per_ip_states.len() - max_entries).max(max_entries / 10);

            let now = std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_secs_f64();

            // Collect IPs that haven't been used in the last 5 minutes
            let stale_threshold = now - 300.0; // 5 minutes
            let stale_ips: Vec<String> = self
                .per_ip_states
                .iter()
                .filter(|entry| entry.value().last_refill < stale_threshold)
                .map(|entry| entry.key().clone())
                .take(to_remove)
                .collect();

            for ip in stale_ips {
                self.per_ip_states.remove(&ip);
            }

            debug!(removed = to_remove, "Cleaned up stale rate limit entries");
        }
    }
}

/// Routes for a specific bind
#[derive(Clone, Default)]
struct BindRoutes {
    routes: Vec<Route>,
}

/// HTTP exposure layer - manages multiple listeners
pub struct HttpExposure {
    /// Named binds (bind_name -> address)
    binds: HashMap<String, Bind>,
    /// Routes per bind (bind_name -> routes)
    routes: HashMap<String, BindRoutes>,
    /// WASM module runtime
    module_runtime: Arc<RwLock<Option<ModuleRuntime>>>,
    /// Module configs for lazy loading
    module_configs: Vec<crate::charter::Module>,
    /// Static directories configuration (sorted by prefix length, longest first)
    static_dirs: Vec<StaticDirConfig>,
    /// Enable response compression
    compression: bool,
    /// Bay connectors for docked backends (populated after bays launch)
    bay_connectors: Arc<RwLock<HashMap<String, Arc<DockingConnector>>>>,
    /// CORS preflight response cache
    cors_cache: Option<Arc<CorsCache>>,
    /// Rate limiter (global + per-IP, None = unlimited)
    rate_limiter: Option<Arc<RateLimiter>>,
}

impl HttpExposure {
    /// Create HTTP exposure from manifest
    ///
    /// Returns None if no binds are configured.
    pub fn from_manifest(manifest: &Manifest) -> Option<Self> {
        if manifest.mothership.bind.is_empty() {
            return None;
        }

        // Clone binds from mothership config
        let binds = manifest.mothership.bind.clone();

        // Build routes per bind from ships
        let mut routes: HashMap<String, BindRoutes> = HashMap::new();

        // Initialize empty routes for each bind
        for bind_name in binds.keys() {
            routes.insert(bind_name.clone(), BindRoutes::default());
        }

        // Process vessels in declaration order to preserve routing priority
        for vessel in &manifest.vessels {
            match vessel {
                crate::charter::Vessel::Ship { config, .. } => {
                    if config.routes.is_empty() {
                        continue;
                    }

                    // Get backend target from ship's internal bind address
                    let backend = match &config.bind {
                        Some(Bind::Tcp { host, port, .. }) => {
                            let h = if host == "0.0.0.0" { "127.0.0.1" } else { host };
                            BackendTarget::Tcp {
                                base_uri: format!("http://{}:{}", h, port),
                            }
                        }
                        Some(Bind::Unix { path }) => BackendTarget::Unix {
                            socket_path: path.clone(),
                        },
                        None => {
                            warn!(
                                ship = %config.name,
                                "Ship has routes but no bind address, skipping"
                            );
                            continue;
                        }
                    };

                    for route_config in &config.routes {
                        // Check if the bind exists
                        if !binds.contains_key(&route_config.bind) {
                            warn!(
                                ship = %config.name,
                                bind = %route_config.bind,
                                "Route references unknown bind, skipping"
                            );
                            continue;
                        }

                        match Regex::new(&route_config.pattern) {
                            Ok(regex) => {
                                let bind_routes =
                                    routes.entry(route_config.bind.clone()).or_default();
                                let breaker_name = format!("{}:{}", config.name, route_config.bind);
                                bind_routes.routes.push(Route {
                                    pattern: regex,
                                    backend: backend.clone(),
                                    ship_name: config.name.clone(),
                                    route_key: format!(
                                        "{}:{}",
                                        route_config.bind, route_config.pattern
                                    ),
                                    circuit_breaker: Arc::new(Mutex::new(create_circuit_breaker(
                                        &breaker_name,
                                    ))),
                                    strip_prefix: route_config.strip_prefix.clone(),
                                    ua_filter: route_config.ua_filter.clone(),
                                });
                                info!(
                                    ship = %config.name,
                                    bind = %route_config.bind,
                                    pattern = %route_config.pattern,
                                    backend = %backend,
                                    strip_prefix = ?route_config.strip_prefix,
                                    ua_filter = ?route_config.ua_filter,
                                    "Registered route with circuit breaker"
                                );
                            }
                            Err(e) => {
                                error!(
                                    ship = %config.name,
                                    bind = %route_config.bind,
                                    pattern = %route_config.pattern,
                                    error = %e,
                                    "Invalid route pattern"
                                );
                            }
                        }
                    }
                }
                crate::charter::Vessel::Bay { config, .. } => {
                    if config.routes.is_empty() {
                        continue;
                    }

                    // Bays use docked backend target
                    let backend = BackendTarget::Docked {
                        bay_name: config.name.clone(),
                    };

                    for route_config in &config.routes {
                        // Check if the bind exists
                        if !binds.contains_key(&route_config.bind) {
                            warn!(
                                bay = %config.name,
                                bind = %route_config.bind,
                                "Bay route references unknown bind, skipping"
                            );
                            continue;
                        }

                        match Regex::new(&route_config.pattern) {
                            Ok(regex) => {
                                let bind_routes =
                                    routes.entry(route_config.bind.clone()).or_default();
                                let breaker_name = format!("{}:{}", config.name, route_config.bind);
                                bind_routes.routes.push(Route {
                                    pattern: regex,
                                    backend: backend.clone(),
                                    ship_name: config.name.clone(),
                                    route_key: format!(
                                        "{}:{}",
                                        route_config.bind, route_config.pattern
                                    ),
                                    circuit_breaker: Arc::new(Mutex::new(create_circuit_breaker(
                                        &breaker_name,
                                    ))),
                                    strip_prefix: route_config.strip_prefix.clone(),
                                    ua_filter: route_config.ua_filter.clone(),
                                });
                                info!(
                                    bay = %config.name,
                                    bind = %route_config.bind,
                                    pattern = %route_config.pattern,
                                    backend = %backend,
                                    ua_filter = ?route_config.ua_filter,
                                    "Registered docked bay route"
                                );
                            }
                            Err(e) => {
                                error!(
                                    bay = %config.name,
                                    bind = %route_config.bind,
                                    pattern = %route_config.pattern,
                                    error = %e,
                                    "Invalid route pattern"
                                );
                            }
                        }
                    }
                }
            }
        }

        // Sort static_dirs by prefix length (longest first) for proper matching
        let mut static_dirs = manifest.mothership.static_dirs.clone();
        static_dirs.sort_by(|a, b| b.prefix.len().cmp(&a.prefix.len()));

        // Initialize CORS cache if enabled
        let cors_cache = if manifest.mothership.cors_cache.is_enabled() {
            let ttl = Duration::from_secs(manifest.mothership.cors_cache.default_ttl());
            let max_entries = manifest.mothership.cors_cache.max_entries();
            info!(
                ttl_secs = ttl.as_secs(),
                max_entries = max_entries,
                "CORS preflight cache enabled"
            );
            Some(Arc::new(CorsCache::new(ttl, max_entries)))
        } else {
            None
        };

        let rate_limiter = manifest.mothership.rate_limiting.as_ref().map(|config| {
            let limiter = Arc::new(RateLimiter::new(config.global_rps, config.per_ip_rpm));

            match (config.global_rps, config.per_ip_rpm) {
                (Some(global), Some(per_ip)) => {
                    info!(
                        global_limit = format!("{} req/s", global),
                        per_ip_limit = format!("{} req/min", per_ip),
                        "Rate limiting enabled"
                    );
                }
                (Some(global), None) => {
                    info!(
                        global_limit = format!("{} req/s", global),
                        "Rate limiting enabled (global only)"
                    );
                }
                (None, Some(per_ip)) => {
                    info!(
                        per_ip_limit = format!("{} req/min", per_ip),
                        "Rate limiting enabled (per-IP only)"
                    );
                }
                (None, None) => {
                    info!("Rate limiting configured but unlimited");
                }
            }
            limiter
        });

        if rate_limiter.is_none() {
            info!("Rate limiting disabled (unlimited)");
        }

        Some(Self {
            binds,
            routes,
            module_runtime: Arc::new(RwLock::new(None)),
            module_configs: manifest.modules.clone(),
            static_dirs,
            compression: manifest.mothership.compression,
            bay_connectors: Arc::new(RwLock::new(HashMap::new())),
            cors_cache,
            rate_limiter,
        })
    }

    /// Register a bay connector after the bay has docked
    pub async fn register_bay_connector(&self, bay_name: String, connector: Arc<DockingConnector>) {
        self.bay_connectors
            .write()
            .await
            .insert(bay_name, connector);
    }

    /// Get the bay connectors map (for passing to request handlers)
    pub fn bay_connectors(&self) -> Arc<RwLock<HashMap<String, Arc<DockingConnector>>>> {
        self.bay_connectors.clone()
    }

    /// Run all HTTP servers
    pub async fn run(self, shutdown: tokio::sync::watch::Receiver<bool>) -> anyhow::Result<()> {
        info!(binds = self.binds.len(), "Starting HTTP exposure layer");

        // Load WASM modules if configured
        if !self.module_configs.is_empty() {
            let runtime = ModuleRuntime::new().map_err(|e| {
                anyhow::anyhow!(
                    "failed to create module runtime with modules configured: {}",
                    e
                )
            })?;
            runtime
                .load_modules(&self.module_configs)
                .await
                .map_err(|e| anyhow::anyhow!("failed to load configured modules: {}", e))?;
            let names = runtime.module_names().await;
            if !names.is_empty() {
                info!(modules = ?names, "Loaded WASM modules");
            }
            *self.module_runtime.write().await = Some(runtime);
        }

        let graceful = rama::graceful::Shutdown::default();
        let module_runtime = self.module_runtime.clone();

        // Log static dirs and compression config
        for static_cfg in &self.static_dirs {
            info!(
                path = %static_cfg.path,
                prefix = %static_cfg.prefix,
                bind = ?static_cfg.bind,
                "Static file serving enabled"
            );
        }
        if self.compression {
            info!("Response compression enabled");
        }

        // Start a listener for each bind
        let bay_connectors = self.bay_connectors.clone();
        let metrics_registry = super::sensors::global_metrics_registry();
        let cors_cache = self.cors_cache.clone();
        let rate_limiter = self.rate_limiter.clone();

        for (bind_name, bind_addr) in &self.binds {
            let (addr, use_proxy_protocol) = match bind_addr {
                Bind::Tcp {
                    host,
                    port,
                    proxy_protocol,
                } => (format!("{}:{}", host, port), *proxy_protocol),
                Bind::Unix { path } => {
                    warn!(bind = %bind_name, path = %path, "Unix sockets not yet supported");
                    continue;
                }
            };

            let routes = self.routes.get(bind_name).cloned().unwrap_or_default();
            let bind_name_clone = bind_name.clone();
            let module_runtime = module_runtime.clone();
            let bay_connectors = bay_connectors.clone();
            let metrics_registry = metrics_registry.clone();
            let cors_cache = cors_cache.clone();
            let rate_limiter_clone = rate_limiter.clone();

            // Filter static dirs that should be served on this bind
            let static_configs: Vec<StaticDirConfig> = self
                .static_dirs
                .iter()
                .filter(|cfg| cfg.bind.as_ref().is_none_or(|b| b == bind_name))
                .cloned()
                .collect();
            let compression_enabled = self.compression;
            let proxy_protocol_enabled = use_proxy_protocol;

            info!(bind = %bind_name, addr = %addr, routes = routes.routes.len(), proxy_protocol = proxy_protocol_enabled, "Starting listener");

            graceful.spawn_task_fn(async move |guard| {
                let bind_name = bind_name_clone;
                let tcp_listener = match TcpListener::build().bind(&addr).await {
                    Ok(l) => {
                        info!(bind = %bind_name, addr = %addr, "Listener bound successfully");
                        l
                    }
                    Err(e) => {
                        error!(bind = %bind_name, addr = %addr, error = %e, "Failed to bind - check permissions for port < 1024");
                        return;
                    }
                };

                let exec = Executor::graceful(guard.clone());
                let ctx = RequestContext {
                    bind_name: bind_name.clone(),
                    routes: Arc::new(routes),
                    module_runtime: module_runtime.clone(),
                    static_configs: Arc::new(static_configs),
                    bay_connectors: bay_connectors.clone(),
                    metrics_registry: metrics_registry.clone(),
                    cors_cache: cors_cache.clone(),
                    rate_limiter: rate_limiter_clone,
                };

                // Build the core service
                let core_service = service_fn(move |req: Request| {
                    let ctx = ctx.clone();
                    async move { handle_request(req, &ctx).await }
                });

                info!(bind = %bind_name, addr = %addr, "Serving HTTP requests");

                // Apply layers and serve: UA classifier + trace + optional compression + optional proxy protocol
                if compression_enabled {
                    let http_service = HttpServer::auto(exec).service(
                        (
                            UserAgentClassifierLayer::new(),
                            TraceLayer::new_for_http(),
                            CompressionLayer::new(),
                        ).into_layer(core_service),
                    );
                    let body_limited = BodyLimitLayer::symmetric(10 * 1024 * 1024).into_layer(http_service);

                    if proxy_protocol_enabled {
                        // Apply HAProxy PROXY protocol layer with peek mode (auto-detect)
                        tcp_listener
                            .serve_graceful(
                                guard,
                                HaProxyLayer::new().with_peek(true).into_layer(body_limited),
                            )
                            .await;
                    } else {
                        tcp_listener
                            .serve_graceful(guard, body_limited)
                            .await;
                    }
                } else {
                    let http_service = HttpServer::auto(exec).service(
                        (
                            UserAgentClassifierLayer::new(),
                            TraceLayer::new_for_http(),
                        ).into_layer(core_service),
                    );
                    let body_limited = BodyLimitLayer::symmetric(10 * 1024 * 1024).into_layer(http_service);

                    if proxy_protocol_enabled {
                        // Apply HAProxy PROXY protocol layer with peek mode (auto-detect)
                        tcp_listener
                            .serve_graceful(
                                guard,
                                HaProxyLayer::new().with_peek(true).into_layer(body_limited),
                            )
                            .await;
                    } else {
                        tcp_listener
                            .serve_graceful(guard, body_limited)
                            .await;
                    }
                }

                info!(bind = %bind_name, "Listener stopped");
            });
        }

        // Wait for shutdown - either from our channel or from SIGINT (handled by graceful)
        let mut shutdown = shutdown;
        let guard = graceful.guard();
        tokio::select! {
            // Our external shutdown signal
            _ = async {
                loop {
                    shutdown.changed().await.ok();
                    if *shutdown.borrow() {
                        break;
                    }
                }
            } => {
                info!("Received external shutdown signal");
            }
            // Rama's graceful shutdown (SIGINT)
            _ = guard.cancelled() => {
                info!("Received SIGINT");
            }
        }
        drop(guard);

        // Now trigger graceful shutdown with timeout
        if let Err(e) = graceful.shutdown_with_limit(Duration::from_secs(30)).await {
            warn!(error = %e, "Graceful shutdown timed out");
        }

        info!("HTTP exposure layer stopped");
        Ok(())
    }
}

/// Shared context passed to request handlers
#[derive(Clone)]
struct RequestContext {
    bind_name: String,
    routes: Arc<BindRoutes>,
    module_runtime: Arc<RwLock<Option<ModuleRuntime>>>,
    static_configs: Arc<Vec<StaticDirConfig>>,
    bay_connectors: Arc<RwLock<HashMap<String, Arc<DockingConnector>>>>,
    metrics_registry: Option<Arc<MetricsRegistry>>,
    cors_cache: Option<Arc<CorsCache>>,
    rate_limiter: Option<Arc<RateLimiter>>,
}

/// Main request handler - static files first (with fallthrough), then reverse proxy
async fn handle_request(req: Request, ctx: &RequestContext) -> Result<Response, Infallible> {
    use rama::http::Method;
    let rate_limiter = &ctx.rate_limiter;
    let static_configs = &ctx.static_configs;

    // Check rate limits BEFORE any processing (if enabled)
    if let Some(limiter) = &rate_limiter {
        let client_ip = req
            .extensions()
            .get::<SocketInfo>()
            .map(|s| s.peer_addr().ip().to_string())
            .unwrap_or_else(|| "unknown".to_string());

        if let Err(retry_after) = limiter.check_request(&client_ip).await {
            let retry_after_secs = retry_after.ceil() as u64;
            warn!(
                client_ip = %client_ip,
                retry_after = retry_after_secs,
                "Rate limit exceeded, returning 429"
            );

            return Ok(Response::builder()
                .status(StatusCode::TOO_MANY_REQUESTS)
                .header("Retry-After", retry_after_secs.to_string())
                .header("X-RateLimit-Limit", "1000") // Global limit displayed
                .header("X-RateLimit-Remaining", "0")
                .body(Body::from("Rate limit exceeded. Please try again later."))
                .unwrap());
        }
    }

    let path = req.uri().path().to_string();
    let method = req.method();

    // Only try static files for GET/HEAD - ServeDir returns 405 for other methods
    let try_static = matches!(method, &Method::GET | &Method::HEAD);

    // Find matching static dir (already sorted by prefix length, longest first)
    if try_static && let Some(cfg) = static_configs.iter().find(|c| path.starts_with(&c.prefix)) {
        // Strip the prefix to get the file path
        let file_path = path.strip_prefix(&cfg.prefix).unwrap_or(&path);
        let file_path = file_path.trim_start_matches('/');

        // Serve static file
        let serve_dir = ServeDir::new(&cfg.path);

        // Build a new request with the stripped path
        let (parts, body) = req.into_parts();
        let mut static_parts = parts.clone();
        let new_path = format!("/{}", file_path);
        if let Ok(uri) = new_path.parse::<Uri>() {
            static_parts.uri = uri;
        }
        let static_req = Request::from_parts(static_parts, Body::empty());

        match serve_dir.serve(static_req).await {
            Ok(resp) => {
                if resp.status() != StatusCode::NOT_FOUND {
                    debug!(path = %path, "Served static file");
                    return Ok(resp);
                }
                // File not found - fall through to routes
                debug!(path = %path, "Static file not found, falling through to routes");
            }
            Err(e) => {
                warn!(path = %path, error = %e, "Static file error, falling through to routes");
            }
        }

        // Reconstruct request for reverse proxy
        let req = Request::from_parts(parts, body);
        return reverse_proxy(req, ctx).await;
    }

    // No matching static dir, use reverse proxy
    reverse_proxy(req, ctx).await
}

/// Reverse proxy handler
async fn reverse_proxy(mut req: Request, ctx: &RequestContext) -> Result<Response, Infallible> {
    use rama::http::Method;

    let bind_name = &ctx.bind_name;
    let routes = &*ctx.routes;
    let module_runtime = &ctx.module_runtime;
    let bay_connectors = &ctx.bay_connectors;
    let metrics_registry = &ctx.metrics_registry;
    let cors_cache = &ctx.cors_cache;

    let mut path = req.uri().path().to_string();
    let method = req.method().to_string();
    let query = req.uri().query().map(|s| s.to_string());
    let is_options = req.method() == Method::OPTIONS;

    // Extract UA info for logging (set by UserAgentClassifierLayer)
    let ua_info = req.extensions().get::<UserAgent>().map(|ua| {
        let kind = ua.info().map(|i| i.kind.to_string()).unwrap_or_default();
        let platform = ua.platform().map(|p| p.to_string()).unwrap_or_default();
        (kind, platform)
    });

    // Shields: compute Ja4H fingerprint for bot detection
    let shields = Ja4H::compute(&req).ok().map(|fp| format!("{fp}"));

    if let Some((kind, platform)) = &ua_info {
        debug!(
            method = %method,
            path = %path,
            ua_kind = %kind,
            ua_platform = %platform,
            shields = ?shields,
            "Request"
        );
    }

    // CORS cache check - return cached response for OPTIONS requests
    let cors_cache_key = if is_options {
        if let Some(cache) = cors_cache {
            if let Some(key) = CorsCacheKey::from_request(&path, bind_name, req.headers()) {
                if let Some(cached) = cache.get(&key) {
                    return Ok(cached);
                }
                Some(key)
            } else {
                None
            }
        } else {
            None
        }
    } else {
        None
    };

    // Extract headers for module processing
    let headers: std::collections::HashMap<String, String> = req
        .headers()
        .iter()
        .map(|(k, v)| (k.to_string(), v.to_str().unwrap_or("").to_string()))
        .collect();

    // Process request through WASM modules
    let request_info = RequestInfo {
        method: method.clone(),
        path: path.clone(),
        query: query.clone(),
        headers: headers.clone(),
    };

    let modules = module_runtime.read().await;
    if let Some(ref runtime) = *modules {
        match runtime.process_request(&path, &request_info).await {
            ModuleAction::Block {
                status,
                body,
                headers,
            } => {
                return Ok(build_block_response(status, body, headers));
            }
            ModuleAction::Modify {
                path: new_path,
                headers: new_headers,
            } => {
                let has_mods = new_path.is_some() || new_headers.is_some();
                if has_mods {
                    info!(new_path = ?new_path, "Module modified request");
                }

                if let Some(new_path) = new_path {
                    let (path_part, query_part) = match new_path.split_once('?') {
                        Some((p, q)) => (p, Some(q)),
                        None => (new_path.as_str(), None),
                    };

                    let normalized_path = if path_part.starts_with('/') {
                        path_part.to_string()
                    } else {
                        format!("/{}", path_part)
                    };

                    let path_and_query = match query_part {
                        Some(q) => format!("{}?{}", normalized_path, q),
                        None => normalized_path,
                    };

                    match path_and_query.parse::<rama::http::uri::PathAndQuery>() {
                        Ok(pq) => {
                            let mut parts = req.uri().clone().into_parts();
                            parts.path_and_query = Some(pq);
                            match Uri::from_parts(parts) {
                                Ok(uri) => {
                                    *req.uri_mut() = uri;
                                }
                                Err(e) => {
                                    warn!(error = %e, path = %path_and_query, "Invalid module-modified URI");
                                }
                            }
                        }
                        Err(e) => {
                            warn!(error = %e, path = %path_and_query, "Invalid module-modified path");
                        }
                    }
                }

                if let Some(headers_map) = new_headers {
                    for (key, value) in headers_map {
                        match (key.parse::<HeaderName>(), value.parse::<HeaderValue>()) {
                            (Ok(name), Ok(val)) => {
                                req.headers_mut().insert(name, val);
                            }
                            (Err(e), _) => {
                                warn!(error = %e, header = %key, "Invalid module-modified header name");
                            }
                            (_, Err(e)) => {
                                warn!(error = %e, header = %key, "Invalid module-modified header value");
                            }
                        }
                    }
                }
            }
            ModuleAction::Continue => {}
        }
    }
    drop(modules);

    // Refresh path after any module modifications
    path = req.uri().path().to_string();

    // Get User-Agent info for route matching
    let ua_header = req
        .headers()
        .get("user-agent")
        .and_then(|v| v.to_str().ok())
        .unwrap_or("");
    let ua_kind = req
        .extensions()
        .get::<UserAgent>()
        .and_then(|ua| ua.info().map(|i| i.kind.to_string()));

    // Find matching route (path pattern + optional UA filter)
    let route = routes.routes.iter().find(|r| {
        if !r.pattern.is_match(&path) {
            return false;
        }
        // If route has a UA filter, check it
        if let Some(ref filter) = r.ua_filter {
            filter.matches(ua_header, ua_kind.as_deref())
        } else {
            true
        }
    });

    let route = match route {
        Some(r) => r,
        None => {
            return Ok(Response::builder()
                .status(StatusCode::NOT_FOUND)
                .body(Body::from("No route matched"))
                .unwrap());
        }
    };

    let backend = &route.backend;
    let ship_name = &route.ship_name;
    let route_key = route.route_key.clone();
    let circuit_breaker = &route.circuit_breaker;
    let strip_prefix = &route.strip_prefix;

    // Check for WebSocket upgrade request using Rama's WebSocketMatcher
    if WebSocketMatcher::new().matches(None, &req) {
        debug!(ship = %ship_name, path = %path, backend = %backend, "WebSocket upgrade request detected");

        // For docked backends, use docking protocol
        let resp = if let BackendTarget::Docked { bay_name } = backend {
            proxy_websocket_docked(
                req,
                bay_name,
                ship_name,
                circuit_breaker,
                bay_connectors.clone(),
                strip_prefix,
            )
            .await
        } else {
            proxy_websocket(req, backend, ship_name, circuit_breaker, strip_prefix).await
        };

        if let Some(registry) = metrics_registry {
            registry.record_websocket(&route_key, ship_name);
        }

        return resp;
    }

    let start = std::time::Instant::now();
    let record_metrics = |elapsed: std::time::Duration| {
        if let Some(registry) = metrics_registry {
            registry.record_request(&route_key, ship_name, elapsed.as_millis() as u64);
        }
    };
    let respond = |status: StatusCode, body: &'static str| -> Result<Response, Infallible> {
        record_metrics(start.elapsed());
        Ok(Response::builder()
            .status(status)
            .body(Body::from(body))
            .unwrap())
    };

    // Docked backends only support WebSocket
    if matches!(backend, BackendTarget::Docked { .. }) {
        return respond(
            StatusCode::NOT_FOUND,
            "Docked backends only support WebSocket connections",
        );
    }

    // Check circuit breaker state
    {
        let breaker = circuit_breaker.lock().await;
        if breaker.is_open() {
            warn!(ship = %ship_name, backend = %backend, "Circuit breaker open, rejecting request");
            return respond(
                StatusCode::SERVICE_UNAVAILABLE,
                "Service temporarily unavailable",
            );
        }
    }

    debug!(ship = %ship_name, path = %path, backend = %backend, "Routing request");

    // Build path with query string, applying strip_prefix if configured
    let uri = req.uri();
    let original_path = uri.path();
    let stripped_path = match strip_prefix {
        Some(prefix) => original_path
            .strip_prefix(prefix.as_str())
            .unwrap_or(original_path),
        None => original_path,
    };
    // Ensure path starts with /
    let final_path = if stripped_path.is_empty() || !stripped_path.starts_with('/') {
        format!("/{}", stripped_path.trim_start_matches('/'))
    } else {
        stripped_path.to_string()
    };
    let path_and_query = format!(
        "{}{}",
        final_path,
        uri.query().map(|q| format!("?{}", q)).unwrap_or_default()
    );

    let timeout = Duration::from_secs(30);

    // Extract client info for proxy headers before consuming request
    let client_ip = req
        .extensions()
        .get::<SocketInfo>()
        .map(|s: &SocketInfo| s.peer_addr().ip().to_string());
    let original_host = req
        .headers()
        .get(HOST)
        .and_then(|v| v.to_str().ok())
        .map(|s| s.to_string());

    // Forward to backend based on backend type
    let resp = match backend {
        BackendTarget::Tcp { base_uri } => {
            // TCP: Rewrite URI and use EasyHttpWebClient
            let new_uri = format!("{}{}", base_uri, path_and_query);
            let new_uri: Uri = match new_uri.parse() {
                Ok(u) => u,
                Err(e) => {
                    error!(error = %e, uri = %new_uri, "Failed to parse backend URI");
                    return respond(StatusCode::INTERNAL_SERVER_ERROR, "Invalid backend URI");
                }
            };

            let (mut parts, body) = req.into_parts();
            parts.uri = new_uri;

            // Add proxy headers
            if let Some(ref ip) = client_ip
                && let Ok(val) = ip.parse::<rama::http::HeaderValue>()
            {
                parts.headers.insert("x-forwarded-for", val);
                if let Ok(val2) = ip.parse::<rama::http::HeaderValue>() {
                    parts.headers.insert("x-real-ip", val2);
                }
            }
            if let Some(ref host) = original_host
                && let Ok(val) = host.parse::<rama::http::HeaderValue>()
            {
                parts.headers.insert("x-forwarded-host", val);
            }
            if let Ok(proto) = "http".parse::<rama::http::HeaderValue>() {
                parts.headers.insert("x-forwarded-proto", proto);
            }

            let req = Request::from_parts(parts, body);

            let client = EasyHttpWebClient::default();
            match tokio::time::timeout(timeout, client.serve(req)).await {
                Ok(Ok(resp)) => {
                    let duration_ms = start.elapsed().as_secs_f64() * 1000.0;
                    let breaker = circuit_breaker.lock().await;
                    breaker.record_success(duration_ms);
                    resp
                }
                Ok(Err(e)) => {
                    let duration_ms = start.elapsed().as_secs_f64() * 1000.0;
                    let breaker = circuit_breaker.lock().await;
                    breaker.record_failure(duration_ms);
                    drop(breaker);
                    error!(error = %e, backend = %backend, "Backend request failed");
                    return respond(StatusCode::BAD_GATEWAY, "Backend unavailable");
                }
                Err(_) => {
                    let breaker = circuit_breaker.lock().await;
                    breaker.record_failure(30_000.0);
                    drop(breaker);
                    error!(backend = %backend, timeout_secs = 30, "Backend request timed out");
                    return respond(StatusCode::GATEWAY_TIMEOUT, "Backend timeout");
                }
            }
        }
        BackendTarget::Unix { socket_path } => {
            // Unix socket: Use HttpConnector with UnixConnector
            // URI uses http://localhost (host is ignored for Unix sockets)
            let new_uri: Uri = match format!("http://localhost{}", path_and_query).parse() {
                Ok(u) => u,
                Err(e) => {
                    error!(error = %e, "Failed to parse Unix socket URI");
                    return respond(StatusCode::INTERNAL_SERVER_ERROR, "Invalid URI");
                }
            };

            let (mut parts, body) = req.into_parts();
            parts.uri = new_uri;

            // Add proxy headers
            if let Some(ref ip) = client_ip
                && let Ok(val) = ip.parse::<rama::http::HeaderValue>()
            {
                parts.headers.insert("x-forwarded-for", val);
                if let Ok(val2) = ip.parse::<rama::http::HeaderValue>() {
                    parts.headers.insert("x-real-ip", val2);
                }
            }
            if let Some(ref host) = original_host
                && let Ok(val) = host.parse::<rama::http::HeaderValue>()
            {
                parts.headers.insert("x-forwarded-host", val);
            }
            if let Ok(proto) = "http".parse::<rama::http::HeaderValue>() {
                parts.headers.insert("x-forwarded-proto", proto);
            }

            let request = Request::from_parts(parts, body);

            // Connect via Unix socket
            let connector = HttpConnector::new(UnixConnector::fixed(socket_path));
            let connect_result = tokio::time::timeout(timeout, connector.connect(request)).await;

            match connect_result {
                Ok(Ok(EstablishedClientConnection { conn, input, .. })) => {
                    // Send request through connection
                    match tokio::time::timeout(timeout, conn.serve(input)).await {
                        Ok(Ok(resp)) => {
                            let duration_ms = start.elapsed().as_secs_f64() * 1000.0;
                            let breaker = circuit_breaker.lock().await;
                            breaker.record_success(duration_ms);
                            resp
                        }
                        Ok(Err(e)) => {
                            let duration_ms = start.elapsed().as_secs_f64() * 1000.0;
                            let breaker = circuit_breaker.lock().await;
                            breaker.record_failure(duration_ms);
                            drop(breaker);
                            error!(error = %e, backend = %backend, "Unix socket request failed");
                            return respond(StatusCode::BAD_GATEWAY, "Backend unavailable");
                        }
                        Err(_) => {
                            let breaker = circuit_breaker.lock().await;
                            breaker.record_failure(30_000.0);
                            drop(breaker);
                            error!(backend = %backend, timeout_secs = 30, "Unix socket request timed out");
                            return respond(StatusCode::GATEWAY_TIMEOUT, "Backend timeout");
                        }
                    }
                }
                Ok(Err(e)) => {
                    let duration_ms = start.elapsed().as_secs_f64() * 1000.0;
                    let breaker = circuit_breaker.lock().await;
                    breaker.record_failure(duration_ms);
                    drop(breaker);
                    error!(error = %e, backend = %backend, "Failed to connect to Unix socket");
                    return respond(StatusCode::BAD_GATEWAY, "Backend unavailable");
                }
                Err(_) => {
                    let breaker = circuit_breaker.lock().await;
                    breaker.record_failure(30_000.0);
                    drop(breaker);
                    error!(backend = %backend, timeout_secs = 30, "Unix socket connect timed out");
                    return respond(StatusCode::GATEWAY_TIMEOUT, "Backend timeout");
                }
            }
        }
        BackendTarget::Docked { bay_name } => {
            // Docked bays only support WebSocket connections, not regular HTTP
            error!(bay = %bay_name, path = %path_and_query, "HTTP request to docked bay - only WebSocket is supported");
            return respond(
                StatusCode::NOT_IMPLEMENTED,
                "This endpoint only supports WebSocket connections",
            );
        }
    };

    // Process response through WASM modules
    let response_headers: std::collections::HashMap<String, String> = resp
        .headers()
        .iter()
        .map(|(k, v)| (k.to_string(), v.to_str().unwrap_or("").to_string()))
        .collect();

    let response_info = ResponseInfo {
        status: resp.status().as_u16(),
        headers: response_headers,
    };

    let modules = module_runtime.read().await;
    let resp = if let Some(ref runtime) = *modules {
        match runtime.process_response(&path, &response_info).await {
            ModuleAction::Block {
                status,
                body,
                headers,
            } => {
                record_metrics(start.elapsed());
                return Ok(build_block_response(status, body, headers));
            }
            ModuleAction::Modify {
                headers: new_headers,
                ..
            } => {
                if let Some(headers_map) = new_headers {
                    // Rebuild response with modified headers
                    let (mut parts, body) = resp.into_parts();
                    for (key, value) in headers_map {
                        if let (Ok(name), Ok(val)) = (key.parse::<HeaderName>(), value.parse()) {
                            parts.headers.insert(name, val);
                        }
                    }
                    Response::from_parts(parts, body)
                } else {
                    resp
                }
            }
            ModuleAction::Continue => resp,
        }
    } else {
        resp
    };

    // Cache successful OPTIONS response for CORS preflight
    if let Some(key) = cors_cache_key
        && resp.status().is_success()
        && let Some(cache) = cors_cache
    {
        cache.insert(key, &resp);
    }

    record_metrics(start.elapsed());
    Ok(resp)
}

/// WebSocket proxy handler
///
/// Proxies WebSocket upgrade requests to the backend and tunnels
/// bidirectional WebSocket frames between client and backend.
async fn proxy_websocket(
    req: Request,
    backend: &BackendTarget,
    ship_name: &str,
    circuit_breaker: &Arc<Mutex<CircuitBreaker>>,
    strip_prefix: &Option<String>,
) -> Result<Response, Infallible> {
    let path = req.uri().path().to_string();

    // Clone request parts for the upgrade task
    let (parts, body) = req.into_parts();
    let parts_clone = parts.clone();
    let mut req = Request::from_parts(parts, body);

    // Get executor from request extensions for spawning the relay task
    let executor = req
        .extensions()
        .get::<Executor>()
        .cloned()
        .unwrap_or_default();

    // Initiate WebSocket handshake based on backend type
    let egress_socket = match backend {
        BackendTarget::Tcp { base_uri } => {
            // Build backend URI, applying strip_prefix if configured
            let original_path = req.uri().path();
            let stripped_path = match strip_prefix {
                Some(prefix) => original_path
                    .strip_prefix(prefix.as_str())
                    .unwrap_or(original_path),
                None => original_path,
            };
            let final_path = if stripped_path.is_empty() || !stripped_path.starts_with('/') {
                format!("/{}", stripped_path.trim_start_matches('/'))
            } else {
                stripped_path.to_string()
            };
            let path_and_query = format!(
                "{}{}",
                final_path,
                req.uri()
                    .query()
                    .map(|q| format!("?{}", q))
                    .unwrap_or_default()
            );
            let backend_uri: Uri = match format!("{}{}", base_uri, path_and_query).parse() {
                Ok(uri) => uri,
                Err(e) => {
                    error!(error = %e, "Failed to parse WebSocket backend URI");
                    return Ok(Response::builder()
                        .status(StatusCode::INTERNAL_SERVER_ERROR)
                        .body(Body::from("Invalid backend URI"))
                        .unwrap());
                }
            };

            // Update request URI to point to backend
            *req.uri_mut() = backend_uri;

            // Initiate WebSocket handshake with TCP backend
            let client = EasyHttpWebClient::default();
            let handshake = match client
                .websocket_with_request(req)
                .initiate_handshake(rama::extensions::Extensions::default())
                .await
            {
                Ok(hs) => hs,
                Err(e) => {
                    error!(
                        ship = %ship_name,
                        path = %path,
                        error = %e,
                        "Failed to initiate WebSocket handshake with TCP backend"
                    );
                    let breaker = circuit_breaker.lock().await;
                    breaker.record_failure(0.0);
                    return Ok(Response::builder()
                        .status(StatusCode::BAD_GATEWAY)
                        .body(Body::from("Backend WebSocket handshake failed"))
                        .unwrap());
                }
            };

            // Complete the handshake
            match handshake.complete().await {
                Ok(socket) => socket,
                Err(e) => {
                    error!(
                        ship = %ship_name,
                        path = %path,
                        error = %e,
                        "Failed to complete WebSocket handshake with TCP backend"
                    );
                    let breaker = circuit_breaker.lock().await;
                    breaker.record_failure(0.0);
                    return Ok(Response::builder()
                        .status(StatusCode::BAD_GATEWAY)
                        .body(Body::from("Backend WebSocket connection failed"))
                        .unwrap());
                }
            }
        }
        BackendTarget::Unix { socket_path } => {
            // Build path for Unix socket (host is ignored)
            let original_path = req.uri().path();
            let stripped_path = match strip_prefix {
                Some(prefix) => original_path
                    .strip_prefix(prefix.as_str())
                    .unwrap_or(original_path),
                None => original_path,
            };
            let final_path = if stripped_path.is_empty() || !stripped_path.starts_with('/') {
                format!("/{}", stripped_path.trim_start_matches('/'))
            } else {
                stripped_path.to_string()
            };
            let path_and_query = format!(
                "{}{}",
                final_path,
                req.uri()
                    .query()
                    .map(|q| format!("?{}", q))
                    .unwrap_or_default()
            );

            // Update request URI (host doesn't matter for Unix sockets)
            let backend_uri: Uri = match format!("http://localhost{}", path_and_query).parse() {
                Ok(uri) => uri,
                Err(e) => {
                    error!(error = %e, "Failed to parse Unix WebSocket URI");
                    return Ok(Response::builder()
                        .status(StatusCode::INTERNAL_SERVER_ERROR)
                        .body(Body::from("Invalid backend URI"))
                        .unwrap());
                }
            };
            *req.uri_mut() = backend_uri;

            // Connect via Unix socket to get HttpClientService
            let connector = HttpConnector::new(UnixConnector::fixed(socket_path));
            let EstablishedClientConnection { conn: client, .. } = match connector.serve(req).await
            {
                Ok(established) => established,
                Err(e) => {
                    error!(
                        ship = %ship_name,
                        path = %path,
                        socket = %socket_path,
                        error = %e,
                        "Failed to connect to Unix socket for WebSocket"
                    );
                    let breaker = circuit_breaker.lock().await;
                    breaker.record_failure(0.0);
                    return Ok(Response::builder()
                        .status(StatusCode::BAD_GATEWAY)
                        .body(Body::from("Backend connection failed"))
                        .unwrap());
                }
            };

            // Build a new WebSocket request for the handshake
            let ws_req = Request::builder()
                .uri(format!("http://localhost{}", path_and_query))
                .body(Body::empty())
                .unwrap();

            // Initiate WebSocket handshake over Unix socket connection
            let handshake = match client
                .websocket_with_request(ws_req)
                .initiate_handshake(rama::extensions::Extensions::default())
                .await
            {
                Ok(hs) => hs,
                Err(e) => {
                    error!(
                        ship = %ship_name,
                        path = %path,
                        socket = %socket_path,
                        error = %e,
                        "Failed to initiate WebSocket handshake with Unix backend"
                    );
                    let breaker = circuit_breaker.lock().await;
                    breaker.record_failure(0.0);
                    return Ok(Response::builder()
                        .status(StatusCode::BAD_GATEWAY)
                        .body(Body::from("Backend WebSocket handshake failed"))
                        .unwrap());
                }
            };

            // Complete the handshake
            match handshake.complete().await {
                Ok(socket) => socket,
                Err(e) => {
                    error!(
                        ship = %ship_name,
                        path = %path,
                        socket = %socket_path,
                        error = %e,
                        "Failed to complete WebSocket handshake with Unix backend"
                    );
                    let breaker = circuit_breaker.lock().await;
                    breaker.record_failure(0.0);
                    return Ok(Response::builder()
                        .status(StatusCode::BAD_GATEWAY)
                        .body(Body::from("Backend WebSocket connection failed"))
                        .unwrap());
                }
            }
        }
        BackendTarget::Docked { .. } => {
            // This case should not happen - docked backends go through proxy_websocket_docked
            error!(ship = %ship_name, path = %path, "Unexpected Docked backend in proxy_websocket");
            return Ok(Response::builder()
                .status(StatusCode::INTERNAL_SERVER_ERROR)
                .body(Body::from("Internal routing error"))
                .unwrap());
        }
    };

    // Record success for circuit breaker
    {
        let breaker = circuit_breaker.lock().await;
        breaker.record_success(0.0);
    }

    // Extract the socket and response parts
    let (egress_socket, response_parts, _) = egress_socket.into_parts();

    // Build the response to send back to client (101 Switching Protocols)
    let response = Response::from_parts(response_parts, Body::empty());

    // Spawn task to handle the WebSocket relay after upgrade completes
    let ship_name_clone = ship_name.to_string();
    let path_clone = path.clone();

    executor.spawn_task(async move {
        let ship_name = ship_name_clone;
        debug!(
            ship = %ship_name,
            path = %path_clone,
            "WebSocket backend connected, waiting for client upgrade"
        );

        // Wait for the client-side upgrade to complete
        let request = Request::from_parts(parts_clone, Body::empty());
        let ingress_socket = match upgrade::handle_upgrade(&request).await {
            Ok(upgraded) => AsyncWebSocket::from_raw_socket(upgraded, Role::Server, None).await,
            Err(e) => {
                error!(
                    ship = %ship_name,
                    path = %path_clone,
                    error = %e,
                    "Failed to upgrade client WebSocket connection"
                );
                return;
            }
        };

        debug!(
            ship = %ship_name,
            path = %path_clone,
            "WebSocket relay started between client and backend"
        );

        // Relay WebSocket frames between client and backend
        relay_websockets(ingress_socket, egress_socket, &ship_name, &path_clone).await;

        debug!(
            ship = %ship_name,
            path = %path_clone,
            "WebSocket connection closed"
        );
    });

    info!(ship = %ship_name, path = %path, "WebSocket upgrade initiated");
    Ok(response)
}

/// Relay WebSocket frames between client (ingress) and backend (egress)
async fn relay_websockets(
    mut ingress: AsyncWebSocket,
    mut egress: AsyncWebSocket,
    ship_name: &str,
    path: &str,
) {
    use rama::futures::SinkExt;

    loop {
        tokio::select! {
            // Client -> Backend
            result = ingress.recv_message() => {
                match result {
                    Ok(msg) => {
                        if let Err(e) = egress.send(msg).await {
                            if e.is_connection_error() {
                                debug!(ship = %ship_name, path = %path, "Backend disconnected");
                                return;
                            }
                            error!(ship = %ship_name, path = %path, error = %e, "Failed to send to backend");
                        }
                    }
                    Err(e) => {
                        if e.is_connection_error() || matches!(e, rama::http::ws::ProtocolError::ResetWithoutClosingHandshake) {
                            debug!(ship = %ship_name, path = %path, "Client disconnected");
                        } else {
                            error!(ship = %ship_name, path = %path, error = %e, "Client WebSocket error");
                        }
                        return;
                    }
                }
            }
            // Backend -> Client
            result = egress.recv_message() => {
                match result {
                    Ok(msg) => {
                        if let Err(e) = ingress.send(msg).await {
                            if e.is_connection_error() {
                                debug!(ship = %ship_name, path = %path, "Client disconnected");
                                return;
                            }
                            error!(ship = %ship_name, path = %path, error = %e, "Failed to send to client");
                        }
                    }
                    Err(e) => {
                        if e.is_connection_error() || matches!(e, rama::http::ws::ProtocolError::ResetWithoutClosingHandshake) {
                            debug!(ship = %ship_name, path = %path, "Backend disconnected");
                        } else {
                            error!(ship = %ship_name, path = %path, error = %e, "Backend WebSocket error");
                        }
                        return;
                    }
                }
            }
        }
    }
}

/// WebSocket proxy handler for docked bays using docking protocol
async fn proxy_websocket_docked(
    req: Request,
    bay_name: &str,
    ship_name: &str,
    circuit_breaker: &Arc<Mutex<CircuitBreaker>>,
    bay_connectors: Arc<RwLock<HashMap<String, Arc<DockingConnector>>>>,
    strip_prefix: &Option<String>,
) -> Result<Response, Infallible> {
    let path = req.uri().path().to_string();

    // Get the docking connector for this bay
    let connector = {
        let connectors = bay_connectors.read().await;
        connectors.get(bay_name).cloned()
    };

    let connector = match connector {
        Some(c) => c,
        None => {
            error!(bay = %bay_name, "Bay connector not found");
            let breaker = circuit_breaker.lock().await;
            breaker.record_failure(0.0);
            return Ok(Response::builder()
                .status(StatusCode::SERVICE_UNAVAILABLE)
                .body(Body::from("Bay not docked"))
                .unwrap());
        }
    };

    // Generate a new connection ID
    let conn_id = next_conn_id();

    // Register the connection to receive cargo from the bay
    let mut cargo_rx = connector.register_connection(conn_id).await;

    // Apply strip_prefix if configured
    let original_path = req.uri().path();
    let stripped_path = match strip_prefix {
        Some(prefix) => original_path
            .strip_prefix(prefix.as_str())
            .unwrap_or(original_path),
        None => original_path,
    };
    let final_path = if stripped_path.is_empty() || !stripped_path.starts_with('/') {
        format!("/{}", stripped_path.trim_start_matches('/'))
    } else {
        stripped_path.to_string()
    };
    // Include query string for the bay
    let path_with_query = format!(
        "{}{}",
        final_path,
        req.uri()
            .query()
            .map(|q| format!("?{}", q))
            .unwrap_or_default()
    );

    // Extract client info for boarding message
    let remote_addr = req
        .extensions()
        .get::<SocketInfo>()
        .map(|s| s.peer_addr().to_string())
        .unwrap_or_else(|| "unknown".to_string());

    let headers: HashMap<String, String> = req
        .headers()
        .iter()
        .map(|(k, v)| (k.to_string(), v.to_str().unwrap_or("").to_string()))
        .collect();

    // Clone request parts for the upgrade task
    let (parts, body) = req.into_parts();
    let parts_clone = parts.clone();
    let req = Request::from_parts(parts, body);

    // Get executor from request extensions for spawning the relay task
    let executor = req
        .extensions()
        .get::<Executor>()
        .cloned()
        .unwrap_or_default();

    // Build the 101 Switching Protocols response
    // We need to manually build the response since we're not proxying to a backend WebSocket
    let response = Response::builder()
        .status(StatusCode::SWITCHING_PROTOCOLS)
        .header("Upgrade", "websocket")
        .header("Connection", "Upgrade")
        .header(
            "Sec-WebSocket-Accept",
            compute_websocket_accept_key(parts_clone.headers.get("Sec-WebSocket-Key")),
        )
        .body(Body::empty())
        .unwrap();

    // Spawn task to handle the WebSocket relay
    let bay_name_clone = bay_name.to_string();
    let ship_name_clone = ship_name.to_string();
    let path_clone = path_with_query.clone();
    let connector_clone = connector.clone();
    let circuit_breaker_clone = circuit_breaker.clone();

    executor.spawn_task(async move {
        let bay_name = bay_name_clone;
        let ship_name = ship_name_clone;
        let connector = connector_clone;
        let circuit_breaker = circuit_breaker_clone;

        debug!(
            bay = %bay_name,
            conn_id = conn_id,
            path = %path_clone,
            "Waiting for client WebSocket upgrade"
        );

        // Wait for the client-side upgrade to complete
        let request = Request::from_parts(parts_clone, Body::empty());
        let ingress_socket = match upgrade::handle_upgrade(&request).await {
            Ok(upgraded) => AsyncWebSocket::from_raw_socket(upgraded, Role::Server, None).await,
            Err(e) => {
                error!(
                    bay = %bay_name,
                    conn_id = conn_id,
                    error = %e,
                    "Failed to upgrade client WebSocket connection"
                );
                connector.unregister_connection(conn_id).await;
                return;
            }
        };

        // Send Boarding message to the bay
        let boarding = Boarding {
            conn_id,
            path: path_clone.clone(),
            remote_addr,
            headers,
        };

        if let Err(e) = connector.send_boarding(boarding).await {
            error!(
                bay = %bay_name,
                conn_id = conn_id,
                error = %e,
                "Failed to send boarding message"
            );
            connector.unregister_connection(conn_id).await;
            return;
        }

        info!(
            bay = %bay_name,
            ship = %ship_name,
            conn_id = conn_id,
            path = %path_clone,
            "WebSocket connection boarded via docking protocol"
        );

        // Record success for circuit breaker
        {
            let breaker = circuit_breaker.lock().await;
            breaker.record_success(0.0);
        }

        // Relay messages between client and bay
        relay_websocket_docked(
            ingress_socket,
            &connector,
            conn_id,
            &mut cargo_rx,
            &bay_name,
            &path_clone,
        )
        .await;

        // Send Disembark message
        let disembark = Disembark {
            conn_id,
            code: 1000,
            reason: "normal".to_string(),
        };
        let _ = connector.send_disembark(disembark).await;

        // Unregister the connection
        connector.unregister_connection(conn_id).await;

        debug!(
            bay = %bay_name,
            conn_id = conn_id,
            path = %path_clone,
            "WebSocket connection closed"
        );
    });

    info!(bay = %bay_name, ship = %ship_name, path = %path, conn_id = conn_id, "WebSocket upgrade initiated via docking");
    Ok(response)
}

/// Compute the Sec-WebSocket-Accept key from the client's Sec-WebSocket-Key
fn compute_websocket_accept_key(key: Option<&rama::http::HeaderValue>) -> String {
    use sha1::{Digest, Sha1};

    const WEBSOCKET_GUID: &str = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";

    let key = key.and_then(|v| v.to_str().ok()).unwrap_or("");

    let mut hasher = Sha1::new();
    hasher.update(key.as_bytes());
    hasher.update(WEBSOCKET_GUID.as_bytes());
    let result = hasher.finalize();

    use base64::Engine;
    base64::engine::general_purpose::STANDARD.encode(result)
}

/// Relay WebSocket frames between client and docked bay
async fn relay_websocket_docked(
    mut ingress: AsyncWebSocket,
    connector: &Arc<DockingConnector>,
    conn_id: u32,
    cargo_rx: &mut tokio::sync::mpsc::Receiver<Vec<u8>>,
    bay_name: &str,
    path: &str,
) {
    use rama::futures::SinkExt;
    use rama::http::ws::Message;

    loop {
        tokio::select! {
            // Client -> Bay
            result = ingress.recv_message() => {
                match result {
                    Ok(msg) => {
                        // Convert WebSocket message to Cargo
                        let data = match &msg {
                            Message::Text(text) => text.as_bytes().to_vec(),
                            Message::Binary(data) => data.to_vec(),
                            Message::Ping(data) => {
                                // Respond to ping directly
                                let _ = ingress.send(Message::Pong(data.clone())).await;
                                continue;
                            }
                            Message::Pong(_) => continue,
                            Message::Close(_) => {
                                debug!(bay = %bay_name, conn_id = conn_id, "Client sent close frame");
                                return;
                            }
                            Message::Frame(_) => {
                                // Low-level frame - skip
                                continue;
                            }
                        };

                        let cargo = Cargo { conn_id, data };
                        if let Err(e) = connector.send_cargo(cargo).await {
                            error!(bay = %bay_name, conn_id = conn_id, error = %e, "Failed to send cargo to bay");
                            return;
                        }
                    }
                    Err(e) => {
                        if e.is_connection_error() || matches!(e, rama::http::ws::ProtocolError::ResetWithoutClosingHandshake) {
                            debug!(bay = %bay_name, conn_id = conn_id, path = %path, "Client disconnected");
                        } else {
                            error!(bay = %bay_name, conn_id = conn_id, path = %path, error = %e, "Client WebSocket error");
                        }
                        return;
                    }
                }
            }
            // Bay -> Client (via cargo_rx)
            result = cargo_rx.recv() => {
                match result {
                    Some(data) => {
                        // Send data to client as text (assuming JSON/text protocol)
                        // If binary is needed, the protocol should indicate it
                        let msg = if data.iter().all(|&b| b.is_ascii()) {
                            Message::Text(String::from_utf8_lossy(&data).to_string().into())
                        } else {
                            Message::Binary(data.into())
                        };

                        if let Err(e) = ingress.send(msg).await {
                            if e.is_connection_error() {
                                debug!(bay = %bay_name, conn_id = conn_id, path = %path, "Client disconnected");
                                return;
                            }
                            error!(bay = %bay_name, conn_id = conn_id, path = %path, error = %e, "Failed to send to client");
                        }
                    }
                    None => {
                        // Channel closed - bay disconnected
                        debug!(bay = %bay_name, conn_id = conn_id, path = %path, "Bay cargo channel closed");
                        return;
                    }
                }
            }
        }
    }
}