rama-ws 0.4.0

WebSocket (WS) support for rama
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
//! WebSocket client types and utilities

#![expect(
    clippy::unreachable,
    reason = "vendored from upstream `tungstenite-rs`: arms gated on caller-validated WebSocket protocol state that the type system can't enforce"
)]

use std::{
    fmt,
    future::Future,
    ops::{Deref, DerefMut},
    pin::Pin,
    sync::Arc,
    task::{Context, Poll},
};

use rama_core::Service;
use rama_core::error::{BoxError, ErrorContext, ErrorExt};
use rama_core::extensions::{Extensions, ExtensionsRef};
use rama_core::futures::{Sink, SinkExt as _, Stream, StreamExt as _};
use rama_core::rt::blocking::Io as BlockingIo;
use rama_core::telemetry::tracing;
use rama_http::conn::TargetHttpVersion;
use rama_http::headers::sec_websocket_extensions::{Extension, PerMessageDeflateConfig};
use rama_http::headers::sec_websocket_protocol::AcceptedWebSocketProtocol;
use rama_http::headers::{
    HeaderMapExt, HttpRequestBuilderExt as _, SecWebSocketExtensions, SecWebSocketKey,
    SecWebSocketProtocol,
};
use rama_http::proto::h2::ext::Protocol;
use rama_http::service::client::blocking::Client as BlockingHttpClient;
use rama_http::service::client::ext::{IntoHeaderName, IntoHeaderValue};
use rama_http::service::client::{HttpClientExt, IntoUrl, RequestBuilder};
use rama_http::{Body, Method, Request, Response, StatusCode, Version, header, headers};
use rama_http::{request, response};
use rama_net::extensions::StreamTransformed;
use rama_utils::str::NonEmptyStr;

use crate::protocol::{CloseFrame, Message, ProtocolError, Role, WebSocket, WebSocketConfig};
use crate::runtime::AsyncWebSocket;

/// Builder that can be used by clients to initiate the WebSocket handshake.
#[derive(Debug, Clone)]
pub struct WebSocketRequestBuilder<B> {
    inner: B,
    protocols: Option<SecWebSocketProtocol>,
    extensions: Option<SecWebSocketExtensions>,
    key: Option<SecWebSocketKey>,
}

#[derive(Debug)]
/// Request data to be used by an http client to initiate an http request.
pub struct HandshakeRequest {
    pub request: Request,
    pub protocols: Option<SecWebSocketProtocol>,
    pub extensions: Option<SecWebSocketExtensions>,
    pub key: Option<SecWebSocketKey>,
}

struct PreparedHandshakeRequest {
    request: Request,
    protocols: Option<SecWebSocketProtocol>,
    extensions: Option<SecWebSocketExtensions>,
    config: Option<WebSocketConfig>,
    key: Option<SecWebSocketKey>,
}

impl PreparedHandshakeRequest {
    async fn send<S, Body>(
        self,
        service: &S,
    ) -> Result<NegotiatedHandshakeRequest<Body>, HandshakeError>
    where
        S: Service<Request, Output = Response<Body>, Error: Into<BoxError>>,
    {
        let uri = self.request.uri().clone();
        let response = service.serve(self.request).await.map_err(|err| {
            let err: BoxError = err.into();
            HandshakeError::HttpRequestError(
                err.context(uri)
                    .context("send initial websocket handshake request (upgrade)"),
            )
        })?;

        Ok(NegotiatedHandshakeRequest {
            protocols: self.protocols,
            extensions: self.extensions,
            config: self.config,
            key: self.key,
            response,
        })
    }
}

/// [`WebSocketRequestBuilder`] inner wrapper type used for a builder,
/// which includes a service, and thus is there to actually send the request as well and
/// even follow up.
pub struct WithService<'a, S, Body, Mode = websocket_builder_mode::Async> {
    service: &'a S,
    builder: RequestBuilder<'a, S, Response<Body>>,
    config: Option<WebSocketConfig>,
    is_h2: bool,
    mode: Mode,
}

impl<S: fmt::Debug, Body, Mode: fmt::Debug> fmt::Debug for WithService<'_, S, Body, Mode> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("WithService")
            .field("builder", &self.builder)
            .field("config", &self.config)
            .field("is_h2", &self.is_h2)
            .field("mode", &self.mode)
            .finish()
    }
}

/// WebSocket request-builder execution modes.
pub mod websocket_builder_mode {
    use std::sync::Arc;

    use rama_core::rt::blocking::Runtime;

    /// Asynchronous terminal handshake operations.
    #[derive(Debug)]
    #[non_exhaustive]
    pub struct Async;

    /// Blocking terminal handshake operations.
    #[derive(Debug, Clone)]
    #[non_exhaustive]
    pub struct Blocking<S> {
        pub(crate) runtime: Runtime,
        pub(crate) service: Arc<S>,
    }
}

/// A WebSocket request builder whose terminal handshake operations block the
/// calling thread.
pub type BlockingWebSocketRequestBuilder<'a, S, Body> =
    WebSocketRequestBuilder<WithService<'a, S, Body, websocket_builder_mode::Blocking<S>>>;

fn new_ws_request_builder_from_uri<T>(uri: T, version: Version) -> request::Builder
where
    T: TryInto<rama_net::uri::Uri, Error: Into<rama_http::HttpError>>,
{
    let builder = Request::builder()
        .version(version)
        .uri(uri)
        .typed_header(headers::SecWebSocketVersion::V13);

    match version {
        version @ (Version::HTTP_10 | Version::HTTP_11) => builder
            .method(Method::GET)
            .version(version)
            .typed_header(headers::Upgrade::websocket())
            .typed_header(headers::Connection::upgrade()),
        Version::HTTP_2 => builder.method(Method::CONNECT).version(Version::HTTP_2),
        _ => unreachable!("bug"),
    }
}

fn new_ws_request_builder_from_uri_with_service<'a, S, Body, T>(
    service: &'a S,
    uri: T,
    version: Version,
) -> RequestBuilder<'a, S, Response<Body>>
where
    S: Service<Request, Output = Response<Body>, Error: Into<BoxError>>,
    T: IntoUrl,
{
    let builder = match version {
        version @ (Version::HTTP_10 | Version::HTTP_11) => service
            .get(uri)
            .version(version)
            .typed_header(headers::Upgrade::websocket())
            .typed_header(headers::Connection::upgrade()),
        Version::HTTP_2 => service.connect(uri).version(Version::HTTP_2),
        _ => unreachable!("bug"),
    };

    builder.typed_header(headers::SecWebSocketVersion::V13)
}

fn new_ws_request_builder_from_request<'a, S, Body, RequestBody>(
    service: &'a S,
    mut request: Request<RequestBody>,
) -> RequestBuilder<'a, S, Response<Body>>
where
    S: Service<Request, Output = Response<Body>, Error: Into<BoxError>>,
    RequestBody: Into<rama_http::Body>,
{
    if !request
        .headers()
        .contains_key(header::SEC_WEBSOCKET_VERSION)
    {
        request
            .headers_mut()
            .typed_insert(headers::SecWebSocketVersion::V13);
    }

    match request.version() {
        Version::HTTP_10 | Version::HTTP_11 => {
            if request.headers().get(header::UPGRADE).is_none() {
                request
                    .headers_mut()
                    .typed_insert(headers::Upgrade::websocket());
            }
            if request.headers().get(header::CONNECTION).is_none() {
                request
                    .headers_mut()
                    .typed_insert(headers::Connection::upgrade());
            }
        }
        // - for h2: nothing to do
        // - else: this will error downstream due to invalid version
        _ => (),
    }
    service.build_from_request(request)
}

#[derive(Debug)]
/// Client error which can be triggered in case the response validation failed
pub enum ResponseValidateError {
    UnexpectedStatusCode(StatusCode),
    UnexpectedHttpVersion(Version),
    MissingUpgradeWebSocketHeader,
    MissingConnectionUpgradeHeader,
    SecWebSocketAcceptKeyMismatch,
    ProtocolMismatch(Option<NonEmptyStr>),
    ExtensionMismatch(Option<Extension>),
}

#[derive(Debug)]
/// Client error which can be triggered in case the handshake phase failed.
pub enum HandshakeError {
    ValidationError(ResponseValidateError),
    HttpRequestError(BoxError),
    HttpUpgradeError(BoxError),
}

impl fmt::Display for ResponseValidateError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::UnexpectedStatusCode(status_code) => {
                write!(f, "unexpected HTTP status code: {status_code}")
            }
            Self::UnexpectedHttpVersion(version) => {
                write!(f, "unexpected HTTP version: {version:?}")
            }
            Self::MissingUpgradeWebSocketHeader => {
                write!(f, "missing upgrade WebSocket header")
            }
            Self::MissingConnectionUpgradeHeader => {
                write!(f, "missing connection upgrade header")
            }
            Self::SecWebSocketAcceptKeyMismatch => {
                write!(f, "key mismatch for sec-websocket-accept header")
            }
            Self::ProtocolMismatch(protocol) => {
                write!(f, "protocol mismatch: {protocol:?}")
            }
            Self::ExtensionMismatch(extension) => {
                write!(f, "extension mismatch: {extension:?}")
            }
        }
    }
}

impl std::error::Error for ResponseValidateError {}

impl fmt::Display for HandshakeError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::ValidationError(error) => {
                write!(f, "response validation failed: {error}")
            }
            Self::HttpRequestError(error) => {
                write!(f, "http request error: {error}")
            }
            Self::HttpUpgradeError(error) => {
                write!(f, "http upgrade error: {error}")
            }
        }
    }
}

impl std::error::Error for HandshakeError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::ValidationError(error) => Some(error as &dyn std::error::Error),
            Self::HttpRequestError(error) | Self::HttpUpgradeError(error) => error.source(),
        }
    }
}

#[derive(Default, Debug)]
pub struct AcceptedWebSocketData {
    pub protocol: Option<AcceptedWebSocketProtocol>,
    pub extension: Option<Extension>,
}

/// Validate the "accept" response from the http server
/// with whom the client is trying to establish a WebSocket connection.
pub fn validate_http_server_response<Body>(
    response: &Response<Body>,
    key: Option<headers::SecWebSocketKey>,
    protocols: Option<SecWebSocketProtocol>,
    extensions: Option<SecWebSocketExtensions>,
) -> Result<AcceptedWebSocketData, ResponseValidateError> {
    tracing::trace!(
        http.version = ?response.version(),
        http.response.status = ?response.status(),
        ws.protocols = ?protocols,
        ws.extensions = ?extensions,
        "validate http server response"
    );

    match response.version() {
        Version::HTTP_10 | Version::HTTP_11 => {
            // If the status code received from the server is not 101, the
            // client handles the response per HTTP [RFC2616] procedures. (RFC 6455)
            let response_status = response.status();
            if response_status != StatusCode::SWITCHING_PROTOCOLS {
                return Err(ResponseValidateError::UnexpectedStatusCode(response_status));
            }

            // If the response lacks an |Upgrade| header field or the |Upgrade|
            // header field contains a value that is not an ASCII case-
            // insensitive match for the value "websocket", the client MUST
            // _Fail the WebSocket Connection_. (RFC 6455)
            if !response
                .headers()
                .typed_get::<headers::Upgrade>()
                .map(|u| u.is_websocket())
                .unwrap_or_default()
            {
                return Err(ResponseValidateError::MissingUpgradeWebSocketHeader);
            }

            // If the response lacks a |Connection| header field or the
            // |Connection| header field doesn't contain a token that is an
            // ASCII case-insensitive match for the value "Upgrade", the client
            // MUST _Fail the WebSocket Connection_. (RFC 6455)
            if !response
                .headers()
                .typed_get::<headers::Connection>()
                .map(|c| c.contains_upgrade())
                .unwrap_or_default()
            {
                return Err(ResponseValidateError::MissingConnectionUpgradeHeader);
            }

            // Sec-WebSocket-Key / Accept is only used in h1 responses.
            //
            // If the response lacks a |Sec-WebSocket-Accept| header field or
            // the |Sec-WebSocket-Accept| contains a value other than the
            // base64-encoded SHA-1 of ... the client MUST _Fail the WebSocket
            // Connection_. (RFC 6455)
            if let Some(key) = key {
                let sec_websocket_accept_header = response
                    .headers()
                    .typed_get::<headers::SecWebSocketAccept>();
                let expected_accept =
                    headers::SecWebSocketAccept::try_from(key).map_err(|err| {
                        tracing::debug!("failed to create WS accept header from key: {err}");
                        ResponseValidateError::SecWebSocketAcceptKeyMismatch
                    })?;
                if sec_websocket_accept_header != Some(expected_accept) {
                    tracing::trace!(
                        "unexpected websocket accept key: {sec_websocket_accept_header:?}"
                    );
                    return Err(ResponseValidateError::SecWebSocketAcceptKeyMismatch);
                }
            }
        }
        Version::HTTP_2 => {
            let response_status = response.status();
            if !response.status().is_success() {
                return Err(ResponseValidateError::UnexpectedStatusCode(response_status));
            }
        }
        version => {
            return Err(ResponseValidateError::UnexpectedHttpVersion(version));
        }
    }

    // If the response includes a |Sec-WebSocket-Extensions| header
    // field and this header field indicates the use of an extension
    // that was not present in the client's handshake (the server has
    // indicated an extension not requested by the client), the client
    // MUST _Fail the WebSocket Connection_. (RFC 6455)
    let mut accepted_extension = None;
    match (
        response
            .headers()
            .typed_get::<SecWebSocketExtensions>()
            .map(|ext| ext.0.head),
        extensions,
    ) {
        (None, Some(allowed_extensions)) => {
            tracing::trace!(
                ws.extensions = ?allowed_extensions,
                "server selected no WS extensions despite client supporting some (valid, move on without)",
            );
        }
        (Some(Extension::PerMessageDeflate(server_cfg)), Some(client_extensions)) => {
            accepted_extension = client_extensions
                .0.iter()
                .find_map(|client_ext| {
                    if let Extension::PerMessageDeflate(client_cfg) = client_ext {
                        return Some(Ok(Extension::PerMessageDeflate(PerMessageDeflateConfig {
                            client_max_window_bits: match (
                                server_cfg.client_max_window_bits,
                                client_cfg.client_max_window_bits,
                            ) {
                                (None, None | Some(_)) => None,
                                (Some(srv), maybe_offered) => {
                                    if !(8..=15).contains(&srv) || maybe_offered.map(|offered| offered != 0 && srv > offered).unwrap_or_default() {
                                        tracing::debug!("server offered invalid client_max_window_bits (pmd)... ext mismatch!");
                                        return Some(Err(
                                            ResponseValidateError::ExtensionMismatch(Some(
                                                Extension::PerMessageDeflate(server_cfg.clone()),
                                            )),
                                        ));
                                    }
                                    Some(srv)
                                }
                            },
                            server_max_window_bits: match (
                                server_cfg.server_max_window_bits,
                                client_cfg.server_max_window_bits,
                            ) {
                                (None, None | Some(_)) => None,
                                (Some(their_bits), maybe_our_bits) => {
                                    if !(8..=15).contains(&their_bits)
                                        || maybe_our_bits
                                            .map(|our_bits| our_bits != 0 && their_bits > our_bits)
                                            .unwrap_or_default()
                                    {
                                        tracing::debug!("server offered invalid server_max_window_bits (pmd)... ext mismatch!");
                                        return Some(Err(
                                            ResponseValidateError::ExtensionMismatch(Some(
                                                Extension::PerMessageDeflate(server_cfg.clone()),
                                            )),
                                        ));
                                    }
                                    Some(their_bits)
                                }
                            },
                            server_no_context_takeover: server_cfg.server_no_context_takeover,
                            client_no_context_takeover: client_cfg.client_no_context_takeover,
                            identifier: server_cfg.identifier.clone(),
                        })));
                    }
                    None
                })
                .transpose()?;
        }
        (Some(server_ext), _) => {
            tracing::debug!("server offered ext, but client (we) not!");
            return Err(ResponseValidateError::ExtensionMismatch(Some(server_ext)));
        }
        (None, None) => (),
    }

    // If the response includes a |Sec-WebSocket-Protocol| header field
    // and this header field indicates the use of a subprotocol that was
    // not present in the client's handshake (the server has indicated a
    // subprotocol not requested by the client), the client MUST _Fail
    // the WebSocket Connection_. (RFC 6455)
    let mut accepted_protocol = None;
    match (
        response
            .headers()
            .typed_get::<SecWebSocketProtocol>()
            .map(|h| h.accept_first_protocol()),
        protocols,
    ) {
        (None, None) => (),
        (None, Some(allowed_protocols)) => {
            // RFC 6455 only mandates failure when the server selects a protocol
            // not in the client's offer — a server may legitimately decline to
            // select any subprotocol even when the client proposed one.
            tracing::trace!(
                ws.protocols = ?allowed_protocols,
                "server selected no WS subprotocol despite client proposing some (valid, proceed without)",
            );
        }
        (Some(header), None) => {
            return Err(ResponseValidateError::ProtocolMismatch(Some(header.0)));
        }
        (Some(protocol_header), Some(sub_protocols)) => {
            match sub_protocols.contains(&protocol_header.0) {
                Some(protocol) => accepted_protocol = Some(protocol),
                None => {
                    return Err(ResponseValidateError::ProtocolMismatch(Some(
                        protocol_header.0,
                    )));
                }
            };
        }
    }

    Ok(AcceptedWebSocketData {
        protocol: accepted_protocol,
        extension: accepted_extension,
    })
}

impl WebSocketRequestBuilder<request::Builder> {
    /// Create a new `http/1.1` WebSocket [`Request`] builder.
    pub fn new<T>(uri: T) -> Self
    where
        T: TryInto<rama_net::uri::Uri, Error: Into<rama_http::HttpError>>,
    {
        Self::new_with_version(uri, Version::HTTP_11)
    }

    /// Create a new `h2` WebSocket [`Request`] builder.
    pub fn new_h2<T>(uri: T) -> Self
    where
        T: TryInto<rama_net::uri::Uri, Error: Into<rama_http::HttpError>>,
    {
        Self::new_with_version(uri, Version::HTTP_2)
    }

    fn new_with_version<T>(uri: T, version: Version) -> Self
    where
        T: TryInto<rama_net::uri::Uri, Error: Into<rama_http::HttpError>>,
    {
        Self {
            inner: new_ws_request_builder_from_uri(uri, version),
            protocols: Default::default(),
            extensions: Default::default(),
            key: Default::default(),
        }
    }

    /// Set a custom http header
    #[must_use]
    pub fn with_header<K, V>(self, name: K, value: V) -> Self
    where
        K: TryInto<rama_http::HeaderName, Error: Into<rama_http::HttpError>>,
        V: TryInto<rama_http::HeaderValue, Error: Into<rama_http::HttpError>>,
    {
        Self {
            inner: self.inner.header(name, value),
            protocols: self.protocols,
            extensions: self.extensions,
            key: self.key,
        }
    }

    /// Set a custom typed http header
    #[must_use]
    pub fn with_typed_header<H>(self, header: H) -> Self
    where
        H: headers::HeaderEncode,
    {
        Self {
            inner: self.inner.typed_header(header),
            protocols: self.protocols,
            extensions: self.extensions,
            key: self.key,
        }
    }

    /// Build the handshake data
    /// to be used to initiate the WebSocket handshake using an http client.
    pub fn build_handshake(self) -> Result<HandshakeRequest, BoxError> {
        let builder = match self.protocols.as_ref() {
            Some(protocols) => self.inner.typed_header(protocols),
            None => self.inner,
        };

        let builder = match self.extensions.as_ref() {
            Some(extensions) => builder.typed_header(extensions),
            None => builder,
        };

        let mut request = builder
            .body(Body::empty())
            .context("request failed to build (invalid custom header?)")?;

        let mut key = None;
        if request.version() != Version::HTTP_2 {
            let k = self.key.unwrap_or_else(headers::SecWebSocketKey::random);
            request.headers_mut().typed_insert(&k);
            key = Some(k);
        }

        // only required for h2, but we might upgrade from h1 to h2 based on layers such as tls
        request
            .extensions()
            .insert(Protocol::from_static("websocket"));

        Ok(HandshakeRequest {
            request,
            protocols: self.protocols,
            extensions: self.extensions,
            key,
        })
    }
}

impl<'a, S, Body> WebSocketRequestBuilder<WithService<'a, S, Body, websocket_builder_mode::Async>>
where
    S: Service<Request, Output = Response<Body>, Error: Into<BoxError>>,
{
    /// Create a new `http/1.1` WebSocket [`Request`] builder.
    pub fn new_with_service<T>(service: &'a S, uri: T) -> Self
    where
        T: IntoUrl,
    {
        Self::new_with_service_and_version_and_mode(
            service,
            Version::HTTP_11,
            uri,
            websocket_builder_mode::Async,
        )
    }

    /// Create a new `h2` WebSocket [`Request`] builder.
    pub fn new_h2_with_service<T>(service: &'a S, uri: T) -> Self
    where
        T: IntoUrl,
    {
        Self::new_with_service_and_version_and_mode(
            service,
            Version::HTTP_2,
            uri,
            websocket_builder_mode::Async,
        )
    }

    /// Create a new WebSocket [`Request`] builder for the given [`Request`]
    pub fn new_with_service_and_request<RequestBody>(
        service: &'a S,
        request: Request<RequestBody>,
    ) -> Self
    where
        RequestBody: Into<rama_http::Body>,
    {
        Self::new_with_service_request_and_mode(service, request, websocket_builder_mode::Async)
    }
}

impl<'a, S, Body, Mode> WebSocketRequestBuilder<WithService<'a, S, Body, Mode>>
where
    S: Service<Request, Output = Response<Body>, Error: Into<BoxError>>,
{
    fn new_with_service_and_version_and_mode<T>(
        service: &'a S,
        version: Version,
        uri: T,
        mode: Mode,
    ) -> Self
    where
        T: IntoUrl,
    {
        Self {
            inner: WithService {
                service,
                builder: new_ws_request_builder_from_uri_with_service(service, uri, version),
                config: Default::default(),
                is_h2: version == Version::HTTP_2,
                mode,
            },
            protocols: Default::default(),
            extensions: Default::default(),
            key: Default::default(),
        }
    }

    fn new_with_service_request_and_mode<RequestBody>(
        service: &'a S,
        request: Request<RequestBody>,
        mode: Mode,
    ) -> Self
    where
        RequestBody: Into<rama_http::Body>,
    {
        let key = request.headers().typed_get();
        let is_h2 = request.version() == Version::HTTP_2;
        let protocols = request.headers().typed_get();
        let extensions = request.headers().typed_get();

        Self {
            inner: WithService {
                service,
                builder: new_ws_request_builder_from_request(service, request),
                config: Default::default(),
                is_h2,
                mode,
            },
            protocols,
            extensions,
            key,
        }
    }

    /// Set a custom http header
    #[must_use]
    pub fn with_header<K, V>(self, name: K, value: V) -> Self
    where
        K: IntoHeaderName,
        V: IntoHeaderValue,
    {
        Self {
            inner: WithService {
                builder: self.inner.builder.header(name, value),
                ..self.inner
            },
            protocols: self.protocols,
            extensions: self.extensions,
            key: self.key,
        }
    }

    /// Overwrite a custom http header
    #[must_use]
    pub fn with_header_overwrite<K, V>(self, name: K, value: V) -> Self
    where
        K: IntoHeaderName,
        V: IntoHeaderValue,
    {
        Self {
            inner: WithService {
                builder: self.inner.builder.overwrite_header(name, value),
                ..self.inner
            },
            protocols: self.protocols,
            extensions: self.extensions,
            key: self.key,
        }
    }

    /// Set a custom typed http header
    #[must_use]
    pub fn with_typed_header<H>(self, header: H) -> Self
    where
        H: headers::HeaderEncode,
    {
        Self {
            inner: WithService {
                builder: self.inner.builder.typed_header(header),
                ..self.inner
            },
            protocols: self.protocols,
            extensions: self.extensions,
            key: self.key,
        }
    }

    /// Overwrite a custom typed http header
    #[must_use]
    pub fn with_typed_header_overwrite<H>(self, header: H) -> Self
    where
        H: headers::HeaderEncode,
    {
        Self {
            inner: WithService {
                builder: self.inner.builder.overwrite_typed_header(header),
                ..self.inner
            },
            protocols: self.protocols,
            extensions: self.extensions,
            key: self.key,
        }
    }

    #[cfg(feature = "compression")]
    rama_utils::macros::generate_set_and_with! {
        /// Set/add deflate ext and also apply it to the [`WebSocketConfig`],
        /// using the default [`crate::protocol::PerMessageDeflateConfig`].
        #[must_use]
        #[cfg_attr(docsrs, doc(cfg(feature = "compression")))]
        pub fn per_message_deflate(mut self) -> Self {
            self.extensions = match self.extensions.take() {
                Some(ext) => {
                    Some(ext.with_extra_extension(Extension::PerMessageDeflate(Default::default())))
                },
                None => Some(SecWebSocketExtensions::per_message_deflate()),
            };
            self.inner.config = Some(self.inner.config.take().unwrap_or_default().with_per_message_deflate_default());
            self
        }
    }

    #[cfg(feature = "compression")]
    rama_utils::macros::generate_set_and_with! {
        /// Set/add deflate ext and also apply it to the [`WebSocketConfig`],
        /// using the default [`crate::protocol::PerMessageDeflateConfig`].
        ///
        /// Overwrites existing extensions if already existed.
        #[must_use]
        #[cfg_attr(docsrs, doc(cfg(feature = "compression")))]
        pub fn per_message_deflate_overwrite_extensions(mut self) -> Self {
            self.extensions = Some(SecWebSocketExtensions::per_message_deflate());
            self.inner.config = Some(self.inner.config.take().unwrap_or_default().with_per_message_deflate_default());
            self
        }
    }

    #[cfg(feature = "compression")]
    rama_utils::macros::generate_set_and_with! {
        /// Set/add deflate ext and also apply it to the [`WebSocketConfig`],
        /// using the default [`crate::protocol::PerMessageDeflateConfig`].
        #[must_use]
        #[cfg_attr(docsrs, doc(cfg(feature = "compression")))]
        pub fn per_message_deflate_with_config(mut self, config: impl Into<crate::protocol::PerMessageDeflateConfig>) -> Self {
            let config = config.into();
            self.extensions = match self.extensions.take() {
                Some(ext) => {
                    Some(ext.with_extra_extension(Extension::PerMessageDeflate((&config).into())))
                }
                None => Some(SecWebSocketExtensions::per_message_deflate_with_config((&config).into())),
            };
            self.inner.config = Some(
                self.inner
                    .config
                    .take()
                    .unwrap_or_default()
                    .with_per_message_deflate(config),
            );
            self
        }
    }

    #[cfg(feature = "compression")]
    rama_utils::macros::generate_set_and_with! {
        /// Set/add deflate ext and also apply it to the [`WebSocketConfig`],
        /// using the default [`crate::protocol::PerMessageDeflateConfig`].
        ///
        /// Overwrites existing extensions if already existed.
        #[must_use]
        #[cfg_attr(docsrs, doc(cfg(feature = "compression")))]
        pub fn per_message_deflate_with_config_overwrite_extensions(mut self, config: impl Into<crate::protocol::PerMessageDeflateConfig>) -> Self {
            let config = config.into();
            self.extensions = Some(SecWebSocketExtensions::per_message_deflate_with_config((&config).into()));
            self.inner.config = Some(
                self.inner
                    .config
                    .take()
                    .unwrap_or_default()
                    .with_per_message_deflate(config),
            );
            self
        }
    }

    rama_utils::macros::generate_set_and_with! {
        /// Set the [`WebSocketConfig`], overwriting the previous config if already set.
        pub fn config(mut self, cfg: Option<WebSocketConfig>) -> Self {
            self.inner.config = cfg;
            self
        }
    }

    fn prepare_handshake_inner(
        self,
        extensions: &Extensions,
    ) -> Result<PreparedHandshakeRequest, HandshakeError> {
        extensions.insert(StreamTransformed {
            by: "rama-ws::WebSocketClient",
        });

        let builder = match self.protocols.as_ref() {
            Some(protocols) => self.inner.builder.overwrite_typed_header(protocols),
            None => self.inner.builder,
        };

        let builder = match self.extensions.as_ref() {
            Some(extensions) => builder.typed_header(extensions),
            None => builder,
        };

        let mut key = None;
        let builder = if !self.inner.is_h2 {
            extensions.insert(TargetHttpVersion(Version::HTTP_11));

            let k = self.key.unwrap_or_else(headers::SecWebSocketKey::random);
            let builder = builder.overwrite_typed_header(&k);
            key = Some(k);
            builder
        } else {
            extensions.insert(TargetHttpVersion(Version::HTTP_2));

            builder
        };

        // only required in h1, but because of layers such as tls we might anyway turn from h1 into h2
        let builder = builder.extension(Protocol::from_static("websocket"));

        if let Some(ext) = builder.extensions() {
            ext.extend(extensions);
        }

        let request = builder
            .build()
            .context("build initial websocket handshake request (upgrade)")
            .map_err(HandshakeError::HttpRequestError)?;

        Ok(PreparedHandshakeRequest {
            request,
            protocols: self.protocols,
            extensions: self.extensions,
            config: self.inner.config,
            key,
        })
    }

    async fn initiate_handshake_inner(
        self,
        extensions: Extensions,
    ) -> Result<NegotiatedHandshakeRequest<Body>, HandshakeError> {
        let service = self.inner.service;
        let prepared = self.prepare_handshake_inner(&extensions)?;
        prepared.send(service).await
    }
}

impl<'a, S, Body> WebSocketRequestBuilder<WithService<'a, S, Body, websocket_builder_mode::Async>>
where
    S: Service<Request, Output = Response<Body>, Error: Into<BoxError>>,
{
    /// Initiate the handshake by preparing the http request, sending it
    /// and receiving the http response.
    ///
    /// This consumes this [`WebSocketRequestBuilder`]. Fulfill
    /// the handshake by calling [`NegotiatedHandshakeRequest::complete`].
    ///
    /// In most cases you have however no need for this intermediate result,
    /// and are better of calling [`Self::handshake`] directly. Only in cases
    /// such as MITM proxies or edge-case purposes you might require access
    /// to [`NegotiatedHandshakeRequest`].
    pub async fn initiate_handshake(
        self,
        extensions: Extensions,
    ) -> Result<NegotiatedHandshakeRequest<Body>, HandshakeError> {
        self.initiate_handshake_inner(extensions).await
    }

    /// Establish a [`ClientWebSocket`], consuming this [`WebSocketRequestBuilder`],
    /// by doing the http-handshake, including validation and returning the socket if all is good.
    pub async fn handshake(self, extensions: Extensions) -> Result<ClientWebSocket, HandshakeError>
    where
        Body: Send + 'static,
    {
        let handshake = self.initiate_handshake(extensions).await?;
        handshake.complete().await
    }
}

impl<'a, S, Body>
    WebSocketRequestBuilder<WithService<'a, S, Body, websocket_builder_mode::Blocking<S>>>
where
    S: Service<Request, Output = Response<Body>, Error: Into<BoxError>>,
    Body: Send + 'static,
{
    fn new_blocking_with_service<T>(client: &'a BlockingHttpClient<S>, uri: T) -> Self
    where
        T: IntoUrl,
    {
        Self::new_with_service_and_version_and_mode(
            client.get_ref(),
            Version::HTTP_11,
            uri,
            websocket_builder_mode::Blocking {
                runtime: client.runtime().clone(),
                service: client.clone_service(),
            },
        )
    }

    fn new_blocking_h2_with_service<T>(client: &'a BlockingHttpClient<S>, uri: T) -> Self
    where
        T: IntoUrl,
    {
        Self::new_with_service_and_version_and_mode(
            client.get_ref(),
            Version::HTTP_2,
            uri,
            websocket_builder_mode::Blocking {
                runtime: client.runtime().clone(),
                service: client.clone_service(),
            },
        )
    }

    fn new_blocking_with_service_and_request<RequestBody>(
        client: &'a BlockingHttpClient<S>,
        request: Request<RequestBody>,
    ) -> Self
    where
        RequestBody: Into<rama_http::Body>,
    {
        Self::new_with_service_request_and_mode(
            client.get_ref(),
            request,
            websocket_builder_mode::Blocking {
                runtime: client.runtime().clone(),
                service: client.clone_service(),
            },
        )
    }

    /// Establish a blocking [`BlockingClientWebSocket`] using empty request
    /// extensions.
    pub fn try_handshake(self) -> Result<BlockingClientWebSocket, HandshakeError> {
        self.try_handshake_with_extensions(Extensions::new())
    }

    /// Establish a blocking [`BlockingClientWebSocket`] using the supplied
    /// request extensions.
    #[expect(
        clippy::needless_pass_by_value,
        reason = "matches the async handshake API and transfers the extension set"
    )]
    pub fn try_handshake_with_extensions(
        self,
        extensions: Extensions,
    ) -> Result<BlockingClientWebSocket, HandshakeError> {
        let runtime = self.inner.mode.runtime.clone();
        let service = Arc::clone(&self.inner.mode.service);
        let prepared = self.prepare_handshake_inner(&extensions)?;
        let completed = runtime.block_on_task(async move {
            let handshake = prepared.send(service.as_ref()).await?;
            handshake.complete_upgrade().await
        })?;
        let socket = WebSocket::from_raw_socket(
            runtime.io(completed.stream),
            Role::Client,
            completed.config,
        );

        Ok(BlockingClientWebSocket {
            socket,
            response: completed.response,
            accepted_protocol: completed.accepted_protocol,
        })
    }
}

impl<B> WebSocketRequestBuilder<B> {
    rama_utils::macros::generate_set_and_with! {
        /// Define the WebSocket protocols to be used.
        pub fn protocols(mut self, protocols: Option<SecWebSocketProtocol>) -> Self {
            self.protocols = protocols;
            self
        }
    }

    rama_utils::macros::generate_set_and_with! {
        /// Set the WebSocket key (a random one will be generated if not defined).
        ///
        /// Only touch this property if you have a good reason to do so.
        pub fn key(mut self, key: Option<headers::SecWebSocketKey>) -> Self {
            self.key = key;
            self
        }
    }
}

/// Utility which can be used my Mitm proxies to
/// update the base config of a client websocket config.
pub fn apply_response_data_to_base_websocket_config<Body>(
    base_cfg: Option<WebSocketConfig>,
    res: &mut Response<Body>,
) -> Option<WebSocketConfig> {
    let accepted_pmd_cfg = res
        .headers()
        .typed_get::<SecWebSocketExtensions>()
        .map(|ext| ext.0.head)
        .and_then(|ext| {
            if let Extension::PerMessageDeflate(cfg) = ext {
                Some(cfg)
            } else {
                None
            }
        });

    if let Some(accepted_protocol) = res
        .headers()
        .typed_get::<SecWebSocketProtocol>()
        .map(|h| h.accept_first_protocol())
    {
        res.extensions().insert(accepted_protocol);
    }

    #[cfg(feature = "compression")]
    {
        if let Some(pmd_cfg) = accepted_pmd_cfg {
            let mut ws_cfg = base_cfg.unwrap_or_default();
            ws_cfg.per_message_deflate = Some(pmd_cfg.into());
            Some(ws_cfg)
        } else if let Some(mut ws_cfg) = base_cfg {
            ws_cfg.per_message_deflate = None;
            Some(ws_cfg)
        } else {
            base_cfg
        }
    }

    #[cfg(not(feature = "compression"))]
    {
        if accepted_pmd_cfg.is_some() {
            tracing::error!(
                "per-message-deflate is used but compression feature is disabled. Enable it if you wish to use this extension."
            );
        }

        base_cfg
    }
}

/// Intermediate websocket handshake created by
/// [`WebSocketRequestBuilder::initiate_handshake`].
///
/// Useful in case you require access to some of the data
/// prior to validation and WS upgrading.
pub struct NegotiatedHandshakeRequest<Body> {
    pub protocols: Option<SecWebSocketProtocol>,
    pub extensions: Option<SecWebSocketExtensions>,
    pub config: Option<WebSocketConfig>,
    pub key: Option<SecWebSocketKey>,
    pub response: Response<Body>,
}

struct CompletedClientHandshake {
    stream: rama_http::io::upgrade::Upgraded,
    response: response::Parts,
    accepted_protocol: Option<AcceptedWebSocketProtocol>,
    config: Option<WebSocketConfig>,
}

impl<Body> NegotiatedHandshakeRequest<Body> {
    /// Fulfill the websocket handshake and return the upgraded [`ClientWebSocket`].
    pub async fn complete(self) -> Result<ClientWebSocket, HandshakeError>
    where
        Body: Send + 'static,
    {
        let completed = self.complete_upgrade().await?;
        let socket =
            AsyncWebSocket::from_raw_socket(completed.stream, Role::Client, completed.config).await;

        Ok(ClientWebSocket {
            socket,
            response: completed.response,
            accepted_protocol: completed.accepted_protocol,
        })
    }

    async fn complete_upgrade(self) -> Result<CompletedClientHandshake, HandshakeError>
    where
        Body: Send + 'static,
    {
        let accepted_data = validate_http_server_response(
            &self.response,
            self.key,
            self.protocols,
            self.extensions,
        )
        .map_err(HandshakeError::ValidationError)?;

        tracing::trace!(
            websocket.protocol = ?accepted_data.protocol,
            websocket.extension = ?accepted_data.extension,
            "websocket handshake http response is valid",
        );

        #[cfg(feature = "compression")]
        let maybe_ws_cfg = {
            let mut ws_cfg = self.config.unwrap_or_default();

            if let Some(Extension::PerMessageDeflate(pmd_cfg)) = accepted_data.extension {
                tracing::trace!(
                    "apply accepted per-message-deflate cfg into WS client config: {pmd_cfg:?}"
                );
                ws_cfg.per_message_deflate = Some(pmd_cfg.into());
            } else {
                ws_cfg.per_message_deflate = None;
            }

            Some(ws_cfg)
        };

        #[cfg(not(feature = "compression"))]
        let maybe_ws_cfg = {
            if let Some(Extension::PerMessageDeflate(pmd_cfg)) = accepted_data.extension {
                tracing::error!(
                    "per-message-deflate is used but compression feature is disabled. Enable it if you wish to use this extension."
                );
                return Err(HandshakeError::ValidationError(
                    ResponseValidateError::ExtensionMismatch(Some(Extension::PerMessageDeflate(
                        pmd_cfg,
                    ))),
                ));
            }
            self.config
        };

        let on_upgrade = rama_http::io::upgrade::handle_upgrade(&self.response);
        let (parts, body) = self.response.into_parts();
        let stream = on_upgrade
            .await
            .context("upgrade http connection into a raw web socket")
            .map_err(HandshakeError::HttpUpgradeError)?
            .with_guard(body);
        Ok(CompletedClientHandshake {
            stream,
            response: parts,
            accepted_protocol: accepted_data.protocol,
            config: maybe_ws_cfg,
        })
    }
}

#[derive(Debug)]
/// [`ClientWebSocket`], used as input-output stream.
///
/// Utility type created via [`WebSocketRequestBuilder::handshake`].
pub struct ClientWebSocket<S = AsyncWebSocket> {
    /// Established WebSocket message transport.
    pub socket: S,
    /// Original HTTP handshake response metadata.
    pub response: response::Parts,
    /// Subprotocol accepted during the HTTP handshake, when any.
    pub accepted_protocol: Option<AcceptedWebSocketProtocol>,
}

impl<S> Deref for ClientWebSocket<S> {
    type Target = S;

    fn deref(&self) -> &Self::Target {
        &self.socket
    }
}

impl<S> DerefMut for ClientWebSocket<S> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.socket
    }
}

impl<S> Stream for ClientWebSocket<S>
where
    S: Stream<Item = Result<Message, ProtocolError>> + Unpin,
{
    type Item = Result<Message, ProtocolError>;

    fn poll_next(self: Pin<&mut Self>, ctx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        Stream::poll_next(Pin::new(&mut self.get_mut().socket), ctx)
    }
}

impl<S> Sink<Message> for ClientWebSocket<S>
where
    S: Sink<Message, Error = ProtocolError> + Unpin,
{
    type Error = ProtocolError;

    fn poll_ready(self: Pin<&mut Self>, ctx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        Sink::poll_ready(Pin::new(&mut self.get_mut().socket), ctx)
    }

    fn start_send(self: Pin<&mut Self>, message: Message) -> Result<(), Self::Error> {
        Sink::start_send(Pin::new(&mut self.get_mut().socket), message)
    }

    fn poll_flush(self: Pin<&mut Self>, ctx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        Sink::poll_flush(Pin::new(&mut self.get_mut().socket), ctx)
    }

    fn poll_close(self: Pin<&mut Self>, ctx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        Sink::poll_close(Pin::new(&mut self.get_mut().socket), ctx)
    }
}

impl<S> ExtensionsRef for ClientWebSocket<S>
where
    S: ExtensionsRef,
{
    fn extensions(&self) -> &Extensions {
        self.socket.extensions()
    }
}

impl<S> ClientWebSocket<S> {
    /// Transform the message transport while preserving handshake metadata.
    #[must_use]
    pub fn map_socket<T>(self, map: impl FnOnce(S) -> T) -> ClientWebSocket<T> {
        ClientWebSocket {
            socket: map(self.socket),
            response: self.response,
            accepted_protocol: self.accepted_protocol,
        }
    }

    /// Write and flush one message.
    pub fn send_message(
        &mut self,
        message: Message,
    ) -> impl Future<Output = Result<(), ProtocolError>> + Send + '_
    where
        S: Sink<Message, Error = ProtocolError> + Send + Unpin,
    {
        self.socket.send(message)
    }

    /// Receive one complete message.
    pub async fn recv_message(&mut self) -> Result<Message, ProtocolError>
    where
        S: Stream<Item = Result<Message, ProtocolError>> + Unpin,
    {
        self.socket.next().await.ok_or_else(|| {
            ProtocolError::Io(std::io::Error::new(
                std::io::ErrorKind::ConnectionAborted,
                "Connection closed: no messages to receive",
            ))
        })?
    }

    /// Close the WebSocket.
    pub async fn close(&mut self, message: Option<CloseFrame>) -> Result<(), ProtocolError>
    where
        S: Sink<Message, Error = ProtocolError> + Send + Unpin,
    {
        self.socket.send(Message::Close(message)).await
    }

    /// View the original response data, from which this client web socket was created.
    pub fn response(&self) -> &response::Parts {
        &self.response
    }

    /// Return the accepted protocol (during the http handshake) of the [`ClientWebSocket`], if any.
    pub fn accepted_protocol(&self) -> Option<&str> {
        self.accepted_protocol.as_ref().map(|p| p.0.as_ref())
    }

    /// Consume `self` and return its message transport.
    pub fn into_inner(self) -> S {
        self.socket
    }
}

/// A synchronous WebSocket over an upgraded HTTP transport driven by a Rama
/// blocking runtime.
pub type BlockingWebSocket = WebSocket<BlockingIo<rama_http::io::upgrade::Upgraded>>;

/// A connected blocking client WebSocket and its HTTP handshake metadata.
#[derive(Debug)]
pub struct BlockingClientWebSocket {
    /// Established blocking WebSocket transport.
    pub socket: BlockingWebSocket,
    /// Original HTTP handshake response metadata.
    pub response: response::Parts,
    /// Subprotocol accepted during the HTTP handshake, when any.
    pub accepted_protocol: Option<AcceptedWebSocketProtocol>,
}

impl Deref for BlockingClientWebSocket {
    type Target = BlockingWebSocket;

    fn deref(&self) -> &Self::Target {
        &self.socket
    }
}

impl DerefMut for BlockingClientWebSocket {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.socket
    }
}

impl BlockingClientWebSocket {
    /// View the original response data from which this WebSocket was created.
    pub fn response(&self) -> &response::Parts {
        &self.response
    }

    /// Return the subprotocol accepted during the HTTP handshake, if any.
    pub fn accepted_protocol(&self) -> Option<&str> {
        self.accepted_protocol.as_ref().map(|p| p.0.as_ref())
    }

    /// Write and immediately flush a message.
    pub fn send_message(&mut self, message: Message) -> Result<(), ProtocolError> {
        self.socket.send(message)
    }

    /// Read the next message.
    pub fn recv_message(&mut self) -> Result<Message, ProtocolError> {
        self.socket.read()
    }

    /// Consume this wrapper and return the blocking WebSocket.
    pub fn into_inner(self) -> BlockingWebSocket {
        self.socket
    }
}

/// Extends an Http Client with high level features WebSocket features.
pub trait HttpClientWebSocketExt<Body>:
    private::HttpClientWebSocketExtSealed<Body> + Sized + Send + Sync + 'static
{
    /// Create a new [`WebSocketRequestBuilder`]] to be used to establish a WebSocket connection over http/1.1.
    fn websocket(&self, url: impl IntoUrl) -> WebSocketRequestBuilder<WithService<'_, Self, Body>>;

    /// Create a new [`WebSocketRequestBuilder`] to be used to establish a WebSocket connection over h2.
    fn websocket_h2(
        &self,
        url: impl IntoUrl,
    ) -> WebSocketRequestBuilder<WithService<'_, Self, Body>>;

    /// Create a new [`WebSocketRequestBuilder`] starting from the given request.
    ///
    /// This is useful in cases where you already have a request that you wish to use,
    /// for example in the case of a proxied reuqest.
    fn websocket_with_request<RequestBody: Into<rama_http::Body>>(
        &self,
        req: Request<RequestBody>,
    ) -> WebSocketRequestBuilder<WithService<'_, Self, Body>>;
}

impl<S, Body> HttpClientWebSocketExt<Body> for S
where
    S: Service<Request, Output = Response<Body>, Error: Into<BoxError>>,
{
    fn websocket(&self, url: impl IntoUrl) -> WebSocketRequestBuilder<WithService<'_, Self, Body>> {
        WebSocketRequestBuilder::new_with_service(self, url)
    }

    fn websocket_h2(
        &self,
        url: impl IntoUrl,
    ) -> WebSocketRequestBuilder<WithService<'_, Self, Body>> {
        WebSocketRequestBuilder::new_h2_with_service(self, url)
    }

    fn websocket_with_request<RequestBody: Into<rama_http::Body>>(
        &self,
        req: Request<RequestBody>,
    ) -> WebSocketRequestBuilder<WithService<'_, Self, Body>> {
        WebSocketRequestBuilder::new_with_service_and_request(self, req)
    }
}

/// Extends a blocking HTTP client with WebSocket handshake builders.
///
/// The HTTP client remains reusable after the handshake. Each successful
/// handshake returns one independent, connected [`BlockingClientWebSocket`].
///
/// # Panics
///
/// Blocking handshakes and socket I/O must not run directly on an asynchronous
/// executor thread.
///
/// ```no_run
/// use rama_core::{Service, error::BoxError};
/// use rama_http::{
///     Body, Request, Response,
///     service::client::blocking::Client,
/// };
/// use rama_ws::handshake::client::BlockingHttpClientWebSocketExt as _;
///
/// fn exchange<S>(client: &Client<S>) -> Result<(), BoxError>
/// where
///     S: Service<Request, Output = Response<Body>, Error: Into<BoxError>>,
/// {
///     let mut socket = client
///         .websocket("wss://example.com/chat")
///         .with_header("authorization", "Bearer secret")
///         .try_handshake()?;
///
///     socket.send_message("hello".into())?;
///     let _reply = socket.recv_message()?;
///     Ok(())
/// }
/// ```
pub trait BlockingHttpClientWebSocketExt<Body>:
    private::BlockingHttpClientWebSocketExtSealed<Body>
{
    /// The asynchronous service wrapped by this blocking HTTP client.
    type AsyncService: Service<Request, Output = Response<Body>, Error: Into<BoxError>>;

    /// Create a WebSocket request builder for an HTTP/1.1 upgrade.
    fn websocket(
        &self,
        url: impl IntoUrl,
    ) -> BlockingWebSocketRequestBuilder<'_, Self::AsyncService, Body>;

    /// Create a WebSocket request builder for HTTP/2 Extended CONNECT.
    fn websocket_h2(
        &self,
        url: impl IntoUrl,
    ) -> BlockingWebSocketRequestBuilder<'_, Self::AsyncService, Body>;

    /// Create a WebSocket request builder from an existing request.
    fn websocket_with_request<RequestBody: Into<rama_http::Body>>(
        &self,
        request: Request<RequestBody>,
    ) -> BlockingWebSocketRequestBuilder<'_, Self::AsyncService, Body>;
}

impl<S, Body> BlockingHttpClientWebSocketExt<Body> for BlockingHttpClient<S>
where
    S: Service<Request, Output = Response<Body>, Error: Into<BoxError>>,
    Body: Send + 'static,
{
    type AsyncService = S;

    fn websocket(
        &self,
        url: impl IntoUrl,
    ) -> BlockingWebSocketRequestBuilder<'_, Self::AsyncService, Body> {
        BlockingWebSocketRequestBuilder::new_blocking_with_service(self, url)
    }

    fn websocket_h2(
        &self,
        url: impl IntoUrl,
    ) -> BlockingWebSocketRequestBuilder<'_, Self::AsyncService, Body> {
        BlockingWebSocketRequestBuilder::new_blocking_h2_with_service(self, url)
    }

    fn websocket_with_request<RequestBody: Into<rama_http::Body>>(
        &self,
        request: Request<RequestBody>,
    ) -> BlockingWebSocketRequestBuilder<'_, Self::AsyncService, Body> {
        BlockingWebSocketRequestBuilder::new_blocking_with_service_and_request(self, request)
    }
}

mod private {
    use super::*;

    pub trait HttpClientWebSocketExtSealed<Body> {}

    impl<S, Body> HttpClientWebSocketExtSealed<Body> for S where
        S: Service<Request, Output = Response<Body>, Error: Into<BoxError>>
    {
    }

    pub trait BlockingHttpClientWebSocketExtSealed<Body> {}

    impl<S, Body> BlockingHttpClientWebSocketExtSealed<Body> for BlockingHttpClient<S>
    where
        S: Service<Request, Output = Response<Body>, Error: Into<BoxError>>,
        Body: Send + 'static,
    {
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use rama_core::{ServiceInput, bytes::Bytes, service::service_fn};
    use rama_http::HeaderMap;
    use std::sync::{
        Arc,
        atomic::{AtomicUsize, Ordering},
    };

    struct ResponseLease(Arc<AtomicUsize>);

    impl Drop for ResponseLease {
        fn drop(&mut self) {
            self.0.fetch_add(1, Ordering::Release);
        }
    }

    #[test]
    fn blocking_client_websocket_roundtrip_and_lifetimes() {
        fn assert_send<T: Send>() {}
        assert_send::<BlockingClientWebSocket>();

        let leases_dropped = Arc::new(AtomicUsize::new(0));
        let service_leases_dropped = leases_dropped.clone();
        let service = service_fn(move |request: Request| {
            let leases_dropped = service_leases_dropped.clone();
            async move {
                let is_h2 = request.version() == Version::HTTP_2;
                let accept = if is_h2 {
                    assert_eq!(request.method(), Method::CONNECT);
                    assert!(request.headers().typed_get::<SecWebSocketKey>().is_none());
                    None
                } else {
                    assert_eq!(request.method(), Method::GET);
                    let key = request
                        .headers()
                        .typed_get::<SecWebSocketKey>()
                        .expect("HTTP/1.1 client handshake request to contain a key");
                    Some(
                        headers::SecWebSocketAccept::try_from(key)
                            .expect("client handshake key to produce an accept value"),
                    )
                };

                if request.uri().path().is_some_and(|path| path == "/custom") {
                    assert_eq!(
                        request.headers().get("x-rama-test"),
                        Some(&rama_http::HeaderValue::from_static("custom")),
                    );
                }

                let (client_io, server_io) = tokio::io::duplex(4 * 1024);
                let (pending, on_upgrade) = rama_http::io::upgrade::pending();
                pending.fulfill(rama_http::io::upgrade::Upgraded::new(
                    ServiceInput::new(client_io),
                    Bytes::new(),
                ));

                tokio::spawn(async move {
                    let mut socket = AsyncWebSocket::from_raw_socket(
                        ServiceInput::new(server_io),
                        Role::Server,
                        None,
                    )
                    .await;
                    let message = socket.recv_message().await.unwrap();
                    socket.send_message(message).await.unwrap();
                });

                let mut response = Response::new(ResponseLease(leases_dropped));
                if let Some(accept) = accept {
                    *response.status_mut() = StatusCode::SWITCHING_PROTOCOLS;
                    *response.version_mut() = Version::HTTP_11;
                    response
                        .headers_mut()
                        .typed_insert(headers::Upgrade::websocket());
                    response
                        .headers_mut()
                        .typed_insert(headers::Connection::upgrade());
                    response.headers_mut().typed_insert(accept);
                } else {
                    *response.status_mut() = StatusCode::OK;
                    *response.version_mut() = Version::HTTP_2;
                }
                response.extensions().insert(on_upgrade);
                Ok::<_, BoxError>(response)
            }
        });

        let client = BlockingHttpClient::try_new(service).unwrap();
        let client_clone = client.clone();
        drop(client);

        let config = WebSocketConfig::default().with_read_buffer_size(4 * 1024);
        let mut from_url = client_clone
            .websocket("ws://example.test/echo")
            .with_config(config)
            .try_handshake()
            .unwrap();
        assert_eq!(from_url.response().status, StatusCode::SWITCHING_PROTOCOLS);
        assert_eq!(from_url.get_config().read_buffer_size, 4 * 1024);
        assert_eq!(
            from_url
                .extensions()
                .get_ref::<StreamTransformed>()
                .unwrap()
                .by,
            "rama-http::Upgraded",
        );

        let request = Request::builder()
            .version(Version::HTTP_11)
            .uri("ws://example.test/custom")
            .header("x-rama-test", "custom")
            .body(Body::empty())
            .unwrap();
        let mut from_request = client_clone
            .websocket_with_request(request)
            .try_handshake()
            .unwrap();
        let mut from_h2 = client_clone
            .websocket_h2("wss://example.test/h2")
            .try_handshake()
            .unwrap();

        drop(client_clone);
        assert_eq!(leases_dropped.load(Ordering::Acquire), 0);

        from_url.send_message("from url".into()).unwrap();
        assert_eq!(
            from_url
                .recv_message()
                .unwrap()
                .into_text()
                .unwrap()
                .as_str(),
            "from url",
        );

        from_request.send_message("from request".into()).unwrap();
        assert_eq!(
            from_request
                .recv_message()
                .unwrap()
                .into_text()
                .unwrap()
                .as_str(),
            "from request",
        );

        from_h2.send_message("from h2".into()).unwrap();
        assert_eq!(
            from_h2
                .recv_message()
                .unwrap()
                .into_text()
                .unwrap()
                .as_str(),
            "from h2",
        );

        let BlockingClientWebSocket {
            socket: from_url,
            response,
            accepted_protocol: protocol,
        } = from_url;
        assert_eq!(response.status, StatusCode::SWITCHING_PROTOCOLS);
        assert!(protocol.is_none());
        assert_eq!(leases_dropped.load(Ordering::Acquire), 0);
        drop(from_url);
        assert_eq!(leases_dropped.load(Ordering::Acquire), 1);
        drop(from_request);
        assert_eq!(leases_dropped.load(Ordering::Acquire), 2);
        drop(from_h2);
        assert_eq!(leases_dropped.load(Ordering::Acquire), 3);
    }

    #[cfg(feature = "dial9")]
    #[test]
    fn blocking_handshake_runs_inside_dial9_session() {
        let temp_dir = tempfile::tempdir().unwrap();
        let config = rama_core::telemetry::dial9::Dial9Config::builder()
            .enabled(true)
            .base_path(temp_dir.path().join("blocking-websocket.bin"))
            .max_file_size(1024 * 1024)
            .max_total_size(4 * 1024 * 1024)
            .build()
            .unwrap();
        let runtime = rama_core::rt::blocking::Runtime::builder()
            .with_dial9_config(config)
            .try_build()
            .unwrap();
        let service = service_fn(|request: Request| async move {
            assert!(
                rama_core::telemetry::dial9::telemetry::TelemetryHandle::current().is_enabled()
            );
            let key = request
                .headers()
                .typed_get::<SecWebSocketKey>()
                .expect("handshake request to contain a key");
            let (client_io, _server_io) = tokio::io::duplex(1024);
            let (pending, on_upgrade) = rama_http::io::upgrade::pending();
            pending.fulfill(rama_http::io::upgrade::Upgraded::new(
                ServiceInput::new(client_io),
                Bytes::new(),
            ));

            let mut response = Response::new(());
            *response.status_mut() = StatusCode::SWITCHING_PROTOCOLS;
            *response.version_mut() = Version::HTTP_11;
            response
                .headers_mut()
                .typed_insert(headers::Upgrade::websocket());
            response
                .headers_mut()
                .typed_insert(headers::Connection::upgrade());
            response.headers_mut().typed_insert(
                headers::SecWebSocketAccept::try_from(key)
                    .expect("client handshake key to produce an accept value"),
            );
            response.extensions().insert(on_upgrade);
            Ok::<_, BoxError>(response)
        });
        let client = BlockingHttpClient::with_runtime(service, &runtime);

        let socket = client
            .websocket("wss://example.test/socket")
            .try_handshake()
            .unwrap();
        assert_eq!(socket.response().status, StatusCode::SWITCHING_PROTOCOLS);
    }

    fn offered_pmd(raw: &str) -> Option<SecWebSocketExtensions> {
        let mut headers = HeaderMap::new();
        headers.insert(
            header::SEC_WEBSOCKET_EXTENSIONS,
            raw.parse().expect("valid sec-websocket-extensions header"),
        );
        headers.typed_get::<SecWebSocketExtensions>()
    }

    fn h2_response_with_pmd(raw: &str) -> Response<()> {
        let mut response = Response::new(());
        *response.version_mut() = Version::HTTP_2;
        *response.status_mut() = StatusCode::OK;
        response.headers_mut().insert(
            header::SEC_WEBSOCKET_EXTENSIONS,
            raw.parse().expect("valid sec-websocket-extensions header"),
        );
        response
    }

    #[test]
    fn h2_handshake_accepts_any_successful_connect_status() {
        let mut response = Response::new(());
        *response.version_mut() = Version::HTTP_2;
        *response.status_mut() = StatusCode::CREATED;

        validate_http_server_response(&response, None, None, None)
            .expect("successful CONNECT response");

        *response.status_mut() = StatusCode::BAD_REQUEST;
        assert!(matches!(
            validate_http_server_response(&response, None, None, None),
            Err(ResponseValidateError::UnexpectedStatusCode(
                StatusCode::BAD_REQUEST
            ))
        ));
    }

    /// Validate an (h2) server handshake response carrying `server_raw` against
    /// a client that offered `offered_raw`, returning the negotiated
    /// `client_max_window_bits`.
    fn validate_pmd(
        server_raw: &str,
        offered_raw: &str,
    ) -> Result<Option<u8>, ResponseValidateError> {
        let response = h2_response_with_pmd(server_raw);
        let accepted =
            validate_http_server_response(&response, None, None, offered_pmd(offered_raw))?;
        match accepted.extension {
            Some(Extension::PerMessageDeflate(cfg)) => Ok(cfg.client_max_window_bits),
            other => panic!("expected per-message-deflate extension, got {other:?}"),
        }
    }

    // Regression: a valueless `client_max_window_bits` offer is parsed as the
    // sentinel `Some(0)` ("server may pick any value <= 15"). A server response
    // of `client_max_window_bits=15` must be accepted, not rejected as an
    // extension mismatch. Previously the `srv > offered` check evaluated
    // `15 > 0` and falsely failed the handshake (intermittent WS-over-h2 502s).
    #[test]
    fn valueless_client_max_window_bits_accepts_server_choice() {
        assert_eq!(
            Some(15),
            validate_pmd(
                "permessage-deflate; client_max_window_bits=15",
                "permessage-deflate; client_max_window_bits",
            )
            .expect("valueless offer should accept the server's window bits"),
        );
    }

    #[test]
    fn explicit_client_max_window_bits_rejects_larger_server_choice() {
        assert!(matches!(
            validate_pmd(
                "permessage-deflate; client_max_window_bits=15",
                "permessage-deflate; client_max_window_bits=10",
            ),
            Err(ResponseValidateError::ExtensionMismatch(_)),
        ));
    }

    #[test]
    fn explicit_client_max_window_bits_accepts_smaller_server_choice() {
        assert_eq!(
            Some(10),
            validate_pmd(
                "permessage-deflate; client_max_window_bits=10",
                "permessage-deflate; client_max_window_bits=12",
            )
            .expect("server choosing a smaller window should validate"),
        );
    }
}