1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411
// Copyright 2023 The Matrix.org Foundation C.I.C.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for that specific language governing permissions and
// limitations under the License.
//! States and actions for the `RoomList` state machine.
use std::{
future::ready,
sync::Mutex,
time::{Duration, Instant},
};
use eyeball::{SharedObservable, Subscriber};
use matrix_sdk::{sliding_sync::Range, SlidingSync, SlidingSyncMode};
use super::Error;
pub const ALL_ROOMS_LIST_NAME: &str = "all_rooms";
/// The state of the [`super::RoomList`].
#[derive(Clone, Debug, PartialEq)]
pub enum State {
/// That's the first initial state.
Init,
/// At this state, the first rooms have been synced.
SettingUp,
/// At this state, the system is recovering from `Error` or `Terminated`.
/// It's similar to `SettingUp` but some lists may already exist, actions
/// are then slightly different.
Recovering,
/// At this state, all rooms are syncing.
Running,
/// At this state, the sync has been stopped because an error happened.
Error { from: Box<State> },
/// At this state, the sync has been stopped because it was requested.
Terminated { from: Box<State> },
}
/// Default value for `StateMachine::state_lifespan`.
const DEFAULT_STATE_LIFESPAN: Duration = Duration::from_secs(1800);
/// The state machine used to transition between the [`State`]s.
#[derive(Debug)]
pub struct StateMachine {
/// The current state of the `RoomListService`.
state: SharedObservable<State>,
/// Last time the state has been updated.
///
/// When the state has not been updated since a long time, we want to enter
/// the [`State::Recovering`] state. Why do we need to do that? Because in
/// some cases, the user might have received many updates between two
/// distant syncs. If the sliding sync list range was too large, like
/// 0..=499, the next sync is likely to be heavy and potentially slow.
/// In this case, it's preferable to jump back onto `Recovering`, which will
/// reset the range, so that the next sync will be fast for the client.
///
/// To be used in coordination with `Self::state_lifespan`.
///
/// This mutex is only taken for short periods of time, so it's sync.
last_state_update_time: Mutex<Instant>,
/// The maximum time before considering the state as “too old”.
///
/// To be used in coordination with `Self::last_state_update_time`.
state_lifespan: Duration,
}
impl StateMachine {
pub(super) fn new() -> Self {
StateMachine {
state: SharedObservable::new(State::Init),
last_state_update_time: Mutex::new(Instant::now()),
state_lifespan: DEFAULT_STATE_LIFESPAN,
}
}
/// Get the current state.
pub(super) fn get(&self) -> State {
self.state.get()
}
/// Set the new state.
///
/// Setting a new state will update `Self::last_state_update`.
pub(super) fn set(&self, state: State) {
let mut last_state_update_time = self.last_state_update_time.lock().unwrap();
*last_state_update_time = Instant::now();
self.state.set(state);
}
/// Subscribe to state updates.
pub fn subscribe(&self) -> Subscriber<State> {
self.state.subscribe()
}
/// Transition to the next state, and execute the associated transition's
/// [`Actions`].
pub(super) async fn next(&self, sliding_sync: &SlidingSync) -> Result<State, Error> {
use State::*;
let next_state = match self.get() {
Init => SettingUp,
SettingUp | Recovering => {
set_all_rooms_to_growing_sync_mode(sliding_sync).await?;
Running
}
Running => {
// We haven't changed the state for a while, we go back to `Recovering` to avoid
// requesting potentially large data. See `Self::last_state_update` to learn
// the details.
if self.last_state_update_time.lock().unwrap().elapsed() > self.state_lifespan {
set_all_rooms_to_selective_sync_mode(sliding_sync).await?;
Recovering
} else {
Running
}
}
Error { from: previous_state } | Terminated { from: previous_state } => {
match previous_state.as_ref() {
// Unreachable state.
Error { .. } | Terminated { .. } => {
unreachable!(
"It's impossible to reach `Error` or `Terminated` from `Error` or `Terminated`"
);
}
// If the previous state was `Running`, we enter the `Recovering` state.
Running => {
set_all_rooms_to_selective_sync_mode(sliding_sync).await?;
Recovering
}
// Jump back to the previous state that led to this termination.
state => state.to_owned(),
}
}
};
Ok(next_state)
}
}
async fn set_all_rooms_to_growing_sync_mode(sliding_sync: &SlidingSync) -> Result<(), Error> {
sliding_sync
.on_list(ALL_ROOMS_LIST_NAME, |list| {
list.set_sync_mode(SlidingSyncMode::new_growing(ALL_ROOMS_DEFAULT_GROWING_BATCH_SIZE));
ready(())
})
.await
.ok_or_else(|| Error::UnknownList(ALL_ROOMS_LIST_NAME.to_owned()))
}
async fn set_all_rooms_to_selective_sync_mode(sliding_sync: &SlidingSync) -> Result<(), Error> {
sliding_sync
.on_list(ALL_ROOMS_LIST_NAME, |list| {
list.set_sync_mode(
SlidingSyncMode::new_selective().add_range(ALL_ROOMS_DEFAULT_SELECTIVE_RANGE),
);
ready(())
})
.await
.ok_or_else(|| Error::UnknownList(ALL_ROOMS_LIST_NAME.to_owned()))
}
/// Default `batch_size` for the selective sync-mode of the
/// `ALL_ROOMS_LIST_NAME` list.
pub const ALL_ROOMS_DEFAULT_SELECTIVE_RANGE: Range = 0..=19;
/// Default `batch_size` for the growing sync-mode of the `ALL_ROOMS_LIST_NAME`
/// list.
pub const ALL_ROOMS_DEFAULT_GROWING_BATCH_SIZE: u32 = 100;
#[cfg(test)]
mod tests {
use matrix_sdk_test::async_test;
use tokio::time::sleep;
use super::{super::tests::new_room_list, *};
#[async_test]
async fn test_states() -> Result<(), Error> {
let room_list = new_room_list().await?;
let sliding_sync = room_list.sliding_sync();
let state_machine = StateMachine::new();
// Hypothetical error.
{
state_machine.set(State::Error { from: Box::new(state_machine.get()) });
// Back to the previous state.
state_machine.set(state_machine.next(sliding_sync).await?);
assert_eq!(state_machine.get(), State::Init);
}
// Hypothetical termination.
{
state_machine.set(State::Terminated { from: Box::new(state_machine.get()) });
// Back to the previous state.
state_machine.set(state_machine.next(sliding_sync).await?);
assert_eq!(state_machine.get(), State::Init);
}
// Next state.
state_machine.set(state_machine.next(sliding_sync).await?);
assert_eq!(state_machine.get(), State::SettingUp);
// Hypothetical error.
{
state_machine.set(State::Error { from: Box::new(state_machine.get()) });
// Back to the previous state.
state_machine.set(state_machine.next(sliding_sync).await?);
assert_eq!(state_machine.get(), State::SettingUp);
}
// Hypothetical termination.
{
state_machine.set(State::Terminated { from: Box::new(state_machine.get()) });
// Back to the previous state.
state_machine.set(state_machine.next(sliding_sync).await?);
assert_eq!(state_machine.get(), State::SettingUp);
}
// Next state.
state_machine.set(state_machine.next(sliding_sync).await?);
assert_eq!(state_machine.get(), State::Running);
// Hypothetical error.
{
state_machine.set(State::Error { from: Box::new(state_machine.get()) });
// Jump to the **recovering** state!
state_machine.set(state_machine.next(sliding_sync).await?);
assert_eq!(state_machine.get(), State::Recovering);
// Now, back to the previous state.
state_machine.set(state_machine.next(sliding_sync).await?);
assert_eq!(state_machine.get(), State::Running);
}
// Hypothetical termination.
{
state_machine.set(State::Terminated { from: Box::new(state_machine.get()) });
// Jump to the **recovering** state!
state_machine.set(state_machine.next(sliding_sync).await?);
assert_eq!(state_machine.get(), State::Recovering);
// Now, back to the previous state.
state_machine.set(state_machine.next(sliding_sync).await?);
assert_eq!(state_machine.get(), State::Running);
}
// Hypothetical error when recovering.
{
state_machine.set(State::Error { from: Box::new(State::Recovering) });
// Back to the previous state.
state_machine.set(state_machine.next(sliding_sync).await?);
assert_eq!(state_machine.get(), State::Recovering);
}
// Hypothetical termination when recovering.
{
state_machine.set(State::Terminated { from: Box::new(State::Recovering) });
// Back to the previous state.
state_machine.set(state_machine.next(sliding_sync).await?);
assert_eq!(state_machine.get(), State::Recovering);
}
Ok(())
}
#[async_test]
async fn test_recover_state_after_delay() -> Result<(), Error> {
let room_list = new_room_list().await?;
let sliding_sync = room_list.sliding_sync();
let mut state_machine = StateMachine::new();
state_machine.state_lifespan = Duration::from_millis(50);
{
state_machine.set(state_machine.next(sliding_sync).await?);
assert_eq!(state_machine.get(), State::SettingUp);
state_machine.set(state_machine.next(sliding_sync).await?);
assert_eq!(state_machine.get(), State::Running);
state_machine.set(state_machine.next(sliding_sync).await?);
assert_eq!(state_machine.get(), State::Running);
state_machine.set(state_machine.next(sliding_sync).await?);
assert_eq!(state_machine.get(), State::Running);
}
// Time passes.
sleep(Duration::from_millis(100)).await;
{
// Time has elapsed, time to recover.
state_machine.set(state_machine.next(sliding_sync).await?);
assert_eq!(state_machine.get(), State::Recovering);
state_machine.set(state_machine.next(sliding_sync).await?);
assert_eq!(state_machine.get(), State::Running);
state_machine.set(state_machine.next(sliding_sync).await?);
assert_eq!(state_machine.get(), State::Running);
state_machine.set(state_machine.next(sliding_sync).await?);
assert_eq!(state_machine.get(), State::Running);
}
// Time passes, again. Just to test everything is going well.
sleep(Duration::from_millis(100)).await;
{
// Time has elapsed, time to recover.
state_machine.set(state_machine.next(sliding_sync).await?);
assert_eq!(state_machine.get(), State::Recovering);
state_machine.set(state_machine.next(sliding_sync).await?);
assert_eq!(state_machine.get(), State::Running);
state_machine.set(state_machine.next(sliding_sync).await?);
assert_eq!(state_machine.get(), State::Running);
state_machine.set(state_machine.next(sliding_sync).await?);
assert_eq!(state_machine.get(), State::Running);
}
Ok(())
}
#[async_test]
async fn test_action_set_all_rooms_list_to_growing_and_selective_sync_mode() -> Result<(), Error>
{
let room_list = new_room_list().await?;
let sliding_sync = room_list.sliding_sync();
// List is present, in Selective mode.
assert_eq!(
sliding_sync
.on_list(ALL_ROOMS_LIST_NAME, |list| ready(matches!(
list.sync_mode(),
SlidingSyncMode::Selective { ranges } if ranges == vec![ALL_ROOMS_DEFAULT_SELECTIVE_RANGE]
)))
.await,
Some(true)
);
// Run the action!
set_all_rooms_to_growing_sync_mode(sliding_sync).await.unwrap();
// List is still present, in Growing mode.
assert_eq!(
sliding_sync
.on_list(ALL_ROOMS_LIST_NAME, |list| ready(matches!(
list.sync_mode(),
SlidingSyncMode::Growing {
batch_size, ..
} if batch_size == ALL_ROOMS_DEFAULT_GROWING_BATCH_SIZE
)))
.await,
Some(true)
);
// Run the other action!
set_all_rooms_to_selective_sync_mode(sliding_sync).await.unwrap();
// List is still present, in Selective mode.
assert_eq!(
sliding_sync
.on_list(ALL_ROOMS_LIST_NAME, |list| ready(matches!(
list.sync_mode(),
SlidingSyncMode::Selective { ranges } if ranges == vec![ALL_ROOMS_DEFAULT_SELECTIVE_RANGE]
)))
.await,
Some(true)
);
Ok(())
}
}