Skip to main content

matrix_sdk/sliding_sync/
builder.rs

1use std::{
2    collections::BTreeMap,
3    fmt::Debug,
4    sync::{Arc, RwLock as StdRwLock},
5    time::Duration,
6};
7
8use matrix_sdk_common::timer;
9use ruma::{OwnedRoomId, api::client::sync::sync_events::msc4186 as http};
10use tokio::sync::{Mutex as AsyncMutex, RwLock as AsyncRwLock, broadcast::channel};
11
12use super::{
13    Error, SlidingSync, SlidingSyncInner, SlidingSyncListBuilder, SlidingSyncPositionMarkers,
14    Version, cache::format_storage_key_prefix,
15};
16use crate::{Client, Result};
17
18/// Configuration for a Sliding Sync instance.
19///
20/// Get a new builder with methods like [`crate::Client::sliding_sync`], or
21/// [`crate::SlidingSync::builder`].
22#[derive(Debug, Clone)]
23pub struct SlidingSyncBuilder {
24    id: String,
25    storage_key: String,
26    version: Option<Version>,
27    client: Client,
28    lists: Vec<SlidingSyncListBuilder>,
29    extensions: Option<http::request::Extensions>,
30    room_subscriptions: BTreeMap<OwnedRoomId, http::request::RoomSubscription>,
31    poll_timeout: Duration,
32    network_timeout: Duration,
33    #[cfg(feature = "e2e-encryption")]
34    share_pos: bool,
35}
36
37impl SlidingSyncBuilder {
38    pub(super) fn new(id: String, client: Client) -> Result<Self, Error> {
39        if id.len() > 16 {
40            Err(Error::InvalidSlidingSyncIdentifier)
41        } else {
42            let storage_key =
43                format_storage_key_prefix(&id, client.user_id().ok_or(Error::UnauthenticatedUser)?);
44
45            Ok(Self {
46                id,
47                storage_key,
48                version: None,
49                client,
50                lists: Vec::new(),
51                extensions: None,
52                room_subscriptions: BTreeMap::new(),
53                poll_timeout: Duration::from_secs(30),
54                network_timeout: Duration::from_secs(30),
55                #[cfg(feature = "e2e-encryption")]
56                share_pos: false,
57            })
58        }
59    }
60
61    /// Set a specific version that will override the one from the [`Client`].
62    pub fn version(mut self, version: Version) -> Self {
63        self.version = Some(version);
64        self
65    }
66
67    /// Add the given list to the lists.
68    ///
69    /// Replace any list with the same name.
70    pub fn add_list(mut self, list_builder: SlidingSyncListBuilder) -> Self {
71        self.lists.push(list_builder);
72        self
73    }
74
75    /// Enroll the list in caching, reloads it from the cache if possible, and
76    /// adds it to the list of lists.
77    ///
78    /// This will raise an error if there was a I/O error reading from the
79    /// cache.
80    ///
81    /// Replace any list with the same name.
82    pub async fn add_cached_list(self, mut list: SlidingSyncListBuilder) -> Result<Self> {
83        let _timer = timer!(format!("restoring (loading+processing) list {}", list.name));
84
85        list.set_cached_and_reload(&self.client, &self.storage_key).await?;
86
87        Ok(self.add_list(list))
88    }
89
90    /// Activate e2ee, to-device-message, account data, typing, receipt and
91    /// (if compiled in) sticky events extensions if not yet configured.
92    ///
93    /// Will leave any extension configuration found untouched, so the order
94    /// does not matter.
95    pub fn with_all_extensions(mut self) -> Self {
96        {
97            let cfg = self.extensions.get_or_insert_with(Default::default);
98            cfg.to_device.enabled = true;
99            cfg.e2ee.enabled = true;
100
101            if cfg.account_data.enabled.is_none() {
102                cfg.account_data.enabled = Some(true);
103            }
104
105            if cfg.receipts.enabled.is_none() {
106                cfg.receipts.enabled = Some(true);
107            }
108
109            if cfg.typing.enabled.is_none() {
110                cfg.typing.enabled = Some(true);
111            }
112
113            #[cfg(feature = "unstable-msc4354")]
114            if cfg.sticky_events.enabled.is_none() {
115                cfg.sticky_events.enabled = Some(true);
116            }
117        }
118        self
119    }
120
121    /// Set the E2EE extension configuration.
122    pub fn with_e2ee_extension(mut self, e2ee: http::request::E2EE) -> Self {
123        self.extensions.get_or_insert_with(Default::default).e2ee = e2ee;
124        self
125    }
126
127    /// Unset the E2EE extension configuration.
128    pub fn without_e2ee_extension(mut self) -> Self {
129        self.extensions.get_or_insert_with(Default::default).e2ee = http::request::E2EE::default();
130        self
131    }
132
133    /// Set the ToDevice extension configuration.
134    pub fn with_to_device_extension(mut self, to_device: http::request::ToDevice) -> Self {
135        self.extensions.get_or_insert_with(Default::default).to_device = to_device;
136        self
137    }
138
139    /// Unset the ToDevice extension configuration.
140    pub fn without_to_device_extension(mut self) -> Self {
141        self.extensions.get_or_insert_with(Default::default).to_device =
142            http::request::ToDevice::default();
143        self
144    }
145
146    /// Set the account data extension configuration.
147    pub fn with_account_data_extension(mut self, account_data: http::request::AccountData) -> Self {
148        self.extensions.get_or_insert_with(Default::default).account_data = account_data;
149        self
150    }
151
152    /// Unset the account data extension configuration.
153    pub fn without_account_data_extension(mut self) -> Self {
154        self.extensions.get_or_insert_with(Default::default).account_data =
155            http::request::AccountData::default();
156        self
157    }
158
159    /// Set the Typing extension configuration.
160    pub fn with_typing_extension(mut self, typing: http::request::Typing) -> Self {
161        self.extensions.get_or_insert_with(Default::default).typing = typing;
162        self
163    }
164
165    /// Unset the Typing extension configuration.
166    pub fn without_typing_extension(mut self) -> Self {
167        self.extensions.get_or_insert_with(Default::default).typing =
168            http::request::Typing::default();
169        self
170    }
171
172    /// Set the Receipt extension configuration.
173    pub fn with_receipt_extension(mut self, receipt: http::request::Receipts) -> Self {
174        self.extensions.get_or_insert_with(Default::default).receipts = receipt;
175        self
176    }
177
178    /// Unset the Receipt extension configuration.
179    pub fn without_receipt_extension(mut self) -> Self {
180        self.extensions.get_or_insert_with(Default::default).receipts =
181            http::request::Receipts::default();
182        self
183    }
184
185    /// Set the Threads subscriptions extension configuration.
186    pub fn with_thread_subscriptions_extension(
187        mut self,
188        thread_subscriptions: http::request::ThreadSubscriptions,
189    ) -> Self {
190        self.extensions.get_or_insert_with(Default::default).thread_subscriptions =
191            thread_subscriptions;
192        self
193    }
194
195    /// Unset the Threads subscriptions extension configuration.
196    pub fn without_thread_subscriptions_extension(mut self) -> Self {
197        self.extensions.get_or_insert_with(Default::default).thread_subscriptions =
198            Default::default();
199        self
200    }
201
202    /// Set the Profiles extension configuration.
203    pub fn with_profiles_extension(mut self, profiles: http::request::Profiles) -> Self {
204        self.extensions.get_or_insert_with(Default::default).profiles = profiles;
205        self
206    }
207
208    /// Unset the Profiles extension configuration.
209    pub fn without_profiles_extension(mut self) -> Self {
210        self.extensions.get_or_insert_with(Default::default).profiles = Default::default();
211        self
212    }
213
214    /// Set the sticky events (MSC4480) extension configuration.
215    ///
216    /// The `since` token of the extension is managed by the sliding sync
217    /// itself, any value set here is ignored.
218    #[cfg(feature = "unstable-msc4354")]
219    pub fn with_sticky_events_extension(
220        mut self,
221        sticky_events: http::request::StickyEvents,
222    ) -> Self {
223        self.extensions.get_or_insert_with(Default::default).sticky_events = sticky_events;
224        self
225    }
226
227    /// Unset the sticky events (MSC4480) extension configuration.
228    #[cfg(feature = "unstable-msc4354")]
229    pub fn without_sticky_events_extension(mut self) -> Self {
230        self.extensions.get_or_insert_with(Default::default).sticky_events = Default::default();
231        self
232    }
233
234    /// Sets a custom timeout duration for the sliding sync polling endpoint.
235    ///
236    /// This is the maximum time to wait before the sliding sync server returns
237    /// the long-polling request. If no events (or other data) become available
238    /// before this time elapses, the server will a return a response with empty
239    /// fields.
240    ///
241    /// There's an additional network timeout on top of that that can be
242    /// configured with [`Self::network_timeout`].
243    pub fn poll_timeout(mut self, timeout: Duration) -> Self {
244        self.poll_timeout = timeout;
245        self
246    }
247
248    /// Sets a custom network timeout for the sliding sync polling.
249    ///
250    /// This is not the polling timeout that can be configured with
251    /// [`Self::poll_timeout`], but an additional timeout that will be added to
252    /// the former.
253    pub fn network_timeout(mut self, timeout: Duration) -> Self {
254        self.network_timeout = timeout;
255        self
256    }
257
258    /// Should the sliding sync instance share its sync position through
259    /// storage?
260    ///
261    /// In general, sliding sync instances will cache the sync position (`pos`
262    /// field in the request) in internal memory. It can be useful, in
263    /// multi-process scenarios, to save it into some shared storage so that one
264    /// sliding sync instance running across two different processes can
265    /// continue with the same sync position it had before being stopped.
266    #[cfg(feature = "e2e-encryption")]
267    pub fn share_pos(mut self) -> Self {
268        self.share_pos = true;
269        self
270    }
271
272    /// Build the Sliding Sync.
273    #[allow(clippy::unused_async)] // Async is only used if the e2e-encryption feature is enabled.
274    pub async fn build(self) -> Result<SlidingSync> {
275        let client = self.client;
276
277        let version = self.version.unwrap_or_else(|| client.sliding_sync_version());
278
279        if matches!(version, Version::None) {
280            return Err(crate::error::Error::SlidingSync(Box::new(Error::VersionIsMissing)));
281        }
282
283        let (internal_channel_sender, _internal_channel_receiver) = channel(8);
284
285        let mut lists = BTreeMap::new();
286
287        for list_builder in self.lists {
288            let list = list_builder.build(internal_channel_sender.clone());
289
290            lists.insert(list.name().to_owned(), list);
291        }
292
293        let (share_pos, pos) = {
294            cfg_select! {
295                feature = "e2e-encryption" => {
296                    if self.share_pos {
297                        // If the sliding sync instance is configured to share
298                        // its current sync position, we will restore it from
299                        // the cache.
300                        (
301                            true,
302                            super::cache::restore_sliding_sync_state(&client, &self.storage_key)
303                                .await?
304                                .and_then(|fields| fields.pos),
305                        )
306                    } else {
307                        (false, None)
308                    }
309                }
310                _ => (false, None),
311            }
312        };
313
314        let lists = AsyncRwLock::new(lists);
315
316        Ok(SlidingSync::new(SlidingSyncInner {
317            id: self.id,
318
319            client,
320            storage_key: self.storage_key,
321            share_pos,
322
323            lists,
324
325            position: Arc::new(AsyncMutex::new(SlidingSyncPositionMarkers { pos })),
326
327            room_subscriptions: StdRwLock::new(self.room_subscriptions),
328            extensions: self.extensions.unwrap_or_default(),
329
330            internal_channel: internal_channel_sender,
331
332            poll_timeout: self.poll_timeout,
333            network_timeout: self.network_timeout,
334        }))
335    }
336}