@file:OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class) package eu.friedcutlet.yokan.services.sync import eu.friedcutlet.yokan.domain.ProfileId import eu.friedcutlet.yokan.database.DbSettings import eu.friedcutlet.yokan.database.DbSyncPreference import eu.friedcutlet.yokan.database.InMemoryYokanDatabase import eu.friedcutlet.yokan.database.SyncServerProvider import eu.friedcutlet.yokan.database.emptySnapshot import eu.friedcutlet.yokan.services.backup.BackupOptions import eu.friedcutlet.yokan.services.backup.RestorePreview import eu.friedcutlet.yokan.services.http.HttpResponse import eu.friedcutlet.yokan.services.http.HttpService import eu.friedcutlet.yokan.services.http.ProfileTestEngine import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Job import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.awaitCancellation import kotlinx.coroutines.cancel import kotlinx.coroutines.cancelAndJoin import kotlinx.coroutines.currentCoroutineContext import kotlinx.coroutines.launch import kotlinx.coroutines.test.StandardTestDispatcher import kotlinx.coroutines.test.TestScope import kotlinx.coroutines.test.UnconfinedTestDispatcher import kotlinx.coroutines.test.runTest import kotlinx.coroutines.withContext import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFailsWith import kotlin.test.assertFalse import kotlin.test.assertNull import kotlin.test.assertSame import kotlin.test.assertTrue class ProfileSyncServicesTest { @Test fun concurrentPublicClosesAwaitTheProviderCleanupOnce() = runTest { val parent = SupervisorJob(); val scope = CoroutineScope(parent + StandardTestDispatcher(testScheduler)) val entered = CompletableDeferred(); val release = CompletableDeferred(); var joins = 0 val router = object : FakeSync() { override fun close() { error("Orderly retirement must await provider cleanup") } override suspend fun closeAndJoin() { joins++; entered.complete(Unit); release.await() } } val bound = ProfileSyncServices(A, router, FakeCloud(), scope) val first = launch { bound.sync.closeAndJoin() } entered.await() val second = launch { bound.cloud.closeAndJoin() } testScheduler.runCurrent() assertFalse(first.isCompleted); assertFalse(second.isCompleted); assertEquals(1, joins) release.complete(Unit); first.join(); second.join() assertEquals(1, joins); assertTrue(parent.isActive) parent.cancelAndJoin() } @Test fun awaitedProviderCleanupIsForwardedAfterLegacyImmediateClose() = runTest { val parent = SupervisorJob(); val scope = CoroutineScope(parent + StandardTestDispatcher(testScheduler)) var joins = 0 val router = object : FakeSync() { override suspend fun closeAndJoin() { joins++ } } val bound = ProfileSyncServices(A, router, FakeCloud(), scope) bound.sync.close(); assertEquals(1, router.closes) bound.cloud.closeAndJoin(); bound.sync.closeAndJoin() assertEquals(1, joins); assertEquals(1, router.closes) parent.cancelAndJoin() } @Test fun hybridProfileRetirementJoinsHubHandshakeWithoutCancelingParentOrSiblings() = runTest { val parent = SupervisorJob(); val dispatcher = StandardTestDispatcher(testScheduler) val scope = CoroutineScope(parent + dispatcher) val sibling = scope.launch { awaitCancellation() } val database = InMemoryYokanDatabase(emptySnapshot()) val preference = DbSyncPreference(syncId = 1, syncOn = true, server = "https://hub.test", authToken = "captured-token", deviceId = "captured-device") database.upsertSyncPreference(preference) val release = CompletableDeferred(); var finalized = false val engine = ProfileTestEngine(dispatcher) { try { awaitCancellation() } finally { withContext(NonCancellable) { release.await(); finalized = true } } } val http = HttpService { error("Handshake is still pending") } val hub = HubSyncService(database, http, engine, scope = scope) val cloud = FakeCloud(); val mangayomi = FakeSync() val bound = ProfileSyncServices(A, HybridSyncService(hub, cloud, database, mangayomiSync = mangayomi), cloud, scope) val request = engine.requests.receive() assertEquals("Bearer captured-token", request.headers["Authorization"]) assertEquals("captured-device", request.headers["X-Device"]) assertEquals("/api/v1/events", request.url.encodedPath) val retiring = launch { bound.sync.closeAndJoin() } testScheduler.runCurrent() assertFalse(retiring.isCompleted); assertFalse(finalized) assertEquals(0, engine.closeCalls); assertEquals(0, cloud.closes); assertEquals(0, mangayomi.closes) assertTrue(parent.isActive); assertTrue(sibling.isActive) release.complete(Unit); retiring.join() assertTrue(finalized); assertEquals(1, engine.closeCalls) assertTrue(engine.coroutineContext[Job]?.isCompleted == true) assertEquals(1, cloud.closes); assertEquals(1, mangayomi.closes) bound.cloud.closeAndJoin() database.upsertSyncPreference(preference.copy(authToken = "replacement-token")) testScheduler.runCurrent() assertTrue(engine.requests.tryReceive().isFailure) assertTrue(parent.isActive); assertTrue(sibling.isActive) assertEquals(listOf(sibling), parent.children.toList()) parent.cancelAndJoin() } @Test fun publicRouterAndDirectCloudCallsRetainTheirArgumentsAndState() = runTest { val fixture = fixture() val sync = fixture.bound.sync val cloud = fixture.bound.cloud assertSame(fixture.router.operationState, sync.operationState) assertSame(fixture.cloud.operationState, cloud.operationState) assertTrue(sync.login(7, "server", "email", "password").success) val attempt = requireNotNull(sync.beginBrowserLogin(7, "server")) assertTrue(requireNotNull(sync.completeBrowserLogin(attempt, "callback")).success) sync.cancelBrowserLogin(attempt) sync.logout(7); sync.sync(7, DbSettings()); sync.pushChanges(7); sync.pullChanges(7) assertTrue(cloud.connect(8, "cloud", "account", "token").success) cloud.uploadBackup(8, BackupOptions()); cloud.restoreLatestBackup(8) assertEquals(listOf("login:7:server:email:password", "begin:7:server", "complete:7:callback", "cancel:7", "logout:7", "sync:7", "push:7", "pull:7"), fixture.router.calls) assertEquals(listOf("connect:8:cloud:account:token", "upload:8", "restore:8"), fixture.cloud.calls) fixture.finish() } @Test fun retirementJoinsAnExternalSignInBeforeReleasingTheProviderGraph() = runTest { val fixture = fixture() val entered = CompletableDeferred(); val release = CompletableDeferred() var finalized = false fixture.router.action = { try { entered.complete(Unit); awaitCancellation() } finally { withContext(NonCancellable) { release.await(); finalized = true } } } val caller = launch { fixture.bound.sync.login(1, "server", "email", "password") } entered.await() val shutdown = launch { fixture.bound.sync.closeAndJoin() } testScheduler.runCurrent() assertFalse(shutdown.isCompleted); assertFalse(caller.isCompleted) assertEquals(0, fixture.router.closes) assertNull(fixture.bound.sync.beginBrowserLogin(1, "server")) assertFailsWith { fixture.bound.cloud.connect(1, "cloud", null, "late") } release.complete(Unit); shutdown.join(); caller.join() assertTrue(finalized); assertEquals(1, fixture.router.closes) fixture.bound.cloud.closeAndJoin(); assertEquals(1, fixture.router.closes) fixture.finish() } @Test fun ownerCancellationJoinsCloudRestoreFinalizers() = runTest { val fixture = fixture() val entered = CompletableDeferred(); val release = CompletableDeferred() var finalized = false fixture.cloud.action = { try { entered.complete(Unit); awaitCancellation() } finally { withContext(NonCancellable) { release.await(); finalized = true } } } val caller = launch { fixture.bound.cloud.restoreLatestBackup(1) } entered.await() val retiring = launch { fixture.parent.cancelAndJoin() } testScheduler.runCurrent() assertFalse(retiring.isCompleted); assertFalse(caller.isCompleted) release.complete(Unit); retiring.join(); caller.join() assertTrue(finalized) fixture.bound.sync.closeAndJoin() assertEquals(1, fixture.router.closes) } @Test fun callerExpiryJoinsOnlyItsCallAndPreservesOwnerAndSiblingWork() = runTest { val fixture = fixture() val entered = CompletableDeferred(); val release = CompletableDeferred() fixture.router.action = { try { entered.complete(Unit); awaitCancellation() } finally { withContext(NonCancellable) { release.await() } } } val sibling = fixture.scope.launch { awaitCancellation() } val caller = launch { fixture.bound.sync.pushChanges(1) } entered.await(); caller.cancel(); testScheduler.runCurrent() assertFalse(caller.isCompleted); assertTrue(fixture.parent.isActive); assertTrue(sibling.isActive) release.complete(Unit); caller.join() fixture.router.action = {} assertTrue(fixture.bound.sync.login(1, "server", "email", "password").success) fixture.finish() } @Test fun alreadyExpiredCallerCannotDispatchWithAnImmediateOwner() = runTest { val fixture = fixture(immediate = true) val caller = launch { currentCoroutineContext().cancel() assertFailsWith { fixture.bound.cloud.connect(1, "cloud", null, "token") } } caller.join() assertTrue(fixture.cloud.calls.isEmpty()); assertTrue(fixture.parent.isActive) fixture.finish() } @Test fun queuedCallCanceledBeforeDispatchCannotWriteCredentials() = runTest { val fixture = fixture() val caller = launch(UnconfinedTestDispatcher(testScheduler)) { fixture.bound.sync.login(1, "server", "email", "password") } fixture.parent.cancel(); testScheduler.runCurrent(); caller.join() assertTrue(fixture.router.calls.isEmpty()) fixture.finish() } @Test fun staleReferencesCannotReadAccountsOrPerformAnySyncAction() = runTest { val fixture = fixture() val attempt = requireNotNull(fixture.bound.sync.beginBrowserLogin(1, "server")) fixture.parent.cancelAndJoin() fixture.router.calls.clear(); fixture.cloud.calls.clear() assertNull(fixture.bound.sync.beginBrowserLogin(1, "server")) fixture.bound.sync.cancelBrowserLogin(attempt) assertEquals(SyncConnectionStatus(false, null, null, null), fixture.bound.sync.status(1)) assertTrue(fixture.bound.cloud.providers().isEmpty()) assertFalse(fixture.bound.cloud.isCloudPreference(DbSyncPreference(syncId = 1, server = "cloud://cloud"))) assertFailsWith { fixture.bound.sync.login(1, "server", "email", "password") } assertFailsWith { fixture.bound.sync.completeBrowserLogin(attempt, "callback") } assertFailsWith { fixture.bound.sync.logout(1) } assertFailsWith { fixture.bound.sync.sync(1, DbSettings()) } assertFailsWith { fixture.bound.sync.pushChanges(1) } assertFailsWith { fixture.bound.sync.pullChanges(1) } assertFailsWith { fixture.bound.cloud.connect(1, "cloud", null, "token") } assertFailsWith { fixture.bound.cloud.uploadBackup(1, BackupOptions()) } assertFailsWith { fixture.bound.cloud.restoreLatestBackup(1) } assertTrue(fixture.router.calls.isEmpty()); assertTrue(fixture.cloud.calls.isEmpty()) fixture.finish() } @Test fun retiringOneOwnerDoesNotRetargetTheOtherWithTheSameSyncId() = runTest { val left = fixture(A); val right = fixture(B) left.bound.cloud.closeAndJoin() assertEquals(A, left.bound.profileId); assertEquals(B, right.bound.profileId) assertFailsWith { left.bound.sync.login(1, "left", "a", "a-token") } assertTrue(right.bound.sync.login(1, "right", "b", "b-token").success) assertEquals(listOf("login:1:right:b:b-token"), right.router.calls) assertTrue(left.router.calls.isEmpty()); assertEquals(0, right.router.closes) left.finish(); right.finish() } @Test fun failedProviderReleaseCanBeRetriedWithoutReopeningCalls() = runTest { val fixture = fixture() fixture.router.failClose = true assertFailsWith { fixture.bound.sync.closeAndJoin() } assertFailsWith { fixture.bound.sync.logout(1) } fixture.router.failClose = false fixture.bound.sync.closeAndJoin(); fixture.bound.cloud.closeAndJoin() assertEquals(2, fixture.router.closes) fixture.finish() } @Test fun lateHubCredentialResponseCannotCommitAfterOwnerRetirement() = runTest { val database = InMemoryYokanDatabase(emptySnapshot()) val entered = CompletableDeferred(); val release = CompletableDeferred() val http = HttpService { request -> if (request.url.endsWith("/api/version")) HttpResponse(200, """{"supported":["1"]}""") else { entered.complete(Unit) withContext(NonCancellable) { release.await() } HttpResponse(200, """{"token":"late-token","user":{"id":"u","email":"a@b"}}""") } } val parent = SupervisorJob(); val scope = CoroutineScope(parent + StandardTestDispatcher(testScheduler)) val hub = HubSyncService(database, http, webSocketEngine = null, autoSync = false, scope = scope) val bound = ProfileSyncServices(A, hub, FakeCloud(), scope) val caller = launch { bound.sync.login(1, "https://hub.test", "a@b", "password") } entered.await(); parent.cancel(); testScheduler.runCurrent() release.complete(Unit); parent.join(); caller.join() assertTrue(database.syncPreferences().isEmpty()) bound.sync.closeAndJoin() } @Test fun lateMangayomiCredentialResponseCannotCommitAfterOwnerRetirement() = runTest { val database = InMemoryYokanDatabase(emptySnapshot()) val prior = DbSyncPreference(syncId = 1, serverProvider = SyncServerProvider.Mangayomi) database.upsertSyncPreference(prior) val entered = CompletableDeferred(); val release = CompletableDeferred() val http = HttpService { entered.complete(Unit) withContext(NonCancellable) { release.await() } HttpResponse(statusCode = 200, body = """{"ok":true}""", setCookies = listOf("id=late-token; Path=/")) } val parent = SupervisorJob(); val scope = CoroutineScope(parent + StandardTestDispatcher(testScheduler)) val mangayomi = MangayomiSyncService(database, http) val bound = ProfileSyncServices(A, mangayomi, FakeCloud(), scope) val caller = launch { bound.sync.login(1, "https://mangayomi.test", "user", "password") } entered.await(); parent.cancel(); testScheduler.runCurrent() release.complete(Unit); parent.join(); caller.join() assertEquals(prior, database.syncPreferences().single()) bound.sync.closeAndJoin() } @Test fun browserAttemptFromAnotherOwnerOrReplacementSessionIsRejected() = runTest { val http = HttpService { HttpResponse(200, """{"supported":["1"]}""") } val parentA = SupervisorJob(); val parentB = SupervisorJob() val scopeA = CoroutineScope(parentA + StandardTestDispatcher(testScheduler)) val scopeB = CoroutineScope(parentB + StandardTestDispatcher(testScheduler)) val databaseA = InMemoryYokanDatabase(emptySnapshot()); val databaseB = InMemoryYokanDatabase(emptySnapshot()) val a = ProfileSyncServices(A, HubSyncService(databaseA, http, null, autoSync = false, scope = scopeA), FakeCloud(), scopeA) val b = ProfileSyncServices(B, HubSyncService(databaseB, http, null, autoSync = false, scope = scopeB), FakeCloud(), scopeB) val attempt = requireNotNull(a.sync.beginBrowserLogin(1, "https://hub.test")) val callback = "https://hub.test/login/done#state=${attempt.state}&device=${attempt.device}&token=token&email=a%40b" assertNull(b.sync.completeBrowserLogin(attempt, callback)) assertTrue(databaseB.syncPreferences().isEmpty()) assertTrue(requireNotNull(a.sync.completeBrowserLogin(attempt, callback)).success) assertEquals("token", databaseA.syncPreferences().single().authToken) a.sync.closeAndJoin(); parentA.cancelAndJoin() val replacement = ProfileSyncServices(A, HubSyncService(databaseB, http, null, autoSync = false, scope = scopeB), FakeCloud(), scopeB) assertNull(replacement.sync.completeBrowserLogin(attempt, callback)) assertTrue(databaseB.syncPreferences().isEmpty()) b.sync.closeAndJoin(); replacement.sync.closeAndJoin(); parentB.cancelAndJoin() } private fun TestScope.fixture(id: ProfileId = A, immediate: Boolean = false): Fixture { val parent = SupervisorJob() val scope = CoroutineScope(parent + if (immediate) UnconfinedTestDispatcher(testScheduler) else StandardTestDispatcher(testScheduler)) val router = FakeSync(); val cloud = FakeCloud() return Fixture(parent, scope, router, cloud, ProfileSyncServices(id, router, cloud, scope)) } private class Fixture(val parent: Job, val scope: CoroutineScope, val router: FakeSync, val cloud: FakeCloud, val bound: ProfileSyncServices) { suspend fun finish() { parent.cancelAndJoin(); bound.sync.closeAndJoin() } } private open class FakeSync : SyncService { val calls = mutableListOf() var action: suspend () -> Unit = {} var closes = 0 var failClose = false override suspend fun login(syncId: Long, server: String, email: String, password: String): SyncLoginResult { calls += "login:$syncId:$server:$email:$password"; action(); return SyncLoginResult(true, "ok") } override fun beginBrowserLogin(syncId: Long, server: String): BrowserLoginAttempt { calls += "begin:$syncId:$server"; return BrowserLoginAttempt(syncId, server, "url", "device", "state") } override suspend fun completeBrowserLogin(attempt: BrowserLoginAttempt, loadedUrl: String): SyncLoginResult { calls += "complete:${attempt.syncId}:$loadedUrl"; action(); return SyncLoginResult(true, "ok") } override fun cancelBrowserLogin(attempt: BrowserLoginAttempt) { calls += "cancel:${attempt.syncId}" } override suspend fun logout(syncId: Long) { calls += "logout:$syncId"; action() } override suspend fun sync(syncId: Long, settings: DbSettings): SyncResult { calls += "sync:$syncId"; action(); return SyncResult(1, 2, true) } override suspend fun pushChanges(syncId: Long): SyncResult { calls += "push:$syncId"; action(); return SyncResult(1, 0, false) } override suspend fun pullChanges(syncId: Long): SyncResult { calls += "pull:$syncId"; action(); return SyncResult(0, 1, false) } override fun status(syncId: Long): SyncConnectionStatus { calls += "status:$syncId"; return SyncConnectionStatus(true, "email", "server", 1) } override fun close() { closes++; check(!failClose) } } private class FakeCloud : FakeSync(), CloudBackupSyncService { override fun providers(): List { calls += "providers"; return emptyList() } override fun isCloudPreference(syncPreference: DbSyncPreference?): Boolean { calls += "isCloud"; return true } override suspend fun connect(syncId: Long, providerId: String, accountLabel: String?, accessToken: String): SyncLoginResult { calls += "connect:$syncId:$providerId:$accountLabel:$accessToken"; action(); return SyncLoginResult(true, "ok") } override suspend fun uploadBackup(syncId: Long, options: BackupOptions): CloudBackupResult { calls += "upload:$syncId"; action(); return CloudBackupResult("cloud", "file", 1, 1, CloudObject("file", "file", 1, 1)) } override suspend fun restoreLatestBackup(syncId: Long): CloudBackupRestoreResult { calls += "restore:$syncId"; action(); return CloudBackupRestoreResult("cloud", "file", RestorePreview(1, emptyList())) } } private companion object { val A = ProfileId("p_11111111111111111111111111111111") val B = ProfileId("p_22222222222222222222222222222222") } }