maxt 0.2.1

One Rust API for Upbit, Bithumb, Binance, and Hyperliquid market data, accounts, and orders.
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
//! Shared WebSocket connection lifecycle for provider adapters.
//!
//! Headers and subscription frames are recreated for every handshake. Heartbeats
//! continue while backpressure waits for the consumer, and inbound silence
//! triggers reconnects. Backoff resets only after inbound traffic, while the
//! reconnect-attempt budget never resets. [`Overflow::DropNewest`] may discard
//! data or errors, but a reconnect notification remains pending until delivered.

use std::pin::Pin;
use std::task::{Context, Poll};
use std::time::Duration;

use futures_core::Stream;
#[cfg(all(test, not(target_arch = "wasm32")))]
use futures_util::{SinkExt, StreamExt};
use tokio::sync::{mpsc, watch};
#[cfg(all(test, not(target_arch = "wasm32")))]
use tokio_tungstenite::tungstenite::Message;

use crate::error::{Error, Result};
use crate::types::{Overflow, StreamConfig};

#[cfg(target_arch = "wasm32")]
#[path = "ws/browser.rs"]
mod platform;
#[cfg(not(target_arch = "wasm32"))]
#[path = "ws/native.rs"]
mod platform;

use platform::{Idle, Pulse, Socket};

/// Events emitted by a WebSocket session.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum WsCommand {
    /// A text frame arrived.
    Text(String),
    /// A binary frame arrived.
    Binary(Vec<u8>),
    /// The socket reconnected and subscription frames were sent again.
    Reconnected,
}

/// Creates fresh headers for each opening handshake.
pub(crate) type WsHeaders = Box<dyn Fn() -> Result<Vec<(String, String)>> + Send + Sync>;

/// Creates fresh subscription frames for each connection.
pub(crate) type WsSubscribe = Box<dyn Fn() -> Result<Vec<String>> + Send + Sync>;

/// How to open one connection.
pub(crate) struct WsConnect {
    /// The `wss://` URL to open.
    pub(crate) url: String,
    /// Per-handshake headers, or `None` for no custom headers.
    pub(crate) headers: Option<WsHeaders>,
    /// Frames created and sent immediately after each handshake.
    pub(crate) subscribe: WsSubscribe,
    /// Optional heartbeat and provider-specific idle-timeout floor.
    pub(crate) heartbeat: Option<Heartbeat>,
}

impl WsConnect {
    /// Reuses immutable subscription frames across connections.
    ///
    /// Signed, nonce-bearing, or time-sensitive frames require a custom
    /// [`WsSubscribe`] instead.
    pub(crate) fn fixed(frames: Vec<String>) -> WsSubscribe {
        Box::new(move || Ok(frames.clone()))
    }
}

/// Client heartbeat settings for one connection.
#[derive(Debug, Clone)]
pub(crate) struct Heartbeat {
    /// Delay between heartbeat frames.
    pub(crate) interval: Duration,
    /// What one heartbeat puts on the wire.
    pub(crate) frame: HeartbeatFrame,
    /// Minimum idle timeout supported by the provider's liveness cadence.
    ///
    /// This raises a smaller [`StreamConfig::idle_timeout_ms`] value.
    pub(crate) min_idle_timeout: Duration,
}

/// Frame kind used for a provider heartbeat.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum HeartbeatFrame {
    /// An application-level text heartbeat.
    Text(&'static str),
    /// A protocol-level WebSocket ping.
    Ping,
}

#[cfg(all(test, not(target_arch = "wasm32")))]
impl HeartbeatFrame {
    fn message(self) -> Message {
        match self {
            Self::Text(text) => Message::Text(text.into()),
            Self::Ping => Message::Ping(Vec::new().into()),
        }
    }
}

/// Signals a WebSocket lifecycle task and waits until it has stopped.
#[derive(Clone)]
pub(crate) struct WsCloseHandle {
    cancel: watch::Sender<bool>,
    completed: watch::Receiver<bool>,
}

impl WsCloseHandle {
    fn signal(&self) {
        self.cancel.send_if_modified(|cancelled| {
            if *cancelled {
                false
            } else {
                *cancelled = true;
                true
            }
        });
    }

    pub(crate) async fn close(&self) -> Result<()> {
        self.signal();
        let mut completed = self.completed.clone();
        while !*completed.borrow_and_update() {
            completed.changed().await.map_err(|_| {
                Error::adapter("WebSocket task ended without publishing completion")
            })?;
        }
        Ok(())
    }
}

fn close_channels() -> (WsCloseHandle, watch::Receiver<bool>, watch::Sender<bool>) {
    let (cancel, cancelled) = watch::channel(false);
    let (completion, completed) = watch::channel(false);
    (WsCloseHandle { cancel, completed }, cancelled, completion)
}

/// Waits until cancellation has been signalled.
async fn wait_for_cancel(cancelled: &mut watch::Receiver<bool>) {
    if *cancelled.borrow_and_update() {
        return;
    }
    let _ = cancelled.changed().await;
}

/// A live WebSocket session exposed as a frame stream.
///
/// Dropping the receiver stops the background task and closes its socket.
pub(crate) struct WsSession {
    events: mpsc::Receiver<Result<WsCommand>>,
    close: WsCloseHandle,
}

impl WsSession {
    pub(crate) fn close_handle(&self) -> WsCloseHandle {
        self.close.clone()
    }
}

impl std::fmt::Debug for WsSession {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("WsSession").finish_non_exhaustive()
    }
}

impl Stream for WsSession {
    type Item = Result<WsCommand>;

    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        self.events.poll_recv(cx)
    }
}

impl Drop for WsSession {
    fn drop(&mut self) {
        self.close.signal();
    }
}

/// Opens the initial connection and starts its lifecycle task.
#[cfg(target_arch = "wasm32")]
pub(crate) async fn connect(connect: WsConnect, config: &StreamConfig) -> Result<WsSession> {
    send_wrapper::SendWrapper::new(connect_inner(connect, config)).await
}

/// Opens the initial connection and starts its lifecycle task.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) async fn connect(connect: WsConnect, config: &StreamConfig) -> Result<WsSession> {
    connect_inner(connect, config).await
}

async fn connect_inner(connect: WsConnect, config: &StreamConfig) -> Result<WsSession> {
    let (sender, events) = mpsc::channel(config.buffer_size.max(1));
    let (close, cancelled, completed) = close_channels();
    let config = config.clone();

    // Initial connection failures are returned directly to the caller.
    let socket = open(&connect, &config).await?;

    platform::spawn(async move {
        run(connect, config, socket, sender, cancelled).await;
        completed.send_replace(true);
    });

    Ok(WsSession { events, close })
}

async fn open(connect: &WsConnect, config: &StreamConfig) -> Result<Socket> {
    platform::open(connect, config).await
}

enum SocketMessage {
    Text(String),
    Binary(Vec<u8>),
    /// Protocol control traffic that only resets the idle timer.
    #[cfg(not(target_arch = "wasm32"))]
    Activity,
    Closed,
}

/// Returns the caller timeout raised to the provider's minimum when necessary.
fn idle_timeout(config: &StreamConfig, heartbeat: Option<&Heartbeat>) -> Duration {
    let asked = Duration::from_millis(config.idle_timeout_ms);
    let floor = heartbeat.map_or(Duration::ZERO, |heartbeat| heartbeat.min_idle_timeout);

    asked.max(floor)
}

/// Returns whether consecutive mute reconnects should be reported.
fn worth_reporting(consecutive_failures: u32) -> bool {
    consecutive_failures >= RECONNECT_FAILURES_BEFORE_REPORTING
}

/// Consecutive mute reconnects tolerated before reporting transport errors.
const RECONNECT_FAILURES_BEFORE_REPORTING: u32 = 3;

async fn run(
    connect: WsConnect,
    config: StreamConfig,
    mut socket: Socket,
    sender: mpsc::Sender<Result<WsCommand>>,
    mut cancelled: watch::Receiver<bool>,
) {
    let idle_timeout = idle_timeout(&config, connect.heartbeat.as_ref());
    // Total reconnect budget; inbound traffic does not reset it.
    let mut attempt = 0_u32;
    // Consecutive mute reconnects scale backoff and error reporting.
    let mut mute = 0_u32;
    // A reconnected socket must notify the consumer before new data.
    let mut reconnected = false;
    let mut pump_cancelled = cancelled.clone();

    loop {
        let pumped = tokio::select! {
            biased;
            () = wait_for_cancel(&mut cancelled) => return,
            pumped = pump(
                &mut socket,
                &sender,
                idle_timeout,
                &connect,
                &config,
                std::mem::take(&mut reconnected),
                &mut pump_cancelled,
            ) => pumped,
        };
        let carried = match pumped {
            Pump::Cancelled | Pump::ConsumerGone => return,
            Pump::Disconnected { carried } => carried,
        };

        if carried {
            // Inbound traffic resets backoff but not the reconnect budget.
            mute = 0;
        } else if worth_reporting(mute) {
            // A repeatedly mute connection is distinguishable from a quiet feed.
            match deliver_until_cancelled(
                &mut cancelled,
                &sender,
                Err(Error::transport(format!(
                    "reconnected {mute} times without the exchange sending anything"
                ))),
                config.overflow,
            )
            .await
            {
                Some(Delivery::Sent | Delivery::Dropped) => {}
                Some(Delivery::ConsumerGone) | None => return,
            }
        }

        // Reconnect with capped exponential backoff; mute sockets keep the streak.
        loop {
            attempt += 1;
            mute += 1;
            if config
                .max_reconnect_attempts
                .is_some_and(|max| attempt > max)
            {
                // `DropNewest` may discard this final error; stream termination remains.
                let _ = deliver_until_cancelled(
                    &mut cancelled,
                    &sender,
                    Err(Error::transport(format!(
                        "gave up reconnecting after {} attempts",
                        attempt - 1
                    ))),
                    config.overflow,
                )
                .await;
                return;
            }

            let backoff = backoff_delay(&config, mute);
            tokio::select! {
                biased;
                () = wait_for_cancel(&mut cancelled) => return,
                () = platform::sleep(backoff) => {}
            }

            let reopened = tokio::select! {
                biased;
                () = wait_for_cancel(&mut cancelled) => return,
                reopened = open(&connect, &config) => reopened,
            };
            match reopened {
                Ok(reopened) => {
                    socket = reopened;
                    reconnected = true;
                    break;
                }
                Err(error) => {
                    if worth_reporting(mute) {
                        match deliver_until_cancelled(
                            &mut cancelled,
                            &sender,
                            Err(error),
                            config.overflow,
                        )
                        .await
                        {
                            Some(Delivery::Sent | Delivery::Dropped) => {}
                            Some(Delivery::ConsumerGone) | None => return,
                        }
                    }
                    continue;
                }
            }
        }
    }
}

enum Pump {
    /// The socket ended; `carried` records whether any data frame arrived.
    Disconnected {
        carried: bool,
    },
    ConsumerGone,
    Cancelled,
}

async fn pump(
    socket: &mut Socket,
    sender: &mpsc::Sender<Result<WsCommand>>,
    idle_timeout: Duration,
    connect: &WsConnect,
    config: &StreamConfig,
    reconnected: bool,
    cancelled: &mut watch::Receiver<bool>,
) -> Pump {
    // The first heartbeat is one full interval after the handshake.
    let mut pulse = platform::pulse(connect.heartbeat.as_ref());
    // Only inbound traffic resets the deadline; consumer waits do not count as idle.
    let mut idle = Idle::new(idle_timeout, connect.heartbeat.as_ref());
    // This controls backoff only; reconnect budget accounting is separate.
    let mut carried = false;
    // Retry a dropped reconnect notice before delivering post-gap data.
    let mut owed = reconnected;

    if owed {
        match hand_over(
            socket,
            sender,
            Ok(WsCommand::Reconnected),
            config.overflow,
            &mut pulse,
        )
        .await
        {
            Handover::Delivered => owed = false,
            Handover::Dropped => {}
            Handover::ConsumerGone => return Pump::ConsumerGone,
            Handover::SocketDead => return Pump::Disconnected { carried },
        }
        idle.reset(idle_timeout);
    }

    loop {
        let next = tokio::select! {
            biased;
            () = wait_for_cancel(cancelled) => return Pump::Cancelled,
            // Treat inbound silence as a disconnected socket.
            () = &mut idle => return Pump::Disconnected { carried },
            frame = platform::due(pulse.as_mut()) => {
                if socket.send_heartbeat(frame).await.is_err() {
                    return Pump::Disconnected { carried };
                }
                continue;
            }
            next = socket.next() => next,
        };

        let message = match next {
            None => return Pump::Disconnected { carried },
            Some(Err(_)) => return Pump::Disconnected { carried },
            Some(Ok(message)) => message,
        };
        idle.reset(idle_timeout);

        let event = match message {
            SocketMessage::Text(text) => WsCommand::Text(text),
            SocketMessage::Binary(bytes) => WsCommand::Binary(bytes),
            #[cfg(not(target_arch = "wasm32"))]
            SocketMessage::Activity => continue,
            SocketMessage::Closed => return Pump::Disconnected { carried },
        };
        carried = true;

        // A reconnect notice must precede every post-gap data frame.
        if owed {
            match hand_over(
                socket,
                sender,
                Ok(WsCommand::Reconnected),
                config.overflow,
                &mut pulse,
            )
            .await
            {
                Handover::Delivered => owed = false,
                Handover::Dropped => {}
                Handover::ConsumerGone => return Pump::ConsumerGone,
                Handover::SocketDead => return Pump::Disconnected { carried },
            }
            idle.reset(idle_timeout);
            if owed {
                // Post-gap data cannot overtake a pending reconnect notice.
                continue;
            }
        }

        match hand_over(socket, sender, Ok(event), config.overflow, &mut pulse).await {
            Handover::Delivered | Handover::Dropped => {}
            Handover::ConsumerGone => return Pump::ConsumerGone,
            Handover::SocketDead => return Pump::Disconnected { carried },
        }
        // Exclude time spent waiting on a backpressured consumer from idle time.
        idle.reset(idle_timeout);
    }
}

/// Result of transferring one event while servicing heartbeats.
enum Handover {
    /// The consumer has it.
    Delivered,
    /// [`Overflow::DropNewest`] discarded the event from a full buffer.
    Dropped,
    /// The consumer receiver was dropped.
    ConsumerGone,
    /// A heartbeat write failed after the event was delivered.
    SocketDead,
}

/// Transfers one event without suspending heartbeat writes.
///
/// Under [`Overflow::Backpressure`], reservation and heartbeat waits race. If a
/// heartbeat write fails, the already-read event is still delivered before the
/// socket is reported dead.
async fn hand_over(
    socket: &mut Socket,
    sender: &mpsc::Sender<Result<WsCommand>>,
    event: Result<WsCommand>,
    overflow: Overflow,
    pulse: &mut Option<Pulse>,
) -> Handover {
    if !matches!(overflow, Overflow::Backpressure) {
        return match deliver(sender, event, overflow).await {
            Delivery::Sent => Handover::Delivered,
            Delivery::Dropped => Handover::Dropped,
            Delivery::ConsumerGone => Handover::ConsumerGone,
        };
    }

    loop {
        tokio::select! {
            // Reserving is cancellation-safe when a heartbeat wins the race.
            reserved = sender.reserve() => return match reserved {
                Ok(permit) => {
                    permit.send(event);
                    Handover::Delivered
                }
                Err(_) => Handover::ConsumerGone,
            },
            frame = platform::due(pulse.as_mut()) => {
                if socket.send_heartbeat(frame).await.is_err() {
                    // Backpressure still guarantees delivery of the already-read event.
                    return match sender.reserve().await {
                        Ok(permit) => {
                            permit.send(event);
                            Handover::SocketDead
                        }
                        Err(_) => Handover::ConsumerGone,
                    };
                }
            }
        }
    }
}

enum Delivery {
    Sent,
    Dropped,
    ConsumerGone,
}

async fn deliver_until_cancelled(
    cancelled: &mut watch::Receiver<bool>,
    sender: &mpsc::Sender<Result<WsCommand>>,
    event: Result<WsCommand>,
    overflow: Overflow,
) -> Option<Delivery> {
    tokio::select! {
        biased;
        () = wait_for_cancel(cancelled) => None,
        delivered = deliver(sender, event, overflow) => Some(delivered),
    }
}

async fn deliver(
    sender: &mpsc::Sender<Result<WsCommand>>,
    event: Result<WsCommand>,
    overflow: Overflow,
) -> Delivery {
    match overflow {
        // Wait until the consumer catches up.
        Overflow::Backpressure => match sender.send(event).await {
            Ok(()) => Delivery::Sent,
            Err(_) => Delivery::ConsumerGone,
        },
        // Discard the new event instead of waiting on a full buffer.
        Overflow::DropNewest => match sender.try_send(event) {
            Ok(()) => Delivery::Sent,
            Err(mpsc::error::TrySendError::Full(_)) => Delivery::Dropped,
            Err(mpsc::error::TrySendError::Closed(_)) => Delivery::ConsumerGone,
        },
    }
}

/// Returns capped exponential backoff with a one-millisecond minimum.
fn backoff_delay(config: &StreamConfig, mute_run: u32) -> Duration {
    let doubling = mute_run.saturating_sub(1).min(16);
    let delay = config
        .initial_reconnect_delay_ms
        .max(1)
        .saturating_mul(1_u64 << doubling)
        .min(config.max_reconnect_delay_ms.max(1));
    Duration::from_millis(delay)
}

#[cfg(all(test, not(target_arch = "wasm32")))]
mod tests {
    use std::sync::Arc;
    use std::sync::atomic::{AtomicUsize, Ordering};

    use super::*;

    fn config() -> StreamConfig {
        StreamConfig {
            initial_reconnect_delay_ms: 1_000,
            max_reconnect_delay_ms: 30_000,
            ..StreamConfig::default()
        }
    }

    #[tokio::test]
    async fn close_handle_signals_once_and_waits_for_task_completion() {
        let (handle, mut cancelled, completed) = close_channels();
        let close_one = tokio::spawn({
            let handle = handle.clone();
            async move { handle.close().await }
        });
        let close_two = tokio::spawn({
            let handle = handle.clone();
            async move { handle.close().await }
        });

        cancelled.changed().await.unwrap();
        assert!(*cancelled.borrow());
        assert!(!close_one.is_finished());
        assert!(!close_two.is_finished());

        completed.send_replace(true);
        close_one.await.unwrap().unwrap();
        close_two.await.unwrap().unwrap();
    }

    #[tokio::test]
    async fn close_handle_reports_a_task_that_omits_completion() {
        let (handle, _cancelled, completed) = close_channels();
        drop(completed);

        assert!(matches!(handle.close().await, Err(Error::Adapter { .. })));
    }

    /// Accepts one connection, sends a greeting, and optionally remains open.
    async fn one_shot_server(stay: bool) -> (std::net::SocketAddr, mpsc::Receiver<Message>) {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
            .await
            .expect("a free local port");
        let address = listener.local_addr().expect("a bound address");
        let (sent, received) = mpsc::channel(8);

        tokio::spawn(async move {
            let Ok((stream, _)) = listener.accept().await else {
                return;
            };
            drop(listener);

            let Ok(mut socket) = tokio_tungstenite::accept_async(stream).await else {
                return;
            };
            if socket.send(Message::Text("hello".into())).await.is_err() {
                return;
            }
            if !stay {
                let _ = socket.close(None).await;
                return;
            }
            while let Some(Ok(message)) = socket.next().await {
                if sent.send(message).await.is_err() {
                    return;
                }
            }
        });

        (address, received)
    }

    /// Sends data continuously while counting client heartbeat frames.
    async fn chatty_server(every: Duration) -> (std::net::SocketAddr, Arc<AtomicUsize>) {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
            .await
            .expect("a free local port");
        let address = listener.local_addr().expect("a bound address");
        let heard = Arc::new(AtomicUsize::new(0));
        let counter = Arc::clone(&heard);

        tokio::spawn(async move {
            let Ok((stream, _)) = listener.accept().await else {
                return;
            };
            drop(listener);

            let Ok(socket) = tokio_tungstenite::accept_async(stream).await else {
                return;
            };
            let (mut write, mut read) = socket.split();

            tokio::spawn(async move {
                while let Some(Ok(message)) = read.next().await {
                    if matches!(message, Message::Text(_) | Message::Ping(_)) {
                        counter.fetch_add(1, Ordering::Relaxed);
                    }
                }
            });

            loop {
                if write.send(Message::Text("tick".into())).await.is_err() {
                    return;
                }
                tokio::time::sleep(every).await;
            }
        });

        (address, heard)
    }

    /// Accepts and immediately closes connections, optionally after one frame.
    ///
    /// The returned receiver counts accepted connections without blocking the
    /// server's reconnect churn.
    async fn flapping_server(
        greet: Option<&'static str>,
    ) -> (std::net::SocketAddr, mpsc::Receiver<()>) {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
            .await
            .expect("a free local port");
        let address = listener.local_addr().expect("a bound address");
        let (accepted, connections) = mpsc::channel(4_096);

        tokio::spawn(async move {
            while let Ok((stream, _)) = listener.accept().await {
                if matches!(
                    accepted.try_send(()),
                    Err(mpsc::error::TrySendError::Closed(()))
                ) {
                    return;
                }
                let Ok(mut socket) = tokio_tungstenite::accept_async(stream).await else {
                    continue;
                };
                if let Some(frame) = greet {
                    let _ = socket.send(Message::Text(frame.into())).await;
                }
                let _ = socket.close(None).await;
            }
        });

        (address, connections)
    }

    /// Closes the first connection, then keeps a second connection alive.
    ///
    /// The second connection starts sending only after observing a client
    /// heartbeat, providing a deterministic reconnect-notice ordering point.
    async fn flaps_once_then_stays(every: Duration) -> (std::net::SocketAddr, mpsc::Receiver<()>) {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
            .await
            .expect("a free local port");
        let address = listener.local_addr().expect("a bound address");
        let (beat, heard) = mpsc::channel(1);

        tokio::spawn(async move {
            let Ok((stream, _)) = listener.accept().await else {
                return;
            };
            if let Ok(mut socket) = tokio_tungstenite::accept_async(stream).await {
                let _ = socket.send(Message::Text("hello".into())).await;
                let _ = socket.close(None).await;
            }

            let Ok((stream, _)) = listener.accept().await else {
                return;
            };
            let Ok(socket) = tokio_tungstenite::accept_async(stream).await else {
                return;
            };
            let (mut write, mut read) = socket.split();

            if read.next().await.is_none() || beat.send(()).await.is_err() {
                return;
            }
            loop {
                if write.send(Message::Text("tick".into())).await.is_err() {
                    return;
                }
                tokio::time::sleep(every).await;
            }
        });

        (address, heard)
    }

    /// Records the authorization header from each handshake before closing.
    #[allow(clippy::result_large_err)] // `tungstenite` fixes the callback's error response type.
    async fn header_recording_server() -> (std::net::SocketAddr, mpsc::Receiver<String>) {
        use tokio_tungstenite::tungstenite::handshake::server::{Request, Response};

        let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
            .await
            .expect("a free local port");
        let address = listener.local_addr().expect("a bound address");
        let (seen, presented) = mpsc::channel(16);

        tokio::spawn(async move {
            while let Ok((stream, _)) = listener.accept().await {
                let seen = seen.clone();
                let socket = tokio_tungstenite::accept_hdr_async(
                    stream,
                    move |request: &Request, response: Response| {
                        let value = request
                            .headers()
                            .get("authorization")
                            .and_then(|value| value.to_str().ok())
                            .unwrap_or_default()
                            .to_string();
                        let _ = seen.try_send(value);
                        Ok(response)
                    },
                )
                .await;

                let Ok(mut socket) = socket else {
                    continue;
                };
                let _ = socket.close(None).await;
            }
        });

        (address, presented)
    }

    /// Records each connection's first subscription frame before closing.
    async fn subscribe_recording_server() -> (std::net::SocketAddr, mpsc::Receiver<String>) {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
            .await
            .expect("a free local port");
        let address = listener.local_addr().expect("a bound address");
        let (seen, subscribed) = mpsc::channel(16);

        tokio::spawn(async move {
            while let Ok((stream, _)) = listener.accept().await {
                let Ok(mut socket) = tokio_tungstenite::accept_async(stream).await else {
                    continue;
                };
                if let Some(Ok(Message::Text(frame))) = socket.next().await
                    && seen.send(frame.to_string()).await.is_err()
                {
                    return;
                }
                let _ = socket.close(None).await;
            }
        });

        (address, subscribed)
    }

    #[tokio::test]
    async fn every_connection_subscribes_with_frames_minted_for_it() {
        let (address, mut subscribed) = subscribe_recording_server().await;
        let signed = AtomicUsize::new(0);
        let config = StreamConfig {
            initial_reconnect_delay_ms: 1,
            max_reconnect_delay_ms: 1,
            idle_timeout_ms: 60_000,
            ..config()
        };

        let _session = connect(
            WsConnect {
                url: format!("ws://{address}"),
                headers: None,
                // Model a time-sensitive subscription signature.
                subscribe: Box::new(move || {
                    let nth = signed.fetch_add(1, Ordering::Relaxed);
                    Ok(vec![format!("subscribe {nth}")])
                }),
                heartbeat: None,
            },
            &config,
        )
        .await
        .expect("the first connection");

        let mut seen = Vec::new();
        for _ in 0..3 {
            seen.push(
                tokio::time::timeout(Duration::from_secs(5), subscribed.recv())
                    .await
                    .expect("another connection before the deadline")
                    .expect("the server still listening"),
            );
        }

        assert_eq!(seen, ["subscribe 0", "subscribe 1", "subscribe 2"]);
    }

    #[tokio::test]
    async fn a_subscription_that_cannot_be_minted_fails_the_connection_it_was_for() {
        let (address, _subscribed) = subscribe_recording_server().await;

        let error = connect(
            WsConnect {
                url: format!("ws://{address}"),
                headers: None,
                subscribe: Box::new(|| Err(Error::auth("no secret key to sign with"))),
                heartbeat: None,
            },
            &config(),
        )
        .await
        .expect_err("a subscription that cannot be signed");

        assert!(matches!(error, Error::Auth { .. }), "{error}");
    }

    #[test]
    fn an_exchange_that_needs_a_slower_idle_timer_than_the_caller_asked_for_gets_one() {
        let config = StreamConfig {
            idle_timeout_ms: 30_000,
            ..config()
        };
        let heartbeat = Heartbeat {
            interval: Duration::from_secs(15),
            frame: HeartbeatFrame::Ping,
            min_idle_timeout: Duration::from_secs(240),
        };

        assert_eq!(
            idle_timeout(&config, Some(&heartbeat)),
            Duration::from_secs(240)
        );
        let patient = StreamConfig {
            idle_timeout_ms: 600_000,
            ..config.clone()
        };
        assert_eq!(
            idle_timeout(&patient, Some(&heartbeat)),
            Duration::from_secs(600)
        );
        assert_eq!(idle_timeout(&config, None), Duration::from_secs(30));
    }

    #[test]
    fn a_heartbeat_goes_out_as_the_kind_of_frame_it_names() {
        assert_eq!(
            HeartbeatFrame::Text("PING").message(),
            Message::Text("PING".into())
        );
        assert!(matches!(
            HeartbeatFrame::Ping.message(),
            Message::Ping(payload) if payload.is_empty()
        ));
    }

    #[test]
    fn a_blip_stays_quiet_and_a_lasting_outage_does_not() {
        assert!(!worth_reporting(1));
        assert!(!worth_reporting(2));
        assert!(worth_reporting(3));
        assert!(worth_reporting(u32::MAX));
    }

    #[tokio::test]
    async fn a_quiet_connection_sends_the_heartbeat_on_its_own_interval() {
        // Exercise application-level and protocol-level heartbeats.
        for frame in [
            HeartbeatFrame::Text(r#"{"method":"ping"}"#),
            HeartbeatFrame::Ping,
        ] {
            let (address, mut received) = one_shot_server(true).await;
            let config = StreamConfig {
                idle_timeout_ms: 60_000,
                ..config()
            };

            let _session = connect(
                WsConnect {
                    url: format!("ws://{address}"),
                    headers: None,
                    subscribe: WsConnect::fixed(Vec::new()),
                    heartbeat: Some(Heartbeat {
                        interval: Duration::from_millis(50),
                        frame,
                        min_idle_timeout: Duration::from_millis(60_000),
                    }),
                },
                &config,
            )
            .await
            .expect("the first connection");

            for _ in 0..2 {
                let message = tokio::time::timeout(Duration::from_secs(5), received.recv())
                    .await
                    .expect("a heartbeat before the deadline")
                    .expect("the server still reading");

                assert_eq!(message, frame.message(), "{frame:?}");
            }
        }
    }

    #[tokio::test]
    async fn a_reconnect_that_never_succeeds_says_so_instead_of_going_quiet() {
        let (address, _received) = one_shot_server(false).await;
        let config = StreamConfig {
            initial_reconnect_delay_ms: 1,
            max_reconnect_delay_ms: 1,
            idle_timeout_ms: 60_000,
            ..config()
        };

        let mut session = connect(
            WsConnect {
                url: format!("ws://{address}"),
                headers: None,
                subscribe: WsConnect::fixed(Vec::new()),
                heartbeat: None,
            },
            &config,
        )
        .await
        .expect("the first connection");

        assert!(matches!(
            session.next().await,
            Some(Ok(WsCommand::Text(text))) if text == "hello"
        ));

        // Unlimited retries still report a persistent outage.
        let reported = tokio::time::timeout(Duration::from_secs(5), session.next())
            .await
            .expect("a report before the deadline");

        assert!(matches!(reported, Some(Err(Error::Transport { .. }))));
    }

    #[test]
    fn backoff_doubles_from_the_initial_delay() {
        let config = config();

        assert_eq!(backoff_delay(&config, 1), Duration::from_millis(1_000));
        assert_eq!(backoff_delay(&config, 2), Duration::from_millis(2_000));
        assert_eq!(backoff_delay(&config, 3), Duration::from_millis(4_000));
        assert_eq!(backoff_delay(&config, 4), Duration::from_millis(8_000));
    }

    #[test]
    fn backoff_stops_growing_at_the_cap() {
        let config = config();

        assert_eq!(backoff_delay(&config, 6), Duration::from_millis(30_000));
        assert_eq!(backoff_delay(&config, 60), Duration::from_millis(30_000));
        assert_eq!(
            backoff_delay(&config, u32::MAX),
            Duration::from_millis(30_000)
        );
    }

    #[test]
    fn a_zero_delay_still_sleeps_between_reconnects() {
        // Public zero values must not create a busy reconnect loop.
        let no_initial = StreamConfig {
            initial_reconnect_delay_ms: 0,
            ..config()
        };
        let no_ceiling = StreamConfig {
            max_reconnect_delay_ms: 0,
            ..config()
        };

        for attempt in [1, 2, 8, u32::MAX] {
            assert!(
                backoff_delay(&no_initial, attempt) >= Duration::from_millis(1),
                "attempt {attempt} from a zero initial delay"
            );
            assert!(
                backoff_delay(&no_ceiling, attempt) >= Duration::from_millis(1),
                "attempt {attempt} under a zero ceiling"
            );
        }

        assert_eq!(backoff_delay(&no_initial, 4), Duration::from_millis(8));
    }

    #[tokio::test]
    async fn backpressure_waits_instead_of_losing_events() {
        let (sender, mut receiver) = mpsc::channel(1);

        assert!(matches!(
            deliver(
                &sender,
                Ok(WsCommand::Text("first".into())),
                Overflow::Backpressure
            )
            .await,
            Delivery::Sent
        ));

        // A full buffer blocks the producer under backpressure.
        let blocked = tokio::time::timeout(
            Duration::from_millis(50),
            deliver(
                &sender,
                Ok(WsCommand::Text("second".into())),
                Overflow::Backpressure,
            ),
        )
        .await;
        assert!(blocked.is_err(), "backpressure should have blocked");

        assert!(matches!(
            receiver.recv().await,
            Some(Ok(WsCommand::Text(text))) if text == "first"
        ));
    }

    #[tokio::test]
    async fn a_full_buffer_drops_rather_than_stalling_when_asked_to() {
        let (sender, _receiver) = mpsc::channel(1);

        assert!(matches!(
            deliver(
                &sender,
                Ok(WsCommand::Text("first".into())),
                Overflow::DropNewest
            )
            .await,
            Delivery::Sent
        ));
        assert!(matches!(
            deliver(
                &sender,
                Ok(WsCommand::Text("second".into())),
                Overflow::DropNewest
            )
            .await,
            Delivery::Dropped
        ));
    }

    #[tokio::test]
    async fn a_dropped_consumer_stops_the_connection() {
        let (sender, receiver) = mpsc::channel(4);
        drop(receiver);

        assert!(matches!(
            deliver(
                &sender,
                Ok(WsCommand::Text("frame".into())),
                Overflow::Backpressure
            )
            .await,
            Delivery::ConsumerGone
        ));
        assert!(matches!(
            deliver(
                &sender,
                Ok(WsCommand::Text("frame".into())),
                Overflow::DropNewest
            )
            .await,
            Delivery::ConsumerGone
        ));
    }

    #[tokio::test]
    async fn every_handshake_is_opened_with_headers_minted_for_it() {
        use std::sync::atomic::{AtomicUsize, Ordering};

        let (address, mut presented) = header_recording_server().await;
        let signed = AtomicUsize::new(0);
        let config = StreamConfig {
            initial_reconnect_delay_ms: 1,
            max_reconnect_delay_ms: 1,
            idle_timeout_ms: 60_000,
            ..config()
        };

        let _session = connect(
            WsConnect {
                url: format!("ws://{address}"),
                // Model a time-sensitive authentication header.
                headers: Some(Box::new(move || {
                    let nth = signed.fetch_add(1, Ordering::Relaxed);
                    Ok(vec![("authorization".to_string(), format!("Bearer {nth}"))])
                })),
                subscribe: WsConnect::fixed(Vec::new()),
                heartbeat: None,
            },
            &config,
        )
        .await
        .expect("the first connection");

        let mut seen = Vec::new();
        for _ in 0..3 {
            seen.push(
                tokio::time::timeout(Duration::from_secs(5), presented.recv())
                    .await
                    .expect("another handshake before the deadline")
                    .expect("the server still listening"),
            );
        }

        assert_eq!(seen, ["Bearer 0", "Bearer 1", "Bearer 2"]);
    }

    #[tokio::test]
    async fn a_consumer_that_stalls_keeps_its_connection_and_its_heartbeat() {
        // Exercise both heartbeat kinds while delivery is backpressured.
        for frame in [
            HeartbeatFrame::Text(r#"{"method":"ping"}"#),
            HeartbeatFrame::Ping,
        ] {
            let (address, heard) = chatty_server(Duration::from_millis(5)).await;
            let config = StreamConfig {
                // Keep delivery blocked after the first frame.
                buffer_size: 1,
                overflow: Overflow::Backpressure,
                idle_timeout_ms: 60_000,
                ..config()
            };

            let mut session = connect(
                WsConnect {
                    url: format!("ws://{address}"),
                    headers: None,
                    subscribe: WsConnect::fixed(Vec::new()),
                    heartbeat: Some(Heartbeat {
                        interval: Duration::from_millis(20),
                        frame,
                        min_idle_timeout: Duration::ZERO,
                    }),
                },
                &config,
            )
            .await
            .expect("the first connection");

            assert!(matches!(session.next().await, Some(Ok(WsCommand::Text(_)))));

            // Heartbeats must continue while the consumer leaves the buffer full.
            for _ in 0..6 {
                let before = heard.load(Ordering::Relaxed);
                let kept_beating = tokio::time::timeout(Duration::from_secs(5), async {
                    while heard.load(Ordering::Relaxed) - before < 3 {
                        tokio::time::sleep(Duration::from_millis(5)).await;
                    }
                })
                .await;
                assert!(
                    kept_beating.is_ok(),
                    "{frame:?}: {} heartbeats reached the server while the consumer was stalled",
                    heard.load(Ordering::Relaxed) - before
                );

                // Backpressure must preserve every data item.
                let item = tokio::time::timeout(Duration::from_secs(5), session.next())
                    .await
                    .expect("the connection to still be delivering");
                assert!(matches!(item, Some(Ok(WsCommand::Text(_)))), "{item:?}");
            }
        }
    }

    #[tokio::test]
    async fn the_idle_timer_does_not_count_time_spent_waiting_on_the_consumer() {
        let (address, _heard) = chatty_server(Duration::from_millis(5)).await;
        let config = StreamConfig {
            // Keep delivery blocked after the first frame.
            buffer_size: 1,
            overflow: Overflow::Backpressure,
            idle_timeout_ms: 500,
            initial_reconnect_delay_ms: 1,
            max_reconnect_delay_ms: 1,
            ..config()
        };

        let mut session = connect(
            WsConnect {
                url: format!("ws://{address}"),
                headers: None,
                subscribe: WsConnect::fixed(Vec::new()),
                heartbeat: None,
            },
            &config,
        )
        .await
        .expect("the first connection");

        assert!(matches!(session.next().await, Some(Ok(WsCommand::Text(_)))));

        // Consumer backpressure alone must not expire the inbound idle timer.
        tokio::time::sleep(Duration::from_millis(3_000)).await;

        for _ in 0..3 {
            let item = tokio::time::timeout(Duration::from_secs(5), session.next())
                .await
                .expect("the connection to still be delivering");
            assert!(matches!(item, Some(Ok(WsCommand::Text(_)))), "{item:?}");
        }
    }

    #[tokio::test]
    async fn a_connection_the_exchange_never_speaks_on_backs_off_and_says_so() {
        let (address, _connections) = flapping_server(None).await;
        let config = StreamConfig {
            initial_reconnect_delay_ms: 1,
            max_reconnect_delay_ms: 50,
            idle_timeout_ms: 60_000,
            ..config()
        };

        let mut session = connect(
            WsConnect {
                url: format!("ws://{address}"),
                headers: None,
                subscribe: WsConnect::fixed(Vec::new()),
                heartbeat: None,
            },
            &config,
        )
        .await
        .expect("the first connection");

        // Successful handshakes with no inbound frames still report an outage.
        let reported = tokio::time::timeout(Duration::from_secs(5), async {
            while let Some(event) = session.next().await {
                if let Err(error) = event {
                    return Some(error);
                }
            }
            None
        })
        .await
        .expect("a report before the deadline");

        assert!(
            matches!(
                &reported,
                Some(Error::Transport { detail })
                    if detail.contains("without the exchange sending anything")
            ),
            "{reported:?}"
        );
    }

    #[tokio::test]
    async fn the_attempt_limit_bounds_a_venue_that_sends_a_frame_on_every_connection() {
        // Raw frames cannot prove subscription success, so they do not reset the budget.
        let (address, mut connections) =
            flapping_server(Some(r#"{"code":-1121,"msg":"Invalid symbol."}"#)).await;
        let config = StreamConfig {
            buffer_size: 64,
            overflow: Overflow::DropNewest,
            max_reconnect_attempts: Some(3),
            initial_reconnect_delay_ms: 1,
            max_reconnect_delay_ms: 1,
            idle_timeout_ms: 60_000,
        };

        let mut session = connect(
            WsConnect {
                url: format!("ws://{address}"),
                headers: None,
                subscribe: WsConnect::fixed(Vec::new()),
                heartbeat: None,
            },
            &config,
        )
        .await
        .expect("the first connection");

        let ended = tokio::time::timeout(Duration::from_secs(20), async {
            while session.next().await.is_some() {}
        })
        .await;

        let mut opened = 0;
        while connections.try_recv().is_ok() {
            opened += 1;
        }

        assert!(
            ended.is_ok(),
            "the stream never ended; {opened} connections opened against a budget of 3"
        );
        // One initial connection plus exactly three reconnect attempts.
        assert_eq!(opened, 4, "connections opened against a budget of 3");
    }

    #[tokio::test]
    async fn a_venue_that_recycles_sockets_keeps_reconnecting_at_the_first_delay() {
        // Inbound traffic resets backoff for the next recycled connection.
        let (address, _connections) = flapping_server(Some("hello")).await;
        let config = StreamConfig {
            initial_reconnect_delay_ms: 1,
            max_reconnect_delay_ms: 30_000,
            idle_timeout_ms: 60_000,
            ..config()
        };

        let mut session = connect(
            WsConnect {
                url: format!("ws://{address}"),
                headers: None,
                subscribe: WsConnect::fixed(Vec::new()),
                heartbeat: None,
            },
            &config,
        )
        .await
        .expect("the first connection");

        let seen = tokio::time::timeout(Duration::from_secs(20), async {
            let mut reconnects = 0;
            while reconnects < 20 {
                match session.next().await {
                    Some(Ok(WsCommand::Reconnected)) => reconnects += 1,
                    Some(Ok(WsCommand::Text(_))) => {}
                    other => return Err(format!("the stream ended or faulted: {other:?}")),
                }
            }
            Ok(())
        })
        .await;

        assert!(
            matches!(seen, Ok(Ok(()))),
            "twenty reconnects at the first delay: {seen:?}"
        );
    }

    #[tokio::test]
    async fn the_attempt_limit_bounds_a_venue_that_accepts_and_says_nothing() {
        let (address, _connections) = flapping_server(None).await;
        let config = StreamConfig {
            buffer_size: 64,
            overflow: Overflow::Backpressure,
            max_reconnect_attempts: Some(2),
            initial_reconnect_delay_ms: 1,
            max_reconnect_delay_ms: 1,
            idle_timeout_ms: 60_000,
        };

        let mut session = connect(
            WsConnect {
                url: format!("ws://{address}"),
                headers: None,
                subscribe: WsConnect::fixed(Vec::new()),
                heartbeat: None,
            },
            &config,
        )
        .await
        .expect("the first connection");

        let ended = tokio::time::timeout(Duration::from_secs(10), async {
            while session.next().await.is_some() {}
        })
        .await;

        assert!(ended.is_ok(), "the stream retried past its attempt limit");
    }

    #[tokio::test]
    async fn the_news_of_a_reconnect_outlives_a_full_buffer() {
        let (address, mut heard) = flaps_once_then_stays(Duration::from_millis(20)).await;
        let config = StreamConfig {
            // The greeting fills the buffer before the reconnect notice arrives.
            buffer_size: 1,
            overflow: Overflow::DropNewest,
            initial_reconnect_delay_ms: 1,
            max_reconnect_delay_ms: 1,
            idle_timeout_ms: 60_000,
            ..config()
        };

        let mut session = connect(
            WsConnect {
                url: format!("ws://{address}"),
                headers: None,
                subscribe: WsConnect::fixed(Vec::new()),
                heartbeat: Some(Heartbeat {
                    interval: Duration::from_millis(20),
                    frame: HeartbeatFrame::Text("beat"),
                    min_idle_timeout: Duration::ZERO,
                }),
            },
            &config,
        )
        .await
        .expect("the first connection");

        // The observed heartbeat confirms the notice met the full buffer.
        tokio::time::timeout(Duration::from_secs(10), heard.recv())
            .await
            .expect("the reconnected socket to reach its heartbeat")
            .expect("the server still running");

        assert!(matches!(
            session.next().await,
            Some(Ok(WsCommand::Text(text))) if text == "hello"
        ));

        // The retained reconnect notice must precede post-gap data.
        let next = tokio::time::timeout(Duration::from_secs(10), session.next())
            .await
            .expect("another event before the deadline");
        assert!(matches!(next, Some(Ok(WsCommand::Reconnected))), "{next:?}");
    }

    #[tokio::test]
    async fn a_reconnect_does_not_wait_on_a_consumer_that_asked_never_to_be_waited_on() {
        let (address, mut connections) = flapping_server(Some("hello")).await;
        let config = StreamConfig {
            buffer_size: 1,
            overflow: Overflow::DropNewest,
            initial_reconnect_delay_ms: 1,
            max_reconnect_delay_ms: 1,
            idle_timeout_ms: 60_000,
            ..config()
        };

        let _session = connect(
            WsConnect {
                url: format!("ws://{address}"),
                headers: None,
                subscribe: WsConnect::fixed(Vec::new()),
                heartbeat: None,
            },
            &config,
        )
        .await
        .expect("the first connection");

        // A pending reconnect notice must not block `DropNewest` reconnects.
        for _ in 0..4 {
            tokio::time::timeout(Duration::from_secs(5), connections.recv())
                .await
                .expect("another connection before the deadline")
                .expect("the server still listening");
        }
    }

    #[tokio::test]
    async fn giving_up_does_not_wait_on_a_consumer_that_asked_never_to_be_waited_on() {
        let (address, _received) = one_shot_server(false).await;
        let config = StreamConfig {
            buffer_size: 1,
            overflow: Overflow::DropNewest,
            max_reconnect_attempts: Some(1),
            initial_reconnect_delay_ms: 1,
            max_reconnect_delay_ms: 1,
            idle_timeout_ms: 60_000,
        };

        let mut session = connect(
            WsConnect {
                url: format!("ws://{address}"),
                headers: None,
                subscribe: WsConnect::fixed(Vec::new()),
                heartbeat: None,
            },
            &config,
        )
        .await
        .expect("the first connection");

        // Keep the buffer full until the lifecycle task reaches its attempt limit.
        tokio::time::timeout(Duration::from_secs(5), async {
            while !session.events.is_closed() {
                tokio::time::sleep(Duration::from_millis(5)).await;
            }
        })
        .await
        .expect("the connection to give up before the deadline");

        assert!(matches!(
            session.next().await,
            Some(Ok(WsCommand::Text(text))) if text == "hello"
        ));

        // The final error may be dropped, but the stream must still terminate.
        let ended = tokio::time::timeout(Duration::from_secs(5), session.next())
            .await
            .expect("the stream to end rather than wait on the consumer");
        assert!(ended.is_none(), "{ended:?}");
    }

    /// Returns a locally closed socket whose writes fail immediately.
    async fn write_dead_socket() -> Socket {
        let (address, _received) = one_shot_server(true).await;
        let mut socket = open(
            &WsConnect {
                url: format!("ws://{address}"),
                headers: None,
                subscribe: WsConnect::fixed(Vec::new()),
                heartbeat: None,
            },
            &StreamConfig::default(),
        )
        .await
        .expect("a connection to the local server");

        socket.close_for_test().await;
        assert!(
            socket.send_heartbeat(HeartbeatFrame::Ping).await.is_err(),
            "a closed socket should refuse writes"
        );

        socket
    }

    #[tokio::test]
    async fn a_heartbeat_that_cannot_be_written_does_not_cost_the_event_in_hand() {
        let mut socket = write_dead_socket().await;
        // Fill the buffer so heartbeat failure wins the reservation race.
        let (sender, mut receiver) = mpsc::channel(1);
        sender
            .send(Ok(WsCommand::Text("already queued".into())))
            .await
            .expect("room in an empty buffer");

        let mut pulse = Some((
            HeartbeatFrame::Ping,
            tokio::time::interval(Duration::from_millis(1)),
        ));

        let handed = tokio::spawn(async move {
            hand_over(
                &mut socket,
                &sender,
                Ok(WsCommand::Text("read before the socket died".into())),
                Overflow::Backpressure,
                &mut pulse,
            )
            .await
        });

        tokio::time::sleep(Duration::from_millis(200)).await;

        // Backpressure preserves the event already read from the failed socket.
        assert!(matches!(
            receiver.recv().await,
            Some(Ok(WsCommand::Text(text))) if text == "already queued"
        ));
        let kept = tokio::time::timeout(Duration::from_secs(5), receiver.recv())
            .await
            .expect("the event to be delivered rather than dropped with the socket");
        assert!(
            matches!(kept, Some(Ok(WsCommand::Text(ref text))) if text == "read before the socket died"),
            "{kept:?}"
        );

        assert!(matches!(
            handed.await.expect("the hand-over task"),
            Handover::SocketDead
        ));
    }

    #[tokio::test]
    async fn a_consumer_that_left_while_the_socket_died_ends_the_connection() {
        let mut socket = write_dead_socket().await;
        let (sender, receiver) = mpsc::channel(1);
        sender
            .send(Ok(WsCommand::Text("already queued".into())))
            .await
            .expect("room in an empty buffer");
        let mut pulse = Some((
            HeartbeatFrame::Ping,
            tokio::time::interval(Duration::from_millis(1)),
        ));

        let handed = tokio::spawn(async move {
            hand_over(
                &mut socket,
                &sender,
                Ok(WsCommand::Text("nobody left to read it".into())),
                Overflow::Backpressure,
                &mut pulse,
            )
            .await
        });

        tokio::time::sleep(Duration::from_millis(50)).await;
        // Dropping the receiver must cancel the pending reservation.
        drop(receiver);

        assert!(matches!(
            tokio::time::timeout(Duration::from_secs(5), handed)
                .await
                .expect("the wait to end with the consumer")
                .expect("the hand-over task"),
            Handover::ConsumerGone
        ));
    }

    #[tokio::test]
    async fn an_unreachable_url_fails_at_connect_not_later_on_the_stream() {
        let error = connect(
            WsConnect {
                url: "not-a-websocket-url".to_string(),
                headers: None,
                subscribe: WsConnect::fixed(Vec::new()),
                heartbeat: None,
            },
            &config(),
        )
        .await
        .unwrap_err();

        assert!(matches!(error, Error::Transport { .. }));
    }
}