Skip to main content

matrix_sdk/config/
sync.rs

1// Copyright 2021 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 the specific language governing permissions and
13// limitations under the License.
14
15use std::{fmt, time::Duration};
16
17use matrix_sdk_common::debug::DebugStructExt;
18use ruma::{api::client::sync::sync_events, presence::PresenceState};
19
20const DEFAULT_SYNC_TIMEOUT: Duration = Duration::from_secs(30);
21
22/// Token to be used in the next sync request.
23#[derive(Clone, Default, Debug)]
24pub enum SyncToken {
25    /// Provide a specific token.
26    Specific(String),
27    /// Enforce no tokens at all.
28    NoToken,
29    /// Use a previous token if the client saw one in the past, and none
30    /// otherwise.
31    ///
32    /// This is the default value.
33    #[default]
34    ReusePrevious,
35}
36
37impl<T> From<T> for SyncToken
38where
39    T: Into<String>,
40{
41    fn from(token: T) -> SyncToken {
42        SyncToken::Specific(token.into())
43    }
44}
45
46impl SyncToken {
47    /// Convert a token that may exist into a [`SyncToken`]
48    pub fn from_optional_token(maybe_token: Option<String>) -> SyncToken {
49        match maybe_token {
50            Some(token) => SyncToken::Specific(token),
51            None => SyncToken::default(),
52        }
53    }
54}
55
56/// Settings for a sync call.
57#[derive(Clone)]
58pub struct SyncSettings {
59    // Filter is pretty big at 1000 bytes, box it to reduce stack size
60    pub(crate) filter: Option<Box<sync_events::v3::Filter>>,
61    pub(crate) timeout: Option<Duration>,
62    pub(crate) ignore_timeout_on_first_sync: bool,
63    /// Whether sync should be throttled, if the server sends responses too
64    /// fast.
65    pub(crate) throttle_sync_loop: bool,
66    pub(crate) token: SyncToken,
67    pub(crate) full_state: bool,
68    pub(crate) set_presence: Option<PresenceState>,
69}
70
71impl Default for SyncSettings {
72    fn default() -> Self {
73        Self::new()
74    }
75}
76
77#[cfg(not(tarpaulin_include))]
78impl fmt::Debug for SyncSettings {
79    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
80        let Self {
81            filter,
82            timeout,
83            ignore_timeout_on_first_sync,
84            token: _,
85            full_state,
86            set_presence,
87            throttle_sync_loop,
88        } = self;
89        f.debug_struct("SyncSettings")
90            .maybe_field("filter", filter)
91            .maybe_field("timeout", timeout)
92            .field("ignore_timeout_on_first_sync", ignore_timeout_on_first_sync)
93            .field("throttle_sync_loop", throttle_sync_loop)
94            .field("full_state", full_state)
95            .maybe_field("set_presence", set_presence)
96            .finish()
97    }
98}
99
100impl SyncSettings {
101    /// Create new default sync settings.
102    #[must_use]
103    pub fn new() -> Self {
104        Self {
105            filter: None,
106            timeout: Some(DEFAULT_SYNC_TIMEOUT),
107            ignore_timeout_on_first_sync: false,
108            throttle_sync_loop: true,
109            token: SyncToken::default(),
110            full_state: false,
111            set_presence: None,
112        }
113    }
114
115    /// Set the sync token.
116    ///
117    /// # Arguments
118    ///
119    /// * `token` - The sync token that should be used for the sync call.
120    #[must_use]
121    pub fn token(mut self, token: impl Into<SyncToken>) -> Self {
122        self.token = token.into();
123        self
124    }
125
126    /// Set the maximum time the server can wait, in milliseconds, before
127    /// responding to the sync request.
128    ///
129    /// # Arguments
130    ///
131    /// - `timeout` - The time the server is allowed to wait.
132    #[must_use]
133    pub fn timeout(mut self, timeout: Duration) -> Self {
134        self.timeout = Some(timeout);
135        self
136    }
137
138    /// Whether to throttle sync loops.
139    ///
140    /// By default, in sync loops, sync requests are throttled and sent at most
141    /// once per second, even if the server responds faster than this. This
142    /// behavior can be controlled using the `value` parameter passed here.
143    ///
144    /// This setting is only active when using one of the sync loop methods:
145    /// - [`crate::Client::sync()`],
146    /// - [`crate::Client::sync_with_callback`]
147    /// - [`crate::Client::sync_with_result_callback`]
148    /// - [`crate::Client::sync_stream`]
149    pub fn throttle_sync_loop(mut self, value: bool) -> Self {
150        self.throttle_sync_loop = value;
151        self
152    }
153
154    /// Whether to ignore the `timeout` the first time that the `/sync` endpoint
155    /// is called.
156    ///
157    /// If there is no new data to show, the server will wait until the end of
158    /// `timeout` before returning a response. It can be an undesirable behavior
159    /// when starting a client and informing the user that we are "catching up"
160    /// while waiting for the first response.
161    ///
162    /// By not setting a `timeout` on the first request to `/sync`, the
163    /// homeserver should reply immediately, whether the response is empty or
164    /// not.
165    ///
166    /// Note that this setting is ignored when calling [`Client::sync_once()`],
167    /// because there is no loop happening.
168    ///
169    /// # Arguments
170    ///
171    /// - `ignore` - Whether to ignore the `timeout` the first time that the
172    ///   `/sync` endpoint is called.
173    ///
174    /// [`Client::sync_once()`]: crate::Client::sync_once
175    #[must_use]
176    pub fn ignore_timeout_on_first_sync(mut self, ignore: bool) -> Self {
177        self.ignore_timeout_on_first_sync = ignore;
178        self
179    }
180
181    /// Set the sync filter. It can be either the filter ID, or the definition
182    /// for the filter.
183    ///
184    /// # Arguments
185    ///
186    /// - `filter` - The filter configuration that should be used for the sync
187    ///   call.
188    #[must_use]
189    pub fn filter(mut self, filter: sync_events::v3::Filter) -> Self {
190        self.filter = Some(Box::new(filter));
191        self
192    }
193
194    /// Should the server return the full state from the start of the timeline.
195    ///
196    /// This does nothing if no sync token is set.
197    ///
198    /// # Arguments
199    ///
200    /// - `full_state` - A boolean deciding if the server should return the full
201    ///   state or not.
202    #[must_use]
203    pub fn full_state(mut self, full_state: bool) -> Self {
204        self.full_state = full_state;
205        self
206    }
207
208    /// Override the presence state for this classic `/sync` request.
209    ///
210    /// If this is not set, the request uses the client-owned sync presence
211    /// value configured with [`Client::set_presence`]. The client default is
212    /// [`PresenceState::Online`].
213    ///
214    /// `PresenceState::Online` - The client is marked as being online. This is
215    /// the active preset and client default.
216    ///
217    /// `PresenceState::Offline` - The client is not marked as being online.
218    ///
219    /// `PresenceState::Unavailable` - The client is marked as being idle. This
220    /// is the idle preset.
221    ///
222    /// Sliding Sync requests do not use this per-request setting; they read the
223    /// client-owned sync presence value directly.
224    ///
225    /// # Arguments
226    ///
227    /// - `set_presence` - The `PresenceState` that the server should set for
228    ///   the client.
229    ///
230    /// [`Client::set_presence`]: crate::Client::set_presence
231    #[must_use]
232    pub fn set_presence(mut self, presence: PresenceState) -> Self {
233        self.set_presence = Some(presence);
234        self
235    }
236}