@file:OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class, io.ktor.utils.io.InternalAPI::class) package eu.friedcutlet.yokan.services.together import eu.friedcutlet.yokan.domain.ProfileId 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.http.ProfileTestEngine import io.ktor.client.engine.HttpClientEngine import io.ktor.client.engine.callContext import io.ktor.client.request.HttpResponseData import io.ktor.http.Headers import io.ktor.http.HttpProtocolVersion import io.ktor.http.HttpStatusCode import io.ktor.util.date.GMTDate import io.ktor.websocket.CloseReason import io.ktor.websocket.DefaultWebSocketSession import io.ktor.websocket.Frame import io.ktor.websocket.WebSocketExtension import io.ktor.websocket.readText 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.channels.Channel import kotlinx.coroutines.launch import kotlinx.coroutines.test.StandardTestDispatcher import kotlinx.coroutines.test.TestScope import kotlinx.coroutines.test.runTest import kotlinx.coroutines.withContext import kotlin.coroutines.CoroutineContext import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertNotNull import kotlin.test.assertNull import kotlin.test.assertSame import kotlin.test.assertTrue class TogetherAccountLifecycleTest { @Test fun tokenChangeRevokesRoomAndJoinsFinalizersBeforeReplacementAllocation() = runTest { val parent = SupervisorJob(); val dispatcher = StandardTestDispatcher(testScheduler) val database = database(); val release = CompletableDeferred() val first = ProfileTestEngine(dispatcher) { try { awaitCancellation() } finally { withContext(NonCancellable) { release.await() } } } val second = ProfileTestEngine(dispatcher) { awaitCancellation() }; var allocations = 0 val scope = CoroutineScope(parent + dispatcher); val sibling = scope.launch { awaitCancellation() } val together = ProfileTogetherSession(ProfileId.Default, database, scope) { allocations++; if (allocations == 1) first else second } val old = assertNotNull(together.join(Hub, "OLD")); first.requests.receive() together.setDriving(true); together.setFollowing(false) database.upsertSyncPreference(Preference.copy(authToken = "new-token")) testScheduler.runCurrent() assertNull(together.client.value); assertFalse(together.driving.value); assertTrue(together.following.value) assertFalse(old.isAvailable); assertEquals(0, first.closeCalls) val joining = launch { together.join(assertNotNull(together.hubSession()), "NEW") } testScheduler.runCurrent() assertFalse(joining.isCompleted); assertEquals(1, allocations) assertTrue(parent.isActive); assertTrue(sibling.isActive) release.complete(Unit); joining.join() assertEquals(1, first.closeCalls); assertEquals("NEW", together.client.value?.code) assertEquals("Bearer new-token", second.requests.receive().headers["Authorization"]) together.closeAndJoin(); parent.cancelAndJoin() } @Test fun logoutProviderServerDeviceAndSelectionChangesEachRevokeTheRoom() = runTest { for (changed in listOf( Preference.copy(authToken = null), Preference.copy(serverProvider = SyncServerProvider.Mangayomi), Preference.copy(server = "https://other-hub.test"), Preference.copy(deviceId = "other-device"), )) { val fixture = fixture() val client = fixture.join() fixture.database.upsertSyncPreference(changed) testScheduler.runCurrent() assertNull(fixture.together.client.value); assertFalse(client.isAvailable) assertEquals(1, fixture.engine.closeCalls); assertTrue(fixture.parent.isActive) fixture.finish() } val fixture = fixture(); val client = fixture.join() fixture.database.replaceAll(fixture.database.snapshot().copy(syncPreferences = listOf(Preference.copy(syncId = 2)))) testScheduler.runCurrent() assertNull(fixture.together.client.value); assertFalse(client.isAvailable) fixture.finish() } @Test fun irrelevantSettingsAndNormalizedServerChangesKeepTheRoom() = runTest { val fixture = fixture(); val client = fixture.join() fixture.together.setDriving(true); fixture.together.setFollowing(false) fixture.database.updateSettings(fixture.database.settings().copy(userAgent = "new-agent")) fixture.database.upsertSyncPreference(Preference.copy(server = "https://hub.test/", email = "label@changed", syncOn = true, lastSyncManga = 999L, hubHead = 42L)) testScheduler.runCurrent() assertSame(client, fixture.together.client.value); assertTrue(client.isAvailable) assertTrue(fixture.together.driving.value); assertFalse(fixture.together.following.value) assertEquals(0, fixture.engine.closeCalls) fixture.finish() } @Test fun retainedClientCannotReconnectEvenWhenCredentialsAreRestored() = runTest { val fixture = fixture(); val old = fixture.join() fixture.database.upsertSyncPreference(Preference.copy(authToken = null)) // A retained command checks the captured account without waiting for the watcher. old.chat("late"); assertFalse(old.isAvailable) fixture.database.upsertSyncPreference(Preference) old.connect(); testScheduler.runCurrent() assertTrue(fixture.engine.requests.tryReceive().isFailure); assertFalse(old.isAvailable) fixture.together.leave(); assertEquals(1, fixture.engine.closeCalls) fixture.finish() } @Test fun accountChangeBeforeQueuedHandshakePreventsTransportDispatch() = runTest { val fixture = fixture() val client = assertNotNull(fixture.together.join(Hub, "ABC")) fixture.database.upsertSyncPreference(Preference.copy(authToken = "replacement")) testScheduler.runCurrent() assertTrue(fixture.engine.requests.tryReceive().isFailure) assertFalse(client.isAvailable); assertNull(fixture.together.client.value) assertEquals(1, fixture.engine.closeCalls) fixture.finish() } @Test fun queuedCommandsAndIncomingMessagesCannotUseAChangedAccount() = runTest { val parent = SupervisorJob(); val dispatcher = StandardTestDispatcher(testScheduler); val database = database() val socketReady = CompletableDeferred() val engine = ProfileTestEngine(dispatcher) { val context = callContext(); val socket = ControlledSocket(context) socketReady.complete(socket) HttpResponseData(HttpStatusCode.SwitchingProtocols, GMTDate(), Headers.Empty, HttpProtocolVersion.HTTP_1_1, socket, context) } val together = ProfileTogetherSession(ProfileId.Default, database, CoroutineScope(parent + dispatcher)) { engine } val client = assertNotNull(together.join(Hub, "ABC")); val socket = socketReady.await() socket.incoming.send(Frame.Text("""{"type":"hello","you":{"id":"me","role":"host"}}""")) testScheduler.runCurrent(); assertEquals(RoomConnection.Open, client.state.value.connection) client.chat("accepted"); testScheduler.runCurrent() assertTrue(socket.sent.any { it.contains("accepted") }) client.chat("queued-late") socket.incoming.send(Frame.Text("""{"type":"error","msg":"late-message"}""")) database.upsertSyncPreference(Preference.copy(authToken = null)) client.chat("late"); client.sendPage(5, 10) testScheduler.runCurrent() assertFalse(socket.sent.any { it.contains("queued-late") || it.contains("\"text\":\"late\"") || it.contains("\"page\":5") }) assertNull(client.state.value.lastError); assertNull(together.client.value) assertFalse(client.isAvailable); assertEquals(1, engine.closeCalls); assertTrue(parent.isActive) together.closeAndJoin(); parent.cancelAndJoin() } @Test fun failedRevocationCleanupIsRetriedBeforeAnotherRoomIsAllocated() = runTest { val parent = SupervisorJob(); val dispatcher = StandardTestDispatcher(testScheduler); val database = database() val first = ProfileTestEngine(dispatcher) { awaitCancellation() } val second = ProfileTestEngine(dispatcher) { awaitCancellation() } var fail = true; var attempts = 0; var allocations = 0 val failing = object : HttpClientEngine by first { override fun close() { attempts++; check(!fail) { "Native cleanup failed" }; first.close() } } val together = ProfileTogetherSession(ProfileId.Default, database, CoroutineScope(parent + dispatcher)) { allocations++; if (allocations == 1) failing else second } together.join(Hub, "OLD"); first.requests.receive() database.upsertSyncPreference(Preference.copy(authToken = "replacement")) testScheduler.runCurrent() assertNull(together.client.value); assertEquals(1, attempts); assertEquals(1, allocations) assertTrue(parent.isActive) fail = false assertNotNull(together.join(assertNotNull(together.hubSession()), "NEW")) assertEquals(2, attempts); assertEquals(2, allocations); assertEquals(1, first.closeCalls) together.closeAndJoin(); parent.cancelAndJoin() } @Test fun queuedAccountWatcherCannotRevokeAReplacementForTheLatestAccount() = runTest { val parent = SupervisorJob(); val dispatcher = StandardTestDispatcher(testScheduler); val database = database() val release = CompletableDeferred() val first = ProfileTestEngine(dispatcher) { try { awaitCancellation() } finally { withContext(NonCancellable) { release.await() } } } val second = ProfileTestEngine(dispatcher) { awaitCancellation() }; var allocations = 0 val together = ProfileTogetherSession(ProfileId.Default, database, CoroutineScope(parent + dispatcher)) { allocations++; if (allocations == 1) first else second } together.join(Hub, "OLD"); first.requests.receive() database.upsertSyncPreference(Preference.copy(authToken = "intermediate")) testScheduler.runCurrent() database.upsertSyncPreference(Preference.copy(authToken = "latest")) val replacing = launch { together.join(assertNotNull(together.hubSession()), "LATEST") } testScheduler.runCurrent(); assertEquals(1, allocations) release.complete(Unit); replacing.join(); testScheduler.runCurrent() val current = assertNotNull(together.client.value) assertEquals("LATEST", current.code); assertTrue(current.isAvailable) assertEquals("Bearer latest", second.requests.receive().headers["Authorization"]) assertEquals(0, second.closeCalls); assertTrue(parent.isActive) together.closeAndJoin(); parent.cancelAndJoin() } @Test fun changingOneAccountDoesNotRevokeAnotherOwner() = runTest { val left = fixture(); val right = fixture() val a = left.join(); val b = right.join() left.database.upsertSyncPreference(Preference.copy(authToken = null)) testScheduler.runCurrent() assertFalse(a.isAvailable); assertNull(left.together.client.value) assertSame(b, right.together.client.value); assertTrue(b.isAvailable); assertEquals(0, right.engine.closeCalls) left.finish(); right.finish() } private fun TestScope.fixture(): Fixture { val parent = SupervisorJob(); val dispatcher = StandardTestDispatcher(testScheduler) val engine = ProfileTestEngine(dispatcher) { awaitCancellation() } val database = database() return Fixture(parent, engine, database, ProfileTogetherSession(ProfileId.Default, database, CoroutineScope(parent + dispatcher)) { engine }) } private class Fixture(val parent: Job, val engine: ProfileTestEngine, val database: InMemoryYokanDatabase, val together: ProfileTogetherSession) { suspend fun join(): RoomClient = assertNotNull(together.join(Hub, "ABC")).also { engine.requests.receive() } suspend fun finish() { together.closeAndJoin(); parent.cancelAndJoin() } } /** A real Ktor upgrade with controlled frame channels instead of a remote socket. */ private class ControlledSocket(context: CoroutineContext) : DefaultWebSocketSession { override val coroutineContext = context + Job(context[Job]) override var masking = false override var maxFrameSize = Long.MAX_VALUE override var pingIntervalMillis = -1L override var timeoutMillis = 15_000L override val incoming = Channel(Channel.UNLIMITED) override val outgoing = Channel(Channel.UNLIMITED) override val extensions: List> = emptyList() override val closeReason = CompletableDeferred() val sent = mutableListOf() init { CoroutineScope(coroutineContext).launch { try { awaitCancellation() } finally { incoming.cancel(); outgoing.cancel(); closeReason.complete(null) } } } override fun start(negotiatedExtensions: List>) = Unit override suspend fun send(frame: Frame) { if (frame is Frame.Text) sent += frame.readText(); outgoing.send(frame) } override suspend fun flush() = Unit @Deprecated("Overrides deprecated Ktor API") override fun terminate() { coroutineContext.cancel() } } private fun database() = InMemoryYokanDatabase(emptySnapshot()).also { it.upsertSyncPreference(Preference) } private companion object { val Preference = DbSyncPreference(syncId = 1, server = "https://hub.test", authToken = "owner-token", deviceId = "owner-device") val Hub = HubSession("https://hub.test", "owner-token", "owner-device") } }