musli-web 0.4.7

Types for integrating Müsli with websocket frameworks.
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
//! The generic asynchronous client implementation.
//!
//! This implements the client side of the same websocket protocol which is
//! implemented by [`web`] for browsers, but built for native asynchronous
//! runtimes instead of the browser event loop.
//!
//! This is specialized over the `T` parameter through modules such as:
//!
//! * [`tungstenite029`] for `tokio-tungstenite` `0.29.x`.
//!
//! [`tungstenite029`]: crate::tungstenite029
//! [`web`]: <https://docs.rs/musli-web/latest/musli_web/web/>
//!
//! # Overview
//!
//! A [`Service`] is a driver which owns the underlying socket. It has to be
//! driven by calling [`Service::run`], which is typically done in a dedicated
//! task.
//!
//! A [`Handle`] is a cheap and [`Clone`]-able handle to the service which can be
//! shared and moved freely between tasks. It is used to perform requests, open
//! channels, and to listen for broadcasts and state changes.

use core::cell::Cell;
use core::fmt;
use core::future::Future;
use core::marker::PhantomData;
use core::{any, mem};

use alloc::boxed::Box;
use alloc::string::{String, ToString};
use alloc::sync::Arc;
use alloc::vec::Vec;

use std::collections::HashMap;
use std::collections::hash_map::Entry;
use std::sync::Mutex;
use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU32, Ordering};

use bytes::Bytes;
use rand::prelude::*;
use rand::rngs::SmallRng;
use slab::Slab;
use tokio::sync::{mpsc, oneshot, watch};
use tokio::time::{Duration, Instant};

use crate::api::{self, ChannelId, DecodeBody, Event, Format, MessageId};
use crate::format;

/// The initial reconnect timeout.
const INITIAL_TIMEOUT: Duration = Duration::from_millis(250);
/// The maximum reconnect timeout.
const MAX_TIMEOUT: Duration = Duration::from_millis(4000);
/// The maximum amount of fuzz added to a reconnect timeout.
const MAX_FUZZ: u64 = 50;
/// The default seed used for reconnect fuzzing.
const DEFAULT_SEED: u64 = 0xdeadbeef;

/// An empty request body.
#[non_exhaustive]
pub struct EmptyBody;

/// An empty callback.
#[non_exhaustive]
pub struct EmptyCallback;

/// A message received over the underlying socket.
///
/// NB: The variants are constructed by the transport bindings, such as
/// [`tungstenite029`], so none are constructed when the generic core is built
/// on its own.
///
/// [`tungstenite029`]: crate::tungstenite029
#[cfg_attr(not(feature = "tungstenite029"), allow(dead_code))]
pub(crate) enum Message {
    /// A text message was received. The protocol is binary only, so receiving
    /// one is a protocol error.
    Text,
    /// A binary message was received.
    Binary(Bytes),
    /// A ping message was received.
    ///
    /// Implementations are expected to respond with a pong on their own.
    Ping,
    /// A pong message was received.
    Pong,
    /// A close message was received.
    Close,
}

pub(crate) mod sealed_socket {
    pub trait Sealed {}
}

pub(crate) trait SocketImpl
where
    Self: 'static + Send + Sized + self::sealed_socket::Sealed,
{
    #[doc(hidden)]
    type Error;

    /// Receive the next message.
    ///
    /// The returned future must be cancel safe, since it is used in a `select!`
    /// loop together with the command queue of the service.
    #[doc(hidden)]
    fn recv(&mut self) -> impl Future<Output = Option<Result<Message, Self::Error>>> + Send + '_;

    /// Send a binary message and flush it.
    #[doc(hidden)]
    fn send(&mut self, data: &[u8]) -> impl Future<Output = Result<(), Self::Error>> + Send + '_;

    /// Close the socket.
    #[doc(hidden)]
    fn close(&mut self) -> impl Future<Output = Result<(), Self::Error>> + Send + '_;
}

pub(crate) mod sealed_client {
    pub trait Sealed {}
}

/// Central trait for asynchronous client integration.
///
/// Since websocket clients are provided by many different crates, this trait
/// abstracts over the details of establishing and driving one.
///
/// The corresponding modules provide integrations:
///
/// * [`tungstenite029`] for `tokio-tungstenite` `0.29.x`.
///
/// [`tungstenite029`]: crate::tungstenite029
pub trait ClientImpl
where
    Self: 'static + Copy + Sized + self::sealed_client::Sealed,
{
    #[doc(hidden)]
    type Error: 'static + Send + Sync + core::error::Error;

    #[doc(hidden)]
    #[allow(private_bounds)]
    type Socket: SocketImpl<Error = Self::Error>;

    #[doc(hidden)]
    fn connect(url: &str) -> impl Future<Output = Result<Self::Socket, Self::Error>> + Send;
}

/// Construct a new [`ServiceBuilder`] which will connect to `url`.
pub fn connect<T>(url: impl AsRef<str>) -> ServiceBuilder<T, EmptyCallback>
where
    T: ClientImpl,
{
    ServiceBuilder {
        url: url.as_ref().to_string(),
        on_error: EmptyCallback,
        reconnect: true,
        seed: DEFAULT_SEED,
        format: Format::DEFAULT,
        _marker: PhantomData,
    }
}

/// The state of the connection.
///
/// A listener for state changes can be set up through [`Handle::state`].
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
#[non_exhaustive]
pub enum State {
    /// The connection is open.
    Open,
    /// The connection is closed.
    Closed,
}

impl State {
    /// Check if the state is open.
    ///
    /// # Examples
    ///
    /// ```
    /// use musli_web::client::State;
    ///
    /// assert!(State::Open.is_open());
    /// assert!(!State::Closed.is_open());
    /// ```
    #[inline]
    pub fn is_open(&self) -> bool {
        matches!(self, Self::Open)
    }
}

/// Trait governing how callbacks are called.
pub trait Callback<I>
where
    Self: 'static + Send + Sync,
{
    /// Call the callback.
    fn call(&self, input: I);
}

impl<I> Callback<I> for EmptyCallback {
    #[inline]
    fn call(&self, _: I) {}
}

impl<F, I> Callback<I> for F
where
    F: 'static + Send + Sync + Fn(I),
{
    #[inline]
    fn call(&self, input: I) {
        self(input)
    }
}

/// Error type for the client.
#[derive(Debug)]
pub struct Error {
    kind: ErrorKind,
}

impl Error {
    #[inline]
    const fn new(kind: ErrorKind) -> Self {
        Self { kind }
    }

    /// Check if the error is caused by an empty packet.
    ///
    /// # Examples
    ///
    /// ```
    /// use musli_web::client::RawPacket;
    ///
    /// let packet = RawPacket::empty();
    /// let e = packet.decode::<u32>().unwrap_err();
    ///
    /// assert!(e.is_empty_packet());
    /// ```
    #[inline]
    pub fn is_empty_packet(&self) -> bool {
        matches!(self.kind, ErrorKind::EmptyPacket)
    }

    /// Check if the error is caused by the connection not being open.
    ///
    /// This is the error which is produced if a request is performed while the
    /// service is not connected. See [`Handle::wait_until_open`] for how to
    /// wait until the connection is available.
    #[inline]
    pub fn is_not_connected(&self) -> bool {
        matches!(self.kind, ErrorKind::NotConnected)
    }

    /// Check if the error is a server error, and if so return the message
    /// reported by the server.
    ///
    /// Server errors are produced by a [`Handler`] which returns an error or
    /// which indicates that it does not support the request being made.
    ///
    /// [`Handler`]: <https://docs.rs/musli-web/latest/musli_web/ws/trait.Handler.html>
    #[inline]
    pub fn as_server_error(&self) -> Option<&str> {
        match &self.kind {
            ErrorKind::Server(message) => Some(message),
            _ => None,
        }
    }

    /// Format a client error consisting of a message.
    #[inline]
    pub fn message(message: impl fmt::Display) -> Self {
        Self::new(ErrorKind::Message(message.to_string()))
    }

    #[inline]
    fn server(message: impl fmt::Display) -> Self {
        Self::new(ErrorKind::Server(message.to_string()))
    }

    #[inline]
    fn transport<E>(error: E) -> Self
    where
        E: 'static + Send + Sync + core::error::Error,
    {
        Self::new(ErrorKind::Transport(Box::new(error)))
    }

    #[inline]
    fn decode_response_header(error: format::Error) -> Self {
        Self::new(ErrorKind::DecodeResponseHeader(error))
    }

    #[inline]
    fn decode_error_message(error: format::Error) -> Self {
        Self::new(ErrorKind::DecodeErrorMessage(error))
    }

    #[inline]
    fn decode_packet(error: format::Error) -> Self {
        Self::new(ErrorKind::DecodePacket(error))
    }

    #[inline]
    fn encoding_header(error: format::Error) -> Self {
        Self::new(ErrorKind::EncodingHeader(error))
    }

    #[inline]
    fn encoding_body(error: format::Error) -> Self {
        Self::new(ErrorKind::EncodingBody(error))
    }
}

#[derive(Debug)]
enum ErrorKind {
    EmptyPacket,
    NotConnected,
    Message(String),
    Server(String),
    Transport(Box<dyn core::error::Error + Send + Sync>),
    DecodeResponseHeader(format::Error),
    DecodeErrorMessage(format::Error),
    DecodePacket(format::Error),
    EncodingHeader(format::Error),
    EncodingBody(format::Error),
}

impl fmt::Display for Error {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match &self.kind {
            ErrorKind::EmptyPacket => write!(f, "Packet is empty"),
            ErrorKind::NotConnected => write!(f, "Client is not connected"),
            ErrorKind::Message(message) => write!(f, "{message}"),
            ErrorKind::Server(message) => write!(f, "Server error: {message}"),
            ErrorKind::Transport(..) => write!(f, "Error in underlying transport"),
            ErrorKind::DecodeResponseHeader(..) => {
                write!(f, "Encoding error when decoding response header")
            }
            ErrorKind::DecodeErrorMessage(..) => {
                write!(f, "Encoding error when decoding error response")
            }
            ErrorKind::DecodePacket(..) => write!(f, "Encoding error when decoding packet"),
            ErrorKind::EncodingHeader(..) => write!(f, "Encoding error when encoding header"),
            ErrorKind::EncodingBody(..) => write!(f, "Encoding error when encoding body"),
        }
    }
}

impl core::error::Error for Error {
    #[inline]
    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
        match &self.kind {
            ErrorKind::Transport(error) => Some(&**error),
            ErrorKind::DecodeResponseHeader(error) => Some(error),
            ErrorKind::DecodeErrorMessage(error) => Some(error),
            ErrorKind::DecodePacket(error) => Some(error),
            ErrorKind::EncodingHeader(error) => Some(error),
            ErrorKind::EncodingBody(error) => Some(error),
            _ => None,
        }
    }
}

type Result<T, E = Error> = core::result::Result<T, E>;

/// Slab of broadcast listeners.
type Broadcasts = HashMap<MessageId, Slab<mpsc::UnboundedSender<Result<RawPacket>>>>;

/// A command sent from a [`Handle`] to the [`Service`] driving the connection.
enum Command {
    /// Send an already encoded message and register a pending response.
    Send {
        serial: u32,
        data: Vec<u8>,
        pending: Pending,
    },
    /// Cleanly disconnect a channel.
    Disconnect { channel: ChannelId },
    /// Close the service, causing [`Service::run`] to return.
    Close,
}

/// A pending response being waited for.
enum Pending {
    /// A format negotiation issued by the service itself.
    Negotiate { format: Format },
    /// A regular request, tagged with the endpoint it belongs to.
    Request {
        id: MessageId,
        reply: oneshot::Sender<Result<RawPacket>>,
    },
    /// A channel being opened.
    Channel {
        reply: oneshot::Sender<Result<ChannelId>>,
    },
}

impl Pending {
    #[inline]
    fn error(self, error: Error) {
        match self {
            Pending::Negotiate { .. } => {
                tracing::debug!("Format negotiation failed: {error}");
            }
            Pending::Request { reply, .. } => {
                _ = reply.send(Err(error));
            }
            Pending::Channel { reply } => {
                _ = reply.send(Err(error));
            }
        }
    }
}

/// State shared between a [`Service`] and every [`Handle`] associated with it.
struct Shared {
    tx: mpsc::UnboundedSender<Command>,
    serial: AtomicU32,
    state: watch::Sender<State>,
    broadcasts: Mutex<Broadcasts>,
    /// Set once the service driving this state is gone, at which point no
    /// further state changes can be observed.
    gone: AtomicBool,
    /// The format which is actually in effect, as agreed by the [negotiation
    /// protocol]. This can differ from the requested format if the server did
    /// not support it.
    ///
    /// [negotiation protocol]: crate::api#negotiating-the-format
    format: AtomicU8,
}

impl Shared {
    #[inline]
    fn next_serial(&self) -> u32 {
        self.serial.fetch_add(1, Ordering::Relaxed)
    }

    #[inline]
    fn is_open(&self) -> bool {
        self.state.borrow().is_open()
    }

    /// The format currently in effect.
    #[inline]
    fn format(&self) -> Format {
        Format::from_u8(self.format.load(Ordering::Acquire)).unwrap_or(Format::DEFAULT)
    }

    #[inline]
    fn set_format(&self, format: Format) {
        self.format.store(format.to_u8(), Ordering::Release);
    }

    /// Test if the service driving this state is gone.
    #[inline]
    fn is_gone(&self) -> bool {
        self.gone.load(Ordering::Acquire)
    }

    /// Mark the service as gone and wake up anyone waiting for a state change.
    fn set_gone(&self) {
        self.gone.store(true, Ordering::Release);
        // NB: Unlike `send_if_modified` this always notifies, which is needed
        // to wake up waiters even if the state itself did not change.
        self.state.send_modify(|state| *state = State::Closed);
    }

    #[inline]
    fn send(&self, command: Command) -> Result<()> {
        if self.tx.send(command).is_err() {
            return Err(Error::message("Client service is down"));
        }

        Ok(())
    }
}

/// Builder of a [`Service`].
///
/// Constructed through [`connect()`].
pub struct ServiceBuilder<T, E> {
    url: String,
    on_error: E,
    reconnect: bool,
    seed: u64,
    format: Format,
    _marker: PhantomData<T>,
}

impl<T, E> ServiceBuilder<T, E>
where
    T: ClientImpl,
    E: Callback<Error>,
{
    /// Set the error handler to use for the service.
    ///
    /// Errors which are reported here are errors which cannot be associated
    /// with a particular request, such as a failure to connect or a message
    /// which could not be decoded.
    #[inline]
    pub fn on_error<U>(self, on_error: U) -> ServiceBuilder<T, U>
    where
        U: Callback<Error>,
    {
        ServiceBuilder {
            url: self.url,
            on_error,
            reconnect: self.reconnect,
            seed: self.seed,
            format: self.format,
            _marker: self._marker,
        }
    }

    /// Set the [`Format`] to use for message bodies.
    ///
    /// The format is negotiated with the server once the connection is
    /// established, see the [negotiation protocol]. If the server does not
    /// support it the error is reported through [`ServiceBuilder::on_error`]
    /// and the connection falls back to [`Format::DEFAULT`], which can be
    /// observed through [`Handle::format`].
    ///
    /// Defaults to [`Format::DEFAULT`].
    ///
    /// [negotiation protocol]: crate::api#negotiating-the-format
    #[inline]
    pub fn format(mut self, format: Format) -> Self {
        self.format = format;
        self
    }

    /// Configure whether the service should try to reconnect when the
    /// connection is lost.
    ///
    /// This defaults to `true`. If this is disabled, [`Service::run`] returns
    /// once the connection has been lost or could not be established.
    #[inline]
    pub fn reconnect(mut self, reconnect: bool) -> Self {
        self.reconnect = reconnect;
        self
    }

    /// Associate the specified seed with the service.
    ///
    /// This affects the random fuzzing which is applied to reconnect timeouts.
    ///
    /// By default the seed is a constant value.
    #[inline]
    pub fn seed(mut self, seed: u64) -> Self {
        self.seed = seed;
        self
    }

    /// Build the service.
    ///
    /// Note that no connection is established until [`Service::run`] is called.
    pub fn build(self) -> Service<T> {
        let (tx, rx) = mpsc::unbounded_channel();
        let (state, _) = watch::channel(State::Closed);

        let shared = Arc::new(Shared {
            tx,
            serial: AtomicU32::new(0),
            state,
            broadcasts: Mutex::new(Broadcasts::new()),
            gone: AtomicBool::new(false),
            format: AtomicU8::new(self.format.to_u8()),
        });

        Service {
            handle: Handle {
                shared: shared.clone(),
            },
            shared,
            rx,
            url: self.url,
            on_error: Box::new(self.on_error),
            reconnect: self.reconnect,
            socket: None,
            pending: HashMap::new(),
            timeout: INITIAL_TIMEOUT,
            next_attempt: Some(Instant::now()),
            rng: SmallRng::seed_from_u64(self.seed),
            closed: false,
            requested: self.format,
        }
    }
}

/// The service which drives a connection.
///
/// This is constructed through [`connect()`] and has to be driven by calling
/// [`Service::run`].
pub struct Service<T>
where
    T: ClientImpl,
{
    handle: Handle,
    shared: Arc<Shared>,
    rx: mpsc::UnboundedReceiver<Command>,
    url: String,
    on_error: Box<dyn Callback<Error>>,
    reconnect: bool,
    socket: Option<T::Socket>,
    pending: HashMap<u32, Pending>,
    timeout: Duration,
    next_attempt: Option<Instant>,
    rng: SmallRng,
    closed: bool,
    /// The format the user asked for, which is re-negotiated on every
    /// reconnect.
    requested: Format,
}

/// The event produced by one iteration of the [`Service::run`] loop.
enum Output<E> {
    /// A message was received over the socket.
    Message(Option<Result<Message, E>>),
    /// A command was received from a handle.
    Command(Option<Command>),
    /// It is time to try and establish a connection.
    Connect,
}

impl<T> Service<T>
where
    T: ClientImpl,
{
    /// Get a handle to the service.
    ///
    /// The returned handle can be cloned and moved freely between tasks.
    #[inline]
    pub fn handle(&self) -> &Handle {
        &self.handle
    }

    /// Run the service.
    ///
    /// This drives the underlying connection and must be called for any
    /// requests to be processed. It is typically spawned onto a task of its
    /// own.
    ///
    /// Unless disabled through [`ServiceBuilder::reconnect`], a connection
    /// which is lost is re-established with an exponential backoff. Any
    /// requests which were in flight at that point are failed.
    ///
    /// This returns once [`Handle::close`] has been called, or the connection
    /// has been lost while reconnecting is disabled.
    pub async fn run(&mut self) -> Result<()> {
        while !self.closed {
            let output = {
                let rx = &mut self.rx;

                match &mut self.socket {
                    Some(socket) => {
                        tokio::select! {
                            message = socket.recv() => Output::Message(message),
                            command = rx.recv() => Output::Command(command),
                        }
                    }
                    None => match self.next_attempt {
                        Some(deadline) => {
                            tokio::select! {
                                _ = tokio::time::sleep_until(deadline) => Output::Connect,
                                command = rx.recv() => Output::Command(command),
                            }
                        }
                        None => Output::Command(rx.recv().await),
                    },
                }
            };

            match output {
                Output::Connect => {
                    self.connect().await;
                }
                Output::Command(command) => {
                    let Some(command) = command else {
                        // Every handle has been dropped and no more commands
                        // can be received.
                        break;
                    };

                    self.command(command).await;
                }
                Output::Message(message) => {
                    let Some(message) = message else {
                        tracing::debug!("Connection closed by server");
                        self.disconnect().await;
                        continue;
                    };

                    let message = match message {
                        Ok(message) => message,
                        Err(error) => {
                            self.on_error.call(Error::transport(error));
                            self.disconnect().await;
                            continue;
                        }
                    };

                    match message {
                        Message::Binary(bytes) => match self.message(bytes) {
                            Ok(Post::Negotiate) => self.send_negotiate().await,
                            Ok(Post::None) => {}
                            Err(error) => self.on_error.call(error),
                        },
                        Message::Text => {
                            self.on_error
                                .call(Error::message("Unsupported text message"));
                            self.disconnect().await;
                        }
                        Message::Ping | Message::Pong => {}
                        Message::Close => {
                            tracing::debug!("Close message received");
                            self.disconnect().await;
                        }
                    }
                }
            }
        }

        self.shutdown().await;
        Ok(())
    }

    /// Try to establish a connection.
    async fn connect(&mut self) {
        tracing::debug!(url = self.url.as_str(), "Connecting");

        match T::connect(&self.url).await {
            Ok(socket) => {
                tracing::debug!("Connection established");
                self.socket = Some(socket);
                self.next_attempt = None;
                self.timeout = INITIAL_TIMEOUT;
            }
            Err(error) => {
                self.on_error.call(Error::transport(error));
                self.schedule_reconnect();
            }
        }
    }

    /// Tear down the current connection and schedule a reconnect.
    async fn disconnect(&mut self) {
        if let Some(mut socket) = self.socket.take() {
            _ = socket.close().await;
        }

        self.emit_state(State::Closed);
        self.close_pending(|| Error::message("Connection closed"));
        self.schedule_reconnect();
    }

    /// Shut the service down for good.
    async fn shutdown(&mut self) {
        if let Some(mut socket) = self.socket.take() {
            _ = socket.close().await;
        }

        self.emit_state(State::Closed);
        self.close_pending(|| Error::message("Client service closed"));
    }

    fn schedule_reconnect(&mut self) {
        if !self.reconnect {
            tracing::debug!("Reconnecting is disabled, closing service");
            self.closed = true;
            return;
        }

        let fuzz = self.rng.random_range(0..=MAX_FUZZ);

        let timeout = self
            .timeout
            .saturating_add(Duration::from_millis(fuzz))
            .min(MAX_TIMEOUT);

        self.timeout = self.timeout.saturating_mul(2).min(MAX_TIMEOUT);
        self.next_attempt = Some(Instant::now() + timeout);
        tracing::debug!(?timeout, "Scheduling reconnect");
    }

    /// Fail every pending request, since there is no chance they will be
    /// responded to any more.
    fn close_pending(&mut self, error: impl Fn() -> Error) {
        for (_, pending) in self.pending.drain() {
            pending.error(error());
        }
    }

    fn emit_state(&mut self, state: State) {
        self.shared.state.send_if_modified(|current| {
            if *current == state {
                return false;
            }

            *current = state;
            true
        });
    }

    /// Handle a command received from a handle.
    async fn command(&mut self, command: Command) {
        match command {
            Command::Send {
                serial,
                data,
                pending,
            } => {
                let Some(socket) = self.socket.as_mut() else {
                    pending.error(Error::new(ErrorKind::NotConnected));
                    return;
                };

                if let Err(error) = socket.send(&data).await {
                    pending.error(Error::transport(error));
                    self.disconnect().await;
                    return;
                }

                if let Some(existing) = self.pending.insert(serial, pending) {
                    existing.error(Error::message("Request cancelled"));
                }
            }
            Command::Disconnect { channel } => {
                if let Err(error) = self.send_disconnect(channel).await {
                    self.on_error.call(error);
                }
            }
            Command::Close => {
                self.closed = true;
            }
        }
    }

    async fn send_disconnect(&mut self, channel: ChannelId) -> Result<()> {
        let Some(socket) = self.socket.as_mut() else {
            return Ok(());
        };

        let mut data = Vec::new();

        let header = api::RequestHeader {
            serial: 0,
            id: MessageId::DISCONNECT.get(),
            // NB: Carries no body.
            format: 0,
            channel,
        };

        format::encode_envelope(&mut data, &header).map_err(Error::encoding_header)?;

        tracing::debug!(?channel, "Sending disconnect");

        if let Err(error) = socket.send(&data).await {
            let error = Error::transport(error);
            self.disconnect().await;
            return Err(error);
        }

        Ok(())
    }

    /// Dispatch a value to every listener of the given broadcast.
    ///
    /// Note that listeners are never removed here, since removal is the
    /// exclusive responsibility of the corresponding [`Listener`]. Sending to a
    /// listener which has been dropped but not yet cleared is simply ignored.
    fn dispatch(&self, id: MessageId, value: impl Fn() -> Result<RawPacket>) {
        let broadcasts = self
            .shared
            .broadcasts
            .lock()
            .unwrap_or_else(|e| e.into_inner());

        let Some(slots) = broadcasts.get(&id) else {
            return;
        };

        for (_, tx) in slots.iter() {
            _ = tx.send(value());
        }
    }

    /// Resolve the format a message body is encoded with from its envelope.
    fn body_format(header: &api::ResponseHeader) -> Result<Format> {
        let Some(format) = Format::from_u8(header.format) else {
            return Err(Error::message(format_args!(
                "Server used unknown format id {} for a message body",
                header.format
            )));
        };

        Ok(format)
    }

    /// Process an incoming binary message.
    fn message(&mut self, bytes: Bytes) -> Result<Post> {
        let mut at = 0;

        let header: api::ResponseHeader =
            format::decode_envelope(&bytes, &mut at).map_err(Error::decode_response_header)?;

        if let Some(broadcast) = MessageId::new(header.broadcast) {
            tracing::debug!(?header, "Got broadcast");

            if broadcast == MessageId::SERVER_HELLO {
                // NB: The connection is not reported as open until the format
                // has been negotiated, so that server-initiated messages are
                // never encoded with a format this client did not agree to.
                tracing::debug!("Server hello, negotiating format");
                return Ok(Post::Negotiate);
            }

            if let Some(id) = MessageId::new(header.error) {
                let error = match id {
                    MessageId::ERROR_MESSAGE => Self::body_format(&header)?
                        .decode(&bytes, &mut at)
                        .map_err(Error::decode_error_message)?,
                    _ => api::ErrorMessage {
                        message: "Unsupported broadcast",
                    },
                };

                self.dispatch(broadcast, || Err(Error::server(error.message)));
                return Ok(Post::None);
            }

            let format = Self::body_format(&header)?;

            let packet = RawPacket {
                id: broadcast,
                buf: bytes,
                at: Cell::new(at),
                format,
                channel: header.channel,
            };

            self.dispatch(broadcast, || Ok(packet.clone()));
            return Ok(Post::None);
        }

        tracing::debug!(?header, "Got response");

        let Some(pending) = self.pending.remove(&header.serial) else {
            // NB: This is normal, it simply indicates that the request has been
            // cancelled.
            tracing::trace!(?header.serial, "Got message with unknown serial");
            return Ok(Post::None);
        };

        if let Some(id) = MessageId::new(header.error) {
            let error = match id {
                MessageId::ERROR_MESSAGE => Self::body_format(&header)?
                    .decode(&bytes, &mut at)
                    .map_err(Error::decode_error_message)?,
                _ => api::ErrorMessage {
                    message: "Unsupported request",
                },
            };

            match pending {
                Pending::Negotiate { format } => {
                    // NB: The server cannot speak the requested format, so fall
                    // back to the default rather than leaving the connection
                    // unusable. The effective format is observable through
                    // `Handle::format`.
                    self.on_error.call(Error::message(format_args!(
                        "Server rejected format `{format}` ({}), falling back to `{}`",
                        error.message,
                        Format::DEFAULT
                    )));

                    self.shared.set_format(Format::DEFAULT);
                    self.emit_state(State::Open);
                }
                pending => {
                    pending.error(Error::server(error.message));
                }
            }

            return Ok(Post::None);
        }

        match pending {
            Pending::Negotiate { format } => {
                // NB: Trust the format the server echoed back over the one that
                // was asked for, so that a server which downgrades is honored.
                let accepted = Format::from_u8(header.format).unwrap_or(format);
                tracing::debug!(?accepted, "Format negotiated");
                self.shared.set_format(accepted);
                self.emit_state(State::Open);
            }
            Pending::Channel { reply } => {
                _ = reply.send(Ok(header.channel));
            }
            Pending::Request { id, reply } => {
                let format = Self::body_format(&header)?;

                let packet = RawPacket {
                    id,
                    buf: bytes,
                    at: Cell::new(at),
                    format,
                    channel: header.channel,
                };

                _ = reply.send(Ok(packet));
            }
        }

        Ok(Post::None)
    }

    /// Ask the server to use the requested format for the rest of the
    /// connection.
    async fn send_negotiate(&mut self) {
        let format = self.requested;
        let serial = self.shared.next_serial();

        let header = api::RequestHeader {
            serial,
            id: MessageId::NEGOTIATE.get(),
            format: format.to_u8(),
            // NB: Carries no body.
            channel: ChannelId::NONE,
        };

        let mut data = Vec::new();

        if let Err(error) = format::encode_envelope(&mut data, &header) {
            self.on_error.call(Error::encoding_header(error));
            return;
        }

        let Some(socket) = self.socket.as_mut() else {
            return;
        };

        tracing::debug!(?format, "Requesting format");

        if let Err(error) = socket.send(&data).await {
            self.on_error.call(Error::transport(error));
            self.disconnect().await;
            return;
        }

        self.pending.insert(serial, Pending::Negotiate { format });
    }
}

/// Work which has to happen after a message has been processed, once the
/// borrow of the message buffer has been released.
enum Post {
    /// Nothing to do.
    None,
    /// The format has to be negotiated with the server.
    Negotiate,
}

impl<T> Drop for Service<T>
where
    T: ClientImpl,
{
    fn drop(&mut self) {
        self.shared.set_gone();

        for (_, pending) in self.pending.drain() {
            pending.error(Error::message("Client service closed"));
        }

        self.shared
            .broadcasts
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .clear();
    }
}

impl<T> fmt::Debug for Service<T>
where
    T: ClientImpl,
{
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Service")
            .field("url", &self.url)
            .field("state", &*self.shared.state.borrow())
            .finish_non_exhaustive()
    }
}

/// A handle to the client service.
///
/// This is cheap to clone and can be moved freely between tasks.
#[derive(Clone)]
pub struct Handle {
    shared: Arc<Shared>,
}

impl Handle {
    /// Get the current state of the connection.
    #[inline]
    pub fn state(&self) -> State {
        *self.shared.state.borrow()
    }

    /// Check if the connection is currently open.
    #[inline]
    pub fn is_open(&self) -> bool {
        self.shared.is_open()
    }

    /// The [`Format`] currently in effect for message bodies.
    ///
    /// Before the connection has been opened this is the format which was
    /// requested through [`ServiceBuilder::format`]. Once the connection is
    /// open it is the format the server actually agreed to, which can differ if
    /// the server does not support what was asked for.
    #[inline]
    pub fn format(&self) -> Format {
        self.shared.format()
    }

    /// Listen for state changes to the underlying connection.
    ///
    /// This indicates when the connection is open and ready to receive requests
    /// through [`State::Open`], or if it's closed and requests will be rejected
    /// through [`State::Closed`].
    #[inline]
    pub fn on_state_change(&self) -> StateListener {
        StateListener {
            rx: self.shared.state.subscribe(),
            shared: self.shared.clone(),
        }
    }

    /// Wait until the connection is open.
    ///
    /// Since a connection is established asynchronously, this must be called
    /// before performing the first request unless you are prepared to handle
    /// the [`Error::is_not_connected`] error.
    ///
    /// This errors if the [`Service`] driving the connection is gone, since the
    /// connection can then never be established.
    pub async fn wait_until_open(&self) -> Result<()> {
        let mut listener = self.on_state_change();

        if listener.wait_until(State::Open).await {
            return Ok(());
        }

        Err(Error::message("Client service is down"))
    }

    /// Open a new logical channel to the websocket server.
    ///
    /// A channel can be uniquely identified on the client and server side over
    /// a single connection. This means that if you send a request over a
    /// channel using [`Channel::request`], the server can access the
    /// [`ChannelId`] to determine which channel sent the request and the client
    /// has the ability to correlate any responses sent by the server by
    /// inspecting [`Packet::channel`] or [`RawPacket::channel`].
    ///
    /// The maximum number of channels is implementation defined, but expect it
    /// to be relatively low like `65535` (non-zero 16 bits) to reduce payload
    /// sizes. Failure to allocate a channel is an error.
    ///
    /// Note that a channel is scoped to the connection it was opened over. If
    /// the connection is lost and re-established, any channel opened over the
    /// old connection is stale and has to be opened again.
    pub async fn channel(&self) -> Result<Channel> {
        if !self.shared.is_open() {
            return Err(Error::new(ErrorKind::NotConnected));
        }

        let serial = self.shared.next_serial();

        let header = api::RequestHeader {
            serial,
            id: MessageId::CONNECT.get(),
            // NB: Carries no body.
            format: 0,
            channel: ChannelId::NONE,
        };

        let mut data = Vec::new();
        format::encode_envelope(&mut data, &header).map_err(Error::encoding_header)?;

        let (reply, rx) = oneshot::channel();

        self.shared.send(Command::Send {
            serial,
            data,
            pending: Pending::Channel { reply },
        })?;

        let Ok(result) = rx.await else {
            return Err(Error::message("Client service is down"));
        };

        Ok(Channel {
            shared: self.shared.clone(),
            id: result?,
        })
    }

    /// Send a request over the default channel.
    ///
    /// See [`RequestBuilder::send`] for how the request is completed.
    #[inline]
    pub fn request(&self) -> RequestBuilder<'_, EmptyBody> {
        RequestBuilder {
            shared: &self.shared,
            channel: ChannelId::NONE,
            body: EmptyBody,
        }
    }

    /// Listen for broadcasts of type `T`.
    ///
    /// Broadcasts are buffered in the returned listener until they are received
    /// with [`Listener::recv`]. Dropping the listener removes it.
    ///
    /// Note that the buffer is unbounded, so a listener which is not drained
    /// keeps accumulating broadcasts. Drop or [`clear`] a listener which is no
    /// longer of interest.
    ///
    /// [`clear`]: Listener::clear
    pub fn on_broadcast<T>(&self) -> Listener<T>
    where
        T: api::Broadcast,
    {
        let (tx, rx) = mpsc::unbounded_channel();

        let index = {
            let mut broadcasts = self
                .shared
                .broadcasts
                .lock()
                .unwrap_or_else(|e| e.into_inner());

            broadcasts.entry(T::ID).or_default().insert(tx)
        };

        Listener {
            shared: Some(self.shared.clone()),
            id: T::ID,
            index,
            rx,
            _marker: PhantomData,
        }
    }

    /// Close the service.
    ///
    /// This causes [`Service::run`] to return.
    #[inline]
    pub fn close(&self) {
        _ = self.shared.tx.send(Command::Close);
    }
}

impl PartialEq for Handle {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        Arc::ptr_eq(&self.shared, &other.shared)
    }
}

impl Eq for Handle {}

impl fmt::Debug for Handle {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Handle")
            .field("state", &*self.shared.state.borrow())
            .finish_non_exhaustive()
    }
}

/// A channel to a websocket server.
///
/// See [`Handle::channel`] for more details.
///
/// Dropping this cleanly disconnects the channel, which is signalled to the
/// server through [`Handler::close_channel`].
///
/// [`Handler::close_channel`]: <https://docs.rs/musli-web/latest/musli_web/ws/trait.Handler.html#method.close_channel>
pub struct Channel {
    shared: Arc<Shared>,
    id: ChannelId,
}

impl Channel {
    /// Get the channel identifier for this channel.
    #[inline]
    pub fn id(&self) -> ChannelId {
        self.id
    }

    /// Get a handle associated with this channel.
    ///
    /// A handle sheds the channel information and allows for setting up things
    /// like broadcast listeners.
    #[inline]
    pub fn handle(&self) -> Handle {
        Handle {
            shared: self.shared.clone(),
        }
    }

    /// Send a request over the current channel.
    ///
    /// See [`RequestBuilder::send`] for how the request is completed.
    #[inline]
    pub fn request(&self) -> RequestBuilder<'_, EmptyBody> {
        RequestBuilder {
            shared: &self.shared,
            channel: self.id,
            body: EmptyBody,
        }
    }
}

impl Drop for Channel {
    #[inline]
    fn drop(&mut self) {
        _ = self.shared.send(Command::Disconnect { channel: self.id });
    }
}

impl fmt::Debug for Channel {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Channel")
            .field("id", &self.id)
            .field("state", &*self.shared.state.borrow())
            .finish_non_exhaustive()
    }
}

/// A request builder.
///
/// Set the body of the request with [`RequestBuilder::body`] and send it with
/// [`RequestBuilder::send`].
pub struct RequestBuilder<'a, B> {
    shared: &'a Arc<Shared>,
    channel: ChannelId,
    body: B,
}

impl<'a, B> RequestBuilder<'a, B> {
    /// Set the body of the request.
    #[inline]
    pub fn body<U>(self, body: U) -> RequestBuilder<'a, U>
    where
        U: api::Request,
    {
        RequestBuilder {
            shared: self.shared,
            channel: self.channel,
            body,
        }
    }
}

impl<B> RequestBuilder<'_, B>
where
    B: api::Request,
{
    /// Send the request and wait for the typed response.
    pub async fn send(self) -> Result<Packet<B::Endpoint>> {
        Ok(Packet::new(self.send_raw().await?))
    }

    /// Send the request and wait for the raw response.
    pub async fn send_raw(self) -> Result<RawPacket> {
        let id = <B::Endpoint as api::Endpoint>::ID;

        if !self.shared.is_open() {
            return Err(Error::new(ErrorKind::NotConnected));
        }

        let serial = self.shared.next_serial();
        let format = self.shared.format();

        let header = api::RequestHeader {
            serial,
            id: id.get(),
            format: format.to_u8(),
            channel: self.channel,
        };

        let mut data = Vec::new();
        format::encode_envelope(&mut data, &header).map_err(Error::encoding_header)?;
        format
            .encode(&mut data, &self.body)
            .map_err(Error::encoding_body)?;

        tracing::debug!(serial, ?id, ?format, len = data.len(), "Sending request");

        let (reply, rx) = oneshot::channel();

        self.shared.send(Command::Send {
            serial,
            data,
            pending: Pending::Request { id, reply },
        })?;

        let Ok(result) = rx.await else {
            return Err(Error::message("Client service is down"));
        };

        result
    }
}

/// A listener for broadcasts of type `T`.
///
/// Constructed through [`Handle::on_broadcast`]. Dropping this removes the
/// listener.
pub struct Listener<T> {
    shared: Option<Arc<Shared>>,
    id: MessageId,
    index: usize,
    rx: mpsc::UnboundedReceiver<Result<RawPacket>>,
    _marker: PhantomData<T>,
}

impl<T> Listener<T> {
    /// Receive the next raw broadcast.
    ///
    /// Returns `None` if the service has been shut down.
    #[inline]
    pub async fn recv_raw(&mut self) -> Option<Result<RawPacket>> {
        self.rx.recv().await
    }

    /// Receive the next broadcast.
    ///
    /// Returns `None` if the service has been shut down.
    #[inline]
    pub async fn recv(&mut self) -> Option<Result<Packet<T>>> {
        Some(match self.rx.recv().await? {
            Ok(packet) => Ok(Packet::new(packet)),
            Err(error) => Err(error),
        })
    }

    /// Clear the listener without dropping it.
    ///
    /// This removes the associated listener from being notified. Any broadcasts
    /// which have already been buffered can still be received, after which
    /// [`Listener::recv`] returns `None`.
    pub fn clear(&mut self) {
        let Some(shared) = self.shared.take() else {
            return;
        };

        let index = mem::take(&mut self.index);

        let mut broadcasts = shared.broadcasts.lock().unwrap_or_else(|e| e.into_inner());

        let Entry::Occupied(mut e) = broadcasts.entry(self.id) else {
            return;
        };

        _ = e.get_mut().try_remove(index);

        if e.get().is_empty() {
            e.remove();
        }
    }
}

impl<T> Drop for Listener<T> {
    #[inline]
    fn drop(&mut self) {
        self.clear();
    }
}

impl<T> fmt::Debug for Listener<T> {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Listener")
            .field("type", &any::type_name::<T>())
            .field("id", &self.id)
            .finish_non_exhaustive()
    }
}

/// A listener for state changes.
///
/// Constructed through [`Handle::on_state_change`].
pub struct StateListener {
    rx: watch::Receiver<State>,
    shared: Arc<Shared>,
}

impl StateListener {
    /// Get the most recently observed state.
    #[inline]
    pub fn state(&self) -> State {
        *self.rx.borrow()
    }

    /// Wait for the state to change and return the new state.
    ///
    /// Returns `None` if the [`Service`] driving the connection is gone.
    #[inline]
    pub async fn changed(&mut self) -> Option<State> {
        if self.shared.is_gone() {
            return None;
        }

        self.rx.changed().await.ok()?;

        if self.shared.is_gone() {
            return None;
        }

        Some(*self.rx.borrow_and_update())
    }

    /// Wait until the observed state is `state`.
    ///
    /// Returns `false` if the [`Service`] driving the connection is gone before
    /// the state could be observed.
    pub async fn wait_until(&mut self, state: State) -> bool {
        loop {
            if *self.rx.borrow_and_update() == state {
                return true;
            }

            if self.shared.is_gone() {
                return false;
            }

            if self.rx.changed().await.is_err() {
                return false;
            }
        }
    }
}

impl Clone for StateListener {
    #[inline]
    fn clone(&self) -> Self {
        Self {
            rx: self.rx.clone(),
            shared: self.shared.clone(),
        }
    }
}

impl fmt::Debug for StateListener {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("StateListener")
            .field("state", &*self.rx.borrow())
            .finish()
    }
}

/// A raw packet of data.
#[derive(Clone)]
pub struct RawPacket {
    id: MessageId,
    buf: Bytes,
    at: Cell<usize>,
    format: Format,
    channel: ChannelId,
}

impl RawPacket {
    /// Construct an empty raw packet.
    ///
    /// # Examples
    ///
    /// ```
    /// use musli_web::api::MessageId;
    /// use musli_web::client::RawPacket;
    ///
    /// let packet = RawPacket::empty();
    ///
    /// assert!(packet.is_empty());
    /// assert_eq!(packet.id(), MessageId::EMPTY);
    /// ```
    #[inline]
    pub const fn empty() -> Self {
        Self {
            id: MessageId::EMPTY,
            buf: Bytes::new(),
            at: Cell::new(0),
            format: Format::DEFAULT,
            channel: ChannelId::NONE,
        }
    }

    /// The [`Format`] the body of this packet is encoded with.
    ///
    /// # Examples
    ///
    /// ```
    /// use musli_web::api::Format;
    /// use musli_web::client::RawPacket;
    ///
    /// let packet = RawPacket::empty();
    /// assert_eq!(packet.format(), Format::DEFAULT);
    /// ```
    #[inline]
    pub fn format(&self) -> Format {
        self.format
    }

    /// Return the channel this packet belongs to.
    ///
    /// This is [`ChannelId::NONE`] unless the packet belongs to a response over
    /// a channel constructed with [`Handle::channel`].
    #[inline]
    pub fn channel(&self) -> ChannelId {
        self.channel
    }

    /// Decode the contents of a raw packet.
    ///
    /// This can be called multiple times if there are multiple payloads in
    /// sequence of the response.
    ///
    /// You can check if the packet is empty using [`RawPacket::is_empty`].
    pub fn decode<'this, T>(&'this self) -> Result<T>
    where
        T: DecodeBody<'this>,
    {
        if self.id == MessageId::EMPTY {
            return Err(Error::new(ErrorKind::EmptyPacket));
        }

        let mut at = self.at.get();

        match self.format.decode(&self.buf, &mut at) {
            Ok(value) => {
                self.at.set(at);
                Ok(value)
            }
            Err(error) => {
                self.at.set(self.len());
                Err(Error::decode_packet(error))
            }
        }
    }

    /// Get the underlying byte slice of the packet.
    ///
    /// # Examples
    ///
    /// ```
    /// use musli_web::client::RawPacket;
    ///
    /// let packet = RawPacket::empty();
    /// assert_eq!(packet.as_slice(), &[] as &[u8]);
    /// ```
    #[inline]
    pub fn as_slice(&self) -> &[u8] {
        &self.buf
    }

    /// Get the number of bytes remaining to be decoded in the packet.
    ///
    /// # Examples
    ///
    /// ```
    /// use musli_web::client::RawPacket;
    ///
    /// let packet = RawPacket::empty();
    /// assert_eq!(packet.remaining(), 0);
    /// ```
    #[inline]
    pub fn remaining(&self) -> usize {
        self.buf.len().saturating_sub(self.at.get())
    }

    /// Get the length of the packet.
    ///
    /// # Examples
    ///
    /// ```
    /// use musli_web::client::RawPacket;
    ///
    /// let packet = RawPacket::empty();
    /// assert_eq!(packet.len(), 0);
    /// ```
    #[inline]
    pub fn len(&self) -> usize {
        self.buf.len()
    }

    /// Check if the packet is empty.
    ///
    /// # Examples
    ///
    /// ```
    /// use musli_web::client::RawPacket;
    ///
    /// let packet = RawPacket::empty();
    /// assert!(packet.is_empty());
    /// ```
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.at.get() >= self.len()
    }

    /// The id of the packet this is a response to as specified by
    /// [`Endpoint::ID`] or [`Broadcast::ID`].
    ///
    /// [`Endpoint::ID`]: crate::api::Endpoint::ID
    /// [`Broadcast::ID`]: crate::api::Broadcast::ID
    #[inline]
    pub fn id(&self) -> MessageId {
        self.id
    }
}

impl fmt::Debug for RawPacket {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("RawPacket")
            .field("id", &self.id)
            .field("remaining", &self.remaining())
            .finish()
    }
}

/// A typed packet of data.
pub struct Packet<T> {
    raw: RawPacket,
    _marker: PhantomData<T>,
}

impl<T> Packet<T> {
    /// Construct an empty packet.
    ///
    /// # Examples
    ///
    /// ```
    /// use musli_web::api::MessageId;
    /// use musli_web::client::Packet;
    ///
    /// let packet = Packet::<()>::empty();
    ///
    /// assert!(packet.is_empty());
    /// assert_eq!(packet.id(), MessageId::EMPTY);
    /// ```
    #[inline]
    pub const fn empty() -> Self {
        Self {
            raw: RawPacket::empty(),
            _marker: PhantomData,
        }
    }

    /// Construct a new typed packet from a raw one.
    ///
    /// Note that this does not guarantee that the typed packet is correct, but
    /// the `T` parameter becomes associated with it allowing it to be used
    /// automatically with methods such as [`Packet::decode`].
    #[inline]
    pub fn new(raw: RawPacket) -> Self {
        Self {
            raw,
            _marker: PhantomData,
        }
    }

    /// Return the channel this packet belongs to.
    ///
    /// This is [`ChannelId::NONE`] unless the packet belongs to a response over
    /// a channel constructed with [`Handle::channel`].
    #[inline]
    pub fn channel(&self) -> ChannelId {
        self.raw.channel()
    }

    /// The [`Format`] the body of this packet is encoded with.
    #[inline]
    pub fn format(&self) -> Format {
        self.raw.format()
    }

    /// Convert a packet into a raw packet.
    #[inline]
    pub fn into_raw(self) -> RawPacket {
        self.raw
    }

    /// Get the number of bytes remaining to be decoded in the packet.
    ///
    /// # Examples
    ///
    /// ```
    /// use musli_web::client::Packet;
    ///
    /// let packet = Packet::<()>::empty();
    /// assert_eq!(packet.remaining(), 0);
    /// ```
    #[inline]
    pub fn remaining(&self) -> usize {
        self.raw.remaining()
    }

    /// Check if the packet is empty.
    ///
    /// # Examples
    ///
    /// ```
    /// use musli_web::client::Packet;
    ///
    /// let packet = Packet::<()>::empty();
    /// assert!(packet.is_empty());
    /// ```
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.raw.is_empty()
    }

    /// The id of the packet this is a response to as specified by
    /// [`Endpoint::ID`] or [`Broadcast::ID`].
    ///
    /// [`Endpoint::ID`]: crate::api::Endpoint::ID
    /// [`Broadcast::ID`]: crate::api::Broadcast::ID
    #[inline]
    pub fn id(&self) -> MessageId {
        self.raw.id()
    }
}

impl<T> Packet<T>
where
    T: api::Decodable,
{
    /// Decode the contents of a packet.
    ///
    /// This can be called multiple times if there are multiple payloads in
    /// sequence of the response.
    ///
    /// You can check if the packet is empty using [`Packet::is_empty`].
    #[inline]
    pub fn decode(&self) -> Result<T::Type<'_>> {
        self.decode_any()
    }

    /// Decode any contents of a packet.
    ///
    /// This can be called multiple times if there are multiple payloads in
    /// sequence of the response.
    ///
    /// You can check if the packet is empty using [`Packet::is_empty`].
    #[inline]
    pub fn decode_any<'de, R>(&'de self) -> Result<R>
    where
        R: DecodeBody<'de>,
    {
        self.raw.decode()
    }
}

impl<T> Packet<T>
where
    T: api::Endpoint,
{
    /// Decode the response of a packet.
    ///
    /// This can be called multiple times if there are multiple payloads in
    /// sequence of the response.
    ///
    /// You can check if the packet is empty using [`Packet::is_empty`].
    #[inline]
    pub fn decode_response(&self) -> Result<T::Response<'_>> {
        self.decode_any_response()
    }

    /// Decode any response of a packet.
    ///
    /// This can be called multiple times if there are multiple payloads in
    /// sequence of the response.
    ///
    /// You can check if the packet is empty using [`Packet::is_empty`].
    #[inline]
    pub fn decode_any_response<'de, R>(&'de self) -> Result<R>
    where
        R: DecodeBody<'de>,
    {
        self.raw.decode()
    }
}

impl<T> Packet<T>
where
    T: api::Broadcast,
{
    /// Decode the primary event related to a broadcast.
    #[inline]
    pub fn decode_event<'de>(&'de self) -> Result<T::Event<'de>>
    where
        T: api::BroadcastWithEvent,
    {
        self.decode_event_any()
    }

    /// Decode any event related to a broadcast.
    #[inline]
    pub fn decode_event_any<'de, E>(&'de self) -> Result<E>
    where
        E: Event<Broadcast = T> + DecodeBody<'de>,
    {
        self.raw.decode()
    }
}

impl<T> Clone for Packet<T> {
    #[inline]
    fn clone(&self) -> Self {
        Self {
            raw: self.raw.clone(),
            _marker: PhantomData,
        }
    }
}

impl<T> fmt::Debug for Packet<T> {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Packet")
            .field("type", &any::type_name::<T>())
            .field("remaining", &self.remaining())
            .finish()
    }
}