matrix_sdk_ui/
sync_service.rs

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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
// 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.

//! Unified API for both the Room List API and the Encryption Sync API, that
//! takes care of all the underlying details.
//!
//! This is an opiniated way to run both APIs, with high-level callbacks that
//! should be called in reaction to user actions and/or system events.
//!
//! The sync service will signal errors via its [`state`](SyncService::state)
//! that the user MUST observe. Whenever an error/termination is observed, the
//! user should call [`SyncService::start()`] again to restart the room list
//! sync, if that is not desirable, the offline support for the [`SyncService`]
//! may be enabled using the [`SyncServiceBuilder::with_offline_mode`] setting.

use std::{sync::Arc, time::Duration};

use eyeball::{SharedObservable, Subscriber};
use futures_util::{
    future::{select, Either},
    pin_mut, StreamExt as _,
};
use matrix_sdk::{
    config::RequestConfig,
    executor::{spawn, JoinHandle},
    sleep::sleep,
    Client,
};
use thiserror::Error;
use tokio::sync::{
    mpsc::{Receiver, Sender},
    Mutex as AsyncMutex, OwnedMutexGuard,
};
use tracing::{error, info, instrument, trace, warn, Instrument, Level};

use crate::{
    encryption_sync_service::{self, EncryptionSyncPermit, EncryptionSyncService, WithLocking},
    room_list_service::{self, RoomListService},
};

/// Current state of the application.
///
/// This is a high-level state indicating what's the status of the underlying
/// syncs. The application starts in [`State::Running`] mode, and then hits a
/// terminal state [`State::Terminated`] (if it gracefully exited) or
/// [`State::Error`] (in case any of the underlying syncs ran into an error).
///
/// This can be observed with [`SyncService::state`].
#[derive(Clone, Debug, PartialEq)]
pub enum State {
    /// The service hasn't ever been started yet, or has been stopped.
    Idle,
    /// The underlying syncs are properly running in the background.
    Running,
    /// Any of the underlying syncs has terminated gracefully (i.e. be stopped).
    Terminated,
    /// Any of the underlying syncs has ran into an error.
    Error,
    /// The service has entered offline mode. This state will only be entered if
    /// the [`SyncService`] has been built with the
    /// [`SyncServiceBuilder::with_offline_mode`] setting.
    ///
    /// The [`SyncService`] will enter the offline mode if syncing with the
    /// server fails, it will then periodically check if the server is
    /// available using the `/_matrix/client/versions` endpoint.
    ///
    /// Once the [`SyncService`] receives a 200 response from the
    /// `/_matrix/client/versions` endpoint, it will go back into the
    /// [`State::Running`] mode and attempt to sync again.
    ///
    /// Calling [`SyncService::start()`] while in this state will abort the
    /// `/_matrix/client/versions` checks and attempt to sync immediately.
    ///
    /// Calling [`SyncService::stop()`] will abort the offline mode and the
    /// [`SyncService`] will go into the [`State::Idle`] mode.
    Offline,
}

enum MaybeAcquiredPermit {
    Acquired(OwnedMutexGuard<EncryptionSyncPermit>),
    Unacquired(Arc<AsyncMutex<EncryptionSyncPermit>>),
}

impl MaybeAcquiredPermit {
    async fn acquire(self) -> OwnedMutexGuard<EncryptionSyncPermit> {
        match self {
            MaybeAcquiredPermit::Acquired(owned_mutex_guard) => owned_mutex_guard,
            MaybeAcquiredPermit::Unacquired(lock) => lock.lock_owned().await,
        }
    }
}

/// A supervisor responsible for managing two sync tasks: one for handling the
/// room list and another for supporting end-to-end encryption.
///
/// The two sync tasks are spawned as child tasks and are contained within the
/// supervising task, which is stored in the [`SyncTaskSupervisor::task`] field.
///
/// The supervisor ensures the two child tasks are managed as a single unit,
/// allowing for them to be shutdown in unison.
struct SyncTaskSupervisor {
    /// The supervising task that manages and contains the two sync child tasks.
    task: JoinHandle<()>,
    /// [`TerminationReport`] sender for the [`SyncTaskSupervisor::shutdown()`]
    /// function.
    termination_sender: Sender<TerminationReport>,
}

impl SyncTaskSupervisor {
    async fn new(
        inner: &SyncServiceInner,
        room_list_service: Arc<RoomListService>,
        encryption_sync_permit: Arc<AsyncMutex<EncryptionSyncPermit>>,
    ) -> Self {
        let (task, termination_sender) =
            Self::spawn_supervisor_task(inner, room_list_service, encryption_sync_permit).await;

        Self { task, termination_sender }
    }

    /// Check if a homeserver is reachable.
    ///
    /// This function handles the offline mode by waiting for either a
    /// termination report or a successful `/_matrix/client/versions` response.
    ///
    /// This function waits for two conditions:
    ///
    /// 1. Waiting for a termination report: This ensures that the user can exit
    ///    offline mode and attempt to restart the [`SyncService`] manually.
    ///
    /// 2. Waiting to come back online: This continuously checks server
    ///    availability.
    ///
    /// If the `/_matrix/client/versions` request succeeds, the function exits
    /// without a termination report. If we receive a [`TerminationReport`] from
    /// the user, we exit immediately and return the termination report.
    async fn offline_check(
        client: &Client,
        receiver: &mut Receiver<TerminationReport>,
    ) -> Option<TerminationReport> {
        info!("Entering the offline mode");

        let wait_for_termination_report = async {
            loop {
                // Since we didn't empty the channel when entering the offline mode in fear that
                // we might miss a report with the
                // `TerminationOrigin::Supervisor` origin and the channel might contain stale
                // reports from one of the sync services, in case both of them have sent a
                // report, let's ignore all reports we receive from the sync
                // services.
                let report =
                    receiver.recv().await.unwrap_or_else(TerminationReport::supervisor_error);

                match report.origin {
                    TerminationOrigin::EncryptionSync | TerminationOrigin::RoomList => {}
                    // Since the sync service aren't running anymore, we can only receive a report
                    // from the supervisor. It would have probably made sense to have separate
                    // channels for reports the sync services send and the user can send using the
                    // `SyncService::stop()` method.
                    TerminationOrigin::Supervisor => break report,
                }
            }
        };

        let wait_to_be_online = async move {
            loop {
                // Encountering network failures when sending a request which has with no retry
                // limit set in the `RequestConfig` are treated as permanent failures and our
                // exponential backoff doesn't kick in.
                //
                // Let's set a retry limit so network failures are retried as well.
                let request_config = RequestConfig::default().retry_limit(5);

                // We're in an infinite loop, but our request sending already has an exponential
                // backoff set up. This will kick in for any request errors that we consider to
                // be transient. Common network errors (timeouts, DNS failures) or any server
                // error in the 5xx range of HTTP errors are considered to be transient.
                //
                // Still, as a precaution, we're going to sleep here for a while in the Error
                // case.
                match client.fetch_server_capabilities(Some(request_config)).await {
                    Ok(_) => break,
                    Err(_) => sleep(Duration::from_millis(100)).await,
                }
            }
        };

        pin_mut!(wait_for_termination_report);
        pin_mut!(wait_to_be_online);

        let maybe_termination_report = select(wait_for_termination_report, wait_to_be_online).await;

        let report = match maybe_termination_report {
            Either::Left((termination_report, _)) => Some(termination_report),
            Either::Right((_, _)) => None,
        };

        info!("Exiting offline mode: {report:?}");

        report
    }

    /// The role of the supervisor task is to wait for a termination message
    /// ([`TerminationReport`]), sent either because we wanted to stop both
    /// syncs, or because one of the syncs failed (in which case we'll stop the
    /// other one too).
    async fn spawn_supervisor_task(
        inner: &SyncServiceInner,
        room_list_service: Arc<RoomListService>,
        encryption_sync_permit: Arc<AsyncMutex<EncryptionSyncPermit>>,
    ) -> (JoinHandle<()>, Sender<TerminationReport>) {
        let (sender, mut receiver) = tokio::sync::mpsc::channel(16);

        let encryption_sync = inner.encryption_sync_service.clone();
        let state = inner.state.clone();
        let termination_sender = sender.clone();

        // When we first start, and don't use offline mode, we want to acquire the sync
        // permit before we enter a future that might be polled at a later time,
        // this means that the permit will be acquired as soon as this future,
        // the one the `spawn_supervisor_task` function creates, is awaited.
        //
        // In other words, once `sync_service.start().await` is finished, the permit
        // will be in the acquired state.
        let mut sync_permit_guard =
            MaybeAcquiredPermit::Acquired(encryption_sync_permit.clone().lock_owned().await);

        let offline_mode = inner.with_offline_mode;

        let future = async move {
            loop {
                let (room_list_task, encryption_sync_task) = Self::spawn_child_tasks(
                    room_list_service.clone(),
                    encryption_sync.clone(),
                    sync_permit_guard,
                    sender.clone(),
                )
                .await;

                sync_permit_guard = MaybeAcquiredPermit::Unacquired(encryption_sync_permit.clone());

                let report = if let Some(report) = receiver.recv().await {
                    report
                } else {
                    info!("internal channel has been closed?");
                    // We should still stop the child tasks in the unlikely scenario that our
                    // receiver died.
                    TerminationReport::supervisor_error()
                };

                // If one service failed, make sure to request stopping the other one.
                let (stop_room_list, stop_encryption) = match &report.origin {
                    TerminationOrigin::EncryptionSync => (true, false),
                    TerminationOrigin::RoomList => (false, true),
                    TerminationOrigin::Supervisor => (true, true),
                };

                // Stop both services, and wait for the streams to properly finish: at some
                // point they'll return `None` and will exit their infinite loops, and their
                // tasks will gracefully terminate.

                if stop_room_list {
                    if let Err(err) = room_list_service.stop_sync() {
                        warn!(?report, "unable to stop room list service: {err:#}");
                    }

                    if report.has_expired {
                        room_list_service.expire_sync_session().await;
                    }
                }

                if let Err(err) = room_list_task.await {
                    error!("when awaiting room list service: {err:#}");
                }

                if stop_encryption {
                    if let Err(err) = encryption_sync.stop_sync() {
                        warn!(?report, "unable to stop encryption sync: {err:#}");
                    }

                    if report.has_expired {
                        encryption_sync.expire_sync_session().await;
                    }
                }

                if let Err(err) = encryption_sync_task.await {
                    error!("when awaiting encryption sync: {err:#}");
                }

                if report.is_error {
                    if offline_mode {
                        state.set(State::Offline);

                        let client = room_list_service.client();

                        if let Some(report) = Self::offline_check(client, &mut receiver).await {
                            if report.is_error {
                                state.set(State::Error);
                            } else {
                                state.set(State::Idle);
                            }
                            break;
                        }

                        state.set(State::Running);
                    } else {
                        state.set(State::Error);
                        break;
                    }
                } else if matches!(report.origin, TerminationOrigin::Supervisor) {
                    state.set(State::Idle);
                    break;
                } else {
                    state.set(State::Terminated);
                    break;
                }
            }
        }
        .instrument(tracing::span!(Level::WARN, "supervisor task"));

        let task = spawn(future);

        (task, termination_sender)
    }

    async fn spawn_child_tasks(
        room_list_service: Arc<RoomListService>,
        encryption_sync_service: Arc<EncryptionSyncService>,
        sync_permit_guard: MaybeAcquiredPermit,
        sender: Sender<TerminationReport>,
    ) -> (JoinHandle<()>, JoinHandle<()>) {
        // First, take care of the room list.
        let room_list_task = spawn(Self::room_list_sync_task(room_list_service, sender.clone()));

        // Then, take care of the encryption sync.
        let encryption_sync_task = spawn(Self::encryption_sync_task(
            encryption_sync_service,
            sender.clone(),
            sync_permit_guard.acquire().await,
        ));

        (room_list_task, encryption_sync_task)
    }

    fn check_if_expired(err: &matrix_sdk::Error) -> bool {
        err.client_api_error_kind() == Some(&ruma::api::client::error::ErrorKind::UnknownPos)
    }

    async fn encryption_sync_task(
        encryption_sync: Arc<EncryptionSyncService>,
        sender: Sender<TerminationReport>,
        sync_permit_guard: OwnedMutexGuard<EncryptionSyncPermit>,
    ) {
        use encryption_sync_service::Error;

        let encryption_sync_stream = encryption_sync.sync(sync_permit_guard);
        pin_mut!(encryption_sync_stream);

        let (is_error, has_expired) = loop {
            match encryption_sync_stream.next().await {
                Some(Ok(())) => {
                    // Carry on.
                }
                Some(Err(err)) => {
                    // If the encryption sync error was an expired session, also expire the
                    // room list sync.
                    let has_expired = if let Error::SlidingSync(err) = &err {
                        Self::check_if_expired(err)
                    } else {
                        false
                    };

                    if !has_expired {
                        error!("Error while processing encryption in sync service: {err:#}");
                    }

                    break (true, has_expired);
                }
                None => {
                    // The stream has ended.
                    break (false, false);
                }
            }
        };

        if let Err(err) = sender
            .send(TerminationReport {
                is_error,
                has_expired,
                origin: TerminationOrigin::EncryptionSync,
            })
            .await
        {
            error!("Error while sending termination report: {err:#}");
        }
    }

    async fn room_list_sync_task(
        room_list_service: Arc<RoomListService>,
        sender: Sender<TerminationReport>,
    ) {
        use room_list_service::Error;

        let room_list_stream = room_list_service.sync();
        pin_mut!(room_list_stream);

        let (is_error, has_expired) = loop {
            match room_list_stream.next().await {
                Some(Ok(())) => {
                    // Carry on.
                }
                Some(Err(err)) => {
                    // If the room list error was an expired session, also expire the
                    // encryption sync.
                    let has_expired = if let Error::SlidingSync(err) = &err {
                        Self::check_if_expired(err)
                    } else {
                        false
                    };

                    if !has_expired {
                        error!("Error while processing room list in sync service: {err:#}");
                    }

                    break (true, has_expired);
                }
                None => {
                    // The stream has ended.
                    break (false, false);
                }
            }
        };

        if let Err(err) = sender
            .send(TerminationReport { is_error, has_expired, origin: TerminationOrigin::RoomList })
            .await
        {
            error!("Error while sending termination report: {err:#}");
        }
    }

    async fn shutdown(self) {
        match self
            .termination_sender
            .send(TerminationReport {
                is_error: false,
                has_expired: false,
                origin: TerminationOrigin::Supervisor,
            })
            .await
        {
            Ok(_) => {
                let _ = self.task.await.inspect_err(|err| {
                    // A `JoinError` indicates that the task was already dead, either because it got
                    // cancelled or because it panicked. We only cancel the task in the Err branch
                    // below and the task shouldn't be able to panic.
                    //
                    // So let's log an error and return.
                    error!("The supervisor task has stopped unexpectedly: {err:?}");
                });
            }
            Err(err) => {
                error!("Couldn't send the termination report to the supervisor task: {err}");
                // Let's abort the task if it won't shut down properly, otherwise we would have
                // left it as a detached task.
                self.task.abort();
            }
        }
    }
}

struct SyncServiceInner {
    encryption_sync_service: Arc<EncryptionSyncService>,
    /// Is the offline mode for the [`SyncService`] enabled?
    ///
    /// The offline mode is described in the [`State::Offline`] enum variant.
    with_offline_mode: bool,
    state: SharedObservable<State>,
    /// Supervisor task ensuring proper termination.
    ///
    /// This task is waiting for a [`TerminationReport`] from any of the other
    /// two tasks, or from a user request via [`SyncService::stop()`]. It
    /// makes sure that the two services are properly shut up and just
    /// interrupted.
    ///
    /// This is set at the same time as the other two tasks.
    supervisor: Option<SyncTaskSupervisor>,
}

impl SyncServiceInner {
    async fn start(
        &mut self,
        room_list_service: Arc<RoomListService>,
        encryption_sync_permit: Arc<AsyncMutex<EncryptionSyncPermit>>,
    ) {
        trace!("starting sync service");

        self.supervisor =
            Some(SyncTaskSupervisor::new(self, room_list_service, encryption_sync_permit).await);
        self.state.set(State::Running);
    }

    async fn stop(&mut self) {
        trace!("pausing sync service");

        // Remove the supervisor from our state and request the tasks to be shutdown.
        if let Some(supervisor) = self.supervisor.take() {
            supervisor.shutdown().await;
        } else {
            error!("The sync service was not properly started, the supervisor task doesn't exist");
        }
    }

    async fn restart(
        &mut self,
        room_list_service: Arc<RoomListService>,
        encryption_sync_permit: Arc<AsyncMutex<EncryptionSyncPermit>>,
    ) {
        self.stop().await;
        self.start(room_list_service, encryption_sync_permit).await;
    }
}

/// A high level manager for your Matrix syncing needs.
///
/// The [`SyncService`] is responsible for managing real-time synchronization
/// with a Matrix server. It can initiate and maintain the necessary
/// synchronization tasks for you.
///
/// **Note**: The [`SyncService`] requires a server with support for [MSC4186],
/// otherwise it will fail with an 404 `M_UNRECOGNIZED` request error.
///
/// [MSC4186]: https://github.com/matrix-org/matrix-spec-proposals/pull/4186/
///
/// # Example
///
/// ```no_run
/// use matrix_sdk::Client;
/// use matrix_sdk_ui::sync_service::{State, SyncService};
/// # use url::Url;
/// # async {
/// let homeserver = Url::parse("http://example.com")?;
/// let client = Client::new(homeserver).await?;
///
/// client
///     .matrix_auth()
///     .login_username("example", "wordpass")
///     .initial_device_display_name("My bot")
///     .await?;
///
/// let sync_service = SyncService::builder(client).build().await?;
/// let mut state = sync_service.state();
///
/// while let Some(state) = state.next().await {
///     match state {
///         State::Idle => eprintln!("The sync service is idle."),
///         State::Running => eprintln!("The sync has started to run."),
///         State::Offline => eprintln!(
///             "We have entered the offline mode, the server seems to be
///              unavailable"
///         ),
///         State::Terminated => {
///             eprintln!("The sync service has been gracefully terminated");
///             break;
///         }
///         State::Error => {
///             eprintln!("The sync service has run into an error");
///             break;
///         }
///     }
/// }
/// # anyhow::Ok(()) };
/// ```
pub struct SyncService {
    inner: Arc<AsyncMutex<SyncServiceInner>>,

    /// Room list service used to synchronize the rooms state.
    room_list_service: Arc<RoomListService>,

    /// What's the state of this sync service? This field is replicated from the
    /// [`SyncServiceInner`] struct, but it should not be modified in this
    /// struct. It's re-exposed here so we can subscribe to the state without
    /// taking the lock on the `inner` field.
    state: SharedObservable<State>,

    /// Global lock to allow using at most one [`EncryptionSyncService`] at all
    /// times.
    ///
    /// This ensures that there's only one ever existing in the application's
    /// lifetime (under the assumption that there is at most one [`SyncService`]
    /// per application).
    encryption_sync_permit: Arc<AsyncMutex<EncryptionSyncPermit>>,
}

impl SyncService {
    /// Create a new builder for configuring an `SyncService`.
    pub fn builder(client: Client) -> SyncServiceBuilder {
        SyncServiceBuilder::new(client)
    }

    /// Get the underlying `RoomListService` instance for easier access to its
    /// methods.
    pub fn room_list_service(&self) -> Arc<RoomListService> {
        self.room_list_service.clone()
    }

    /// Returns the state of the sync service.
    pub fn state(&self) -> Subscriber<State> {
        self.state.subscribe()
    }

    /// Start (or restart) the underlying sliding syncs.
    ///
    /// This can be called multiple times safely:
    /// - if the stream is still properly running, it won't be restarted.
    /// - if the [`SyncService`] is in the offline mode we will exit the offline
    ///   mode and immediately attempt to sync again.
    /// - if the stream has been aborted before, it will be properly cleaned up
    ///   and restarted.
    pub async fn start(&self) {
        let mut inner = self.inner.lock().await;

        // Only (re)start the tasks if it's stopped or if we're in the offline mode.
        match inner.state.get() {
            // If we're already running, there's nothing to do.
            State::Running => {}
            // If we're in the offline mode, first stop the service and then start it again.
            State::Offline => {
                inner
                    .restart(self.room_list_service.clone(), self.encryption_sync_permit.clone())
                    .await
            }
            // Otherwise just start.
            State::Idle | State::Terminated | State::Error => {
                inner
                    .start(self.room_list_service.clone(), self.encryption_sync_permit.clone())
                    .await
            }
        }
    }

    /// Stop the underlying sliding syncs.
    ///
    /// This must be called when the app goes into the background. It's better
    /// to call this API when the application exits, although not strictly
    /// necessary.
    #[instrument(skip_all)]
    pub async fn stop(&self) {
        let mut inner = self.inner.lock().await;

        match inner.state.get() {
            State::Idle | State::Terminated | State::Error => {
                // No need to stop if we were not running.
                return;
            }
            State::Running | State::Offline => {}
        }

        inner.stop().await
    }

    /// Attempt to get a permit to use an `EncryptionSyncService` at a given
    /// time.
    ///
    /// This ensures there is at most one [`EncryptionSyncService`] active at
    /// any time, per application.
    pub fn try_get_encryption_sync_permit(&self) -> Option<OwnedMutexGuard<EncryptionSyncPermit>> {
        self.encryption_sync_permit.clone().try_lock_owned().ok()
    }
}

#[derive(Debug)]
enum TerminationOrigin {
    EncryptionSync,
    RoomList,
    Supervisor,
}

#[derive(Debug)]
struct TerminationReport {
    is_error: bool,
    has_expired: bool,
    origin: TerminationOrigin,
}

impl TerminationReport {
    fn supervisor_error() -> Self {
        TerminationReport {
            is_error: true,
            has_expired: false,
            origin: TerminationOrigin::Supervisor,
        }
    }
}

// Testing helpers, mostly.
#[doc(hidden)]
impl SyncService {
    /// Is the task supervisor running?
    pub async fn is_supervisor_running(&self) -> bool {
        self.inner.lock().await.supervisor.is_some()
    }
}

#[derive(Clone)]
pub struct SyncServiceBuilder {
    /// SDK client.
    client: Client,

    /// Is the cross-process lock for the crypto store enabled?
    with_cross_process_lock: bool,

    /// Is the offline mode for the [`SyncService`] enabled?
    ///
    /// The offline mode is described in the [`State::Offline`] enum variant.
    with_offline_mode: bool,
}

impl SyncServiceBuilder {
    fn new(client: Client) -> Self {
        Self { client, with_cross_process_lock: false, with_offline_mode: false }
    }

    /// Enables the cross-process lock, if the sync service is being built in a
    /// multi-process setup.
    ///
    /// It's a prerequisite if another process can *also* process encryption
    /// events. This is only applicable to very specific use cases, like an
    /// external process attempting to decrypt notifications. In general,
    /// `with_cross_process_lock` should not be called.
    ///
    /// Be sure to have configured
    /// [`Client::cross_process_store_locks_holder_name`] accordingly.
    pub fn with_cross_process_lock(mut self) -> Self {
        self.with_cross_process_lock = true;
        self
    }

    /// Enable the "offline" mode for the [`SyncService`].
    ///
    /// To learn more about the "offline" mode read the documentation for the
    /// [`State::Offline`] enum variant.
    pub fn with_offline_mode(mut self) -> Self {
        self.with_offline_mode = true;
        self
    }

    /// Finish setting up the [`SyncService`].
    ///
    /// This creates the underlying sliding syncs, and will *not* start them in
    /// the background. The resulting [`SyncService`] must be kept alive as long
    /// as the sliding syncs are supposed to run.
    pub async fn build(self) -> Result<SyncService, Error> {
        let Self { client, with_cross_process_lock, with_offline_mode } = self;

        let encryption_sync_permit = Arc::new(AsyncMutex::new(EncryptionSyncPermit::new()));

        let room_list = RoomListService::new(client.clone()).await?;

        let encryption_sync = Arc::new(
            EncryptionSyncService::new(client, None, WithLocking::from(with_cross_process_lock))
                .await?,
        );

        let room_list_service = Arc::new(room_list);
        let state = SharedObservable::new(State::Idle);

        Ok(SyncService {
            state: state.clone(),
            room_list_service,
            encryption_sync_permit,
            inner: Arc::new(AsyncMutex::new(SyncServiceInner {
                supervisor: None,
                encryption_sync_service: encryption_sync,
                state,
                with_offline_mode,
            })),
        })
    }
}

/// Errors for the [`SyncService`] API.
#[derive(Debug, Error)]
pub enum Error {
    /// An error received from the `RoomListService` API.
    #[error(transparent)]
    RoomList(#[from] room_list_service::Error),

    /// An error received from the `EncryptionSyncService` API.
    #[error(transparent)]
    EncryptionSync(#[from] encryption_sync_service::Error),

    /// An error had occurred in the sync task supervisor, likely due to a bug.
    #[error("the supervisor channel has run into an unexpected error")]
    InternalSupervisorError,
}