package eu.friedcutlet.yokan.services.sync import eu.friedcutlet.yokan.domain.ProfileId import eu.friedcutlet.yokan.app.profiles.ProfileRegistry import eu.friedcutlet.yokan.app.profiles.ProfileRegistryPersistence import eu.friedcutlet.yokan.database.DbSettings import eu.friedcutlet.yokan.database.DbSyncPreference import eu.friedcutlet.yokan.database.InMemoryYokanDatabase import eu.friedcutlet.yokan.database.emptySnapshot import eu.friedcutlet.yokan.services.http.HttpRequest import eu.friedcutlet.yokan.services.http.HttpResponse import eu.friedcutlet.yokan.services.http.HttpService import kotlinx.coroutines.test.TestScope import kotlinx.coroutines.test.runTest import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertNull import kotlin.test.assertTrue class SyncAccountLeasesTest { private class MemoryRegistry : ProfileRegistryPersistence { var raw: String? = null override suspend fun read() = raw override suspend fun compareAndSet(expected: String?, replacement: String) = (raw == expected).also { if (it) raw = replacement } } /** Answers the version probe and login; everything else is an unexpected network call. */ private class FakeHub : HttpService { val requests = mutableListOf() override suspend fun request(request: HttpRequest): HttpResponse { requests += request return when { request.url.endsWith("/api/version") -> HttpResponse(200, """{"supported":["1"]}""") request.url.endsWith("/api/v1/login") -> HttpResponse(200, """{"token":"tok"}""") else -> HttpResponse(500, "") } } } private suspend fun registry() = ProfileRegistry(MemoryRegistry()).apply { refresh(); beginCreate("Reader", A); markReady(A); beginCreate("Other", B); markReady(B) } private fun TestScope.hub(db: InMemoryYokanDatabase, http: HttpService, leases: SyncAccountLeases) = HubSyncService(db, http, webSocketEngine = null, autoSync = false, scope = backgroundScope, leases = leases) @Test fun leasedAccountRejectsOtherProfilesLoginWithoutWritingCredentials() = runTest { val registry = registry() val dbA = InMemoryYokanDatabase(emptySnapshot()); val dbB = InMemoryYokanDatabase(emptySnapshot()) assertTrue(hub(dbA, FakeHub(), registry.syncLeases(A)).login(1, "hub.test", "a@b", "pw").success) // Server/account spelling differences still name the same remote library. val result = hub(dbB, FakeHub(), registry.syncLeases(B)).login(1, "https://HUB.test/", " A@B ", "pw") assertFalse(result.success) assertEquals("This sync account is already connected to profile ‘Reader’. Log out there first.", result.message) assertTrue(dbB.syncPreferences().isEmpty()) hub(dbA, FakeHub(), registry.syncLeases(A)).logout(1) assertTrue(hub(dbB, FakeHub(), registry.syncLeases(B)).login(1, "https://HUB.test/", " A@B ", "pw").success) assertEquals("tok", dbB.syncPreferences().single().authToken) } @Test fun conflictingExistingLoginDoesNotSync() = runTest { val registry = registry() registry.claimSyncLease(A, "hub|https://hub.test|a@b") // e.g. a login restored into B from a backup of A. val dbB = InMemoryYokanDatabase(emptySnapshot()) dbB.upsertSyncPreference(DbSyncPreference(syncId = 1, server = "https://hub.test", email = "a@b", authToken = "tok", syncOn = true)) val http = FakeHub() val result = hub(dbB, http, registry.syncLeases(B)).sync(1, DbSettings()) assertEquals(listOf("This sync account is already connected to profile ‘Reader’. Log out there first."), result.errors) assertTrue(http.requests.isEmpty()) assertEquals("tok", dbB.syncPreferences().single().authToken, "the conflicting login is kept, not deleted") } @Test fun rejectedCommitReturnsTheLeaseToThePreviousAccount() = runTest { val registry = registry() val previous = DbSyncPreference(server = "https://hub.test", email = "old", authToken = "tok") registry.claimSyncLease(A, syncLeaseKey(previous)!!) val failure = registry.syncLeases(A).commitClaimed(previous, previous.copy(email = "new")) { false } assertEquals("Sync configuration changed during login; try again.", failure) assertEquals(listOf("hub|https://hub.test|old"), registry.refresh().syncLeases.map { it.key }) assertNull(registry.syncLeases(A).commitClaimed(null, previous.copy(email = "new")) { true }) assertEquals(listOf("hub|https://hub.test|new"), registry.refresh().syncLeases.map { it.key }) } private companion object { val A = ProfileId("p_${"a".repeat(32)}") val B = ProfileId("p_${"b".repeat(32)}") } }