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