matrix_sdk_ui/sync_service.rs
1// Copyright 2023 The Matrix.org Foundation C.I.C.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for that specific language governing permissions and
13// limitations under the License.
14
15//! Unified API for both the Room List API and the Encryption Sync API, that
16//! takes care of all the underlying details.
17//!
18//! This is an opiniated way to run both APIs, with high-level callbacks that
19//! should be called in reaction to user actions and/or system events.
20//!
21//! The sync service will signal errors via its [`state`](SyncService::state)
22//! that the user MUST observe. Whenever an error/termination is observed, the
23//! user should call [`SyncService::start()`] again to restart the room list
24//! sync, if that is not desirable, the offline support for the [`SyncService`]
25//! may be enabled using the [`SyncServiceBuilder::with_offline_mode`] setting.
26
27use std::{pin::pin, sync::Arc, time::Duration};
28
29use eyeball::{SharedObservable, Subscriber};
30use futures_util::{
31 StreamExt as _,
32 future::{Either, select},
33};
34use matrix_sdk::{
35 Client,
36 config::RequestConfig,
37 executor::{JoinHandle, spawn},
38 sleep::sleep,
39};
40use thiserror::Error;
41use tokio::sync::{
42 Mutex as AsyncMutex, OwnedMutexGuard,
43 mpsc::{Receiver, Sender},
44};
45use tracing::{Instrument, Level, Span, error, info, instrument, trace, warn};
46
47use crate::{
48 encryption_sync_service::{self, EncryptionSyncPermit, EncryptionSyncService},
49 room_list_service::{
50 self, DEFAULT_CONNECTION_ID, DEFAULT_LIST_TIMELINE_LIMIT, RoomListService,
51 },
52};
53
54const OFFLINE_MODE_SLEEP_TIME: Duration = Duration::from_secs(1);
55
56/// Current state of the application.
57///
58/// This is a high-level state indicating what's the status of the underlying
59/// syncs. The application starts in [`State::Running`] mode, and then hits a
60/// terminal state [`State::Terminated`] (if it gracefully exited) or
61/// [`State::Error`] (in case any of the underlying syncs ran into an error).
62///
63/// This can be observed with [`SyncService::state`].
64#[derive(Clone, Debug)]
65pub enum State {
66 /// The service hasn't ever been started yet, or has been stopped.
67 Idle,
68
69 /// The underlying syncs are properly running in the background.
70 Running,
71
72 /// Any of the underlying syncs has terminated gracefully (i.e. be stopped).
73 Terminated,
74
75 /// Any of the underlying syncs has ran into an error.
76 ///
77 /// The associated [`enum@Error`] is inside an [`Arc`] to (i) make [`State`]
78 /// cloneable, and to (ii) not make it heavier.
79 Error(Arc<Error>),
80
81 /// The service has entered offline mode. This state will only be entered if
82 /// the [`SyncService`] has been built with the
83 /// [`SyncServiceBuilder::with_offline_mode`] setting.
84 ///
85 /// The [`SyncService`] will enter the offline mode if syncing with the
86 /// server fails, it will then periodically check if the server is available
87 /// using the `/_matrix/client/versions` endpoint.
88 ///
89 /// Once the [`SyncService`] receives a 200 response from the
90 /// `/_matrix/client/versions` endpoint, it will go back into the
91 /// [`State::Running`] mode and attempt to sync again.
92 ///
93 /// Calling [`SyncService::start()`] while in this state will abort the
94 /// `/_matrix/client/versions` checks and attempt to sync immediately.
95 ///
96 /// Calling [`SyncService::stop()`] will abort the offline mode and the
97 /// [`SyncService`] will go into the [`State::Idle`] mode.
98 Offline,
99}
100
101enum MaybeAcquiredPermit {
102 Acquired(OwnedMutexGuard<EncryptionSyncPermit>),
103 Unacquired(Arc<AsyncMutex<EncryptionSyncPermit>>),
104}
105
106impl MaybeAcquiredPermit {
107 async fn acquire(self) -> OwnedMutexGuard<EncryptionSyncPermit> {
108 match self {
109 MaybeAcquiredPermit::Acquired(owned_mutex_guard) => owned_mutex_guard,
110 MaybeAcquiredPermit::Unacquired(lock) => lock.lock_owned().await,
111 }
112 }
113}
114
115/// A supervisor responsible for managing two sync tasks: one for handling the
116/// room list and another for supporting end-to-end encryption.
117///
118/// The two sync tasks are spawned as child tasks and are contained within the
119/// supervising task, which is stored in the [`SyncTaskSupervisor::task`] field.
120///
121/// The supervisor ensures the two child tasks are managed as a single unit,
122/// allowing for them to be shutdown in unison.
123struct SyncTaskSupervisor {
124 /// The supervising task that manages and contains the two sync child tasks.
125 task: JoinHandle<()>,
126 /// [`TerminationReport`] sender for the [`SyncTaskSupervisor::shutdown()`]
127 /// function.
128 termination_sender: Sender<TerminationReport>,
129}
130
131impl SyncTaskSupervisor {
132 async fn new(
133 inner: &SyncServiceInner,
134 room_list_service: Arc<RoomListService>,
135 encryption_sync_permit: Arc<AsyncMutex<EncryptionSyncPermit>>,
136 ) -> Self {
137 let (task, termination_sender) =
138 Self::spawn_supervisor_task(inner, room_list_service, encryption_sync_permit).await;
139
140 Self { task, termination_sender }
141 }
142
143 /// Check if a homeserver is reachable.
144 ///
145 /// This function handles the offline mode by waiting for either a
146 /// termination report or a successful `/_matrix/client/versions` response.
147 ///
148 /// This function waits for two conditions:
149 ///
150 /// 1. Waiting for a termination report: This ensures that the user can exit
151 /// offline mode and attempt to restart the [`SyncService`] manually.
152 ///
153 /// 2. Waiting to come back online: This continuously checks server
154 /// availability.
155 ///
156 /// If the `/_matrix/client/versions` request succeeds, the function exits
157 /// without a termination report. If we receive a [`TerminationReport`] from
158 /// the user, we exit immediately and return the termination report.
159 async fn offline_check(
160 client: &Client,
161 receiver: &mut Receiver<TerminationReport>,
162 ) -> Option<TerminationReport> {
163 info!("Entering the offline mode");
164
165 let wait_for_termination_report = async {
166 loop {
167 // Since we didn't empty the channel when entering the offline
168 // mode in fear that we might miss a report with the
169 // `TerminationOrigin::Supervisor` origin and the channel might
170 // contain stale reports from one of the sync services, in case
171 // both of them have sent a report, let's ignore all reports we
172 // receive from the sync services.
173 let report =
174 receiver.recv().await.unwrap_or_else(TerminationReport::supervisor_error);
175
176 match report.origin {
177 TerminationOrigin::EncryptionSync | TerminationOrigin::RoomList => {}
178 // Since the sync service aren't running anymore, we can
179 // only receive a report from the supervisor. It would have
180 // probably made sense to have separate channels for reports
181 // the sync services send and the user can send using the
182 // `SyncService::stop()` method.
183 TerminationOrigin::Supervisor => break report,
184 }
185 }
186 };
187
188 let wait_to_be_online = async move {
189 loop {
190 // Encountering network failures when sending a request which
191 // has with no retry limit set in the `RequestConfig` are
192 // treated as permanent failures and our exponential backoff
193 // doesn't kick in.
194 //
195 // Let's set a retry limit so network failures are retried as
196 // well.
197 //
198 // We only use /versions to check whether the server is
199 // reachable, we can skip authentication for this.
200 let request_config = RequestConfig::default().retry_limit(5).skip_auth();
201
202 // We're in an infinite loop, but our request sending already
203 // has an exponential backoff set up. This will kick in for any
204 // request errors that we consider to be transient. Common
205 // network errors (timeouts, DNS failures) or any server error
206 // in the 5xx range of HTTP errors are considered to be
207 // transient.
208 //
209 // Still, as a precaution, we're going to sleep here for a while
210 // in the Error case.
211 match client.fetch_server_versions(Some(request_config)).await {
212 Ok(_) => break,
213 Err(_) => sleep(OFFLINE_MODE_SLEEP_TIME).await,
214 }
215 }
216 };
217
218 let wait_for_termination_report = pin!(wait_for_termination_report);
219 let wait_to_be_online = pin!(wait_to_be_online);
220
221 let maybe_termination_report = select(wait_for_termination_report, wait_to_be_online).await;
222
223 let report = match maybe_termination_report {
224 Either::Left((termination_report, _)) => Some(termination_report),
225 Either::Right((_, _)) => None,
226 };
227
228 info!("Exiting offline mode: {report:?}");
229
230 report
231 }
232
233 /// The role of the supervisor task is to wait for a termination message
234 /// ([`TerminationReport`]), sent either because we wanted to stop both
235 /// syncs, or because one of the syncs failed (in which case we'll stop the
236 /// other one too).
237 async fn spawn_supervisor_task(
238 inner: &SyncServiceInner,
239 room_list_service: Arc<RoomListService>,
240 encryption_sync_permit: Arc<AsyncMutex<EncryptionSyncPermit>>,
241 ) -> (JoinHandle<()>, Sender<TerminationReport>) {
242 let (sender, mut receiver) = tokio::sync::mpsc::channel(16);
243
244 let encryption_sync = inner.encryption_sync_service.clone();
245 let state = inner.state.clone();
246 let termination_sender = sender.clone();
247
248 // When we first start, and don't use offline mode, we want to acquire
249 // the sync permit before we enter a future that might be polled at a
250 // later time, this means that the permit will be acquired as soon as
251 // this future, the one the `spawn_supervisor_task` function creates, is
252 // awaited.
253 //
254 // In other words, once `sync_service.start().await` is finished, the
255 // permit will be in the acquired state.
256 let mut sync_permit_guard =
257 MaybeAcquiredPermit::Acquired(encryption_sync_permit.clone().lock_owned().await);
258
259 let offline_mode = inner.with_offline_mode;
260 let parent_span = inner.parent_span.clone();
261
262 let future = async move {
263 loop {
264 let (room_list_task, encryption_sync_task) = Self::spawn_child_tasks(
265 room_list_service.clone(),
266 encryption_sync.clone(),
267 sync_permit_guard,
268 sender.clone(),
269 parent_span.clone(),
270 )
271 .await;
272
273 sync_permit_guard = MaybeAcquiredPermit::Unacquired(encryption_sync_permit.clone());
274
275 let report = if let Some(report) = receiver.recv().await {
276 report
277 } else {
278 info!("internal channel has been closed?");
279 // We should still stop the child tasks in the unlikely
280 // scenario that our receiver died.
281 TerminationReport::supervisor_error()
282 };
283
284 // If one service failed, make sure to request stopping the
285 // other one.
286 let (stop_room_list, stop_encryption) = match &report.origin {
287 TerminationOrigin::EncryptionSync => (true, false),
288 TerminationOrigin::RoomList => (false, true),
289 TerminationOrigin::Supervisor => (true, true),
290 };
291
292 // Stop both services, and wait for the streams to properly
293 // finish: at some point they'll return `None` and will exit
294 // their infinite loops, and their tasks will gracefully
295 // terminate.
296
297 if stop_room_list {
298 if let Err(err) = room_list_service.stop_sync() {
299 warn!(?report, "unable to stop room list service: {err:#}");
300 }
301
302 if report.has_expired() {
303 room_list_service.expire_sync_session().await;
304 }
305 }
306
307 if let Err(err) = room_list_task.await {
308 error!("when awaiting room list service: {err:#}");
309 }
310
311 if stop_encryption {
312 if let Err(err) = encryption_sync.stop_sync() {
313 warn!(?report, "unable to stop encryption sync: {err:#}");
314 }
315
316 if report.has_expired() {
317 encryption_sync.expire_sync_session().await;
318 }
319 }
320
321 if let Err(err) = encryption_sync_task.await {
322 error!("when awaiting encryption sync: {err:#}");
323 }
324
325 let has_unknown_token = report.has_unknown_token();
326
327 if let Some(error) = report.error {
328 if offline_mode & !has_unknown_token {
329 state.set(State::Offline);
330
331 let client = room_list_service.client();
332
333 if let Some(report) = Self::offline_check(client, &mut receiver).await {
334 if let Some(error) = report.error {
335 state.set(State::Error(Arc::new(error)));
336 } else {
337 state.set(State::Idle);
338 }
339 break;
340 }
341
342 state.set(State::Running);
343 } else {
344 state.set(State::Error(Arc::new(error)));
345 break;
346 }
347 } else if matches!(report.origin, TerminationOrigin::Supervisor) {
348 state.set(State::Idle);
349 break;
350 } else {
351 state.set(State::Terminated);
352 break;
353 }
354 }
355 }
356 .instrument(tracing::span!(Level::WARN, "supervisor task"));
357
358 let task = spawn(future);
359
360 (task, termination_sender)
361 }
362
363 async fn spawn_child_tasks(
364 room_list_service: Arc<RoomListService>,
365 encryption_sync_service: Arc<EncryptionSyncService>,
366 sync_permit_guard: MaybeAcquiredPermit,
367 sender: Sender<TerminationReport>,
368 parent_span: Span,
369 ) -> (JoinHandle<()>, JoinHandle<()>) {
370 // First, take care of the room list.
371 let room_list_task = spawn(
372 Self::room_list_sync_task(room_list_service, sender.clone())
373 .instrument(parent_span.clone()),
374 );
375
376 // Then, take care of the encryption sync.
377 let encryption_sync_task = spawn(
378 Self::encryption_sync_task(
379 encryption_sync_service,
380 sender.clone(),
381 sync_permit_guard.acquire().await,
382 )
383 .instrument(parent_span),
384 );
385
386 (room_list_task, encryption_sync_task)
387 }
388
389 async fn encryption_sync_task(
390 encryption_sync: Arc<EncryptionSyncService>,
391 sender: Sender<TerminationReport>,
392 sync_permit_guard: OwnedMutexGuard<EncryptionSyncPermit>,
393 ) {
394 let encryption_sync_stream = encryption_sync.sync(sync_permit_guard);
395 let mut encryption_sync_stream = pin!(encryption_sync_stream);
396
397 let termination_report = loop {
398 match encryption_sync_stream.next().await {
399 Some(Ok(())) => {
400 // Carry on.
401 }
402 Some(Err(error)) => {
403 let termination_report = TerminationReport::encryption_sync(Some(error));
404
405 if !termination_report.has_expired() {
406 error!(
407 "Error while processing encryption in sync service: {:#?}",
408 termination_report.error
409 );
410 }
411
412 break termination_report;
413 }
414 None => {
415 // The stream has ended.
416 break TerminationReport::encryption_sync(None);
417 }
418 }
419 };
420
421 if let Err(err) = sender.send(termination_report).await {
422 error!("Error while sending termination report: {err:#}");
423 }
424 }
425
426 async fn room_list_sync_task(
427 room_list_service: Arc<RoomListService>,
428 sender: Sender<TerminationReport>,
429 ) {
430 let room_list_stream = room_list_service.sync();
431 let mut room_list_stream = pin!(room_list_stream);
432
433 let termination_report = loop {
434 match room_list_stream.next().await {
435 Some(Ok(())) => {
436 // Carry on.
437 }
438 Some(Err(error)) => {
439 let termination_report = TerminationReport::room_list(Some(error));
440
441 if !termination_report.has_expired() {
442 error!(
443 "Error while processing room list in sync service: {:#?}",
444 termination_report.error
445 );
446 }
447
448 break termination_report;
449 }
450 None => {
451 // The stream has ended.
452 break TerminationReport::room_list(None);
453 }
454 }
455 };
456
457 if let Err(err) = sender.send(termination_report).await {
458 error!("Error while sending termination report: {err:#}");
459 }
460 }
461
462 async fn shutdown(self) {
463 match self.termination_sender.send(TerminationReport::supervisor()).await {
464 Ok(_) => {
465 let _ = self.task.await.inspect_err(|err| {
466 // A `JoinError` indicates that the task was already dead,
467 // either because it got cancelled or because it panicked.
468 // We only cancel the task in the Err branch below and the
469 // task shouldn't be able to panic.
470 //
471 // So let's log an error and return.
472 error!("The supervisor task has stopped unexpectedly: {err:?}");
473 });
474 }
475 Err(err) => {
476 error!("Couldn't send the termination report to the supervisor task: {err}");
477 // Let's abort the task if it won't shut down properly,
478 // otherwise we would have left it as a detached task.
479 self.task.abort();
480 }
481 }
482 }
483}
484
485struct SyncServiceInner {
486 encryption_sync_service: Arc<EncryptionSyncService>,
487
488 /// Is the offline mode for the [`SyncService`] enabled?
489 ///
490 /// The offline mode is described in the [`State::Offline`] enum variant.
491 with_offline_mode: bool,
492
493 /// What's the state of this sync service?
494 state: SharedObservable<State>,
495
496 /// The parent tracing span to use for the tasks within this service.
497 ///
498 /// Normally this will be [`Span::none`], but it may be useful to assign a
499 /// defined span, for example if there is more than one active sync service.
500 parent_span: Span,
501
502 /// Supervisor task ensuring proper termination.
503 ///
504 /// This task is waiting for a [`TerminationReport`] from any of the other
505 /// two tasks, or from a user request via [`SyncService::stop()`]. It makes
506 /// sure that the two services are properly shut up and just interrupted.
507 ///
508 /// This is set at the same time as the other two tasks.
509 supervisor: Option<SyncTaskSupervisor>,
510}
511
512impl SyncServiceInner {
513 async fn start(
514 &mut self,
515 room_list_service: Arc<RoomListService>,
516 encryption_sync_permit: Arc<AsyncMutex<EncryptionSyncPermit>>,
517 ) {
518 trace!("starting sync service");
519
520 self.supervisor =
521 Some(SyncTaskSupervisor::new(self, room_list_service, encryption_sync_permit).await);
522 self.state.set(State::Running);
523 }
524
525 async fn stop(&mut self) {
526 trace!("pausing sync service");
527
528 // Remove the supervisor from our state and request the tasks to be
529 // shutdown.
530 if let Some(supervisor) = self.supervisor.take() {
531 supervisor.shutdown().await;
532 } else {
533 error!("The sync service was not properly started, the supervisor task doesn't exist");
534 }
535 }
536
537 async fn restart(
538 &mut self,
539 room_list_service: Arc<RoomListService>,
540 encryption_sync_permit: Arc<AsyncMutex<EncryptionSyncPermit>>,
541 ) {
542 self.stop().await;
543 self.start(room_list_service, encryption_sync_permit).await;
544 }
545}
546
547/// A high level manager for your Matrix syncing needs.
548///
549/// The [`SyncService`] is responsible for managing real-time synchronization
550/// with a Matrix server. It can initiate and maintain the necessary
551/// synchronization tasks for you.
552///
553/// **Note**: The [`SyncService`] requires a server with support for [MSC4186],
554/// otherwise it will fail with an 404 `M_UNRECOGNIZED` request error.
555///
556/// [MSC4186]: https://github.com/matrix-org/matrix-spec-proposals/pull/4186/
557///
558/// # Example
559///
560/// ```no_run
561/// use matrix_sdk::Client;
562/// use matrix_sdk_ui::sync_service::{State, SyncService};
563/// # use url::Url;
564/// # async {
565/// let homeserver = Url::parse("http://example.com")?;
566/// let client = Client::new(homeserver).await?;
567///
568/// client
569/// .matrix_auth()
570/// .login_username("example", "wordpass")
571/// .initial_device_display_name("My bot")
572/// .await?;
573///
574/// let sync_service = SyncService::builder(client).build().await?;
575/// let mut state = sync_service.state();
576///
577/// while let Some(state) = state.next().await {
578/// match state {
579/// State::Idle => eprintln!("The sync service is idle."),
580/// State::Running => eprintln!("The sync has started to run."),
581/// State::Offline => eprintln!(
582/// "We have entered the offline mode, the server seems to be
583/// unavailable"
584/// ),
585/// State::Terminated => {
586/// eprintln!("The sync service has been gracefully terminated");
587/// break;
588/// }
589/// State::Error(_) => {
590/// eprintln!("The sync service has run into an error");
591/// break;
592/// }
593/// }
594/// }
595/// # anyhow::Ok(()) };
596/// ```
597pub struct SyncService {
598 inner: Arc<AsyncMutex<SyncServiceInner>>,
599
600 /// Room list service used to synchronize the rooms state.
601 room_list_service: Arc<RoomListService>,
602
603 /// What's the state of this sync service? This field is replicated from the
604 /// [`SyncServiceInner`] struct, but it should not be modified in this
605 /// struct. It's re-exposed here so we can subscribe to the state without
606 /// taking the lock on the `inner` field.
607 state: SharedObservable<State>,
608
609 /// Global lock to allow using at most one [`EncryptionSyncService`] at all
610 /// times.
611 ///
612 /// This ensures that there's only one ever existing in the application's
613 /// lifetime (under the assumption that there is at most one [`SyncService`]
614 /// per application).
615 encryption_sync_permit: Arc<AsyncMutex<EncryptionSyncPermit>>,
616}
617
618impl SyncService {
619 /// Create a new builder for configuring an `SyncService`.
620 pub fn builder(client: Client) -> SyncServiceBuilder {
621 SyncServiceBuilder::new(client)
622 }
623
624 /// Get the underlying `RoomListService` instance for easier access to its
625 /// methods.
626 pub fn room_list_service(&self) -> Arc<RoomListService> {
627 self.room_list_service.clone()
628 }
629
630 /// Returns the state of the sync service.
631 pub fn state(&self) -> Subscriber<State> {
632 self.state.subscribe()
633 }
634
635 /// Start (or restart) the underlying sliding syncs.
636 ///
637 /// This can be called multiple times safely:
638 ///
639 /// - if the stream is still properly running, it won't be restarted.
640 /// - if the [`SyncService`] is in the offline mode we will exit the offline
641 /// mode and immediately attempt to sync again.
642 /// - if the stream has been aborted before, it will be properly cleaned up
643 /// and restarted.
644 pub async fn start(&self) {
645 let mut inner = self.inner.lock().await;
646
647 // Only (re)start the tasks if it's stopped or if we're in the offline
648 // mode.
649 match inner.state.get() {
650 // If we're already running, there's nothing to do.
651 State::Running => {}
652 // If we're in the offline mode, first stop the service and then
653 // start it again.
654 State::Offline => {
655 inner
656 .restart(self.room_list_service.clone(), self.encryption_sync_permit.clone())
657 .await
658 }
659 // Otherwise just start.
660 State::Idle | State::Terminated | State::Error(_) => {
661 inner
662 .start(self.room_list_service.clone(), self.encryption_sync_permit.clone())
663 .await
664 }
665 }
666 }
667
668 /// Stop the underlying sliding syncs.
669 ///
670 /// This must be called when the app goes into the background. It's better
671 /// to call this API when the application exits, although not strictly
672 /// necessary.
673 #[instrument(skip_all)]
674 pub async fn stop(&self) {
675 let mut inner = self.inner.lock().await;
676
677 match inner.state.get() {
678 State::Idle | State::Terminated | State::Error(_) => {
679 // No need to stop if we were not running.
680 return;
681 }
682 State::Running | State::Offline => {}
683 }
684
685 inner.stop().await;
686 }
687
688 /// Force expiring both sessions.
689 ///
690 /// This ensures that the sync service is stopped before expiring both
691 /// sessions. It should be used sparingly, as it will cause a restart of the
692 /// sessions on the server as well.
693 #[instrument(skip_all)]
694 pub async fn expire_sessions(&self) {
695 // First, stop the sync service if it was running; it's a no-op if it
696 // was already stopped.
697 self.stop().await;
698
699 // Expire the room list sync session.
700 self.room_list_service.expire_sync_session().await;
701
702 // Expire the encryption sync session.
703 self.inner.lock().await.encryption_sync_service.expire_sync_session().await;
704 }
705
706 /// Attempt to get a permit to use an `EncryptionSyncService` at a given
707 /// time.
708 ///
709 /// This ensures there is at most one [`EncryptionSyncService`] active at
710 /// any time, per application.
711 pub fn try_get_encryption_sync_permit(&self) -> Option<OwnedMutexGuard<EncryptionSyncPermit>> {
712 self.encryption_sync_permit.clone().try_lock_owned().ok()
713 }
714}
715
716#[derive(Debug)]
717enum TerminationOrigin {
718 EncryptionSync,
719 RoomList,
720 Supervisor,
721}
722
723#[derive(Debug)]
724struct TerminationReport {
725 /// The origin of the termination.
726 origin: TerminationOrigin,
727
728 /// If the termination is due to an error, this is the cause.
729 error: Option<Error>,
730}
731
732impl TerminationReport {
733 /// Create a new [`TerminationReport`] with `origin` set to
734 /// [`TerminationOrigin::EncryptionSync`] and `error` set to
735 /// [`Error::EncryptionSync`].
736 fn encryption_sync(error: Option<encryption_sync_service::Error>) -> Self {
737 Self { origin: TerminationOrigin::EncryptionSync, error: error.map(Error::EncryptionSync) }
738 }
739
740 /// Create a new [`TerminationReport`] with `origin` set to
741 /// [`TerminationOrigin::RoomList`] and `error` set to [`Error::RoomList`].
742 fn room_list(error: Option<room_list_service::Error>) -> Self {
743 Self { origin: TerminationOrigin::RoomList, error: error.map(Error::RoomList) }
744 }
745
746 /// Create a new [`TerminationReport`] with `origin` set to
747 /// [`TerminationOrigin::Supervisor`] and `error` set to
748 /// [`Error::Supervisor`].
749 fn supervisor_error() -> Self {
750 Self { origin: TerminationOrigin::Supervisor, error: Some(Error::Supervisor) }
751 }
752
753 /// Create a new [`TerminationReport`] with `origin` set to
754 /// [`TerminationOrigin::Supervisor`] and `error` set to `None`.
755 fn supervisor() -> Self {
756 Self { origin: TerminationOrigin::Supervisor, error: None }
757 }
758
759 /// Check whether the termination is due to an expired sliding sync session.
760 fn has_expired(&self) -> bool {
761 match &self.error {
762 Some(Error::RoomList(room_list_service::Error::SlidingSync(error)))
763 | Some(Error::EncryptionSync(encryption_sync_service::Error::SlidingSync(error))) => {
764 error.client_api_error_kind() == Some(&ruma::api::error::ErrorKind::UnknownPos)
765 }
766 _ => false,
767 }
768 }
769
770 /// Check whether the termination is due to an unknown access token without
771 /// a soft logout.
772 fn has_unknown_token(&self) -> bool {
773 let (Some(Error::RoomList(room_list_service::Error::SlidingSync(error)))
774 | Some(Error::EncryptionSync(encryption_sync_service::Error::SlidingSync(error)))) =
775 &self.error
776 else {
777 return false;
778 };
779
780 matches!(
781 error.client_api_error_kind(),
782 Some(ruma::api::error::ErrorKind::UnknownToken(data))
783 if !data.soft_logout
784 )
785 }
786}
787
788// Testing helpers, mostly.
789#[doc(hidden)]
790impl SyncService {
791 /// Is the task supervisor running?
792 pub async fn is_supervisor_running(&self) -> bool {
793 self.inner.lock().await.supervisor.is_some()
794 }
795}
796
797#[derive(Clone)]
798pub struct SyncServiceBuilder {
799 /// SDK client.
800 client: Client,
801
802 /// Is the offline mode for the [`SyncService`] enabled?
803 ///
804 /// The offline mode is described in the [`State::Offline`] enum variant.
805 with_offline_mode: bool,
806
807 /// Whether to turn [`SlidingSyncBuilder::share_pos`] on or off.
808 ///
809 /// [`SlidingSyncBuilder::share_pos`]: matrix_sdk::sliding_sync::SlidingSyncBuilder::share_pos
810 with_share_pos: bool,
811
812 /// Custom connection ID for the room list service. Defaults to
813 /// [`room_list_service::DEFAULT_CONNECTION_ID`]. Use a different value for
814 /// secondary processes such as iOS share extensions that are not meant to
815 /// reuse the main app's connection.
816 room_list_conn_id: String,
817
818 /// Custom timeline limit for the room list service. Defaults to
819 /// [`room_list_service::DEFAULT_LIST_TIMELINE_LIMIT`].
820 room_list_timeline_limit: u32,
821
822 /// The parent tracing span to use for the tasks within this service.
823 ///
824 /// Normally this will be [`Span::none`], but it may be useful to assign a
825 /// defined span, for example if there is more than one active sync service.
826 parent_span: Span,
827}
828
829impl SyncServiceBuilder {
830 fn new(client: Client) -> Self {
831 Self {
832 client,
833 with_offline_mode: false,
834 with_share_pos: true,
835 room_list_conn_id: DEFAULT_CONNECTION_ID.to_owned(),
836 room_list_timeline_limit: DEFAULT_LIST_TIMELINE_LIMIT,
837 parent_span: Span::none(),
838 }
839 }
840
841 /// Enable the "offline" mode for the [`SyncService`].
842 ///
843 /// To learn more about the "offline" mode read the documentation for the
844 /// [`State::Offline`] enum variant.
845 pub fn with_offline_mode(mut self) -> Self {
846 self.with_offline_mode = true;
847 self
848 }
849
850 /// Whether to turn [`SlidingSyncBuilder::share_pos`] on or off.
851 ///
852 /// [`SlidingSyncBuilder::share_pos`]: matrix_sdk::sliding_sync::SlidingSyncBuilder::share_pos
853 pub fn with_share_pos(mut self, enable: bool) -> Self {
854 self.with_share_pos = enable;
855 self
856 }
857
858 /// Set a custom conn_id for the room list sliding sync connection.
859 pub fn with_room_list_conn_id(mut self, conn_id: String) -> Self {
860 self.room_list_conn_id = conn_id;
861 self
862 }
863
864 /// Set a custom timeline limit for the room list service.
865 pub fn with_room_list_timeline_limit(mut self, limit: u32) -> Self {
866 self.room_list_timeline_limit = limit;
867 self
868 }
869
870 /// Set the parent tracing span to be used for the tasks within this
871 /// service.
872 pub fn with_parent_span(mut self, parent_span: Span) -> Self {
873 self.parent_span = parent_span;
874 self
875 }
876
877 /// Finish setting up the [`SyncService`].
878 ///
879 /// This creates the underlying sliding syncs, and will _not_ start them in
880 /// the background. The resulting [`SyncService`] must be kept alive as long
881 /// as the sliding syncs are supposed to run.
882 pub async fn build(self) -> Result<SyncService, Error> {
883 let Self {
884 client,
885 with_offline_mode,
886 with_share_pos,
887 room_list_conn_id,
888 room_list_timeline_limit,
889 parent_span,
890 } = self;
891
892 let encryption_sync_permit = Arc::new(AsyncMutex::new(EncryptionSyncPermit::new()));
893
894 let room_list = RoomListService::new_with(
895 client.clone(),
896 with_share_pos,
897 &room_list_conn_id,
898 room_list_timeline_limit,
899 )
900 .await?;
901
902 let encryption_sync = Arc::new(EncryptionSyncService::new(client, None).await?);
903
904 let room_list_service = Arc::new(room_list);
905 let state = SharedObservable::new(State::Idle);
906
907 Ok(SyncService {
908 state: state.clone(),
909 room_list_service,
910 encryption_sync_permit,
911 inner: Arc::new(AsyncMutex::new(SyncServiceInner {
912 supervisor: None,
913 encryption_sync_service: encryption_sync,
914 state,
915 with_offline_mode,
916 parent_span,
917 })),
918 })
919 }
920}
921
922/// Errors for the [`SyncService`] API.
923#[derive(Debug, Error)]
924pub enum Error {
925 /// An error received from the `RoomListService` API.
926 #[error(transparent)]
927 RoomList(#[from] room_list_service::Error),
928
929 /// An error received from the `EncryptionSyncService` API.
930 #[error(transparent)]
931 EncryptionSync(#[from] encryption_sync_service::Error),
932
933 /// An error had occurred in the sync task supervisor, likely due to a bug.
934 #[error("the supervisor channel has run into an unexpected error")]
935 Supervisor,
936}