matrix_sdk/sliding_sync/list/
builder.rs

1//! Builder for [`SlidingSyncList`].
2
3use std::{
4    convert::identity,
5    fmt,
6    sync::{Arc, RwLock as StdRwLock},
7};
8
9use eyeball::{Observable, SharedObservable};
10use ruma::{api::client::sync::sync_events::v5 as http, events::StateEventType};
11use tokio::sync::broadcast::Sender;
12
13use super::{
14    super::SlidingSyncInternalMessage, Bound, SlidingSyncList, SlidingSyncListCachePolicy,
15    SlidingSyncListInner, SlidingSyncListLoadingState, SlidingSyncListRequestGenerator,
16    SlidingSyncListStickyParameters, SlidingSyncMode,
17};
18use crate::{
19    sliding_sync::{cache::restore_sliding_sync_list, sticky_parameters::SlidingSyncStickyManager},
20    Client,
21};
22
23/// Data that might have been read from the cache.
24#[derive(Clone)]
25struct SlidingSyncListCachedData {
26    /// Total number of rooms that is possible to interact with the given list.
27    /// See also comment of [`SlidingSyncList::maximum_number_of_rooms`].
28    /// May be reloaded from the cache.
29    maximum_number_of_rooms: Option<u32>,
30}
31
32/// Builder for [`SlidingSyncList`].
33#[derive(Clone)]
34pub struct SlidingSyncListBuilder {
35    sync_mode: SlidingSyncMode,
36    required_state: Vec<(StateEventType, String)>,
37    include_heroes: Option<bool>,
38    filters: Option<http::request::ListFilters>,
39    timeline_limit: Bound,
40    pub(crate) name: String,
41
42    /// Should this list be cached and reloaded from the cache?
43    cache_policy: SlidingSyncListCachePolicy,
44
45    /// If set, temporary data that's been read from the cache, reloaded from a
46    /// `FrozenSlidingSyncList`.
47    reloaded_cached_data: Option<SlidingSyncListCachedData>,
48
49    once_built: Arc<Box<dyn Fn(SlidingSyncList) -> SlidingSyncList + Send + Sync>>,
50}
51
52#[cfg(not(tarpaulin_include))]
53impl fmt::Debug for SlidingSyncListBuilder {
54    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
55        // Print debug values for the builder, except `once_built` which is ignored.
56        formatter
57            .debug_struct("SlidingSyncListBuilder")
58            .field("sync_mode", &self.sync_mode)
59            .field("required_state", &self.required_state)
60            .field("include_heroes", &self.include_heroes)
61            .field("filters", &self.filters)
62            .field("timeline_limit", &self.timeline_limit)
63            .field("name", &self.name)
64            .finish_non_exhaustive()
65    }
66}
67
68impl SlidingSyncListBuilder {
69    pub(super) fn new(name: impl Into<String>) -> Self {
70        Self {
71            sync_mode: SlidingSyncMode::default(),
72            required_state: vec![
73                (StateEventType::RoomEncryption, "".to_owned()),
74                (StateEventType::RoomTombstone, "".to_owned()),
75            ],
76            include_heroes: None,
77            filters: None,
78            timeline_limit: 1,
79            name: name.into(),
80            reloaded_cached_data: None,
81            cache_policy: SlidingSyncListCachePolicy::Disabled,
82            once_built: Arc::new(Box::new(identity)),
83        }
84    }
85
86    /// Runs a callback once the list has been built.
87    ///
88    /// If the list was cached, then the cached fields won't be available in
89    /// this callback. Use the streams to get published versions of the
90    /// cached fields, once they've been set.
91    pub fn once_built<C>(mut self, callback: C) -> Self
92    where
93        C: Fn(SlidingSyncList) -> SlidingSyncList + Send + Sync + 'static,
94    {
95        self.once_built = Arc::new(Box::new(callback));
96        self
97    }
98
99    /// Which SlidingSyncMode to start this list under.
100    pub fn sync_mode(mut self, value: impl Into<SlidingSyncMode>) -> Self {
101        self.sync_mode = value.into();
102        self
103    }
104
105    /// Required states to return per room.
106    pub fn required_state(mut self, value: Vec<(StateEventType, String)>) -> Self {
107        self.required_state = value;
108        self
109    }
110
111    /// Include heroes.
112    pub fn include_heroes(mut self, value: Option<bool>) -> Self {
113        self.include_heroes = value;
114        self
115    }
116
117    /// Any filters to apply to the query.
118    pub fn filters(mut self, value: Option<http::request::ListFilters>) -> Self {
119        self.filters = value;
120        self
121    }
122
123    /// Set the limit of regular events to fetch for the timeline.
124    pub fn timeline_limit(mut self, timeline_limit: Bound) -> Self {
125        self.timeline_limit = timeline_limit;
126        self
127    }
128
129    /// Set the limit of regular events to fetch for the timeline to 0.
130    pub fn no_timeline_limit(mut self) -> Self {
131        self.timeline_limit = 0;
132        self
133    }
134
135    /// Marks this list as sync'd from the cache, and attempts to reload it from
136    /// storage.
137    ///
138    /// Returns a mapping of the room's data read from the cache, to be
139    /// incorporated into the `SlidingSync` bookkeepping.
140    pub(in super::super) async fn set_cached_and_reload(
141        &mut self,
142        client: &Client,
143        storage_key: &str,
144    ) -> crate::Result<()> {
145        self.cache_policy = SlidingSyncListCachePolicy::Enabled;
146
147        if let Some(frozen_list) =
148            restore_sliding_sync_list(client.store(), storage_key, &self.name).await?
149        {
150            assert!(
151                self.reloaded_cached_data.is_none(),
152                "can't call `set_cached_and_reload` twice"
153            );
154            self.reloaded_cached_data = Some(SlidingSyncListCachedData {
155                maximum_number_of_rooms: frozen_list.maximum_number_of_rooms,
156            });
157            Ok(())
158        } else {
159            Ok(())
160        }
161    }
162
163    /// Build the list.
164    pub(in super::super) fn build(
165        self,
166        sliding_sync_internal_channel_sender: Sender<SlidingSyncInternalMessage>,
167    ) -> SlidingSyncList {
168        let list = SlidingSyncList {
169            inner: Arc::new(SlidingSyncListInner {
170                #[cfg(any(test, feature = "testing"))]
171                sync_mode: StdRwLock::new(self.sync_mode.clone()),
172
173                // From the builder
174                sticky: StdRwLock::new(SlidingSyncStickyManager::new(
175                    SlidingSyncListStickyParameters::new(
176                        self.required_state,
177                        self.include_heroes,
178                        self.filters,
179                    ),
180                )),
181                timeline_limit: StdRwLock::new(self.timeline_limit),
182                name: self.name,
183                cache_policy: self.cache_policy,
184
185                // Computed from the builder.
186                request_generator: StdRwLock::new(SlidingSyncListRequestGenerator::new(
187                    self.sync_mode,
188                )),
189
190                // Values read from deserialization, or that are still equal to the default values
191                // otherwise.
192                state: StdRwLock::new(Observable::new(Default::default())),
193                maximum_number_of_rooms: SharedObservable::new(None),
194
195                // Internal data.
196                sliding_sync_internal_channel_sender,
197            }),
198        };
199
200        let once_built = self.once_built;
201
202        let list = once_built(list);
203
204        // If we reloaded from the cache, update values in the list here.
205        //
206        // Note about ordering: because of the contract with the observables, the
207        // initial values, if filled, have to be observable in the `once_built`
208        // callback. That's why we're doing this here *after* constructing the
209        // list, and not a few lines above.
210
211        if let Some(SlidingSyncListCachedData { maximum_number_of_rooms }) =
212            self.reloaded_cached_data
213        {
214            // Mark state as preloaded.
215            Observable::set(
216                &mut list.inner.state.write().unwrap(),
217                SlidingSyncListLoadingState::Preloaded,
218            );
219
220            // Reload the maximum number of rooms.
221            list.inner.maximum_number_of_rooms.set(maximum_number_of_rooms);
222        }
223
224        list
225    }
226}