Skip to main content

matrix_sdk/sliding_sync/
mod.rs

1// Copyright 2022-2023 Benjamin Kampmann
2// Copyright 2022 The Matrix.org Foundation C.I.C.
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8//     http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for that specific language governing permissions and
14// limitations under the License.
15
16#![doc = include_str!("README.md")]
17
18mod builder;
19mod cache;
20mod client;
21mod error;
22mod list;
23
24use std::{
25    collections::{BTreeMap, btree_map::Entry},
26    fmt::Debug,
27    future::Future,
28    sync::{Arc, RwLock as StdRwLock},
29    time::Duration,
30};
31
32use async_stream::stream;
33pub use client::{Version, VersionBuilder};
34use futures_core::stream::Stream;
35use matrix_sdk_base::RequestedRequiredStates;
36#[cfg(feature = "e2e-encryption")]
37use matrix_sdk_common::executor::JoinHandleExt as _;
38use matrix_sdk_common::{executor::spawn, timer};
39#[cfg(feature = "e2e-encryption")]
40use ruma::api::error::{ErrorBody, StandardErrorBody};
41use ruma::{
42    OwnedRoomId, RoomId,
43    api::{client::sync::sync_events::msc4186 as http, error::ErrorKind},
44    assign,
45};
46use tokio::{
47    select,
48    sync::{Mutex as AsyncMutex, OwnedMutexGuard, RwLock as AsyncRwLock, broadcast::Sender},
49};
50use tracing::{Instrument, Span, debug, error, info, instrument, trace, warn};
51
52pub use self::{builder::*, client::VersionBuilderError, error::*, list::*};
53use self::{cache::restore_sliding_sync_state, client::SlidingSyncResponseProcessor};
54use crate::{Client, Result, config::RequestConfig};
55
56/// The Sliding Sync instance.
57///
58/// It is OK to clone this type as much as you need: cloning it is cheap.
59#[derive(Clone, Debug)]
60pub struct SlidingSync {
61    /// The Sliding Sync data.
62    inner: Arc<SlidingSyncInner>,
63}
64
65#[derive(Debug)]
66pub(super) struct SlidingSyncInner {
67    /// A unique identifier for this instance of sliding sync.
68    ///
69    /// Used to distinguish different connections to sliding sync.
70    id: String,
71
72    /// The HTTP Matrix client.
73    client: Client,
74
75    /// Long-polling timeout that appears in sliding sync request.
76    poll_timeout: Duration,
77
78    /// Extra duration for the sliding sync request to timeout. This is added to
79    /// the [`Self::poll_timeout`].
80    network_timeout: Duration,
81
82    /// The storage key to keep this cache at and load it from.
83    storage_key: String,
84
85    /// Should this sliding sync instance try to restore its sync position from
86    /// the database?
87    ///
88    /// Note: in non-cfg(e2e-encryption) builds, it's always set to false. We
89    /// keep it even so, to avoid sparkling cfg statements everywhere throughout
90    /// this file.
91    share_pos: bool,
92
93    /// Position markers.
94    ///
95    /// The `pos` marker represents a progression when exchanging requests and
96    /// responses with the server: the server acknowledges the request by
97    /// responding with a new `pos`. If the client sends two non-necessarily
98    /// consecutive requests with the same `pos`, the server has to reply with
99    /// the same identical response.
100    ///
101    /// `position` is behind a mutex so that a new request starts after the
102    /// previous request trip has fully ended (successfully or not). This
103    /// mechanism exists to wait for the response to be handled and to see the
104    /// `position` being updated, before sending a new request.
105    position: Arc<AsyncMutex<SlidingSyncPositionMarkers>>,
106
107    /// The lists of this Sliding Sync instance.
108    lists: AsyncRwLock<BTreeMap<String, SlidingSyncList>>,
109
110    /// Room subscriptions, i.e. rooms that may be out-of-scope of all lists but
111    /// one wants to receive updates.
112    room_subscriptions: StdRwLock<BTreeMap<OwnedRoomId, http::request::RoomSubscription>>,
113
114    /// The intended state of the extensions being supplied to sliding /sync
115    /// calls.
116    extensions: http::request::Extensions,
117
118    /// Internal channel used to pass messages between Sliding Sync and other
119    /// types.
120    internal_channel: Sender<SlidingSyncInternalMessage>,
121}
122
123impl SlidingSync {
124    pub(super) fn new(inner: SlidingSyncInner) -> Self {
125        Self { inner: Arc::new(inner) }
126    }
127
128    async fn cache_to_storage(&self, position: &SlidingSyncPositionMarkers) -> Result<()> {
129        cache::store_sliding_sync_state(self, position).await
130    }
131
132    /// Create a new [`SlidingSyncBuilder`].
133    pub fn builder(id: String, client: Client) -> Result<SlidingSyncBuilder, Error> {
134        SlidingSyncBuilder::new(id, client)
135    }
136
137    /// Add a subscription for each room of `room_ids`, and keep the existing
138    /// subscriptions to other rooms.
139    ///
140    /// If the associated `Room`s exist, they will be marked as members are
141    /// missing, so that it ensures to re-fetch all members.
142    ///
143    /// A subscription to an already subscribed room only updates its
144    /// `settings`, and only if they differ. In particular, its members are not
145    /// marked as missing again.
146    pub fn add_room_subscriptions(
147        &self,
148        room_ids: &[&RoomId],
149        settings: Option<http::request::RoomSubscription>,
150        cancel_in_flight_request: bool,
151    ) {
152        let subscriptions_have_changed = upsert_room_subscriptions(
153            &mut self.inner.room_subscriptions.write().unwrap(),
154            &self.inner.client,
155            room_ids,
156            settings,
157        );
158
159        if cancel_in_flight_request && subscriptions_have_changed {
160            self.inner.cancel_in_flight_request();
161        }
162    }
163
164    /// Remove the subscription of each room of `room_ids`.
165    pub fn remove_room_subscriptions(&self, room_ids: &[&RoomId], cancel_in_flight_request: bool) {
166        let mut room_subscriptions = self.inner.room_subscriptions.write().unwrap();
167        let mut subscriptions_have_changed = false;
168
169        for room_id in room_ids {
170            if room_subscriptions.remove(*room_id).is_some() {
171                subscriptions_have_changed = true;
172            }
173        }
174
175        if cancel_in_flight_request && subscriptions_have_changed {
176            self.inner.cancel_in_flight_request();
177        }
178    }
179
180    /// Set the room subscriptions to exactly `room_ids`.
181    ///
182    /// This is similar to [`Self::reset_and_add_room_subscriptions`] but
183    /// doesn't clear and then recreate all subscriptions. Instead, it will
184    /// perform a delta-like update which involves:
185    ///
186    /// - refreshing the `settings` of existing subscriptions if the room is
187    ///   contained in `room_ids`, and only if they differ
188    /// - adding new subscriptions for rooms in `room_ids` that are currently
189    ///   unsubscribed
190    /// - removing existing subscriptions for rooms that are not contained in
191    ///   `room_ids`
192    ///
193    /// Note that unlike [`Self::reset_and_add_room_subscriptions`], this method
194    /// will not mark members as unsynced (which would cause them to be
195    /// refetched) for subscriptions that already exist.
196    pub fn set_room_subscriptions(
197        &self,
198        room_ids: &[&RoomId],
199        settings: Option<http::request::RoomSubscription>,
200        cancel_in_flight_request: bool,
201    ) {
202        let mut room_subscriptions = self.inner.room_subscriptions.write().unwrap();
203
204        // Remove the subscriptions to the rooms that are not in `room_ids`
205        // anymore.
206        let number_of_subscriptions_before = room_subscriptions.len();
207        room_subscriptions.retain(|room_id, _| room_ids.contains(&room_id.as_ref()));
208        let a_subscription_has_been_removed =
209            room_subscriptions.len() != number_of_subscriptions_before;
210
211        // Add the subscriptions to the rooms that aren't subscribed yet, and
212        // refresh the settings of the ones that already are.
213        let a_subscription_has_been_added_or_updated = upsert_room_subscriptions(
214            &mut room_subscriptions,
215            &self.inner.client,
216            room_ids,
217            settings,
218        );
219
220        // The in-flight request must be cancelled as soon as the set of
221        // subscriptions has changed.
222        if cancel_in_flight_request
223            && (a_subscription_has_been_added_or_updated || a_subscription_has_been_removed)
224        {
225            self.inner.cancel_in_flight_request();
226        }
227    }
228
229    /// Remove all the room subscriptions, then add a subscription for each room
230    /// of `room_ids`.
231    ///
232    /// If the associated `Room`s exist, they will be marked as members are
233    /// missing, so that it ensures to re-fetch all members.
234    pub fn reset_and_add_room_subscriptions(
235        &self,
236        room_ids: &[&RoomId],
237        settings: Option<http::request::RoomSubscription>,
238        cancel_in_flight_request: bool,
239    ) {
240        let mut room_subscriptions = self.inner.room_subscriptions.write().unwrap();
241
242        let a_subscription_has_been_removed = !room_subscriptions.is_empty();
243        room_subscriptions.clear();
244
245        let a_subscription_has_been_added = upsert_room_subscriptions(
246            &mut room_subscriptions,
247            &self.inner.client,
248            room_ids,
249            settings,
250        );
251
252        if cancel_in_flight_request
253            && (a_subscription_has_been_added || a_subscription_has_been_removed)
254        {
255            self.inner.cancel_in_flight_request();
256        }
257    }
258
259    /// Find a list by its name, and do something on it if it exists.
260    pub async fn on_list<Function, FunctionOutput, R>(
261        &self,
262        list_name: &str,
263        function: Function,
264    ) -> Option<R>
265    where
266        Function: FnOnce(&SlidingSyncList) -> FunctionOutput,
267        FunctionOutput: Future<Output = R>,
268    {
269        let lists = self.inner.lists.read().await;
270
271        match lists.get(list_name) {
272            Some(list) => Some(function(list).await),
273            None => None,
274        }
275    }
276
277    /// Add the list to the list of lists.
278    ///
279    /// As lists need to have a unique `.name`, if a list with the same name is
280    /// found the new list will replace the old one and the return it or `None`.
281    pub async fn add_list(
282        &self,
283        list_builder: SlidingSyncListBuilder,
284    ) -> Result<Option<SlidingSyncList>> {
285        let list = list_builder.build(self.inner.internal_channel.clone());
286
287        let old_list = self.inner.lists.write().await.insert(list.name().to_owned(), list);
288
289        self.inner.internal_channel_send_if_possible(
290            SlidingSyncInternalMessage::SyncLoopSkipOverCurrentIteration,
291        );
292
293        Ok(old_list)
294    }
295
296    /// Add a list that will be cached and reloaded from the cache.
297    ///
298    /// This will raise an error if a storage key was not set, or if there was a
299    /// I/O error reading from the cache.
300    ///
301    /// The rest of the semantics is the same as [`Self::add_list`].
302    pub async fn add_cached_list(
303        &self,
304        mut list_builder: SlidingSyncListBuilder,
305    ) -> Result<Option<SlidingSyncList>> {
306        let _timer = timer!(format!("restoring (loading+processing) list {}", list_builder.name));
307
308        list_builder.set_cached_and_reload(&self.inner.client, &self.inner.storage_key).await?;
309
310        self.add_list(list_builder).await
311    }
312
313    /// Handle the HTTP response.
314    #[instrument(skip_all)]
315    async fn handle_response(
316        &self,
317        mut sliding_sync_response: http::Response,
318        position: &mut SlidingSyncPositionMarkers,
319        requested_required_states: RequestedRequiredStates,
320    ) -> Result<UpdateSummary, crate::Error> {
321        let pos = Some(sliding_sync_response.pos.clone());
322
323        let must_process_rooms_response = self.must_process_rooms_response().await;
324
325        trace!(yes = must_process_rooms_response, "Must process rooms response?");
326
327        // Transform a Sliding Sync Response to a `SyncResponse`.
328        //
329        // We may not need the `sync_response` in the future (once
330        // `SyncResponse` will move to Sliding Sync, i.e. to `http::Response`),
331        // but processing the `sliding_sync_response` is vital, so it must be
332        // done somewhere; for now it happens here.
333
334        let sync_response = {
335            let _timer = timer!("response processor");
336
337            let response_processor = {
338                // Take the lock to synchronise accesses to the state store, to
339                // avoid concurrent sliding syncs overwriting each other's room
340                // infos.
341                let state_store_guard = {
342                    let _timer = timer!("acquiring the `state_store_lock`");
343
344                    self.inner.client.base_client().state_store_lock().lock().await
345                };
346
347                let mut response_processor =
348                    SlidingSyncResponseProcessor::new(self.inner.client.clone());
349
350                // Process thread subscriptions if they're available.
351                //
352                // It's important to do this _before_ handling the room
353                // responses, so that notifications can be properly generated
354                // based on the thread subscriptions, for the events in threads
355                // we've subscribed to.
356                if self.is_thread_subscriptions_enabled() {
357                    response_processor
358                        .handle_thread_subscriptions(
359                            position.pos.as_deref(),
360                            std::mem::take(
361                                &mut sliding_sync_response.extensions.thread_subscriptions,
362                            ),
363                        )
364                        .await?;
365                }
366
367                #[cfg(feature = "e2e-encryption")]
368                if self.is_e2ee_enabled() {
369                    response_processor
370                        .handle_encryption(&sliding_sync_response.extensions, &state_store_guard)
371                        .await?
372                }
373
374                // Only handle the room's subsection of the response, if this
375                // sliding sync was configured to do so.
376                if must_process_rooms_response {
377                    response_processor
378                        .handle_room_response(
379                            &sliding_sync_response,
380                            &requested_required_states,
381                            &state_store_guard,
382                        )
383                        .await?;
384                }
385
386                response_processor
387            };
388
389            // Release the lock before calling event handlers
390            response_processor.process_and_take_response().await?
391        };
392
393        debug!("Sliding Sync response has been handled by the client");
394        trace!(?sync_response);
395
396        let update_summary = {
397            // Update the rooms.
398            let updated_rooms = {
399                let mut updated_rooms = Vec::with_capacity(
400                    sliding_sync_response.rooms.len() + sync_response.rooms.joined.len(),
401                );
402
403                updated_rooms.extend(sliding_sync_response.rooms.keys().cloned());
404
405                // There might be other rooms that were only mentioned in the
406                // sliding sync extensions part of the response, and thus would
407                // result in rooms present in the `sync_response.joined`. Mark
408                // them as updated too.
409                //
410                // Since we've removed rooms that were in the room subsection
411                // from `sync_response.rooms.joined`, the remaining ones aren't
412                // already present in `updated_rooms` and wouldn't cause any
413                // duplicates.
414                updated_rooms.extend(sync_response.rooms.joined.keys().cloned());
415
416                updated_rooms
417            };
418
419            // Update the lists.
420            let updated_lists = {
421                debug!(
422                    lists = ?sliding_sync_response.lists,
423                    "Update lists"
424                );
425
426                let mut updated_lists = Vec::with_capacity(sliding_sync_response.lists.len());
427                let mut lists = self.inner.lists.write().await;
428
429                // Iterate on known lists, not on lists in the response. Rooms
430                // may have been updated that were not involved in any list
431                // update.
432                for (name, list) in lists.iter_mut() {
433                    if let Some(updates) = sliding_sync_response.lists.get(name) {
434                        let maximum_number_of_rooms: u32 =
435                            updates.count.try_into().expect("failed to convert `count` to `u32`");
436
437                        if list.update(Some(maximum_number_of_rooms))? {
438                            updated_lists.push(name.clone());
439                        }
440                    } else if list.update(None)? {
441                        updated_lists.push(name.clone());
442                    }
443                }
444
445                // Report about unknown lists.
446                for name in sliding_sync_response.lists.keys() {
447                    if !lists.contains_key(name) {
448                        error!("Response for list `{name}` - unknown to us; skipping");
449                    }
450                }
451
452                updated_lists
453            };
454
455            UpdateSummary { lists: updated_lists, rooms: updated_rooms }
456        };
457
458        // Everything went well, we can update the position markers.
459        //
460        // Save the new position markers.
461        debug!(previous_pos = position.pos, new_pos = pos, "Updating `pos`");
462
463        position.pos = pos;
464
465        Ok(update_summary)
466    }
467
468    async fn generate_sync_request(
469        &self,
470    ) -> Result<(http::Request, RequestConfig, OwnedMutexGuard<SlidingSyncPositionMarkers>)> {
471        // Collect requests for lists.
472        let mut requests_lists = BTreeMap::new();
473
474        let timeout = {
475            let lists = self.inner.lists.read().await;
476
477            // Start at `Default` in case there is zero list.
478            let mut timeout = PollTimeout::Default;
479
480            for (name, list) in lists.iter() {
481                requests_lists.insert(name.clone(), list.next_request()?);
482                timeout = timeout.min(list.requires_timeout());
483            }
484
485            timeout
486        };
487
488        // Collect the `pos`.
489        //
490        // Wait on the `position` mutex to be available. It means no request nor
491        // response is running. The `position` mutex is released whether the
492        // response has been fully handled successfully, in this case the `pos`
493        // is updated, or the response handling has failed, in this case the
494        // `pos` hasn't been updated and the same `pos` will be used for this
495        // new request.
496        let mut position_guard = {
497            debug!("Waiting to acquire the `position` lock");
498
499            let _timer = timer!("acquiring the `position` lock");
500
501            self.inner.position.clone().lock_owned().await
502        };
503
504        debug!(pos = ?position_guard.pos, "Got a position");
505
506        let to_device_enabled = self.inner.extensions.to_device.enabled;
507
508        let restored_fields = if self.inner.share_pos || to_device_enabled {
509            restore_sliding_sync_state(&self.inner.client, &self.inner.storage_key).await?
510        } else {
511            None
512        };
513
514        // Update pos: either the one restored from the database, if any and the
515        // sliding sync was configured so, or read it from the memory cache.
516        let pos = if self.inner.share_pos {
517            if let Some(fields) = &restored_fields {
518                // Override the memory one with the database one, for
519                // consistency.
520                if fields.pos != position_guard.pos {
521                    info!(
522                        "Pos from previous request ('{:?}') was different from \
523                         pos in database ('{:?}').",
524                        position_guard.pos, fields.pos
525                    );
526                    position_guard.pos = fields.pos.clone();
527                }
528                fields.pos.clone()
529            } else {
530                position_guard.pos.clone()
531            }
532        } else {
533            position_guard.pos.clone()
534        };
535
536        // When the client sends a request with no `pos`, MSC4186 returns no
537        // device lists updates, as it only returns changes since the provided
538        // `pos` (which is `null` in this case); this is in line with sync v2.
539        //
540        // Therefore, with MSC4186, the device list cache must be marked as to
541        // be re-downloaded if the `since` token is `None`, otherwise it's easy
542        // to miss device lists updates that happened between the previous
543        // request and the new “initial” request.
544        #[cfg(feature = "e2e-encryption")]
545        if pos.is_none() && self.is_e2ee_enabled() {
546            info!("Marking all tracked users as dirty");
547
548            let olm_machine = self.inner.client.olm_machine().await;
549            let olm_machine = olm_machine.as_ref().ok_or(Error::NoOlmMachine)?;
550            olm_machine.mark_all_tracked_users_as_dirty().await?;
551        }
552
553        // Configure the timeout.
554        //
555        // The `timeout` query is necessary when all lists require it. Please
556        // see [`SlidingSyncList::requires_timeout`].
557        let timeout = match timeout {
558            PollTimeout::None => None,
559            PollTimeout::Some(timeout) => Some(Duration::from_secs(timeout.into())),
560            PollTimeout::Default => Some(self.inner.poll_timeout),
561        };
562
563        Span::current()
564            .record("pos", &pos)
565            .record("timeout", timeout.map(|duration| duration.as_millis()));
566
567        let mut request = assign!(http::Request::new(), {
568            conn_id: Some(self.inner.id.clone()),
569            pos,
570            set_presence: self.inner.client.sync_presence(),
571            timeout,
572            lists: requests_lists,
573        });
574
575        // Add room subscriptions.
576        request.room_subscriptions = self.inner.room_subscriptions.read().unwrap().clone();
577
578        // Add extensions.
579        request.extensions = self.inner.extensions.clone();
580
581        // Override the to-device token if the extension is enabled.
582        if to_device_enabled {
583            request.extensions.to_device.since =
584                restored_fields.and_then(|fields| fields.to_device_token);
585        }
586
587        Ok((
588            // The request itself.
589            request,
590            // Configure long-polling. We need some time for the long-poll
591            // itself, and extra time for the network delays.
592            RequestConfig::default()
593                .timeout(self.inner.poll_timeout + self.inner.network_timeout)
594                .retry_limit(3),
595            position_guard,
596        ))
597    }
598
599    /// Send a sliding sync request.
600    ///
601    /// This method contains the sending logic.
602    async fn send_sync_request(
603        &self,
604        request: http::Request,
605        request_config: RequestConfig,
606        mut position_guard: OwnedMutexGuard<SlidingSyncPositionMarkers>,
607    ) -> Result<UpdateSummary> {
608        debug!("Sending request");
609
610        // Prepare the request.
611        let requested_required_states = RequestedRequiredStates::from(&request);
612        let request = self.inner.client.send(request).with_request_config(request_config);
613
614        // Send the request and get a response with end-to-end encryption
615        // support.
616        //
617        // Sending the `/sync` request out when end-to-end encryption is enabled
618        // means that we need to also send out any outgoing e2ee related request
619        // out coming from the `OlmMachine::outgoing_requests()` method.
620
621        #[cfg(feature = "e2e-encryption")]
622        let response = {
623            if self.is_e2ee_enabled() {
624                // Here, we need to run 2 things:
625                //
626                // 1. Send the sliding sync request and get a response,
627                // 2. Send the E2EE requests.
628                //
629                // We don't want to use a `join` or `try_join` because we want
630                // to fail if and only if sending the sliding sync request
631                // fails. Failing to send the E2EE requests should just result
632                // in a log.
633                //
634                // We also want to give the priority to sliding sync request.
635                // E2EE requests are sent concurrently to the sliding sync
636                // request, but the priority is on waiting a sliding sync
637                // response.
638                //
639                // If sending sliding sync request fails, the sending of E2EE
640                // requests must be aborted as soon as possible.
641
642                let client = self.inner.client.clone();
643                let e2ee_uploads = spawn(
644                    async move {
645                        if let Err(error) = client.send_outgoing_requests().await {
646                            error!(?error, "Error while sending outgoing E2EE requests");
647                        }
648                    }
649                    .instrument(Span::current()),
650                )
651                // Ensure that the task is not running in detached mode. It is
652                // aborted when it's dropped.
653                .abort_on_drop();
654
655                // Wait on the sliding sync request success or failure early.
656                let response = request.await?;
657
658                // At this point, if `request` has been resolved successfully,
659                // we wait on `e2ee_uploads`. It did run concurrently, so it
660                // should not be blocking for too long. Otherwise —if `request`
661                // has failed— `e2ee_uploads` has been dropped, so aborted.
662                e2ee_uploads.await.map_err(|error| Error::JoinError {
663                    task_description: "e2ee_uploads".to_owned(),
664                    error,
665                })?;
666
667                response
668            } else {
669                request.await?
670            }
671        };
672
673        // Send the request and get a response _without_ end-to-end encryption
674        // support.
675        #[cfg(not(feature = "e2e-encryption"))]
676        let response = request.await?;
677
678        debug!("Received response");
679
680        // At this point, the request has been sent, and a response has been
681        // received.
682        //
683        // We must ensure the handling of the response cannot be stopped/
684        // cancelled. It must be done entirely, otherwise we can have
685        // corrupted/incomplete states for Sliding Sync and other parts of the
686        // code.
687        //
688        // That's why we are running the handling of the response in a spawned
689        // future that cannot be cancelled by anything.
690        let this = self.clone();
691
692        // Spawn a new future to ensure that the code inside this future cannot
693        // be cancelled if this method is cancelled.
694        let future = async move {
695            debug!("Start handling response");
696
697            // In case the task running this future is detached, we must ensure
698            // responses are handled one at a time. At this point we still own
699            // `position_guard`, so we're fine.
700
701            // Handle the response.
702            let updates = this
703                .handle_response(response, &mut position_guard, requested_required_states)
704                .await?;
705
706            this.cache_to_storage(&position_guard).await?;
707
708            // Release the position guard lock. It means that other responses
709            // can be generated and then handled later.
710            drop(position_guard);
711
712            // Handling the response can queue new E2EE requests (e.g. SAS
713            // verification replies). Send them now, as `Client::sync_once`
714            // does: the next request may long-poll for a while.
715            //
716            // Fixes https://github.com/element-hq/element-x-ios/issues/2428
717            #[cfg(feature = "e2e-encryption")]
718            if this.is_e2ee_enabled()
719                && let Err(error) = this.inner.client.send_outgoing_requests().await
720            {
721                error!(?error, "Error while sending outgoing E2EE requests");
722            }
723
724            debug!("Done handling response");
725
726            Ok(updates)
727        };
728
729        spawn(future.instrument(Span::current())).await.map_err(|error| Error::JoinError {
730            task_description: "handle_response".to_owned(),
731            error,
732        })?
733    }
734
735    /// Is the e2ee extension enabled for this sliding sync instance?
736    #[cfg(feature = "e2e-encryption")]
737    fn is_e2ee_enabled(&self) -> bool {
738        self.inner.extensions.e2ee.enabled
739    }
740
741    /// Is the thread subscriptions extension enabled for this sliding sync
742    /// instance?
743    fn is_thread_subscriptions_enabled(&self) -> bool {
744        self.inner.extensions.thread_subscriptions.enabled
745    }
746
747    #[cfg(not(feature = "e2e-encryption"))]
748    fn is_e2ee_enabled(&self) -> bool {
749        false
750    }
751
752    /// Should we process the room's subpart of a response?
753    async fn must_process_rooms_response(&self) -> bool {
754        // We consider that we must, if there's any room subscription or there's
755        // any list.
756        !self.inner.room_subscriptions.read().unwrap().is_empty()
757            || !self.inner.lists.read().await.is_empty()
758    }
759
760    /// Send a single sliding sync request, and returns the response summary.
761    ///
762    /// Public for testing purposes only.
763    #[doc(hidden)]
764    #[instrument(skip_all, fields(conn_id = self.inner.id, pos, timeout))]
765    pub async fn sync_once(&self) -> Result<UpdateSummary> {
766        let (request, request_config, position_guard) = self.generate_sync_request().await?;
767
768        // Send the request.
769        let summaries = self.send_sync_request(request, request_config, position_guard).await?;
770
771        // Notify a new sync was received.
772        self.inner.client.inner.sync_beat.notify(usize::MAX);
773
774        Ok(summaries)
775    }
776
777    /// Create a _new_ Sliding Sync sync loop.
778    ///
779    /// This method returns a `Stream`, which will send requests and will handle
780    /// responses automatically. Lists and rooms are updated automatically.
781    ///
782    /// This function returns `Ok(…)` if everything went well, otherwise it will
783    /// return `Err(…)`. An `Err` will _always_ lead to the `Stream`
784    /// termination.
785    #[allow(unknown_lints, clippy::let_with_type_underscore)] // triggered by instrument macro
786    #[instrument(name = "sync_stream", skip_all, fields(conn_id = self.inner.id, with_e2ee = self.is_e2ee_enabled()))]
787    pub fn sync(&self) -> impl Stream<Item = Result<UpdateSummary, crate::Error>> + '_ {
788        debug!("Starting sync stream");
789
790        let mut internal_channel_receiver = self.inner.internal_channel.subscribe();
791
792        stream! {
793            loop {
794                debug!("Sync stream is running");
795
796                select! {
797                    biased;
798
799                    internal_message = internal_channel_receiver.recv() => {
800                        use SlidingSyncInternalMessage::*;
801
802                        debug!(?internal_message, "Sync stream has received an internal message");
803
804                        match internal_message {
805                            Err(_) | Ok(SyncLoopStop) => {
806                                break;
807                            }
808
809                            Ok(SyncLoopSkipOverCurrentIteration) => {
810                                continue;
811                            }
812                        }
813                    }
814
815                    update_summary = self.sync_once() => {
816                        match update_summary {
817                            Ok(updates) => {
818                                yield Ok(updates);
819                            }
820
821                            // Here, errors we **cannot** ignore, and that must stop the sync loop.
822                            Err(error) => {
823                                if error.client_api_error_kind() == Some(&ErrorKind::UnknownPos) {
824                                    // The Sliding Sync session has expired. Let's reset `pos`.
825                                    self.expire_session().await;
826                                }
827
828                                #[cfg(feature = "e2e-encryption")]
829                                if is_synapse_incompatible_token_error(&error)
830                                    && let Some(olm_machine) = &*self.inner.client.olm_machine().await {
831                                    // Just delete the token since that error should only happen
832                                    // once when upgrading to Sliding Sync.
833
834
835                                    if let Ok(()) = olm_machine.store().delete_next_batch_token().await {
836                                        warn!("Outdated to_device token loaded from cache. Retrying without token.");
837                                        continue;
838                                    }
839                                }
840
841                                yield Err(error);
842
843                                // Terminates the loop, and terminates the stream.
844                                break;
845                            }
846                        }
847                    }
848                }
849            }
850
851            debug!("Sync stream has exited.");
852        }
853    }
854
855    /// Force to stop the sync loop ([`Self::sync`]) if it's running.
856    ///
857    /// Usually, dropping the `Stream` returned by [`Self::sync`] should be
858    /// enough to “stop” it, but depending of how this `Stream` is used, it
859    /// might not be obvious to drop it immediately (thinking of using this API
860    /// over FFI; the foreign-language might not be able to drop a value
861    /// immediately). Thus, calling this method will ensure that the sync loop
862    /// stops gracefully and as soon as it returns.
863    pub fn stop_sync(&self) -> Result<()> {
864        Ok(self.inner.internal_channel_send(SlidingSyncInternalMessage::SyncLoopStop)?)
865    }
866
867    /// Expire the current Sliding Sync session on the client-side.
868    ///
869    /// Expiring a Sliding Sync session means: resetting `pos`.
870    ///
871    /// This should only be used when it's clear that this session was about to
872    /// expire anyways, and should be used only in very specific cases (e.g.
873    /// multiple sliding syncs being run in parallel, and one of them has
874    /// expired).
875    ///
876    /// This method **MUST** be called when the sync loop is stopped.
877    #[doc(hidden)]
878    pub async fn expire_session(&self) {
879        info!("Session expired; resetting `pos`");
880
881        {
882            let lists = self.inner.lists.read().await;
883
884            for list in lists.values() {
885                // Invalidate in-memory data that would be persisted on disk.
886                list.set_maximum_number_of_rooms(None);
887            }
888        }
889
890        // Remove the cached sliding sync state as well.
891        {
892            let mut position = self.inner.position.lock().await;
893
894            // Invalidate in memory.
895            position.pos = None;
896
897            // Propagate to disk. Note: this propagates both the sliding sync
898            // state and the cached lists' state to disk.
899            if let Err(err) = self.cache_to_storage(&position).await {
900                warn!("Failed to invalidate cached sliding sync state: {err}");
901            }
902        }
903
904        {
905            // Clear all room subscriptions: we don't want to resend all room
906            // subscriptions when the session will restart.
907            self.inner.room_subscriptions.write().unwrap().clear();
908        }
909    }
910}
911
912/// Identify whether an error indicates an invalid `next_batch` token.
913///
914/// Synapse uses different `to_device` tokens for Sliding Sync and sync v3. This
915/// function matches the error that is returned if the sync v3 token is used
916/// with the Sliding Sync API.
917#[cfg(feature = "e2e-encryption")]
918fn is_synapse_incompatible_token_error(error: &crate::Error) -> bool {
919    let Some(ruma::api::error::Error {
920        status_code: ::http::StatusCode::BAD_REQUEST,
921        body: ErrorBody::Standard(StandardErrorBody { message, .. }),
922        ..
923    }) = error.as_client_api_error()
924    else {
925        return false;
926    };
927
928    message.starts_with("1 validation error for SlidingSyncBody")
929        && message.contains("'extensions.to_device.since' is invalid")
930        && message.contains("(should look like an int)")
931}
932
933/// Add a subscription for each room of `room_ids` that isn't subscribed yet,
934/// and refresh the `settings` of the ones that already are.
935///
936/// It returns whether the set of subscriptions has changed, i.e. a subscription
937/// has been added, or the settings of an existing one have been updated. It is
938/// up to the caller to decide whether this warrants cancelling the in-flight
939/// request: a caller can have other reasons to cancel it, e.g. having removed a
940/// subscription.
941fn upsert_room_subscriptions(
942    room_subscriptions: &mut BTreeMap<OwnedRoomId, http::request::RoomSubscription>,
943    client: &Client,
944    room_ids: &[&RoomId],
945    settings: Option<http::request::RoomSubscription>,
946) -> bool {
947    let settings = settings.unwrap_or_default();
948    let mut subscriptions_have_changed = false;
949
950    for room_id in room_ids {
951        match room_subscriptions.entry((*room_id).to_owned()) {
952            Entry::Vacant(entry) => {
953                if let Some(room) = client.get_room(room_id) {
954                    room.mark_members_missing();
955                }
956
957                entry.insert(settings.clone());
958
959                subscriptions_have_changed = true;
960            }
961
962            // The room is already subscribed but its settings might need to be
963            // refreshed
964            Entry::Occupied(mut entry) => {
965                if room_subscriptions_differ(entry.get(), &settings) {
966                    entry.insert(settings.clone());
967
968                    subscriptions_have_changed = true;
969                }
970            }
971        }
972    }
973
974    subscriptions_have_changed
975}
976
977/// Compare two [`http::request::RoomSubscription`].
978fn room_subscriptions_differ(
979    left: &http::request::RoomSubscription,
980    right: &http::request::RoomSubscription,
981) -> bool {
982    left.timeline_limit != right.timeline_limit || left.required_state != right.required_state
983}
984
985impl SlidingSyncInner {
986    /// Send a message over the internal channel.
987    #[instrument]
988    fn internal_channel_send(&self, message: SlidingSyncInternalMessage) -> Result<(), Error> {
989        self.internal_channel.send(message).map(|_| ()).map_err(|_| Error::InternalChannelIsBroken)
990    }
991
992    /// Send a message over the internal channel if there is a receiver, i.e. if
993    /// the sync loop is running.
994    #[instrument]
995    fn internal_channel_send_if_possible(&self, message: SlidingSyncInternalMessage) {
996        // If there is no receiver, the send will fail, but that's OK here.
997        let _ = self.internal_channel.send(message);
998    }
999
1000    /// Cancel the in-flight request (if any) so that the sync loop immediately
1001    /// starts a new iteration, with a fresh request.
1002    fn cancel_in_flight_request(&self) {
1003        self.internal_channel_send_if_possible(
1004            SlidingSyncInternalMessage::SyncLoopSkipOverCurrentIteration,
1005        );
1006    }
1007}
1008
1009#[derive(Copy, Clone, Debug, PartialEq)]
1010enum SlidingSyncInternalMessage {
1011    /// Instruct the sync loop to stop.
1012    SyncLoopStop,
1013
1014    /// Instruct the sync loop to skip over any remaining work in its iteration,
1015    /// and to jump to the next iteration.
1016    SyncLoopSkipOverCurrentIteration,
1017}
1018
1019#[cfg(any(test, feature = "testing"))]
1020impl SlidingSync {
1021    /// Set a new value for `pos`.
1022    pub async fn set_pos(&self, new_pos: String) {
1023        let mut position_lock = self.inner.position.lock().await;
1024        position_lock.pos = Some(new_pos);
1025    }
1026}
1027
1028#[derive(Clone, Debug)]
1029pub(super) struct SlidingSyncPositionMarkers {
1030    /// An ephemeral position in the current stream, as received from the
1031    /// previous `/sync` response, or `None` for the first request.
1032    pos: Option<String>,
1033}
1034
1035/// A summary of the updates received after a sync (like in
1036/// [`SlidingSync::sync`]).
1037#[derive(Debug, Clone)]
1038pub struct UpdateSummary {
1039    /// The names of the lists that have seen an update.
1040    pub lists: Vec<String>,
1041    /// The rooms that have seen updates
1042    pub rooms: Vec<OwnedRoomId>,
1043}
1044
1045/// Define what kind of poll timeout [`SlidingSync`] must use.
1046///
1047/// [The spec says about `timeout`][spec]:
1048///
1049/// > How long to wait for new events […] If omitted the response is always
1050/// > returned immediately, even if there are no changes.
1051///
1052/// [spec]: https://github.com/matrix-org/matrix-spec-proposals/blob/erikj/sss/proposals/4186-simplified-sliding-sync.md#top-level
1053#[derive(Debug)]
1054pub enum PollTimeout {
1055    /// No `timeout` must be present.
1056    None,
1057
1058    /// A `timeout=X` must be present, where `X` is in seconds and represents
1059    /// how long to wait for new events.
1060    Some(u32),
1061
1062    /// A `timeout=X` must be present, where `X` is the default value passed to
1063    /// [`SlidingSyncBuilder::poll_timeout`].
1064    Default,
1065}
1066
1067impl PollTimeout {
1068    /// Computes the smallest `PollTimeout` between two of them.
1069    ///
1070    /// The rules are the following:
1071    ///
1072    /// - `None` < `Some`,
1073    /// - `Some(x) < Some(y)` if and only if `x < y`,
1074    /// - `Some < Default`.
1075    ///
1076    /// The `Default` value is unknown at this step but is assumed to be the
1077    /// largest.
1078    fn min(self, left: Self) -> Self {
1079        match (self, left) {
1080            (Self::None, _) => Self::None,
1081
1082            (Self::Some(_), Self::None) => Self::None,
1083            (Self::Some(right), Self::Some(left)) => Self::Some(right.min(left)),
1084            (Self::Some(right), Self::Default) => Self::Some(right),
1085
1086            (Self::Default, Self::None) => Self::None,
1087            (Self::Default, Self::Some(left)) => Self::Some(left),
1088            (Self::Default, Self::Default) => Self::Default,
1089        }
1090    }
1091}
1092
1093#[cfg(all(test, not(target_family = "wasm")))]
1094#[allow(clippy::dbg_macro)]
1095mod tests {
1096    use std::{
1097        collections::BTreeMap,
1098        future::ready,
1099        ops::Not,
1100        pin::pin,
1101        sync::{Arc, Mutex},
1102        time::Duration,
1103    };
1104
1105    use assert_matches::assert_matches;
1106    use event_listener::Listener;
1107    use futures_util::{StreamExt, future::join_all};
1108    use matrix_sdk_base::{RequestedRequiredStates, RoomMemberships};
1109    use matrix_sdk_common::executor::spawn;
1110    use matrix_sdk_test::{User, async_test, event_factory::EventFactory};
1111    use ruma::{
1112        OwnedRoomId, assign,
1113        events::{direct::DirectEvent, room::member::MembershipState},
1114        owned_room_id,
1115        presence::PresenceState,
1116        profile::{
1117            AvatarUrl, DisplayName, ProfileFieldName, UserProfileChanges, UserProfileUpdate,
1118        },
1119        room_id,
1120        serde::Raw,
1121        uint,
1122    };
1123    use serde::Deserialize;
1124    use serde_json::json;
1125    use stream_assert::assert_pending;
1126    use wiremock::{
1127        Match, Mock, MockServer, Request, ResponseTemplate, http::Method, matchers::method,
1128    };
1129
1130    use super::{
1131        SlidingSync, SlidingSyncBuilder, SlidingSyncInternalMessage, SlidingSyncList,
1132        SlidingSyncListBuilder, SlidingSyncMode, cache::restore_sliding_sync_state, http,
1133    };
1134    use crate::{
1135        Client, Result,
1136        test_utils::{logged_in_client, mocks::MatrixMockServer},
1137    };
1138
1139    #[derive(Copy, Clone)]
1140    struct SlidingSyncMatcher;
1141
1142    impl Match for SlidingSyncMatcher {
1143        fn matches(&self, request: &Request) -> bool {
1144            request.url.path() == "/_matrix/client/unstable/org.matrix.simplified_msc3575/sync"
1145                && request.method == Method::POST
1146        }
1147    }
1148
1149    async fn new_sliding_sync(
1150        lists: Vec<SlidingSyncListBuilder>,
1151    ) -> Result<(MockServer, SlidingSync)> {
1152        let server = MockServer::start().await;
1153        let client = logged_in_client(Some(server.uri())).await;
1154
1155        let mut sliding_sync_builder = client.sliding_sync("test-slidingsync")?;
1156
1157        for list in lists {
1158            sliding_sync_builder = sliding_sync_builder.add_list(list);
1159        }
1160
1161        let sliding_sync = sliding_sync_builder.build().await?;
1162
1163        Ok((server, sliding_sync))
1164    }
1165
1166    #[async_test]
1167    async fn test_subscribe_to_own_profile() {
1168        let client = logged_in_client(None).await;
1169        let own_user_id = client.user_id().expect("client should be logged in").to_owned();
1170
1171        // Given a stored global profile for the current user, received through
1172        // a previous sync.
1173        let mut response = http::Response::new("0".to_owned());
1174
1175        let mut profile_changes = UserProfileChanges::new();
1176        profile_changes.updated.insert(ProfileFieldName::DisplayName, json!("Example"));
1177
1178        response
1179            .extensions
1180            .profiles
1181            .users
1182            .insert(own_user_id.clone(), UserProfileUpdate::Updated(profile_changes));
1183        client
1184            .process_sliding_sync_test_helper(&response, &RequestedRequiredStates::default())
1185            .await
1186            .expect("Failed to process sync");
1187
1188        // Subscribing emits the currently stored value immediately.
1189        let stream = client.subscribe_to_own_profile().expect("client should be logged in");
1190        let mut stream = pin!(stream);
1191
1192        let profile = stream.next().await.expect("should emit the initial profile");
1193        assert_eq!(profile.get_static::<DisplayName>().unwrap().as_deref(), Some("Example"));
1194
1195        // An update for another user only is ignored: nothing is emitted.
1196        let mut response = http::Response::new("1".to_owned());
1197
1198        let mut profile_changes = UserProfileChanges::new();
1199        profile_changes.updated.insert(ProfileFieldName::DisplayName, json!("Alice"));
1200        response
1201            .extensions
1202            .profiles
1203            .users
1204            .insert(User::Alice.into(), UserProfileUpdate::Updated(profile_changes));
1205        client
1206            .process_sliding_sync_test_helper(&response, &RequestedRequiredStates::default())
1207            .await
1208            .expect("Failed to process sync");
1209
1210        assert_pending!(stream);
1211
1212        // An update for the current user is emitted with the merged value.
1213        let mut response = http::Response::new("2".to_owned());
1214
1215        let mut profile_changes = UserProfileChanges::new();
1216        profile_changes
1217            .updated
1218            .insert(ProfileFieldName::AvatarUrl, json!("mxc://example.org/avatar"));
1219
1220        response
1221            .extensions
1222            .profiles
1223            .users
1224            .insert(own_user_id.clone(), UserProfileUpdate::Updated(profile_changes));
1225        client
1226            .process_sliding_sync_test_helper(&response, &RequestedRequiredStates::default())
1227            .await
1228            .expect("Failed to process sync");
1229
1230        let profile = stream.next().await.expect("should emit the updated profile");
1231        assert_eq!(profile.get_static::<DisplayName>().unwrap().as_deref(), Some("Example"));
1232        assert_eq!(
1233            profile.get_static::<AvatarUrl>().unwrap().map(|url| url.to_string()).as_deref(),
1234            Some("mxc://example.org/avatar")
1235        );
1236    }
1237
1238    #[async_test]
1239    async fn test_sliding_sync_request_uses_client_sync_presence() -> Result<()> {
1240        let (_server, sliding_sync) = new_sliding_sync(vec![]).await?;
1241        let client = sliding_sync.inner.client.clone();
1242
1243        {
1244            let (request, _, _position_guard) = sliding_sync.generate_sync_request().await?;
1245
1246            assert_eq!(request.set_presence, PresenceState::Online);
1247        }
1248
1249        client.set_presence(PresenceState::Unavailable, None, false).await?;
1250
1251        {
1252            let (request, _, _position_guard) = sliding_sync.generate_sync_request().await?;
1253
1254            assert_eq!(request.set_presence, PresenceState::Unavailable);
1255        }
1256
1257        client.set_presence(PresenceState::Offline, None, false).await?;
1258
1259        {
1260            let (request, _, _position_guard) = sliding_sync.generate_sync_request().await?;
1261
1262            assert_eq!(request.set_presence, PresenceState::Offline);
1263        }
1264
1265        Ok(())
1266    }
1267
1268    #[async_test]
1269    async fn test_add_room_subscriptions() -> Result<()> {
1270        let (server, sliding_sync) = new_sliding_sync(vec![
1271            SlidingSyncList::builder("foo")
1272                .sync_mode(SlidingSyncMode::new_selective().range(0..=10)),
1273        ])
1274        .await?;
1275
1276        let stream = sliding_sync.sync();
1277        let mut stream = pin!(stream);
1278
1279        let room_id_0 = room_id!("!r0:bar.org");
1280        let room_id_1 = room_id!("!r1:bar.org");
1281        let room_id_2 = room_id!("!r2:bar.org");
1282
1283        {
1284            let _mock_guard = Mock::given(SlidingSyncMatcher)
1285                .respond_with(ResponseTemplate::new(200).set_body_json(json!({
1286                    "pos": "1",
1287                    "lists": {},
1288                    "rooms": {
1289                        room_id_0: {
1290                            "name": "Room #0",
1291                            "initial": true,
1292                        },
1293                        room_id_1: {
1294                            "name": "Room #1",
1295                            "initial": true,
1296                        },
1297                        room_id_2: {
1298                            "name": "Room #2",
1299                            "initial": true,
1300                        },
1301                    }
1302                })))
1303                .mount_as_scoped(&server)
1304                .await;
1305
1306            let _ = stream.next().await.unwrap()?;
1307        }
1308
1309        let room0 = sliding_sync.inner.client.get_room(room_id_0).unwrap();
1310
1311        // Members aren't synced. We need to make them synced, so that we can
1312        // test that subscribing to a room make members not synced. That's a
1313        // desired feature.
1314        assert!(room0.are_members_synced().not());
1315
1316        {
1317            struct MemberMatcher(OwnedRoomId);
1318
1319            impl Match for MemberMatcher {
1320                fn matches(&self, request: &Request) -> bool {
1321                    request.url.path()
1322                        == format!("/_matrix/client/r0/rooms/{room_id}/members", room_id = self.0)
1323                        && request.method == Method::GET
1324                }
1325            }
1326
1327            let _mock_guard = Mock::given(MemberMatcher(room_id_0.to_owned()))
1328                .respond_with(ResponseTemplate::new(200).set_body_json(json!({
1329                    "chunk": [],
1330                })))
1331                .mount_as_scoped(&server)
1332                .await;
1333
1334            assert_matches!(room0.request_members().await, Ok(()));
1335        }
1336
1337        // Members are now synced! We can start subscribing and see how it goes.
1338        assert!(room0.are_members_synced());
1339
1340        sliding_sync.add_room_subscriptions(&[room_id_0, room_id_1], None, true);
1341
1342        // OK, we have subscribed to some rooms. Let's check on `room0` if
1343        // members are now marked as not synced.
1344        assert!(room0.are_members_synced().not());
1345
1346        {
1347            let room_subscriptions = sliding_sync.inner.room_subscriptions.read().unwrap();
1348
1349            assert!(room_subscriptions.contains_key(room_id_0));
1350            assert!(room_subscriptions.contains_key(room_id_1));
1351            assert!(!room_subscriptions.contains_key(room_id_2));
1352        }
1353
1354        // Subscribing to the same room doesn't reset the member sync state.
1355
1356        {
1357            struct MemberMatcher(OwnedRoomId);
1358
1359            impl Match for MemberMatcher {
1360                fn matches(&self, request: &Request) -> bool {
1361                    request.url.path()
1362                        == format!("/_matrix/client/r0/rooms/{room_id}/members", room_id = self.0)
1363                        && request.method == Method::GET
1364                }
1365            }
1366
1367            let _mock_guard = Mock::given(MemberMatcher(room_id_0.to_owned()))
1368                .respond_with(ResponseTemplate::new(200).set_body_json(json!({
1369                    "chunk": [],
1370                })))
1371                .mount_as_scoped(&server)
1372                .await;
1373
1374            assert_matches!(room0.request_members().await, Ok(()));
1375        }
1376
1377        // Members are synced, good, good.
1378        assert!(room0.are_members_synced());
1379
1380        sliding_sync.add_room_subscriptions(&[room_id_0], None, false);
1381
1382        // Members are still synced: because we have already subscribed to the
1383        // room, the members aren't marked as unsynced.
1384        assert!(room0.are_members_synced());
1385
1386        Ok(())
1387    }
1388
1389    #[async_test]
1390    async fn test_add_remove_and_reset_room_subscriptions() -> Result<()> {
1391        let (_server, sliding_sync) = new_sliding_sync(vec![
1392            SlidingSyncList::builder("foo")
1393                .sync_mode(SlidingSyncMode::new_selective().range(0..=10)),
1394        ])
1395        .await?;
1396
1397        let room_id_0 = room_id!("!r0:bar.org");
1398        let room_id_1 = room_id!("!r1:bar.org");
1399        let room_id_2 = room_id!("!r2:bar.org");
1400        let room_id_3 = room_id!("!r3:bar.org");
1401
1402        // Initially empty.
1403        {
1404            let room_subscriptions = sliding_sync.inner.room_subscriptions.read().unwrap();
1405
1406            assert!(room_subscriptions.is_empty());
1407        }
1408
1409        // Add 2 rooms.
1410        sliding_sync.add_room_subscriptions(&[room_id_0, room_id_1], Default::default(), false);
1411
1412        {
1413            let room_subscriptions = sliding_sync.inner.room_subscriptions.read().unwrap();
1414
1415            assert_eq!(room_subscriptions.len(), 2);
1416            assert!(room_subscriptions.contains_key(room_id_0));
1417            assert!(room_subscriptions.contains_key(room_id_1));
1418        }
1419
1420        // Remove 1 room.
1421        sliding_sync.remove_room_subscriptions(&[room_id_0], false);
1422
1423        {
1424            let room_subscriptions = sliding_sync.inner.room_subscriptions.read().unwrap();
1425
1426            assert_eq!(room_subscriptions.len(), 1);
1427            assert!(room_subscriptions.contains_key(room_id_1));
1428        }
1429
1430        // Add 2 rooms, but one already exists.
1431        sliding_sync.add_room_subscriptions(&[room_id_0, room_id_1], Default::default(), false);
1432
1433        {
1434            let room_subscriptions = sliding_sync.inner.room_subscriptions.read().unwrap();
1435
1436            assert_eq!(room_subscriptions.len(), 2);
1437            assert!(room_subscriptions.contains_key(room_id_0));
1438            assert!(room_subscriptions.contains_key(room_id_1));
1439        }
1440
1441        // Replace all rooms with 2 other rooms.
1442        sliding_sync.reset_and_add_room_subscriptions(
1443            &[room_id_2, room_id_3],
1444            Default::default(),
1445            false,
1446        );
1447
1448        {
1449            let room_subscriptions = sliding_sync.inner.room_subscriptions.read().unwrap();
1450
1451            assert_eq!(room_subscriptions.len(), 2);
1452            assert!(room_subscriptions.contains_key(room_id_2));
1453            assert!(room_subscriptions.contains_key(room_id_3));
1454        }
1455
1456        Ok(())
1457    }
1458
1459    #[async_test]
1460    async fn test_set_room_subscriptions_refreshes_the_settings() -> Result<()> {
1461        let (_server, sliding_sync) = new_sliding_sync(vec![
1462            SlidingSyncList::builder("foo")
1463                .sync_mode(SlidingSyncMode::new_selective().range(0..=10)),
1464        ])
1465        .await?;
1466
1467        let room_id_0 = room_id!("!r0:bar.org");
1468
1469        let settings = |timeline_limit: u32| {
1470            Some(assign!(http::request::RoomSubscription::default(), {
1471                timeline_limit: timeline_limit.into(),
1472            }))
1473        };
1474        let timeline_limit_of_room_0 = || {
1475            sliding_sync
1476                .inner
1477                .room_subscriptions
1478                .read()
1479                .unwrap()
1480                .get(room_id_0)
1481                .map(|subscription| subscription.timeline_limit)
1482        };
1483
1484        let mut internal_channel = sliding_sync.inner.internal_channel.subscribe();
1485
1486        // Subscribe for the first time.
1487        sliding_sync.set_room_subscriptions(&[room_id_0], settings(10), true);
1488
1489        assert_eq!(timeline_limit_of_room_0(), Some(10u32.into()));
1490        assert_matches!(
1491            internal_channel.try_recv(),
1492            Ok(SlidingSyncInternalMessage::SyncLoopSkipOverCurrentIteration)
1493        );
1494
1495        // Resubscribe with the same settings: nothing changes, no cancellation.
1496        sliding_sync.set_room_subscriptions(&[room_id_0], settings(10), true);
1497
1498        assert_eq!(timeline_limit_of_room_0(), Some(10u32.into()));
1499        assert!(internal_channel.try_recv().is_err());
1500
1501        // Resubscribe with new settings: they must be applied, and the
1502        // in-flight request must be cancelled so that they are sent right away.
1503        sliding_sync.set_room_subscriptions(&[room_id_0], settings(42), true);
1504
1505        assert_eq!(timeline_limit_of_room_0(), Some(42u32.into()));
1506        assert_matches!(
1507            internal_channel.try_recv(),
1508            Ok(SlidingSyncInternalMessage::SyncLoopSkipOverCurrentIteration)
1509        );
1510
1511        Ok(())
1512    }
1513
1514    #[async_test]
1515    async fn test_set_room_subscriptions_cancels_the_in_flight_request() -> Result<()> {
1516        let (_server, sliding_sync) = new_sliding_sync(vec![
1517            SlidingSyncList::builder("foo")
1518                .sync_mode(SlidingSyncMode::new_selective().range(0..=10)),
1519        ])
1520        .await?;
1521
1522        let room_id_0 = room_id!("!r0:bar.org");
1523        let room_id_1 = room_id!("!r1:bar.org");
1524
1525        let mut internal_channel = sliding_sync.inner.internal_channel.subscribe();
1526
1527        // A first-ever subscription: nothing is removed, but a subscription is
1528        // added, so the in-flight request must be cancelled.
1529        sliding_sync.set_room_subscriptions(&[room_id_0], None, true);
1530
1531        assert_matches!(
1532            internal_channel.try_recv(),
1533            Ok(SlidingSyncInternalMessage::SyncLoopSkipOverCurrentIteration)
1534        );
1535
1536        // Resubscribing to the same room: nothing is added nor removed, no
1537        // cancellation.
1538        sliding_sync.set_room_subscriptions(&[room_id_0], None, true);
1539
1540        assert!(internal_channel.try_recv().is_err());
1541
1542        // A subscription is removed: the in-flight request must be cancelled.
1543        sliding_sync.set_room_subscriptions(&[room_id_1], None, true);
1544
1545        assert_matches!(
1546            internal_channel.try_recv(),
1547            Ok(SlidingSyncInternalMessage::SyncLoopSkipOverCurrentIteration)
1548        );
1549
1550        // Finally, no cancellation is asked: no cancellation happens.
1551        sliding_sync.set_room_subscriptions(&[room_id_0], None, false);
1552
1553        assert!(internal_channel.try_recv().is_err());
1554
1555        Ok(())
1556    }
1557
1558    #[async_test]
1559    async fn test_reset_and_add_room_subscriptions_cancels_the_in_flight_request() -> Result<()> {
1560        let (_server, sliding_sync) = new_sliding_sync(vec![
1561            SlidingSyncList::builder("foo")
1562                .sync_mode(SlidingSyncMode::new_selective().range(0..=10)),
1563        ])
1564        .await?;
1565
1566        let room_id_0 = room_id!("!r0:bar.org");
1567
1568        let mut internal_channel = sliding_sync.inner.internal_channel.subscribe();
1569
1570        // Nothing is removed, nothing is added: no cancellation.
1571        sliding_sync.reset_and_add_room_subscriptions(&[], None, true);
1572
1573        assert!(internal_channel.try_recv().is_err());
1574
1575        // A subscription is added: the in-flight request must be cancelled.
1576        sliding_sync.reset_and_add_room_subscriptions(&[room_id_0], None, true);
1577
1578        assert_matches!(
1579            internal_channel.try_recv(),
1580            Ok(SlidingSyncInternalMessage::SyncLoopSkipOverCurrentIteration)
1581        );
1582
1583        // All the subscriptions are removed: the in-flight request must be
1584        // cancelled.
1585        sliding_sync.reset_and_add_room_subscriptions(&[], None, true);
1586
1587        assert!(sliding_sync.inner.room_subscriptions.read().unwrap().is_empty());
1588        assert_matches!(
1589            internal_channel.try_recv(),
1590            Ok(SlidingSyncInternalMessage::SyncLoopSkipOverCurrentIteration)
1591        );
1592
1593        // Finally, no cancellation is asked: no cancellation happens.
1594        sliding_sync.reset_and_add_room_subscriptions(&[room_id_0], None, false);
1595
1596        assert!(internal_channel.try_recv().is_err());
1597
1598        Ok(())
1599    }
1600
1601    #[async_test]
1602    async fn test_set_room_subscriptions() -> Result<()> {
1603        let (server, sliding_sync) = new_sliding_sync(vec![
1604            SlidingSyncList::builder("foo")
1605                .sync_mode(SlidingSyncMode::new_selective().range(0..=10)),
1606        ])
1607        .await?;
1608
1609        let stream = sliding_sync.sync();
1610        let mut stream = pin!(stream);
1611
1612        let room_id_0 = room_id!("!r0:bar.org");
1613        let room_id_1 = room_id!("!r1:bar.org");
1614        let room_id_2 = room_id!("!r2:bar.org");
1615
1616        {
1617            let _mock_guard = Mock::given(SlidingSyncMatcher)
1618                .respond_with(ResponseTemplate::new(200).set_body_json(json!({
1619                    "pos": "1",
1620                    "lists": {},
1621                    "rooms": {
1622                        room_id_0: {
1623                            "name": "Room #0",
1624                            "initial": true,
1625                        },
1626                        room_id_1: {
1627                            "name": "Room #1",
1628                            "initial": true,
1629                        },
1630                        room_id_2: {
1631                            "name": "Room #2",
1632                            "initial": true,
1633                        },
1634                    }
1635                })))
1636                .mount_as_scoped(&server)
1637                .await;
1638
1639            let _ = stream.next().await.unwrap()?;
1640        }
1641
1642        let room0 = sliding_sync.inner.client.get_room(room_id_0).unwrap();
1643
1644        // Members aren't synced. We need to make them synced, so that we can
1645        // test that subscribing to a room make members not synced. That's a
1646        // desired feature.
1647        assert!(room0.are_members_synced().not());
1648
1649        {
1650            struct MemberMatcher(OwnedRoomId);
1651
1652            impl Match for MemberMatcher {
1653                fn matches(&self, request: &Request) -> bool {
1654                    request.url.path()
1655                        == format!("/_matrix/client/r0/rooms/{room_id}/members", room_id = self.0)
1656                        && request.method == Method::GET
1657                }
1658            }
1659
1660            let _mock_guard = Mock::given(MemberMatcher(room_id_0.to_owned()))
1661                .respond_with(ResponseTemplate::new(200).set_body_json(json!({
1662                    "chunk": [],
1663                })))
1664                .mount_as_scoped(&server)
1665                .await;
1666
1667            assert_matches!(room0.request_members().await, Ok(()));
1668        }
1669
1670        // Members are now synced! We can start subscribing and see how it goes.
1671        assert!(room0.are_members_synced());
1672
1673        sliding_sync.set_room_subscriptions(&[room_id_0, room_id_1], None, true);
1674
1675        // OK, we have subscribed to some rooms. Let's check on `room0` if
1676        // members are now marked as not synced.
1677        assert!(room0.are_members_synced().not());
1678
1679        // Both resubscribed rooms are subscribed.
1680        {
1681            let room_subscriptions = sliding_sync.inner.room_subscriptions.read().unwrap();
1682
1683            assert!(room_subscriptions.contains_key(room_id_0));
1684            assert!(room_subscriptions.contains_key(room_id_1));
1685            assert!(!room_subscriptions.contains_key(room_id_2));
1686        }
1687
1688        // Subscribing to the same room doesn't reset the member sync state.
1689
1690        {
1691            struct MemberMatcher(OwnedRoomId);
1692
1693            impl Match for MemberMatcher {
1694                fn matches(&self, request: &Request) -> bool {
1695                    request.url.path()
1696                        == format!("/_matrix/client/r0/rooms/{room_id}/members", room_id = self.0)
1697                        && request.method == Method::GET
1698                }
1699            }
1700
1701            let _mock_guard = Mock::given(MemberMatcher(room_id_0.to_owned()))
1702                .respond_with(ResponseTemplate::new(200).set_body_json(json!({
1703                    "chunk": [],
1704                })))
1705                .mount_as_scoped(&server)
1706                .await;
1707
1708            assert_matches!(room0.request_members().await, Ok(()));
1709        }
1710
1711        // Members are synced, good, good.
1712        assert!(room0.are_members_synced());
1713
1714        sliding_sync.set_room_subscriptions(&[room_id_0], None, false);
1715
1716        // Members are still synced: because we have already subscribed to the
1717        // room, the members aren't marked as unsynced.
1718        assert!(room0.are_members_synced());
1719
1720        // Only the resubscribed room is subscribed.
1721        {
1722            let room_subscriptions = sliding_sync.inner.room_subscriptions.read().unwrap();
1723
1724            assert!(room_subscriptions.contains_key(room_id_0));
1725            assert!(!room_subscriptions.contains_key(room_id_1));
1726            assert!(!room_subscriptions.contains_key(room_id_2));
1727        }
1728        Ok(())
1729    }
1730
1731    #[async_test]
1732    async fn test_room_subscriptions_are_reset_when_session_expires() -> Result<()> {
1733        let (_server, sliding_sync) = new_sliding_sync(vec![
1734            SlidingSyncList::builder("foo")
1735                .sync_mode(SlidingSyncMode::new_selective().range(0..=10)),
1736        ])
1737        .await?;
1738
1739        let room_id_0 = room_id!("!r0:bar.org");
1740        let room_id_1 = room_id!("!r1:bar.org");
1741        let room_id_2 = room_id!("!r2:bar.org");
1742
1743        // Subscribe to two rooms.
1744        sliding_sync.add_room_subscriptions(&[room_id_0, room_id_1], None, false);
1745
1746        {
1747            let room_subscriptions = sliding_sync.inner.room_subscriptions.read().unwrap();
1748
1749            assert!(room_subscriptions.contains_key(room_id_0));
1750            assert!(room_subscriptions.contains_key(room_id_1));
1751            assert!(room_subscriptions.contains_key(room_id_2).not());
1752        }
1753
1754        // Subscribe to one more room.
1755        sliding_sync.add_room_subscriptions(&[room_id_2], None, false);
1756
1757        {
1758            let room_subscriptions = sliding_sync.inner.room_subscriptions.read().unwrap();
1759
1760            assert!(room_subscriptions.contains_key(room_id_0));
1761            assert!(room_subscriptions.contains_key(room_id_1));
1762            assert!(room_subscriptions.contains_key(room_id_2));
1763        }
1764
1765        // Suddenly, the session expires!
1766        sliding_sync.expire_session().await;
1767
1768        {
1769            let room_subscriptions = sliding_sync.inner.room_subscriptions.read().unwrap();
1770
1771            assert!(room_subscriptions.is_empty());
1772        }
1773
1774        // Subscribe to one room again.
1775        sliding_sync.add_room_subscriptions(&[room_id_2], None, false);
1776
1777        {
1778            let room_subscriptions = sliding_sync.inner.room_subscriptions.read().unwrap();
1779
1780            assert!(room_subscriptions.contains_key(room_id_0).not());
1781            assert!(room_subscriptions.contains_key(room_id_1).not());
1782            assert!(room_subscriptions.contains_key(room_id_2));
1783        }
1784
1785        Ok(())
1786    }
1787
1788    #[async_test]
1789    async fn test_add_list() -> Result<()> {
1790        let (_server, sliding_sync) = new_sliding_sync(vec![
1791            SlidingSyncList::builder("foo")
1792                .sync_mode(SlidingSyncMode::new_selective().range(0..=10)),
1793        ])
1794        .await?;
1795
1796        let _stream = sliding_sync.sync();
1797        let mut _stream = pin!(_stream);
1798
1799        sliding_sync
1800            .add_list(
1801                SlidingSyncList::builder("bar")
1802                    .sync_mode(SlidingSyncMode::new_selective().range(50..=60)),
1803            )
1804            .await?;
1805
1806        let lists = sliding_sync.inner.lists.read().await;
1807
1808        assert!(lists.contains_key("foo"));
1809        assert!(lists.contains_key("bar"));
1810
1811        // this test also ensures that Tokio is not panicking when calling
1812        // `add_list`.
1813
1814        Ok(())
1815    }
1816
1817    #[cfg(feature = "e2e-encryption")]
1818    #[async_test]
1819    async fn test_extensions_to_device_since_is_set() {
1820        use matrix_sdk_base::crypto::store::types::Changes;
1821
1822        let client = logged_in_client(None).await;
1823        let sliding_sync = SlidingSyncBuilder::new("foo".to_owned(), client.clone())
1824            .unwrap()
1825            .with_to_device_extension(assign!(
1826                http::request::ToDevice::default(),
1827                {
1828                    enabled: true,
1829                }
1830            ))
1831            .build()
1832            .await
1833            .unwrap();
1834
1835        // Test `SlidingSyncInner::extensions`.
1836        {
1837            let to_device = &sliding_sync.inner.extensions.to_device;
1838
1839            assert!(to_device.enabled);
1840            assert!(to_device.since.is_none());
1841        }
1842
1843        // Test `Request::extensions`.
1844        {
1845            let (request, _, _) = sliding_sync.generate_sync_request().await.unwrap();
1846
1847            let to_device = &request.extensions.to_device;
1848
1849            assert!(to_device.enabled);
1850            assert!(to_device.since.is_none());
1851        }
1852
1853        // Define a `since` token.
1854        let since_token = "depuis".to_owned();
1855
1856        {
1857            if let Some(olm_machine) = &*client.olm_machine().await {
1858                olm_machine
1859                    .store()
1860                    .save_changes(Changes {
1861                        next_batch_token: Some(since_token.clone()),
1862                        ..Default::default()
1863                    })
1864                    .await
1865                    .unwrap();
1866            } else {
1867                panic!("Where is the Olm machine?");
1868            }
1869        }
1870
1871        // Test `Request::extensions` again.
1872        {
1873            let (request, _, _) = sliding_sync.generate_sync_request().await.unwrap();
1874
1875            let to_device = &request.extensions.to_device;
1876
1877            assert!(to_device.enabled);
1878            assert_eq!(to_device.since, Some(since_token));
1879        }
1880    }
1881
1882    // With MSC4186, with the `e2ee` extension enabled, if a request has no
1883    // `pos`, all the tracked users by the `OlmMachine` must be marked as dirty,
1884    // i.e. `/key/query` requests must be sent. See the code to see the details.
1885    //
1886    // This test is asserting that.
1887    #[async_test]
1888    #[cfg(feature = "e2e-encryption")]
1889    async fn test_no_pos_with_e2ee_marks_all_tracked_users_as_dirty() -> anyhow::Result<()> {
1890        use matrix_sdk_base::crypto::types::requests::{AnyIncomingResponse, AnyOutgoingRequest};
1891        use matrix_sdk_test::ruma_response_from_json;
1892        use ruma::user_id;
1893
1894        let server = MockServer::start().await;
1895        let client = logged_in_client(Some(server.uri())).await;
1896
1897        let alice = user_id!("@alice:localhost");
1898        let bob = user_id!("@bob:localhost");
1899        let me = user_id!("@example:localhost");
1900
1901        // Track and mark users are not dirty, so that we can check they are
1902        // “dirty” after that. Dirty here means that a `/key/query` must be
1903        // sent.
1904        {
1905            let olm_machine = client.olm_machine().await;
1906            let olm_machine = olm_machine.as_ref().unwrap();
1907
1908            olm_machine.update_tracked_users([alice, bob]).await?;
1909
1910            // Assert requests.
1911            let outgoing_requests = olm_machine.outgoing_requests().await?;
1912
1913            assert_eq!(outgoing_requests.len(), 2);
1914            assert_matches!(outgoing_requests[0].request(), AnyOutgoingRequest::KeysUpload(_));
1915            assert_matches!(outgoing_requests[1].request(), AnyOutgoingRequest::KeysQuery(_));
1916
1917            // Fake responses.
1918            olm_machine
1919                .mark_request_as_sent(
1920                    outgoing_requests[0].request_id(),
1921                    AnyIncomingResponse::KeysUpload(&ruma_response_from_json(&json!({
1922                        "one_time_key_counts": {}
1923                    }))),
1924                )
1925                .await?;
1926
1927            olm_machine
1928                .mark_request_as_sent(
1929                    outgoing_requests[1].request_id(),
1930                    AnyIncomingResponse::KeysQuery(&ruma_response_from_json(&json!({
1931                        "device_keys": {
1932                            alice: {},
1933                            bob: {},
1934                        }
1935                    }))),
1936                )
1937                .await?;
1938
1939            // Once more.
1940            let outgoing_requests = olm_machine.outgoing_requests().await?;
1941
1942            assert_eq!(outgoing_requests.len(), 1);
1943            assert_matches!(outgoing_requests[0].request(), AnyOutgoingRequest::KeysQuery(_));
1944
1945            olm_machine
1946                .mark_request_as_sent(
1947                    outgoing_requests[0].request_id(),
1948                    AnyIncomingResponse::KeysQuery(&ruma_response_from_json(&json!({
1949                        "device_keys": {
1950                            me: {},
1951                        }
1952                    }))),
1953                )
1954                .await?;
1955
1956            // No more.
1957            let outgoing_requests = olm_machine.outgoing_requests().await?;
1958
1959            assert!(outgoing_requests.is_empty());
1960        }
1961
1962        let sync = client
1963            .sliding_sync("test-slidingsync")?
1964            .add_list(SlidingSyncList::builder("new_list"))
1965            .with_e2ee_extension(assign!(http::request::E2EE::default(), { enabled: true }))
1966            .build()
1967            .await?;
1968
1969        // First request: no `pos`.
1970        let (_request, _, _) = sync.generate_sync_request().await?;
1971
1972        // Now, tracked users must be dirty.
1973        {
1974            let olm_machine = client.olm_machine().await;
1975            let olm_machine = olm_machine.as_ref().unwrap();
1976
1977            // Assert requests.
1978            let outgoing_requests = olm_machine.outgoing_requests().await?;
1979
1980            assert_eq!(outgoing_requests.len(), 1);
1981            assert_matches!(
1982                outgoing_requests[0].request(),
1983                AnyOutgoingRequest::KeysQuery(request) => {
1984                    assert!(request.device_keys.contains_key(alice));
1985                    assert!(request.device_keys.contains_key(bob));
1986                    assert!(request.device_keys.contains_key(me));
1987                }
1988            );
1989
1990            // Fake responses.
1991            olm_machine
1992                .mark_request_as_sent(
1993                    outgoing_requests[0].request_id(),
1994                    AnyIncomingResponse::KeysQuery(&ruma_response_from_json(&json!({
1995                        "device_keys": {
1996                            alice: {},
1997                            bob: {},
1998                            me: {},
1999                        }
2000                    }))),
2001                )
2002                .await?;
2003        }
2004
2005        // Second request: with a `pos` this time.
2006        sync.set_pos("chocolat".to_owned()).await;
2007
2008        let (_request, _, _) = sync.generate_sync_request().await?;
2009
2010        // Tracked users are not marked as dirty.
2011        {
2012            let olm_machine = client.olm_machine().await;
2013            let olm_machine = olm_machine.as_ref().unwrap();
2014
2015            // Assert requests.
2016            let outgoing_requests = olm_machine.outgoing_requests().await?;
2017
2018            assert!(outgoing_requests.is_empty());
2019        }
2020
2021        Ok(())
2022    }
2023
2024    #[cfg(feature = "e2e-encryption")]
2025    #[async_test]
2026    async fn test_e2ee_requests_are_sent_after_handling_response() -> Result<()> {
2027        let server = MockServer::start().await;
2028
2029        // The response reports no one-time keys left, so handling it queues a
2030        // new `/keys/upload`.
2031        Mock::given(SlidingSyncMatcher)
2032            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
2033                "pos": "0",
2034                "extensions": {
2035                    "e2ee": { "device_one_time_keys_count": { "signed_curve25519": 0 } },
2036                },
2037            })))
2038            .mount(&server)
2039            .await;
2040
2041        // Once alongside the sync request, once after handling its response.
2042        Mock::given(method("POST"))
2043            .and(wiremock::matchers::path_regex("/keys/upload$"))
2044            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
2045                "one_time_key_counts": { "signed_curve25519": 50 },
2046            })))
2047            .expect(2)
2048            .mount(&server)
2049            .await;
2050
2051        let client = logged_in_client(Some(server.uri())).await;
2052        let sliding_sync = client
2053            .sliding_sync("e2ee")?
2054            .with_e2ee_extension(assign!(http::request::E2EE::default(), { enabled: true}))
2055            .build()
2056            .await?;
2057
2058        // A single iteration: the second upload must not wait for the next one.
2059        sliding_sync.sync_once().await?;
2060        server.verify().await;
2061
2062        Ok(())
2063    }
2064
2065    #[cfg(feature = "e2e-encryption")]
2066    #[async_test]
2067    async fn test_sliding_sync_doesnt_remember_pos() -> Result<()> {
2068        let server = MockServer::start().await;
2069
2070        #[derive(Deserialize)]
2071        struct PartialRequest {
2072            txn_id: Option<String>,
2073        }
2074
2075        let server_pos = Arc::new(Mutex::new(0));
2076        let _mock_guard = Mock::given(SlidingSyncMatcher)
2077            .respond_with(move |request: &Request| {
2078                // Repeat the txn_id in the response, if set.
2079                let request: PartialRequest = request.body_json().unwrap();
2080                let pos = {
2081                    let mut pos = server_pos.lock().unwrap();
2082                    let prev = *pos;
2083                    *pos += 1;
2084                    prev
2085                };
2086
2087                ResponseTemplate::new(200).set_body_json(json!({
2088                    "txn_id": request.txn_id,
2089                    "pos": pos.to_string(),
2090                }))
2091            })
2092            .mount_as_scoped(&server)
2093            .await;
2094
2095        let client = logged_in_client(Some(server.uri())).await;
2096
2097        let sliding_sync = client.sliding_sync("forgetful-sync")?.build().await?;
2098
2099        // `pos` is `None` to start with.
2100        {
2101            assert!(sliding_sync.inner.position.lock().await.pos.is_none());
2102
2103            let (request, _, _) = sliding_sync.generate_sync_request().await?;
2104            assert!(request.pos.is_none());
2105        }
2106
2107        let sync = sliding_sync.sync();
2108        let mut sync = pin!(sync);
2109
2110        // Sync goes well, and then the position is saved both into the internal
2111        // memory and the database.
2112        let next = sync.next().await;
2113        assert_matches!(next, Some(Ok(_update_summary)));
2114
2115        assert_eq!(sliding_sync.inner.position.lock().await.pos.as_deref(), Some("0"));
2116
2117        let restored_fields = restore_sliding_sync_state(&client, &sliding_sync.inner.storage_key)
2118            .await?
2119            .expect("must have restored fields");
2120
2121        // While it has been saved into the database, it's not necessarily going
2122        // to be used later!
2123        assert_eq!(restored_fields.pos.as_deref(), Some("0"));
2124
2125        // Now, even if we mess with the position stored in the database, the
2126        // sliding sync instance isn't configured to reload the stream position
2127        // from the database, so it won't be changed.
2128        {
2129            let other_sync = client.sliding_sync("forgetful-sync")?.build().await?;
2130
2131            let mut position_guard = other_sync.inner.position.lock().await;
2132            position_guard.pos = Some("yolo".to_owned());
2133
2134            other_sync.cache_to_storage(&position_guard).await?;
2135        }
2136
2137        // It's still 0, not "yolo".
2138        {
2139            assert_eq!(sliding_sync.inner.position.lock().await.pos.as_deref(), Some("0"));
2140            let (request, _, _) = sliding_sync.generate_sync_request().await?;
2141            assert_eq!(request.pos.as_deref(), Some("0"));
2142        }
2143
2144        // Recreating a sliding sync with the same ID doesn't preload the pos,
2145        // if not asked to.
2146        {
2147            let sliding_sync = client.sliding_sync("forgetful-sync")?.build().await?;
2148            assert!(sliding_sync.inner.position.lock().await.pos.is_none());
2149        }
2150
2151        Ok(())
2152    }
2153
2154    #[cfg(feature = "e2e-encryption")]
2155    #[async_test]
2156    async fn test_sliding_sync_does_remember_pos() -> Result<()> {
2157        let server = MockServer::start().await;
2158
2159        #[derive(Deserialize)]
2160        struct PartialRequest {
2161            txn_id: Option<String>,
2162        }
2163
2164        let server_pos = Arc::new(Mutex::new(0));
2165        let _mock_guard = Mock::given(SlidingSyncMatcher)
2166            .respond_with(move |request: &Request| {
2167                // Repeat the txn_id in the response, if set.
2168                let request: PartialRequest = request.body_json().unwrap();
2169                let pos = {
2170                    let mut pos = server_pos.lock().unwrap();
2171                    let prev = *pos;
2172                    *pos += 1;
2173                    prev
2174                };
2175
2176                ResponseTemplate::new(200).set_body_json(json!({
2177                    "txn_id": request.txn_id,
2178                    "pos": pos.to_string(),
2179                }))
2180            })
2181            .mount_as_scoped(&server)
2182            .await;
2183
2184        let client = logged_in_client(Some(server.uri())).await;
2185
2186        let sliding_sync = client.sliding_sync("elephant-sync")?.share_pos().build().await?;
2187
2188        // `pos` is `None` to start with.
2189        {
2190            let (request, _, _) = sliding_sync.generate_sync_request().await?;
2191
2192            assert!(request.pos.is_none());
2193            assert!(sliding_sync.inner.position.lock().await.pos.is_none());
2194        }
2195
2196        let sync = sliding_sync.sync();
2197        let mut sync = pin!(sync);
2198
2199        // Sync goes well, and then the position is saved both into the internal
2200        // memory and the database.
2201        let next = sync.next().await;
2202        assert_matches!(next, Some(Ok(_update_summary)));
2203
2204        assert_eq!(sliding_sync.inner.position.lock().await.pos, Some("0".to_owned()));
2205
2206        let restored_fields = restore_sliding_sync_state(&client, &sliding_sync.inner.storage_key)
2207            .await?
2208            .expect("must have restored fields");
2209
2210        // While it has been saved into the database, it's not necessarily going
2211        // to be used later!
2212        assert_eq!(restored_fields.pos.as_deref(), Some("0"));
2213
2214        // Another process modifies the stream position under our feet...
2215        {
2216            let other_sync = client.sliding_sync("elephant-sync")?.build().await?;
2217
2218            let mut position_guard = other_sync.inner.position.lock().await;
2219            position_guard.pos = Some("42".to_owned());
2220
2221            other_sync.cache_to_storage(&position_guard).await?;
2222        }
2223
2224        // It's alright, the next request will load it from the database.
2225        {
2226            let (request, _, _) = sliding_sync.generate_sync_request().await?;
2227            assert_eq!(request.pos.as_deref(), Some("42"));
2228            assert_eq!(sliding_sync.inner.position.lock().await.pos.as_deref(), Some("42"));
2229        }
2230
2231        // Recreating a sliding sync with the same ID will reload it too.
2232        {
2233            let sliding_sync = client.sliding_sync("elephant-sync")?.share_pos().build().await?;
2234            assert_eq!(sliding_sync.inner.position.lock().await.pos.as_deref(), Some("42"));
2235
2236            let (request, _, _) = sliding_sync.generate_sync_request().await?;
2237            assert_eq!(request.pos.as_deref(), Some("42"));
2238        }
2239
2240        // Invalidating the session will remove the in-memory value AND the
2241        // database value.
2242        sliding_sync.expire_session().await;
2243
2244        {
2245            assert!(sliding_sync.inner.position.lock().await.pos.is_none());
2246
2247            let (request, _, _) = sliding_sync.generate_sync_request().await?;
2248            assert!(request.pos.is_none());
2249        }
2250
2251        // And new sliding syncs with the same ID won't find it either.
2252        {
2253            let sliding_sync = client.sliding_sync("elephant-sync")?.share_pos().build().await?;
2254            assert!(sliding_sync.inner.position.lock().await.pos.is_none());
2255
2256            let (request, _, _) = sliding_sync.generate_sync_request().await?;
2257            assert!(request.pos.is_none());
2258        }
2259
2260        Ok(())
2261    }
2262
2263    #[async_test]
2264    async fn test_stop_sync_loop() -> Result<()> {
2265        let (_server, sliding_sync) = new_sliding_sync(vec![
2266            SlidingSyncList::builder("foo")
2267                .sync_mode(SlidingSyncMode::new_selective().range(0..=10)),
2268        ])
2269        .await?;
2270
2271        // Start the sync loop.
2272        let stream = sliding_sync.sync();
2273        let mut stream = pin!(stream);
2274
2275        // The sync loop is actually running.
2276        assert!(stream.next().await.is_some());
2277
2278        // Stop the sync loop.
2279        sliding_sync.stop_sync()?;
2280
2281        // The sync loop is actually stopped.
2282        assert!(stream.next().await.is_none());
2283
2284        // Start a new sync loop.
2285        let stream = sliding_sync.sync();
2286        let mut stream = pin!(stream);
2287
2288        // The sync loop is actually running.
2289        assert!(stream.next().await.is_some());
2290
2291        Ok(())
2292    }
2293
2294    #[async_test]
2295    async fn test_process_read_receipts() -> Result<()> {
2296        let room = owned_room_id!("!pony:example.org");
2297
2298        let server = MockServer::start().await;
2299        let client = logged_in_client(Some(server.uri())).await;
2300
2301        let sliding_sync = client
2302            .sliding_sync("test")?
2303            .with_receipt_extension(
2304                assign!(http::request::Receipts::default(), { enabled: Some(true) }),
2305            )
2306            .add_list(
2307                SlidingSyncList::builder("all")
2308                    .sync_mode(SlidingSyncMode::new_selective().range(0..=100)),
2309            )
2310            .build()
2311            .await?;
2312
2313        // Initial state.
2314        {
2315            let server_response = assign!(http::Response::new("0".to_owned()), {
2316                rooms: BTreeMap::from([(
2317                    room.clone(),
2318                    http::response::Room::default(),
2319                )])
2320            });
2321
2322            let _summary = {
2323                let mut pos_guard = sliding_sync.inner.position.clone().lock_owned().await;
2324                sliding_sync
2325                    .handle_response(
2326                        server_response.clone(),
2327                        &mut pos_guard,
2328                        RequestedRequiredStates::default(),
2329                    )
2330                    .await?
2331            };
2332        }
2333
2334        let server_response = assign!(http::Response::new("1".to_owned()), {
2335            extensions: assign!(http::response::Extensions::default(), {
2336                receipts: assign!(http::response::Receipts::default(), {
2337                    rooms: BTreeMap::from([
2338                        (
2339                            room.clone(),
2340                            Raw::from_json_string(
2341                                json!({
2342                                    "room_id": room,
2343                                    "type": "m.receipt",
2344                                    "content": {
2345                                        "$event:bar.org": {
2346                                            "m.read": {
2347                                                client.user_id().unwrap(): {
2348                                                    "ts": 1436451550,
2349                                                }
2350                                            }
2351                                        }
2352                                    }
2353                                })
2354                                .to_string(),
2355                            ).unwrap()
2356                        )
2357                    ])
2358                })
2359            })
2360        });
2361
2362        let summary = {
2363            let mut pos_guard = sliding_sync.inner.position.clone().lock_owned().await;
2364            sliding_sync
2365                .handle_response(
2366                    server_response.clone(),
2367                    &mut pos_guard,
2368                    RequestedRequiredStates::default(),
2369                )
2370                .await?
2371        };
2372
2373        assert!(summary.rooms.contains(&room));
2374
2375        Ok(())
2376    }
2377
2378    #[async_test]
2379    async fn test_process_marked_unread_room_account_data() -> Result<()> {
2380        let room_id = owned_room_id!("!unicorn:example.org");
2381
2382        let server = MockServer::start().await;
2383        let client = logged_in_client(Some(server.uri())).await;
2384
2385        // Setup sliding sync with with one room and one list
2386
2387        let sliding_sync = client
2388            .sliding_sync("test")?
2389            .with_account_data_extension(
2390                assign!(http::request::AccountData::default(), { enabled: Some(true) }),
2391            )
2392            .add_list(
2393                SlidingSyncList::builder("all")
2394                    .sync_mode(SlidingSyncMode::new_selective().range(0..=100)),
2395            )
2396            .build()
2397            .await?;
2398
2399        // Initial state.
2400        {
2401            let server_response = assign!(http::Response::new("0".to_owned()), {
2402                rooms: BTreeMap::from([(
2403                    room_id.clone(),
2404                    http::response::Room::default(),
2405                )])
2406            });
2407
2408            let _summary = {
2409                let mut pos_guard = sliding_sync.inner.position.clone().lock_owned().await;
2410                sliding_sync
2411                    .handle_response(
2412                        server_response.clone(),
2413                        &mut pos_guard,
2414                        RequestedRequiredStates::default(),
2415                    )
2416                    .await?
2417            };
2418        }
2419
2420        // Simulate a response that only changes the marked unread state of the
2421        // room to true
2422
2423        let server_response = make_mark_unread_response("1", room_id.clone(), true, false);
2424
2425        let update_summary = {
2426            let mut pos_guard = sliding_sync.inner.position.clone().lock_owned().await;
2427            sliding_sync
2428                .handle_response(
2429                    server_response.clone(),
2430                    &mut pos_guard,
2431                    RequestedRequiredStates::default(),
2432                )
2433                .await?
2434        };
2435
2436        // Check that the list list and entry received the update
2437
2438        assert!(update_summary.rooms.contains(&room_id));
2439
2440        let room = client.get_room(&room_id).unwrap();
2441
2442        // Check the actual room data, this powers RoomInfo
2443
2444        assert!(room.is_marked_unread());
2445
2446        // Change it back to false and check if it updates
2447
2448        let server_response = make_mark_unread_response("2", room_id.clone(), false, true);
2449
2450        let mut pos_guard = sliding_sync.inner.position.clone().lock_owned().await;
2451        sliding_sync
2452            .handle_response(
2453                server_response.clone(),
2454                &mut pos_guard,
2455                RequestedRequiredStates::default(),
2456            )
2457            .await?;
2458
2459        let room = client.get_room(&room_id).unwrap();
2460
2461        assert!(!room.is_marked_unread());
2462
2463        Ok(())
2464    }
2465
2466    fn make_mark_unread_response(
2467        response_number: &str,
2468        room_id: OwnedRoomId,
2469        unread: bool,
2470        add_rooms_section: bool,
2471    ) -> http::Response {
2472        let rooms = if add_rooms_section {
2473            BTreeMap::from([(room_id.clone(), http::response::Room::default())])
2474        } else {
2475            BTreeMap::new()
2476        };
2477
2478        let extensions = assign!(http::response::Extensions::default(), {
2479            account_data: assign!(http::response::AccountData::default(), {
2480                rooms: BTreeMap::from([
2481                    (
2482                        room_id,
2483                        vec![
2484                            Raw::from_json_string(
2485                                json!({
2486                                    "content": {
2487                                        "unread": unread
2488                                    },
2489                                    "type": "m.marked_unread"
2490                                })
2491                                .to_string(),
2492                            ).unwrap()
2493                        ]
2494                    )
2495                ])
2496            })
2497        });
2498
2499        assign!(http::Response::new(response_number.to_owned()), { rooms: rooms, extensions: extensions })
2500    }
2501
2502    #[async_test]
2503    async fn test_process_rooms_account_data() -> Result<()> {
2504        let room = owned_room_id!("!pony:example.org");
2505
2506        let server = MockServer::start().await;
2507        let client = logged_in_client(Some(server.uri())).await;
2508
2509        let sliding_sync = client
2510            .sliding_sync("test")?
2511            .with_account_data_extension(
2512                assign!(http::request::AccountData::default(), { enabled: Some(true) }),
2513            )
2514            .add_list(
2515                SlidingSyncList::builder("all")
2516                    .sync_mode(SlidingSyncMode::new_selective().range(0..=100)),
2517            )
2518            .build()
2519            .await?;
2520
2521        // Initial state.
2522        {
2523            let server_response = assign!(http::Response::new("0".to_owned()), {
2524                rooms: BTreeMap::from([(
2525                    room.clone(),
2526                    http::response::Room::default(),
2527                )])
2528            });
2529
2530            let _summary = {
2531                let mut pos_guard = sliding_sync.inner.position.clone().lock_owned().await;
2532                sliding_sync
2533                    .handle_response(
2534                        server_response.clone(),
2535                        &mut pos_guard,
2536                        RequestedRequiredStates::default(),
2537                    )
2538                    .await?
2539            };
2540        }
2541
2542        let server_response = assign!(http::Response::new("1".to_owned()), {
2543            extensions: assign!(http::response::Extensions::default(), {
2544                account_data: assign!(http::response::AccountData::default(), {
2545                    rooms: BTreeMap::from([
2546                        (
2547                            room.clone(),
2548                            vec![
2549                                Raw::from_json_string(
2550                                    json!({
2551                                        "content": {
2552                                            "tags": {
2553                                                "u.work": {
2554                                                    "order": 0.9
2555                                                }
2556                                            }
2557                                        },
2558                                        "type": "m.tag"
2559                                    })
2560                                    .to_string(),
2561                                ).unwrap()
2562                            ]
2563                        )
2564                    ])
2565                })
2566            })
2567        });
2568        let summary = {
2569            let mut pos_guard = sliding_sync.inner.position.clone().lock_owned().await;
2570            sliding_sync
2571                .handle_response(
2572                    server_response.clone(),
2573                    &mut pos_guard,
2574                    RequestedRequiredStates::default(),
2575                )
2576                .await?
2577        };
2578
2579        assert!(summary.rooms.contains(&room));
2580
2581        Ok(())
2582    }
2583
2584    #[async_test]
2585    #[cfg(feature = "e2e-encryption")]
2586    async fn test_process_only_encryption_events() -> Result<()> {
2587        use ruma::OneTimeKeyAlgorithm;
2588
2589        let room = owned_room_id!("!croissant:example.org");
2590
2591        let server = MockServer::start().await;
2592        let client = logged_in_client(Some(server.uri())).await;
2593
2594        let server_response = assign!(http::Response::new("0".to_owned()), {
2595            rooms: BTreeMap::from([(
2596                room.clone(),
2597                assign!(http::response::Room::default(), {
2598                    name: Some("Croissants lovers".to_owned()),
2599                    timeline: Vec::new(),
2600                }),
2601            )]),
2602
2603            extensions: assign!(http::response::Extensions::default(), {
2604                e2ee: assign!(http::response::E2EE::default(), {
2605                    device_one_time_keys_count: BTreeMap::from([(OneTimeKeyAlgorithm::SignedCurve25519, uint!(42))])
2606                }),
2607                to_device: Some(assign!(http::response::ToDevice::default(), {
2608                    next_batch: "to-device-token".to_owned(),
2609                })),
2610            })
2611        });
2612
2613        // Don't process non-encryption events if the sliding sync is configured
2614        // for encryption only.
2615
2616        let sliding_sync = client
2617            .sliding_sync("test")?
2618            .with_to_device_extension(
2619                assign!(http::request::ToDevice::default(), { enabled: true }),
2620            )
2621            .with_e2ee_extension(assign!(http::request::E2EE::default(), { enabled: true }))
2622            .build()
2623            .await?;
2624
2625        {
2626            let mut position_guard = sliding_sync.inner.position.clone().lock_owned().await;
2627
2628            sliding_sync
2629                .handle_response(
2630                    server_response.clone(),
2631                    &mut position_guard,
2632                    RequestedRequiredStates::default(),
2633                )
2634                .await?;
2635        }
2636
2637        // E2EE has been properly handled.
2638        let uploaded_key_count = client.encryption().uploaded_key_count().await?;
2639        assert_eq!(uploaded_key_count, 42);
2640
2641        {
2642            let olm_machine = &*client.olm_machine_for_testing().await;
2643            assert_eq!(
2644                olm_machine.as_ref().unwrap().store().next_batch_token().await?.as_deref(),
2645                Some("to-device-token")
2646            );
2647        }
2648
2649        // Room events haven't.
2650        assert!(client.get_room(&room).is_none());
2651
2652        // Conversely, only process room lists events if the sliding sync was
2653        // configured as so.
2654        let client = logged_in_client(Some(server.uri())).await;
2655
2656        let sliding_sync = client
2657            .sliding_sync("test")?
2658            .add_list(SlidingSyncList::builder("thelist"))
2659            .build()
2660            .await?;
2661
2662        {
2663            let mut position_guard = sliding_sync.inner.position.clone().lock_owned().await;
2664
2665            sliding_sync
2666                .handle_response(
2667                    server_response.clone(),
2668                    &mut position_guard,
2669                    RequestedRequiredStates::default(),
2670                )
2671                .await?;
2672        }
2673
2674        // E2EE response has been ignored.
2675        let uploaded_key_count = client.encryption().uploaded_key_count().await?;
2676        assert_eq!(uploaded_key_count, 0);
2677
2678        {
2679            let olm_machine = &*client.olm_machine_for_testing().await;
2680            assert_eq!(
2681                olm_machine.as_ref().unwrap().store().next_batch_token().await?.as_deref(),
2682                None
2683            );
2684        }
2685
2686        // The room is now known.
2687        assert!(client.get_room(&room).is_some());
2688
2689        // And it's also possible to set up both.
2690        let client = logged_in_client(Some(server.uri())).await;
2691
2692        let sliding_sync = client
2693            .sliding_sync("test")?
2694            .add_list(SlidingSyncList::builder("thelist"))
2695            .with_to_device_extension(
2696                assign!(http::request::ToDevice::default(), { enabled: true }),
2697            )
2698            .with_e2ee_extension(assign!(http::request::E2EE::default(), { enabled: true }))
2699            .build()
2700            .await?;
2701
2702        {
2703            let mut position_guard = sliding_sync.inner.position.clone().lock_owned().await;
2704
2705            sliding_sync
2706                .handle_response(
2707                    server_response.clone(),
2708                    &mut position_guard,
2709                    RequestedRequiredStates::default(),
2710                )
2711                .await?;
2712        }
2713
2714        // E2EE has been properly handled.
2715        let uploaded_key_count = client.encryption().uploaded_key_count().await?;
2716        assert_eq!(uploaded_key_count, 42);
2717
2718        {
2719            let olm_machine = &*client.olm_machine_for_testing().await;
2720            assert_eq!(
2721                olm_machine.as_ref().unwrap().store().next_batch_token().await?.as_deref(),
2722                Some("to-device-token")
2723            );
2724        }
2725
2726        // The room is now known.
2727        assert!(client.get_room(&room).is_some());
2728
2729        Ok(())
2730    }
2731
2732    #[async_test]
2733    async fn test_lock_multiple_requests() -> Result<()> {
2734        let server = MockServer::start().await;
2735        let client = logged_in_client(Some(server.uri())).await;
2736
2737        let pos = Arc::new(Mutex::new(0));
2738        let _mock_guard = Mock::given(SlidingSyncMatcher)
2739            .respond_with(move |_: &Request| {
2740                let mut pos = pos.lock().unwrap();
2741                *pos += 1;
2742                ResponseTemplate::new(200).set_body_json(json!({
2743                    "pos": pos.to_string(),
2744                    "lists": {},
2745                    "rooms": {}
2746                }))
2747            })
2748            .mount_as_scoped(&server)
2749            .await;
2750
2751        let sliding_sync = client
2752            .sliding_sync("test")?
2753            .with_to_device_extension(
2754                assign!(http::request::ToDevice::default(), { enabled: true }),
2755            )
2756            .with_e2ee_extension(assign!(http::request::E2EE::default(), { enabled: true }))
2757            .build()
2758            .await?;
2759
2760        // Spawn two requests in parallel. Before #2430, this lead to a deadlock
2761        // and the test would never terminate.
2762        let requests = join_all([sliding_sync.sync_once(), sliding_sync.sync_once()]);
2763
2764        for result in requests.await {
2765            result?;
2766        }
2767
2768        Ok(())
2769    }
2770
2771    #[async_test]
2772    async fn test_aborted_request_doesnt_update_future_requests() -> Result<()> {
2773        let server = MockServer::start().await;
2774        let client = logged_in_client(Some(server.uri())).await;
2775
2776        let pos = Arc::new(Mutex::new(0));
2777        let _mock_guard = Mock::given(SlidingSyncMatcher)
2778            .respond_with(move |_: &Request| {
2779                let mut pos = pos.lock().unwrap();
2780                *pos += 1;
2781                // Respond slowly enough that we can skip one iteration.
2782                ResponseTemplate::new(200)
2783                    .set_body_json(json!({
2784                        "pos": pos.to_string(),
2785                        "lists": {},
2786                        "rooms": {}
2787                    }))
2788                    .set_delay(Duration::from_secs(2))
2789            })
2790            .mount_as_scoped(&server)
2791            .await;
2792
2793        let sliding_sync =
2794            client
2795                .sliding_sync("test")?
2796                .add_list(SlidingSyncList::builder("room-list").sync_mode(
2797                    SlidingSyncMode::new_growing(10).maximum_number_of_rooms_to_fetch(100),
2798                ))
2799                .add_list(
2800                    SlidingSyncList::builder("another-list")
2801                        .sync_mode(SlidingSyncMode::new_selective().range(0..=10)),
2802                )
2803                .build()
2804                .await?;
2805
2806        let stream = sliding_sync.sync();
2807        let mut stream = pin!(stream);
2808
2809        let cloned_sync = sliding_sync.clone();
2810        spawn(async move {
2811            tokio::time::sleep(Duration::from_millis(100)).await;
2812
2813            cloned_sync
2814                .on_list("another-list", |list| {
2815                    list.set_sync_mode(SlidingSyncMode::new_selective().range(10..=20));
2816                    ready(())
2817                })
2818                .await;
2819        });
2820
2821        assert_matches!(stream.next().await, Some(Ok(_)));
2822
2823        sliding_sync.stop_sync().unwrap();
2824
2825        assert_matches!(stream.next().await, None);
2826
2827        let mut num_requests = 0;
2828
2829        for request in server.received_requests().await.unwrap() {
2830            if !SlidingSyncMatcher.matches(&request) {
2831                continue;
2832            }
2833
2834            let another_list_ranges = if num_requests == 0 {
2835                // First request
2836                json!([[0, 10]])
2837            } else {
2838                // Second request
2839                json!([[10, 20]])
2840            };
2841
2842            num_requests += 1;
2843            assert!(num_requests <= 2, "more than one request hit the server");
2844
2845            let json_value = serde_json::from_slice::<serde_json::Value>(&request.body).unwrap();
2846
2847            if let Err(err) = assert_json_diff::assert_json_matches_no_panic(
2848                &json_value,
2849                &json!({
2850                    "conn_id": "test",
2851                    "lists": {
2852                        "room-list": {
2853                            "ranges": [[0, 9]],
2854                            "required_state": [
2855                                ["m.room.encryption", ""],
2856                                ["m.room.tombstone", ""]
2857                            ],
2858                        },
2859                        "another-list": {
2860                            "ranges": another_list_ranges,
2861                            "required_state": [
2862                                ["m.room.encryption", ""],
2863                                ["m.room.tombstone", ""]
2864                            ],
2865                        },
2866                    }
2867                }),
2868                assert_json_diff::Config::new(assert_json_diff::CompareMode::Inclusive),
2869            ) {
2870                dbg!(json_value);
2871                panic!("json differ: {err}");
2872            }
2873        }
2874
2875        assert_eq!(num_requests, 2);
2876
2877        Ok(())
2878    }
2879
2880    #[async_test]
2881    async fn test_timeout_zero_list() -> Result<()> {
2882        let (_server, sliding_sync) = new_sliding_sync(vec![]).await?;
2883
2884        let (request, _, _) = sliding_sync.generate_sync_request().await?;
2885
2886        // Zero list means sliding sync is fully loaded, so there is a timeout
2887        // to wait on new update to pop.
2888        assert!(request.timeout.is_some());
2889
2890        Ok(())
2891    }
2892
2893    #[async_test]
2894    async fn test_timeout_one_list() -> Result<()> {
2895        let (_server, sliding_sync) = new_sliding_sync(vec![
2896            SlidingSyncList::builder("foo").sync_mode(SlidingSyncMode::new_growing(10)),
2897        ])
2898        .await?;
2899
2900        let (request, _, _) = sliding_sync.generate_sync_request().await?;
2901
2902        // The list does not require a timeout.
2903        assert!(request.timeout.is_none());
2904
2905        // Simulate a response.
2906        {
2907            let server_response = assign!(http::Response::new("0".to_owned()), {
2908                lists: BTreeMap::from([(
2909                    "foo".to_owned(),
2910                    assign!(http::response::List::default(), {
2911                        count: uint!(7),
2912                    })
2913                 )])
2914            });
2915
2916            let _summary = {
2917                let mut pos_guard = sliding_sync.inner.position.clone().lock_owned().await;
2918                sliding_sync
2919                    .handle_response(
2920                        server_response.clone(),
2921                        &mut pos_guard,
2922                        RequestedRequiredStates::default(),
2923                    )
2924                    .await?
2925            };
2926        }
2927
2928        let (request, _, _) = sliding_sync.generate_sync_request().await?;
2929
2930        // The list is now fully loaded, so it requires a timeout.
2931        assert!(request.timeout.is_some());
2932
2933        Ok(())
2934    }
2935
2936    #[async_test]
2937    async fn test_timeout_three_lists() -> Result<()> {
2938        let (_server, sliding_sync) = new_sliding_sync(vec![
2939            SlidingSyncList::builder("foo").sync_mode(SlidingSyncMode::new_growing(10)),
2940            SlidingSyncList::builder("bar").sync_mode(SlidingSyncMode::new_paging(10)),
2941            SlidingSyncList::builder("baz")
2942                .sync_mode(SlidingSyncMode::new_selective().range(0..=10)),
2943        ])
2944        .await?;
2945
2946        let (request, _, _) = sliding_sync.generate_sync_request().await?;
2947
2948        // Two lists don't require a timeout.
2949        assert!(request.timeout.is_none());
2950
2951        // Simulate a response.
2952        {
2953            let server_response = assign!(http::Response::new("0".to_owned()), {
2954                lists: BTreeMap::from([(
2955                    "foo".to_owned(),
2956                    assign!(http::response::List::default(), {
2957                        count: uint!(7),
2958                    })
2959                 )])
2960            });
2961
2962            let _summary = {
2963                let mut pos_guard = sliding_sync.inner.position.clone().lock_owned().await;
2964                sliding_sync
2965                    .handle_response(
2966                        server_response.clone(),
2967                        &mut pos_guard,
2968                        RequestedRequiredStates::default(),
2969                    )
2970                    .await?
2971            };
2972        }
2973
2974        let (request, _, _) = sliding_sync.generate_sync_request().await?;
2975
2976        // One don't require a timeout.
2977        assert!(request.timeout.is_none());
2978
2979        // Simulate a response.
2980        {
2981            let server_response = assign!(http::Response::new("1".to_owned()), {
2982                lists: BTreeMap::from([(
2983                    "bar".to_owned(),
2984                    assign!(http::response::List::default(), {
2985                        count: uint!(7),
2986                    })
2987                 )])
2988            });
2989
2990            let _summary = {
2991                let mut pos_guard = sliding_sync.inner.position.clone().lock_owned().await;
2992                sliding_sync
2993                    .handle_response(
2994                        server_response.clone(),
2995                        &mut pos_guard,
2996                        RequestedRequiredStates::default(),
2997                    )
2998                    .await?
2999            };
3000        }
3001
3002        let (request, _, _) = sliding_sync.generate_sync_request().await?;
3003
3004        // All lists require a timeout.
3005        assert!(request.timeout.is_some());
3006
3007        Ok(())
3008    }
3009
3010    #[async_test]
3011    async fn test_sync_beat_is_notified_on_sync_response() -> Result<()> {
3012        let server = MockServer::start().await;
3013        let client = logged_in_client(Some(server.uri())).await;
3014
3015        let _mock_guard = Mock::given(SlidingSyncMatcher)
3016            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
3017                "pos": "0",
3018                "lists": {},
3019                "rooms": {}
3020            })))
3021            .mount_as_scoped(&server)
3022            .await;
3023
3024        let sliding_sync = client
3025            .sliding_sync("test")?
3026            .with_to_device_extension(
3027                assign!(http::request::ToDevice::default(), { enabled: true }),
3028            )
3029            .with_e2ee_extension(assign!(http::request::E2EE::default(), { enabled: true }))
3030            .build()
3031            .await?;
3032
3033        let sliding_sync = Arc::new(sliding_sync);
3034
3035        // Create the listener and perform a sync request
3036        let sync_beat_listener = client.inner.sync_beat.listen();
3037        sliding_sync.sync_once().await?;
3038
3039        // The sync beat listener should be notified shortly after
3040        assert!(sync_beat_listener.wait_timeout(Duration::from_secs(1)).is_some());
3041        Ok(())
3042    }
3043
3044    #[async_test]
3045    async fn test_sync_beat_is_not_notified_on_sync_failure() -> Result<()> {
3046        let server = MockServer::start().await;
3047        let client = logged_in_client(Some(server.uri())).await;
3048
3049        let _mock_guard = Mock::given(SlidingSyncMatcher)
3050            .respond_with(ResponseTemplate::new(404))
3051            .mount_as_scoped(&server)
3052            .await;
3053
3054        let sliding_sync = client
3055            .sliding_sync("test")?
3056            .with_to_device_extension(
3057                assign!(http::request::ToDevice::default(), { enabled: true }),
3058            )
3059            .with_e2ee_extension(assign!(http::request::E2EE::default(), { enabled: true }))
3060            .build()
3061            .await?;
3062
3063        let sliding_sync = Arc::new(sliding_sync);
3064
3065        // Create the listener and perform a sync request
3066        let sync_beat_listener = client.inner.sync_beat.listen();
3067        let sync_result = sliding_sync.sync_once().await;
3068        assert!(sync_result.is_err());
3069
3070        // The sync beat listener won't be notified in this case
3071        assert!(sync_beat_listener.wait_timeout(Duration::from_secs(1)).is_none());
3072
3073        Ok(())
3074    }
3075
3076    #[async_test]
3077    async fn test_state_store_lock_is_released_before_calling_handlers() -> Result<()> {
3078        let server = MatrixMockServer::new().await;
3079        let client = server.client_builder().build().await;
3080        let room_id = room_id!("!mu5hr00m:example.org");
3081
3082        let _sync_mock_guard = Mock::given(SlidingSyncMatcher)
3083            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
3084                "pos": "0",
3085                "lists": {},
3086                "extensions": {
3087                    "account_data": {
3088                        "global": [
3089                            {
3090                                "type": "m.direct",
3091                                "content": {
3092                                    "@de4dlockh0lmes:example.org": [
3093                                        "!mu5hr00m:example.org"
3094                                    ]
3095                                }
3096                            }
3097                        ]
3098                    }
3099                },
3100                "rooms": {
3101                    room_id: {
3102                        "name": "Mario Bros Fanbase Room",
3103                        "initial": true,
3104                    },
3105                }
3106            })))
3107            .mount_as_scoped(server.server())
3108            .await;
3109
3110        let f = EventFactory::new().room(room_id);
3111
3112        Mock::given(method("GET"))
3113            .and(wiremock::matchers::path_regex(r"/_matrix/client/v3/rooms/.*/members"))
3114            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
3115                "chunk": [
3116                    f.member(User::Alice).membership(MembershipState::Join).into_raw_timeline(),
3117                ]
3118            })))
3119            .mount(server.server())
3120            .await;
3121
3122        let (tx, rx) = tokio::sync::oneshot::channel();
3123
3124        let tx = Arc::new(Mutex::new(Some(tx)));
3125        client.add_event_handler(move |_: DirectEvent, client: Client| async move {
3126            // Try to run a /members query while in a event handler.
3127            let members =
3128                client.get_room(room_id).unwrap().members(RoomMemberships::JOIN).await.unwrap();
3129            assert_eq!(members.len(), 1);
3130            tx.lock().unwrap().take().expect("sender consumed multiple times").send(()).unwrap();
3131        });
3132
3133        let sliding_sync = client
3134            .sliding_sync("test")?
3135            .add_list(SlidingSyncList::builder("thelist"))
3136            .with_account_data_extension(
3137                assign!(http::request::AccountData::default(), { enabled: Some(true) }),
3138            )
3139            .build()
3140            .await?;
3141
3142        tokio::time::timeout(Duration::from_secs(5), sliding_sync.sync_once())
3143            .await
3144            .expect("Sync did not complete in time")
3145            .expect("Sync failed");
3146
3147        // Wait for the event handler to complete.
3148        tokio::time::timeout(Duration::from_secs(5), rx)
3149            .await
3150            .expect("Event handler did not complete in time")
3151            .expect("Event handler failed");
3152
3153        Ok(())
3154    }
3155
3156    #[cfg(feature = "e2e-encryption")]
3157    #[async_test]
3158    async fn test_syncing_one_time_key_counts_updates() -> Result<()> {
3159        macro_rules! assert_key_count {
3160            ($client: ident, $count:literal) => {{
3161                let machine = $client.olm_machine().await;
3162                let uploaded_key_counts =
3163                    machine.as_ref().unwrap().uploaded_key_count().await.unwrap();
3164                assert_eq!(uploaded_key_counts, $count)
3165            }};
3166        }
3167
3168        macro_rules! sync_with_key_count {
3169            ($client: ident, $server:ident, $count:literal) => {
3170                let count = Some($count);
3171                sync_with_key_count!($client, $server, count);
3172            };
3173            ($client: ident, $server:ident, $count:ident) => {{
3174                let count: Option<u32> = $count;
3175
3176                let template = if let Some(count) = count {
3177                    ResponseTemplate::new(200).set_body_json(json!({
3178                                        "pos": "0",
3179                                        "lists": {},
3180                                        "extensions": {
3181                                            "e2ee": {
3182                                                "device_one_time_keys_count": {
3183                                                    "signed_curve25519": count,
3184                                                }
3185                                            }
3186                                        },
3187                    }))
3188                } else {
3189                    ResponseTemplate::new(200).set_body_json(json!({
3190                                        "pos": "0",
3191                                        "lists": {},
3192                                        "extensions": {
3193                                            "e2ee": {}
3194                                        },
3195                    }))
3196                };
3197
3198                let _sync_mock_guard = Mock::given(SlidingSyncMatcher)
3199                    .respond_with(template)
3200                    .mount_as_scoped($server.server())
3201                    .await;
3202
3203                let sliding_sync = $client
3204                    .sliding_sync("test")?
3205                    .with_e2ee_extension(
3206                        assign!(http::request::E2EE::default(), { enabled: true }),
3207                    )
3208                    .build()
3209                    .await?;
3210
3211                tokio::time::timeout(Duration::from_secs(5), sliding_sync.sync_once())
3212                    .await
3213                    .expect("Sync did not complete in time")
3214                    .expect("Sync failed");
3215            }}
3216        }
3217
3218        let server = MatrixMockServer::new().await;
3219        let client = server.client_builder().build().await;
3220
3221        server.mock_upload_keys().ok_with_signed_curve_key_count(50).mock_once().mount().await;
3222
3223        // In the beginning there were no uploaded keys.
3224        assert_key_count!(client, 0);
3225
3226        // The first sync will upload 50 one-time keys.
3227        sync_with_key_count!(client, server, None);
3228        assert_key_count!(client, 50);
3229
3230        // Syncing with no key count will not modify the local key count.
3231        sync_with_key_count!(client, server, None);
3232        assert_key_count!(client, 50);
3233
3234        // Syncing with a key count, will update the key count.
3235        sync_with_key_count!(client, server, 10);
3236        assert_key_count!(client, 10);
3237
3238        Ok(())
3239    }
3240
3241    /// `pos` must never be persisted ahead of the event cache: if the process
3242    /// dies after `pos` is saved but before the events of the same response
3243    /// are in the event cache store, or if the store fails to write them, the
3244    /// server won't send these events again, and they're lost for good. See
3245    /// #5500.
3246    ///
3247    /// `pos` is only persisted with the `e2e-encryption` feature, as it lives
3248    /// in the crypto store (see `store_sliding_sync_state`).
3249    #[cfg(feature = "e2e-encryption")]
3250    mod pos_and_event_cache {
3251        use std::time::Duration;
3252
3253        use matrix_sdk_base::{
3254            event_cache::store::{ControlledMemoryStore, EventCacheStore},
3255            store::StoreConfig,
3256        };
3257        use matrix_sdk_common::{
3258            cross_process_lock::CrossProcessLockConfig, executor::spawn, sleep::sleep,
3259        };
3260        use matrix_sdk_test::{async_test, event_factory::EventFactory};
3261        use ruma::{event_id, room_id};
3262        use serde_json::json;
3263        use tokio::time::timeout;
3264        use wiremock::{Mock, ResponseTemplate};
3265
3266        use super::{SlidingSyncMatcher, restore_sliding_sync_state};
3267        use crate::{
3268            Client, Result, SlidingSyncList, sliding_sync::SlidingSync,
3269            test_utils::mocks::MatrixMockServer,
3270        };
3271
3272        /// Create a client using the given event cache store, and a sliding
3273        /// sync whose next response carries a timeline event for a room.
3274        async fn set_up(
3275            server: &MatrixMockServer,
3276            store: &ControlledMemoryStore,
3277        ) -> Result<(Client, SlidingSync)> {
3278            let store_config = StoreConfig::new(CrossProcessLockConfig::SingleProcess)
3279                .event_cache_store(store.clone());
3280            let client = server
3281                .client_builder()
3282                .on_builder(|builder| builder.store_config(store_config))
3283                .build()
3284                .await;
3285
3286            let room_id = room_id!("!r0:example.org");
3287            let f = EventFactory::new().room(room_id).sender(ruma::user_id!("@alice:example.org"));
3288
3289            Mock::given(SlidingSyncMatcher)
3290                .respond_with(ResponseTemplate::new(200).set_body_json(json!({
3291                    "pos": "0",
3292                    "lists": {},
3293                    "rooms": {
3294                        room_id: {
3295                            "initial": true,
3296                            "timeline": [
3297                                f.text_msg("hello").event_id(event_id!("$ev0")).into_raw_sync(),
3298                            ],
3299                        },
3300                    },
3301                })))
3302                .mount(server.server())
3303                .await;
3304
3305            let sliding_sync = client
3306                .sliding_sync("pos-test")?
3307                .add_list(SlidingSyncList::builder("all"))
3308                .build()
3309                .await?;
3310
3311            Ok((client, sliding_sync))
3312        }
3313
3314        async fn persisted_pos(client: &Client, sliding_sync: &SlidingSync) -> Option<String> {
3315            restore_sliding_sync_state(client, &sliding_sync.inner.storage_key)
3316                .await
3317                .unwrap()
3318                .and_then(|fields| fields.pos)
3319        }
3320
3321        #[async_test]
3322        async fn test_pos_is_persisted_after_the_event_cache() -> Result<()> {
3323            let server = MatrixMockServer::new().await;
3324            let store = ControlledMemoryStore::new();
3325            store.block_writes();
3326
3327            let (client, sliding_sync) = set_up(&server, &store).await?;
3328
3329            let sync = spawn({
3330                let sliding_sync = sliding_sync.clone();
3331                async move { sliding_sync.sync_once().await }
3332            });
3333
3334            // The event cache has started to write the events of the response…
3335            timeout(Duration::from_secs(5), store.wait_for_write_to_start())
3336                .await
3337                .expect("the event cache never wrote to its store");
3338
3339            // … but hasn't finished. If the process was killed now, the `pos`
3340            // must still be the previous one. Leave some time to the sync to
3341            // (wrongly) persist it.
3342            sleep(Duration::from_millis(200)).await;
3343            assert!(!sync.is_finished(), "the sync must wait for the event cache store");
3344            assert_eq!(persisted_pos(&client, &sliding_sync).await, None);
3345
3346            // Once the events are stored, the `pos` can be persisted.
3347            store.unblock_writes();
3348            timeout(Duration::from_secs(5), sync)
3349                .await
3350                .expect("the sync never finished after unblocking the store")
3351                .unwrap()?;
3352
3353            assert!(
3354                store.find_event(room_id!("!r0:example.org"), event_id!("$ev0")).await?.is_some()
3355            );
3356            assert_eq!(persisted_pos(&client, &sliding_sync).await.as_deref(), Some("0"));
3357
3358            Ok(())
3359        }
3360
3361        /// If the event cache fails to write the events of a response, the
3362        /// sync must fail and `pos` must not be persisted, otherwise the
3363        /// events are lost for good. See #7300.
3364        #[async_test]
3365        async fn test_pos_is_not_persisted_if_the_event_cache_fails() -> Result<()> {
3366            let server = MatrixMockServer::new().await;
3367            let store = ControlledMemoryStore::new();
3368            store.fail_writes();
3369
3370            let (client, sliding_sync) = set_up(&server, &store).await?;
3371
3372            // The event cache can't store the events of the response, so the
3373            // sync must fail…
3374            assert!(sliding_sync.sync_once().await.is_err());
3375
3376            // … and the `pos` must not move forward, so that the server sends
3377            // the events again.
3378            assert_eq!(persisted_pos(&client, &sliding_sync).await, None);
3379            assert_eq!(sliding_sync.inner.position.lock().await.pos, None);
3380
3381            Ok(())
3382        }
3383    }
3384}