ProfileSyncServicesTest.kt
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/sync/ProfileSyncServicesTest.kt
1@file:OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)23package eu.friedcutlet.yokan.services.sync45import eu.friedcutlet.yokan.domain.ProfileId6import eu.friedcutlet.yokan.database.DbSettings7import eu.friedcutlet.yokan.database.DbSyncPreference8import eu.friedcutlet.yokan.database.InMemoryYokanDatabase9import eu.friedcutlet.yokan.database.SyncServerProvider10import eu.friedcutlet.yokan.database.emptySnapshot11import eu.friedcutlet.yokan.services.backup.BackupOptions12import eu.friedcutlet.yokan.services.backup.RestorePreview13import eu.friedcutlet.yokan.services.http.HttpResponse14import eu.friedcutlet.yokan.services.http.HttpService15import eu.friedcutlet.yokan.services.http.ProfileTestEngine16import kotlinx.coroutines.CancellationException17import kotlinx.coroutines.CompletableDeferred18import kotlinx.coroutines.CoroutineScope19import kotlinx.coroutines.Job20import kotlinx.coroutines.NonCancellable21import kotlinx.coroutines.SupervisorJob22import kotlinx.coroutines.awaitCancellation23import kotlinx.coroutines.cancel24import kotlinx.coroutines.cancelAndJoin25import kotlinx.coroutines.currentCoroutineContext26import kotlinx.coroutines.launch27import kotlinx.coroutines.test.StandardTestDispatcher28import kotlinx.coroutines.test.TestScope29import kotlinx.coroutines.test.UnconfinedTestDispatcher30import kotlinx.coroutines.test.runTest31import kotlinx.coroutines.withContext32import kotlin.test.Test33import kotlin.test.assertEquals34import kotlin.test.assertFailsWith35import kotlin.test.assertFalse36import kotlin.test.assertNull37import kotlin.test.assertSame38import kotlin.test.assertTrue3940class ProfileSyncServicesTest {41 @Test fun concurrentPublicClosesAwaitTheProviderCleanupOnce() = runTest {42 val parent = SupervisorJob(); val scope = CoroutineScope(parent + StandardTestDispatcher(testScheduler))43 val entered = CompletableDeferred<Unit>(); val release = CompletableDeferred<Unit>(); var joins = 044 val router = object : FakeSync() {45 override fun close() { error("Orderly retirement must await provider cleanup") }46 override suspend fun closeAndJoin() { joins++; entered.complete(Unit); release.await() }47 }48 val bound = ProfileSyncServices(A, router, FakeCloud(), scope)49 val first = launch { bound.sync.closeAndJoin() }50 entered.await()51 val second = launch { bound.cloud.closeAndJoin() }52 testScheduler.runCurrent()53 assertFalse(first.isCompleted); assertFalse(second.isCompleted); assertEquals(1, joins)54 release.complete(Unit); first.join(); second.join()55 assertEquals(1, joins); assertTrue(parent.isActive)56 parent.cancelAndJoin()57 }5859 @Test fun awaitedProviderCleanupIsForwardedAfterLegacyImmediateClose() = runTest {60 val parent = SupervisorJob(); val scope = CoroutineScope(parent + StandardTestDispatcher(testScheduler))61 var joins = 062 val router = object : FakeSync() { override suspend fun closeAndJoin() { joins++ } }63 val bound = ProfileSyncServices(A, router, FakeCloud(), scope)64 bound.sync.close(); assertEquals(1, router.closes)65 bound.cloud.closeAndJoin(); bound.sync.closeAndJoin()66 assertEquals(1, joins); assertEquals(1, router.closes)67 parent.cancelAndJoin()68 }6970 @Test fun hybridProfileRetirementJoinsHubHandshakeWithoutCancelingParentOrSiblings() = runTest {71 val parent = SupervisorJob(); val dispatcher = StandardTestDispatcher(testScheduler)72 val scope = CoroutineScope(parent + dispatcher)73 val sibling = scope.launch { awaitCancellation() }74 val database = InMemoryYokanDatabase(emptySnapshot())75 val preference = DbSyncPreference(syncId = 1, syncOn = true, server = "https://hub.test",76 authToken = "captured-token", deviceId = "captured-device")77 database.upsertSyncPreference(preference)78 val release = CompletableDeferred<Unit>(); var finalized = false79 val engine = ProfileTestEngine(dispatcher) {80 try { awaitCancellation() }81 finally { withContext(NonCancellable) { release.await(); finalized = true } }82 }83 val http = HttpService { error("Handshake is still pending") }84 val hub = HubSyncService(database, http, engine, scope = scope)85 val cloud = FakeCloud(); val mangayomi = FakeSync()86 val bound = ProfileSyncServices(A, HybridSyncService(hub, cloud, database, mangayomiSync = mangayomi), cloud, scope)87 val request = engine.requests.receive()88 assertEquals("Bearer captured-token", request.headers["Authorization"])89 assertEquals("captured-device", request.headers["X-Device"])90 assertEquals("/api/v1/events", request.url.encodedPath)91 val retiring = launch { bound.sync.closeAndJoin() }92 testScheduler.runCurrent()93 assertFalse(retiring.isCompleted); assertFalse(finalized)94 assertEquals(0, engine.closeCalls); assertEquals(0, cloud.closes); assertEquals(0, mangayomi.closes)95 assertTrue(parent.isActive); assertTrue(sibling.isActive)96 release.complete(Unit); retiring.join()97 assertTrue(finalized); assertEquals(1, engine.closeCalls)98 assertTrue(engine.coroutineContext[Job]?.isCompleted == true)99 assertEquals(1, cloud.closes); assertEquals(1, mangayomi.closes)100 bound.cloud.closeAndJoin()101 database.upsertSyncPreference(preference.copy(authToken = "replacement-token"))102 testScheduler.runCurrent()103 assertTrue(engine.requests.tryReceive().isFailure)104 assertTrue(parent.isActive); assertTrue(sibling.isActive)105 assertEquals(listOf(sibling), parent.children.toList())106 parent.cancelAndJoin()107 }108109 @Test fun publicRouterAndDirectCloudCallsRetainTheirArgumentsAndState() = runTest {110 val fixture = fixture()111 val sync = fixture.bound.sync112 val cloud = fixture.bound.cloud113 assertSame(fixture.router.operationState, sync.operationState)114 assertSame(fixture.cloud.operationState, cloud.operationState)115 assertTrue(sync.login(7, "server", "email", "password").success)116 val attempt = requireNotNull(sync.beginBrowserLogin(7, "server"))117 assertTrue(requireNotNull(sync.completeBrowserLogin(attempt, "callback")).success)118 sync.cancelBrowserLogin(attempt)119 sync.logout(7); sync.sync(7, DbSettings()); sync.pushChanges(7); sync.pullChanges(7)120 assertTrue(cloud.connect(8, "cloud", "account", "token").success)121 cloud.uploadBackup(8, BackupOptions()); cloud.restoreLatestBackup(8)122 assertEquals(listOf("login:7:server:email:password", "begin:7:server", "complete:7:callback", "cancel:7",123 "logout:7", "sync:7", "push:7", "pull:7"), fixture.router.calls)124 assertEquals(listOf("connect:8:cloud:account:token", "upload:8", "restore:8"), fixture.cloud.calls)125 fixture.finish()126 }127128 @Test fun retirementJoinsAnExternalSignInBeforeReleasingTheProviderGraph() = runTest {129 val fixture = fixture()130 val entered = CompletableDeferred<Unit>(); val release = CompletableDeferred<Unit>()131 var finalized = false132 fixture.router.action = {133 try { entered.complete(Unit); awaitCancellation() }134 finally { withContext(NonCancellable) { release.await(); finalized = true } }135 }136 val caller = launch { fixture.bound.sync.login(1, "server", "email", "password") }137 entered.await()138 val shutdown = launch { fixture.bound.sync.closeAndJoin() }139 testScheduler.runCurrent()140 assertFalse(shutdown.isCompleted); assertFalse(caller.isCompleted)141 assertEquals(0, fixture.router.closes)142 assertNull(fixture.bound.sync.beginBrowserLogin(1, "server"))143 assertFailsWith<CancellationException> { fixture.bound.cloud.connect(1, "cloud", null, "late") }144 release.complete(Unit); shutdown.join(); caller.join()145 assertTrue(finalized); assertEquals(1, fixture.router.closes)146 fixture.bound.cloud.closeAndJoin(); assertEquals(1, fixture.router.closes)147 fixture.finish()148 }149150 @Test fun ownerCancellationJoinsCloudRestoreFinalizers() = runTest {151 val fixture = fixture()152 val entered = CompletableDeferred<Unit>(); val release = CompletableDeferred<Unit>()153 var finalized = false154 fixture.cloud.action = {155 try { entered.complete(Unit); awaitCancellation() }156 finally { withContext(NonCancellable) { release.await(); finalized = true } }157 }158 val caller = launch { fixture.bound.cloud.restoreLatestBackup(1) }159 entered.await()160 val retiring = launch { fixture.parent.cancelAndJoin() }161 testScheduler.runCurrent()162 assertFalse(retiring.isCompleted); assertFalse(caller.isCompleted)163 release.complete(Unit); retiring.join(); caller.join()164 assertTrue(finalized)165 fixture.bound.sync.closeAndJoin()166 assertEquals(1, fixture.router.closes)167 }168169 @Test fun callerExpiryJoinsOnlyItsCallAndPreservesOwnerAndSiblingWork() = runTest {170 val fixture = fixture()171 val entered = CompletableDeferred<Unit>(); val release = CompletableDeferred<Unit>()172 fixture.router.action = {173 try { entered.complete(Unit); awaitCancellation() }174 finally { withContext(NonCancellable) { release.await() } }175 }176 val sibling = fixture.scope.launch { awaitCancellation() }177 val caller = launch { fixture.bound.sync.pushChanges(1) }178 entered.await(); caller.cancel(); testScheduler.runCurrent()179 assertFalse(caller.isCompleted); assertTrue(fixture.parent.isActive); assertTrue(sibling.isActive)180 release.complete(Unit); caller.join()181 fixture.router.action = {}182 assertTrue(fixture.bound.sync.login(1, "server", "email", "password").success)183 fixture.finish()184 }185186 @Test fun alreadyExpiredCallerCannotDispatchWithAnImmediateOwner() = runTest {187 val fixture = fixture(immediate = true)188 val caller = launch {189 currentCoroutineContext().cancel()190 assertFailsWith<CancellationException> { fixture.bound.cloud.connect(1, "cloud", null, "token") }191 }192 caller.join()193 assertTrue(fixture.cloud.calls.isEmpty()); assertTrue(fixture.parent.isActive)194 fixture.finish()195 }196197 @Test fun queuedCallCanceledBeforeDispatchCannotWriteCredentials() = runTest {198 val fixture = fixture()199 val caller = launch(UnconfinedTestDispatcher(testScheduler)) {200 fixture.bound.sync.login(1, "server", "email", "password")201 }202 fixture.parent.cancel(); testScheduler.runCurrent(); caller.join()203 assertTrue(fixture.router.calls.isEmpty())204 fixture.finish()205 }206207 @Test fun staleReferencesCannotReadAccountsOrPerformAnySyncAction() = runTest {208 val fixture = fixture()209 val attempt = requireNotNull(fixture.bound.sync.beginBrowserLogin(1, "server"))210 fixture.parent.cancelAndJoin()211 fixture.router.calls.clear(); fixture.cloud.calls.clear()212 assertNull(fixture.bound.sync.beginBrowserLogin(1, "server"))213 fixture.bound.sync.cancelBrowserLogin(attempt)214 assertEquals(SyncConnectionStatus(false, null, null, null), fixture.bound.sync.status(1))215 assertTrue(fixture.bound.cloud.providers().isEmpty())216 assertFalse(fixture.bound.cloud.isCloudPreference(DbSyncPreference(syncId = 1, server = "cloud://cloud")))217 assertFailsWith<CancellationException> { fixture.bound.sync.login(1, "server", "email", "password") }218 assertFailsWith<CancellationException> { fixture.bound.sync.completeBrowserLogin(attempt, "callback") }219 assertFailsWith<CancellationException> { fixture.bound.sync.logout(1) }220 assertFailsWith<CancellationException> { fixture.bound.sync.sync(1, DbSettings()) }221 assertFailsWith<CancellationException> { fixture.bound.sync.pushChanges(1) }222 assertFailsWith<CancellationException> { fixture.bound.sync.pullChanges(1) }223 assertFailsWith<CancellationException> { fixture.bound.cloud.connect(1, "cloud", null, "token") }224 assertFailsWith<CancellationException> { fixture.bound.cloud.uploadBackup(1, BackupOptions()) }225 assertFailsWith<CancellationException> { fixture.bound.cloud.restoreLatestBackup(1) }226 assertTrue(fixture.router.calls.isEmpty()); assertTrue(fixture.cloud.calls.isEmpty())227 fixture.finish()228 }229230 @Test fun retiringOneOwnerDoesNotRetargetTheOtherWithTheSameSyncId() = runTest {231 val left = fixture(A); val right = fixture(B)232 left.bound.cloud.closeAndJoin()233 assertEquals(A, left.bound.profileId); assertEquals(B, right.bound.profileId)234 assertFailsWith<CancellationException> { left.bound.sync.login(1, "left", "a", "a-token") }235 assertTrue(right.bound.sync.login(1, "right", "b", "b-token").success)236 assertEquals(listOf("login:1:right:b:b-token"), right.router.calls)237 assertTrue(left.router.calls.isEmpty()); assertEquals(0, right.router.closes)238 left.finish(); right.finish()239 }240241 @Test fun failedProviderReleaseCanBeRetriedWithoutReopeningCalls() = runTest {242 val fixture = fixture()243 fixture.router.failClose = true244 assertFailsWith<IllegalStateException> { fixture.bound.sync.closeAndJoin() }245 assertFailsWith<CancellationException> { fixture.bound.sync.logout(1) }246 fixture.router.failClose = false247 fixture.bound.sync.closeAndJoin(); fixture.bound.cloud.closeAndJoin()248 assertEquals(2, fixture.router.closes)249 fixture.finish()250 }251252 @Test fun lateHubCredentialResponseCannotCommitAfterOwnerRetirement() = runTest {253 val database = InMemoryYokanDatabase(emptySnapshot())254 val entered = CompletableDeferred<Unit>(); val release = CompletableDeferred<Unit>()255 val http = HttpService { request ->256 if (request.url.endsWith("/api/version")) HttpResponse(200, """{"supported":["1"]}""")257 else {258 entered.complete(Unit)259 withContext(NonCancellable) { release.await() }260 HttpResponse(200, """{"token":"late-token","user":{"id":"u","email":"a@b"}}""")261 }262 }263 val parent = SupervisorJob(); val scope = CoroutineScope(parent + StandardTestDispatcher(testScheduler))264 val hub = HubSyncService(database, http, webSocketEngine = null, autoSync = false, scope = scope)265 val bound = ProfileSyncServices(A, hub, FakeCloud(), scope)266 val caller = launch { bound.sync.login(1, "https://hub.test", "a@b", "password") }267 entered.await(); parent.cancel(); testScheduler.runCurrent()268 release.complete(Unit); parent.join(); caller.join()269 assertTrue(database.syncPreferences().isEmpty())270 bound.sync.closeAndJoin()271 }272273 @Test fun lateMangayomiCredentialResponseCannotCommitAfterOwnerRetirement() = runTest {274 val database = InMemoryYokanDatabase(emptySnapshot())275 val prior = DbSyncPreference(syncId = 1, serverProvider = SyncServerProvider.Mangayomi)276 database.upsertSyncPreference(prior)277 val entered = CompletableDeferred<Unit>(); val release = CompletableDeferred<Unit>()278 val http = HttpService {279 entered.complete(Unit)280 withContext(NonCancellable) { release.await() }281 HttpResponse(statusCode = 200, body = """{"ok":true}""", setCookies = listOf("id=late-token; Path=/"))282 }283 val parent = SupervisorJob(); val scope = CoroutineScope(parent + StandardTestDispatcher(testScheduler))284 val mangayomi = MangayomiSyncService(database, http)285 val bound = ProfileSyncServices(A, mangayomi, FakeCloud(), scope)286 val caller = launch { bound.sync.login(1, "https://mangayomi.test", "user", "password") }287 entered.await(); parent.cancel(); testScheduler.runCurrent()288 release.complete(Unit); parent.join(); caller.join()289 assertEquals(prior, database.syncPreferences().single())290 bound.sync.closeAndJoin()291 }292293 @Test fun browserAttemptFromAnotherOwnerOrReplacementSessionIsRejected() = runTest {294 val http = HttpService { HttpResponse(200, """{"supported":["1"]}""") }295 val parentA = SupervisorJob(); val parentB = SupervisorJob()296 val scopeA = CoroutineScope(parentA + StandardTestDispatcher(testScheduler))297 val scopeB = CoroutineScope(parentB + StandardTestDispatcher(testScheduler))298 val databaseA = InMemoryYokanDatabase(emptySnapshot()); val databaseB = InMemoryYokanDatabase(emptySnapshot())299 val a = ProfileSyncServices(A, HubSyncService(databaseA, http, null, autoSync = false, scope = scopeA), FakeCloud(), scopeA)300 val b = ProfileSyncServices(B, HubSyncService(databaseB, http, null, autoSync = false, scope = scopeB), FakeCloud(), scopeB)301 val attempt = requireNotNull(a.sync.beginBrowserLogin(1, "https://hub.test"))302 val callback = "https://hub.test/login/done#state=${attempt.state}&device=${attempt.device}&token=token&email=a%40b"303 assertNull(b.sync.completeBrowserLogin(attempt, callback))304 assertTrue(databaseB.syncPreferences().isEmpty())305 assertTrue(requireNotNull(a.sync.completeBrowserLogin(attempt, callback)).success)306 assertEquals("token", databaseA.syncPreferences().single().authToken)307 a.sync.closeAndJoin(); parentA.cancelAndJoin()308 val replacement = ProfileSyncServices(A, HubSyncService(databaseB, http, null, autoSync = false, scope = scopeB), FakeCloud(), scopeB)309 assertNull(replacement.sync.completeBrowserLogin(attempt, callback))310 assertTrue(databaseB.syncPreferences().isEmpty())311 b.sync.closeAndJoin(); replacement.sync.closeAndJoin(); parentB.cancelAndJoin()312 }313314 private fun TestScope.fixture(id: ProfileId = A, immediate: Boolean = false): Fixture {315 val parent = SupervisorJob()316 val scope = CoroutineScope(parent + if (immediate) UnconfinedTestDispatcher(testScheduler) else StandardTestDispatcher(testScheduler))317 val router = FakeSync(); val cloud = FakeCloud()318 return Fixture(parent, scope, router, cloud, ProfileSyncServices(id, router, cloud, scope))319 }320321 private class Fixture(val parent: Job, val scope: CoroutineScope, val router: FakeSync, val cloud: FakeCloud, val bound: ProfileSyncServices) {322 suspend fun finish() { parent.cancelAndJoin(); bound.sync.closeAndJoin() }323 }324325 private open class FakeSync : SyncService {326 val calls = mutableListOf<String>()327 var action: suspend () -> Unit = {}328 var closes = 0329 var failClose = false330 override suspend fun login(syncId: Long, server: String, email: String, password: String): SyncLoginResult {331 calls += "login:$syncId:$server:$email:$password"; action(); return SyncLoginResult(true, "ok")332 }333 override fun beginBrowserLogin(syncId: Long, server: String): BrowserLoginAttempt {334 calls += "begin:$syncId:$server"; return BrowserLoginAttempt(syncId, server, "url", "device", "state")335 }336 override suspend fun completeBrowserLogin(attempt: BrowserLoginAttempt, loadedUrl: String): SyncLoginResult {337 calls += "complete:${attempt.syncId}:$loadedUrl"; action(); return SyncLoginResult(true, "ok")338 }339 override fun cancelBrowserLogin(attempt: BrowserLoginAttempt) { calls += "cancel:${attempt.syncId}" }340 override suspend fun logout(syncId: Long) { calls += "logout:$syncId"; action() }341 override suspend fun sync(syncId: Long, settings: DbSettings): SyncResult { calls += "sync:$syncId"; action(); return SyncResult(1, 2, true) }342 override suspend fun pushChanges(syncId: Long): SyncResult { calls += "push:$syncId"; action(); return SyncResult(1, 0, false) }343 override suspend fun pullChanges(syncId: Long): SyncResult { calls += "pull:$syncId"; action(); return SyncResult(0, 1, false) }344 override fun status(syncId: Long): SyncConnectionStatus { calls += "status:$syncId"; return SyncConnectionStatus(true, "email", "server", 1) }345 override fun close() { closes++; check(!failClose) }346 }347348 private class FakeCloud : FakeSync(), CloudBackupSyncService {349 override fun providers(): List<CloudProviderDescriptor> { calls += "providers"; return emptyList() }350 override fun isCloudPreference(syncPreference: DbSyncPreference?): Boolean { calls += "isCloud"; return true }351 override suspend fun connect(syncId: Long, providerId: String, accountLabel: String?, accessToken: String): SyncLoginResult {352 calls += "connect:$syncId:$providerId:$accountLabel:$accessToken"; action(); return SyncLoginResult(true, "ok")353 }354 override suspend fun uploadBackup(syncId: Long, options: BackupOptions): CloudBackupResult {355 calls += "upload:$syncId"; action(); return CloudBackupResult("cloud", "file", 1, 1, CloudObject("file", "file", 1, 1))356 }357 override suspend fun restoreLatestBackup(syncId: Long): CloudBackupRestoreResult {358 calls += "restore:$syncId"; action(); return CloudBackupRestoreResult("cloud", "file", RestorePreview(1, emptyList()))359 }360 }361362 private companion object {363 val A = ProfileId("p_11111111111111111111111111111111")364 val B = ProfileId("p_22222222222222222222222222222222")365 }366}367