Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create SyncOrchestrator #4176

Open
wants to merge 9 commits into
base: develop
Choose a base branch
from
Open

Create SyncOrchestrator #4176

wants to merge 9 commits into from

Conversation

jmartinesp
Copy link
Member

@jmartinesp jmartinesp commented Jan 20, 2025

Content

Centralise the start/stop sync logic in a single component of the app:

  • Create SyncOrchestrator, which will act as the single point where sync start/stop can happen, based on several inputs (sync state, network available, app in foreground, app in call, app needing to sync an event for a notification).
  • Add the extra cases (app in call, syncing an event) to AppForegroundStateService.
  • Remove the start/stop sync logic from several parts of the code, replace them with toggling the inputs for the SyncOrchestrator.

Motivation and context

Having too many points where the sync could be started and stopped could cause issues where the sync was unexpectedly stopped when it should instead be running or a deadlock may happen for several start/stop calls.

It should help with #4150

Tests

Just play with the sync state with network online/offline and app foreground state, receiving notifications, joining calls, etc.

Tested devices

  • Physical
  • Emulator
  • OS version(s): 14

Checklist

  • Changes have been tested on an Android device or Android emulator with API 24
  • UI change has been tested on both light and dark themes
  • Accessibility has been taken into account. See https://github.com/element-hq/element-x-android/blob/develop/CONTRIBUTING.md#accessibility
  • Pull request is based on the develop branch
  • Pull request title will be used in the release note, it clearly define what will change for the user
  • Pull request includes screenshots or videos if containing UI changes
  • You've made a self review of your PR

Copy link
Contributor

github-actions bot commented Jan 20, 2025

📱 Scan the QR code below to install the build (arm64 only) for this PR.
QR code
If you can't scan the QR code you can install the build via this link: https://i.diawi.com/UtojEU

Copy link

codecov bot commented Jan 21, 2025

Codecov Report

Attention: Patch coverage is 75.96154% with 25 lines in your changes missing coverage. Please review.

Project coverage is 80.24%. Comparing base (6362e01) to head (27e841a).

Files with missing lines Patch % Lines
...oid/libraries/matrix/impl/timeline/RustTimeline.kt 0.00% 6 Missing ⚠️
...pnavstate/impl/DefaultAppForegroundStateService.kt 0.00% 6 Missing ⚠️
...tures/networkmonitor/impl/DefaultNetworkMonitor.kt 0.00% 4 Missing ⚠️
...n/io/element/android/appnav/di/SyncOrchestrator.kt 91.17% 2 Missing and 1 partial ⚠️
...ent/android/appnav/root/RootNavStateFlowFactory.kt 0.00% 2 Missing ⚠️
...io/element/android/appnav/di/MatrixSessionCache.kt 95.83% 0 Missing and 1 partial ⚠️
...atures/lockscreen/impl/DefaultLockScreenService.kt 0.00% 1 Missing ⚠️
...d/libraries/designsystem/utils/ForceOrientation.kt 0.00% 1 Missing ⚠️
...pnavstate/impl/DefaultAppNavigationStateService.kt 0.00% 1 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff             @@
##           develop    #4176      +/-   ##
===========================================
+ Coverage    80.22%   80.24%   +0.02%     
===========================================
  Files         2043     2044       +1     
  Lines        54113    54153      +40     
  Branches      6570     6573       +3     
===========================================
+ Hits         43411    43457      +46     
+ Misses        8429     8421       -8     
- Partials      2273     2275       +2     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

@jmartinesp jmartinesp added the PR-Feature For a new feature label Jan 22, 2025
@jmartinesp jmartinesp force-pushed the refactor/sync-observer branch from 396fe48 to 801dd62 Compare January 22, 2025 11:12
@jmartinesp jmartinesp marked this pull request as ready for review January 22, 2025 11:19
@jmartinesp jmartinesp requested a review from a team as a code owner January 22, 2025 11:19
@jmartinesp jmartinesp requested review from ganfra and removed request for a team January 22, 2025 11:19
@jmartinesp jmartinesp changed the title Create SyncObserver Create SyncOrchestrator Jan 22, 2025
@jmartinesp jmartinesp requested a review from bmarty January 22, 2025 15:29
@@ -147,6 +138,9 @@ class LoggedInFlowNode @AssistedInject constructor(

override fun onBuilt() {
super.onBuilt()

syncOrchestrator.start()
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this code will not be run if the app is killed and a Push is received. In this case the sync will not start?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think you're right, and I completely overlooked this... This complicates things, as we would have to use SyncOrchestrator in the AppScope and that means holding as many as MatrixClients there are in MatrixClientsHolder, maybe following a similar approach 🫤 .

Copy link
Member

@bmarty bmarty left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks! Please see my comments.

}
}
// Make sure we mark the call as ended in the app state
if (appForegroundStateService.isInCall.value) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: I do not think it is useful to read the value before changing it, or do I miss something here?

@@ -199,7 +199,7 @@ class LoginFlowNode @AssistedInject constructor(

@Composable
override fun View(modifier: Modifier) {
activity = LocalContext.current as? Activity
activity = LocalActivity.current
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe stick to the same line of code than for other classes:
val activity = requireNotNull(LocalActivity.current)

Copy link
Member

@ganfra ganfra left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Some remarks

/**
* Observes the app state and network state to start/stop the sync service.
*/
interface SyncOrchestrator {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure this class belongs the the matrix api, it's more an app thing to me

/**
* Provides a [SyncOrchestrator] for a given [SessionId].
*/
fun interface SyncOrchestratorProvider {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same ^

@@ -29,13 +30,14 @@ private const val SAVE_INSTANCE_KEY = "io.element.android.x.di.MatrixClientsHold
@ContributesBinding(AppScope::class)
class MatrixClientsHolder @Inject constructor(
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe we should rename this class so it's a bit clearer it's not just about MatrixClients?
Also we might want to create a class instead of using Pair?

I don't think we need the DefaultSyncOrchestratorProvider, we should let MatrixClientsHolder (with a new name :P) implements the SyncOrchestratorProvider

@jmartinesp
Copy link
Member Author

@ganfra all the points should have been fixed in the latest commit.

Copy link
Member

@ganfra ganfra left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM, thanks!

…ugh the whole app.

The decision is based on several inputs: sync state, network available, app in foreground, app in call, app needing to sync an event for a notification.
…fail instead

This prevents an issue when using the offline mode of the SDK, which made the wrong UI states to be shown when the `SyncState` is `Idle` (that is, after the service being manually stopped).
…they're not easily mistaken with internet connectivity instead
@jmartinesp jmartinesp force-pushed the refactor/sync-observer branch from 3033b67 to 64abdf6 Compare February 5, 2025 10:30
@jmartinesp jmartinesp requested a review from ganfra February 5, 2025 10:32
Copy link
Member

@bmarty bmarty left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A new bunch of comments, I have not run the code yet

@ContributesBinding(AppScope::class)
class MatrixClientsHolder @Inject constructor(
@ContributesBinding(AppScope::class, boundType = MatrixClientProvider::class)
@ContributesBinding(AppScope::class, boundType = SyncOrchestratorProvider::class)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

TIL we can have multiple @ContributesBinding annotations

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Well, we don't have them anymore after the latest changes 😅 .

private val sessionIdsToMatrixClient = ConcurrentHashMap<SessionId, MatrixClient>()
private val syncOrchestratorFactory: DefaultSyncOrchestrator.Factory,
) : MatrixClientProvider, SyncOrchestratorProvider {
private val sessionIdsToMatrixClient = ConcurrentHashMap<SessionId, InMemoryMatrixSession>()
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe rename this val now that it will contain InMemoryMatrixSession?

/**
* Stop observing the app state and network state.
*/
override fun stop() {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since this method is only used for test, you should remove it.
The background coroutine scope can be used from the TestScope, and can be provided in the constructor parameter.


// Start the sync if it wasn't already started
syncOrchestratorProvider.getSyncOrchestrator(notifiableEvent.sessionId)?.start() ?: return@withContext

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am wondering if matrixClientProvider.getOrRestore could also take care of starting the syncOrchestrator. Maybe the sync orchestrator should always be started? In this case the interface SyncOrchestrator could just be private?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good call, this simplified the code quite a bit!

baseCoroutineScope.launch(dispatchers.io) {
try {
initialSyncMutex.lock()
syncService.startSync()
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why do we need a first startSync here? The combine below is not enough to decide what to do depending on the status of all the observed flows?

Copy link
Member Author

@jmartinesp jmartinesp Feb 5, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was mimicking what we had before in LoggedInFlowNode for the airgapped case. After the changes in the SDK it's probably not needed anymore.

initialSyncMutex.lock()

combine(
// small debounce to avoid spamming startSync when the state is changing quickly in case of error.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe the debounced can be moved after the combine block (before .distinctUntilChanged())?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This causes issues in the tests, since it's preventing some intermediate states from being generated. I'd rather keep it were it is, if possible.

Copy link

sonarqubecloud bot commented Feb 5, 2025

@jmartinesp jmartinesp requested a review from bmarty February 5, 2025 13:11
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
PR-Feature For a new feature
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants