Skip to main content

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