fidl/
client.rs

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

//! An implementation of a client for a fidl interface.

use crate::encoding::{
    decode_transaction_header, Decode, Decoder, DefaultFuchsiaResourceDialect, DynamicFlags,
    Encode, Encoder, EpitaphBody, MessageBufFor, ProxyChannelBox, ProxyChannelFor, ResourceDialect,
    TransactionHeader, TransactionMessage, TransactionMessageType, TypeMarker,
};
use crate::Error;
use fuchsia_sync::Mutex;
use futures::future::{self, FusedFuture, Future, FutureExt, Map, MaybeDone};
use futures::ready;
use futures::stream::{FusedStream, Stream};
use futures::task::{Context, Poll, Waker};
use slab::Slab;
use std::collections::VecDeque;
use std::mem;
use std::ops::ControlFlow;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{RawWaker, RawWakerVTable};
use zx_status;

/// Decodes the body of `buf` as the FIDL type `T`.
#[doc(hidden)] // only exported for use in macros or generated code
pub fn decode_transaction_body<T: TypeMarker, D: ResourceDialect, const EXPECTED_ORDINAL: u64>(
    mut buf: D::MessageBufEtc,
) -> Result<T::Owned, Error>
where
    T::Owned: Decode<T, D>,
{
    let (bytes, handles) = buf.split_mut();
    let (header, body_bytes) = decode_transaction_header(bytes)?;
    if header.ordinal != EXPECTED_ORDINAL {
        return Err(Error::InvalidResponseOrdinal);
    }
    let mut output = Decode::<T, D>::new_empty();
    Decoder::<D>::decode_into::<T>(&header, body_bytes, handles, &mut output)?;
    Ok(output)
}

/// A FIDL client which can be used to send buffers and receive responses via a channel.
#[derive(Debug, Clone)]
pub struct Client<D: ResourceDialect = DefaultFuchsiaResourceDialect> {
    inner: Arc<ClientInner<D>>,
}

/// A future representing the decoded and transformed response to a FIDL query.
pub type DecodedQueryResponseFut<T, D = DefaultFuchsiaResourceDialect> = Map<
    MessageResponse<D>,
    fn(Result<<D as ResourceDialect>::MessageBufEtc, Error>) -> Result<T, Error>,
>;

/// A future representing the result of a FIDL query, with early error detection available if the
/// message couldn't be sent.
#[derive(Debug)]
#[must_use = "futures do nothing unless you `.await` or poll them"]
pub struct QueryResponseFut<T, D: ResourceDialect = DefaultFuchsiaResourceDialect>(
    pub MaybeDone<DecodedQueryResponseFut<T, D>>,
);

impl<T: Unpin, D: ResourceDialect> FusedFuture for QueryResponseFut<T, D> {
    fn is_terminated(&self) -> bool {
        matches!(self.0, MaybeDone::Gone)
    }
}

impl<T: Unpin, D: ResourceDialect> Future for QueryResponseFut<T, D> {
    type Output = Result<T, Error>;

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        ready!(self.0.poll_unpin(cx));
        let maybe_done = Pin::new(&mut self.0);
        Poll::Ready(maybe_done.take_output().unwrap_or(Err(Error::PollAfterCompletion)))
    }
}

impl<T> QueryResponseFut<T> {
    /// Check to see if the query has an error. If there was en error sending, this returns it and
    /// the error is returned, otherwise it returns self, which can then be awaited on:
    /// i.e. match echo_proxy.echo("something").check() {
    ///      Err(e) => error!("Couldn't send: {}", e),
    ///      Ok(fut) => fut.await
    /// }
    pub fn check(self) -> Result<Self, Error> {
        match self.0 {
            MaybeDone::Done(Err(e)) => Err(e),
            x => Ok(QueryResponseFut(x)),
        }
    }
}

/// A FIDL transaction id. Will not be zero for a message that includes a response.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct Txid(u32);
/// A message interest id.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
struct InterestId(usize);

impl InterestId {
    fn from_txid(txid: Txid) -> Self {
        InterestId(txid.0 as usize - 1)
    }
}

impl Txid {
    fn from_interest_id(int_id: InterestId) -> Self {
        Txid((int_id.0 + 1) as u32)
    }

    /// Get the raw u32 transaction ID.
    pub fn as_raw_id(&self) -> u32 {
        self.0
    }
}

impl From<u32> for Txid {
    fn from(txid: u32) -> Self {
        Self(txid)
    }
}

impl<D: ResourceDialect> Client<D> {
    /// Create a new client.
    ///
    /// `channel` is the asynchronous channel over which data is sent and received.
    /// `event_ordinals` are the ordinals on which events will be received.
    pub fn new(channel: D::ProxyChannel, protocol_name: &'static str) -> Client<D> {
        Client {
            inner: Arc::new(ClientInner {
                channel: channel.boxed(),
                interests: Mutex::default(),
                terminal_error: Mutex::default(),
                protocol_name,
            }),
        }
    }

    /// Get a reference to the client's underlying channel.
    pub fn as_channel(&self) -> &D::ProxyChannel {
        self.inner.channel.as_channel()
    }

    /// Attempt to convert the `Client` back into a channel.
    ///
    /// This will only succeed if there are no active clones of this `Client`,
    /// no currently-alive `EventReceiver` or `MessageResponse`s that came from
    /// this `Client`, and no outstanding messages awaiting a response, even if
    /// that response will be discarded.
    pub fn into_channel(self) -> Result<D::ProxyChannel, Self> {
        // We need to check the message_interests table to make sure there are no outstanding
        // interests, since an interest might still exist even if all EventReceivers and
        // MessageResponses have been dropped. That would lead to returning an AsyncChannel which
        // could then later receive the outstanding response unexpectedly.
        //
        // We do try_unwrap before checking the message_interests to avoid a race where another
        // thread inserts a new value into message_interests after we check
        // message_interests.is_empty(), but before we get to try_unwrap. This forces us to create a
        // new Arc if message_interests isn't empty, since try_unwrap destroys the original Arc.
        match Arc::try_unwrap(self.inner) {
            Ok(inner) => {
                if inner.interests.lock().messages.is_empty() || inner.channel.is_closed() {
                    Ok(inner.channel.unbox())
                } else {
                    // This creates a new arc if there are outstanding interests. This will drop
                    // weak references, and whilst we do create a weak reference to ClientInner if
                    // we use it as a waker, it doesn't matter because if we have got this far, the
                    // waker is obsolete: no tasks are waiting.
                    Err(Self { inner: Arc::new(inner) })
                }
            }
            Err(inner) => Err(Self { inner }),
        }
    }

    /// Retrieve the stream of event messages for the `Client`.
    /// Panics if the stream was already taken.
    pub fn take_event_receiver(&self) -> EventReceiver<D> {
        {
            let mut lock = self.inner.interests.lock();

            if let EventListener::None = lock.event_listener {
                lock.event_listener = EventListener::WillPoll;
            } else {
                panic!("Event stream was already taken");
            }
        }

        EventReceiver { inner: self.inner.clone(), state: EventReceiverState::Active }
    }

    /// Encodes and sends a request without expecting a response.
    pub fn send<T: TypeMarker>(
        &self,
        body: impl Encode<T, D>,
        ordinal: u64,
        dynamic_flags: DynamicFlags,
    ) -> Result<(), Error> {
        let msg =
            TransactionMessage { header: TransactionHeader::new(0, ordinal, dynamic_flags), body };
        crate::encoding::with_tls_encoded::<TransactionMessageType<T>, D, ()>(
            msg,
            |bytes, handles| self.send_raw(bytes, handles),
        )
    }

    /// Encodes and sends a request. Returns a future that decodes the response.
    pub fn send_query<Request: TypeMarker, Response: TypeMarker, const ORDINAL: u64>(
        &self,
        body: impl Encode<Request, D>,
        dynamic_flags: DynamicFlags,
    ) -> QueryResponseFut<Response::Owned, D>
    where
        Response::Owned: Decode<Response, D>,
    {
        self.send_query_and_decode::<Request, Response::Owned>(
            body,
            ORDINAL,
            dynamic_flags,
            |buf| buf.and_then(decode_transaction_body::<Response, D, ORDINAL>),
        )
    }

    /// Encodes and sends a request. Returns a future that decodes the response
    /// using the given `decode` function.
    pub fn send_query_and_decode<Request: TypeMarker, Output>(
        &self,
        body: impl Encode<Request, D>,
        ordinal: u64,
        dynamic_flags: DynamicFlags,
        decode: fn(Result<D::MessageBufEtc, Error>) -> Result<Output, Error>,
    ) -> QueryResponseFut<Output, D> {
        let send_result = self.send_raw_query(|tx_id, bytes, handles| {
            let msg = TransactionMessage {
                header: TransactionHeader::new(tx_id.as_raw_id(), ordinal, dynamic_flags),
                body,
            };
            Encoder::encode::<TransactionMessageType<Request>>(bytes, handles, msg)?;
            Ok(())
        });

        QueryResponseFut(match send_result {
            Ok(res_fut) => future::maybe_done(res_fut.map(decode)),
            Err(e) => MaybeDone::Done(Err(e)),
        })
    }

    /// Sends a raw message without expecting a response.
    pub fn send_raw(
        &self,
        bytes: &[u8],
        handles: &mut [<D::ProxyChannel as ProxyChannelFor<D>>::HandleDisposition],
    ) -> Result<(), Error> {
        match self.inner.channel.write_etc(bytes, handles) {
            Ok(()) | Err(None) => Ok(()),
            Err(Some(e)) => Err(Error::ClientWrite(e.into())),
        }
    }

    /// Sends a raw query and receives a response future.
    pub fn send_raw_query<F>(&self, encode_msg: F) -> Result<MessageResponse<D>, Error>
    where
        F: for<'a, 'b> FnOnce(
            Txid,
            &'a mut Vec<u8>,
            &'b mut Vec<<D::ProxyChannel as ProxyChannelFor<D>>::HandleDisposition>,
        ) -> Result<(), Error>,
    {
        let id = self.inner.interests.lock().register_msg_interest();
        crate::encoding::with_tls_encode_buf::<_, D>(|bytes, handles| {
            encode_msg(id, bytes, handles)?;
            self.send_raw(bytes, handles)
        })?;

        Ok(MessageResponse { id, client: Some(self.inner.clone()) })
    }
}

#[must_use]
/// A future which polls for the response to a client message.
#[derive(Debug)]
pub struct MessageResponse<D: ResourceDialect = DefaultFuchsiaResourceDialect> {
    id: Txid,
    // `None` if the message response has been received
    client: Option<Arc<ClientInner<D>>>,
}

impl<D: ResourceDialect> Unpin for MessageResponse<D> {}

impl<D: ResourceDialect> Future for MessageResponse<D> {
    type Output = Result<D::MessageBufEtc, Error>;
    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let this = &mut *self;
        let res;
        {
            let client = this.client.as_ref().ok_or(Error::PollAfterCompletion)?;
            res = client.poll_recv_msg_response(this.id, cx);
        }

        // Drop the client reference if the response has been received
        if let Poll::Ready(Ok(_)) = res {
            this.client.take().expect("MessageResponse polled after completion");
        }

        res
    }
}

impl<D: ResourceDialect> Drop for MessageResponse<D> {
    fn drop(&mut self) {
        if let Some(client) = &self.client {
            client.interests.lock().deregister(self.id);
        }
    }
}

/// An enum reprenting either a resolved message interest or a task on which to alert
/// that a response message has arrived.
#[derive(Debug)]
enum MessageInterest<D: ResourceDialect> {
    /// A new `MessageInterest`
    WillPoll,
    /// A task is waiting to receive a response, and can be awoken with `Waker`.
    Waiting(Waker),
    /// A message has been received, and a task will poll to receive it.
    Received(D::MessageBufEtc),
    /// A message has not been received, but the person interested in the response
    /// no longer cares about it, so the message should be discared upon arrival.
    Discard,
}

impl<D: ResourceDialect> MessageInterest<D> {
    /// Check if a message has been received.
    fn is_received(&self) -> bool {
        matches!(*self, MessageInterest::Received(_))
    }

    fn unwrap_received(self) -> D::MessageBufEtc {
        if let MessageInterest::Received(buf) = self {
            buf
        } else {
            panic!("EXPECTED received message")
        }
    }
}

#[derive(Debug)]
enum EventReceiverState {
    Active,
    Terminal,
    Terminated,
}

/// A stream of events as `MessageBufEtc`s.
#[derive(Debug)]
pub struct EventReceiver<D: ResourceDialect = DefaultFuchsiaResourceDialect> {
    inner: Arc<ClientInner<D>>,
    state: EventReceiverState,
}

impl<D: ResourceDialect> Unpin for EventReceiver<D> {}

impl<D: ResourceDialect> FusedStream for EventReceiver<D> {
    fn is_terminated(&self) -> bool {
        matches!(self.state, EventReceiverState::Terminated)
    }
}

/// This implementation holds up two invariants
///   (1) After `None` is returned, the next poll panics
///   (2) Until this instance is dropped, no other EventReceiver may claim the
///       event channel by calling Client::take_event_receiver.
impl<D: ResourceDialect> Stream for EventReceiver<D> {
    type Item = Result<D::MessageBufEtc, Error>;

    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        match self.state {
            EventReceiverState::Active => {}
            EventReceiverState::Terminated => {
                panic!("polled EventReceiver after `None`");
            }
            EventReceiverState::Terminal => {
                self.state = EventReceiverState::Terminated;
                return Poll::Ready(None);
            }
        }

        Poll::Ready(match ready!(self.inner.poll_recv_event(cx)) {
            Ok(x) => Some(Ok(x)),
            Err(Error::ClientChannelClosed { status: zx_status::Status::PEER_CLOSED, .. }) => {
                // The channel is closed, with no epitaph. Set our internal state so that on
                // the next poll_next() we panic and is_terminated() returns an appropriate value.
                self.state = EventReceiverState::Terminated;
                None
            }
            err @ Err(_) => {
                // We've received a terminal error. Return it and set our internal state so that on
                // the next poll_next() we return a None and terminate the stream.
                self.state = EventReceiverState::Terminal;
                Some(err)
            }
        })
    }
}

impl<D: ResourceDialect> Drop for EventReceiver<D> {
    fn drop(&mut self) {
        self.inner.interests.lock().dropped_event_listener();
    }
}

#[derive(Debug, Default)]
enum EventListener {
    /// No one is listening for the event
    #[default]
    None,
    /// Someone is listening for the event but has not yet polled
    WillPoll,
    /// Someone is listening for the event and can be woken via the `Waker`
    Some(Waker),
}

impl EventListener {
    fn is_some(&self) -> bool {
        matches!(self, EventListener::Some(_))
    }
}

/// A shared client channel which tracks EXPECTED and received responses
#[derive(Debug)]
struct ClientInner<D: ResourceDialect> {
    /// The channel that leads to the server we are connected to.
    channel: <D::ProxyChannel as ProxyChannelFor<D>>::Boxed,

    /// Tracks the state of responses to two-way messages and events.
    interests: Mutex<Interests<D>>,

    /// A terminal error, which can be a server provided epitaph, or None if the channel is still
    /// active.
    terminal_error: Mutex<Option<Error>>,

    /// The `ProtocolMarker::DEBUG_NAME` for the service this client connects to.
    protocol_name: &'static str,
}

#[derive(Debug)]
struct Interests<D: ResourceDialect> {
    messages: Slab<MessageInterest<D>>,
    events: VecDeque<D::MessageBufEtc>,
    event_listener: EventListener,
    // The number of wakers registered waiting for either a message or an event.
    waker_count: usize,
}

impl<D: ResourceDialect> Default for Interests<D> {
    fn default() -> Self {
        Interests {
            messages: Slab::new(),
            events: Default::default(),
            event_listener: Default::default(),
            waker_count: 0,
        }
    }
}

impl<D: ResourceDialect> Interests<D> {
    /// Receives an event and returns a waker, if any.
    fn push_event(&mut self, buf: D::MessageBufEtc) -> Option<Waker> {
        self.events.push_back(buf);
        self.take_event_waker()
    }

    /// Returns the waker for the task waiting for events, if any.
    fn take_event_waker(&mut self) -> Option<Waker> {
        if self.event_listener.is_some() {
            let EventListener::Some(waker) =
                mem::replace(&mut self.event_listener, EventListener::WillPoll)
            else {
                unreachable!()
            };

            // Matches the +1 in `register_event_listener`.
            self.waker_count -= 1;
            Some(waker)
        } else {
            None
        }
    }

    /// Returns a reference to the waker.
    fn event_waker(&self) -> Option<&Waker> {
        match &self.event_listener {
            EventListener::Some(waker) => Some(waker),
            _ => None,
        }
    }

    /// Receive a message, waking the waiter if they are waiting to poll and `wake` is true.
    /// Returns an error of the message isn't found.
    fn push_message(&mut self, txid: Txid, buf: D::MessageBufEtc) -> Result<Option<Waker>, Error> {
        let InterestId(raw_id) = InterestId::from_txid(txid);
        // Look for a message interest with the given ID.
        // If one is found, store the message so that it can be picked up later.
        let Some(interest) = self.messages.get_mut(raw_id) else {
            // TODO(https://fxbug.dev/42066009): Should close the channel.
            return Err(Error::InvalidResponseTxid);
        };

        let mut waker = None;
        if let MessageInterest::Discard = interest {
            self.messages.remove(raw_id);
        } else if let MessageInterest::Waiting(w) =
            mem::replace(interest, MessageInterest::Received(buf))
        {
            waker = Some(w);

            // Matches the +1 in `register`.
            self.waker_count -= 1;
        }

        Ok(waker)
    }

    /// Registers the waker from `cx` if the message has not already been received, replacing any
    /// previous waker registered.  Returns the message if it has been received.
    fn register(&mut self, txid: Txid, cx: &Context<'_>) -> Option<D::MessageBufEtc> {
        let InterestId(raw_id) = InterestId::from_txid(txid);
        let interest = self.messages.get_mut(raw_id).expect("Polled unregistered interest");
        match interest {
            MessageInterest::Received(_) => {
                return Some(self.messages.remove(raw_id).unwrap_received())
            }
            MessageInterest::Discard => panic!("Polled a discarded MessageReceiver?!"),
            MessageInterest::WillPoll => self.waker_count += 1,
            MessageInterest::Waiting(_) => {}
        }
        *interest = MessageInterest::Waiting(cx.waker().clone());
        None
    }

    /// Deregisters an interest.
    fn deregister(&mut self, txid: Txid) {
        let InterestId(raw_id) = InterestId::from_txid(txid);
        match self.messages[raw_id] {
            MessageInterest::Received(_) => {
                self.messages.remove(raw_id);
                return;
            }
            MessageInterest::WillPoll => {}
            MessageInterest::Waiting(_) => self.waker_count -= 1,
            MessageInterest::Discard => unreachable!(),
        }
        self.messages[raw_id] = MessageInterest::Discard;
    }

    /// Registers an event listener.
    fn register_event_listener(&mut self, cx: &Context<'_>) -> Option<D::MessageBufEtc> {
        self.events.pop_front().or_else(|| {
            if !mem::replace(&mut self.event_listener, EventListener::Some(cx.waker().clone()))
                .is_some()
            {
                self.waker_count += 1;
            }
            None
        })
    }

    /// Indicates the event listener has been dropped.
    fn dropped_event_listener(&mut self) {
        if self.event_listener.is_some() {
            // Matches the +1 in register_event_listener.
            self.waker_count -= 1;
        }
        self.event_listener = EventListener::None;
    }

    /// Registers interest in a response message.
    ///
    /// This function returns a new transaction ID which should be used to send a message
    /// via the channel. Responses are then received using `poll_recv_msg_response`.
    fn register_msg_interest(&mut self) -> Txid {
        // TODO(cramertj) use `try_from` here and assert that the conversion from
        // `usize` to `u32` hasn't overflowed.
        Txid::from_interest_id(InterestId(self.messages.insert(MessageInterest::WillPoll)))
    }
}

impl<D: ResourceDialect> ClientInner<D> {
    fn poll_recv_event(
        self: &Arc<Self>,
        cx: &Context<'_>,
    ) -> Poll<Result<D::MessageBufEtc, Error>> {
        // Update the EventListener with the latest waker, remove any stale WillPoll state
        if let Some(msg_buf) = self.interests.lock().register_event_listener(cx) {
            return Poll::Ready(Ok(msg_buf));
        }

        // Process any data on the channel, registering any tasks still waiting to wake when the
        // channel becomes ready.
        let maybe_terminal_error = self.recv_all(Some(Txid(0)));

        let mut lock = self.interests.lock();

        if let Some(msg_buf) = lock.events.pop_front() {
            Poll::Ready(Ok(msg_buf))
        } else {
            maybe_terminal_error?;
            Poll::Pending
        }
    }

    /// Poll for the response to `txid`, registering the waker associated with `cx` to be awoken,
    /// or returning the response buffer if it has been received.
    fn poll_recv_msg_response(
        self: &Arc<Self>,
        txid: Txid,
        cx: &Context<'_>,
    ) -> Poll<Result<D::MessageBufEtc, Error>> {
        // Register our waker with the interest if we haven't received a message yet.
        if let Some(buf) = self.interests.lock().register(txid, cx) {
            return Poll::Ready(Ok(buf));
        }

        // Process any data on the channel, registering tasks still waiting for wake when the
        // channel becomes ready.
        let maybe_terminal_error = self.recv_all(Some(txid));

        let InterestId(raw_id) = InterestId::from_txid(txid);
        let mut interests = self.interests.lock();
        if interests.messages.get(raw_id).expect("Polled unregistered interest").is_received() {
            // If we got the result remove the received buffer and return, freeing up the
            // space for a new message.
            let buf = interests.messages.remove(raw_id).unwrap_received();
            Poll::Ready(Ok(buf))
        } else {
            maybe_terminal_error?;
            Poll::Pending
        }
    }

    /// Poll for the receipt of any response message or an event.
    /// Wakers present in any MessageInterest or the EventReceiver when this is called will be
    /// notified when their message arrives or when there is new data if the channel is empty.
    ///
    /// All errors are terminal, so once an error has been encountered, all subsequent calls will
    /// produce the same error.  The error might be due to the reception of an epitaph, the peer end
    /// of the channel being closed, a decode error or some other error.  Before using this terminal
    /// error, callers *should* check to see if a response or event has been received as they
    /// should normally, at least for the PEER_CLOSED case, be delivered before the terminal error.
    fn recv_all(self: &Arc<Self>, want_txid: Option<Txid>) -> Result<(), Error> {
        // Acquire a mutex so that only one thread can read from the underlying channel
        // at a time. Channel is already synchronized, but we need to also decode the
        // FIDL message header atomically so that epitaphs can be properly handled.
        let mut terminal_error = self.terminal_error.lock();
        if let Some(error) = terminal_error.as_ref() {
            return Err(error.clone());
        }

        let recv_once = |waker| {
            let cx = &mut Context::from_waker(&waker);

            let mut buf = D::MessageBufEtc::new();
            let result = self.channel.recv_etc_from(cx, &mut buf);
            match result {
                Poll::Ready(Ok(())) => {}
                Poll::Ready(Err(None)) => {
                    // The channel has been closed, and no epitaph was received.
                    // Set the epitaph to PEER_CLOSED.
                    return Err(Error::ClientChannelClosed {
                        status: zx_status::Status::PEER_CLOSED,
                        protocol_name: self.protocol_name,
                        #[cfg(not(target_os = "fuchsia"))]
                        reason: self.channel.closed_reason(),
                    });
                }
                Poll::Ready(Err(Some(e))) => return Err(Error::ClientRead(e.into())),
                Poll::Pending => return Ok(ControlFlow::Break(())),
            };

            let (bytes, _) = buf.split_mut();
            let (header, body_bytes) = decode_transaction_header(bytes)?;
            if header.is_epitaph() {
                // Received an epitaph. Record this so that everyone receives the same epitaph.
                let handles = &mut [];
                let mut epitaph_body = Decode::<EpitaphBody, D>::new_empty();
                Decoder::<D>::decode_into::<EpitaphBody>(
                    &header,
                    body_bytes,
                    handles,
                    &mut epitaph_body,
                )?;
                return Err(Error::ClientChannelClosed {
                    status: epitaph_body.error,
                    protocol_name: self.protocol_name,
                    #[cfg(not(target_os = "fuchsia"))]
                    reason: self.channel.closed_reason(),
                });
            }

            let txid = Txid(header.tx_id);

            let waker = {
                buf.shrink_bytes_to_fit();
                let mut interests = self.interests.lock();
                if txid == Txid(0) {
                    interests.push_event(buf)
                } else {
                    interests.push_message(txid, buf)?
                }
            };

            // Skip waking if the message was for the caller.
            if want_txid != Some(txid) {
                if let Some(waker) = waker {
                    waker.wake();
                }
            }

            Ok(ControlFlow::Continue(()))
        };

        loop {
            let waker = {
                let interests = self.interests.lock();
                if interests.waker_count == 0 {
                    return Ok(());
                } else if interests.waker_count == 1 {
                    // There's only one waker, so just use the waker for the one interest.  This
                    // is also required to allow `into_channel` to work, which relies on
                    // `Arc::try_into` which won't always work if we use a waker based on
                    // `ClientInner` (even if it's weak), because there can be races where the
                    // reference count on ClientInner is > 1.
                    if let Some(waker) = interests.event_waker() {
                        waker.clone()
                    } else {
                        interests
                            .messages
                            .iter()
                            .find_map(|(_, interest)| {
                                if let MessageInterest::Waiting(waker) = interest {
                                    Some(waker.clone())
                                } else {
                                    None
                                }
                            })
                            .unwrap()
                    }
                } else {
                    let weak = Arc::downgrade(self);
                    let waker = ClientWaker(Arc::new(move || {
                        if let Some(strong) = weak.upgrade() {
                            // On host, we can't call recv_all because there are reentrancy issues; the waker is
                            // woken whilst locks are held on the channel which recv_all needs.
                            #[cfg(target_os = "fuchsia")]
                            if strong.recv_all(None).is_ok() {
                                return;
                            }

                            strong.wake_all();
                        }
                    }));
                    // If there's more than one waker, use a waker that points to
                    // `ClientInner` which will read the message and figure out which is
                    // the correct task to wake.
                    // SAFETY: We meet the requirements specified by RawWaker.
                    unsafe {
                        Waker::from_raw(RawWaker::new(
                            Arc::into_raw(Arc::new(waker)) as *const (),
                            &WAKER_VTABLE,
                        ))
                    }
                }
            };

            match recv_once(waker) {
                Ok(ControlFlow::Continue(())) => {}
                Ok(ControlFlow::Break(())) => return Ok(()),
                Err(error) => {
                    // Broadcast all errors.
                    self.wake_all();
                    return Err(terminal_error.insert(error).clone());
                }
            }
        }
    }

    /// Wakes all tasks that have polled on this channel.
    fn wake_all(&self) {
        let mut lock = self.interests.lock();
        for (_, interest) in &mut lock.messages {
            if let MessageInterest::Waiting(_) = interest {
                let MessageInterest::Waiting(waker) =
                    mem::replace(interest, MessageInterest::WillPoll)
                else {
                    unreachable!()
                };
                waker.wake();
            }
        }
        if let Some(waker) = lock.take_event_waker() {
            waker.wake();
        }
        lock.waker_count = 0;
    }
}

#[derive(Clone)]
struct ClientWaker(Arc<dyn Fn() + Send + Sync + 'static>);

static WAKER_VTABLE: RawWakerVTable =
    RawWakerVTable::new(clone_waker, wake, wake_by_ref, drop_waker);

unsafe fn clone_waker(data: *const ()) -> RawWaker {
    Arc::increment_strong_count(data as *const ClientWaker);
    RawWaker::new(data, &WAKER_VTABLE)
}

unsafe fn wake(data: *const ()) {
    Arc::from_raw(data as *const ClientWaker).0();
}

unsafe fn wake_by_ref(data: *const ()) {
    mem::ManuallyDrop::new(Arc::from_raw(data as *const ClientWaker)).0();
}

unsafe fn drop_waker(data: *const ()) {
    Arc::from_raw(data as *const ClientWaker);
}

#[cfg(target_os = "fuchsia")]
pub mod sync {
    //! Synchronous FIDL Client

    use super::*;
    use std::mem::MaybeUninit;
    use zx::{self as zx, AsHandleRef, MessageBufEtc};

    /// A synchronous client for making FIDL calls.
    #[derive(Debug)]
    pub struct Client {
        // Underlying channel
        channel: zx::Channel,

        // The `ProtocolMarker::DEBUG_NAME` for the service this client connects to.
        protocol_name: &'static str,
    }

    impl Client {
        /// Create a new synchronous FIDL client.
        pub fn new(channel: zx::Channel, protocol_name: &'static str) -> Self {
            Client { channel, protocol_name }
        }

        /// Return a reference to the underlying channel for the client.
        pub fn as_channel(&self) -> &zx::Channel {
            &self.channel
        }

        /// Get the underlying channel out of the client.
        pub fn into_channel(self) -> zx::Channel {
            self.channel
        }

        /// Send a new message.
        pub fn send<T: TypeMarker>(
            &self,
            body: impl Encode<T, DefaultFuchsiaResourceDialect>,
            ordinal: u64,
            dynamic_flags: DynamicFlags,
        ) -> Result<(), Error> {
            let mut write_bytes = Vec::new();
            let mut write_handles = Vec::new();
            let msg = TransactionMessage {
                header: TransactionHeader::new(0, ordinal, dynamic_flags),
                body,
            };
            Encoder::encode::<TransactionMessageType<T>>(
                &mut write_bytes,
                &mut write_handles,
                msg,
            )?;
            match self.channel.write_etc(&write_bytes, &mut write_handles) {
                Ok(()) | Err(zx_status::Status::PEER_CLOSED) => Ok(()),
                Err(e) => Err(Error::ClientWrite(e.into())),
            }
        }

        /// Send a new message expecting a response.
        pub fn send_query<Request: TypeMarker, Response: TypeMarker>(
            &self,
            body: impl Encode<Request, DefaultFuchsiaResourceDialect>,
            ordinal: u64,
            dynamic_flags: DynamicFlags,
            deadline: zx::MonotonicInstant,
        ) -> Result<Response::Owned, Error>
        where
            Response::Owned: Decode<Response, DefaultFuchsiaResourceDialect>,
        {
            let mut write_bytes = Vec::new();
            let mut write_handles = Vec::new();

            let msg = TransactionMessage {
                header: TransactionHeader::new(0, ordinal, dynamic_flags),
                body,
            };
            Encoder::encode::<TransactionMessageType<Request>>(
                &mut write_bytes,
                &mut write_handles,
                msg,
            )?;

            // Stack-allocate these buffers to avoid the heap and reuse any populated pages from
            // previous function calls. Use uninitialized memory so that the only writes to this
            // array will be by the kernel for whatever's actually used for the reply.
            let bytes_out =
                &mut [MaybeUninit::<u8>::uninit(); zx::sys::ZX_CHANNEL_MAX_MSG_BYTES as usize];
            let handles_out = &mut [const { MaybeUninit::<zx::HandleInfo>::uninit() };
                zx::sys::ZX_CHANNEL_MAX_MSG_HANDLES as usize];

            // TODO: We should be able to use the same memory to back the bytes we use for writing
            // and reading.
            let (bytes_out, handles_out) = self
                .channel
                .call_etc_uninit(deadline, &write_bytes, &mut write_handles, bytes_out, handles_out)
                .map_err(|e| self.wrap_error(Error::ClientCall, e))?;

            let (header, body_bytes) = decode_transaction_header(bytes_out)?;
            if header.ordinal != ordinal {
                return Err(Error::InvalidResponseOrdinal);
            }
            let mut output = Decode::<Response, DefaultFuchsiaResourceDialect>::new_empty();
            Decoder::<DefaultFuchsiaResourceDialect>::decode_into::<Response>(
                &header,
                body_bytes,
                handles_out,
                &mut output,
            )?;
            Ok(output)
        }

        /// Wait for an event to arrive on the underlying channel.
        pub fn wait_for_event(
            &self,
            deadline: zx::MonotonicInstant,
        ) -> Result<MessageBufEtc, Error> {
            let mut buf = zx::MessageBufEtc::new();
            buf.ensure_capacity_bytes(zx::sys::ZX_CHANNEL_MAX_MSG_BYTES as usize);
            buf.ensure_capacity_handle_infos(zx::sys::ZX_CHANNEL_MAX_MSG_HANDLES as usize);

            loop {
                self.channel
                    .wait_handle(
                        zx::Signals::CHANNEL_READABLE | zx::Signals::CHANNEL_PEER_CLOSED,
                        deadline,
                    )
                    .map_err(|e| self.wrap_error(Error::ClientEvent, e))?;
                match self.channel.read_etc(&mut buf) {
                    Ok(()) => {
                        // We succeeded in reading the message. Check that it is
                        // an event not a two-way method reply.
                        let (header, _) = decode_transaction_header(buf.bytes())
                            .map_err(|_| Error::InvalidHeader)?;
                        if header.tx_id != 0 {
                            return Err(Error::UnexpectedSyncResponse);
                        }
                        return Ok(buf);
                    }
                    Err(zx::Status::SHOULD_WAIT) => {
                        // Some other thread read the message we woke up to read.
                        continue;
                    }
                    Err(e) => {
                        return Err(self.wrap_error(|x| Error::ClientRead(x.into()), e));
                    }
                }
            }
        }

        /// Wraps an error in the given `variant` of the `Error` enum, except
        /// for `zx_status::Status::PEER_CLOSED`, in which case it uses the
        /// `Error::ClientChannelClosed` variant.
        fn wrap_error<T: Fn(zx_status::Status) -> Error>(
            &self,
            variant: T,
            err: zx_status::Status,
        ) -> Error {
            if err == zx_status::Status::PEER_CLOSED {
                Error::ClientChannelClosed {
                    status: zx_status::Status::PEER_CLOSED,
                    protocol_name: self.protocol_name,
                }
            } else {
                variant(err)
            }
        }
    }
}

#[cfg(all(test, target_os = "fuchsia"))]
mod tests {
    use super::*;
    use crate::encoding::MAGIC_NUMBER_INITIAL;
    use crate::epitaph::{self, ChannelEpitaphExt};
    use anyhow::{Context as _, Error};
    use assert_matches::assert_matches;
    use fuchsia_async as fasync;
    use fuchsia_async::{Channel as AsyncChannel, DurationExt, TimeoutExt};
    use futures::channel::oneshot;
    use futures::stream::FuturesUnordered;
    use futures::task::{noop_waker, waker, ArcWake};
    use futures::{join, StreamExt, TryFutureExt};
    use futures_test::task::new_count_waker;
    use std::future::pending;
    use std::thread;
    use zx::{AsHandleRef, MessageBufEtc};

    const SEND_ORDINAL_HIGH_BYTE: u8 = 42;
    const SEND_ORDINAL: u64 = 42 << 32;
    const SEND_DATA: u8 = 55;

    const EVENT_ORDINAL: u64 = 854 << 23;

    #[rustfmt::skip]
    fn expected_sent_bytes(tx_id_low_byte: u8) -> [u8; 24] {
        [
            tx_id_low_byte, 0, 0, 0, // 32 bit tx_id
            2, 0, 0, // flags
            MAGIC_NUMBER_INITIAL,
            0, 0, 0, 0, // low bytes of 64 bit ordinal
            SEND_ORDINAL_HIGH_BYTE, 0, 0, 0, // high bytes of 64 bit ordinal
            SEND_DATA, // 8 bit data
            0, 0, 0, 0, 0, 0, 0, // 7 bytes of padding after our 1 byte of data
        ]
    }

    fn send_transaction(header: TransactionHeader, channel: &zx::Channel) {
        let (bytes, handles) = (&mut vec![], &mut vec![]);
        encode_transaction(header, bytes, handles);
        channel.write_etc(bytes, handles).expect("Server channel write failed");
    }

    fn encode_transaction(
        header: TransactionHeader,
        bytes: &mut Vec<u8>,
        handles: &mut Vec<zx::HandleDisposition<'static>>,
    ) {
        let event = TransactionMessage { header, body: SEND_DATA };
        Encoder::<DefaultFuchsiaResourceDialect>::encode::<TransactionMessageType<u8>>(
            bytes, handles, event,
        )
        .expect("Encoding failure");
    }

    #[test]
    fn sync_client() -> Result<(), Error> {
        let (client_end, server_end) = zx::Channel::create();
        let client = sync::Client::new(client_end, "test_protocol");
        client.send::<u8>(SEND_DATA, SEND_ORDINAL, DynamicFlags::empty()).context("sending")?;
        let mut received = MessageBufEtc::new();
        server_end.read_etc(&mut received).context("reading")?;
        let one_way_tx_id = 0;
        assert_eq!(received.bytes(), expected_sent_bytes(one_way_tx_id));
        Ok(())
    }

    #[test]
    fn sync_client_with_response() -> Result<(), Error> {
        let (client_end, server_end) = zx::Channel::create();
        let client = sync::Client::new(client_end, "test_protocol");
        thread::spawn(move || {
            // Server
            let mut received = MessageBufEtc::new();
            server_end
                .wait_handle(
                    zx::Signals::CHANNEL_READABLE,
                    zx::MonotonicInstant::after(zx::MonotonicDuration::from_seconds(5)),
                )
                .expect("failed to wait for channel readable");
            server_end.read_etc(&mut received).expect("failed to read on server end");
            let (buf, _handles) = received.split_mut();
            let (header, _body_bytes) = decode_transaction_header(buf).expect("server decode");
            assert_eq!(header.ordinal, SEND_ORDINAL);
            send_transaction(
                TransactionHeader::new(header.tx_id, header.ordinal, DynamicFlags::empty()),
                &server_end,
            );
        });
        let response_data = client
            .send_query::<u8, u8>(
                SEND_DATA,
                SEND_ORDINAL,
                DynamicFlags::empty(),
                zx::MonotonicInstant::after(zx::MonotonicDuration::from_seconds(5)),
            )
            .context("sending query")?;
        assert_eq!(SEND_DATA, response_data);
        Ok(())
    }

    #[test]
    fn sync_client_with_event_and_response() -> Result<(), Error> {
        let (client_end, server_end) = zx::Channel::create();
        let client = sync::Client::new(client_end, "test_protocol");
        thread::spawn(move || {
            // Server
            let mut received = MessageBufEtc::new();
            server_end
                .wait_handle(
                    zx::Signals::CHANNEL_READABLE,
                    zx::MonotonicInstant::after(zx::MonotonicDuration::from_seconds(5)),
                )
                .expect("failed to wait for channel readable");
            server_end.read_etc(&mut received).expect("failed to read on server end");
            let (buf, _handles) = received.split_mut();
            let (header, _body_bytes) = decode_transaction_header(buf).expect("server decode");
            assert_ne!(header.tx_id, 0);
            assert_eq!(header.ordinal, SEND_ORDINAL);
            // First, send an event.
            send_transaction(
                TransactionHeader::new(0, EVENT_ORDINAL, DynamicFlags::empty()),
                &server_end,
            );
            // Then send the reply. The kernel should pick the correct message to deliver based
            // on the tx_id.
            send_transaction(
                TransactionHeader::new(header.tx_id, header.ordinal, DynamicFlags::empty()),
                &server_end,
            );
        });
        let response_data = client
            .send_query::<u8, u8>(
                SEND_DATA,
                SEND_ORDINAL,
                DynamicFlags::empty(),
                zx::MonotonicInstant::after(zx::MonotonicDuration::from_seconds(5)),
            )
            .context("sending query")?;
        assert_eq!(SEND_DATA, response_data);

        let event_buf = client
            .wait_for_event(zx::MonotonicInstant::after(zx::MonotonicDuration::from_seconds(5)))
            .context("waiting for event")?;
        let (bytes, _handles) = event_buf.split();
        let (header, _body) = decode_transaction_header(&bytes).expect("event decode");
        assert_eq!(header.ordinal, EVENT_ORDINAL);

        Ok(())
    }

    #[test]
    fn sync_client_with_racing_events() -> Result<(), Error> {
        let (client_end, server_end) = zx::Channel::create();
        let client1 = Arc::new(sync::Client::new(client_end, "test_protocol"));
        let client2 = client1.clone();

        let thread1 = thread::spawn(move || {
            let result = client1.wait_for_event(zx::MonotonicInstant::after(
                zx::MonotonicDuration::from_seconds(5),
            ));
            assert!(result.is_ok());
        });

        let thread2 = thread::spawn(move || {
            let result = client2.wait_for_event(zx::MonotonicInstant::after(
                zx::MonotonicDuration::from_seconds(5),
            ));
            assert!(result.is_ok());
        });

        send_transaction(
            TransactionHeader::new(0, EVENT_ORDINAL, DynamicFlags::empty()),
            &server_end,
        );
        send_transaction(
            TransactionHeader::new(0, EVENT_ORDINAL, DynamicFlags::empty()),
            &server_end,
        );

        assert!(thread1.join().is_ok());
        assert!(thread2.join().is_ok());

        Ok(())
    }

    #[test]
    fn sync_client_wait_for_event_gets_method_response() -> Result<(), Error> {
        let (client_end, server_end) = zx::Channel::create();
        let client = sync::Client::new(client_end, "test_protocol");
        send_transaction(
            TransactionHeader::new(3902304923, SEND_ORDINAL, DynamicFlags::empty()),
            &server_end,
        );
        assert_matches!(
            client.wait_for_event(zx::MonotonicInstant::after(
                zx::MonotonicDuration::from_seconds(5)
            )),
            Err(crate::Error::UnexpectedSyncResponse)
        );
        Ok(())
    }

    #[test]
    fn sync_client_one_way_call_suceeds_after_peer_closed() -> Result<(), Error> {
        let (client_end, server_end) = zx::Channel::create();
        let client = sync::Client::new(client_end, "test_protocol");
        drop(server_end);
        assert_matches!(client.send::<u8>(SEND_DATA, SEND_ORDINAL, DynamicFlags::empty()), Ok(()));
        Ok(())
    }

    #[test]
    fn sync_client_two_way_call_fails_after_peer_closed() -> Result<(), Error> {
        let (client_end, server_end) = zx::Channel::create();
        let client = sync::Client::new(client_end, "test_protocol");
        drop(server_end);
        assert_matches!(
            client.send_query::<u8, u8>(
                SEND_DATA,
                SEND_ORDINAL,
                DynamicFlags::empty(),
                zx::MonotonicInstant::after(zx::MonotonicDuration::from_seconds(5))
            ),
            Err(crate::Error::ClientChannelClosed {
                status: zx_status::Status::PEER_CLOSED,
                protocol_name: "test_protocol",
            })
        );
        Ok(())
    }

    // TODO(https://fxbug.dev/42153053): When the sync client supports epitaphs, rename
    // this and change the assert to expect zx_status::Status::UNAVAILABLE.
    #[test]
    fn sync_client_does_not_receive_epitaphs() -> Result<(), Error> {
        let (client_end, server_end) = zx::Channel::create();
        let client = sync::Client::new(client_end, "test_protocol");
        // Close the server channel with an epitaph.
        server_end
            .close_with_epitaph(zx_status::Status::UNAVAILABLE)
            .expect("failed to write epitaph");
        assert_matches!(
            client.send_query::<u8, u8>(
                SEND_DATA,
                SEND_ORDINAL,
                DynamicFlags::empty(),
                zx::MonotonicInstant::after(zx::MonotonicDuration::from_seconds(5))
            ),
            Err(crate::Error::ClientChannelClosed {
                status: zx_status::Status::PEER_CLOSED,
                protocol_name: "test_protocol",
            })
        );
        Ok(())
    }

    #[test]
    fn sync_client_into_channel() -> Result<(), Error> {
        let (client_end, _server_end) = zx::Channel::create();
        let client_end_raw = client_end.raw_handle();
        let client = sync::Client::new(client_end, "test_protocol");
        assert_eq!(client.into_channel().raw_handle(), client_end_raw);
        Ok(())
    }

    #[fasync::run_singlethreaded(test)]
    async fn client() {
        let (client_end, server_end) = zx::Channel::create();
        let client_end = AsyncChannel::from_channel(client_end);
        let client = Client::<DefaultFuchsiaResourceDialect>::new(client_end, "test_protocol");

        let server = AsyncChannel::from_channel(server_end);
        let receiver = async move {
            let mut buffer = MessageBufEtc::new();
            server.recv_etc_msg(&mut buffer).await.expect("failed to recv msg");
            let one_way_tx_id = 0;
            assert_eq!(buffer.bytes(), expected_sent_bytes(one_way_tx_id));
        };

        // add a timeout to receiver so if test is broken it doesn't take forever
        let receiver = receiver
            .on_timeout(zx::MonotonicDuration::from_millis(300).after_now(), || {
                panic!("did not receive message in time!")
            });

        client
            .send::<u8>(SEND_DATA, SEND_ORDINAL, DynamicFlags::empty())
            .expect("failed to send msg");

        receiver.await;
    }

    #[fasync::run_singlethreaded(test)]
    async fn client_with_response() {
        let (client_end, server_end) = zx::Channel::create();
        let client_end = AsyncChannel::from_channel(client_end);
        let client = Client::<DefaultFuchsiaResourceDialect>::new(client_end, "test_protocol");

        let server = AsyncChannel::from_channel(server_end);
        let mut buffer = MessageBufEtc::new();
        let receiver = async move {
            server.recv_etc_msg(&mut buffer).await.expect("failed to recv msg");
            let two_way_tx_id = 1u8;
            assert_eq!(buffer.bytes(), expected_sent_bytes(two_way_tx_id));

            let (bytes, handles) = (&mut vec![], &mut vec![]);
            let header =
                TransactionHeader::new(two_way_tx_id as u32, SEND_ORDINAL, DynamicFlags::empty());
            encode_transaction(header, bytes, handles);
            server.write_etc(bytes, handles).expect("Server channel write failed");
        };

        // add a timeout to receiver so if test is broken it doesn't take forever
        let receiver = receiver
            .on_timeout(zx::MonotonicDuration::from_millis(300).after_now(), || {
                panic!("did not receiver message in time!")
            });

        let sender = client
            .send_query::<u8, u8, SEND_ORDINAL>(SEND_DATA, DynamicFlags::empty())
            .map_ok(|x| assert_eq!(x, SEND_DATA))
            .unwrap_or_else(|e| panic!("fidl error: {:?}", e));

        // add a timeout to receiver so if test is broken it doesn't take forever
        let sender = sender.on_timeout(zx::MonotonicDuration::from_millis(300).after_now(), || {
            panic!("did not receive response in time!")
        });

        let ((), ()) = join!(receiver, sender);
    }

    #[fasync::run_singlethreaded(test)]
    async fn client_with_response_receives_epitaph() {
        let (client_end, server_end) = zx::Channel::create();
        let client_end = AsyncChannel::from_channel(client_end);
        let client = Client::<DefaultFuchsiaResourceDialect>::new(client_end, "test_protocol");

        let server = AsyncChannel::from_channel(server_end);
        let mut buffer = zx::MessageBufEtc::new();
        let receiver = async move {
            server.recv_etc_msg(&mut buffer).await.expect("failed to recv msg");
            server
                .close_with_epitaph(zx_status::Status::UNAVAILABLE)
                .expect("failed to write epitaph");
        };
        // add a timeout to receiver so if test is broken it doesn't take forever
        let receiver = receiver
            .on_timeout(zx::MonotonicDuration::from_millis(300).after_now(), || {
                panic!("did not receive message in time!")
            });

        let sender = async move {
            const ORDINAL: u64 = 42 << 32;
            let result = client.send_query::<u8, u8, ORDINAL>(55, DynamicFlags::empty()).await;
            assert_matches!(
                result,
                Err(crate::Error::ClientChannelClosed {
                    status: zx_status::Status::UNAVAILABLE,
                    protocol_name: "test_protocol"
                })
            );
        };
        // add a timeout to sender so if test is broken it doesn't take forever
        let sender = sender.on_timeout(zx::MonotonicDuration::from_millis(300).after_now(), || {
            panic!("did not receive response in time!")
        });

        let ((), ()) = join!(receiver, sender);
    }

    #[fasync::run_singlethreaded(test)]
    #[should_panic]
    async fn event_cant_be_taken_twice() {
        let (client_end, _) = zx::Channel::create();
        let client_end = AsyncChannel::from_channel(client_end);
        let client = Client::<DefaultFuchsiaResourceDialect>::new(client_end, "test_protocol");
        let _foo = client.take_event_receiver();
        client.take_event_receiver();
    }

    #[fasync::run_singlethreaded(test)]
    async fn event_can_be_taken_after_drop() {
        let (client_end, _) = zx::Channel::create();
        let client_end = AsyncChannel::from_channel(client_end);
        let client = Client::<DefaultFuchsiaResourceDialect>::new(client_end, "test_protocol");
        let foo = client.take_event_receiver();
        drop(foo);
        client.take_event_receiver();
    }

    #[fasync::run_singlethreaded(test)]
    async fn receiver_termination_test() {
        let (client_end, _) = zx::Channel::create();
        let client_end = AsyncChannel::from_channel(client_end);
        let client = Client::<DefaultFuchsiaResourceDialect>::new(client_end, "test_protocol");
        let mut foo = client.take_event_receiver();
        assert!(!foo.is_terminated(), "receiver should not report terminated before being polled");
        let _ = foo.next().await;
        assert!(
            foo.is_terminated(),
            "receiver should report terminated after seeing channel is closed"
        );
    }

    #[fasync::run_singlethreaded(test)]
    #[should_panic(expected = "polled EventReceiver after `None`")]
    async fn receiver_cant_be_polled_more_than_once_on_closed_stream() {
        let (client_end, _) = zx::Channel::create();
        let client_end = AsyncChannel::from_channel(client_end);
        let client = Client::<DefaultFuchsiaResourceDialect>::new(client_end, "test_protocol");
        let foo = client.take_event_receiver();
        drop(foo);
        let mut bar = client.take_event_receiver();
        assert!(bar.next().await.is_none(), "read on closed channel should return none");
        // this should panic
        let _ = bar.next().await;
    }

    #[fasync::run_singlethreaded(test)]
    #[should_panic(expected = "polled EventReceiver after `None`")]
    async fn receiver_panics_when_polled_after_receiving_epitaph_then_none() {
        let (client_end, server_end) = zx::Channel::create();
        let client_end = AsyncChannel::from_channel(client_end);
        let server_end = AsyncChannel::from_channel(server_end);
        let client = Client::<DefaultFuchsiaResourceDialect>::new(client_end, "test_protocol");
        let mut stream = client.take_event_receiver();

        epitaph::write_epitaph_impl(&server_end, zx_status::Status::UNAVAILABLE)
            .expect("wrote epitaph");
        drop(server_end);

        assert_matches!(
            stream.next().await,
            Some(Err(crate::Error::ClientChannelClosed {
                status: zx_status::Status::UNAVAILABLE,
                protocol_name: "test_protocol"
            }))
        );
        assert_matches!(stream.next().await, None);
        // this should panic
        let _ = stream.next().await;
    }

    #[fasync::run_singlethreaded(test)]
    async fn event_can_be_taken() {
        let (client_end, _) = zx::Channel::create();
        let client_end = AsyncChannel::from_channel(client_end);
        let client = Client::<DefaultFuchsiaResourceDialect>::new(client_end, "test_protocol");
        client.take_event_receiver();
    }

    #[fasync::run_singlethreaded(test)]
    async fn event_received() {
        let (client_end, server_end) = zx::Channel::create();
        let client_end = AsyncChannel::from_channel(client_end);
        let client = Client::<DefaultFuchsiaResourceDialect>::new(client_end, "test_protocol");

        // Send the event from the server
        let server = AsyncChannel::from_channel(server_end);
        let (bytes, handles) = (&mut vec![], &mut vec![]);
        const ORDINAL: u64 = 5;
        let header = TransactionHeader::new(0, ORDINAL, DynamicFlags::empty());
        encode_transaction(header, bytes, handles);
        server.write_etc(bytes, handles).expect("Server channel write failed");
        drop(server);

        let recv = client
            .take_event_receiver()
            .into_future()
            .then(|(x, stream)| {
                let x = x.expect("should contain one element");
                let x = x.expect("fidl error");
                let x: i32 =
                    decode_transaction_body::<i32, DefaultFuchsiaResourceDialect, ORDINAL>(x)
                        .expect("failed to decode event");
                assert_eq!(x, 55);
                stream.into_future()
            })
            .map(|(x, _stream)| assert!(x.is_none(), "should have emptied"));

        // add a timeout to receiver so if test is broken it doesn't take forever
        let recv = recv.on_timeout(zx::MonotonicDuration::from_millis(300).after_now(), || {
            panic!("did not receive event in time!")
        });

        recv.await;
    }

    /// Tests that the event receiver can be taken, the stream read to the end,
    /// the receiver dropped, and then a new receiver gotten from taking the
    /// stream again.
    #[fasync::run_singlethreaded(test)]
    async fn receiver_can_be_taken_after_end_of_stream() {
        let (client_end, server_end) = zx::Channel::create();
        let client_end = AsyncChannel::from_channel(client_end);
        let client = Client::<DefaultFuchsiaResourceDialect>::new(client_end, "test_protocol");

        // Send the event from the server
        let server = AsyncChannel::from_channel(server_end);
        let (bytes, handles) = (&mut vec![], &mut vec![]);
        const ORDINAL: u64 = 5;
        let header = TransactionHeader::new(0, ORDINAL, DynamicFlags::empty());
        encode_transaction(header, bytes, handles);
        server.write_etc(bytes, handles).expect("Server channel write failed");
        drop(server);

        // Create a block to make sure the first event receiver is dropped.
        // Creating the block is a bit of paranoia, because awaiting the
        // future moves the receiver anyway.
        {
            let recv = client
                .take_event_receiver()
                .into_future()
                .then(|(x, stream)| {
                    let x = x.expect("should contain one element");
                    let x = x.expect("fidl error");
                    let x: i32 =
                        decode_transaction_body::<i32, DefaultFuchsiaResourceDialect, ORDINAL>(x)
                            .expect("failed to decode event");
                    assert_eq!(x, 55);
                    stream.into_future()
                })
                .map(|(x, _stream)| assert!(x.is_none(), "should have emptied"));

            // add a timeout to receiver so if test is broken it doesn't take forever
            let recv = recv.on_timeout(zx::MonotonicDuration::from_millis(300).after_now(), || {
                panic!("did not receive event in time!")
            });

            recv.await;
        }

        // if we take the event stream again, we should be able to get the next
        // without a panic, but that should be none
        let mut c = client.take_event_receiver();
        assert!(
            c.next().await.is_none(),
            "receiver on closed channel should return none on first call"
        );
    }

    #[fasync::run_singlethreaded(test)]
    async fn event_incompatible_format() {
        let (client_end, server_end) = zx::Channel::create();
        let client_end = AsyncChannel::from_channel(client_end);
        let client = Client::<DefaultFuchsiaResourceDialect>::new(client_end, "test_protocol");

        // Send the event from the server
        let server = AsyncChannel::from_channel(server_end);
        let (bytes, handles) = (&mut vec![], &mut vec![]);
        let header = TransactionHeader::new_full(
            0,
            5,
            crate::encoding::Context {
                wire_format_version: crate::encoding::WireFormatVersion::V2,
            },
            DynamicFlags::empty(),
            0,
        );
        encode_transaction(header, bytes, handles);
        server.write_etc(bytes, handles).expect("Server channel write failed");
        drop(server);

        let mut event_receiver = client.take_event_receiver();
        let recv = event_receiver.next().map(|event| {
            assert_matches!(event, Some(Err(crate::Error::IncompatibleMagicNumber(0))))
        });

        // add a timeout to receiver so if test is broken it doesn't take forever
        let recv = recv.on_timeout(zx::MonotonicDuration::from_millis(300).after_now(), || {
            panic!("did not receive event in time!")
        });

        recv.await;
    }

    #[test]
    fn client_always_wakes_pending_futures() {
        let mut executor = fasync::TestExecutor::new();

        let (client_end, server_end) = zx::Channel::create();
        let client_end = AsyncChannel::from_channel(client_end);
        let client = Client::<DefaultFuchsiaResourceDialect>::new(client_end, "test_protocol");

        let mut event_receiver = client.take_event_receiver();

        // first poll on a response
        let (response_waker, response_waker_count) = new_count_waker();
        let response_cx = &mut Context::from_waker(&response_waker);
        let mut response_txid = Txid(0);
        let mut response_future = client
            .send_raw_query(|tx_id, bytes, handles| {
                response_txid = tx_id;
                let header = TransactionHeader::new(
                    response_txid.as_raw_id(),
                    SEND_ORDINAL,
                    DynamicFlags::empty(),
                );
                encode_transaction(header, bytes, handles);
                Ok(())
            })
            .expect("Couldn't send query");
        assert!(response_future.poll_unpin(response_cx).is_pending());

        // then, poll on an event
        let (event_waker, event_waker_count) = new_count_waker();
        let event_cx = &mut Context::from_waker(&event_waker);
        assert!(event_receiver.poll_next_unpin(event_cx).is_pending());

        // at this point, nothing should have been woken
        assert_eq!(response_waker_count.get(), 0);
        assert_eq!(event_waker_count.get(), 0);

        // next, simulate an event coming in
        send_transaction(TransactionHeader::new(0, 5, DynamicFlags::empty()), &server_end);

        // get event loop to deliver readiness notifications to channels
        let _ = executor.run_until_stalled(&mut future::pending::<()>());

        // The event wake should be woken but not the response_waker.
        assert_eq!(response_waker_count.get(), 0);
        assert_eq!(event_waker_count.get(), 1);

        // we'll pretend event_waker was woken, and have that poll out the event
        assert!(event_receiver.poll_next_unpin(event_cx).is_ready());

        // next, simulate a response coming in
        send_transaction(
            TransactionHeader::new(response_txid.as_raw_id(), SEND_ORDINAL, DynamicFlags::empty()),
            &server_end,
        );

        // get event loop to deliver readiness notifications to channels
        let _ = executor.run_until_stalled(&mut future::pending::<()>());

        // response waker should now get woken.
        assert_eq!(response_waker_count.get(), 1);
    }

    #[test]
    fn client_always_wakes_pending_futures_on_epitaph() {
        let mut executor = fasync::TestExecutor::new();

        let (client_end, server_end) = zx::Channel::create();
        let client_end = AsyncChannel::from_channel(client_end);
        let server_end = AsyncChannel::from_channel(server_end);
        let client = Client::<DefaultFuchsiaResourceDialect>::new(client_end, "test_protocol");

        let mut event_receiver = client.take_event_receiver();

        // first poll on a response
        let (response1_waker, response1_waker_count) = new_count_waker();
        let response1_cx = &mut Context::from_waker(&response1_waker);
        let mut response1_future = client
            .send_raw_query(|tx_id, bytes, handles| {
                let header =
                    TransactionHeader::new(tx_id.as_raw_id(), SEND_ORDINAL, DynamicFlags::empty());
                encode_transaction(header, bytes, handles);
                Ok(())
            })
            .expect("Couldn't send query");
        assert!(response1_future.poll_unpin(response1_cx).is_pending());

        // then, poll on an event
        let (event_waker, event_waker_count) = new_count_waker();
        let event_cx = &mut Context::from_waker(&event_waker);
        assert!(event_receiver.poll_next_unpin(event_cx).is_pending());

        // poll on another response
        let (response2_waker, response2_waker_count) = new_count_waker();
        let response2_cx = &mut Context::from_waker(&response2_waker);
        let mut response2_future = client
            .send_raw_query(|tx_id, bytes, handles| {
                let header =
                    TransactionHeader::new(tx_id.as_raw_id(), SEND_ORDINAL, DynamicFlags::empty());
                encode_transaction(header, bytes, handles);
                Ok(())
            })
            .expect("Couldn't send query");
        assert!(response2_future.poll_unpin(response2_cx).is_pending());

        let wakers = vec![response1_waker_count, response2_waker_count, event_waker_count];

        // get event loop to deliver readiness notifications to channels
        let _ = executor.run_until_stalled(&mut future::pending::<()>());

        // at this point, nothing should have been woken
        assert_eq!(0, wakers.iter().fold(0, |acc, x| acc + x.get()));

        // next, simulate an epitaph without closing
        epitaph::write_epitaph_impl(&server_end, zx_status::Status::UNAVAILABLE)
            .expect("wrote epitaph");

        // get event loop to deliver readiness notifications to channels
        let _ = executor.run_until_stalled(&mut future::pending::<()>());

        // All the wakers should be woken up because the channel is ready to read, and the message
        // could be for any of them.
        for wake_count in &wakers {
            assert_eq!(wake_count.get(), 1);
        }

        // pretend that response1 woke and poll that to completion.
        assert_matches!(
            response1_future.poll_unpin(response1_cx),
            Poll::Ready(Err(crate::Error::ClientChannelClosed {
                status: zx_status::Status::UNAVAILABLE,
                protocol_name: "test_protocol"
            }))
        );

        // get event loop to deliver readiness notifications to channels
        let _ = executor.run_until_stalled(&mut future::pending::<()>());

        // poll response2 to completion.
        assert_matches!(
            response2_future.poll_unpin(response2_cx),
            Poll::Ready(Err(crate::Error::ClientChannelClosed {
                status: zx_status::Status::UNAVAILABLE,
                protocol_name: "test_protocol"
            }))
        );

        // poll the event stream to completion.
        assert!(event_receiver.poll_next_unpin(event_cx).is_ready());
    }

    #[fasync::run_singlethreaded(test)]
    async fn client_allows_take_event_stream_even_if_event_delivered() {
        let (client_end, server_end) = zx::Channel::create();
        let client_end = AsyncChannel::from_channel(client_end);
        let client = Client::<DefaultFuchsiaResourceDialect>::new(client_end, "test_protocol");

        // first simulate an event coming in, even though nothing has polled
        send_transaction(TransactionHeader::new(0, 5, DynamicFlags::empty()), &server_end);

        // next, poll on a response
        let (response_waker, _response_waker_count) = new_count_waker();
        let response_cx = &mut Context::from_waker(&response_waker);
        let mut response_future =
            client.send_query::<u8, u8, SEND_ORDINAL>(55, DynamicFlags::empty());
        assert!(response_future.poll_unpin(response_cx).is_pending());

        // then, make sure we can still take the event receiver without panicking
        let mut _event_receiver = client.take_event_receiver();
    }

    #[fasync::run_singlethreaded(test)]
    async fn client_reports_epitaph_from_all_read_actions() {
        #[derive(Debug, PartialEq)]
        enum Action {
            SendMsg,   // send a one-way message
            SendQuery, // send a two-way message and just call .check()
            WaitQuery, // send a two-way message and wait for the response
            RecvEvent, // wait to receive an event
        }
        impl Action {
            fn should_report_epitaph(&self) -> bool {
                match self {
                    Action::SendMsg | Action::SendQuery => false,
                    Action::WaitQuery | Action::RecvEvent => true,
                }
            }
        }
        use Action::*;
        // Test all permutations of two actions. Verify the epitaph is reported
        // twice (2 reads), once (1 read, 1 write), or not at all (2 writes).
        for two_actions in &[
            [SendMsg, SendMsg],
            [SendMsg, SendQuery],
            [SendMsg, WaitQuery],
            [SendMsg, RecvEvent],
            [SendQuery, SendMsg],
            [SendQuery, SendQuery],
            [SendQuery, WaitQuery],
            [SendQuery, RecvEvent],
            [WaitQuery, SendMsg],
            [WaitQuery, SendQuery],
            [WaitQuery, WaitQuery],
            [WaitQuery, RecvEvent],
            [RecvEvent, SendMsg],
            [RecvEvent, SendQuery],
            [RecvEvent, WaitQuery],
            // No [RecvEvent, RecvEvent] because it behaves differently: after
            // reporting an epitaph, the next call returns None.
        ] {
            let (client_end, server_end) = zx::Channel::create();
            let client_end = AsyncChannel::from_channel(client_end);
            let client = Client::new(client_end, "test_protocol");

            // Immediately close the FIDL channel with an epitaph.
            let server_end = AsyncChannel::from_channel(server_end);
            server_end
                .close_with_epitaph(zx_status::Status::UNAVAILABLE)
                .expect("failed to write epitaph");

            let mut event_receiver = client.take_event_receiver();

            // Assert that each action reports the epitaph.
            for (index, action) in two_actions.iter().enumerate() {
                let err = match action {
                    SendMsg => {
                        client.send::<u8>(SEND_DATA, SEND_ORDINAL, DynamicFlags::empty()).err()
                    }
                    WaitQuery => client
                        .send_query::<u8, u8, SEND_ORDINAL>(SEND_DATA, DynamicFlags::empty())
                        .await
                        .err(),
                    SendQuery => client
                        .send_query::<u8, u8, SEND_ORDINAL>(SEND_DATA, DynamicFlags::empty())
                        .check()
                        .err(),
                    RecvEvent => event_receiver.next().await.unwrap().err(),
                };
                let details = format!("index: {index:?}, two_actions: {two_actions:?}");
                match err {
                    None => assert!(
                        !action.should_report_epitaph(),
                        "expected epitaph, but succeeded.\n{details}"
                    ),
                    Some(crate::Error::ClientChannelClosed {
                        status: zx_status::Status::UNAVAILABLE,
                        protocol_name: "test_protocol",
                    }) => assert!(
                        action.should_report_epitaph(),
                        "got epitaph unexpectedly.\n{details}",
                    ),
                    Some(err) => panic!("unexpected error: {err:#?}.\n{details}"),
                }
            }

            // If we got the epitaph from RecvEvent, the next should return None.
            if two_actions.contains(&RecvEvent) {
                assert_matches!(event_receiver.next().await, None);
            }
        }
    }

    #[test]
    fn client_query_result_check() {
        let mut executor = fasync::TestExecutor::new();
        let (client_end, server_end) = zx::Channel::create();
        let client_end = AsyncChannel::from_channel(client_end);
        let client = Client::new(client_end, "test_protocol");

        let server = AsyncChannel::from_channel(server_end);

        // Sending works, and checking when a message successfully sends returns itself.
        let active_fut =
            client.send_query::<u8, u8, SEND_ORDINAL>(SEND_DATA, DynamicFlags::empty());

        let mut checked_fut = active_fut.check().expect("failed to check future");

        // Should be able to complete the query even after checking.
        let mut buffer = MessageBufEtc::new();
        executor.run_singlethreaded(server.recv_etc_msg(&mut buffer)).expect("failed to recv msg");
        let two_way_tx_id = 1u8;
        assert_eq!(buffer.bytes(), expected_sent_bytes(two_way_tx_id));

        let (bytes, handles) = (&mut vec![], &mut vec![]);
        let header =
            TransactionHeader::new(two_way_tx_id as u32, SEND_ORDINAL, DynamicFlags::empty());
        encode_transaction(header, bytes, handles);
        server.write_etc(bytes, handles).expect("Server channel write failed");

        executor
            .run_singlethreaded(&mut checked_fut)
            .map(|x| assert_eq!(x, SEND_DATA))
            .unwrap_or_else(|e| panic!("fidl error: {:?}", e));

        // Close the server channel, meaning the next query will fail.
        drop(server);

        let query_fut = client.send_query::<u8, u8, SEND_ORDINAL>(SEND_DATA, DynamicFlags::empty());

        // The check succeeds, because we do not expose PEER_CLOSED on writes.
        let mut checked_fut = query_fut.check().expect("failed to check future");
        // But the query will fail when it tries to read the response.
        assert_matches!(
            executor.run_singlethreaded(&mut checked_fut),
            Err(crate::Error::ClientChannelClosed {
                status: zx_status::Status::PEER_CLOSED,
                protocol_name: "test_protocol"
            })
        );
    }

    #[fasync::run_singlethreaded(test)]
    async fn client_into_channel() {
        // This test doesn't actually do any async work, but the fuchsia
        // executor must be set up in order to create the channel.
        let (client_end, _server_end) = zx::Channel::create();
        let client_end = AsyncChannel::from_channel(client_end);
        let client = Client::<DefaultFuchsiaResourceDialect>::new(client_end, "test_protocol");

        assert!(client.into_channel().is_ok());
    }

    #[fasync::run_singlethreaded(test)]
    async fn client_into_channel_outstanding_messages() {
        // This test doesn't actually do any async work, but the fuchsia
        // executor must be set up in order to create the channel.
        let (client_end, _server_end) = zx::Channel::create();
        let client_end = AsyncChannel::from_channel(client_end);
        let client = Client::<DefaultFuchsiaResourceDialect>::new(client_end, "test_protocol");

        {
            // Create a send future to insert a message interest but drop it
            // before a response can be received.
            let _sender =
                client.send_query::<u8, u8, SEND_ORDINAL>(SEND_DATA, DynamicFlags::empty());
        }

        assert!(client.into_channel().is_err());
    }

    #[fasync::run_singlethreaded(test)]
    async fn client_into_channel_active_clone() {
        // This test doesn't actually do any async work, but the fuchsia
        // executor must be set up in order to create the channel.
        let (client_end, _server_end) = zx::Channel::create();
        let client_end = AsyncChannel::from_channel(client_end);
        let client = Client::<DefaultFuchsiaResourceDialect>::new(client_end, "test_protocol");

        let _cloned_client = client.clone();

        assert!(client.into_channel().is_err());
    }

    #[fasync::run_singlethreaded(test)]
    async fn client_into_channel_outstanding_messages_get_received() {
        let (client_end, server_end) = zx::Channel::create();
        let client_end = AsyncChannel::from_channel(client_end);
        let client = Client::<DefaultFuchsiaResourceDialect>::new(client_end, "test_protocol");

        let server = AsyncChannel::from_channel(server_end);
        let mut buffer = MessageBufEtc::new();
        let receiver = async move {
            server.recv_etc_msg(&mut buffer).await.expect("failed to recv msg");
            let two_way_tx_id = 1u8;
            assert_eq!(buffer.bytes(), expected_sent_bytes(two_way_tx_id));

            let (bytes, handles) = (&mut vec![], &mut vec![]);
            let header =
                TransactionHeader::new(two_way_tx_id as u32, SEND_ORDINAL, DynamicFlags::empty());
            encode_transaction(header, bytes, handles);
            server.write_etc(bytes, handles).expect("Server channel write failed");
        };

        // add a timeout to receiver so if test is broken it doesn't take forever
        let receiver = receiver
            .on_timeout(zx::MonotonicDuration::from_millis(300).after_now(), || {
                panic!("did not receiver message in time!")
            });

        let sender = client
            .send_query::<u8, u8, SEND_ORDINAL>(SEND_DATA, DynamicFlags::empty())
            .map_ok(|x| assert_eq!(x, SEND_DATA))
            .unwrap_or_else(|e| panic!("fidl error: {:?}", e));

        // add a timeout to receiver so if test is broken it doesn't take forever
        let sender = sender.on_timeout(zx::MonotonicDuration::from_millis(300).after_now(), || {
            panic!("did not receive response in time!")
        });

        let ((), ()) = join!(receiver, sender);

        assert!(client.into_channel().is_ok());
    }

    #[fasync::run_singlethreaded(test)]
    async fn client_decode_errors_are_broadcast() {
        let (client_end, server_end) = zx::Channel::create();
        let client_end = AsyncChannel::from_channel(client_end);
        let client = Client::<DefaultFuchsiaResourceDialect>::new(client_end, "test_protocol");

        let server = AsyncChannel::from_channel(server_end);

        let _server = fasync::Task::spawn(async move {
            let mut buffer = MessageBufEtc::new();
            server.recv_etc_msg(&mut buffer).await.expect("failed to recv msg");
            let two_way_tx_id = 1u8;
            assert_eq!(buffer.bytes(), expected_sent_bytes(two_way_tx_id));

            let (bytes, handles) = (&mut vec![], &mut vec![]);
            let header =
                TransactionHeader::new(two_way_tx_id as u32, SEND_ORDINAL, DynamicFlags::empty());
            encode_transaction(header, bytes, handles);
            // Zero out the at-rest flags which will give this message an invalid version.
            bytes[4] = 0;
            server.write_etc(bytes, handles).expect("Server channel write failed");

            // Wait forever to stop the channel from being closed.
            pending::<()>().await;
        });

        let futures = FuturesUnordered::new();

        for _ in 0..4 {
            futures.push(async {
                assert_matches!(
                    client
                        .send_query::<u8, u8, SEND_ORDINAL>(SEND_DATA, DynamicFlags::empty())
                        .map_ok(|x| assert_eq!(x, SEND_DATA))
                        .await,
                    Err(crate::Error::UnsupportedWireFormatVersion)
                );
            });
        }

        futures
            .collect::<Vec<_>>()
            .on_timeout(zx::MonotonicDuration::from_seconds(1).after_now(), || panic!("timed out!"))
            .await;
    }

    #[fasync::run_singlethreaded(test)]
    async fn into_channel_from_waker_succeeds() {
        let (client_end, server_end) = zx::Channel::create();
        let client_end = AsyncChannel::from_channel(client_end);
        let client = Client::<DefaultFuchsiaResourceDialect>::new(client_end, "test_protocol");

        let server = AsyncChannel::from_channel(server_end);
        let mut buffer = MessageBufEtc::new();
        let receiver = async move {
            server.recv_etc_msg(&mut buffer).await.expect("failed to recv msg");
            let two_way_tx_id = 1u8;
            assert_eq!(buffer.bytes(), expected_sent_bytes(two_way_tx_id));

            let (bytes, handles) = (&mut vec![], &mut vec![]);
            let header =
                TransactionHeader::new(two_way_tx_id as u32, SEND_ORDINAL, DynamicFlags::empty());
            encode_transaction(header, bytes, handles);
            server.write_etc(bytes, handles).expect("Server channel write failed");
        };

        struct Sender {
            future: Mutex<Pin<Box<dyn Future<Output = ()> + Send + Sync + 'static>>>,
        }

        let (done_tx, done_rx) = oneshot::channel();

        let sender = Arc::new(Sender {
            future: Mutex::new(Box::pin(async move {
                client
                    .send_query::<u8, u8, SEND_ORDINAL>(SEND_DATA, DynamicFlags::empty())
                    .map_ok(|x| assert_eq!(x, SEND_DATA))
                    .unwrap_or_else(|e| panic!("fidl error: {:?}", e))
                    .await;

                assert!(client.into_channel().is_ok());

                let _ = done_tx.send(());
            })),
        });

        // This test isn't typically how this would work; normally, the future would get woken and
        // an executor would be responsible for running the task.  We do it this way because if this
        // works, then it means the case where `into_channel` is used after a response is received
        // on a multi-threaded executor will always work (which isn't easy to test directly).
        impl ArcWake for Sender {
            fn wake_by_ref(arc_self: &Arc<Self>) {
                assert!(arc_self
                    .future
                    .lock()
                    .poll_unpin(&mut Context::from_waker(&noop_waker()))
                    .is_ready());
            }
        }

        let waker = waker(sender.clone());

        assert!(sender.future.lock().poll_unpin(&mut Context::from_waker(&waker)).is_pending());

        receiver.await;

        done_rx.await.unwrap();
    }
}