TogetherAccountLifecycleTest.kt
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/together/TogetherAccountLifecycleTest.kt
1@file:OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class, io.ktor.utils.io.InternalAPI::class)23package eu.friedcutlet.yokan.services.together45import eu.friedcutlet.yokan.domain.ProfileId6import eu.friedcutlet.yokan.database.DbSyncPreference7import eu.friedcutlet.yokan.database.InMemoryYokanDatabase8import eu.friedcutlet.yokan.database.SyncServerProvider9import eu.friedcutlet.yokan.database.emptySnapshot10import eu.friedcutlet.yokan.services.http.ProfileTestEngine11import io.ktor.client.engine.HttpClientEngine12import io.ktor.client.engine.callContext13import io.ktor.client.request.HttpResponseData14import io.ktor.http.Headers15import io.ktor.http.HttpProtocolVersion16import io.ktor.http.HttpStatusCode17import io.ktor.util.date.GMTDate18import io.ktor.websocket.CloseReason19import io.ktor.websocket.DefaultWebSocketSession20import io.ktor.websocket.Frame21import io.ktor.websocket.WebSocketExtension22import io.ktor.websocket.readText23import kotlinx.coroutines.CompletableDeferred24import kotlinx.coroutines.CoroutineScope25import kotlinx.coroutines.Job26import kotlinx.coroutines.NonCancellable27import kotlinx.coroutines.SupervisorJob28import kotlinx.coroutines.awaitCancellation29import kotlinx.coroutines.cancel30import kotlinx.coroutines.cancelAndJoin31import kotlinx.coroutines.channels.Channel32import kotlinx.coroutines.launch33import kotlinx.coroutines.test.StandardTestDispatcher34import kotlinx.coroutines.test.TestScope35import kotlinx.coroutines.test.runTest36import kotlinx.coroutines.withContext37import kotlin.coroutines.CoroutineContext38import kotlin.test.Test39import kotlin.test.assertEquals40import kotlin.test.assertFalse41import kotlin.test.assertNotNull42import kotlin.test.assertNull43import kotlin.test.assertSame44import kotlin.test.assertTrue4546class TogetherAccountLifecycleTest {47 @Test fun tokenChangeRevokesRoomAndJoinsFinalizersBeforeReplacementAllocation() = runTest {48 val parent = SupervisorJob(); val dispatcher = StandardTestDispatcher(testScheduler)49 val database = database(); val release = CompletableDeferred<Unit>()50 val first = ProfileTestEngine(dispatcher) {51 try { awaitCancellation() } finally { withContext(NonCancellable) { release.await() } }52 }53 val second = ProfileTestEngine(dispatcher) { awaitCancellation() }; var allocations = 054 val scope = CoroutineScope(parent + dispatcher); val sibling = scope.launch { awaitCancellation() }55 val together = ProfileTogetherSession(ProfileId.Default, database, scope) {56 allocations++; if (allocations == 1) first else second57 }58 val old = assertNotNull(together.join(Hub, "OLD")); first.requests.receive()59 together.setDriving(true); together.setFollowing(false)60 database.upsertSyncPreference(Preference.copy(authToken = "new-token"))61 testScheduler.runCurrent()62 assertNull(together.client.value); assertFalse(together.driving.value); assertTrue(together.following.value)63 assertFalse(old.isAvailable); assertEquals(0, first.closeCalls)64 val joining = launch { together.join(assertNotNull(together.hubSession()), "NEW") }65 testScheduler.runCurrent()66 assertFalse(joining.isCompleted); assertEquals(1, allocations)67 assertTrue(parent.isActive); assertTrue(sibling.isActive)68 release.complete(Unit); joining.join()69 assertEquals(1, first.closeCalls); assertEquals("NEW", together.client.value?.code)70 assertEquals("Bearer new-token", second.requests.receive().headers["Authorization"])71 together.closeAndJoin(); parent.cancelAndJoin()72 }7374 @Test fun logoutProviderServerDeviceAndSelectionChangesEachRevokeTheRoom() = runTest {75 for (changed in listOf(76 Preference.copy(authToken = null),77 Preference.copy(serverProvider = SyncServerProvider.Mangayomi),78 Preference.copy(server = "https://other-hub.test"),79 Preference.copy(deviceId = "other-device"),80 )) {81 val fixture = fixture()82 val client = fixture.join()83 fixture.database.upsertSyncPreference(changed)84 testScheduler.runCurrent()85 assertNull(fixture.together.client.value); assertFalse(client.isAvailable)86 assertEquals(1, fixture.engine.closeCalls); assertTrue(fixture.parent.isActive)87 fixture.finish()88 }89 val fixture = fixture(); val client = fixture.join()90 fixture.database.replaceAll(fixture.database.snapshot().copy(syncPreferences = listOf(Preference.copy(syncId = 2))))91 testScheduler.runCurrent()92 assertNull(fixture.together.client.value); assertFalse(client.isAvailable)93 fixture.finish()94 }9596 @Test fun irrelevantSettingsAndNormalizedServerChangesKeepTheRoom() = runTest {97 val fixture = fixture(); val client = fixture.join()98 fixture.together.setDriving(true); fixture.together.setFollowing(false)99 fixture.database.updateSettings(fixture.database.settings().copy(userAgent = "new-agent"))100 fixture.database.upsertSyncPreference(Preference.copy(server = "https://hub.test/", email = "label@changed",101 syncOn = true, lastSyncManga = 999L, hubHead = 42L))102 testScheduler.runCurrent()103 assertSame(client, fixture.together.client.value); assertTrue(client.isAvailable)104 assertTrue(fixture.together.driving.value); assertFalse(fixture.together.following.value)105 assertEquals(0, fixture.engine.closeCalls)106 fixture.finish()107 }108109 @Test fun retainedClientCannotReconnectEvenWhenCredentialsAreRestored() = runTest {110 val fixture = fixture(); val old = fixture.join()111 fixture.database.upsertSyncPreference(Preference.copy(authToken = null))112 // A retained command checks the captured account without waiting for the watcher.113 old.chat("late"); assertFalse(old.isAvailable)114 fixture.database.upsertSyncPreference(Preference)115 old.connect(); testScheduler.runCurrent()116 assertTrue(fixture.engine.requests.tryReceive().isFailure); assertFalse(old.isAvailable)117 fixture.together.leave(); assertEquals(1, fixture.engine.closeCalls)118 fixture.finish()119 }120121 @Test fun accountChangeBeforeQueuedHandshakePreventsTransportDispatch() = runTest {122 val fixture = fixture()123 val client = assertNotNull(fixture.together.join(Hub, "ABC"))124 fixture.database.upsertSyncPreference(Preference.copy(authToken = "replacement"))125 testScheduler.runCurrent()126 assertTrue(fixture.engine.requests.tryReceive().isFailure)127 assertFalse(client.isAvailable); assertNull(fixture.together.client.value)128 assertEquals(1, fixture.engine.closeCalls)129 fixture.finish()130 }131132 @Test fun queuedCommandsAndIncomingMessagesCannotUseAChangedAccount() = runTest {133 val parent = SupervisorJob(); val dispatcher = StandardTestDispatcher(testScheduler); val database = database()134 val socketReady = CompletableDeferred<ControlledSocket>()135 val engine = ProfileTestEngine(dispatcher) {136 val context = callContext(); val socket = ControlledSocket(context)137 socketReady.complete(socket)138 HttpResponseData(HttpStatusCode.SwitchingProtocols, GMTDate(), Headers.Empty,139 HttpProtocolVersion.HTTP_1_1, socket, context)140 }141 val together = ProfileTogetherSession(ProfileId.Default, database, CoroutineScope(parent + dispatcher)) { engine }142 val client = assertNotNull(together.join(Hub, "ABC")); val socket = socketReady.await()143 socket.incoming.send(Frame.Text("""{"type":"hello","you":{"id":"me","role":"host"}}"""))144 testScheduler.runCurrent(); assertEquals(RoomConnection.Open, client.state.value.connection)145 client.chat("accepted"); testScheduler.runCurrent()146 assertTrue(socket.sent.any { it.contains("accepted") })147 client.chat("queued-late")148 socket.incoming.send(Frame.Text("""{"type":"error","msg":"late-message"}"""))149 database.upsertSyncPreference(Preference.copy(authToken = null))150 client.chat("late"); client.sendPage(5, 10)151 testScheduler.runCurrent()152 assertFalse(socket.sent.any { it.contains("queued-late") || it.contains("\"text\":\"late\"") || it.contains("\"page\":5") })153 assertNull(client.state.value.lastError); assertNull(together.client.value)154 assertFalse(client.isAvailable); assertEquals(1, engine.closeCalls); assertTrue(parent.isActive)155 together.closeAndJoin(); parent.cancelAndJoin()156 }157158 @Test fun failedRevocationCleanupIsRetriedBeforeAnotherRoomIsAllocated() = runTest {159 val parent = SupervisorJob(); val dispatcher = StandardTestDispatcher(testScheduler); val database = database()160 val first = ProfileTestEngine(dispatcher) { awaitCancellation() }161 val second = ProfileTestEngine(dispatcher) { awaitCancellation() }162 var fail = true; var attempts = 0; var allocations = 0163 val failing = object : HttpClientEngine by first {164 override fun close() { attempts++; check(!fail) { "Native cleanup failed" }; first.close() }165 }166 val together = ProfileTogetherSession(ProfileId.Default, database, CoroutineScope(parent + dispatcher)) {167 allocations++; if (allocations == 1) failing else second168 }169 together.join(Hub, "OLD"); first.requests.receive()170 database.upsertSyncPreference(Preference.copy(authToken = "replacement"))171 testScheduler.runCurrent()172 assertNull(together.client.value); assertEquals(1, attempts); assertEquals(1, allocations)173 assertTrue(parent.isActive)174 fail = false175 assertNotNull(together.join(assertNotNull(together.hubSession()), "NEW"))176 assertEquals(2, attempts); assertEquals(2, allocations); assertEquals(1, first.closeCalls)177 together.closeAndJoin(); parent.cancelAndJoin()178 }179180 @Test fun queuedAccountWatcherCannotRevokeAReplacementForTheLatestAccount() = runTest {181 val parent = SupervisorJob(); val dispatcher = StandardTestDispatcher(testScheduler); val database = database()182 val release = CompletableDeferred<Unit>()183 val first = ProfileTestEngine(dispatcher) {184 try { awaitCancellation() } finally { withContext(NonCancellable) { release.await() } }185 }186 val second = ProfileTestEngine(dispatcher) { awaitCancellation() }; var allocations = 0187 val together = ProfileTogetherSession(ProfileId.Default, database, CoroutineScope(parent + dispatcher)) {188 allocations++; if (allocations == 1) first else second189 }190 together.join(Hub, "OLD"); first.requests.receive()191 database.upsertSyncPreference(Preference.copy(authToken = "intermediate"))192 testScheduler.runCurrent()193 database.upsertSyncPreference(Preference.copy(authToken = "latest"))194 val replacing = launch { together.join(assertNotNull(together.hubSession()), "LATEST") }195 testScheduler.runCurrent(); assertEquals(1, allocations)196 release.complete(Unit); replacing.join(); testScheduler.runCurrent()197 val current = assertNotNull(together.client.value)198 assertEquals("LATEST", current.code); assertTrue(current.isAvailable)199 assertEquals("Bearer latest", second.requests.receive().headers["Authorization"])200 assertEquals(0, second.closeCalls); assertTrue(parent.isActive)201 together.closeAndJoin(); parent.cancelAndJoin()202 }203204 @Test fun changingOneAccountDoesNotRevokeAnotherOwner() = runTest {205 val left = fixture(); val right = fixture()206 val a = left.join(); val b = right.join()207 left.database.upsertSyncPreference(Preference.copy(authToken = null))208 testScheduler.runCurrent()209 assertFalse(a.isAvailable); assertNull(left.together.client.value)210 assertSame(b, right.together.client.value); assertTrue(b.isAvailable); assertEquals(0, right.engine.closeCalls)211 left.finish(); right.finish()212 }213214 private fun TestScope.fixture(): Fixture {215 val parent = SupervisorJob(); val dispatcher = StandardTestDispatcher(testScheduler)216 val engine = ProfileTestEngine(dispatcher) { awaitCancellation() }217 val database = database()218 return Fixture(parent, engine, database,219 ProfileTogetherSession(ProfileId.Default, database, CoroutineScope(parent + dispatcher)) { engine })220 }221222 private class Fixture(val parent: Job, val engine: ProfileTestEngine, val database: InMemoryYokanDatabase,223 val together: ProfileTogetherSession) {224 suspend fun join(): RoomClient = assertNotNull(together.join(Hub, "ABC")).also { engine.requests.receive() }225 suspend fun finish() { together.closeAndJoin(); parent.cancelAndJoin() }226 }227228 /** A real Ktor upgrade with controlled frame channels instead of a remote socket. */229 private class ControlledSocket(context: CoroutineContext) : DefaultWebSocketSession {230 override val coroutineContext = context + Job(context[Job])231 override var masking = false232 override var maxFrameSize = Long.MAX_VALUE233 override var pingIntervalMillis = -1L234 override var timeoutMillis = 15_000L235 override val incoming = Channel<Frame>(Channel.UNLIMITED)236 override val outgoing = Channel<Frame>(Channel.UNLIMITED)237 override val extensions: List<WebSocketExtension<*>> = emptyList()238 override val closeReason = CompletableDeferred<CloseReason?>()239 val sent = mutableListOf<String>()240 init {241 CoroutineScope(coroutineContext).launch {242 try { awaitCancellation() }243 finally { incoming.cancel(); outgoing.cancel(); closeReason.complete(null) }244 }245 }246 override fun start(negotiatedExtensions: List<WebSocketExtension<*>>) = Unit247 override suspend fun send(frame: Frame) { if (frame is Frame.Text) sent += frame.readText(); outgoing.send(frame) }248 override suspend fun flush() = Unit249 @Deprecated("Overrides deprecated Ktor API")250 override fun terminate() { coroutineContext.cancel() }251 }252253 private fun database() = InMemoryYokanDatabase(emptySnapshot()).also { it.upsertSyncPreference(Preference) }254 private companion object {255 val Preference = DbSyncPreference(syncId = 1, server = "https://hub.test", authToken = "owner-token", deviceId = "owner-device")256 val Hub = HubSession("https://hub.test", "owner-token", "owner-device")257 }258}259