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