Skip to content

Commit fa25e4d

Browse files
authored
sliding sync: Rejigger the range API (#1955)
* feat: introduce SlidingSyncSelectiveModeBuilder * feat: get rid of `CannotModifyRanges` \o/ * chore: rustfmt * chore: remove scope in test * chore: move request generator update to its own mod, gets rid of `set_ranges` * chore: add comments on the request generator methods * chore: sink one range_end definition into the match arm that matters * ffi: remove unused `add_range` method * test: update incorrect test expectation * chore: make clippy happy * address first review comments * review: don't reuse the ranges field for two things * chore: use a builder pattern for sliding sync selective mode * address review comments + CI Signed-off-by: Benjamin Bouvier <public@benj.me>
1 parent df6d0aa commit fa25e4d

File tree

9 files changed

+324
-477
lines changed

9 files changed

+324
-477
lines changed

bindings/matrix-sdk-ffi/src/sliding_sync.rs

Lines changed: 35 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -3,18 +3,21 @@ use std::sync::{Arc, RwLock};
33
use anyhow::Context;
44
use eyeball_im::VectorDiff;
55
use futures_util::{future::join4, pin_mut, StreamExt};
6-
use matrix_sdk::ruma::{
7-
api::client::sync::sync_events::{
8-
v4::RoomSubscription as RumaRoomSubscription,
9-
UnreadNotificationsCount as RumaUnreadNotificationsCount,
10-
},
11-
assign, IdParseError, OwnedRoomId, RoomId,
12-
};
136
pub use matrix_sdk::{
147
ruma::api::client::sync::sync_events::v4::SyncRequestListFilters, Client as MatrixClient,
158
LoopCtrl, RoomListEntry as MatrixRoomEntry, SlidingSyncBuilder as MatrixSlidingSyncBuilder,
169
SlidingSyncMode, SlidingSyncState,
1710
};
11+
use matrix_sdk::{
12+
ruma::{
13+
api::client::sync::sync_events::{
14+
v4::RoomSubscription as RumaRoomSubscription,
15+
UnreadNotificationsCount as RumaUnreadNotificationsCount,
16+
},
17+
assign, IdParseError, OwnedRoomId, RoomId,
18+
},
19+
sliding_sync::SlidingSyncSelectiveModeBuilder as MatrixSlidingSyncSelectiveModeBuilder,
20+
};
1821
use matrix_sdk_ui::timeline::SlidingSyncRoomExt;
1922
use tokio::task::JoinHandle;
2023
use tracing::{debug, error, warn};
@@ -104,9 +107,6 @@ pub enum SlidingSyncError {
104107
/// initialized. It happens when a response is handled before a request has
105108
/// been sent. It usually happens when testing.
106109
RequestGeneratorHasNotBeenInitialized { msg: String },
107-
/// Someone has tried to modify a sliding sync list's ranges, but the
108-
/// selected sync mode doesn't allow that.
109-
CannotModifyRanges { msg: String },
110110
/// Ranges have a `start` bound greater than `end`.
111111
InvalidRange {
112112
/// Start bound.
@@ -129,7 +129,6 @@ impl From<matrix_sdk::sliding_sync::Error> for SlidingSyncError {
129129
E::RequestGeneratorHasNotBeenInitialized(msg) => {
130130
Self::RequestGeneratorHasNotBeenInitialized { msg }
131131
}
132-
E::CannotModifyRanges(msg) => Self::CannotModifyRanges { msg },
133132
E::InvalidRange { start, end } => Self::InvalidRange { start, end },
134133
E::InternalChannelIsBroken => Self::InternalChannelIsBroken,
135134
error => Self::Unknown { error: error.to_string() },
@@ -410,6 +409,25 @@ pub trait SlidingSyncListStateObserver: Sync + Send {
410409
fn did_receive_update(&self, new_state: SlidingSyncState);
411410
}
412411

412+
#[derive(Clone, uniffi::Object)]
413+
pub struct SlidingSyncSelectiveModeBuilder {
414+
inner: MatrixSlidingSyncSelectiveModeBuilder,
415+
}
416+
417+
#[uniffi::export]
418+
impl SlidingSyncSelectiveModeBuilder {
419+
#[uniffi::constructor]
420+
pub fn new() -> Arc<Self> {
421+
Arc::new(Self { inner: SlidingSyncMode::new_selective() })
422+
}
423+
424+
pub fn add_range(self: Arc<Self>, start: u32, end_inclusive: u32) -> Arc<Self> {
425+
let mut builder = unwrap_or_clone_arc(self);
426+
builder.inner = builder.inner.add_range(start..=end_inclusive);
427+
Arc::new(builder)
428+
}
429+
}
430+
413431
#[derive(Clone, uniffi::Object)]
414432
pub struct SlidingSyncListBuilder {
415433
inner: matrix_sdk::SlidingSyncListBuilder,
@@ -458,9 +476,13 @@ impl SlidingSyncListBuilder {
458476
Arc::new(Self { inner: matrix_sdk::SlidingSyncList::builder(name) })
459477
}
460478

461-
pub fn sync_mode_selective(self: Arc<Self>) -> Arc<Self> {
479+
pub fn sync_mode_selective(
480+
self: Arc<Self>,
481+
selective_mode_builder: Arc<SlidingSyncSelectiveModeBuilder>,
482+
) -> Arc<Self> {
462483
let mut builder = unwrap_or_clone_arc(self);
463-
builder.inner = builder.inner.sync_mode(SlidingSyncMode::new_selective());
484+
let selective_mode_builder = unwrap_or_clone_arc(selective_mode_builder);
485+
builder.inner = builder.inner.sync_mode(selective_mode_builder.inner);
464486
Arc::new(builder)
465487
}
466488

@@ -526,12 +548,6 @@ impl SlidingSyncListBuilder {
526548
Arc::new(builder)
527549
}
528550

529-
pub fn add_range(self: Arc<Self>, from: u32, to_included: u32) -> Arc<Self> {
530-
let mut builder = unwrap_or_clone_arc(self);
531-
builder.inner = builder.inner.add_range(from..=to_included);
532-
Arc::new(builder)
533-
}
534-
535551
pub fn once_built(self: Arc<Self>, callback: Box<dyn SlidingSyncListOnceBuilt>) -> Arc<Self> {
536552
let mut builder = unwrap_or_clone_arc(self);
537553

@@ -613,27 +629,6 @@ impl SlidingSyncList {
613629
self.inner.room_list()
614630
}
615631

616-
/// Reset the ranges to a particular set
617-
///
618-
/// Remember to cancel the existing stream and fetch a new one as this will
619-
/// only be applied on the next request.
620-
pub fn set_range(&self, start: u32, end: u32) -> Result<(), SlidingSyncError> {
621-
self.inner.set_range(start..=end).map_err(Into::into)
622-
}
623-
624-
/// Set the ranges to fetch
625-
///
626-
/// Remember to cancel the existing stream and fetch a new one as this will
627-
/// only be applied on the next request.
628-
pub fn add_range(&self, start: u32, end: u32) -> Result<(), SlidingSyncError> {
629-
self.inner.add_range(start..=end).map_err(Into::into)
630-
}
631-
632-
/// Reset the ranges
633-
pub fn reset_ranges(&self) -> Result<(), SlidingSyncError> {
634-
self.inner.reset_ranges().map_err(Into::into)
635-
}
636-
637632
/// Total of rooms matching the filter
638633
pub fn current_room_count(&self) -> Option<u32> {
639634
self.inner.maximum_number_of_rooms()

crates/matrix-sdk-ui/tests/integration/timeline/sliding_sync.rs

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -219,8 +219,7 @@ impl Match for SlidingSyncMatcher {
219219
#[async_test]
220220
async fn test_timeline_basic() -> Result<()> {
221221
let (server, sliding_sync) = new_sliding_sync(vec![SlidingSyncList::builder("foo")
222-
.sync_mode(SlidingSyncMode::Selective)
223-
.add_range(0..=10)])
222+
.sync_mode(SlidingSyncMode::new_selective().add_range(0..=10))])
224223
.await?;
225224

226225
let stream = sliding_sync.sync();
@@ -266,8 +265,7 @@ async fn test_timeline_basic() -> Result<()> {
266265
#[async_test]
267266
async fn test_timeline_duplicated_events() -> Result<()> {
268267
let (server, sliding_sync) = new_sliding_sync(vec![SlidingSyncList::builder("foo")
269-
.sync_mode(SlidingSyncMode::Selective)
270-
.add_range(0..=10)])
268+
.sync_mode(SlidingSyncMode::new_selective().add_range(0..=10))])
271269
.await?;
272270

273271
let stream = sliding_sync.sync();

crates/matrix-sdk/src/sliding_sync/README.md

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -72,12 +72,11 @@ are **inclusive**) like so:
7272
use ruma::{assign, api::client::sync::sync_events::v4};
7373

7474
let list_builder = SlidingSyncList::builder("main_list")
75-
.sync_mode(SlidingSyncMode::Selective)
75+
.sync_mode(SlidingSyncMode::new_selective().add_range(0..=9))
7676
.filters(Some(assign!(
7777
v4::SyncRequestListFilters::default(), { is_dm: Some(true)}
7878
)))
79-
.sort(vec!["by_recency".to_owned()])
80-
.add_range(0u32..=9);
79+
.sort(vec!["by_recency".to_owned()]);
8180
```
8281

8382
Please refer to the [specification][MSC], the [Ruma types][ruma-types],
@@ -424,8 +423,7 @@ let full_sync_list = SlidingSyncList::builder(&full_sync_list_name)
424423
]); // only want to know if the room is encrypted
425424
426425
let active_list = SlidingSyncList::builder(&active_list_name) // the active window
427-
.sync_mode(SlidingSyncMode::Selective) // sync up the specific range only
428-
.add_range(0u32..=9) // only the top 10 items
426+
.sync_mode(SlidingSyncMode::new_selective().add_range(0..=9)) // sync up the specific range only, first 10 items
429427
.sort(vec!["by_recency".to_owned()]) // last active
430428
.timeline_limit(5u32) // add the last 5 timeline items for room preview and faster timeline loading
431429
.required_state(vec![ // we want to know immediately:

crates/matrix-sdk/src/sliding_sync/error.rs

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -19,11 +19,6 @@ pub enum Error {
1919
#[error("The sliding sync list `{0}` is handling a response, but its request generator has not been initialized")]
2020
RequestGeneratorHasNotBeenInitialized(String),
2121

22-
/// Someone has tried to modify a sliding sync list's ranges, but only the
23-
/// `Selective` sync mode does allow that.
24-
#[error("The chosen sync mode for the list `{0}` doesn't allow to modify the ranges; only `Selective` allows that")]
25-
CannotModifyRanges(String),
26-
2722
/// Ranges have a `start` bound greater than `end`.
2823
#[error("Ranges have invalid bounds: `{start}..{end}`")]
2924
InvalidRange {

crates/matrix-sdk/src/sliding_sync/list/builder.rs

Lines changed: 2 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@ use std::{
44
collections::BTreeMap,
55
convert::identity,
66
fmt,
7-
ops::RangeInclusive,
87
sync::{Arc, RwLock as StdRwLock},
98
};
109

@@ -45,7 +44,6 @@ pub struct SlidingSyncListBuilder {
4544
filters: Option<v4::SyncRequestListFilters>,
4645
timeline_limit: Option<Bound>,
4746
name: String,
48-
ranges: Vec<RangeInclusive<Bound>>,
4947

5048
/// Should this list be cached and reloaded from the cache?
5149
cache_policy: SlidingSyncListCachePolicy,
@@ -68,7 +66,6 @@ impl fmt::Debug for SlidingSyncListBuilder {
6866
.field("filters", &self.filters)
6967
.field("timeline_limit", &self.timeline_limit)
7068
.field("name", &self.name)
71-
.field("ranges", &self.ranges)
7269
.finish_non_exhaustive()
7370
}
7471
}
@@ -85,7 +82,6 @@ impl SlidingSyncListBuilder {
8582
filters: None,
8683
timeline_limit: None,
8784
name: name.into(),
88-
ranges: Vec::new(),
8985
reloaded_cached_data: None,
9086
cache_policy: SlidingSyncListCachePolicy::Disabled,
9187
once_built: Arc::new(Box::new(identity)),
@@ -106,8 +102,8 @@ impl SlidingSyncListBuilder {
106102
}
107103

108104
/// Which SlidingSyncMode to start this list under.
109-
pub fn sync_mode(mut self, value: SlidingSyncMode) -> Self {
110-
self.sync_mode = value;
105+
pub fn sync_mode(mut self, value: impl Into<SlidingSyncMode>) -> Self {
106+
self.sync_mode = value.into();
111107
self
112108
}
113109

@@ -142,12 +138,6 @@ impl SlidingSyncListBuilder {
142138
self
143139
}
144140

145-
/// Set the ranges to fetch.
146-
pub fn add_range(mut self, range: RangeInclusive<Bound>) -> Self {
147-
self.ranges.push(range);
148-
self
149-
}
150-
151141
/// Marks this list as sync'd from the cache, and attempts to reload it from
152142
/// storage.
153143
///
@@ -184,13 +174,11 @@ impl SlidingSyncListBuilder {
184174
let list = SlidingSyncList {
185175
inner: Arc::new(SlidingSyncListInner {
186176
// From the builder
187-
sync_mode: StdRwLock::new(self.sync_mode.clone()),
188177
sort: self.sort,
189178
required_state: self.required_state,
190179
filters: self.filters,
191180
timeline_limit: StdRwLock::new(self.timeline_limit),
192181
name: self.name,
193-
ranges: StdRwLock::new(self.ranges),
194182
cache_policy: self.cache_policy,
195183

196184
// Computed from the builder.

0 commit comments

Comments
 (0)