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
mod builder;
mod frozen;
mod request_generator;
mod room_list_entry;
mod sticky;
use std::{
collections::HashSet,
fmt::Debug,
iter,
ops::RangeInclusive,
sync::{Arc, RwLock as StdRwLock},
};
use eyeball::{Observable, Subscriber};
use eyeball_im::{ObservableVector, ObservableVectorTransaction, VectorDiff};
use futures_core::Stream;
use imbl::Vector;
use ruma::{api::client::sync::sync_events::v4, assign, OwnedRoomId, TransactionId};
use serde::{Deserialize, Serialize};
use tokio::sync::broadcast::Sender;
use tracing::{instrument, warn};
use self::sticky::SlidingSyncListStickyParameters;
pub use self::{builder::*, room_list_entry::RoomListEntry};
pub(super) use self::{frozen::FrozenSlidingSyncList, request_generator::*};
use super::{
sticky_parameters::{LazyTransactionId, SlidingSyncStickyManager},
Error, SlidingSyncInternalMessage,
};
use crate::Result;
/// Should this [`SlidingSyncList`] be stored in the cache, and automatically
/// reloaded from the cache upon creation?
#[derive(Clone, Copy, Debug)]
pub(crate) enum SlidingSyncListCachePolicy {
/// Store and load this list from the cache.
Enabled,
/// Don't store and load this list from the cache.
Disabled,
}
/// The type used to express natural bounds (including but not limited to:
/// ranges, timeline limit) in the Sliding Sync.
pub type Bound = u32;
/// One range of rooms in a response from Sliding Sync.
pub type Range = RangeInclusive<Bound>;
/// Many ranges of rooms.
pub type Ranges = Vec<Range>;
/// Holding a specific filtered list within the concept of sliding sync.
///
/// It is OK to clone this type as much as you need: cloning it is cheap.
#[derive(Clone, Debug)]
pub struct SlidingSyncList {
inner: Arc<SlidingSyncListInner>,
}
impl SlidingSyncList {
/// Create a new [`SlidingSyncListBuilder`] with the given name.
pub fn builder(name: impl Into<String>) -> SlidingSyncListBuilder {
SlidingSyncListBuilder::new(name)
}
/// Get the name of the list.
pub fn name(&self) -> &str {
self.inner.name.as_str()
}
/// Change the sync-mode.
///
/// It is sometimes necessary to change the sync-mode of a list on-the-fly.
///
/// This will change the sync-mode but also the request generator. A new
/// request generator is generated. Since requests are calculated based on
/// the request generator, changing the sync-mode is equivalent to
/// “resetting” the list. It's actually not calling `Self::reset`, which
/// means that the state is not reset **purposely**. The ranges and the
/// state will be updated when the next request will be sent and a
/// response will be received. The maximum number of rooms won't change.
pub fn set_sync_mode<M>(&self, sync_mode: M)
where
M: Into<SlidingSyncMode>,
{
self.inner.set_sync_mode(sync_mode.into());
// When the sync mode is changed, the sync loop must skip over any work in its
// iteration and jump to the next iteration.
self.inner.internal_channel_send_if_possible(
SlidingSyncInternalMessage::SyncLoopSkipOverCurrentIteration,
);
}
/// Get the current state.
pub fn state(&self) -> SlidingSyncListLoadingState {
self.inner.state.read().unwrap().clone()
}
/// Get a stream of state updates.
///
/// If this list has been reloaded from a cache, the initial value read from
/// the cache will be published.
///
/// There's no guarantee of ordering between items emitted by this stream
/// and those emitted by other streams exposed on this structure.
///
/// The first part of the returned tuple is the actual loading state, and
/// the second part is the `Stream` to receive updates.
pub fn state_stream(
&self,
) -> (SlidingSyncListLoadingState, impl Stream<Item = SlidingSyncListLoadingState>) {
let read_lock = self.inner.state.read().unwrap();
let previous_value = (*read_lock).clone();
let subscriber = Observable::subscribe(&read_lock);
(previous_value, subscriber)
}
/// Get the timeline limit.
pub fn timeline_limit(&self) -> Option<Bound> {
self.inner.sticky.read().unwrap().data().timeline_limit()
}
/// Set timeline limit.
pub fn set_timeline_limit(&self, timeline: Option<Bound>) {
self.inner.sticky.write().unwrap().data_mut().set_timeline_limit(timeline);
}
/// Get the current room list.
pub fn room_list<R>(&self) -> Vec<R>
where
R: for<'a> From<&'a RoomListEntry>,
{
self.inner.room_list.read().unwrap().iter().map(|e| R::from(e)).collect()
}
/// Get a stream of room list.
///
/// If this list has been reloaded from a cache, the initial value read from
/// the cache will be published.
///
/// There's no guarantee of ordering between items emitted by this stream
/// and those emitted by other streams exposed on this structure.
///
/// The first part of the returned tuple is the actual room list entries,
/// and the second part is the `Stream` to receive updates on the room list
/// entries.
pub fn room_list_stream(
&self,
) -> (Vector<RoomListEntry>, impl Stream<Item = Vec<VectorDiff<RoomListEntry>>>) {
let read_lock = self.inner.room_list.read().unwrap();
let values = (*read_lock).clone();
let subscriber = ObservableVector::subscribe(&read_lock);
(values, subscriber.into_batched_stream())
}
/// Get the maximum number of rooms. See [`Self::maximum_number_of_rooms`]
/// to learn more.
pub fn maximum_number_of_rooms(&self) -> Option<u32> {
**self.inner.maximum_number_of_rooms.read().unwrap()
}
/// Get a stream of rooms count.
///
/// If this list has been reloaded from a cache, the initial value is
/// published too.
///
/// There's no guarantee of ordering between items emitted by this stream
/// and those emitted by other streams exposed on this structure.
pub fn maximum_number_of_rooms_stream(&self) -> Subscriber<Option<u32>> {
Observable::subscribe(&self.inner.maximum_number_of_rooms.read().unwrap())
}
/// Return the `room_id` at the given index.
pub fn get_room_id(&self, index: usize) -> Option<OwnedRoomId> {
self.inner
.room_list
.read()
.unwrap()
.get(index)
.and_then(|room_list_entry| room_list_entry.as_room_id().map(ToOwned::to_owned))
}
/// Calculate the next request and return it.
///
/// The next request is entirely calculated based on the request generator
/// ([`SlidingSyncListRequestGenerator`]).
pub(super) fn next_request(
&self,
txn_id: &mut LazyTransactionId,
) -> Result<v4::SyncRequestList, Error> {
self.inner.next_request(txn_id)
}
/// Returns the current cache policy for this list.
pub(super) fn cache_policy(&self) -> SlidingSyncListCachePolicy {
self.inner.cache_policy
}
/// Update the list based on the server's response.
///
/// # Parameters
///
/// - `maximum_number_of_rooms`: the `lists.$this_list.count` value, i.e.
/// maximum number of available rooms in this list, as defined by the
/// server.
/// - `list_sync_operations` is the `list.$this_list.ops` value received
/// from the server for this specific list. It consists of operations to
/// “move” rooms' positions.
/// - `rooms_that_have_received_an_update` is the `rooms` value received
/// from the server, which represents aggregated rooms that have received
/// an update. Maybe their position has changed, maybe they have received
/// a new event in their timeline, maybe their `RoomInfo` has been
/// updated. We need this information to update the `room_list` even if
/// the position of the room hasn't be modified: it helps the user to know
/// that a room has received an update.
#[instrument(skip(self, list_sync_operations), fields(name = self.name(), list_sync_operations_count = list_sync_operations.len()))]
pub(super) fn update(
&mut self,
maximum_number_of_rooms: Option<u32>,
list_sync_operations: &[v4::SyncOp],
rooms_that_have_received_an_update: &[OwnedRoomId],
) -> Result<bool, Error> {
// Make sure to update the generator state first; ordering matters because
// `update_room_list` observes the latest ranges in the response.
if let Some(maximum_number_of_rooms) = maximum_number_of_rooms {
self.inner.update_request_generator_state(maximum_number_of_rooms)?;
}
let new_changes = self.inner.update_room_list(
maximum_number_of_rooms,
list_sync_operations,
rooms_that_have_received_an_update,
)?;
Ok(new_changes)
}
/// Commit the set of sticky parameters for this list.
pub fn maybe_commit_sticky(&mut self, txn_id: &TransactionId) {
self.inner.sticky.write().unwrap().maybe_commit(txn_id);
}
/// Manually invalidate the sticky data, so the sticky parameters are
/// re-sent next time.
pub fn invalidate_sticky_data(&self) {
let _ = self.inner.sticky.write().unwrap().data_mut();
}
}
#[cfg(any(test, feature = "testing"))]
#[allow(dead_code)]
impl SlidingSyncList {
/// Set the maximum number of rooms.
pub(super) fn set_maximum_number_of_rooms(&self, maximum_number_of_rooms: Option<u32>) {
Observable::set(
&mut self.inner.maximum_number_of_rooms.write().unwrap(),
maximum_number_of_rooms,
);
}
/// Get the sync-mode.
pub fn sync_mode(&self) -> SlidingSyncMode {
self.inner.sync_mode.read().unwrap().clone()
}
/// Sets some rooms in the filled state.
pub fn set_filled_rooms(&self, rooms: Vec<OwnedRoomId>) {
let mut room_list = self.inner.room_list.write().unwrap();
room_list.append(rooms.into_iter().map(RoomListEntry::Filled).collect());
}
}
#[derive(Debug)]
pub(super) struct SlidingSyncListInner {
/// Name of this list to easily recognize them.
name: String,
/// The state this list is in.
state: StdRwLock<Observable<SlidingSyncListLoadingState>>,
/// Parameters that are sticky, and can be sent only once per session (until
/// the connection is dropped or the server invalidates what the client
/// knows).
sticky: StdRwLock<SlidingSyncStickyManager<SlidingSyncListStickyParameters>>,
/// The total number of rooms that is possible to interact with for the
/// given list.
///
/// It's not the total rooms that have been fetched. The server tells the
/// client that it's possible to fetch this amount of rooms maximum.
/// Since this number can change according to the list filters, it's
/// observable.
maximum_number_of_rooms: StdRwLock<Observable<Option<u32>>>,
/// The rooms in order.
room_list: StdRwLock<ObservableVector<RoomListEntry>>,
/// The request generator, i.e. a type that yields the appropriate list
/// request. See [`SlidingSyncListRequestGenerator`] to learn more.
request_generator: StdRwLock<SlidingSyncListRequestGenerator>,
/// Cache policy for this list.
cache_policy: SlidingSyncListCachePolicy,
/// The Sliding Sync internal channel sender. See
/// [`SlidingSyncInner::internal_channel`] to learn more.
sliding_sync_internal_channel_sender: Sender<SlidingSyncInternalMessage>,
#[cfg(any(test, feature = "testing"))]
sync_mode: StdRwLock<SlidingSyncMode>,
}
impl SlidingSyncListInner {
/// Change the sync-mode.
///
/// This will change the sync-mode but also the request generator.
///
/// The [`Self::state`] is immediately updated to reflect the new state. The
/// [`Self::maximum_number_of_rooms`] won't change.
pub fn set_sync_mode(&self, sync_mode: SlidingSyncMode) {
#[cfg(any(test, feature = "testing"))]
{
*self.sync_mode.write().unwrap() = sync_mode.clone();
}
{
let mut request_generator = self.request_generator.write().unwrap();
*request_generator = SlidingSyncListRequestGenerator::new(sync_mode);
}
{
let mut state = self.state.write().unwrap();
let next_state = match **state {
SlidingSyncListLoadingState::NotLoaded => SlidingSyncListLoadingState::NotLoaded,
SlidingSyncListLoadingState::Preloaded => SlidingSyncListLoadingState::Preloaded,
SlidingSyncListLoadingState::PartiallyLoaded
| SlidingSyncListLoadingState::FullyLoaded => {
SlidingSyncListLoadingState::PartiallyLoaded
}
};
Observable::set(&mut state, next_state);
}
}
/// Update the state to the next request, and return it.
fn next_request(&self, txn_id: &mut LazyTransactionId) -> Result<v4::SyncRequestList, Error> {
let ranges = {
// Use a dedicated scope to ensure the lock is released before continuing.
let mut request_generator = self.request_generator.write().unwrap();
request_generator
.generate_next_ranges(**self.maximum_number_of_rooms.read().unwrap())?
};
// Here we go.
Ok(self.request(ranges, txn_id))
}
/// Build a [`SyncRequestList`][v4::SyncRequestList] based on the current
/// state of the request generator.
#[instrument(skip(self), fields(name = self.name))]
fn request(&self, ranges: Ranges, txn_id: &mut LazyTransactionId) -> v4::SyncRequestList {
use ruma::UInt;
let ranges =
ranges.into_iter().map(|r| (UInt::from(*r.start()), UInt::from(*r.end()))).collect();
let mut request = assign!(v4::SyncRequestList::default(), { ranges });
{
let mut sticky = self.sticky.write().unwrap();
sticky.maybe_apply(&mut request, txn_id);
}
request
}
/// Update the [`Self::room_list`]. It also updates
/// `[Self::maximum_number_of_rooms]`.
///
/// The `maximum_number_of_rooms` is the `lists.$this_list.count` value,
/// i.e. maximum number of available rooms as defined by the server. The
/// `list_sync_operations` is the `list.$this_list.ops` value
/// received from the server for this specific list. It consists of
/// operations to “move” rooms' positions. Finally,
/// the `rooms_that_have_received_an_update` is the `rooms` value received
/// from the server, which represents aggregated rooms that have received an
/// update. Maybe their position has changed, maybe they have received a new
/// event in their timeline. We need this information to update the
/// `room_list` even if the position of the room hasn't be modified: it
/// helps the user to know that a room has received an update.
fn update_room_list(
&self,
maximum_number_of_rooms: Option<u32>,
list_sync_operations: &[v4::SyncOp],
rooms_that_have_received_an_update: &[OwnedRoomId],
) -> Result<bool, Error> {
let mut new_changes = false;
if let Some(maximum_number_of_rooms) = maximum_number_of_rooms {
// Adjust room list entries.
{
let number_of_missing_rooms = (maximum_number_of_rooms as usize)
.saturating_sub(self.room_list.read().unwrap().len());
if number_of_missing_rooms > 0 {
self.room_list.write().unwrap().append(
iter::repeat(RoomListEntry::Empty).take(number_of_missing_rooms).collect(),
);
new_changes = true;
}
}
// Update the `maximum_number_of_rooms` if it has changed.
{
let mut maximum_number_of_rooms_lock =
self.maximum_number_of_rooms.write().unwrap();
if Observable::get(&maximum_number_of_rooms_lock) != &Some(maximum_number_of_rooms)
{
Observable::set(
&mut maximum_number_of_rooms_lock,
Some(maximum_number_of_rooms),
);
new_changes = true;
}
}
}
{
let mut room_list = self.room_list.write().unwrap();
let mut room_list_txn = room_list.transaction();
// Run the sync operations.
let mut rooms_that_have_received_an_update =
HashSet::from_iter(rooms_that_have_received_an_update.iter().cloned());
if !list_sync_operations.is_empty() {
apply_sync_operations(
list_sync_operations,
&mut room_list_txn,
&mut rooms_that_have_received_an_update,
)?;
new_changes = true;
}
// Finally, some rooms have received an update, but their position
// didn't change in the `room_list`, so no “diff” has
// been triggered. The `room_list` value is used by the
// user to know if a room has received an update: be either a
// position modification or an update in general (like a new room
// message). Let's trigger those.
let mut rooms_to_update = Vec::with_capacity(rooms_that_have_received_an_update.len());
for (position, room_list_entry) in room_list_txn.iter().enumerate() {
// Invalidated rooms must be considered as empty rooms, so let's just filter by
// filled rooms.
if let RoomListEntry::Filled(room_id) = room_list_entry {
// Some room has received an update but it wasn't caused by a
// sync operation. Force an update for observers.
if rooms_that_have_received_an_update.contains(room_id) {
rooms_to_update.push((position, room_list_entry.clone()));
}
}
}
if !rooms_to_update.is_empty() {
for (position, room_list_entry) in rooms_to_update {
// Setting to `room_list`'s item to the same value, just
// to generate an “diff update”.
room_list_txn.set(position, room_list_entry);
}
new_changes = true;
}
room_list_txn.commit();
}
Ok(new_changes)
}
/// Update the state of the [`SlidingSyncListRequestGenerator`] after
/// receiving a response.
fn update_request_generator_state(&self, maximum_number_of_rooms: u32) -> Result<(), Error> {
let mut request_generator = self.request_generator.write().unwrap();
let new_state = request_generator.handle_response(&self.name, maximum_number_of_rooms)?;
Observable::set_if_not_eq(&mut self.state.write().unwrap(), new_state);
Ok(())
}
/// Send a message over the internal channel if there is a receiver, i.e. if
/// the sync loop is running.
#[instrument]
fn internal_channel_send_if_possible(&self, message: SlidingSyncInternalMessage) {
// If there is no receiver, the send will fail, but that's OK here.
let _ = self.sliding_sync_internal_channel_sender.send(message);
}
}
fn apply_sync_operations(
operations: &[v4::SyncOp],
room_list_txn: &mut ObservableVectorTransaction<'_, RoomListEntry>,
rooms_that_have_received_an_update: &mut HashSet<OwnedRoomId>,
) -> Result<(), Error> {
for operation in operations {
match &operation.op {
// Specification says:
//
// > Sets a range of entries. Clients SHOULD discard what they previous
// > knew about entries in this range.
v4::SlidingOp::Sync => {
// Extract `start` and `end` from the operation's range.
let (start, end) = operation
.range
.ok_or_else(|| {
Error::BadResponse(
"`range` must be present for `SYNC` operation".to_owned(),
)
})
.map(|(start, end)| {
(
usize::try_from(start).unwrap(),
usize::try_from(end).unwrap().saturating_add(1),
)
})?;
// Range is invalid.
if start > end {
return Err(Error::BadResponse(format!(
"`range` bounds are invalid ({} > {})",
start, end,
)));
}
// Range is too big.
if end > room_list_txn.len() {
return Err(Error::BadResponse(format!(
"`range` is out of the `rooms_list`'s bounds ({} > {})",
end,
room_list_txn.len(),
)));
}
let room_entry_range = start..end;
// `room_ids` is absent.
if operation.room_ids.is_empty() {
return Err(Error::BadResponse(
"`room_ids` must be present for `SYNC` operation".to_owned(),
));
}
let room_ids = operation.room_ids.iter();
// Mismatch between the `range` and `room_ids`.
if room_entry_range.len() != room_ids.len() {
return Err(Error::BadResponse(
format!(
"There is a mismatch between the number of items in `range` and `room_ids` ({} != {})",
room_entry_range.len(),
room_ids.len(),
)
));
}
// Update parts `room_list`.
//
// The room entry index is given by the `room_entry_range` bounds.
// The room ID is given by the `room_ids`.
for (room_entry_index, room_id) in room_entry_range.zip(room_ids) {
// Syncing means updating the room list to `Filled`.
room_list_txn.set(room_entry_index, RoomListEntry::Filled(room_id.clone()));
// This `room_id` has been handled, let's remove it from the rooms to handle
// later.
rooms_that_have_received_an_update.remove(room_id);
}
}
// Specification says:
//
// > Remove a single entry. Often comes before an INSERT to allow entries
// > to move places.
v4::SlidingOp::Delete => {
let index = operation
.index
.ok_or_else(|| {
Error::BadResponse(
"`index` must be present for `DELETE` operation".to_owned(),
)
})?
.try_into()
.unwrap();
// Index is out of bounds.
if index >= room_list_txn.len() {
// OK, so, normally, we should raise an error. But the server sometimes sends a
// `DELETE` for an index that doesn't exist. It happens with the existing
// Sliding Sync Proxy (at the time of writing). It may be a bug or something
// else. Anyway, it's better to consider an out-of-bounds `DELETE` as a no-op.
continue;
}
// Removing the entry in the room list.
let room_entry = room_list_txn.remove(index);
// This `room_id` has been handled, let's remove it from the rooms to handle
// later.
if let Some(room_id) = room_entry.as_room_id() {
rooms_that_have_received_an_update.remove(room_id);
}
}
// Specification says:
//
// > Sets a single entry. If the position is not empty then clients MUST
// > move entries to the left or the right depending on where the closest
// > empty space is.
v4::SlidingOp::Insert => {
let index: usize = operation
.index
.ok_or_else(|| {
Error::BadResponse(
"`index` must be present for `INSERT` operation".to_owned(),
)
})?
.try_into()
.unwrap();
let room_id = operation.room_id.clone().ok_or_else(|| {
Error::BadResponse(
"`room_id` must be present for `INSERT` operation".to_owned(),
)
})?;
// Index is out of bounds.
if index > room_list_txn.len() {
return Err(Error::BadResponse(format!(
"`index` is out of the `room_list`' bounds ({} > {})",
index,
room_list_txn.len(),
)));
}
// This `room_id` is being handled, let's remove it from the rooms to handle
// later.
rooms_that_have_received_an_update.remove(&room_id);
// Inserting a `Filled` entry in the room list .
room_list_txn.insert(index, RoomListEntry::Filled(room_id));
}
// Specification says:
//
// > Remove a range of entries. Clients MAY persist the invalidated
// > range for offline support, but they should be treated as empty
// > when additional operations which concern indexes in the range
// > arrive from the server.
v4::SlidingOp::Invalidate => {
// Extract `start` and `end` from the operation's range.
let (start, end) = operation
.range
.ok_or_else(|| {
Error::BadResponse(
"`range` must be present for `INVALIDATE` operation".to_owned(),
)
})
.map(|(start, end)| {
(
usize::try_from(start).unwrap(),
usize::try_from(end).unwrap().saturating_add(1),
)
})?;
// Range is invalid.
if start > end {
return Err(Error::BadResponse(format!(
"`range` bounds are invalid ({} > {})",
start, end,
)));
}
// Range is too big.
if end > room_list_txn.len() {
return Err(Error::BadResponse(format!(
"`range` is out of the `room_list`' bounds ({} > {})",
end,
room_list_txn.len(),
)));
}
let room_entry_range = start..end;
// Invalidate parts of `room_list`.
//
// The room entry index is given by the `room_entry_range` bounds.
for room_entry_index in room_entry_range {
// Invalidating means updating the room list to `Invalidate`.
//
// If the previous room list entry is `Filled`, it becomes `Invalidated`.
// Otherwise, for `Empty` or `Invalidated`, it stays as is.
match room_list_txn.get(room_entry_index) {
Some(RoomListEntry::Filled(room_id)) => {
// This `room_id` is being handled, let's remove it from the rooms to
// handle later.
rooms_that_have_received_an_update.remove(room_id);
room_list_txn.set(
room_entry_index,
RoomListEntry::Invalidated(room_id.to_owned()),
);
}
Some(RoomListEntry::Invalidated(room_id)) => {
// This `room_id` has been handled, let's remove it from the rooms to
// handle later.
rooms_that_have_received_an_update.remove(room_id);
}
_ => {}
}
}
}
unknown_operation => {
warn!("Unknown operation occurred: {unknown_operation:?}");
}
}
}
Ok(())
}
/// The state the [`SlidingSyncList`] is in.
///
/// The lifetime of a `SlidingSyncList` usually starts at `NotLoaded` or
/// `Preloaded` (if it is restored from a cache). When loading rooms in a list,
/// depending of the [`SlidingSyncMode`], it moves to `PartiallyLoaded` or
/// `FullyLoaded`.
///
/// If the client has been offline for a while, though, the `SlidingSyncList`
/// might return back to `PartiallyLoaded` at any point.
#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum SlidingSyncListLoadingState {
/// Sliding Sync has not started to load anything yet.
#[default]
NotLoaded,
/// Sliding Sync has been preloaded, i.e. restored from a cache for example.
Preloaded,
/// Updates are received from the loaded rooms, and new rooms are being
/// fetched in the background.
PartiallyLoaded,
/// Updates are received for all the loaded rooms, and all rooms have been
/// loaded!
FullyLoaded,
}
/// Builder for a new sliding sync list in selective mode.
///
/// Conveniently allows to add ranges.
#[derive(Clone, Debug, Default)]
pub struct SlidingSyncSelectiveModeBuilder {
ranges: Ranges,
}
impl SlidingSyncSelectiveModeBuilder {
/// Create a new `SlidingSyncSelectiveModeBuilder`.
fn new() -> Self {
Self::default()
}
/// Select a range to fetch.
pub fn add_range(mut self, range: Range) -> Self {
self.ranges.push(range);
self
}
/// Select many ranges to fetch.
pub fn add_ranges(mut self, ranges: Ranges) -> Self {
self.ranges.extend(ranges);
self
}
}
impl From<SlidingSyncSelectiveModeBuilder> for SlidingSyncMode {
fn from(builder: SlidingSyncSelectiveModeBuilder) -> Self {
Self::Selective { ranges: builder.ranges }
}
}
#[derive(Clone, Debug)]
enum WindowedModeBuilderKind {
Paging,
Growing,
}
/// Builder for a new sliding sync list in growing/paging mode.
#[derive(Clone, Debug)]
pub struct SlidingSyncWindowedModeBuilder {
mode: WindowedModeBuilderKind,
batch_size: u32,
maximum_number_of_rooms_to_fetch: Option<u32>,
}
impl SlidingSyncWindowedModeBuilder {
fn new(mode: WindowedModeBuilderKind, batch_size: u32) -> Self {
Self { mode, batch_size, maximum_number_of_rooms_to_fetch: None }
}
/// The maximum number of rooms to fetch.
pub fn maximum_number_of_rooms_to_fetch(mut self, num: u32) -> Self {
self.maximum_number_of_rooms_to_fetch = Some(num);
self
}
}
impl From<SlidingSyncWindowedModeBuilder> for SlidingSyncMode {
fn from(builder: SlidingSyncWindowedModeBuilder) -> Self {
match builder.mode {
WindowedModeBuilderKind::Paging => Self::Paging {
batch_size: builder.batch_size,
maximum_number_of_rooms_to_fetch: builder.maximum_number_of_rooms_to_fetch,
},
WindowedModeBuilderKind::Growing => Self::Growing {
batch_size: builder.batch_size,
maximum_number_of_rooms_to_fetch: builder.maximum_number_of_rooms_to_fetch,
},
}
}
}
/// How a [`SlidingSyncList`] fetches the data.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum SlidingSyncMode {
/// Only sync the specific defined windows/ranges.
Selective {
/// The specific defined ranges.
ranges: Ranges,
},
/// Fully sync all rooms in the background, page by page of `batch_size`,
/// like `0..=19`, `20..=39`, 40..=59` etc. assuming the `batch_size` is 20.
Paging {
/// The batch size.
batch_size: u32,
/// The maximum number of rooms to fetch. `None` to fetch everything
/// possible.
maximum_number_of_rooms_to_fetch: Option<u32>,
},
/// Fully sync all rooms in the background, with a growing window of
/// `batch_size`, like `0..=19`, `0..=39`, `0..=59` etc. assuming the
/// `batch_size` is 20.
Growing {
/// The batch size.
batch_size: u32,
/// The maximum number of rooms to fetch. `None` to fetch everything
/// possible.
maximum_number_of_rooms_to_fetch: Option<u32>,
},
}
impl Default for SlidingSyncMode {
fn default() -> Self {
Self::Selective { ranges: Vec::new() }
}
}
impl SlidingSyncMode {
/// Create a `SlidingSyncMode::Selective`.
pub fn new_selective() -> SlidingSyncSelectiveModeBuilder {
SlidingSyncSelectiveModeBuilder::new()
}
/// Create a `SlidingSyncMode::Paging`.
pub fn new_paging(batch_size: u32) -> SlidingSyncWindowedModeBuilder {
SlidingSyncWindowedModeBuilder::new(WindowedModeBuilderKind::Paging, batch_size)
}
/// Create a `SlidingSyncMode::Growing`.
pub fn new_growing(batch_size: u32) -> SlidingSyncWindowedModeBuilder {
SlidingSyncWindowedModeBuilder::new(WindowedModeBuilderKind::Growing, batch_size)
}
}
#[cfg(test)]
mod tests {
use std::{
cell::Cell,
collections::HashSet,
sync::{Arc, Mutex},
};
use eyeball_im::{ObservableVector, VectorDiff};
use futures_util::StreamExt;
use imbl::vector;
use matrix_sdk_test::async_test;
use ruma::{
api::client::sync::sync_events::v4::{self, SlidingOp},
room_id, uint, OwnedRoomId,
};
use serde_json::json;
use tokio::{
spawn,
sync::{
broadcast::{channel, error::TryRecvError},
mpsc::unbounded_channel,
},
};
use super::{
apply_sync_operations, RoomListEntry, SlidingSyncList, SlidingSyncListLoadingState,
SlidingSyncMode,
};
use crate::sliding_sync::{sticky_parameters::LazyTransactionId, SlidingSyncInternalMessage};
macro_rules! assert_json_roundtrip {
(from $type:ty: $rust_value:expr => $json_value:expr) => {
let json = serde_json::to_value(&$rust_value).unwrap();
assert_eq!(json, $json_value);
let rust: $type = serde_json::from_value(json).unwrap();
assert_eq!(rust, $rust_value);
};
}
#[async_test]
async fn test_sliding_sync_list_selective_mode() {
let (sender, mut receiver) = channel(1);
// Set range on `Selective`.
let list = SlidingSyncList::builder("foo")
.sync_mode(SlidingSyncMode::new_selective().add_range(0..=1).add_range(2..=3))
.build(sender);
{
let mut generator = list.inner.request_generator.write().unwrap();
assert_eq!(generator.requested_ranges(), &[0..=1, 2..=3]);
let ranges = generator.generate_next_ranges(None).unwrap();
assert_eq!(ranges, &[0..=1, 2..=3]);
}
// There shouldn't be any internal request to restart the sync loop yet.
assert!(matches!(receiver.try_recv(), Err(TryRecvError::Empty)));
list.set_sync_mode(SlidingSyncMode::new_selective().add_range(4..=5));
{
let mut generator = list.inner.request_generator.write().unwrap();
assert_eq!(generator.requested_ranges(), &[4..=5]);
let ranges = generator.generate_next_ranges(None).unwrap();
assert_eq!(ranges, &[4..=5]);
}
// Setting the sync mode requests exactly one restart of the sync loop.
assert!(matches!(
receiver.try_recv(),
Ok(SlidingSyncInternalMessage::SyncLoopSkipOverCurrentIteration)
));
assert!(matches!(receiver.try_recv(), Err(TryRecvError::Empty)));
}
#[test]
fn test_sliding_sync_list_timeline_limit() {
let (sender, _receiver) = channel(1);
let list = SlidingSyncList::builder("foo")
.sync_mode(SlidingSyncMode::new_selective().add_range(0..=1))
.timeline_limit(7)
.build(sender);
assert_eq!(list.inner.sticky.read().unwrap().data().timeline_limit(), Some(7));
list.set_timeline_limit(Some(42));
assert_eq!(list.inner.sticky.read().unwrap().data().timeline_limit(), Some(42));
list.set_timeline_limit(None);
assert_eq!(list.inner.sticky.read().unwrap().data().timeline_limit(), None);
}
#[test]
fn test_sliding_sync_get_room_id() {
let (sender, _receiver) = channel(1);
let mut list = SlidingSyncList::builder("foo")
.sync_mode(SlidingSyncMode::new_selective().add_range(0..=1))
.build(sender);
let room0 = room_id!("!room0:bar.org");
let room1 = room_id!("!room1:bar.org");
// Simulate a request.
let _ = list.next_request(&mut LazyTransactionId::new());
// A new response.
let sync0: v4::SyncOp = serde_json::from_value(json!({
"op": SlidingOp::Sync,
"range": [0, 1],
"room_ids": [room0, room1],
}))
.unwrap();
list.update(Some(6), &[sync0], &[]).unwrap();
assert_eq!(list.get_room_id(0), Some(room0.to_owned()));
assert_eq!(list.get_room_id(1), Some(room1.to_owned()));
assert_eq!(list.get_room_id(2), None);
}
macro_rules! assert_ranges {
(
list = $list:ident,
list_state = $first_list_state:ident,
maximum_number_of_rooms = $maximum_number_of_rooms:expr,
$(
next => {
ranges = $( $range_start:literal ..= $range_end:literal ),* ,
is_fully_loaded = $is_fully_loaded:expr,
list_state = $list_state:ident,
}
),*
$(,)*
) => {
assert_eq!($list.state(), SlidingSyncListLoadingState::$first_list_state, "first state");
$(
{
// Generate a new request.
let request = $list.next_request(&mut LazyTransactionId::new()).unwrap();
assert_eq!(
request.ranges,
[
$( (uint!( $range_start ), uint!( $range_end )) ),*
],
"ranges",
);
// Fake a response.
let _ = $list.update(Some($maximum_number_of_rooms), &[], &[]);
assert_eq!(
$list.inner.request_generator.read().unwrap().is_fully_loaded(),
$is_fully_loaded,
"is fully loaded",
);
assert_eq!(
$list.state(),
SlidingSyncListLoadingState::$list_state,
"state",
);
}
)*
};
}
#[test]
fn test_generator_paging_full_sync() {
let (sender, _receiver) = channel(1);
let mut list = SlidingSyncList::builder("testing")
.sync_mode(SlidingSyncMode::new_paging(10))
.build(sender);
assert_ranges! {
list = list,
list_state = NotLoaded,
maximum_number_of_rooms = 25,
next => {
ranges = 0..=9,
is_fully_loaded = false,
list_state = PartiallyLoaded,
},
next => {
ranges = 10..=19,
is_fully_loaded = false,
list_state = PartiallyLoaded,
},
// The maximum number of rooms is reached!
next => {
ranges = 20..=24,
is_fully_loaded = true,
list_state = FullyLoaded,
},
// Now it's fully loaded, so the same request must be produced every time.
next => {
ranges = 0..=24, // the range starts at 0 now!
is_fully_loaded = true,
list_state = FullyLoaded,
},
next => {
ranges = 0..=24,
is_fully_loaded = true,
list_state = FullyLoaded,
},
};
}
#[test]
fn test_generator_paging_full_sync_with_a_maximum_number_of_rooms_to_fetch() {
let (sender, _receiver) = channel(1);
let mut list = SlidingSyncList::builder("testing")
.sync_mode(SlidingSyncMode::new_paging(10).maximum_number_of_rooms_to_fetch(22))
.build(sender);
assert_ranges! {
list = list,
list_state = NotLoaded,
maximum_number_of_rooms = 25,
next => {
ranges = 0..=9,
is_fully_loaded = false,
list_state = PartiallyLoaded,
},
next => {
ranges = 10..=19,
is_fully_loaded = false,
list_state = PartiallyLoaded,
},
// The maximum number of rooms to fetch is reached!
next => {
ranges = 20..=21,
is_fully_loaded = true,
list_state = FullyLoaded,
},
// Now it's fully loaded, so the same request must be produced every time.
next => {
ranges = 0..=21, // the range starts at 0 now!
is_fully_loaded = true,
list_state = FullyLoaded,
},
next => {
ranges = 0..=21,
is_fully_loaded = true,
list_state = FullyLoaded,
},
};
}
#[test]
fn test_generator_growing_full_sync() {
let (sender, _receiver) = channel(1);
let mut list = SlidingSyncList::builder("testing")
.sync_mode(SlidingSyncMode::new_growing(10))
.build(sender);
assert_ranges! {
list = list,
list_state = NotLoaded,
maximum_number_of_rooms = 25,
next => {
ranges = 0..=9,
is_fully_loaded = false,
list_state = PartiallyLoaded,
},
next => {
ranges = 0..=19,
is_fully_loaded = false,
list_state = PartiallyLoaded,
},
// The maximum number of rooms is reached!
next => {
ranges = 0..=24,
is_fully_loaded = true,
list_state = FullyLoaded,
},
// Now it's fully loaded, so the same request must be produced every time.
next => {
ranges = 0..=24,
is_fully_loaded = true,
list_state = FullyLoaded,
},
next => {
ranges = 0..=24,
is_fully_loaded = true,
list_state = FullyLoaded,
},
};
}
#[test]
fn test_generator_growing_full_sync_with_a_maximum_number_of_rooms_to_fetch() {
let (sender, _receiver) = channel(1);
let mut list = SlidingSyncList::builder("testing")
.sync_mode(SlidingSyncMode::new_growing(10).maximum_number_of_rooms_to_fetch(22))
.build(sender);
assert_ranges! {
list = list,
list_state = NotLoaded,
maximum_number_of_rooms = 25,
next => {
ranges = 0..=9,
is_fully_loaded = false,
list_state = PartiallyLoaded,
},
next => {
ranges = 0..=19,
is_fully_loaded = false,
list_state = PartiallyLoaded,
},
// The maximum number of rooms is reached!
next => {
ranges = 0..=21,
is_fully_loaded = true,
list_state = FullyLoaded,
},
// Now it's fully loaded, so the same request must be produced every time.
next => {
ranges = 0..=21,
is_fully_loaded = true,
list_state = FullyLoaded,
},
next => {
ranges = 0..=21,
is_fully_loaded = true,
list_state = FullyLoaded,
},
};
}
#[test]
fn test_generator_selective() {
let (sender, _receiver) = channel(1);
let mut list = SlidingSyncList::builder("testing")
.sync_mode(SlidingSyncMode::new_selective().add_range(0..=10).add_range(42..=153))
.build(sender);
assert_ranges! {
list = list,
list_state = NotLoaded,
maximum_number_of_rooms = 25,
// The maximum number of rooms is reached directly!
next => {
ranges = 0..=10, 42..=153,
is_fully_loaded = true,
list_state = FullyLoaded,
},
// Now it's fully loaded, so the same request must be produced every time.
next => {
ranges = 0..=10, 42..=153,
is_fully_loaded = true,
list_state = FullyLoaded,
},
next => {
ranges = 0..=10, 42..=153,
is_fully_loaded = true,
list_state = FullyLoaded,
}
};
}
#[async_test]
async fn test_generator_selective_with_modifying_ranges_on_the_fly() {
let (sender, _receiver) = channel(4);
let mut list = SlidingSyncList::builder("testing")
.sync_mode(SlidingSyncMode::new_selective().add_range(0..=10).add_range(42..=153))
.build(sender);
assert_ranges! {
list = list,
list_state = NotLoaded,
maximum_number_of_rooms = 25,
// The maximum number of rooms is reached directly!
next => {
ranges = 0..=10, 42..=153,
is_fully_loaded = true,
list_state = FullyLoaded,
},
// Now it's fully loaded, so the same request must be produced every time.
next => {
ranges = 0..=10, 42..=153,
is_fully_loaded = true,
list_state = FullyLoaded,
},
next => {
ranges = 0..=10, 42..=153,
is_fully_loaded = true,
list_state = FullyLoaded,
}
};
list.set_sync_mode(SlidingSyncMode::new_selective().add_range(3..=7));
assert_ranges! {
list = list,
list_state = PartiallyLoaded,
maximum_number_of_rooms = 25,
next => {
ranges = 3..=7,
is_fully_loaded = true,
list_state = FullyLoaded,
},
};
list.set_sync_mode(SlidingSyncMode::new_selective().add_range(42..=77));
assert_ranges! {
list = list,
list_state = PartiallyLoaded,
maximum_number_of_rooms = 25,
next => {
ranges = 42..=77,
is_fully_loaded = true,
list_state = FullyLoaded,
},
};
list.set_sync_mode(SlidingSyncMode::new_selective());
assert_ranges! {
list = list,
list_state = PartiallyLoaded,
maximum_number_of_rooms = 25,
next => {
ranges = ,
is_fully_loaded = true,
list_state = FullyLoaded,
},
};
}
#[async_test]
async fn test_generator_changing_sync_mode_to_various_modes() {
let (sender, _receiver) = channel(4);
let mut list = SlidingSyncList::builder("testing")
.sync_mode(SlidingSyncMode::new_selective().add_range(0..=10).add_range(42..=153))
.build(sender);
assert_ranges! {
list = list,
list_state = NotLoaded,
maximum_number_of_rooms = 25,
// The maximum number of rooms is reached directly!
next => {
ranges = 0..=10, 42..=153,
is_fully_loaded = true,
list_state = FullyLoaded,
},
// Now it's fully loaded, so the same request must be produced every time.
next => {
ranges = 0..=10, 42..=153,
is_fully_loaded = true,
list_state = FullyLoaded,
},
next => {
ranges = 0..=10, 42..=153,
is_fully_loaded = true,
list_state = FullyLoaded,
}
};
// Changing from `Selective` to `Growing`.
list.set_sync_mode(SlidingSyncMode::new_growing(10));
assert_ranges! {
list = list,
list_state = PartiallyLoaded, // we had some partial state, but we can't be sure it's fully loaded until the next request
maximum_number_of_rooms = 25,
next => {
ranges = 0..=9,
is_fully_loaded = false,
list_state = PartiallyLoaded,
},
next => {
ranges = 0..=19,
is_fully_loaded = false,
list_state = PartiallyLoaded,
},
// The maximum number of rooms is reached!
next => {
ranges = 0..=24,
is_fully_loaded = true,
list_state = FullyLoaded,
},
// Now it's fully loaded, so the same request must be produced every time.
next => {
ranges = 0..=24,
is_fully_loaded = true,
list_state = FullyLoaded,
},
next => {
ranges = 0..=24,
is_fully_loaded = true,
list_state = FullyLoaded,
},
};
// Changing from `Growing` to `Paging`.
list.set_sync_mode(SlidingSyncMode::new_paging(10));
assert_ranges! {
list = list,
list_state = PartiallyLoaded, // we had some partial state, but we can't be sure it's fully loaded until the next request
maximum_number_of_rooms = 25,
next => {
ranges = 0..=9,
is_fully_loaded = false,
list_state = PartiallyLoaded,
},
next => {
ranges = 10..=19,
is_fully_loaded = false,
list_state = PartiallyLoaded,
},
// The maximum number of rooms is reached!
next => {
ranges = 20..=24,
is_fully_loaded = true,
list_state = FullyLoaded,
},
// Now it's fully loaded, so the same request must be produced every time.
next => {
ranges = 0..=24, // the range starts at 0 now!
is_fully_loaded = true,
list_state = FullyLoaded,
},
next => {
ranges = 0..=24,
is_fully_loaded = true,
list_state = FullyLoaded,
},
};
// Changing from `Paging` to `Selective`.
list.set_sync_mode(SlidingSyncMode::new_selective());
assert_eq!(list.state(), SlidingSyncListLoadingState::PartiallyLoaded); // we had some partial state, but we can't be sure it's fully loaded until the
// next request
// We need to update the ranges, of course, as they are not managed
// automatically anymore.
list.set_sync_mode(SlidingSyncMode::new_selective().add_range(0..=100));
assert_ranges! {
list = list,
list_state = PartiallyLoaded, // we had some partial state, but we can't be sure it's fully loaded until the next request
maximum_number_of_rooms = 25,
// The maximum number of rooms is reached directly!
next => {
ranges = 0..=100,
is_fully_loaded = true,
list_state = FullyLoaded,
},
// Now it's fully loaded, so the same request must be produced every time.
next => {
ranges = 0..=100,
is_fully_loaded = true,
list_state = FullyLoaded,
},
next => {
ranges = 0..=100,
is_fully_loaded = true,
list_state = FullyLoaded,
}
};
}
#[async_test]
#[allow(clippy::await_holding_lock)]
async fn test_sliding_sync_inner_update_state_room_list_and_maximum_number_of_rooms() {
let (sender, _receiver) = channel(1);
let mut list = SlidingSyncList::builder("foo")
.sync_mode(SlidingSyncMode::new_selective().add_range(0..=3))
.build(sender);
assert_eq!(**list.inner.maximum_number_of_rooms.read().unwrap(), None);
assert_eq!(list.inner.room_list.read().unwrap().len(), 0);
let room0 = room_id!("!room0:bar.org");
let room1 = room_id!("!room1:bar.org");
let room2 = room_id!("!room2:bar.org");
let room3 = room_id!("!room3:bar.org");
let room4 = room_id!("!room4:bar.org");
// Initial range.
for _ in 0..=1 {
// Simulate a request.
let _ = list.next_request(&mut LazyTransactionId::new());
// A new response.
let sync: v4::SyncOp = serde_json::from_value(json!({
"op": SlidingOp::Sync,
"range": [0, 2],
"room_ids": [room0, room1, room2],
}))
.unwrap();
let new_changes = list.update(Some(5), &[sync], &[]).unwrap();
assert!(new_changes);
// The `maximum_number_of_rooms` has been updated as expected.
assert_eq!(**list.inner.maximum_number_of_rooms.read().unwrap(), Some(5));
// The `room_list` has the correct size and contains expected room entries.
let room_list = list.inner.room_list.read().unwrap();
assert_eq!(room_list.len(), 5);
assert_eq!(
**room_list,
vector![
RoomListEntry::Filled(room0.to_owned()),
RoomListEntry::Filled(room1.to_owned()),
RoomListEntry::Filled(room2.to_owned()),
RoomListEntry::Empty,
RoomListEntry::Empty,
]
);
}
let (_, mut room_list_stream) = list.room_list_stream();
let (room_list_stream_sender, mut room_list_stream_receiver) = unbounded_channel();
spawn(async move {
while let Some(diff) = room_list_stream.next().await {
room_list_stream_sender.send(diff).unwrap();
}
});
// Simulate a request.
let _ = list.next_request(&mut LazyTransactionId::new());
// A new response.
let sync: v4::SyncOp = serde_json::from_value(json!({
"op": SlidingOp::Sync,
"range": [3, 4],
"room_ids": [room3, room4],
}))
.unwrap();
let new_changes = list
.update(
Some(5),
&[sync],
// Let's imagine `room2` has received an update, but its position doesn't
// change.
&[room3.to_owned(), room4.to_owned(), room2.to_owned()],
)
.unwrap();
assert!(new_changes);
// The `maximum_number_of_rooms` has been updated as expected.
assert_eq!(**list.inner.maximum_number_of_rooms.read().unwrap(), Some(5));
// The `room_list` has the correct size and contains expected room entries.
let room_list = list.inner.room_list.read().unwrap();
assert_eq!(room_list.len(), 5);
assert_eq!(
**room_list,
vector![
RoomListEntry::Filled(room0.to_owned()),
RoomListEntry::Filled(room1.to_owned()),
RoomListEntry::Filled(room2.to_owned()),
RoomListEntry::Filled(room3.to_owned()),
RoomListEntry::Filled(room4.to_owned()),
]
);
// Wait for “diff” to be generated.
// Why this? Because the following `assert_eq` are using `try_recv()` instead of
// recv().await`, so that a missing “diff” doesn't make the test to hang
// forever.
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
assert_eq!(
room_list_stream_receiver.try_recv(),
Ok(vec![
// `room3` has been modified by a `SYNC` operation.
VectorDiff::Set { index: 3, value: RoomListEntry::Filled(room3.to_owned()) },
// `room4` has been modified by a `SYNC` operation.
VectorDiff::Set { index: 4, value: RoomListEntry::Filled(room4.to_owned()) },
// `room2` has been modified by another update (like a new event).
VectorDiff::Set { index: 2, value: RoomListEntry::Filled(room2.to_owned()) },
])
);
}
#[test]
fn test_sliding_sync_mode_serialization() {
assert_json_roundtrip!(
from SlidingSyncMode: SlidingSyncMode::from(SlidingSyncMode::new_paging(1).maximum_number_of_rooms_to_fetch(2)) => json!({
"Paging": {
"batch_size": 1,
"maximum_number_of_rooms_to_fetch": 2
}
})
);
assert_json_roundtrip!(
from SlidingSyncMode: SlidingSyncMode::from(SlidingSyncMode::new_growing(1).maximum_number_of_rooms_to_fetch(2)) => json!({
"Growing": {
"batch_size": 1,
"maximum_number_of_rooms_to_fetch": 2
}
})
);
assert_json_roundtrip!(from SlidingSyncMode: SlidingSyncMode::from(SlidingSyncMode::new_selective()) => json!({
"Selective": {
"ranges": []
}
})
);
}
#[test]
fn test_sliding_sync_state_serialization() {
assert_json_roundtrip!(from SlidingSyncListLoadingState: SlidingSyncListLoadingState::NotLoaded => json!("NotLoaded"));
assert_json_roundtrip!(from SlidingSyncListLoadingState: SlidingSyncListLoadingState::Preloaded => json!("Preloaded"));
assert_json_roundtrip!(from SlidingSyncListLoadingState: SlidingSyncListLoadingState::PartiallyLoaded => json!("PartiallyLoaded"));
assert_json_roundtrip!(from SlidingSyncListLoadingState: SlidingSyncListLoadingState::FullyLoaded => json!("FullyLoaded"));
}
macro_rules! entries {
( @_ [ E $( , $( $rest:tt )* )? ] [ $( $accumulator:tt )* ] ) => {
entries!( @_ [ $( $( $rest )* )? ] [ $( $accumulator )* RoomListEntry::Empty, ] )
};
( @_ [ F( $room_id:literal ) $( , $( $rest:tt )* )? ] [ $( $accumulator:tt )* ] ) => {
entries!( @_ [ $( $( $rest )* )? ] [ $( $accumulator )* RoomListEntry::Filled(room_id!( $room_id ).to_owned()), ] )
};
( @_ [ I( $room_id:literal ) $( , $( $rest:tt )* )? ] [ $( $accumulator:tt )* ] ) => {
entries!( @_ [ $( $( $rest )* )? ] [ $( $accumulator )* RoomListEntry::Invalidated(room_id!( $room_id ).to_owned()), ] )
};
( @_ [] [ $( $accumulator:tt )* ] ) => {
vector![ $( $accumulator )* ]
};
( $( $all:tt )* ) => {
entries!( @_ [ $( $all )* ] [] )
};
}
macro_rules! assert_sync_operations {
(
$assert_description:literal :
room_list = [ $( $room_list_entries:tt )* ],
sync_operations = [
$(
{ $( $operation:tt )+ }
),*
$(,)?
]
$( , rooms = [ $( $rooms:literal ),* ] )?
$(,)?
=>
result = $result:tt,
room_list = [ $( $expected_room_list_entries:tt )* ]
$( , rooms = [ $( $expected_rooms:literal ),* ] )?
$(,)?
) => {
let mut room_list = ObservableVector::from(entries![ $( $room_list_entries )* ]);
let operations: &[v4::SyncOp] = &[
$(
serde_json::from_value(json!({
$( $operation )+
})).unwrap()
),*
];
let mut rooms_that_have_received_an_update = HashSet::<OwnedRoomId>::new();
$(
{
$(
rooms_that_have_received_an_update.insert(room_id!( $rooms ).to_owned());
)*
}
)?
let mut txn = room_list.transaction();
let result = apply_sync_operations(
operations,
&mut txn,
&mut rooms_that_have_received_an_update,
);
txn.commit();
assert!(result.$result(), "{}; assert the `Result`", $assert_description);
assert_eq!(
*room_list,
entries![ $( $expected_room_list_entries )* ],
"{}; asserting the `room_list`",
$assert_description,
);
$(
#[allow(unused_mut)]
let mut expected_rooms_that_have_received_an_update = HashSet::<OwnedRoomId>::new();
{
$(
expected_rooms_that_have_received_an_update.insert(room_id!( $expected_rooms ).to_owned());
)*
}
assert_eq!(
rooms_that_have_received_an_update,
expected_rooms_that_have_received_an_update,
"{}; asserting the rooms that have received an update",
$assert_description,
);
)?
};
}
#[test]
fn test_sync_operations_sync() {
assert_sync_operations! {
"All room list is updated":
room_list = [E, E, E, F("!r3:x.y")],
sync_operations = [
{
"op": SlidingOp::Sync,
"range": [0, 2],
"room_ids": ["!r0:x.y", "!r1:x.y", "!r2:x.y"],
}
],
rooms = ["!r0:x.y", "!r1:x.y", "!r2:x.y", "!r3:x.y"], // `r3` has received an update, but its position didn't change
=>
result = is_ok,
room_list = [F("!r0:x.y"), F("!r1:x.y"), F("!r2:x.y"), F("!r3:x.y")],
rooms = ["!r3:x.y"],
};
assert_sync_operations! {
"Partial update":
room_list = [E, E, E],
sync_operations = [
{
"op": SlidingOp::Sync,
"range": [0, 1],
"room_ids": ["!r0:x.y", "!r1:x.y"],
}
]
=>
result = is_ok,
room_list = [F("!r0:x.y"), F("!r1:x.y"), E],
};
assert_sync_operations! {
"Partial update":
room_list = [E, E, E],
sync_operations = [
{
"op": SlidingOp::Sync,
"range": [1, 2],
"room_ids": ["!r1:x.y", "!r2:x.y"],
}
]
=>
result = is_ok,
room_list = [E, F("!r1:x.y"), F("!r2:x.y")],
};
assert_sync_operations! {
"The range returned by the server is too large compared to the `room_ids`":
room_list = [E],
sync_operations = [
{
"op": SlidingOp::Sync,
"range": [0, 2], // <- it should be [0, 0]
"room_ids": ["!r0:x.y"],
}
]
=>
result = is_err,
room_list = [E],
};
assert_sync_operations! {
"Missing `range`":
room_list = [E, E, E],
sync_operations = [
{
"op": SlidingOp::Sync,
"room_ids": ["!r0:x.y", "!r1:x.y"],
}
]
=>
result = is_err,
room_list = [E, E, E],
};
assert_sync_operations! {
"Invalid `range`":
room_list = [E, E, E],
sync_operations = [
{
"op": SlidingOp::Sync,
"range": [2, 0],
"room_ids": ["!r0:x.y", "!r1:x.y"],
}
]
=>
result = is_err,
room_list = [E, E, E],
};
assert_sync_operations! {
"Missing `room_ids`":
room_list = [E, E, E],
sync_operations = [
{
"op": SlidingOp::Sync,
"range": [0, 2],
}
]
=>
result = is_err,
room_list = [E, E, E],
};
assert_sync_operations! {
"Out of bounds operation":
room_list = [E, F("!r1:x.y"), E],
sync_operations = [
{
"op": SlidingOp::Sync,
"range": [2, 3],
"room_ids": ["!r1:x.y", "!r2:x.y"],
}
]
=>
result = is_err,
room_list = [E, F("!r1:x.y"), E],
};
assert_sync_operations! {
"The server replies with a particular range, but some room IDs are missing":
room_list = [E, E, E],
sync_operations = [
{
"op": SlidingOp::Sync,
"range": [0, 2],
"room_ids": ["!r0:x.y" /* items are missing here! */],
}
]
=>
result = is_err,
room_list = [E, E, E],
};
assert_sync_operations! {
"The server replies with a particular range, but there is too much room IDs":
room_list = [E, E, E],
sync_operations = [
{
"op": SlidingOp::Sync,
"range": [0, 1],
"room_ids": ["!r0:x.y", "!r1:x.y", "!extra:x.y"],
}
]
=>
result = is_err,
room_list = [E, E, E],
};
}
#[test]
fn test_sync_operations_delete() {
assert_sync_operations! {
"Delete a room entry in the middle":
room_list = [F("!r0:x.y"), F("!r1:x.y"), F("!r2:x.y")],
sync_operations = [
{
"op": SlidingOp::Delete,
"index": 1,
}
],
rooms = ["!r0:x.y", "!r1:x.y"], // `r0` has also received an update.
=>
result = is_ok,
room_list = [F("!r0:x.y"), F("!r2:x.y")],
rooms = ["!r0:x.y"],
};
assert_sync_operations! {
"Delete a room entry at the beginning":
room_list = [F("!r0:x.y"), F("!r1:x.y"), F("!r2:x.y")],
sync_operations = [
{
"op": SlidingOp::Delete,
"index": 0,
}
]
=>
result = is_ok,
room_list = [F("!r1:x.y"), F("!r2:x.y")],
};
assert_sync_operations! {
"Delete a room entry at the end":
room_list = [F("!r0:x.y"), F("!r1:x.y"), F("!r2:x.y")],
sync_operations = [
{
"op": SlidingOp::Delete,
"index": 2,
}
]
=>
result = is_ok,
room_list = [F("!r0:x.y"), F("!r1:x.y")],
};
assert_sync_operations! {
"Delete an out of bounds room entry":
room_list = [F("!r0:x.y"), F("!r1:x.y"), F("!r2:x.y")],
sync_operations = [
{
"op": SlidingOp::Delete,
"index": 3,
}
]
=>
result = is_ok, // <- that's surprising, see the code for more explanations!
room_list = [F("!r0:x.y"), F("!r1:x.y"), F("!r2:x.y")],
};
}
#[test]
fn test_sync_operations_insert() {
assert_sync_operations! {
"Insert a room entry in the middle":
room_list = [E, E, E],
sync_operations = [
{
"op": SlidingOp::Insert,
"index": 1,
"room_id": "!r1:x.y",
}
],
rooms = ["!r0:x.y", "!r1:x.y"], // `r0` has also received an update.
=>
result = is_ok,
room_list = [E, F("!r1:x.y"), E, E],
rooms = ["!r0:x.y"],
};
assert_sync_operations! {
"Insert a room entry at the beginning":
room_list = [E, E, E],
sync_operations = [
{
"op": SlidingOp::Insert,
"index": 0,
"room_id": "!r0:x.y",
}
]
=>
result = is_ok,
room_list = [F("!r0:x.y"), E, E, E],
};
assert_sync_operations! {
"Insert a room entry at the end":
room_list = [E, E, E],
sync_operations = [
{
"op": SlidingOp::Insert,
"index": 3,
"room_id": "!r3:x.y",
}
]
=>
result = is_ok,
room_list = [E, E, E, F("!r3:x.y")],
};
assert_sync_operations! {
"Insert an out of bounds room entry":
room_list = [E, F("!r1:x.y"), E],
sync_operations = [
{
"op": SlidingOp::Insert,
"index": 4,
"room_id": "!r4:x.y",
}
]
=>
result = is_err,
room_list = [E, F("!r1:x.y"), E],
};
}
#[test]
fn test_sync_operations_invalidate() {
assert_sync_operations! {
"Invalidating an empty room":
room_list = [E, F("!r1:x.y")],
sync_operations = [
{
"op": SlidingOp::Invalidate,
"range": [0, 0],
}
],
rooms = ["!r1:x.y"], // `r1` has also received an update.
=>
result = is_ok,
room_list = [E, F("!r1:x.y")],
rooms = ["!r1:x.y"],
};
assert_sync_operations! {
"Invalidating a filled room":
room_list = [F("!r0:x.y"), F("!r1:x.y")],
sync_operations = [
{
"op": SlidingOp::Invalidate,
"range": [0, 0],
}
],
rooms = ["!r0:x.y", "!r1:x.y"], // `r1` has also received an update.
=>
result = is_ok,
room_list = [I("!r0:x.y"), F("!r1:x.y")],
rooms = ["!r1:x.y"],
};
assert_sync_operations! {
"Invalidating an invalidated room":
room_list = [I("!r0:x.y"), F("!r1:x.y")],
sync_operations = [
{
"op": SlidingOp::Invalidate,
"range": [0, 0],
}
],
rooms = ["!r0:x.y", "!r1:x.y"], // `r1` has also received an update.
=>
result = is_ok,
room_list = [I("!r0:x.y"), F("!r1:x.y")],
rooms = ["!r1:x.y"],
};
assert_sync_operations! {
"Partial update from the beginning":
room_list = [F("!r0:x.y"), F("!r1:x.y"), F("!r2:x.y")],
sync_operations = [
{
"op": SlidingOp::Invalidate,
"range": [0, 1],
}
]
=>
result = is_ok,
room_list = [I("!r0:x.y"), I("!r1:x.y"), F("!r2:x.y")],
};
assert_sync_operations! {
"Partial update from the end":
room_list = [F("!r0:x.y"), F("!r1:x.y"), F("!r2:x.y")],
sync_operations = [
{
"op": SlidingOp::Invalidate,
"range": [1, 2],
}
]
=>
result = is_ok,
room_list = [F("!r0:x.y"), I("!r1:x.y"), I("!r2:x.y")],
};
assert_sync_operations! {
"Full update":
room_list = [F("!r0:x.y"), F("!r1:x.y"), F("!r2:x.y")],
sync_operations = [
{
"op": SlidingOp::Invalidate,
"range": [0, 2],
}
]
=>
result = is_ok,
room_list = [I("!r0:x.y"), I("!r1:x.y"), I("!r2:x.y")],
};
assert_sync_operations! {
"The range returned by the server is too large compared to the `room_lists`":
room_list = [F("!r0:x.y")],
sync_operations = [
{
"op": SlidingOp::Invalidate,
"range": [0, 9], // <- it should be [0, 0]
}
]
=>
result = is_err,
room_list = [F("!r0:x.y")],
};
assert_sync_operations! {
"Missing `range`":
room_list = [F("!r0:x.y"), F("!r1:x.y"), F("!r2:x.y")],
sync_operations = [
{
"op": SlidingOp::Delete,
}
]
=>
result = is_err,
room_list = [F("!r0:x.y"), F("!r1:x.y"), F("!r2:x.y")],
};
assert_sync_operations! {
"Invalid `range`":
room_list = [F("!r0:x.y"), F("!r1:x.y"), F("!r2:x.y")],
sync_operations = [
{
"op": SlidingOp::Delete,
"range": [12, 0],
}
]
=>
result = is_err,
room_list = [F("!r0:x.y"), F("!r1:x.y"), F("!r2:x.y")],
};
assert_sync_operations! {
"Out of bounds operation":
room_list = [F("!r0:x.y"), F("!r1:x.y"), F("!r2:x.y")],
sync_operations = [
{
"op": SlidingOp::Delete,
"range": [2, 3],
}
]
=>
result = is_err,
room_list = [F("!r0:x.y"), F("!r1:x.y"), F("!r2:x.y")],
};
}
#[test]
fn test_once_built() {
let (sender, _receiver) = channel(1);
let probe = Arc::new(Mutex::new(Cell::new(false)));
let probe_clone = probe.clone();
let _list = SlidingSyncList::builder("testing")
.once_built(move |list| {
let mut probe_lock = probe.lock().unwrap();
*probe_lock.get_mut() = true;
list
})
.build(sender);
let probe_lock = probe_clone.lock().unwrap();
assert!(probe_lock.get());
}
}