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