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