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 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248
use std::future::Future;
use std::time::Duration;
use std::{fmt, io};
use async_trait::async_trait;
use bytes::{Buf, BytesMut};
use log::*;
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use super::{InmemoryTransport, Interest, Ready, Reconnectable, Transport};
use crate::common::{utils, SecretKey32};
mod backup;
mod codec;
mod exchange;
mod frame;
mod handshake;
pub use backup::*;
pub use codec::*;
pub use exchange::*;
pub use frame::*;
pub use handshake::*;
/// Size of the read buffer when reading bytes to construct a frame
const READ_BUF_SIZE: usize = 8 * 1024;
/// Duration to wait after WouldBlock received during looping operations like `read_frame`
const SLEEP_DURATION: Duration = Duration::from_millis(1);
/// Represents a wrapper around a [`Transport`] that reads and writes using frames defined by a
/// [`Codec`].
///
/// [`try_read`]: Transport::try_read
#[derive(Clone)]
pub struct FramedTransport<T> {
/// Inner transport wrapped to support frames of data
inner: T,
/// Codec used to encoding outgoing bytes and decode incoming bytes
codec: BoxedCodec,
/// Bytes in queue to be read
incoming: BytesMut,
/// Bytes in queue to be written
outgoing: BytesMut,
/// Stores outgoing frames in case of transmission issues
pub backup: Backup,
}
impl<T> FramedTransport<T> {
pub fn new(inner: T, codec: BoxedCodec) -> Self {
Self {
inner,
codec,
incoming: BytesMut::with_capacity(READ_BUF_SIZE * 2),
outgoing: BytesMut::with_capacity(READ_BUF_SIZE * 2),
backup: Backup::new(),
}
}
/// Creates a new [`FramedTransport`] using the [`PlainCodec`]
pub fn plain(inner: T) -> Self {
Self::new(inner, Box::new(PlainCodec::new()))
}
/// Replaces the current codec with the provided codec. Note that any bytes in the incoming or
/// outgoing buffers will remain in the transport, meaning that this can cause corruption if
/// the bytes in the buffers do not match the new codec.
///
/// For safety, use [`clear`] to wipe the buffers before further use.
///
/// [`clear`]: FramedTransport::clear
pub fn set_codec(&mut self, codec: BoxedCodec) {
self.codec = codec;
}
/// Returns a reference to the codec used by the transport.
///
/// ### Note
///
/// Be careful when accessing the codec to avoid corrupting it through unexpected modifications
/// as this will place the transport in an undefined state.
pub fn codec(&self) -> &dyn Codec {
self.codec.as_ref()
}
/// Returns a mutable reference to the codec used by the transport.
///
/// ### Note
///
/// Be careful when accessing the codec to avoid corrupting it through unexpected modifications
/// as this will place the transport in an undefined state.
pub fn mut_codec(&mut self) -> &mut dyn Codec {
self.codec.as_mut()
}
/// Clears the internal transport buffers.
pub fn clear(&mut self) {
self.incoming.clear();
self.outgoing.clear();
}
/// Returns a reference to the inner value this transport wraps.
pub fn as_inner(&self) -> &T {
&self.inner
}
/// Returns a mutable reference to the inner value this transport wraps.
pub fn as_mut_inner(&mut self) -> &mut T {
&mut self.inner
}
/// Consumes this transport, returning the inner value that it wraps.
pub fn into_inner(self) -> T {
self.inner
}
}
impl<T> fmt::Debug for FramedTransport<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("FramedTransport")
.field("incoming", &self.incoming)
.field("outgoing", &self.outgoing)
.field("backup", &self.backup)
.finish()
}
}
impl<T: Transport + 'static> FramedTransport<T> {
/// Converts this instance to a [`FramedTransport`] whose inner [`Transport`] is [`Box`]ed.
pub fn into_boxed(self) -> FramedTransport<Box<dyn Transport>> {
FramedTransport {
inner: Box::new(self.inner),
codec: self.codec,
incoming: self.incoming,
outgoing: self.outgoing,
backup: self.backup,
}
}
}
impl<T: Transport> FramedTransport<T> {
/// Waits for the transport to be ready based on the given interest, returning the ready status
pub async fn ready(&self, interest: Interest) -> io::Result<Ready> {
// If interest includes reading, we check if we already have a frame in our queue,
// as there can be a scenario where a frame was received and then the connection
// was closed, and we still want to be able to read the next frame is if it is
// available in the connection.
let ready = if interest.is_readable() && Frame::available(&self.incoming) {
Ready::READABLE
} else {
Ready::EMPTY
};
// If we know that we are readable and not checking for write status, we can short-circuit
// to avoid an async call by returning immediately that we are readable
if !interest.is_writable() && ready.is_readable() {
return Ok(ready);
}
// Otherwise, we need to check the status using the underlying transport and merge it with
// our current understanding based on internal state
Transport::ready(&self.inner, interest)
.await
.map(|r| r | ready)
}
/// Waits for the transport to be readable to follow up with [`try_read_frame`].
///
/// [`try_read_frame`]: FramedTransport::try_read_frame
pub async fn readable(&self) -> io::Result<()> {
let _ = self.ready(Interest::READABLE).await?;
Ok(())
}
/// Waits for the transport to be writeable to follow up with [`try_write_frame`].
///
/// [`try_write_frame`]: FramedTransport::try_write_frame
pub async fn writeable(&self) -> io::Result<()> {
let _ = self.ready(Interest::WRITABLE).await?;
Ok(())
}
/// Waits for the transport to be readable or writeable, returning the [`Ready`] status.
pub async fn readable_or_writeable(&self) -> io::Result<Ready> {
self.ready(Interest::READABLE | Interest::WRITABLE).await
}
/// Attempts to flush any remaining bytes in the outgoing queue, returning the total bytes
/// written as a result of the flush. Note that a return of 0 bytes does not indicate that the
/// underlying transport has closed, but rather that no bytes were flushed such as when the
/// outgoing queue is empty.
///
/// This is accomplished by continually calling the inner transport's `try_write`. If 0 is
/// returned from a call to `try_write`, this will fail with [`ErrorKind::WriteZero`].
///
/// This call may return an error with [`ErrorKind::WouldBlock`] in the case that the transport
/// is not ready to write data.
///
/// [`ErrorKind::WouldBlock`]: io::ErrorKind::WouldBlock
pub fn try_flush(&mut self) -> io::Result<usize> {
let mut bytes_written = 0;
// Continue to send from the outgoing buffer until we either finish or fail
while !self.outgoing.is_empty() {
match self.inner.try_write(self.outgoing.as_ref()) {
// Getting 0 bytes on write indicates the channel has closed
Ok(0) => return Err(io::Error::from(io::ErrorKind::WriteZero)),
// Successful write will advance the outgoing buffer
Ok(n) => {
self.outgoing.advance(n);
bytes_written += n;
}
// Any error (including WouldBlock) will get bubbled up
Err(x) => return Err(x),
}
}
Ok(bytes_written)
}
/// Flushes all buffered, outgoing bytes using repeated calls to [`try_flush`].
///
/// [`try_flush`]: FramedTransport::try_flush
pub async fn flush(&mut self) -> io::Result<()> {
while !self.outgoing.is_empty() {
self.writeable().await?;
match self.try_flush() {
Err(x) if x.kind() == io::ErrorKind::WouldBlock => {
// NOTE: We sleep for a little bit before trying again to avoid pegging CPU
tokio::time::sleep(SLEEP_DURATION).await
}
Err(x) => return Err(x),
Ok(_) => return Ok(()),
}
}
Ok(())
}
/// Reads a frame of bytes by using the [`Codec`] tied to this transport. Returns
/// `Ok(Some(frame))` upon reading a frame, or `Ok(None)` if the underlying transport has
/// closed.
///
/// This call may return an error with [`ErrorKind::WouldBlock`] in the case that the transport
/// is not ready to read data or has not received a full frame before waiting.
///
/// [`ErrorKind::WouldBlock`]: io::ErrorKind::WouldBlock
pub fn try_read_frame(&mut self) -> io::Result<Option<OwnedFrame>> {
// Attempt to read a frame, returning the decoded frame if we get one, returning any error
// that is encountered from reading frames or failing to decode, or otherwise doing nothing
// and continuing forward.
macro_rules! read_next_frame {
() => {{
match Frame::read(&mut self.incoming) {
None => (),
Some(frame) => {
if frame.is_nonempty() {
self.backup.increment_received_cnt();
}
return Ok(Some(self.codec.decode(frame)?.into_owned()));
}
}
}};
}
// If we have data remaining in the buffer, we first try to parse it in case we received
// multiple frames from a previous call.
//
// NOTE: This exists to avoid the situation where there is a valid frame remaining in the
// incoming buffer, but it is never evaluated because a call to `try_read` returns
// `WouldBlock`, 0 bytes, or some other error.
if !self.incoming.is_empty() {
read_next_frame!();
}
// Continually read bytes into the incoming queue and then attempt to tease out a frame
let mut buf = [0; READ_BUF_SIZE];
loop {
match self.inner.try_read(&mut buf) {
// Getting 0 bytes on read indicates the channel has closed. If we were still
// expecting more bytes for our frame, then this is an error, otherwise if we
// have nothing remaining if our queue then this is an expected end and we
// return None
Ok(0) if self.incoming.is_empty() => return Ok(None),
Ok(0) => return Err(io::Error::from(io::ErrorKind::UnexpectedEof)),
// Got some additional bytes, which we will add to our queue and then attempt to
// decode into a frame
Ok(n) => {
self.incoming.extend_from_slice(&buf[..n]);
read_next_frame!();
}
// Any error (including WouldBlock) will get bubbled up
Err(x) => return Err(x),
}
}
}
/// Reads a frame using [`try_read_frame`] and then deserializes the bytes into `D`.
///
/// [`try_read_frame`]: FramedTransport::try_read_frame
pub fn try_read_frame_as<D: DeserializeOwned>(&mut self) -> io::Result<Option<D>> {
match self.try_read_frame() {
Ok(Some(frame)) => Ok(Some(utils::deserialize_from_slice(frame.as_item())?)),
Ok(None) => Ok(None),
Err(x) => Err(x),
}
}
/// Continues to invoke [`try_read_frame`] until a frame is successfully read, an error is
/// encountered that is not [`ErrorKind::WouldBlock`], or the underlying transport has closed.
///
/// [`try_read_frame`]: FramedTransport::try_read_frame
/// [`ErrorKind::WouldBlock`]: io::ErrorKind::WouldBlock
pub async fn read_frame(&mut self) -> io::Result<Option<OwnedFrame>> {
loop {
self.readable().await?;
match self.try_read_frame() {
Err(x) if x.kind() == io::ErrorKind::WouldBlock => {
// NOTE: We sleep for a little bit before trying again to avoid pegging CPU
tokio::time::sleep(SLEEP_DURATION).await
}
x => return x,
}
}
}
/// Reads a frame using [`read_frame`] and then deserializes the bytes into `D`.
///
/// [`read_frame`]: FramedTransport::read_frame
pub async fn read_frame_as<D: DeserializeOwned>(&mut self) -> io::Result<Option<D>> {
match self.read_frame().await {
Ok(Some(frame)) => Ok(Some(utils::deserialize_from_slice(frame.as_item())?)),
Ok(None) => Ok(None),
Err(x) => Err(x),
}
}
/// Writes a `frame` of bytes by using the [`Codec`] tied to this transport.
///
/// This is accomplished by continually calling the inner transport's `try_write`. If 0 is
/// returned from a call to `try_write`, this will fail with [`ErrorKind::WriteZero`].
///
/// This call may return an error with [`ErrorKind::WouldBlock`] in the case that the transport
/// is not ready to write data or has not written the entire frame before waiting.
///
/// [`ErrorKind::WriteZero`]: io::ErrorKind::WriteZero
/// [`ErrorKind::WouldBlock`]: io::ErrorKind::WouldBlock
pub fn try_write_frame<'a, F>(&mut self, frame: F) -> io::Result<()>
where
F: TryInto<Frame<'a>>,
F::Error: Into<Box<dyn std::error::Error + Send + Sync>>,
{
// Grab the frame to send
let frame = frame
.try_into()
.map_err(|x| io::Error::new(io::ErrorKind::InvalidInput, x))?;
// Encode the frame and store it in our outgoing queue
self.codec
.encode(frame.as_borrowed())?
.write(&mut self.outgoing);
// Update tracking stats and more of backup if frame is nonempty
if frame.is_nonempty() {
// Once the frame enters our queue, we count it as written, even if it isn't fully flushed
self.backup.increment_sent_cnt();
// Then we store the raw frame (non-encoded) for the future in case we need to retry
// sending it later (possibly with a different codec)
self.backup.push_frame(frame);
}
// Attempt to write everything in our queue
self.try_flush()?;
Ok(())
}
/// Serializes `value` into bytes and passes them to [`try_write_frame`].
///
/// [`try_write_frame`]: FramedTransport::try_write_frame
pub fn try_write_frame_for<D: Serialize>(&mut self, value: &D) -> io::Result<()> {
let data = utils::serialize_to_vec(value)?;
self.try_write_frame(data)
}
/// Invokes [`try_write_frame`] followed by a continuous calls to [`try_flush`] until a frame
/// is successfully written, an error is encountered that is not [`ErrorKind::WouldBlock`], or
/// the underlying transport has closed.
///
/// [`try_write_frame`]: FramedTransport::try_write_frame
/// [`try_flush`]: FramedTransport::try_flush
/// [`ErrorKind::WouldBlock`]: io::ErrorKind::WouldBlock
pub async fn write_frame<'a, F>(&mut self, frame: F) -> io::Result<()>
where
F: TryInto<Frame<'a>>,
F::Error: Into<Box<dyn std::error::Error + Send + Sync>>,
{
self.writeable().await?;
match self.try_write_frame(frame) {
// Would block, so continually try to flush until good to go
Err(x) if x.kind() == io::ErrorKind::WouldBlock => loop {
self.writeable().await?;
match self.try_flush() {
Err(x) if x.kind() == io::ErrorKind::WouldBlock => {
// NOTE: We sleep for a little bit before trying again to avoid pegging CPU
tokio::time::sleep(SLEEP_DURATION).await
}
Err(x) => return Err(x),
Ok(_) => return Ok(()),
}
},
// Already fully succeeded or failed
x => x,
}
}
/// Serializes `value` into bytes and passes them to [`write_frame`].
///
/// [`write_frame`]: FramedTransport::write_frame
pub async fn write_frame_for<D: Serialize>(&mut self, value: &D) -> io::Result<()> {
let data = utils::serialize_to_vec(value)?;
self.write_frame(data).await
}
/// Executes the async function while the [`Backup`] of this transport is frozen.
pub async fn do_frozen<F, X>(&mut self, mut f: F) -> io::Result<()>
where
F: FnMut(&mut Self) -> X,
X: Future<Output = io::Result<()>>,
{
let is_frozen = self.backup.is_frozen();
self.backup.freeze();
let result = f(self).await;
self.backup.set_frozen(is_frozen);
result
}
/// Places the transport in **synchronize mode** where it communicates with the other side how
/// many frames have been sent and received. From there, any frames not received by the other
/// side are sent again and then this transport waits for any missing frames that it did not
/// receive from the other side.
///
/// ### Note
///
/// This will clear the internal incoming and outgoing buffers, so any frame that was in
/// transit in either direction will be dropped.
pub async fn synchronize(&mut self) -> io::Result<()> {
async fn synchronize_impl<T: Transport>(
this: &mut FramedTransport<T>,
backup: &mut Backup,
) -> io::Result<()> {
type Stats = (u64, u64, u64);
// Stats in the form of (sent, received, available)
let sent_cnt: u64 = backup.sent_cnt();
let received_cnt: u64 = backup.received_cnt();
let available_cnt: u64 = backup
.frame_cnt()
.try_into()
.expect("Cannot case usize to u64");
// Clear our internal buffers
this.clear();
// Communicate frame counters with other side so we can determine how many frames to send
// and how many to receive. Wait until we get the stats from the other side, and then send
// over any missing frames.
trace!(
"Stats: sent = {sent_cnt}, received = {received_cnt}, available = {available_cnt}"
);
this.write_frame_for(&(sent_cnt, received_cnt, available_cnt))
.await?;
let (other_sent_cnt, other_received_cnt, other_available_cnt) =
this.read_frame_as::<Stats>().await?.ok_or_else(|| {
io::Error::new(
io::ErrorKind::UnexpectedEof,
"Transport terminated before getting replay stats",
)
})?;
trace!("Other stats: sent = {other_sent_cnt}, received = {other_received_cnt}, available = {other_available_cnt}");
// Determine how many frames we need to resend. This will either be (sent - received) or
// available frames, whichever is smaller.
let resend_cnt = std::cmp::min(
if sent_cnt > other_received_cnt {
sent_cnt - other_received_cnt
} else {
0
},
available_cnt,
);
// Determine how many frames we expect to receive. This will either be (received - sent) or
// available frames, whichever is smaller.
let expected_cnt = std::cmp::min(
if received_cnt < other_sent_cnt {
other_sent_cnt - received_cnt
} else {
0
},
other_available_cnt,
);
// Send all missing frames, removing any frames that we know have been received
trace!("Reducing internal replay frames to {resend_cnt}");
backup.truncate_front(resend_cnt.try_into().expect("Cannot cast usize to u64"));
debug!("Sending {resend_cnt} frames");
for frame in backup.frames() {
this.try_write_frame(frame.as_borrowed())?;
}
this.flush().await?;
// Receive all expected frames, placing their contents into our incoming queue
//
// NOTE: We do not increment our counter as this is done during `try_read_frame`, even
// when the frame comes from our internal queue. To avoid duplicating the increment,
// we do not increment the counter here.
debug!("Waiting for {expected_cnt} frames");
for i in 0..expected_cnt {
let frame = this.read_frame().await?.ok_or_else(|| {
io::Error::new(
io::ErrorKind::UnexpectedEof,
format!(
"Transport terminated before getting frame {}/{expected_cnt}",
i + 1
),
)
})?;
// Encode our frame and write it to be queued in our incoming data
// NOTE: We have to do encoding here as incoming bytes are expected to be encoded
this.codec.encode(frame)?.write(&mut this.incoming);
}
// Catch up our read count as we can have the case where the other side has a higher
// count than frames sent if some frames were fully dropped due to size limits
if backup.received_cnt() != other_sent_cnt {
warn!(
"Backup received count ({}) != other sent count ({}), so resetting to match",
backup.received_cnt(),
other_sent_cnt
);
backup.set_received_cnt(other_sent_cnt);
}
Ok(())
}
// Swap out our backup so we don't mutate it from synchronization efforts
let mut backup = std::mem::take(&mut self.backup);
// Perform our operation, but don't return immediately so we can restore our backup
let result = synchronize_impl(self, &mut backup).await;
// Reset our backup to the real version
self.backup = backup;
result
}
/// Shorthand for creating a [`FramedTransport`] with a [`PlainCodec`] and then immediately
/// performing a [`client_handshake`], returning the updated [`FramedTransport`] on success.
///
/// [`client_handshake`]: FramedTransport::client_handshake
#[inline]
pub async fn from_client_handshake(transport: T) -> io::Result<Self> {
let mut transport = Self::plain(transport);
transport.client_handshake().await?;
Ok(transport)
}
/// Perform the client-side of a handshake. See [`handshake`] for more details.
///
/// [`handshake`]: FramedTransport::handshake
pub async fn client_handshake(&mut self) -> io::Result<()> {
self.handshake(Handshake::client()).await
}
/// Shorthand for creating a [`FramedTransport`] with a [`PlainCodec`] and then immediately
/// performing a [`server_handshake`], returning the updated [`FramedTransport`] on success.
///
/// [`client_handshake`]: FramedTransport::client_handshake
#[inline]
pub async fn from_server_handshake(transport: T) -> io::Result<Self> {
let mut transport = Self::plain(transport);
transport.server_handshake().await?;
Ok(transport)
}
/// Perform the server-side of a handshake. See [`handshake`] for more details.
///
/// [`handshake`]: FramedTransport::handshake
pub async fn server_handshake(&mut self) -> io::Result<()> {
self.handshake(Handshake::server()).await
}
/// Performs a handshake in order to establish a new codec to use between this transport and
/// the other side. The parameter `handshake` defines how the transport will handle the
/// handshake with `Client` being used to pick the compression and encryption used while
/// `Server` defines what the choices are for compression and encryption.
///
/// This will reset the framed transport's codec to [`PlainCodec`] in order to communicate
/// which compression and encryption to use. Upon selecting an encryption type, a shared secret
/// key will be derived on both sides and used to establish the [`EncryptionCodec`], which in
/// combination with the [`CompressionCodec`] (if any) will replace this transport's codec.
///
/// ### Client
///
/// 1. Wait for options from server
/// 2. Send to server a compression and encryption choice
/// 3. Configure framed transport using selected choices
/// 4. Invoke on_handshake function
///
/// ### Server
///
/// 1. Send options to client
/// 2. Receive choices from client
/// 3. Configure framed transport using client's choices
/// 4. Invoke on_handshake function
///
/// ### Failure
///
/// The handshake will fail in several cases:
///
/// * If any frame during the handshake fails to be serialized
/// * If any unexpected frame is received during the handshake
/// * If using encryption and unable to derive a shared secret key
///
/// If a failure happens, the codec will be reset to what it was prior to the handshake
/// request, and all internal buffers will be cleared to avoid corruption.
///
pub async fn handshake(&mut self, handshake: Handshake) -> io::Result<()> {
// Place transport in plain text communication mode for start of handshake, and clear any
// data that is lingering within internal buffers
//
// NOTE: We grab the old codec in case we encounter an error and need to reset it
let old_codec = std::mem::replace(&mut self.codec, Box::new(PlainCodec::new()));
self.clear();
// Swap out our backup so we don't mutate it from synchronization efforts
let backup = std::mem::take(&mut self.backup);
// Transform the transport's codec to abide by the choice. In the case of an error, we
// reset the codec back to what it was prior to attempting the handshake and clear the
// internal buffers as they may be corrupt.
match self.handshake_impl(handshake).await {
Ok(codec) => {
self.set_codec(codec);
self.backup = backup;
Ok(())
}
Err(x) => {
self.set_codec(old_codec);
self.clear();
self.backup = backup;
Err(x)
}
}
}
async fn handshake_impl(&mut self, handshake: Handshake) -> io::Result<BoxedCodec> {
#[derive(Debug, Serialize, Deserialize)]
struct Choice {
compression_level: Option<CompressionLevel>,
compression_type: Option<CompressionType>,
encryption_type: Option<EncryptionType>,
}
#[derive(Debug, Serialize, Deserialize)]
struct Options {
compression_types: Vec<CompressionType>,
encryption_types: Vec<EncryptionType>,
}
// Define a label to distinguish log output for client and server
let log_label = if handshake.is_client() {
"Handshake | Client"
} else {
"Handshake | Server"
};
// Determine compression and encryption to apply to framed transport
let choice = match handshake {
Handshake::Client {
preferred_compression_type,
preferred_compression_level,
preferred_encryption_type,
} => {
// Receive options from the server and pick one
debug!("[{log_label}] Waiting on options");
let options = self.read_frame_as::<Options>().await?.ok_or_else(|| {
io::Error::new(
io::ErrorKind::UnexpectedEof,
"Transport closed early while waiting for options",
)
})?;
// Choose a compression and encryption option from the options
debug!("[{log_label}] Selecting from options: {options:?}");
let choice = Choice {
// Use preferred compression if available, otherwise default to no compression
// to avoid choosing something poor
compression_type: preferred_compression_type
.filter(|ty| options.compression_types.contains(ty)),
// Use preferred compression level, otherwise allowing the server to pick
compression_level: preferred_compression_level,
// Use preferred encryption, otherwise pick first non-unknown encryption type
// that is available instead
encryption_type: preferred_encryption_type
.filter(|ty| options.encryption_types.contains(ty))
.or_else(|| {
options
.encryption_types
.iter()
.find(|ty| !ty.is_unknown())
.copied()
}),
};
// Report back to the server the choice
debug!("[{log_label}] Reporting choice: {choice:?}");
self.write_frame_for(&choice).await?;
choice
}
Handshake::Server {
compression_types,
encryption_types,
} => {
let options = Options {
compression_types: compression_types.to_vec(),
encryption_types: encryption_types.to_vec(),
};
// Send options to the client
debug!("[{log_label}] Sending options: {options:?}");
self.write_frame_for(&options).await?;
// Get client's response with selected compression and encryption
debug!("[{log_label}] Waiting on choice");
self.read_frame_as::<Choice>().await?.ok_or_else(|| {
io::Error::new(
io::ErrorKind::UnexpectedEof,
"Transport closed early while waiting for choice",
)
})?
}
};
debug!("[{log_label}] Building compression & encryption codecs based on {choice:?}");
let compression_level = choice.compression_level.unwrap_or_default();
// Acquire a codec for the compression type
let compression_codec = choice
.compression_type
.map(|ty| ty.new_codec(compression_level))
.transpose()?;
// In the case that we are using encryption, we derive a shared secret key to use with the
// encryption type
let encryption_codec = match choice.encryption_type {
// Fail early if we got an unknown encryption type
Some(EncryptionType::Unknown) => {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"Unknown compression type",
))
}
Some(ty) => {
let key = self.exchange_keys_impl(log_label).await?;
Some(ty.new_codec(key.unprotected_as_bytes())?)
}
None => None,
};
// Bundle our compression and encryption codecs into a single, chained codec
trace!("[{log_label}] Bundling codecs");
let codec: BoxedCodec = match (compression_codec, encryption_codec) {
// If we have both encryption and compression, do the encryption first and then
// compress in order to get smallest result
(Some(c), Some(e)) => Box::new(ChainCodec::new(e, c)),
// If we just have compression, pass along the compression codec
(Some(c), None) => Box::new(c),
// If we just have encryption, pass along the encryption codec
(None, Some(e)) => Box::new(e),
// If we have neither compression nor encryption, use a plaintext codec
(None, None) => Box::new(PlainCodec::new()),
};
Ok(codec)
}
/// Places the transport into key-exchange mode where it attempts to derive a shared secret key
/// with the other transport.
pub async fn exchange_keys(&mut self) -> io::Result<SecretKey32> {
self.exchange_keys_impl("").await
}
async fn exchange_keys_impl(&mut self, label: &str) -> io::Result<SecretKey32> {
let log_label = if label.is_empty() {
String::new()
} else {
format!("[{label}] ")
};
#[derive(Serialize, Deserialize)]
struct KeyExchangeData {
/// Bytes of the public key
#[serde(with = "serde_bytes")]
public_key: PublicKeyBytes,
/// Randomly generated salt
#[serde(with = "serde_bytes")]
salt: Salt,
}
debug!("{log_label}Exchanging public key and salt");
let exchange = KeyExchange::default();
self.write_frame_for(&KeyExchangeData {
public_key: exchange.pk_bytes(),
salt: *exchange.salt(),
})
.await?;
// TODO: This key only works because it happens to be 32 bytes and our encryption
// also wants a 32-byte key. Once we introduce new encryption algorithms that
// are not using 32-byte keys, the key exchange will need to support deriving
// other length keys.
trace!("{log_label}Waiting on public key and salt from other side");
let data = self
.read_frame_as::<KeyExchangeData>()
.await?
.ok_or_else(|| {
io::Error::new(
io::ErrorKind::UnexpectedEof,
"Transport closed early while waiting for key data",
)
})?;
trace!("{log_label}Deriving shared secret key");
let key = exchange.derive_shared_secret(data.public_key, data.salt)?;
Ok(key)
}
}
#[async_trait]
impl<T> Reconnectable for FramedTransport<T>
where
T: Transport,
{
async fn reconnect(&mut self) -> io::Result<()> {
Reconnectable::reconnect(&mut self.inner).await
}
}
impl FramedTransport<InmemoryTransport> {
/// Produces a pair of inmemory transports that are connected to each other using a
/// [`PlainCodec`].
///
/// Sets the buffer for message passing for each underlying transport to the given buffer size.
pub fn pair(
buffer: usize,
) -> (
FramedTransport<InmemoryTransport>,
FramedTransport<InmemoryTransport>,
) {
let (a, b) = InmemoryTransport::pair(buffer);
let a = FramedTransport::new(a, Box::new(PlainCodec::new()));
let b = FramedTransport::new(b, Box::new(PlainCodec::new()));
(a, b)
}
/// Links the underlying transports together using [`InmemoryTransport::link`].
pub fn link(&mut self, other: &mut Self, buffer: usize) {
self.inner.link(&mut other.inner, buffer)
}
}
#[cfg(test)]
impl FramedTransport<InmemoryTransport> {
/// Generates a test pair with default capacity
pub fn test_pair(
buffer: usize,
) -> (
FramedTransport<InmemoryTransport>,
FramedTransport<InmemoryTransport>,
) {
Self::pair(buffer)
}
}
#[cfg(test)]
mod tests {
use bytes::BufMut;
use test_log::test;
use super::*;
use crate::common::TestTransport;
/// Codec that always succeeds without altering the frame
#[derive(Clone, Debug, PartialEq, Eq)]
struct OkCodec;
impl Codec for OkCodec {
fn encode<'a>(&mut self, frame: Frame<'a>) -> io::Result<Frame<'a>> {
Ok(frame)
}
fn decode<'a>(&mut self, frame: Frame<'a>) -> io::Result<Frame<'a>> {
Ok(frame)
}
}
/// Codec that always fails
#[derive(Clone, Debug, PartialEq, Eq)]
struct ErrCodec;
impl Codec for ErrCodec {
fn encode<'a>(&mut self, _frame: Frame<'a>) -> io::Result<Frame<'a>> {
Err(io::Error::from(io::ErrorKind::Other))
}
fn decode<'a>(&mut self, _frame: Frame<'a>) -> io::Result<Frame<'a>> {
Err(io::Error::from(io::ErrorKind::Other))
}
}
// Hardcoded custom codec so we can verify it works differently than plain codec
#[derive(Clone)]
struct CustomCodec;
impl Codec for CustomCodec {
fn encode<'a>(&mut self, _: Frame<'a>) -> io::Result<Frame<'a>> {
Ok(Frame::new(b"encode"))
}
fn decode<'a>(&mut self, _: Frame<'a>) -> io::Result<Frame<'a>> {
Ok(Frame::new(b"decode"))
}
}
type SimulateTryReadFn = Box<dyn Fn(&mut [u8]) -> io::Result<usize> + Send + Sync>;
/// Simulate calls to try_read by feeding back `data` in `step` increments, triggering a block
/// if `block_on` returns true where `block_on` is provided a counter value that is incremented
/// every time the simulated `try_read` function is called
///
/// NOTE: This will inject the frame len in front of the provided data to properly simulate
/// receiving a frame of data
fn simulate_try_read(
frames: Vec<Frame>,
step: usize,
block_on: impl Fn(usize) -> bool + Send + Sync + 'static,
) -> SimulateTryReadFn {
use std::sync::atomic::{AtomicUsize, Ordering};
// Stuff all of our frames into a single byte collection
let data = {
let mut buf = BytesMut::new();
for frame in frames {
frame.write(&mut buf);
}
buf.to_vec()
};
let idx = AtomicUsize::new(0);
let cnt = AtomicUsize::new(0);
Box::new(move |buf| {
if block_on(cnt.fetch_add(1, Ordering::Relaxed)) {
return Err(io::Error::from(io::ErrorKind::WouldBlock));
}
let start = idx.fetch_add(step, Ordering::Relaxed);
let end = start + step;
let end = if end > data.len() { data.len() } else { end };
let len = if start > end { 0 } else { end - start };
buf[..len].copy_from_slice(&data[start..end]);
Ok(len)
})
}
#[test]
fn try_read_frame_should_return_would_block_if_fails_to_read_frame_before_blocking() {
// Should fail if immediately blocks
let mut transport = FramedTransport::new(
TestTransport {
f_try_read: Box::new(|_| Err(io::Error::from(io::ErrorKind::WouldBlock))),
f_ready: Box::new(|_| Ok(Ready::READABLE)),
..Default::default()
},
Box::new(OkCodec),
);
assert_eq!(
transport.try_read_frame().unwrap_err().kind(),
io::ErrorKind::WouldBlock
);
// Should fail if not read enough bytes before blocking
let mut transport = FramedTransport::new(
TestTransport {
f_try_read: simulate_try_read(vec![Frame::new(b"some data")], 1, |cnt| cnt == 1),
f_ready: Box::new(|_| Ok(Ready::READABLE)),
..Default::default()
},
Box::new(OkCodec),
);
assert_eq!(
transport.try_read_frame().unwrap_err().kind(),
io::ErrorKind::WouldBlock
);
}
#[test]
fn try_read_frame_should_return_error_if_encountered_error_with_reading_bytes() {
let mut transport = FramedTransport::new(
TestTransport {
f_try_read: Box::new(|_| Err(io::Error::from(io::ErrorKind::NotConnected))),
f_ready: Box::new(|_| Ok(Ready::READABLE)),
..Default::default()
},
Box::new(OkCodec),
);
assert_eq!(
transport.try_read_frame().unwrap_err().kind(),
io::ErrorKind::NotConnected
);
}
#[test]
fn try_read_frame_should_return_error_if_encountered_error_during_decode() {
let mut transport = FramedTransport::new(
TestTransport {
f_try_read: simulate_try_read(vec![Frame::new(b"some data")], 1, |_| false),
f_ready: Box::new(|_| Ok(Ready::READABLE)),
..Default::default()
},
Box::new(ErrCodec),
);
assert_eq!(
transport.try_read_frame().unwrap_err().kind(),
io::ErrorKind::Other
);
}
#[test]
fn try_read_frame_should_return_next_available_frame() {
let data = {
let mut data = BytesMut::new();
Frame::new(b"hello world").write(&mut data);
data.freeze()
};
let mut transport = FramedTransport::new(
TestTransport {
f_try_read: Box::new(move |buf| {
buf[..data.len()].copy_from_slice(data.as_ref());
Ok(data.len())
}),
f_ready: Box::new(|_| Ok(Ready::READABLE)),
..Default::default()
},
Box::new(OkCodec),
);
assert_eq!(transport.try_read_frame().unwrap().unwrap(), b"hello world");
}
#[test]
fn try_read_frame_should_return_next_available_frame_if_already_in_incoming_buffer() {
// Store two frames in our data to transmit
let data = {
let mut data = BytesMut::new();
Frame::new(b"hello world").write(&mut data);
Frame::new(b"hello again").write(&mut data);
data.freeze()
};
// Configure transport to return both frames in single read such that we have another
// complete frame to parse (in the case that an underlying try_read would block, but we had
// data available before that)
let mut transport = FramedTransport::new(
TestTransport {
f_try_read: Box::new(move |buf| {
static mut CNT: usize = 0;
unsafe {
CNT += 1;
if CNT == 2 {
Err(io::Error::from(io::ErrorKind::WouldBlock))
} else {
let n = data.len();
buf[..data.len()].copy_from_slice(data.as_ref());
Ok(n)
}
}
}),
f_ready: Box::new(|_| Ok(Ready::READABLE)),
..Default::default()
},
Box::new(OkCodec),
);
// Read first frame
assert_eq!(transport.try_read_frame().unwrap().unwrap(), b"hello world");
// Read second frame
assert_eq!(transport.try_read_frame().unwrap().unwrap(), b"hello again");
}
#[test]
fn try_read_frame_should_keep_reading_until_a_frame_is_found() {
const STEP_SIZE: usize = Frame::HEADER_SIZE + 7;
let mut transport = FramedTransport::new(
TestTransport {
f_try_read: simulate_try_read(
vec![Frame::new(b"hello world"), Frame::new(b"test hello")],
STEP_SIZE,
|_| false,
),
f_ready: Box::new(|_| Ok(Ready::READABLE)),
..Default::default()
},
Box::new(OkCodec),
);
assert_eq!(transport.try_read_frame().unwrap().unwrap(), b"hello world");
// Should have leftover bytes from next frame
// where len = 10, "tes"
assert_eq!(
transport.incoming.to_vec(),
[0, 0, 0, 0, 0, 0, 0, 10, b't', b'e', b's']
);
}
#[test]
fn try_write_frame_should_return_would_block_if_fails_to_write_frame_before_blocking() {
let mut transport = FramedTransport::new(
TestTransport {
f_try_write: Box::new(|_| Err(io::Error::from(io::ErrorKind::WouldBlock))),
f_ready: Box::new(|_| Ok(Ready::WRITABLE)),
..Default::default()
},
Box::new(OkCodec),
);
// First call will only write part of the frame and then return WouldBlock
assert_eq!(
transport
.try_write_frame(b"hello world")
.unwrap_err()
.kind(),
io::ErrorKind::WouldBlock
);
}
#[test]
fn try_write_frame_should_return_error_if_encountered_error_with_writing_bytes() {
let mut transport = FramedTransport::new(
TestTransport {
f_try_write: Box::new(|_| Err(io::Error::from(io::ErrorKind::NotConnected))),
f_ready: Box::new(|_| Ok(Ready::WRITABLE)),
..Default::default()
},
Box::new(OkCodec),
);
assert_eq!(
transport
.try_write_frame(b"hello world")
.unwrap_err()
.kind(),
io::ErrorKind::NotConnected
);
}
#[test]
fn try_write_frame_should_return_error_if_encountered_error_during_encode() {
let mut transport = FramedTransport::new(
TestTransport {
f_try_write: Box::new(|buf| Ok(buf.len())),
f_ready: Box::new(|_| Ok(Ready::WRITABLE)),
..Default::default()
},
Box::new(ErrCodec),
);
assert_eq!(
transport
.try_write_frame(b"hello world")
.unwrap_err()
.kind(),
io::ErrorKind::Other
);
}
#[test]
fn try_write_frame_should_write_entire_frame_if_possible() {
let (tx, rx) = std::sync::mpsc::sync_channel(1);
let mut transport = FramedTransport::new(
TestTransport {
f_try_write: Box::new(move |buf| {
let len = buf.len();
tx.send(buf.to_vec()).unwrap();
Ok(len)
}),
f_ready: Box::new(|_| Ok(Ready::WRITABLE)),
..Default::default()
},
Box::new(OkCodec),
);
transport.try_write_frame(b"hello world").unwrap();
// Transmitted data should be encoded using the framed transport's codec
assert_eq!(
rx.try_recv().unwrap(),
[11u64.to_be_bytes().as_slice(), b"hello world".as_slice()].concat()
);
}
#[test]
fn try_write_frame_should_write_any_prior_queued_bytes_before_writing_next_frame() {
const STEP_SIZE: usize = Frame::HEADER_SIZE + 5;
let (tx, rx) = std::sync::mpsc::sync_channel(10);
let mut transport = FramedTransport::new(
TestTransport {
f_try_write: Box::new(move |buf| {
static mut CNT: usize = 0;
unsafe {
CNT += 1;
if CNT == 2 {
Err(io::Error::from(io::ErrorKind::WouldBlock))
} else {
let len = std::cmp::min(STEP_SIZE, buf.len());
tx.send(buf[..len].to_vec()).unwrap();
Ok(len)
}
}
}),
f_ready: Box::new(|_| Ok(Ready::WRITABLE)),
..Default::default()
},
Box::new(OkCodec),
);
// First call will only write part of the frame and then return WouldBlock
assert_eq!(
transport
.try_write_frame(b"hello world")
.unwrap_err()
.kind(),
io::ErrorKind::WouldBlock
);
// Transmitted data should be encoded using the framed transport's codec
assert_eq!(
rx.try_recv().unwrap(),
[11u64.to_be_bytes().as_slice(), b"hello".as_slice()].concat()
);
assert_eq!(
rx.try_recv().unwrap_err(),
std::sync::mpsc::TryRecvError::Empty
);
// Next call will keep writing successfully until done
transport.try_write_frame(b"test").unwrap();
assert_eq!(
rx.try_recv().unwrap(),
[b' ', b'w', b'o', b'r', b'l', b'd', 0, 0, 0, 0, 0, 0, 0]
);
assert_eq!(rx.try_recv().unwrap(), [4, b't', b'e', b's', b't']);
assert_eq!(
rx.try_recv().unwrap_err(),
std::sync::mpsc::TryRecvError::Empty
);
}
#[test]
fn try_flush_should_return_error_if_try_write_fails() {
let mut transport = FramedTransport::new(
TestTransport {
f_try_write: Box::new(|_| Err(io::Error::from(io::ErrorKind::NotConnected))),
f_ready: Box::new(|_| Ok(Ready::WRITABLE)),
..Default::default()
},
Box::new(OkCodec),
);
// Set our outgoing buffer to flush
transport.outgoing.put_slice(b"hello world");
// Perform flush and verify error happens
assert_eq!(
transport.try_flush().unwrap_err().kind(),
io::ErrorKind::NotConnected
);
}
#[test]
fn try_flush_should_return_error_if_try_write_returns_0_bytes_written() {
let mut transport = FramedTransport::new(
TestTransport {
f_try_write: Box::new(|_| Ok(0)),
f_ready: Box::new(|_| Ok(Ready::WRITABLE)),
..Default::default()
},
Box::new(OkCodec),
);
// Set our outgoing buffer to flush
transport.outgoing.put_slice(b"hello world");
// Perform flush and verify error happens
assert_eq!(
transport.try_flush().unwrap_err().kind(),
io::ErrorKind::WriteZero
);
}
#[test]
fn try_flush_should_be_noop_if_nothing_to_flush() {
let mut transport = FramedTransport::new(
TestTransport {
f_try_write: Box::new(|_| Err(io::Error::from(io::ErrorKind::NotConnected))),
f_ready: Box::new(|_| Ok(Ready::WRITABLE)),
..Default::default()
},
Box::new(OkCodec),
);
// Perform flush and verify nothing happens
transport.try_flush().unwrap();
}
#[test]
fn try_flush_should_continually_call_try_write_until_outgoing_buffer_is_empty() {
const STEP_SIZE: usize = 5;
let (tx, rx) = std::sync::mpsc::sync_channel(10);
let mut transport = FramedTransport::new(
TestTransport {
f_try_write: Box::new(move |buf| {
let len = std::cmp::min(STEP_SIZE, buf.len());
tx.send(buf[..len].to_vec()).unwrap();
Ok(len)
}),
f_ready: Box::new(|_| Ok(Ready::WRITABLE)),
..Default::default()
},
Box::new(OkCodec),
);
// Set our outgoing buffer to flush
transport.outgoing.put_slice(b"hello world");
// Perform flush
transport.try_flush().unwrap();
// Verify outgoing data flushed with N calls to try_write
assert_eq!(rx.try_recv().unwrap(), b"hello".as_slice());
assert_eq!(rx.try_recv().unwrap(), b" worl".as_slice());
assert_eq!(rx.try_recv().unwrap(), b"d".as_slice());
assert_eq!(
rx.try_recv().unwrap_err(),
std::sync::mpsc::TryRecvError::Empty
);
}
#[inline]
async fn test_synchronize_stats(
transport: &mut FramedTransport<InmemoryTransport>,
sent_cnt: u64,
received_cnt: u64,
available_cnt: u64,
expected_sent_cnt: u64,
expected_received_cnt: u64,
expected_available_cnt: u64,
) {
// From the other side, claim that we have received 2 frames
// (sent, received, available)
transport
.write_frame_for(&(sent_cnt, received_cnt, available_cnt))
.await
.unwrap();
// Receive stats from the other side
let (sent, received, available) = transport
.read_frame_as::<(u64, u64, u64)>()
.await
.unwrap()
.unwrap();
assert_eq!(sent, expected_sent_cnt, "Wrong sent cnt");
assert_eq!(received, expected_received_cnt, "Wrong received cnt");
assert_eq!(available, expected_available_cnt, "Wrong available cnt");
}
#[test(tokio::test)]
async fn synchronize_should_resend_no_frames_if_other_side_claims_it_has_more_than_us() {
let (mut t1, mut t2) = FramedTransport::pair(100);
// Configure the backup such that we have sent one frame
t2.backup.push_frame(Frame::new(b"hello world"));
t2.backup.increment_sent_cnt();
// Spawn a separate task to do synchronization simulation so we don't deadlock, and also
// send a frame to indicate when finished so we can know when synchronization is done
// during our test
let _task = tokio::spawn(async move {
t2.synchronize().await.unwrap();
t2.write_frame(Frame::new(b"done")).await.unwrap();
t2
});
// fake (sent, received, available) = 0, 2, 0
// expected (sent, received, available) = 1, 0, 1
test_synchronize_stats(&mut t1, 0, 2, 0, 1, 0, 1).await;
// Should not receive anything before our done indicator
assert_eq!(t1.read_frame().await.unwrap().unwrap(), b"done");
}
#[test(tokio::test)]
async fn synchronize_should_resend_no_frames_if_none_missing_on_other_side() {
let (mut t1, mut t2) = FramedTransport::pair(100);
// Configure the backup such that we have sent one frame
t2.backup.push_frame(Frame::new(b"hello world"));
t2.backup.increment_sent_cnt();
// Spawn a separate task to do synchronization simulation so we don't deadlock, and also
// send a frame to indicate when finished so we can know when synchronization is done
// during our test
let _task = tokio::spawn(async move {
t2.synchronize().await.unwrap();
t2.write_frame(Frame::new(b"done")).await.unwrap();
t2
});
// fake (sent, received, available) = 0, 1, 0
// expected (sent, received, available) = 1, 0, 1
test_synchronize_stats(&mut t1, 0, 1, 0, 1, 0, 1).await;
// Should not receive anything before our done indicator
assert_eq!(t1.read_frame().await.unwrap().unwrap(), b"done");
}
#[test(tokio::test)]
async fn synchronize_should_resend_some_frames_if_some_missing_on_other_side() {
let (mut t1, mut t2) = FramedTransport::pair(100);
// Configure the backup such that we have sent two frames
t2.backup.push_frame(Frame::new(b"hello"));
t2.backup.push_frame(Frame::new(b"world"));
t2.backup.increment_sent_cnt();
t2.backup.increment_sent_cnt();
// Spawn a separate task to do synchronization simulation so we don't deadlock, and also
// send a frame to indicate when finished so we can know when synchronization is done
// during our test
let _task = tokio::spawn(async move {
t2.synchronize().await.unwrap();
t2.write_frame(Frame::new(b"done")).await.unwrap();
t2
});
// fake (sent, received, available) = 0, 1, 0
// expected (sent, received, available) = 2, 0, 2
test_synchronize_stats(&mut t1, 0, 1, 0, 2, 0, 2).await;
// Recieve both frames and then the done indicator
assert_eq!(t1.read_frame().await.unwrap().unwrap(), b"world");
assert_eq!(t1.read_frame().await.unwrap().unwrap(), b"done");
}
#[test(tokio::test)]
async fn synchronize_should_resend_all_frames_if_all_missing_on_other_side() {
let (mut t1, mut t2) = FramedTransport::pair(100);
// Configure the backup such that we have sent two frames
t2.backup.push_frame(Frame::new(b"hello"));
t2.backup.push_frame(Frame::new(b"world"));
t2.backup.increment_sent_cnt();
t2.backup.increment_sent_cnt();
// Spawn a separate task to do synchronization simulation so we don't deadlock, and also
// send a frame to indicate when finished so we can know when synchronization is done
// during our test
let _task = tokio::spawn(async move {
t2.synchronize().await.unwrap();
t2.write_frame(Frame::new(b"done")).await.unwrap();
t2
});
// fake (sent, received, available) = 0, 0, 0
// expected (sent, received, available) = 2, 0, 2
test_synchronize_stats(&mut t1, 0, 0, 0, 2, 0, 2).await;
// Recieve both frames and then the done indicator
assert_eq!(t1.read_frame().await.unwrap().unwrap(), b"hello");
assert_eq!(t1.read_frame().await.unwrap().unwrap(), b"world");
assert_eq!(t1.read_frame().await.unwrap().unwrap(), b"done");
}
#[test(tokio::test)]
async fn synchronize_should_resend_available_frames_if_more_than_available_missing_on_other_side(
) {
let (mut t1, mut t2) = FramedTransport::pair(100);
// Configure the backup such that we have sent two frames, and believe that we have
// sent 3 in total, a situation that happens once we reach the peak possible size of
// old frames to store
t2.backup.push_frame(Frame::new(b"hello"));
t2.backup.push_frame(Frame::new(b"world"));
t2.backup.increment_sent_cnt();
t2.backup.increment_sent_cnt();
t2.backup.increment_sent_cnt();
// Spawn a separate task to do synchronization simulation so we don't deadlock, and also
// send a frame to indicate when finished so we can know when synchronization is done
// during our test
let _task = tokio::spawn(async move {
t2.synchronize().await.unwrap();
t2.write_frame(Frame::new(b"done")).await.unwrap();
t2
});
// fake (sent, received, available) = 0, 0, 0
// expected (sent, received, available) = 3, 0, 2
test_synchronize_stats(&mut t1, 0, 0, 0, 3, 0, 2).await;
// Recieve both frames and then the done indicator
assert_eq!(t1.read_frame().await.unwrap().unwrap(), b"hello");
assert_eq!(t1.read_frame().await.unwrap().unwrap(), b"world");
assert_eq!(t1.read_frame().await.unwrap().unwrap(), b"done");
}
#[test(tokio::test)]
async fn synchronize_should_receive_no_frames_if_other_side_claims_it_has_more_than_us() {
let (mut t1, mut t2) = FramedTransport::pair(100);
// Mark other side as having received a frame
t2.backup.increment_received_cnt();
// Spawn a separate task to do synchronization simulation so we don't deadlock, and also
// send a frame to indicate when finished so we can know when synchronization is done
// during our test
let _task = tokio::spawn(async move {
t2.synchronize().await.unwrap();
t2.write_frame(Frame::new(b"done")).await.unwrap();
t2
});
// fake (sent, received, available) = 0, 0, 0
// expected (sent, received, available) = 0, 1, 0
test_synchronize_stats(&mut t1, 0, 0, 0, 0, 1, 0).await;
// Recieve the done indicator
assert_eq!(t1.read_frame().await.unwrap().unwrap(), b"done");
}
#[test(tokio::test)]
async fn synchronize_should_receive_no_frames_if_none_missing_from_other_side() {
let (mut t1, mut t2) = FramedTransport::pair(100);
// Mark other side as having received a frame
t2.backup.increment_received_cnt();
// Spawn a separate task to do synchronization simulation so we don't deadlock, and also
// send a frame to indicate when finished so we can know when synchronization is done
// during our test
let _task = tokio::spawn(async move {
t2.synchronize().await.unwrap();
t2.write_frame(Frame::new(b"done")).await.unwrap();
t2
});
// fake (sent, received, available) = 1, 0, 1
// expected (sent, received, available) = 0, 1, 0
test_synchronize_stats(&mut t1, 1, 0, 1, 0, 1, 0).await;
// Recieve the done indicator
assert_eq!(t1.read_frame().await.unwrap().unwrap(), b"done");
}
#[test(tokio::test)]
async fn synchronize_should_receive_some_frames_if_some_missing_from_other_side() {
let (mut t1, mut t2) = FramedTransport::pair(100);
// Mark other side as having received a frame
t2.backup.increment_received_cnt();
// Spawn a separate task to do synchronization simulation so we don't deadlock, and also
// send a frame to indicate when finished so we can know when synchronization is done
// during our test
let task = tokio::spawn(async move {
t2.synchronize().await.unwrap();
t2.write_frame(Frame::new(b"done")).await.unwrap();
t2
});
// fake (sent, received, available) = 2, 0, 2
// expected (sent, received, available) = 0, 1, 0
test_synchronize_stats(&mut t1, 2, 0, 2, 0, 1, 0).await;
// Send a frame to fill the gap
t1.write_frame(Frame::new(b"hello")).await.unwrap();
// Recieve the done indicator
assert_eq!(t1.read_frame().await.unwrap().unwrap(), b"done");
// Drop the transport such that the other side will get a definite termination
drop(t1);
// Verify that the frame was captured on the other side
let mut t2 = task.await.unwrap();
assert_eq!(t2.read_frame().await.unwrap().unwrap(), b"hello");
assert_eq!(t2.read_frame().await.unwrap(), None);
}
#[test(tokio::test)]
async fn synchronize_should_receive_all_frames_if_all_missing_from_other_side() {
let (mut t1, mut t2) = FramedTransport::pair(100);
// Spawn a separate task to do synchronization simulation so we don't deadlock, and also
// send a frame to indicate when finished so we can know when synchronization is done
// during our test
let task = tokio::spawn(async move {
t2.synchronize().await.unwrap();
t2.write_frame(Frame::new(b"done")).await.unwrap();
t2
});
// fake (sent, received, available) = 2, 0, 2
// expected (sent, received, available) = 0, 0, 0
test_synchronize_stats(&mut t1, 2, 0, 2, 0, 0, 0).await;
// Send frames to fill the gap
t1.write_frame(Frame::new(b"hello")).await.unwrap();
t1.write_frame(Frame::new(b"world")).await.unwrap();
// Recieve the done indicator
assert_eq!(t1.read_frame().await.unwrap().unwrap(), b"done");
// Drop the transport such that the other side will get a definite termination
drop(t1);
// Verify that the frame was captured on the other side
let mut t2 = task.await.unwrap();
assert_eq!(t2.read_frame().await.unwrap().unwrap(), b"hello");
assert_eq!(t2.read_frame().await.unwrap().unwrap(), b"world");
assert_eq!(t2.read_frame().await.unwrap(), None);
}
#[test(tokio::test)]
async fn synchronize_should_receive_all_frames_if_more_than_all_missing_from_other_side() {
let (mut t1, mut t2) = FramedTransport::pair(100);
// Spawn a separate task to do synchronization simulation so we don't deadlock, and also
// send a frame to indicate when finished so we can know when synchronization is done
// during our test
let task = tokio::spawn(async move {
t2.synchronize().await.unwrap();
t2.write_frame(Frame::new(b"done")).await.unwrap();
t2
});
// fake (sent, received, available) = 3, 0, 2
// expected (sent, received, available) = 0, 0, 0
test_synchronize_stats(&mut t1, 2, 0, 2, 0, 0, 0).await;
// Send frames to fill the gap
t1.write_frame(Frame::new(b"hello")).await.unwrap();
t1.write_frame(Frame::new(b"world")).await.unwrap();
// Recieve the done indicator
assert_eq!(t1.read_frame().await.unwrap().unwrap(), b"done");
// Drop the transport such that the other side will get a definite termination
drop(t1);
// Verify that the frame was captured on the other side
let mut t2 = task.await.unwrap();
assert_eq!(t2.read_frame().await.unwrap().unwrap(), b"hello");
assert_eq!(t2.read_frame().await.unwrap().unwrap(), b"world");
assert_eq!(t2.read_frame().await.unwrap(), None);
}
#[test(tokio::test)]
async fn synchronize_should_fail_if_connection_terminated_before_receiving_missing_frames() {
let (mut t1, mut t2) = FramedTransport::pair(100);
// Spawn a separate task to do synchronization simulation so we don't deadlock, and also
// send a frame to indicate when finished so we can know when synchronization is done
// during our test
let task = tokio::spawn(async move {
t2.synchronize().await.unwrap();
t2.write_frame(Frame::new(b"done")).await.unwrap();
t2
});
// fake (sent, received, available) = 2, 0, 2
// expected (sent, received, available) = 0, 0, 0
test_synchronize_stats(&mut t1, 2, 0, 2, 0, 0, 0).await;
// Send one frame to fill the gap
t1.write_frame(Frame::new(b"hello")).await.unwrap();
// Drop the transport to cause a failure
drop(t1);
// Verify that the other side's synchronization failed
task.await.unwrap_err();
}
#[test(tokio::test)]
async fn synchronize_should_fail_if_connection_terminated_while_waiting_for_frame_stats() {
let (t1, mut t2) = FramedTransport::pair(100);
// Spawn a separate task to do synchronization simulation so we don't deadlock, and also
// send a frame to indicate when finished so we can know when synchronization is done
// during our test
let task = tokio::spawn(async move {
t2.synchronize().await.unwrap();
t2.write_frame(Frame::new(b"done")).await.unwrap();
t2
});
// Drop the transport to cause a failure
drop(t1);
// Verify that the other side's synchronization failed
task.await.unwrap_err();
}
#[test(tokio::test)]
async fn synchronize_should_clear_any_prexisting_incoming_and_outgoing_data() {
let (mut t1, mut t2) = FramedTransport::pair(100);
// Put some frames into the incoming and outgoing of our transport
Frame::new(b"bad incoming").write(&mut t2.incoming);
Frame::new(b"bad outgoing").write(&mut t2.outgoing);
// Configure the backup such that we have sent two frames
t2.backup.push_frame(Frame::new(b"hello"));
t2.backup.push_frame(Frame::new(b"world"));
t2.backup.increment_sent_cnt();
t2.backup.increment_sent_cnt();
// Spawn a separate task to do synchronization simulation so we don't deadlock, and also
// send a frame to indicate when finished so we can know when synchronization is done
// during our test
let task = tokio::spawn(async move {
t2.synchronize().await.unwrap();
t2.write_frame(Frame::new(b"done")).await.unwrap();
t2
});
// fake (sent, received, available) = 2, 0, 2
// expected (sent, received, available) = 2, 0, 2
test_synchronize_stats(&mut t1, 2, 0, 2, 2, 0, 2).await;
// Send frames to fill the gap
t1.write_frame(Frame::new(b"one")).await.unwrap();
t1.write_frame(Frame::new(b"two")).await.unwrap();
// Recieve both frames and then the done indicator
assert_eq!(t1.read_frame().await.unwrap().unwrap(), b"hello");
assert_eq!(t1.read_frame().await.unwrap().unwrap(), b"world");
assert_eq!(t1.read_frame().await.unwrap().unwrap(), b"done");
// Drop the transport such that the other side will get a definite termination
drop(t1);
// Verify that the frame was captured on the other side
let mut t2 = task.await.unwrap();
assert_eq!(t2.read_frame().await.unwrap().unwrap(), b"one");
assert_eq!(t2.read_frame().await.unwrap().unwrap(), b"two");
assert_eq!(t2.read_frame().await.unwrap(), None);
}
#[test(tokio::test)]
async fn synchronize_should_not_increment_the_sent_frames_or_store_replayed_frames_in_the_backup(
) {
let (mut t1, mut t2) = FramedTransport::pair(100);
// Configure the backup such that we have sent two frames
t2.backup.push_frame(Frame::new(b"hello"));
t2.backup.push_frame(Frame::new(b"world"));
t2.backup.increment_sent_cnt();
t2.backup.increment_sent_cnt();
// Spawn a separate task to do synchronization simulation so we don't deadlock, and also
// send a frame to indicate when finished so we can know when synchronization is done
// during our test
let task = tokio::spawn(async move {
t2.synchronize().await.unwrap();
t2.backup.freeze();
t2.write_frame(Frame::new(b"done")).await.unwrap();
t2.backup.unfreeze();
t2
});
// fake (sent, received, available) = 0, 0, 0
// expected (sent, received, available) = 2, 0, 2
test_synchronize_stats(&mut t1, 0, 0, 0, 2, 0, 2).await;
// Recieve both frames and then the done indicator
assert_eq!(t1.read_frame().await.unwrap().unwrap(), b"hello");
assert_eq!(t1.read_frame().await.unwrap().unwrap(), b"world");
assert_eq!(t1.read_frame().await.unwrap().unwrap(), b"done");
// Drop the transport such that the other side will get a definite termination
drop(t1);
// Verify that the backup on the other side was unaltered by the frames being sent
let t2 = task.await.unwrap();
assert_eq!(t2.backup.sent_cnt(), 2, "Wrong sent cnt");
assert_eq!(t2.backup.received_cnt(), 0, "Wrong received cnt");
assert_eq!(t2.backup.frame_cnt(), 2, "Wrong frame cnt");
}
#[test(tokio::test)]
async fn synchronize_should_update_the_backup_received_cnt_to_match_other_side_sent() {
let (mut t1, mut t2) = FramedTransport::pair(100);
// Spawn a separate task to do synchronization simulation so we don't deadlock, and also
// send a frame to indicate when finished so we can know when synchronization is done
// during our test
let task = tokio::spawn(async move {
t2.synchronize().await.unwrap();
t2.backup.freeze();
t2.write_frame(Frame::new(b"done")).await.unwrap();
t2.backup.unfreeze();
t2
});
// fake (sent, received, available) = 2, 0, 1
// expected (sent, received, available) = 0, 0, 0
test_synchronize_stats(&mut t1, 2, 0, 1, 0, 0, 0).await;
// Send frames to fill the gap
t1.write_frame(Frame::new(b"hello")).await.unwrap();
// Recieve both frames and then the done indicator
assert_eq!(t1.read_frame().await.unwrap().unwrap(), b"done");
// Drop the transport such that the other side will get a definite termination
drop(t1);
// Verify that the backup on the other side updated based on sent count and not available
let t2 = task.await.unwrap();
assert_eq!(t2.backup.sent_cnt(), 0, "Wrong sent cnt");
assert_eq!(t2.backup.received_cnt(), 2, "Wrong received cnt");
assert_eq!(t2.backup.frame_cnt(), 0, "Wrong frame cnt");
}
#[test(tokio::test)]
async fn synchronize_should_work_even_if_codec_changes_between_attempts() {
let (mut t1, _t1_other) = FramedTransport::pair(100);
let (mut t2, _t2_other) = FramedTransport::pair(100);
// Send some frames from each side
t1.write_frame(Frame::new(b"hello")).await.unwrap();
t1.write_frame(Frame::new(b"world")).await.unwrap();
t2.write_frame(Frame::new(b"foo")).await.unwrap();
t2.write_frame(Frame::new(b"bar")).await.unwrap();
// Drop the other transports, link our real transports together, and change the codec
drop(_t1_other);
drop(_t2_other);
t1.link(&mut t2, 100);
let codec = EncryptionCodec::new_xchacha20poly1305(Default::default());
t1.codec = Box::new(codec.clone());
t2.codec = Box::new(codec);
// Spawn a separate task to do synchronization so we don't deadlock
let task = tokio::spawn(async move {
t2.synchronize().await.unwrap();
t2
});
t1.synchronize().await.unwrap();
// Verify that we get the appropriate frames from both sides
let mut t2 = task.await.unwrap();
assert_eq!(t1.read_frame().await.unwrap().unwrap(), b"foo");
assert_eq!(t1.read_frame().await.unwrap().unwrap(), b"bar");
assert_eq!(t2.read_frame().await.unwrap().unwrap(), b"hello");
assert_eq!(t2.read_frame().await.unwrap().unwrap(), b"world");
}
#[test(tokio::test)]
async fn handshake_should_configure_transports_with_matching_codec() {
let (mut t1, mut t2) = FramedTransport::test_pair(100);
// NOTE: Spawn a separate task for one of our transports so we can communicate without
// deadlocking
let task = tokio::spawn(async move {
// Wait for handshake to complete
t2.server_handshake().await.unwrap();
// Receive one frame and echo it back
let frame = t2.read_frame().await.unwrap().unwrap();
t2.write_frame(frame).await.unwrap();
});
t1.client_handshake().await.unwrap();
// Verify that the transports can still communicate with one another
t1.write_frame(b"hello world").await.unwrap();
assert_eq!(t1.read_frame().await.unwrap().unwrap(), b"hello world");
// Ensure that the other transport did not error
task.await.unwrap();
}
#[test(tokio::test)]
async fn handshake_failing_should_ensure_existing_codec_remains() {
let (mut t1, t2) = FramedTransport::test_pair(100);
// Set a different codec on our transport so we can verify it doesn't change
t1.set_codec(Box::new(CustomCodec));
// Drop our transport on the other side to cause an immediate failure
drop(t2);
// Ensure we detect the failure on handshake
t1.client_handshake().await.unwrap_err();
// Verify that the codec did not reset to plain text by using the codec
assert_eq!(t1.codec.encode(Frame::new(b"test")).unwrap(), b"encode");
assert_eq!(t1.codec.decode(Frame::new(b"test")).unwrap(), b"decode");
}
#[test(tokio::test)]
async fn handshake_should_clear_any_intermittent_buffer_contents_prior_to_handshake_failing() {
let (mut t1, t2) = FramedTransport::test_pair(100);
// Set a different codec on our transport so we can verify it doesn't change
t1.set_codec(Box::new(CustomCodec));
// Drop our transport on the other side to cause an immediate failure
drop(t2);
// Put some garbage in our buffers
t1.incoming.extend_from_slice(b"garbage in");
t1.outgoing.extend_from_slice(b"garbage out");
// Ensure we detect the failure on handshake
t1.client_handshake().await.unwrap_err();
// Verify that the incoming and outgoing buffers are empty
assert!(t1.incoming.is_empty());
assert!(t1.outgoing.is_empty());
}
#[test(tokio::test)]
async fn handshake_should_clear_any_intermittent_buffer_contents_prior_to_handshake_succeeding()
{
let (mut t1, mut t2) = FramedTransport::test_pair(100);
// NOTE: Spawn a separate task for one of our transports so we can communicate without
// deadlocking
let task = tokio::spawn(async move {
// Wait for handshake to complete
t2.server_handshake().await.unwrap();
// Receive one frame and echo it back
let frame = t2.read_frame().await.unwrap().unwrap();
t2.write_frame(frame).await.unwrap();
});
// Put some garbage in our buffers
t1.incoming.extend_from_slice(b"garbage in");
t1.outgoing.extend_from_slice(b"garbage out");
t1.client_handshake().await.unwrap();
// Verify that the transports can still communicate with one another
t1.write_frame(b"hello world").await.unwrap();
assert_eq!(t1.read_frame().await.unwrap().unwrap(), b"hello world");
// Ensure that the other transport did not error
task.await.unwrap();
// Verify that the incoming and outgoing buffers are empty
assert!(t1.incoming.is_empty());
assert!(t1.outgoing.is_empty());
}
#[test(tokio::test)]
async fn handshake_for_client_should_fail_if_receives_unexpected_frame_instead_of_options() {
let (mut t1, mut t2) = FramedTransport::test_pair(100);
// NOTE: Spawn a separate task for one of our transports so we can communicate without
// deadlocking
let task = tokio::spawn(async move {
t2.write_frame(b"not a valid frame for handshake")
.await
.unwrap();
});
// Ensure we detect the failure on handshake
let err = t1.client_handshake().await.unwrap_err();
assert_eq!(err.kind(), io::ErrorKind::InvalidData);
// Ensure that the other transport did not error
task.await.unwrap();
}
#[test(tokio::test)]
async fn handshake_for_client_should_fail_unable_to_send_codec_choice_to_other_side() {
let (mut t1, mut t2) = FramedTransport::test_pair(100);
#[derive(Debug, Serialize, Deserialize)]
struct Options {
compression_types: Vec<CompressionType>,
encryption_types: Vec<EncryptionType>,
}
// NOTE: Spawn a separate task for one of our transports so we can communicate without
// deadlocking
let task = tokio::spawn(async move {
// Send options, and then quit so the client side will fail
t2.write_frame_for(&Options {
compression_types: Vec::new(),
encryption_types: Vec::new(),
})
.await
.unwrap();
});
// Ensure we detect the failure on handshake
let err = t1.client_handshake().await.unwrap_err();
assert_eq!(err.kind(), io::ErrorKind::WriteZero);
// Ensure that the other transport did not error
task.await.unwrap();
}
#[test(tokio::test)]
async fn handshake_for_client_should_fail_if_unable_to_receive_key_exchange_data_from_other_side(
) {
#[derive(Debug, Serialize, Deserialize)]
struct Options {
compression_types: Vec<CompressionType>,
encryption_types: Vec<EncryptionType>,
}
let (mut t1, mut t2) = FramedTransport::test_pair(100);
// Go ahead and queue up a choice, and then queue up invalid key exchange data
t2.write_frame_for(&Options {
compression_types: CompressionType::known_variants().to_vec(),
encryption_types: EncryptionType::known_variants().to_vec(),
})
.await
.unwrap();
t2.write_frame(b"not valid key exchange data")
.await
.unwrap();
// Ensure we detect the failure on handshake
let err = t1.client_handshake().await.unwrap_err();
assert_eq!(err.kind(), io::ErrorKind::InvalidData);
}
#[test(tokio::test)]
async fn handshake_for_server_should_fail_if_receives_unexpected_frame_instead_of_choice() {
let (mut t1, mut t2) = FramedTransport::test_pair(100);
// NOTE: Spawn a separate task for one of our transports so we can communicate without
// deadlocking
let task = tokio::spawn(async move {
t2.write_frame(b"not a valid frame for handshake")
.await
.unwrap();
});
// Ensure we detect the failure on handshake
let err = t1.server_handshake().await.unwrap_err();
assert_eq!(err.kind(), io::ErrorKind::InvalidData);
// Ensure that the other transport did not error
task.await.unwrap();
}
#[test(tokio::test)]
async fn handshake_for_server_should_fail_unable_to_send_codec_options_to_other_side() {
let (mut t1, t2) = FramedTransport::test_pair(100);
// Drop our other transport to ensure that nothing can be sent to it
drop(t2);
// Ensure we detect the failure on handshake
let err = t1.server_handshake().await.unwrap_err();
assert_eq!(err.kind(), io::ErrorKind::WriteZero);
}
#[test(tokio::test)]
async fn handshake_for_server_should_fail_if_selected_codec_choice_uses_an_unknown_compression_type(
) {
#[derive(Debug, Serialize, Deserialize)]
struct Choice {
compression_level: Option<CompressionLevel>,
compression_type: Option<CompressionType>,
encryption_type: Option<EncryptionType>,
}
let (mut t1, mut t2) = FramedTransport::test_pair(100);
// Go ahead and queue up an improper response
t2.write_frame_for(&Choice {
compression_level: None,
compression_type: Some(CompressionType::Unknown),
encryption_type: None,
})
.await
.unwrap();
// Ensure we detect the failure on handshake
let err = t1.server_handshake().await.unwrap_err();
assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
}
#[test(tokio::test)]
async fn handshake_for_server_should_fail_if_selected_codec_choice_uses_an_unknown_encryption_type(
) {
#[derive(Debug, Serialize, Deserialize)]
struct Choice {
compression_level: Option<CompressionLevel>,
compression_type: Option<CompressionType>,
encryption_type: Option<EncryptionType>,
}
let (mut t1, mut t2) = FramedTransport::test_pair(100);
// Go ahead and queue up an improper response
t2.write_frame_for(&Choice {
compression_level: None,
compression_type: None,
encryption_type: Some(EncryptionType::Unknown),
})
.await
.unwrap();
// Ensure we detect the failure on handshake
let err = t1.server_handshake().await.unwrap_err();
assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
}
#[test(tokio::test)]
async fn handshake_for_server_should_fail_if_unable_to_receive_key_exchange_data_from_other_side(
) {
#[derive(Debug, Serialize, Deserialize)]
struct Choice {
compression_level: Option<CompressionLevel>,
compression_type: Option<CompressionType>,
encryption_type: Option<EncryptionType>,
}
let (mut t1, mut t2) = FramedTransport::test_pair(100);
// Go ahead and queue up a choice, and then queue up invalid key exchange data
t2.write_frame_for(&Choice {
compression_level: None,
compression_type: None,
encryption_type: Some(EncryptionType::XChaCha20Poly1305),
})
.await
.unwrap();
t2.write_frame(b"not valid key exchange data")
.await
.unwrap();
// Ensure we detect the failure on handshake
let err = t1.server_handshake().await.unwrap_err();
assert_eq!(err.kind(), io::ErrorKind::InvalidData);
}
#[test(tokio::test)]
async fn exchange_keys_should_fail_if_unable_to_send_exchange_data_to_other_side() {
let (mut t1, t2) = FramedTransport::test_pair(100);
// Drop the other side to ensure that the exchange fails at the beginning
drop(t2);
// Perform key exchange and verify error is as expected
assert_eq!(
t1.exchange_keys().await.unwrap_err().kind(),
io::ErrorKind::WriteZero
);
}
#[test(tokio::test)]
async fn exchange_keys_should_fail_if_received_invalid_exchange_data() {
let (mut t1, mut t2) = FramedTransport::test_pair(100);
// Queue up an invalid exchange response
t2.write_frame(b"some invalid frame").await.unwrap();
// Perform key exchange and verify error is as expected
assert_eq!(
t1.exchange_keys().await.unwrap_err().kind(),
io::ErrorKind::InvalidData
);
}
#[test(tokio::test)]
async fn exchange_keys_should_return_shared_secret_key_if_successful() {
let (mut t1, mut t2) = FramedTransport::test_pair(100);
// Spawn a task to avoid deadlocking
let task = tokio::spawn(async move { t2.exchange_keys().await.unwrap() });
// Perform key exchange
let key = t1.exchange_keys().await.unwrap();
// Validate that the keys on both sides match
assert_eq!(key, task.await.unwrap());
}
}