hypercall-client 0.5.0

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

use std::collections::BTreeMap;
use std::sync::{
    atomic::{AtomicBool, Ordering},
    Arc, Mutex as StdMutex,
};

use futures::{SinkExt, StreamExt};
use sonic_rs::JsonValueTrait;
use tokio::io::{AsyncRead, AsyncWrite};
use tokio::net::TcpStream;
use tokio::sync::{mpsc, oneshot, watch, Mutex, RwLock};
use tokio::time::Duration;
use tokio_tungstenite::tungstenite::client::IntoClientRequest;
use tokio_tungstenite::tungstenite::http::HeaderValue;
use tokio_tungstenite::{client_async, tungstenite, WebSocketStream};
use tracing::{debug, info, warn};

use crate::error::{ClientError, Result};
#[cfg(feature = "rfq-v2")]
use crate::rfq_v2::encode_rfq_v2_read_grant;
use crate::wallet::AccountAddress;
#[cfg(feature = "rfq-v2")]
use hypercall_sdk_types::rfq_v2::RfqV2ReadGrant;
use hypercall_sdk_types::ws_protocol::{RfqV2View, WsMessage};
use hypercall_ws_protocol::{WsChannel, WsSlowConsumerCloseReason};

/// Original indicative channel: one `IndicativeMarketData` frame per row.
const INDICATIVE_CHANNEL: &str = WsChannel::IndicativeMarketData.as_str();
/// Batched indicative channel: `IndicativeMarketDataBatch` frames.
const INDICATIVE_V2_CHANNEL: &str = WsChannel::IndicativeMarketDataV2.as_str();

#[path = "websocket_deflate_io.rs"]
mod deflate_io;

use deflate_io::{InflatingStream, PERMESSAGE_DEFLATE_OFFER};

const MAX_CONTROL_FRAME_PAYLOAD_LEN: usize = 125;
const OUTBOUND_CONTROL_CAPACITY: usize = 256;
/// Tungstenite's default frame limit. Inflated messages are re-framed in
/// frames no larger than this.
const MAX_FRAME_LEN: usize = 16 << 20;
/// Tungstenite's default message limit, which also caps inflated messages.
const MAX_MESSAGE_LEN: usize = 64 << 20;

/// The byte stream under the WebSocket: plain TCP or native-tls over TCP.
trait ClientIo: AsyncRead + AsyncWrite + Send + Unpin {}

impl<T: AsyncRead + AsyncWrite + Send + Unpin> ClientIo for T {}

type ClientSocket = WebSocketStream<InflatingStream<Box<dyn ClientIo>>>;

/// Reconnection and handshake policy for [`WsClient`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct WsClientConfig {
    pub reconnect_initial_delay: Duration,
    pub reconnect_max_delay: Duration,
    pub reconnect_reset_after: Duration,
    pub authentication_timeout: Duration,
    pub subscription_timeout: Duration,
}

impl Default for WsClientConfig {
    fn default() -> Self {
        Self {
            reconnect_initial_delay: Duration::from_millis(500),
            reconnect_max_delay: Duration::from_secs(30),
            reconnect_reset_after: Duration::from_secs(30),
            authentication_timeout: Duration::from_secs(5),
            subscription_timeout: Duration::from_secs(5),
        }
    }
}

impl WsClientConfig {
    fn validate(self) -> Result<()> {
        if self.reconnect_initial_delay.is_zero() {
            return Err(ClientError::InvalidInput(
                "reconnect_initial_delay must be positive".to_string(),
            ));
        }
        if self.reconnect_max_delay < self.reconnect_initial_delay {
            return Err(ClientError::InvalidInput(
                "reconnect_max_delay must be at least reconnect_initial_delay".to_string(),
            ));
        }
        if self.reconnect_reset_after.is_zero() {
            return Err(ClientError::InvalidInput(
                "reconnect_reset_after must be positive".to_string(),
            ));
        }
        if self.authentication_timeout.is_zero() || self.subscription_timeout.is_zero() {
            return Err(ClientError::InvalidInput(
                "WebSocket handshake timeouts must be positive".to_string(),
            ));
        }
        Ok(())
    }
}

/// Application work required before state is continuous after a reconnect.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct WsRecoveryPlan {
    /// Fetch an authoritative snapshot before consuming ordered public deltas.
    pub snapshot_resubscribe: bool,
    /// Reconcile durable private events through REST.
    pub rest_reconcile: bool,
    /// Refetch the current portfolio snapshot.
    pub portfolio_refetch: bool,
    /// Reconcile an unrecognized channel according to application semantics.
    pub application_reconcile: bool,
}

impl WsRecoveryPlan {
    pub const fn is_empty(self) -> bool {
        !self.snapshot_resubscribe
            && !self.rest_reconcile
            && !self.portfolio_refetch
            && !self.application_reconcile
    }

    fn include_channel(&mut self, channel: &str) {
        match channel {
            "orderbook" | "trades" | "options_chain" => self.snapshot_resubscribe = true,
            "portfolio" => {
                self.portfolio_refetch = true;
                self.rest_reconcile = true;
            }
            "order_updates" | "fills" | "liquidation" | "rfq" => self.rest_reconcile = true,
            #[cfg(feature = "rfq-v2")]
            "rfq_v2" => self.rest_reconcile = true,
            "indicative_market_data"
            | "indicative_market_data_v2"
            | "index_prices"
            | "market_updates" => {}
            channel if channel.starts_with("candles") => {}
            _ => self.application_reconcile = true,
        }
    }
}

/// Why an established WebSocket session ended.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum WsDisconnectReason {
    SlowConsumer(WsSlowConsumerCloseReason),
    CloseFrame { code: u16, reason: String },
    Transport(String),
    Protocol(String),
    EndOfStream,
}

/// Current lifecycle state of the client-managed WebSocket session.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum WsConnectionState {
    Disconnected,
    Connecting { attempt: u32 },
    Authenticating,
    Resubscribing { channels: usize },
    Reconnecting { attempt: u32, delay: Duration },
    RecoveryRequired(WsRecoveryPlan),
    Ready,
}

impl WsConnectionState {
    pub const fn transport_connected(&self) -> bool {
        matches!(self, Self::Ready | Self::RecoveryRequired(_))
    }

    pub const fn state_recovered(&self) -> bool {
        matches!(self, Self::Ready)
    }
}

#[derive(Debug, Clone)]
struct DesiredSubscription {
    channel: String,
    symbols: Option<Vec<String>>,
    expiry: Option<String>,
    option_type: Option<String>,
    /// Owned by [`WsClient::subscribe_indicative_market_data`], so it may live
    /// on either indicative channel after a fallback and is released by
    /// [`WsClient::unsubscribe_indicative_market_data`].
    logical_indicative: bool,
    /// Owned by a direct subscribe ([`WsClient::subscribe_with_options`] and
    /// friends) and released by [`WsClient::unsubscribe`]. A fallback can make
    /// one entry carry both claims; it is removed when neither remains.
    direct: bool,
    subscribe: String,
    unsubscribe: String,
}

fn canonical_symbols(symbols: Option<&[String]>) -> Option<std::collections::BTreeSet<String>> {
    let set: std::collections::BTreeSet<String> = symbols?
        .iter()
        .map(|symbol| symbol.trim().to_uppercase())
        .filter(|symbol| !symbol.is_empty())
        .collect();
    (!set.is_empty()).then_some(set)
}

impl DesiredSubscription {
    /// Take over the ownership claims of an equivalent entry it replaces.
    fn absorb(&mut self, other: &Self) {
        self.logical_indicative |= other.logical_indicative;
        self.direct |= other.direct;
    }

    /// Whether both entries describe the same channel and filter.
    ///
    /// Symbols compare the way the server stores them: trimmed, upper-cased,
    /// as a set, with an empty list meaning no filter.
    fn same_filter(&self, other: &Self) -> bool {
        self.channel == other.channel
            && canonical_symbols(self.symbols.as_deref())
                == canonical_symbols(other.symbols.as_deref())
            && self.expiry == other.expiry
            && self.option_type == other.option_type
    }

    fn new(
        channel: &str,
        symbols: Option<Vec<String>>,
        expiry: Option<String>,
        option_type: Option<String>,
    ) -> Result<Self> {
        Self::with_view(channel, symbols, expiry, option_type, None)
    }

    /// `view` (`rfq_v2` only) is encoded into the subscribe frame and is not
    /// part of the filter, so a later subscribe with another view replaces
    /// the earlier one.
    fn with_view(
        channel: &str,
        symbols: Option<Vec<String>>,
        expiry: Option<String>,
        option_type: Option<String>,
        view: Option<RfqV2View>,
    ) -> Result<Self> {
        let subscribe = sonic_rs::to_string(&WsMessage::Subscribe {
            channel: channel.to_string(),
            symbols: symbols.clone(),
            expiry: expiry.clone(),
            option_type: option_type.clone(),
            view,
        })?;
        let unsubscribe = sonic_rs::to_string(&WsMessage::Unsubscribe {
            channel: channel.to_string(),
            symbols: symbols.clone(),
            expiry: expiry.clone(),
            option_type: option_type.clone(),
        })?;
        Ok(Self {
            channel: channel.to_string(),
            symbols,
            expiry,
            option_type,
            logical_indicative: false,
            direct: false,
            subscribe,
            unsubscribe,
        })
    }
}

struct WsClientShared {
    messages: Arc<Mutex<Vec<sonic_rs::Value>>>,
    pongs: Arc<Mutex<Vec<Vec<u8>>>>,
    tx: StdMutex<Option<mpsc::Sender<tungstenite::Message>>>,
    subscriptions: RwLock<BTreeMap<String, DesiredSubscription>>,
    state: StdMutex<WsConnectionState>,
    state_tx: watch::Sender<WsConnectionState>,
    last_disconnect: StdMutex<Option<WsDisconnectReason>>,
    started: AtomicBool,
    /// Prefer `indicative_market_data_v2` for indicative subscriptions.
    batched_indicative: AtomicBool,
    /// Set once a server confirmed v2 without the batch marker: it does not
    /// know the channel. Sticky for the client's life.
    v2_unsupported: AtomicBool,
    /// A v2 confirmation without the marker arrived and the switch to v1 has
    /// not been applied yet.
    v2_fallback_pending: AtomicBool,
    /// The RFQ V2 read grant the session authenticates with, replaced by
    /// [`WsClient::reauthenticate_rfq_v2`] and presented again on reconnect.
    #[cfg(feature = "rfq-v2")]
    rfq_v2_grant: StdMutex<Option<RfqV2SocketGrant>>,
}

/// What [`WsClient::release_where`] does with one stored subscription.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Release {
    Keep,
    Remove,
}

/// What the client offers in the upgrade request.
#[derive(Debug, Clone, Copy)]
struct ConnectOptions {
    permessage_deflate: bool,
}

/// WebSocket client for Hypercall.
pub struct WsClient {
    shared: Arc<WsClientShared>,
    config: WsClientConfig,
    options: ConnectOptions,
    shutdown_tx: StdMutex<Option<watch::Sender<bool>>>,
}

#[cfg(feature = "rfq-v2")]
#[derive(Clone)]
struct RfqV2SocketGrant {
    token: String,
    account: String,
    expires_at_ms: u64,
}

/// The identity a session presents after every (re)connect. An RFQ V2
/// session's grant lives in [`WsClientShared`], since it can be replaced on
/// the live connection.
struct SessionCredentials {
    wallet: Option<String>,
}

impl SessionCredentials {
    fn wallet(wallet: Option<String>) -> Self {
        Self { wallet }
    }
}

#[cfg(feature = "rfq-v2")]
fn current_rfq_v2_grant(shared: &WsClientShared) -> Option<RfqV2SocketGrant> {
    shared
        .rfq_v2_grant
        .lock()
        .expect("WebSocket RFQ grant mutex poisoned")
        .clone()
}

/// Wall-clock expiry of the session's current RFQ V2 read grant, if any.
fn rfq_v2_expires_at_ms(shared: &WsClientShared) -> Option<u64> {
    #[cfg(feature = "rfq-v2")]
    {
        current_rfq_v2_grant(shared).map(|grant| grant.expires_at_ms)
    }
    #[cfg(not(feature = "rfq-v2"))]
    {
        let _ = shared;
        None
    }
}

fn current_unix_ms() -> Option<u64> {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .ok()
        .and_then(|elapsed| u64::try_from(elapsed.as_millis()).ok())
}

impl WsClient {
    /// Create a new WebSocket client (not yet connected).
    pub fn new() -> Self {
        Self::with_config(WsClientConfig::default())
    }

    /// Create a WebSocket client with an explicit reconnection policy.
    pub fn with_config(config: WsClientConfig) -> Self {
        let (state_tx, _) = watch::channel(WsConnectionState::Disconnected);
        Self {
            shared: Arc::new(WsClientShared {
                messages: Arc::new(Mutex::new(Vec::new())),
                pongs: Arc::new(Mutex::new(Vec::new())),
                tx: StdMutex::new(None),
                subscriptions: RwLock::new(BTreeMap::new()),
                state: StdMutex::new(WsConnectionState::Disconnected),
                state_tx,
                last_disconnect: StdMutex::new(None),
                started: AtomicBool::new(false),
                batched_indicative: AtomicBool::new(true),
                v2_unsupported: AtomicBool::new(false),
                v2_fallback_pending: AtomicBool::new(false),
                #[cfg(feature = "rfq-v2")]
                rfq_v2_grant: StdMutex::new(None),
            }),
            config,
            options: ConnectOptions {
                permessage_deflate: true,
            },
            shutdown_tx: StdMutex::new(None),
        }
    }

    /// Choose whether to offer RFC 7692 `permessage-deflate` when connecting.
    ///
    /// Enabled by default. The server decides whether to accept, and the client
    /// works either way: compressed frames are inflated transparently, and the
    /// JSON messages are identical. Disable it to save the CPU spent inflating,
    /// or to rule compression out while debugging. The setting applies to the
    /// initial connection and every reconnect.
    pub fn with_permessage_deflate(mut self, enabled: bool) -> Self {
        self.options.permessage_deflate = enabled;
        self
    }

    /// Choose whether [`WsClient::subscribe_indicative_market_data`] uses
    /// the batched `indicative_market_data_v2` channel.
    ///
    /// Enabled by default: fewer frames, rows up to one short batch window
    /// later, and much better compression. Disable it to receive one
    /// `IndicativeMarketData` frame per row from `indicative_market_data`.
    pub fn with_batched_indicative(self, enabled: bool) -> Self {
        self.shared
            .batched_indicative
            .store(enabled, Ordering::Release);
        self
    }

    /// Whether indicative subscriptions are currently delivered in batches:
    /// batching is enabled and no server has shown it lacks the v2 channel.
    pub fn indicative_batched(&self) -> bool {
        self.shared.batched_indicative.load(Ordering::Acquire)
            && !self.shared.v2_unsupported.load(Ordering::Acquire)
    }

    /// Connect to the WebSocket endpoint.
    ///
    /// If a wallet is provided, sends an `Authenticate` message after connecting
    /// and waits for the `Authenticated` confirmation before returning. After
    /// the initial connection succeeds, the client reconnects, reauthenticates,
    /// and restores desired subscriptions until [`WsClient::disconnect`] is called
    /// or the client is dropped.
    pub async fn connect(&self, base_url: &str, wallet: Option<&AccountAddress>) -> Result<()> {
        self.start_session(
            base_url,
            SessionCredentials::wallet(wallet.map(ToString::to_string)),
        )
        .await
    }

    /// Connect using a signed private RFQ read grant. The grant is sent again
    /// before subscriptions on reconnect.
    ///
    /// When the grant lapses the server keeps the connection and its
    /// subscriptions, and sends one `Error` with `code`
    /// `rfq_v2_grant_expired` (delivered like any other message) when it
    /// withholds a change. Sign a fresh grant and call
    /// [`WsClient::reauthenticate_rfq_v2`], ideally before expiry. A reconnect
    /// with an expired grant ends the session; no unsigned wallet identity
    /// grants RFQ access.
    #[cfg(feature = "rfq-v2")]
    pub async fn connect_rfq_v2(&self, base_url: &str, grant: &RfqV2ReadGrant) -> Result<()> {
        let socket_grant = RfqV2SocketGrant {
            token: encode_rfq_v2_read_grant(grant)?,
            account: grant.account.to_string(),
            expires_at_ms: grant.expires_at_ms,
        };
        if self.shared.started.load(Ordering::Acquire) {
            return Err(ClientError::WebSocket(
                "WebSocket client is already connected or connecting".to_string(),
            ));
        }
        *self
            .shared
            .rfq_v2_grant
            .lock()
            .expect("WebSocket RFQ grant mutex poisoned") = Some(socket_grant);
        let result = self
            .start_session(base_url, SessionCredentials { wallet: None })
            .await;
        if result.is_err() {
            *self
                .shared
                .rfq_v2_grant
                .lock()
                .expect("WebSocket RFQ grant mutex poisoned") = None;
        }
        result
    }

    /// Present a fresh RFQ read grant on the live connection, for the same
    /// account. Subscriptions stay; the grant is also used for later
    /// reconnects. `Ok` means the `AuthenticateRfqV2` frame was sent (or will
    /// be sent by the reconnect in progress); observe `RfqV2Authenticated`
    /// or `Error` for the server's answer.
    #[cfg(feature = "rfq-v2")]
    pub async fn reauthenticate_rfq_v2(&self, grant: &RfqV2ReadGrant) -> Result<()> {
        let socket_grant = RfqV2SocketGrant {
            token: encode_rfq_v2_read_grant(grant)?,
            account: grant.account.to_string(),
            expires_at_ms: grant.expires_at_ms,
        };
        {
            let mut current = self
                .shared
                .rfq_v2_grant
                .lock()
                .expect("WebSocket RFQ grant mutex poisoned");
            match current.as_ref() {
                None => {
                    return Err(ClientError::WebSocket(
                        "not an RFQ V2 session; use connect_rfq_v2".to_string(),
                    ))
                }
                Some(existing) if !existing.account.eq_ignore_ascii_case(&socket_grant.account) => {
                    return Err(ClientError::InvalidInput(
                        "RFQ read grant is for a different account than the session".to_string(),
                    ))
                }
                Some(_) => {}
            }
            *current = Some(socket_grant.clone());
        }
        let frame = sonic_rs::to_string(&WsMessage::AuthenticateRfqV2 {
            token: socket_grant.token,
        })?;
        let tx = self
            .shared
            .tx
            .lock()
            .expect("WebSocket sender mutex poisoned")
            .clone();
        if let Some(tx) = tx {
            tx.send(tungstenite::Message::Text(frame))
                .await
                .map_err(|e| ClientError::WebSocket(format!("Failed to send: {}", e)))?;
        }
        Ok(())
    }

    async fn start_session(&self, base_url: &str, credentials: SessionCredentials) -> Result<()> {
        self.config.validate()?;
        let ws_url = websocket_url(base_url)?;
        if self
            .shared
            .started
            .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
            .is_err()
        {
            return Err(ClientError::WebSocket(
                "WebSocket client is already connected or connecting".to_string(),
            ));
        }

        let (shutdown_tx, shutdown_rx) = watch::channel(false);
        *self
            .shutdown_tx
            .lock()
            .expect("WebSocket shutdown mutex poisoned") = Some(shutdown_tx);
        let (initial_tx, initial_rx) = oneshot::channel();
        let shared = self.shared.clone();
        let config = self.config;
        let options = self.options;
        tokio::spawn(async move {
            run_ws_session(
                shared,
                config,
                ws_url,
                options,
                credentials,
                shutdown_rx,
                initial_tx,
            )
            .await;
        });

        initial_rx.await.map_err(|_| {
            ClientError::WebSocket("WebSocket connection task stopped before startup".to_string())
        })?
    }

    fn validate_control_payload(payload: &[u8]) -> Result<()> {
        if payload.len() > MAX_CONTROL_FRAME_PAYLOAD_LEN {
            return Err(ClientError::WebSocket(format!(
                "WebSocket control frame payload exceeds {} bytes",
                MAX_CONTROL_FRAME_PAYLOAD_LEN
            )));
        }

        Ok(())
    }

    async fn send_control_frame(&self, msg: tungstenite::Message) -> Result<()> {
        let tx = self
            .shared
            .tx
            .lock()
            .expect("WebSocket sender mutex poisoned")
            .clone()
            .ok_or(ClientError::WebSocket("Not connected".to_string()))?;

        tx.send(msg)
            .await
            .map_err(|e| ClientError::WebSocket(format!("Failed to send: {}", e)))
    }

    /// Send an empty WebSocket ping frame.
    pub async fn ping(&self) -> Result<()> {
        self.ping_with_payload(Vec::new()).await
    }

    /// Send a WebSocket ping frame with a payload.
    ///
    /// WebSocket control frame payloads are limited to 125 bytes by the protocol.
    pub async fn ping_with_payload(&self, payload: impl Into<Vec<u8>>) -> Result<()> {
        let payload = payload.into();
        Self::validate_control_payload(&payload)?;
        self.send_control_frame(tungstenite::Message::Ping(payload))
            .await
    }

    /// Send a WebSocket pong frame with a payload.
    ///
    /// This is rarely needed directly because `WsClient` automatically responds
    /// to server ping frames.
    pub async fn pong_with_payload(&self, payload: impl Into<Vec<u8>>) -> Result<()> {
        let payload = payload.into();
        Self::validate_control_payload(&payload)?;
        self.send_control_frame(tungstenite::Message::Pong(payload))
            .await
    }

    /// Subscribe to channels.
    pub async fn subscribe(&self, channels: Vec<&str>) -> Result<()> {
        for channel in channels {
            self.subscribe_with_options(channel, None, None, None)
                .await?;
        }

        Ok(())
    }

    /// Send a subscription request for private RFQ V2 change hints. `Ok` means
    /// the frame was sent; observe `Subscribed` or `Error` for server acceptance.
    /// Use a periodic signed change-feed read to recover hints lost while a
    /// socket stays connected.
    #[cfg(feature = "rfq-v2")]
    pub async fn subscribe_rfq_v2(&self) -> Result<()> {
        self.subscribe_with_options("rfq_v2", None, None, None)
            .await
    }

    /// [`WsClient::subscribe_rfq_v2`] with an explicit delivery view.
    /// [`RfqV2View::Full`] delivers `RfqV2Rfq` frames carrying the account's
    /// RFQ read (decode them with
    /// [`crate::rfq_v2_recovery::rfq_v2_full_read`]), falling back to
    /// `RfqV2Changed` for a change whose read the server could not build.
    /// The view is kept across reconnects; subscribing again with another
    /// view replaces it.
    #[cfg(feature = "rfq-v2")]
    pub async fn subscribe_rfq_v2_with_view(&self, view: RfqV2View) -> Result<()> {
        let desired = DesiredSubscription::with_view("rfq_v2", None, None, None, Some(view))?;
        self.subscribe_entry(desired, false).await
    }

    /// Remove the RFQ V2 subscription, including its reconnect intent.
    #[cfg(feature = "rfq-v2")]
    pub async fn unsubscribe_rfq_v2(&self) -> Result<()> {
        self.unsubscribe(vec!["rfq_v2"]).await
    }

    /// Subscribe to a channel and retain its filters across reconnects.
    pub async fn subscribe_with_options(
        &self,
        channel: &str,
        symbols: Option<Vec<String>>,
        expiry: Option<String>,
        option_type: Option<String>,
    ) -> Result<()> {
        self.subscribe_desired(channel, symbols, expiry, option_type)
            .await
    }

    /// Subscribe to indicative market data and retain the subscription
    /// across reconnects.
    ///
    /// By default this uses `indicative_market_data_v2`, whose
    /// `IndicativeMarketDataBatch` frames carry the rows of one short batch
    /// window. If the server confirms v2 without `"batch": true` (it predates
    /// the channel), the client switches to `indicative_market_data`, one
    /// `IndicativeMarketData` frame per row. Read rows with
    /// [`crate::indicative::indicative_rows_from_value`], which handles both.
    ///
    /// The server keeps one symbol filter per channel per connection: every
    /// `Subscribe` adds symbols to it, and a filtered subscribe narrows an
    /// unfiltered one. If you also subscribe to `indicative_market_data`
    /// directly with a different filter, a fallback onto v1 shares that one
    /// server filter with your direct subscription. Use one or the other per
    /// connection when exact filters matter.
    pub async fn subscribe_indicative_market_data(
        &self,
        symbols: Option<Vec<String>>,
    ) -> Result<()> {
        let channel = if self.indicative_batched() {
            INDICATIVE_V2_CHANNEL
        } else {
            INDICATIVE_CHANNEL
        };
        self.subscribe_desired_with(channel, symbols, None, None, true)
            .await
    }

    /// Stop the subscriptions made by
    /// [`WsClient::subscribe_indicative_market_data`], on whichever channel
    /// each resolved to after a fallback, and stop restoring them after
    /// reconnects. Subscriptions made with [`WsClient::subscribe_with_options`]
    /// on either indicative channel are left alone.
    pub async fn unsubscribe_indicative_market_data(&self) -> Result<()> {
        self.release_where(|subscription| {
            if !subscription.logical_indicative {
                return Release::Keep;
            }
            subscription.logical_indicative = false;
            if subscription.direct {
                Release::Keep
            } else {
                Release::Remove
            }
        })
        .await
    }

    async fn subscribe_desired(
        &self,
        channel: &str,
        symbols: Option<Vec<String>>,
        expiry: Option<String>,
        option_type: Option<String>,
    ) -> Result<()> {
        self.subscribe_desired_with(channel, symbols, expiry, option_type, false)
            .await
    }

    async fn subscribe_desired_with(
        &self,
        channel: &str,
        symbols: Option<Vec<String>>,
        expiry: Option<String>,
        option_type: Option<String>,
        logical_indicative: bool,
    ) -> Result<()> {
        if !self.shared.started.load(Ordering::Acquire) {
            return Err(ClientError::WebSocket("Not connected".to_string()));
        }

        let desired = DesiredSubscription::new(channel, symbols, expiry, option_type)?;
        self.subscribe_entry(desired, logical_indicative).await
    }

    async fn subscribe_entry(
        &self,
        mut desired: DesiredSubscription,
        logical_indicative: bool,
    ) -> Result<()> {
        if !self.shared.started.load(Ordering::Acquire) {
            return Err(ClientError::WebSocket("Not connected".to_string()));
        }
        let channel = desired.channel.clone();
        desired.logical_indicative = logical_indicative;
        desired.direct = !logical_indicative;
        let frame = tungstenite::Message::Text(desired.subscribe.clone());
        {
            let mut subscriptions = self.shared.subscriptions.write().await;
            // One logical subscription is one channel plus its filter fields.
            // Replace any equivalent earlier entry so a reconnect replays it
            // (and its subscribe-time snapshot) once.
            // Keep any ownership claim the equivalent entry already had.
            for existing in subscriptions.values() {
                if desired.same_filter(existing) {
                    desired.absorb(existing);
                }
            }
            subscriptions.retain(|_, existing| !desired.same_filter(existing));
            subscriptions.insert(desired.subscribe.clone(), desired);
        }

        let tx = self
            .shared
            .tx
            .lock()
            .expect("WebSocket sender mutex poisoned")
            .clone();
        if let Some(tx) = tx {
            debug!("Subscribing to: {}", channel);
            tx.send(frame)
                .await
                .map_err(|e| ClientError::WebSocket(format!("Failed to send: {}", e)))?;
        }

        Ok(())
    }

    /// Unsubscribe from channels and stop restoring them after reconnects.
    ///
    /// Channels match exactly, and only subscriptions made directly (for
    /// example with [`WsClient::subscribe_with_options`]) are released. To
    /// stop a subscription made by
    /// [`WsClient::subscribe_indicative_market_data`], which may have moved
    /// from `indicative_market_data_v2` to `indicative_market_data`, use
    /// [`WsClient::unsubscribe_indicative_market_data`]. If both own the same
    /// channel and filter, the server subscription ends when both release it.
    pub async fn unsubscribe(&self, channels: Vec<&str>) -> Result<()> {
        for channel in channels {
            // Releases the direct claim; an entry the indicative helper also
            // owns stays subscribed until that claim is released too.
            self.release_where(|subscription| {
                if subscription.channel != channel {
                    return Release::Keep;
                }
                subscription.direct = false;
                if subscription.logical_indicative {
                    Release::Keep
                } else {
                    Release::Remove
                }
            })
            .await?;
        }
        Ok(())
    }

    /// Apply `release` to every stored subscription and unsubscribe the ones
    /// it says to remove.
    async fn release_where(
        &self,
        release: impl Fn(&mut DesiredSubscription) -> Release,
    ) -> Result<()> {
        if !self.shared.started.load(Ordering::Acquire) {
            return Err(ClientError::WebSocket("Not connected".to_string()));
        }

        let removed = {
            let mut subscriptions = self.shared.subscriptions.write().await;
            let keys = subscriptions
                .iter_mut()
                .filter_map(|(key, subscription)| {
                    (release(subscription) == Release::Remove).then(|| key.clone())
                })
                .collect::<Vec<_>>();
            keys.into_iter()
                .filter_map(|key| subscriptions.remove(&key))
                .collect::<Vec<_>>()
        };
        for removed in removed {
            let tx = self
                .shared
                .tx
                .lock()
                .expect("WebSocket sender mutex poisoned")
                .clone();
            if let Some(tx) = tx {
                tx.send(tungstenite::Message::Text(removed.unsubscribe))
                    .await
                    .map_err(|e| ClientError::WebSocket(format!("Failed to send: {}", e)))?;
            }
        }
        Ok(())
    }

    /// Stop reconnecting and close the current socket.
    pub async fn disconnect(&self) {
        let _ = self
            .send_control_frame(tungstenite::Message::Close(None))
            .await;
        if let Some(shutdown_tx) = self
            .shutdown_tx
            .lock()
            .expect("WebSocket shutdown mutex poisoned")
            .take()
        {
            let _ = shutdown_tx.send(true);
        }
    }

    /// Return the current connection and recovery state.
    pub fn connection_state(&self) -> WsConnectionState {
        self.shared
            .state
            .lock()
            .expect("WebSocket state mutex poisoned")
            .clone()
    }

    /// Watch connection and recovery state transitions.
    pub fn connection_state_receiver(&self) -> watch::Receiver<WsConnectionState> {
        self.shared.state_tx.subscribe()
    }

    /// Return the most recent established-session disconnect reason.
    pub fn last_disconnect_reason(&self) -> Option<WsDisconnectReason> {
        self.shared
            .last_disconnect
            .lock()
            .expect("WebSocket disconnect mutex poisoned")
            .clone()
    }

    /// Mark application-owned snapshot or REST recovery as complete.
    pub fn mark_recovered(&self) -> Result<()> {
        let mut state = self
            .shared
            .state
            .lock()
            .expect("WebSocket state mutex poisoned");
        if !matches!(*state, WsConnectionState::RecoveryRequired(_)) {
            return Err(ClientError::WebSocket(
                "No WebSocket recovery is currently required".to_string(),
            ));
        }
        *state = WsConnectionState::Ready;
        self.shared.state_tx.send_replace(WsConnectionState::Ready);
        Ok(())
    }

    /// Get all received WebSocket pong payloads.
    pub async fn get_pongs(&self) -> Vec<Vec<u8>> {
        self.shared.pongs.lock().await.clone()
    }

    /// Clear all received WebSocket pong payloads.
    pub async fn clear_pongs(&self) {
        self.shared.pongs.lock().await.clear();
    }

    /// Wait for a pong payload matching a predicate.
    pub async fn wait_for_pong<F>(&self, check: F, timeout_ms: u64) -> Option<Vec<u8>>
    where
        F: Fn(&[u8]) -> bool,
    {
        let start = std::time::Instant::now();
        let timeout = Duration::from_millis(timeout_ms);

        while start.elapsed() < timeout {
            let pongs = self.get_pongs().await;
            if let Some(pong) = pongs.iter().find(|payload| check(payload)) {
                return Some(pong.clone());
            }
            tokio::time::sleep(Duration::from_millis(50)).await;
        }

        None
    }

    /// Get all received messages.
    pub async fn get_messages(&self) -> Vec<sonic_rs::Value> {
        self.shared.messages.lock().await.clone()
    }

    /// Clear all received messages.
    pub async fn clear_messages(&self) {
        self.shared.messages.lock().await.clear();
    }

    /// Wait for a message matching a predicate.
    pub async fn wait_for_message<F>(&self, check: F, timeout_ms: u64) -> Option<sonic_rs::Value>
    where
        F: Fn(&sonic_rs::Value) -> bool,
    {
        let start = std::time::Instant::now();
        let timeout = Duration::from_millis(timeout_ms);

        while start.elapsed() < timeout {
            let messages = self.get_messages().await;
            if let Some(msg) = messages.iter().find(|m| check(m)) {
                return Some(msg.clone());
            }
            tokio::time::sleep(Duration::from_millis(50)).await;
        }

        None
    }

    /// Count messages matching a predicate.
    pub async fn count_messages<F>(&self, check: F) -> usize
    where
        F: Fn(&sonic_rs::Value) -> bool,
    {
        self.get_messages()
            .await
            .iter()
            .filter(|msg| check(msg))
            .count()
    }
}

impl Drop for WsClient {
    fn drop(&mut self) {
        if let Some(shutdown_tx) = self
            .shutdown_tx
            .lock()
            .expect("WebSocket shutdown mutex poisoned")
            .take()
        {
            let _ = shutdown_tx.send(true);
        }
    }
}

#[derive(Debug, Clone)]
enum SessionStop {
    Shutdown,
    Disconnected(WsDisconnectReason),
    NonReconnectable(WsDisconnectReason),
}

impl SessionStop {
    fn websocket_error(&self, context: &str) -> ClientError {
        match self {
            Self::Shutdown => ClientError::WebSocket(format!("{}: client stopped", context)),
            Self::Disconnected(reason) | Self::NonReconnectable(reason) => {
                ClientError::WebSocket(format!("{}: {:?}", context, reason))
            }
        }
    }
}

fn websocket_url(base_url: &str) -> Result<String> {
    let base_url = base_url.trim_end_matches('/');
    let ws_origin = if let Some(rest) = base_url.strip_prefix("https://") {
        format!("wss://{}", rest)
    } else if let Some(rest) = base_url.strip_prefix("http://") {
        format!("ws://{}", rest)
    } else if base_url.starts_with("wss://") || base_url.starts_with("ws://") {
        base_url.to_string()
    } else {
        return Err(ClientError::InvalidInput(
            "WebSocket base URL must use http, https, ws, or wss".to_string(),
        ));
    };

    if ws_origin.ends_with("/ws") {
        Ok(ws_origin)
    } else {
        Ok(format!("{}/ws", ws_origin))
    }
}

/// Why opening a WebSocket connection failed, with the source kept until the
/// session renders it at the existing `ClientError::WebSocket` boundary.
#[derive(Debug, thiserror::Error)]
#[displaystr::display]
enum ConnectError {
    Url(#[source] tungstenite::Error) = "invalid WebSocket URL: {_0}",
    MissingHost = "WebSocket URL has no host",
    UnsupportedScheme = "WebSocket URL must use ws or wss",
    Tcp(#[source] std::io::Error) = "IO error: {_0}",
    Tls(#[source] tokio_native_tls::native_tls::Error) = "TLS error: {_0}",
    /// The upgrade handshake stage. Named rather than transparent because it
    /// adds a stage to the Tungstenite error; the text is unchanged.
    Handshake(#[source] tungstenite::Error) = "{_0}",
}

/// Opens TCP, then native-tls for `wss` (the platform trust store, as before),
/// then runs the Tungstenite handshake over [`InflatingStream`].
async fn connect_socket(
    ws_url: &str,
    options: ConnectOptions,
) -> std::result::Result<(ClientSocket, tungstenite::handshake::client::Response), ConnectError> {
    let permessage_deflate = options.permessage_deflate;
    let mut request = ws_url.into_client_request().map_err(ConnectError::Url)?;
    if permessage_deflate {
        request.headers_mut().insert(
            "Sec-WebSocket-Extensions",
            HeaderValue::from_static(PERMESSAGE_DEFLATE_OFFER),
        );
    }
    let uri = request.uri();
    let host = uri.host().ok_or(ConnectError::MissingHost)?.to_string();
    let tls = match uri.scheme_str() {
        Some("wss") => true,
        Some("ws") => false,
        _ => return Err(ConnectError::UnsupportedScheme),
    };
    let port = uri.port_u16().unwrap_or(if tls { 443 } else { 80 });
    let tcp = TcpStream::connect(format!("{host}:{port}"))
        .await
        .map_err(ConnectError::Tcp)?;

    let io: Box<dyn ClientIo> = if tls {
        let domain = host.trim_start_matches('[').trim_end_matches(']');
        let connector =
            tokio_native_tls::native_tls::TlsConnector::new().map_err(ConnectError::Tls)?;
        let stream = tokio_native_tls::TlsConnector::from(connector)
            .connect(domain, tcp)
            .await
            .map_err(ConnectError::Tls)?;
        Box::new(stream)
    } else {
        Box::new(tcp)
    };

    let stream = InflatingStream::new(io, permessage_deflate, MAX_FRAME_LEN, MAX_MESSAGE_LEN);
    client_async(request, stream)
        .await
        .map_err(ConnectError::Handshake)
}

fn reconnect_delay(config: WsClientConfig, attempt: u32) -> Duration {
    let multiplier = 1_u32 << attempt.min(31);
    let ceiling = config
        .reconnect_initial_delay
        .saturating_mul(multiplier)
        .min(config.reconnect_max_delay);
    ceiling.mul_f64(0.5 + rand::random::<f64>() * 0.5)
}

fn set_state(shared: &WsClientShared, next: WsConnectionState) {
    *shared.state.lock().expect("WebSocket state mutex poisoned") = next.clone();
    shared.state_tx.send_replace(next);
}

fn finish_session(shared: &WsClientShared) {
    *shared.tx.lock().expect("WebSocket sender mutex poisoned") = None;
    #[cfg(feature = "rfq-v2")]
    {
        *shared
            .rfq_v2_grant
            .lock()
            .expect("WebSocket RFQ grant mutex poisoned") = None;
    }
    shared.started.store(false, Ordering::Release);
    set_state(shared, WsConnectionState::Disconnected);
}

fn record_disconnect(shared: &WsClientShared, reason: WsDisconnectReason) {
    *shared
        .last_disconnect
        .lock()
        .expect("WebSocket disconnect mutex poisoned") = Some(reason);
}

async fn record_text(shared: &WsClientShared, text: &str) -> Option<sonic_rs::Value> {
    debug!("WS received: {}", text);
    let json = sonic_rs::from_str::<sonic_rs::Value>(text).ok()?;
    if is_unbatched_v2_confirmation(&json) {
        // The server accepted the name but does not know the channel, so no
        // data would ever arrive on it. Switch to v1 at the next safe point.
        warn!("server lacks indicative_market_data_v2; falling back to indicative_market_data");
        shared.v2_unsupported.store(true, Ordering::Release);
        shared.v2_fallback_pending.store(true, Ordering::Release);
    }
    shared.messages.lock().await.push(json.clone());
    Some(json)
}

/// The server cannot deliver `indicative_market_data_v2`: it confirmed the
/// channel without `"batch": true` (servers that predate the channel confirm
/// any name), or it rejected the channel as unknown.
fn is_unbatched_v2_confirmation(json: &sonic_rs::Value) -> bool {
    let channel_is_v2 =
        json.get("channel").and_then(|value| value.as_str()) == Some(INDICATIVE_V2_CHANNEL);
    match json.get("type").and_then(|value| value.as_str()) {
        Some("Subscribed") => {
            channel_is_v2 && json.get("batch").and_then(|value| value.as_bool()) != Some(true)
        }
        Some("Error") => {
            channel_is_v2
                && json.get("code").and_then(|value| value.as_str())
                    == Some(hypercall_ws_protocol::UNKNOWN_CHANNEL_CODE)
        }
        _ => false,
    }
}

/// Move every v2 subscription made by
/// [`WsClient::subscribe_indicative_market_data`] to v1 with the same filter.
/// Subscriptions made directly on `indicative_market_data_v2` are the
/// caller's to manage and are left alone. Returns
/// the `Unsubscribe` frames for the dead v2 subscriptions and the new v1
/// entries, which the caller subscribes (and, during a reconnect, waits for).
async fn take_v2_fallback(
    shared: &WsClientShared,
) -> std::result::Result<(Vec<String>, BTreeMap<String, DesiredSubscription>), SessionStop> {
    let mut subscriptions = shared.subscriptions.write().await;
    take_v2_fallback_locked(shared, &mut subscriptions)
}

/// [`take_v2_fallback`] under a guard the caller already holds, so it can keep
/// holding it while the replacements are subscribed.
fn take_v2_fallback_locked(
    shared: &WsClientShared,
    subscriptions: &mut BTreeMap<String, DesiredSubscription>,
) -> std::result::Result<(Vec<String>, BTreeMap<String, DesiredSubscription>), SessionStop> {
    let mut unsubscribes = Vec::new();
    let mut replacements = BTreeMap::new();
    if !shared.v2_fallback_pending.swap(false, Ordering::AcqRel) {
        return Ok((unsubscribes, replacements));
    }
    let v2_keys: Vec<String> = subscriptions
        .iter()
        .filter(|(_, desired)| {
            desired.channel == INDICATIVE_V2_CHANNEL && desired.logical_indicative
        })
        .map(|(key, _)| key.clone())
        .collect();
    for key in v2_keys {
        let Some(mut v2) = subscriptions.remove(&key) else {
            continue;
        };
        if v2.direct {
            // A direct claim on the same v2 entry is the caller's to manage:
            // keep it (and the server subscription) and move only the
            // helper's claim to v1.
            v2.logical_indicative = false;
            subscriptions.insert(key, v2.clone());
        } else {
            unsubscribes.push(v2.unsubscribe.clone());
        }
        let mut v1 = DesiredSubscription::new(
            INDICATIVE_CHANNEL,
            v2.symbols.clone(),
            v2.expiry.clone(),
            v2.option_type.clone(),
        )
        .map_err(|error| {
            SessionStop::Disconnected(WsDisconnectReason::Protocol(error.to_string()))
        })?;
        v1.logical_indicative = true;
        // A direct v1 subscription with the same filter keeps its claim: the
        // merged entry stays until both owners release it.
        for existing in subscriptions.values() {
            if v1.same_filter(existing) {
                v1.absorb(existing);
            }
        }
        subscriptions.retain(|_, existing| !v1.same_filter(existing));
        subscriptions.insert(v1.subscribe.clone(), v1.clone());
        replacements.insert(v1.subscribe.clone(), v1);
    }
    Ok((unsubscribes, replacements))
}

/// Steady-state fallback: switch v2 subscriptions to v1 on the live socket.
/// Their confirmations are recorded like any other message.
async fn apply_v2_fallback<S>(
    socket: &mut S,
    shared: &WsClientShared,
) -> std::result::Result<(), SessionStop>
where
    S: futures::Sink<tungstenite::Message, Error = tungstenite::Error> + Unpin,
{
    let (unsubscribes, replacements) = take_v2_fallback(shared).await?;
    let frames = unsubscribes.into_iter().chain(
        replacements
            .into_values()
            .map(|replacement| replacement.subscribe),
    );
    for frame in frames {
        socket
            .send(tungstenite::Message::Text(frame))
            .await
            .map_err(|error| {
                SessionStop::Disconnected(WsDisconnectReason::Transport(error.to_string()))
            })?;
    }
    Ok(())
}

fn disconnect_reason_from_close(
    frame: Option<tungstenite::protocol::CloseFrame<'_>>,
) -> WsDisconnectReason {
    let Some(frame) = frame else {
        return WsDisconnectReason::EndOfStream;
    };
    let reason = frame.reason.into_owned();
    if let Ok(slow_consumer) = serde_json::from_str::<WsSlowConsumerCloseReason>(&reason) {
        return WsDisconnectReason::SlowConsumer(slow_consumer);
    }

    WsDisconnectReason::CloseFrame {
        code: frame.code.into(),
        reason,
    }
}

async fn authenticate_socket<S>(
    socket: &mut S,
    shared: &WsClientShared,
    wallet: &str,
    shutdown_rx: &mut watch::Receiver<bool>,
    timeout: Duration,
) -> std::result::Result<(), SessionStop>
where
    S: futures::Sink<tungstenite::Message, Error = tungstenite::Error>
        + futures::Stream<Item = std::result::Result<tungstenite::Message, tungstenite::Error>>
        + Unpin,
{
    let auth_msg = sonic_rs::to_string(&WsMessage::Authenticate {
        wallet: wallet.to_string(),
    })
    .map_err(|error| {
        SessionStop::Disconnected(WsDisconnectReason::Protocol(format!(
            "failed to serialize authentication: {}",
            error
        )))
    })?;
    socket
        .send(tungstenite::Message::Text(auth_msg))
        .await
        .map_err(|error| {
            SessionStop::Disconnected(WsDisconnectReason::Transport(error.to_string()))
        })?;

    let deadline = tokio::time::sleep(timeout);
    tokio::pin!(deadline);
    loop {
        tokio::select! {
            changed = shutdown_rx.changed() => {
                if changed.is_err() || *shutdown_rx.borrow() {
                    return Err(SessionStop::Shutdown);
                }
            }
            _ = &mut deadline => {
                return Err(SessionStop::Disconnected(WsDisconnectReason::Protocol(
                    "timed out waiting for authentication response".to_string(),
                )));
            }
            incoming = socket.next() => {
                match incoming {
                    Some(Ok(tungstenite::Message::Text(text))) => {
                        let Some(json) = record_text(shared, &text).await else {
                            continue;
                        };
                        match json.get("type").and_then(|value| value.as_str()) {
                            Some("Authenticated") => {
                                let authenticated_wallet = json
                                    .get("wallet")
                                    .and_then(|value| value.as_str())
                                    .ok_or_else(|| SessionStop::Disconnected(
                                        WsDisconnectReason::Protocol(
                                            "authentication response omitted wallet".to_string(),
                                        )
                                    ))?;
                                if !authenticated_wallet.eq_ignore_ascii_case(wallet) {
                                    return Err(SessionStop::Disconnected(
                                        WsDisconnectReason::Protocol(format!(
                                            "authenticated wallet mismatch: expected {}, received {}",
                                            wallet, authenticated_wallet
                                        )),
                                    ));
                                }
                                return Ok(());
                            }
                            Some("Error") => {
                                let message = json
                                    .get("message")
                                    .and_then(|value| value.as_str())
                                    .unwrap_or("authentication failed");
                                return Err(SessionStop::Disconnected(
                                    WsDisconnectReason::Protocol(message.to_string()),
                                ));
                            }
                            _ => {}
                        }
                    }
                    Some(Ok(tungstenite::Message::Ping(payload))) => {
                        socket.send(tungstenite::Message::Pong(payload)).await.map_err(|error| {
                            SessionStop::Disconnected(WsDisconnectReason::Transport(error.to_string()))
                        })?;
                    }
                    Some(Ok(tungstenite::Message::Pong(payload))) => {
                        shared.pongs.lock().await.push(payload);
                    }
                    Some(Ok(tungstenite::Message::Close(frame))) => {
                        return Err(SessionStop::Disconnected(disconnect_reason_from_close(frame)));
                    }
                    Some(Err(error)) => {
                        return Err(SessionStop::Disconnected(WsDisconnectReason::Transport(
                            error.to_string(),
                        )));
                    }
                    None => return Err(SessionStop::Disconnected(WsDisconnectReason::EndOfStream)),
                    _ => {}
                }
            }
        }
    }
}

#[cfg(feature = "rfq-v2")]
async fn authenticate_rfq_v2_socket<S>(
    socket: &mut S,
    shared: &WsClientShared,
    grant: &RfqV2SocketGrant,
    shutdown_rx: &mut watch::Receiver<bool>,
    timeout: Duration,
) -> std::result::Result<(), SessionStop>
where
    S: futures::Sink<tungstenite::Message, Error = tungstenite::Error>
        + futures::Stream<Item = std::result::Result<tungstenite::Message, tungstenite::Error>>
        + Unpin,
{
    let auth_msg = sonic_rs::to_string(&WsMessage::AuthenticateRfqV2 {
        token: grant.token.clone(),
    })
    .map_err(|error| {
        SessionStop::NonReconnectable(WsDisconnectReason::Protocol(format!(
            "failed to serialize RFQ authentication: {error}"
        )))
    })?;
    socket
        .send(tungstenite::Message::Text(auth_msg))
        .await
        .map_err(|error| {
            SessionStop::Disconnected(WsDisconnectReason::Transport(error.to_string()))
        })?;

    let deadline = tokio::time::sleep(timeout);
    tokio::pin!(deadline);
    loop {
        tokio::select! {
            changed = shutdown_rx.changed() => {
                if changed.is_err() || *shutdown_rx.borrow() {
                    return Err(SessionStop::Shutdown);
                }
            }
            _ = &mut deadline => {
                return Err(SessionStop::Disconnected(WsDisconnectReason::Protocol(
                    "timed out waiting for RFQ authentication response".to_string(),
                )));
            }
            incoming = socket.next() => {
                match incoming {
                    Some(Ok(tungstenite::Message::Text(text))) => {
                        let Some(json) = record_text(shared, &text).await else {
                            continue;
                        };
                        match json.get("type").and_then(|value| value.as_str()) {
                            Some("RfqV2Authenticated") => {
                                let account = json
                                    .get("account")
                                    .and_then(|value| value.as_str())
                                    .ok_or_else(|| SessionStop::NonReconnectable(
                                        WsDisconnectReason::Protocol(
                                            "RFQ authentication response omitted account".to_string(),
                                        )
                                    ))?;
                                if !account.eq_ignore_ascii_case(&grant.account) {
                                    return Err(SessionStop::NonReconnectable(
                                        WsDisconnectReason::Protocol(
                                            "RFQ authenticated account does not match signed grant".to_string(),
                                        ),
                                    ));
                                }
                                return Ok(());
                            }
                            Some("Error") => {
                                let message = json
                                    .get("message")
                                    .and_then(|value| value.as_str())
                                    .unwrap_or("RFQ authentication failed");
                                return Err(SessionStop::NonReconnectable(
                                    WsDisconnectReason::Protocol(message.to_string()),
                                ));
                            }
                            _ => {}
                        }
                    }
                    Some(Ok(tungstenite::Message::Ping(payload))) => {
                        socket.send(tungstenite::Message::Pong(payload)).await.map_err(|error| {
                            SessionStop::Disconnected(WsDisconnectReason::Transport(error.to_string()))
                        })?;
                    }
                    Some(Ok(tungstenite::Message::Pong(payload))) => {
                        shared.pongs.lock().await.push(payload);
                    }
                    Some(Ok(tungstenite::Message::Close(frame))) => {
                        return Err(SessionStop::Disconnected(disconnect_reason_from_close(frame)));
                    }
                    Some(Err(error)) => {
                        return Err(SessionStop::Disconnected(WsDisconnectReason::Transport(error.to_string())));
                    }
                    None => return Err(SessionStop::Disconnected(WsDisconnectReason::EndOfStream)),
                    _ => {}
                }
            }
        }
    }
}

async fn replay_subscriptions<S>(
    socket: &mut S,
    shared: &WsClientShared,
    subscriptions: &BTreeMap<String, DesiredSubscription>,
    shutdown_rx: &mut watch::Receiver<bool>,
    timeout: Duration,
) -> std::result::Result<(), SessionStop>
where
    S: futures::Sink<tungstenite::Message, Error = tungstenite::Error>
        + futures::Stream<Item = std::result::Result<tungstenite::Message, tungstenite::Error>>
        + Unpin,
{
    let mut pending = BTreeMap::<String, usize>::new();
    for subscription in subscriptions.values() {
        socket
            .send(tungstenite::Message::Text(subscription.subscribe.clone()))
            .await
            .map_err(|error| {
                SessionStop::Disconnected(WsDisconnectReason::Transport(error.to_string()))
            })?;
        *pending.entry(subscription.channel.clone()).or_default() += 1;
    }

    let deadline = tokio::time::sleep(timeout);
    tokio::pin!(deadline);
    while !pending.is_empty() {
        tokio::select! {
            changed = shutdown_rx.changed() => {
                if changed.is_err() || *shutdown_rx.borrow() {
                    return Err(SessionStop::Shutdown);
                }
            }
            _ = &mut deadline => {
                return Err(SessionStop::NonReconnectable(WsDisconnectReason::Protocol(format!(
                    "timed out restoring subscriptions: {}",
                    pending
                        .into_iter()
                        .map(|(channel, count)| format!("{} ({})", channel, count))
                        .collect::<Vec<_>>()
                        .join(", ")
                ))));
            }
            incoming = socket.next() => {
                match incoming {
                    Some(Ok(tungstenite::Message::Text(text))) => {
                        let Some(json) = record_text(shared, &text).await else {
                            continue;
                        };
                        // Whether a v2 refusal (unmarked confirmation or
                        // `unknown_channel`) can be absorbed by the logical fallback.
                        // It cannot say which v2 request it answers, so any direct
                        // v2 subscription being restored makes it a failure.
                        let v2_refusal = is_unbatched_v2_confirmation(&json);
                        let v2_all_logical = subscriptions
                            .values()
                            .filter(|desired| desired.channel == INDICATIVE_V2_CHANNEL)
                            .all(|desired| desired.logical_indicative && !desired.direct);
                        if v2_refusal && !v2_all_logical {
                            return Err(SessionStop::NonReconnectable(
                                WsDisconnectReason::Protocol(format!(
                                    "server does not support {INDICATIVE_V2_CHANNEL}; \
                                     direct subscriptions to it cannot be restored"
                                )),
                            ));
                        }
                        match json.get("type").and_then(|value| value.as_str()) {
                            Some("Subscribed") => {
                                if let Some(channel) = json.get("channel").and_then(|value| value.as_str()) {
                                    if let Some(count) = pending.get_mut(channel) {
                                        *count -= 1;
                                        if *count == 0 {
                                            pending.remove(channel);
                                        }
                                    }
                                }
                            }
                            // A logical v2 subscription rejected by the server falls
                            // back to v1 once replay finishes.
                            Some("Error") if v2_refusal => {
                                if let Some(count) = pending.get_mut(INDICATIVE_V2_CHANNEL) {
                                    *count -= 1;
                                    if *count == 0 {
                                        pending.remove(INDICATIVE_V2_CHANNEL);
                                    }
                                }
                            }
                            Some("Error") => {
                                let message = json
                                    .get("message")
                                    .and_then(|value| value.as_str())
                                    .unwrap_or("subscription restoration failed");
                                return Err(SessionStop::NonReconnectable(
                                    WsDisconnectReason::Protocol(message.to_string()),
                                ));
                            }
                            _ => {}
                        }
                    }
                    Some(Ok(tungstenite::Message::Ping(payload))) => {
                        socket.send(tungstenite::Message::Pong(payload)).await.map_err(|error| {
                            SessionStop::Disconnected(WsDisconnectReason::Transport(error.to_string()))
                        })?;
                    }
                    Some(Ok(tungstenite::Message::Pong(payload))) => {
                        shared.pongs.lock().await.push(payload);
                    }
                    Some(Ok(tungstenite::Message::Close(frame))) => {
                        return Err(SessionStop::Disconnected(disconnect_reason_from_close(frame)));
                    }
                    Some(Err(error)) => {
                        return Err(SessionStop::Disconnected(WsDisconnectReason::Transport(
                            error.to_string(),
                        )));
                    }
                    None => return Err(SessionStop::Disconnected(WsDisconnectReason::EndOfStream)),
                    _ => {}
                }
            }
        }
    }
    Ok(())
}

async fn run_connected_socket<S>(
    socket: &mut S,
    shared: &WsClientShared,
    outbound_rx: &mut mpsc::Receiver<tungstenite::Message>,
    shutdown_rx: &mut watch::Receiver<bool>,
) -> SessionStop
where
    S: futures::Sink<tungstenite::Message, Error = tungstenite::Error>
        + futures::Stream<Item = std::result::Result<tungstenite::Message, tungstenite::Error>>
        + Unpin,
{
    // A lapsed RFQ V2 grant does not end the session: the server keeps the
    // subscription and sends `rfq_v2_grant_expired`, which is recorded like
    // any message, and `reauthenticate_rfq_v2` sends a fresh grant.
    loop {
        tokio::select! {
            changed = shutdown_rx.changed() => {
                if changed.is_err() || *shutdown_rx.borrow() {
                    let _ = socket.send(tungstenite::Message::Close(None)).await;
                    return SessionStop::Shutdown;
                }
            }
            outbound = outbound_rx.recv() => {
                let Some(outbound) = outbound else {
                    return SessionStop::Shutdown;
                };
                if let Err(error) = socket.send(outbound).await {
                    return SessionStop::Disconnected(WsDisconnectReason::Transport(
                        error.to_string(),
                    ));
                }
            }
            incoming = socket.next() => {
                match incoming {
                    Some(Ok(tungstenite::Message::Text(text))) => {
                        let _ = record_text(shared, &text).await;
                        if let Err(stop) = apply_v2_fallback(socket, shared).await {
                            return stop;
                        }
                    }
                    Some(Ok(tungstenite::Message::Ping(payload))) => {
                        if let Err(error) = socket.send(tungstenite::Message::Pong(payload)).await {
                            return SessionStop::Disconnected(WsDisconnectReason::Transport(
                                error.to_string(),
                            ));
                        }
                    }
                    Some(Ok(tungstenite::Message::Pong(payload))) => {
                        shared.pongs.lock().await.push(payload);
                    }
                    Some(Ok(tungstenite::Message::Close(frame))) => {
                        return SessionStop::Disconnected(disconnect_reason_from_close(frame));
                    }
                    Some(Err(error)) => {
                        return SessionStop::Disconnected(WsDisconnectReason::Transport(
                            error.to_string(),
                        ));
                    }
                    None => return SessionStop::Disconnected(WsDisconnectReason::EndOfStream),
                    _ => {}
                }
            }
        }
    }
}

#[expect(clippy::too_many_lines, reason = "pre-existing; split pending")]
async fn run_ws_session(
    shared: Arc<WsClientShared>,
    config: WsClientConfig,
    ws_url: String,
    options: ConnectOptions,
    credentials: SessionCredentials,
    mut shutdown_rx: watch::Receiver<bool>,
    initial_tx: oneshot::Sender<Result<()>>,
) {
    let mut initial_tx = Some(initial_tx);
    let mut reconnecting = false;
    let mut attempt = 0_u32;

    loop {
        if reconnecting {
            let delay = reconnect_delay(config, attempt);
            set_state(&shared, WsConnectionState::Reconnecting { attempt, delay });
            tokio::select! {
                changed = shutdown_rx.changed() => {
                    if changed.is_err() || *shutdown_rx.borrow() {
                        finish_session(&shared);
                        return;
                    }
                }
                _ = tokio::time::sleep(delay) => {}
            }
        }

        if rfq_v2_expires_at_ms(&shared)
            .is_some_and(|expires_at_ms| current_unix_ms().is_none_or(|now| now >= expires_at_ms))
        {
            let reason = WsDisconnectReason::Protocol(
                "RFQ V2 read grant expired; sign a fresh grant".to_string(),
            );
            record_disconnect(&shared, reason.clone());
            finish_session(&shared);
            if let Some(initial_tx) = initial_tx.take() {
                let _ = initial_tx.send(Err(ClientError::WebSocket(format!("{reason:?}"))));
            }
            return;
        }

        set_state(&shared, WsConnectionState::Connecting { attempt });
        debug!("Connecting to WebSocket: {}", ws_url);
        let connect_result = tokio::select! {
            changed = shutdown_rx.changed() => {
                if changed.is_err() || *shutdown_rx.borrow() {
                    finish_session(&shared);
                    if let Some(initial_tx) = initial_tx.take() {
                        let _ = initial_tx.send(Err(ClientError::WebSocket(
                            "WebSocket connection stopped before startup".to_string(),
                        )));
                    }
                    return;
                }
                continue;
            }
            result = connect_socket(&ws_url, options) => result,
        };

        let (mut socket, response) = match connect_result {
            Ok(connection) => connection,
            Err(error) => {
                let reason = WsDisconnectReason::Transport(error.to_string());
                record_disconnect(&shared, reason.clone());
                if !reconnecting {
                    finish_session(&shared);
                    if let Some(initial_tx) = initial_tx.take() {
                        let _ = initial_tx.send(Err(ClientError::WebSocket(format!(
                            "Failed to connect: {}",
                            error
                        ))));
                    }
                    return;
                }
                attempt = attempt.saturating_add(1);
                continue;
            }
        };
        info!(
            permessage_deflate = socket.get_ref().deflate_negotiated(),
            "WebSocket connected, status: {}",
            response.status()
        );

        let handshake_result = async {
            if let Some(wallet) = credentials.wallet.as_deref() {
                set_state(&shared, WsConnectionState::Authenticating);
                authenticate_socket(
                    &mut socket,
                    &shared,
                    wallet,
                    &mut shutdown_rx,
                    config.authentication_timeout,
                )
                .await?;
                info!("WebSocket authenticated as wallet: {}", wallet);
            }

            #[cfg(feature = "rfq-v2")]
            if let Some(grant) = current_rfq_v2_grant(&shared).as_ref() {
                set_state(&shared, WsConnectionState::Authenticating);
                authenticate_rfq_v2_socket(
                    &mut socket,
                    &shared,
                    grant,
                    &mut shutdown_rx,
                    config.authentication_timeout,
                )
                .await?;
            }

            // One write guard from the first replay until the sender is
            // published: a subscribe or unsubscribe from another task waits
            // and then runs against the live socket, so nothing it changes is
            // missed by the replay or the v2 fallback below.
            let mut subscriptions = shared.subscriptions.write().await;
            if !subscriptions.is_empty() {
                set_state(
                    &shared,
                    WsConnectionState::Resubscribing {
                        channels: subscriptions.len(),
                    },
                );
                replay_subscriptions(
                    &mut socket,
                    &shared,
                    &subscriptions,
                    &mut shutdown_rx,
                    config.subscription_timeout,
                )
                .await?;
            }
            // A v2 confirmation without the marker during replay: switch
            // those subscriptions to v1, and wait for the v1 confirmations
            // like the rest of the replay, before reporting the session ready.
            let (unsubscribes, replacements) =
                take_v2_fallback_locked(&shared, &mut subscriptions)?;
            for frame in unsubscribes {
                socket
                    .send(tungstenite::Message::Text(frame))
                    .await
                    .map_err(|error| {
                        SessionStop::Disconnected(WsDisconnectReason::Transport(error.to_string()))
                    })?;
            }
            if !replacements.is_empty() {
                replay_subscriptions(
                    &mut socket,
                    &shared,
                    &replacements,
                    &mut shutdown_rx,
                    config.subscription_timeout,
                )
                .await?;
            }

            let mut recovery_plan = WsRecoveryPlan::default();
            for subscription in subscriptions.values() {
                recovery_plan.include_channel(&subscription.channel);
            }
            let (tx, outbound_rx) = mpsc::channel(OUTBOUND_CONTROL_CAPACITY);
            *shared.tx.lock().expect("WebSocket sender mutex poisoned") = Some(tx);
            if reconnecting && !recovery_plan.is_empty() {
                set_state(&shared, WsConnectionState::RecoveryRequired(recovery_plan));
            } else {
                set_state(&shared, WsConnectionState::Ready);
            }
            drop(subscriptions);
            Ok::<_, SessionStop>(outbound_rx)
        }
        .await;

        let mut outbound_rx = match handshake_result {
            Ok(outbound_rx) => outbound_rx,
            Err(SessionStop::Shutdown) => {
                finish_session(&shared);
                if let Some(initial_tx) = initial_tx.take() {
                    let _ = initial_tx.send(Err(ClientError::WebSocket(
                        "WebSocket connection stopped before startup".to_string(),
                    )));
                }
                return;
            }
            Err(SessionStop::NonReconnectable(reason)) => {
                record_disconnect(&shared, reason.clone());
                finish_session(&shared);
                if let Some(initial_tx) = initial_tx.take() {
                    let _ = initial_tx.send(Err(ClientError::WebSocket(format!(
                        "WebSocket handshake failed: {:?}",
                        reason
                    ))));
                }
                return;
            }
            Err(stop) => {
                if let SessionStop::Disconnected(reason) = &stop {
                    record_disconnect(&shared, reason.clone());
                }
                if !reconnecting {
                    finish_session(&shared);
                    if let Some(initial_tx) = initial_tx.take() {
                        let _ = initial_tx
                            .send(Err(stop.websocket_error("WebSocket handshake failed")));
                    }
                    return;
                }
                attempt = attempt.saturating_add(1);
                continue;
            }
        };

        let was_reconnect = reconnecting;
        if let Some(initial_tx) = initial_tx.take() {
            let _ = initial_tx.send(Ok(()));
        }
        reconnecting = true;
        let connected_at = tokio::time::Instant::now();

        match run_connected_socket(&mut socket, &shared, &mut outbound_rx, &mut shutdown_rx).await {
            SessionStop::Shutdown => {
                finish_session(&shared);
                return;
            }
            SessionStop::NonReconnectable(reason) => {
                record_disconnect(&shared, reason);
                finish_session(&shared);
                return;
            }
            SessionStop::Disconnected(reason) => {
                warn!(?reason, "WebSocket disconnected; scheduling reconnect");
                record_disconnect(&shared, reason);
                *shared.tx.lock().expect("WebSocket sender mutex poisoned") = None;
                if !was_reconnect || connected_at.elapsed() >= config.reconnect_reset_after {
                    attempt = 0;
                } else {
                    attempt = attempt.saturating_add(1);
                }
            }
        }
    }
}

impl Default for WsClient {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
#[path = "websocket_reconnect_test.rs"]
mod reconnect_tests;

#[cfg(test)]
#[path = "websocket_deflate_test.rs"]
mod deflate_tests;

#[cfg(test)]
#[path = "websocket_test.rs"]
mod tests;