matrix_sdk_ui/room_list_service/mod.rs
1// Copyright 2023 The Matrix.org Foundation C.I.C.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for that specific language governing permissions and
13// limitations under the License.
14
15//! `RoomListService` API.
16//!
17//! The `RoomListService` is a UI API dedicated to present a list of Matrix
18//! rooms to the user. The syncing is handled by [`SlidingSync`]. The idea is to
19//! expose a simple API to handle most of the client app use cases, like:
20//! Showing and updating a list of rooms, filtering a list of rooms, handling
21//! particular updates of a range of rooms (the ones the client app is showing
22//! to the view, i.e. the rooms present in the viewport) etc.
23//!
24//! As such, the `RoomListService` works as an opinionated state machine. The
25//! states are defined by [`State`]. Actions are attached to the each state
26//! transition.
27//!
28//! The API is purposely small. Sliding Sync is versatile. `RoomListService` is
29//! _one_ specific usage of Sliding Sync.
30//!
31//! # Basic principle
32//!
33//! `RoomListService` works with 1 Sliding Sync List:
34//!
35//! * `all_rooms` (referred by the constant [`ALL_ROOMS_LIST_NAME`]) is the only
36//! list. Its goal is to load all the user' rooms. It starts with a
37//! [`SlidingSyncMode::Selective`] sync-mode with a small range (i.e. a small
38//! set of rooms) to load the first rooms quickly, and then updates to a
39//! [`SlidingSyncMode::Growing`] sync-mode to load the remaining rooms “in the
40//! background”: it will sync the existing rooms and will fetch new rooms, by
41//! a certain batch size.
42//!
43//! This behavior has proven to be empirically satisfying to provide a fast and
44//! fluid user experience for a Matrix client.
45//!
46//! [`RoomListService::all_rooms`] provides a way to get a [`RoomList`] for all
47//! the rooms. From that, calling [`RoomList::entries_with_dynamic_adapters`]
48//! provides a way to get a stream of rooms. This stream is sorted, can be
49//! filtered, and the filter can be changed over time.
50//!
51//! [`RoomListService::state`] provides a way to get a stream of the state
52//! machine's state, which can be pretty helpful for the client app.
53
54pub mod filters;
55mod room_list;
56pub mod sorters;
57mod state;
58
59use std::{sync::Arc, time::Duration};
60
61use async_stream::stream;
62use eyeball::Subscriber;
63use futures_util::{Stream, StreamExt, pin_mut};
64use matrix_sdk::{
65 Client, Error as SlidingSyncError, Room, SlidingSync, SlidingSyncList, SlidingSyncMode,
66 event_cache::EventCacheError, sliding_sync::PollTimeout, timeout::timeout,
67};
68pub use room_list::*;
69use ruma::{
70 OwnedRoomId, RoomId, UInt, api::client::sync::sync_events::v5 as http, assign,
71 events::StateEventType,
72};
73pub use state::*;
74use thiserror::Error;
75use tracing::{debug, error, warn};
76
77/// The default `required_state` constant value for sliding sync lists and
78/// sliding sync room subscriptions.
79const DEFAULT_REQUIRED_STATE: &[(StateEventType, &str)] = &[
80 (StateEventType::RoomName, ""),
81 (StateEventType::RoomEncryption, ""),
82 (StateEventType::RoomMember, "$LAZY"),
83 (StateEventType::RoomMember, "$ME"),
84 (StateEventType::RoomTopic, ""),
85 // Temporary workaround for https://github.com/matrix-org/matrix-rust-sdk/issues/5285
86 (StateEventType::RoomAvatar, ""),
87 (StateEventType::RoomCanonicalAlias, ""),
88 (StateEventType::RoomPowerLevels, ""),
89 (StateEventType::CallMember, "*"),
90 (StateEventType::RoomJoinRules, ""),
91 (StateEventType::RoomTombstone, ""),
92 // Those two events are required to properly compute room previews.
93 // `StateEventType::RoomCreate` is also necessary to compute the room
94 // version, and thus handling the tombstoned room correctly.
95 (StateEventType::RoomCreate, ""),
96 (StateEventType::RoomHistoryVisibility, ""),
97 // Required to correctly calculate the room display name.
98 (StateEventType::MemberHints, ""),
99 (StateEventType::SpaceParent, "*"),
100 (StateEventType::SpaceChild, "*"),
101 // Required for live location sharing to work - beacon events reference this state.
102 (StateEventType::BeaconInfo, "*"),
103 // Required for `Room::retention`/`Room::effective_retention` (MSC1763) to see
104 // room-level retention overrides.
105 (StateEventType::RoomRetention, ""),
106];
107
108/// The default `required_state` constant value for sliding sync room
109/// subscriptions that must be added to `DEFAULT_REQUIRED_STATE`.
110const DEFAULT_ROOM_SUBSCRIPTION_EXTRA_REQUIRED_STATE: &[(StateEventType, &str)] =
111 &[(StateEventType::RoomPinnedEvents, "")];
112
113/// The default Sliding Sync connection ID for the room list service.
114pub(crate) const DEFAULT_CONNECTION_ID: &str = "room-list";
115
116/// The default timeline limit for the room list service.
117pub(crate) const DEFAULT_LIST_TIMELINE_LIMIT: u32 = 1;
118
119/// The default `timeline_limit` value when used with room subscriptions.
120const DEFAULT_ROOM_SUBSCRIPTION_TIMELINE_LIMIT: u32 = 20;
121
122/// The [`RoomListService`] type. See the module's documentation to learn more.
123#[derive(Debug)]
124pub struct RoomListService {
125 /// Client that has created this [`RoomListService`].
126 client: Client,
127
128 /// The Sliding Sync instance.
129 sliding_sync: Arc<SlidingSync>,
130
131 /// The current state of the `RoomListService`.
132 ///
133 /// `RoomListService` is a simple state-machine.
134 state_machine: StateMachine,
135}
136
137impl RoomListService {
138 /// Create a new `RoomList`.
139 ///
140 /// A [`matrix_sdk::SlidingSync`] client will be created, with a cached list
141 /// already pre-configured.
142 ///
143 /// This won't start an encryption sync, and it's the user's responsibility
144 /// to create one in this case using
145 /// [`EncryptionSyncService`][crate::encryption_sync_service::EncryptionSyncService].
146 pub async fn new(client: Client) -> Result<Self, Error> {
147 Self::new_with(client, true, DEFAULT_CONNECTION_ID, DEFAULT_LIST_TIMELINE_LIMIT).await
148 }
149
150 /// Like [`RoomListService::new`] but with additional configuration options.
151 ///
152 /// - `share_pos`: toggles [`SlidingSyncBuilder::share_pos`] for
153 /// cross-process position sharing.
154 /// - `connection_id`: the Sliding Sync connection ID
155 /// - `timeline_limit`: the timeline limit
156 ///
157 /// [`SlidingSyncBuilder::share_pos`]: matrix_sdk::sliding_sync::SlidingSyncBuilder::share_pos
158 pub async fn new_with(
159 client: Client,
160 share_pos: bool,
161 connection_id: &str,
162 timeline_limit: u32,
163 ) -> Result<Self, Error> {
164 let mut builder = client
165 .sliding_sync(connection_id)
166 .map_err(Error::SlidingSync)?
167 .with_account_data_extension(
168 assign!(http::request::AccountData::default(), { enabled: Some(true) }),
169 )
170 .with_receipt_extension(assign!(http::request::Receipts::default(), {
171 enabled: Some(true),
172 rooms: Some(vec![http::request::ExtensionRoomConfig::AllSubscribed])
173 }))
174 .with_typing_extension(assign!(http::request::Typing::default(), {
175 enabled: Some(true),
176 }))
177 .with_profiles_extension(assign!(http::request::Profiles::default(), {
178 enabled: Some(true),
179 }));
180
181 match client.enabled_thread_subscriptions().await {
182 Ok(true) => {
183 debug!("Client requested thread subscriptions extension");
184
185 builder = builder.with_thread_subscriptions_extension(
186 assign!(http::request::ThreadSubscriptions::default(), {
187 enabled: Some(true),
188 limit: Some(ruma::uint!(10))
189 }),
190 );
191 }
192
193 Ok(false) => {
194 debug!(
195 "Thread subscriptions extension either not requested on the client, or the server doesn't advertise support for it: not enabling."
196 );
197 }
198
199 Err(error) => {
200 warn!(
201 ?error,
202 "Failed to check whether the client requested thread subscriptions extension: not enabling."
203 );
204 }
205 }
206
207 if share_pos {
208 // The e2ee extensions aren't enabled in this sliding sync instance, and this is
209 // the only one that could be used from a different process. So it's
210 // fine to enable position sharing (i.e. reloading it from disk),
211 // since it's always exclusively owned by the current process.
212 debug!("Enabling `share_pos` for the room list sliding sync");
213 builder = builder.share_pos();
214 }
215
216 let state_machine = StateMachine::new();
217 let observable_state = state_machine.cloned_state();
218
219 let sliding_sync = builder
220 .add_cached_list(
221 SlidingSyncList::builder(ALL_ROOMS_LIST_NAME)
222 .sync_mode(
223 SlidingSyncMode::new_selective()
224 .add_range(ALL_ROOMS_DEFAULT_SELECTIVE_RANGE),
225 )
226 .timeline_limit(timeline_limit)
227 .required_state(
228 DEFAULT_REQUIRED_STATE
229 .iter()
230 .map(|(state_event, value)| (state_event.clone(), (*value).to_owned()))
231 .collect(),
232 )
233 .filters(Some(assign!(http::request::ListFilters::default(), {
234 // As defined in the [SlidingSync MSC](https://github.com/matrix-org/matrix-spec-proposals/blob/9450ced7fb9cf5ea9077d029b3adf36aebfa8709/proposals/3575-sync.md?plain=1#L444)
235 // If unset, both invited and joined rooms are returned. If false, no invited rooms are
236 // returned. If true, only invited rooms are returned.
237 is_invite: None,
238 })))
239 .requires_timeout(move |request_generator| {
240 // We want Sliding Sync to apply the poll + network timeout —i.e. to do the
241 // long-polling— in some particular cases. Let's define them.
242 match observable_state.get() {
243 // These are the states where we want an immediate response from the
244 // server, with no long-polling.
245 State::Init
246 | State::SettingUp
247 | State::Recovering
248 | State::Error { .. }
249 | State::Terminated { .. } => PollTimeout::Some(0),
250
251 // Otherwise we want long-polling if the list is fully-loaded.
252 State::Running => {
253 if request_generator.is_fully_loaded() {
254 // Long-polling.
255 PollTimeout::Default
256 } else {
257 // No long-polling yet.
258 PollTimeout::Some(0)
259 }
260 }
261 }
262 }),
263 )
264 .await
265 .map_err(Error::SlidingSync)?
266 .build()
267 .await
268 .map(Arc::new)
269 .map_err(Error::SlidingSync)?;
270
271 // Eagerly subscribe the event cache to sync responses.
272 client.event_cache().subscribe()?;
273
274 Ok(Self { client, sliding_sync, state_machine })
275 }
276
277 /// Start to sync the room list.
278 ///
279 /// It's the main method of this entire API. Calling `sync` allows to
280 /// receive updates on the room list: new rooms, rooms updates etc. Those
281 /// updates can be read with `RoomList::entries` for example. This method
282 /// returns a [`Stream`] where produced items only hold an empty value
283 /// in case of a sync success, otherwise an error.
284 ///
285 /// The `RoomListService`' state machine is run by this method.
286 ///
287 /// Stopping the [`Stream`] (i.e. by calling [`Self::stop_sync`]), and
288 /// calling [`Self::sync`] again will resume from the previous state of
289 /// the state machine.
290 ///
291 /// This should be used only for testing. In practice, most users should be
292 /// using the [`SyncService`](crate::sync_service::SyncService) instead.
293 #[doc(hidden)]
294 pub fn sync(&self) -> impl Stream<Item = Result<(), Error>> + '_ {
295 stream! {
296 let sync = self.sliding_sync.sync();
297 pin_mut!(sync);
298
299 // This is a state machine implementation.
300 // Things happen in this order:
301 //
302 // 1. The next state is calculated,
303 // 2. The actions associated to the next state are run,
304 // 3. A sync is done,
305 // 4. The next state is stored.
306 loop {
307 debug!("Run a sync iteration");
308
309 // Calculate the next state, and run the associated actions.
310 let next_state = self.state_machine.next(&self.sliding_sync).await?;
311
312 // Do the sync.
313 match sync.next().await {
314 // Got a successful result while syncing.
315 Some(Ok(_update_summary)) => {
316 debug!(state = ?next_state, "New state");
317
318 // Update the state.
319 self.state_machine.set(next_state);
320
321 yield Ok(());
322 }
323
324 // Got an error while syncing.
325 Some(Err(error)) => {
326 debug!(expected_state = ?next_state, "New state is an error");
327
328 let next_state = State::Error { from: Box::new(next_state) };
329 self.state_machine.set(next_state);
330
331 yield Err(Error::SlidingSync(error));
332
333 break;
334 }
335
336 // Sync loop has terminated.
337 None => {
338 debug!(expected_state = ?next_state, "New state is a termination");
339
340 let next_state = State::Terminated { from: Box::new(next_state) };
341 self.state_machine.set(next_state);
342
343 break;
344 }
345 }
346 }
347 }
348 }
349
350 /// Force to stop the sync of the `RoomListService` started by
351 /// [`Self::sync`].
352 ///
353 /// It's of utter importance to call this method rather than stop polling
354 /// the `Stream` returned by [`Self::sync`] because it will force the
355 /// cancellation and exit the sync loop, i.e. it will cancel any
356 /// in-flight HTTP requests, cancel any pending futures etc. and put the
357 /// service into a termination state.
358 ///
359 /// Ideally, one wants to consume the `Stream` returned by [`Self::sync`]
360 /// until it returns `None`, because of [`Self::stop_sync`], so that it
361 /// ensures the states are correctly placed.
362 ///
363 /// Stopping the sync of the room list via this method will put the
364 /// state-machine into the [`State::Terminated`] state.
365 ///
366 /// This should be used only for testing. In practice, most users should be
367 /// using the [`SyncService`](crate::sync_service::SyncService) instead.
368 #[doc(hidden)]
369 pub fn stop_sync(&self) -> Result<(), Error> {
370 self.sliding_sync.stop_sync().map_err(Error::SlidingSync)
371 }
372
373 /// Force the sliding sync session to expire.
374 ///
375 /// This is used by [`SyncService`](crate::sync_service::SyncService).
376 ///
377 /// **Warning**: This method **must not** be called while the sync loop is
378 /// running!
379 pub(crate) async fn expire_sync_session(&self) {
380 self.sliding_sync.expire_session().await;
381
382 // Usually, when the session expires, it leads the state to be `Error`,
383 // thus some actions (like refreshing the lists) are executed. However,
384 // if the sync loop has been stopped manually, the state is `Terminated`, and
385 // when the session is forced to expire, the state remains `Terminated`, thus
386 // the actions aren't executed as expected. Consequently, let's update the
387 // state.
388 if let State::Terminated { from } = self.state_machine.get() {
389 self.state_machine.set(State::Error { from });
390 }
391 }
392
393 /// Get a [`Stream`] of [`SyncIndicator`].
394 ///
395 /// Read the documentation of [`SyncIndicator`] to learn more about it.
396 pub fn sync_indicator(
397 &self,
398 delay_before_showing: Duration,
399 delay_before_hiding: Duration,
400 ) -> impl Stream<Item = SyncIndicator> + use<> {
401 let mut state = self.state();
402
403 stream! {
404 // Ensure the `SyncIndicator` is always hidden to start with.
405 yield SyncIndicator::Hide;
406
407 // Let's not wait for an update to happen. The `SyncIndicator` must be
408 // computed as fast as possible.
409 let mut current_state = state.next_now();
410
411 loop {
412 let (sync_indicator, yield_delay) = match current_state {
413 State::SettingUp | State::Error { .. } => {
414 (SyncIndicator::Show, delay_before_showing)
415 }
416
417 State::Init | State::Recovering | State::Running | State::Terminated { .. } => {
418 (SyncIndicator::Hide, delay_before_hiding)
419 }
420 };
421
422 // `state.next().await` has a maximum of `yield_delay` time to execute…
423 let next_state = match timeout(state.next(), yield_delay).await {
424 // A new state has been received before `yield_delay` time. The new
425 // `sync_indicator` value won't be yielded.
426 Ok(next_state) => next_state,
427
428 // No new state has been received before `yield_delay` time. The
429 // `sync_indicator` value can be yielded.
430 Err(_) => {
431 yield sync_indicator;
432
433 // Now that `sync_indicator` has been yielded, let's wait on
434 // the next state again.
435 state.next().await
436 }
437 };
438
439 if let Some(next_state) = next_state {
440 // Update the `current_state`.
441 current_state = next_state;
442 } else {
443 // Something is broken with the state. Let's stop this stream too.
444 break;
445 }
446 }
447 }
448 }
449
450 /// Get the [`Client`] that has been used to create [`Self`].
451 pub fn client(&self) -> &Client {
452 &self.client
453 }
454
455 /// Get a subscriber to the state.
456 pub fn state(&self) -> Subscriber<State> {
457 self.state_machine.subscribe()
458 }
459
460 async fn list_for(&self, sliding_sync_list_name: &str) -> Result<RoomList, Error> {
461 RoomList::new(&self.client, &self.sliding_sync, sliding_sync_list_name, self.state()).await
462 }
463
464 /// Get a [`RoomList`] for all rooms.
465 pub async fn all_rooms(&self) -> Result<RoomList, Error> {
466 self.list_for(ALL_ROOMS_LIST_NAME).await
467 }
468
469 /// Get a [`Room`] if it exists.
470 pub fn room(&self, room_id: &RoomId) -> Result<Room, Error> {
471 self.client.get_room(room_id).ok_or_else(|| Error::RoomNotFound(room_id.to_owned()))
472 }
473
474 /// Set the room subscriptions to exactly `room_ids`.
475 ///
476 /// It means that all events from these rooms will be received every time,
477 /// no matter how the `RoomList` is configured.
478 ///
479 /// [`LatestEvents::listen_to_room`][listen_to_room] will be called for each
480 /// room in `room_ids`, so that the [`LatestEventValue`] will automatically
481 /// be calculated and updated for these rooms, for free.
482 ///
483 /// [listen_to_room]: matrix_sdk::latest_events::LatestEvents::listen_to_room
484 /// [`LatestEventValue`]: matrix_sdk::latest_events::LatestEventValue
485 pub async fn set_room_subscriptions(&self, room_ids: &[&RoomId]) {
486 // Read the state before the await: the state machine can drift meanwhile.
487 let cancel_in_flight_request = self.must_cancel_in_flight_request();
488
489 self.listen_to_latest_events(room_ids).await;
490
491 self.sliding_sync.set_room_subscriptions(
492 room_ids,
493 Some(room_subscription_settings()),
494 cancel_in_flight_request,
495 )
496 }
497
498 /// Remove the room subscriptions of `room_ids`.
499 ///
500 /// The latest events of these rooms are still listened to.
501 pub fn remove_room_subscriptions(&self, room_ids: &[&RoomId]) {
502 self.sliding_sync.remove_room_subscriptions(room_ids, self.must_cancel_in_flight_request())
503 }
504
505 /// Remove all the room subscriptions, then subscribe to `room_ids`.
506 ///
507 /// Contrary to [`Self::set_room_subscriptions`], the members of every room
508 /// of `room_ids` are marked as missing, so that they are re-fetched.
509 pub async fn reset_and_add_room_subscriptions(&self, room_ids: &[&RoomId]) {
510 // Read the state before the await: the state machine can drift meanwhile.
511 let cancel_in_flight_request = self.must_cancel_in_flight_request();
512
513 self.listen_to_latest_events(room_ids).await;
514
515 self.sliding_sync.reset_and_add_room_subscriptions(
516 room_ids,
517 Some(room_subscription_settings()),
518 cancel_in_flight_request,
519 )
520 }
521
522 async fn listen_to_latest_events(&self, room_ids: &[&RoomId]) {
523 if !self.client.event_cache().has_subscribed() {
524 return;
525 }
526
527 let latest_events = self.client.latest_events().await;
528
529 for room_id in room_ids {
530 if let Err(error) = latest_events.listen_to_room(room_id).await {
531 // A failure here must not fail the room subscription.
532 error!(?error, ?room_id, "Failed to listen to the latest event for this room");
533 }
534 }
535 }
536
537 fn must_cancel_in_flight_request(&self) -> bool {
538 match self.state_machine.get() {
539 State::Init | State::Recovering | State::Error { .. } | State::Terminated { .. } => {
540 false
541 }
542 State::SettingUp | State::Running => true,
543 }
544 }
545
546 #[cfg(test)]
547 pub fn sliding_sync(&self) -> &SlidingSync {
548 &self.sliding_sync
549 }
550}
551
552fn room_subscription_settings() -> http::request::RoomSubscription {
553 assign!(http::request::RoomSubscription::default(), {
554 required_state: DEFAULT_REQUIRED_STATE.iter().map(|(state_event, value)| {
555 (state_event.clone(), (*value).to_owned())
556 })
557 .chain(
558 DEFAULT_ROOM_SUBSCRIPTION_EXTRA_REQUIRED_STATE.iter().map(|(state_event, value)| {
559 (state_event.clone(), (*value).to_owned())
560 })
561 )
562 .collect(),
563 timeline_limit: UInt::from(DEFAULT_ROOM_SUBSCRIPTION_TIMELINE_LIMIT),
564 })
565}
566
567/// [`RoomList`]'s errors.
568#[derive(Debug, Error)]
569pub enum Error {
570 /// Error from [`matrix_sdk::SlidingSync`].
571 #[error(transparent)]
572 SlidingSync(SlidingSyncError),
573
574 /// An operation has been requested on an unknown list.
575 #[error("Unknown list `{0}`")]
576 UnknownList(String),
577
578 /// The requested room doesn't exist.
579 #[error("Room `{0}` not found")]
580 RoomNotFound(OwnedRoomId),
581
582 #[error(transparent)]
583 EventCache(#[from] EventCacheError),
584}
585
586/// An hint whether a _sync spinner/loader/toaster_ should be prompted to the
587/// user, indicating that the [`RoomListService`] is syncing.
588///
589/// This is entirely arbitrary and optinionated. Of course, once
590/// [`RoomListService::sync`] has been called, it's going to be constantly
591/// syncing, until [`RoomListService::stop_sync`] is called, or until an error
592/// happened. But in some cases, it's better for the user experience to prompt
593/// to the user that a sync is happening. It's usually the first sync, or the
594/// recovering sync. However, the sync indicator must be prompted if the
595/// aforementioned sync is “slow”, otherwise the indicator is likely to “blink”
596/// pretty fast, which can be very confusing. It's also common to indicate to
597/// the user that a syncing is happening in case of a network error, that
598/// something is catching up etc.
599#[derive(Debug, Eq, PartialEq)]
600pub enum SyncIndicator {
601 /// Show the sync indicator.
602 Show,
603
604 /// Hide the sync indicator.
605 Hide,
606}
607
608#[cfg(test)]
609mod tests {
610 use std::future::ready;
611
612 use futures_util::{StreamExt, pin_mut};
613 use matrix_sdk::{SlidingSyncMode, test_utils::mocks::MatrixMockServer};
614 use matrix_sdk_test::{TestError, async_test};
615 use ruma::{api::client::sync::sync_events::v5, assign, uint};
616
617 use super::{ALL_ROOMS_LIST_NAME, Error, RoomListService, State};
618
619 #[async_test]
620 async fn test_all_rooms_are_declared() -> Result<(), TestError> {
621 let server = MatrixMockServer::new().await;
622 let client = server.client_builder().build().await;
623 let room_list = RoomListService::new(client).await?;
624
625 let sliding_sync = room_list.sliding_sync();
626
627 // List is present, in Selective mode.
628 assert_eq!(
629 sliding_sync
630 .on_list(ALL_ROOMS_LIST_NAME, |list| ready(matches!(
631 list.sync_mode(),
632 SlidingSyncMode::Selective { ranges } if ranges == vec![0..=19]
633 )))
634 .await,
635 Some(true)
636 );
637
638 Ok(())
639 }
640
641 #[async_test]
642 async fn test_expire_sliding_sync_session_manually() -> Result<(), Error> {
643 let server = MatrixMockServer::new().await;
644 let client = server.client_builder().build().await;
645
646 let room_list = RoomListService::new(client).await?;
647
648 let sync = room_list.sync();
649 pin_mut!(sync);
650
651 // Run a first sync.
652 {
653 let _mock_guard = server
654 .mock_sliding_sync()
655 .ok({
656 let mut response = v5::Response::new("0".to_owned());
657 response.lists.insert(
658 ALL_ROOMS_LIST_NAME.to_owned(),
659 assign!(v5::response::List::default(), { count: uint!(0) }),
660 );
661 response
662 })
663 .mount_as_scoped()
664 .await;
665
666 let _ = sync.next().await;
667 }
668
669 assert_eq!(room_list.state().get(), State::SettingUp);
670
671 // Stop the sync.
672 room_list.stop_sync()?;
673
674 // Do another sync.
675 let _ = sync.next().await;
676
677 // State is `Terminated`, as expected!
678 assert_eq!(
679 room_list.state_machine.get(),
680 State::Terminated { from: Box::new(State::Running) }
681 );
682
683 // Now, let's make the sliding sync session to expire.
684 room_list.expire_sync_session().await;
685
686 // State is `Error`, as a regular session expiration would generate!
687 assert_eq!(room_list.state_machine.get(), State::Error { from: Box::new(State::Running) });
688
689 Ok(())
690 }
691}