ProfileTogetherSessionTest.kt
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/together/ProfileTogetherSessionTest.kt
1@file:OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::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 kotlinx.coroutines.CancellationException12import kotlinx.coroutines.CompletableDeferred13import kotlinx.coroutines.CoroutineScope14import kotlinx.coroutines.NonCancellable15import kotlinx.coroutines.SupervisorJob16import kotlinx.coroutines.awaitCancellation17import kotlinx.coroutines.cancel18import kotlinx.coroutines.cancelAndJoin19import kotlinx.coroutines.currentCoroutineContext20import kotlinx.coroutines.launch21import kotlinx.coroutines.test.StandardTestDispatcher22import kotlinx.coroutines.test.UnconfinedTestDispatcher23import kotlinx.coroutines.test.runTest24import kotlinx.coroutines.withContext25import kotlin.test.Test26import kotlin.test.assertEquals27import kotlin.test.assertFailsWith28import kotlin.test.assertFalse29import kotlin.test.assertNotNull30import kotlin.test.assertNull31import kotlin.test.assertSame32import kotlin.test.assertTrue3334class ProfileTogetherSessionTest {35 @Test fun connectionUsesCapturedCredentialsAndLeavePreservesOwner() = runTest {36 val parent = SupervisorJob()37 val engine = ProfileTestEngine(StandardTestDispatcher(testScheduler)) { awaitCancellation() }38 val together = ProfileTogetherSession(ProfileId.Default, database(), CoroutineScope(parent + StandardTestDispatcher(testScheduler))) { engine }39 val client = assertNotNull(together.join(Hub, "abc"))40 val request = engine.requests.receive()41 assertEquals("Bearer owner-token", request.headers["Authorization"])42 assertEquals("owner-device", request.headers["X-Device"])43 assertTrue(request.url.toString().endsWith("/rooms/ABC/ws"))44 assertEquals("ABC", client.code)45 together.leave(); assertNull(together.client.value); assertEquals(1, engine.closeCalls)46 assertTrue(parent.isActive)47 client.connect(); testScheduler.runCurrent(); assertTrue(engine.requests.tryReceive().isFailure)48 together.closeAndJoin(); parent.cancelAndJoin()49 }5051 @Test fun replacementJoinsOldSocketBeforeAllocatingOrPublishingAnother() = runTest {52 val parent = SupervisorJob(); val release = CompletableDeferred<Unit>()53 val first = ProfileTestEngine(StandardTestDispatcher(testScheduler)) {54 try { awaitCancellation() } finally { withContext(NonCancellable) { release.await() } }55 }56 val second = ProfileTestEngine(StandardTestDispatcher(testScheduler)) { awaitCancellation() }57 var allocations = 058 val together = ProfileTogetherSession(ProfileId.Default, database(), CoroutineScope(parent + StandardTestDispatcher(testScheduler))) {59 allocations++; if (allocations == 1) first else second60 }61 together.join(Hub, "OLD"); first.requests.receive()62 val replacing = launch { together.join(Hub, "NEW") }63 testScheduler.runCurrent()64 assertFalse(replacing.isCompleted); assertEquals(1, allocations); assertEquals(0, first.closeCalls)65 assertNull(together.client.value)66 release.complete(Unit); replacing.join()67 assertEquals(1, first.closeCalls); assertEquals("NEW", together.client.value?.code)68 together.closeAndJoin(); parent.cancelAndJoin(); assertEquals(1, second.closeCalls)69 }7071 @Test fun retirementJoinsSocketFinalizerThenReleasesTransportAndState() = runTest {72 val parent = SupervisorJob(); val release = CompletableDeferred<Unit>(); var finalized = false73 val engine = ProfileTestEngine(StandardTestDispatcher(testScheduler)) {74 try { awaitCancellation() } finally { withContext(NonCancellable) { release.await(); finalized = true } }75 }76 val together = ProfileTogetherSession(ProfileId.Default, database(), CoroutineScope(parent + StandardTestDispatcher(testScheduler))) { engine }77 together.join(Hub, "ABC"); engine.requests.receive(); together.setDriving(true)78 val retiring = launch { parent.cancelAndJoin(); together.closeAndJoin() }79 testScheduler.runCurrent(); assertFalse(retiring.isCompleted); assertEquals(0, engine.closeCalls)80 assertNull(together.hubSession())81 release.complete(Unit); retiring.join()82 assertTrue(finalized); assertNull(together.client.value); assertFalse(together.driving.value)83 assertEquals(1, engine.closeCalls); together.closeAndJoin(); assertEquals(1, engine.closeCalls)84 }8586 @Test fun staleAccountOrOtherSyncProviderCannotAllocateARoomTransport() = runTest {87 val parent = SupervisorJob(); val db = database(); var allocations = 088 val together = ProfileTogetherSession(ProfileId.Default, db, CoroutineScope(parent + StandardTestDispatcher(testScheduler))) {89 allocations++; error("Stale credential transport")90 }91 db.upsertSyncPreference(Preference.copy(authToken = "replacement"))92 assertNull(together.join(Hub, "ABC"))93 db.upsertSyncPreference(Preference.copy(serverProvider = SyncServerProvider.Mangayomi))94 assertNull(together.hubSession()); assertNull(together.join(Hub, "ABC")); assertEquals(0, allocations)95 together.closeAndJoin(); parent.cancelAndJoin()96 }9798 @Test fun expiredAndRetiredCallsCannotReadCredentialsOrDispatch() = runTest {99 val parent = SupervisorJob(); var allocations = 0100 val together = ProfileTogetherSession(ProfileId.Default, database(), CoroutineScope(parent + UnconfinedTestDispatcher(testScheduler))) {101 allocations++; error("Expired transport")102 }103 val caller = launch {104 currentCoroutineContext().cancel()105 assertFailsWith<CancellationException> { together.join(Hub, "ABC") }106 }107 caller.join(); assertEquals(0, allocations); assertTrue(parent.isActive)108 parent.cancelAndJoin(); together.closeAndJoin()109 assertNull(together.hubSession())110 assertFailsWith<CancellationException> { together.join(Hub, "ABC") }111 together.setDriving(true); together.setFollowing(false)112 assertFalse(together.driving.value); assertTrue(together.following.value)113 }114115 @Test fun callerExpiryDuringReplacementJoinsCleanupAndDoesNotRetireOwner() = runTest {116 val parent = SupervisorJob(); val release = CompletableDeferred<Unit>(); var allocations = 0117 val first = ProfileTestEngine(StandardTestDispatcher(testScheduler)) {118 try { awaitCancellation() } finally { withContext(NonCancellable) { release.await() } }119 }120 val second = ProfileTestEngine(StandardTestDispatcher(testScheduler)) { awaitCancellation() }121 val together = ProfileTogetherSession(ProfileId.Default, database(), CoroutineScope(parent + StandardTestDispatcher(testScheduler))) {122 allocations++; if (allocations == 1) first else second123 }124 together.join(Hub, "OLD"); first.requests.receive()125 val caller = launch { together.join(Hub, "ABANDONED") }126 testScheduler.runCurrent(); caller.cancel(); testScheduler.runCurrent()127 assertFalse(caller.isCompleted); assertTrue(parent.isActive); assertEquals(1, allocations)128 release.complete(Unit); caller.join(); assertNull(together.client.value)129 assertNotNull(together.join(Hub, "RETRY")); assertEquals(2, allocations)130 together.closeAndJoin(); parent.cancelAndJoin()131 }132133 @Test fun independentOwnersRetainTheirRoomStateAndCleanupTargets() = runTest {134 val a = SupervisorJob(); val b = SupervisorJob()135 val engineA = ProfileTestEngine(StandardTestDispatcher(testScheduler)) { awaitCancellation() }136 val engineB = ProfileTestEngine(StandardTestDispatcher(testScheduler)) { awaitCancellation() }137 val idA = ProfileId("p_11111111111111111111111111111111")138 val idB = ProfileId("p_22222222222222222222222222222222")139 val first = ProfileTogetherSession(idA, database(), CoroutineScope(a + StandardTestDispatcher(testScheduler))) { assertEquals(idA, it); engineA }140 val second = ProfileTogetherSession(idB, database(), CoroutineScope(b + StandardTestDispatcher(testScheduler))) { assertEquals(idB, it); engineB }141 first.join(Hub, "AAA"); val currentB = second.join(Hub, "BBB")142 first.setFollowing(false); second.setDriving(true)143 a.cancelAndJoin(); first.closeAndJoin()144 assertSame(currentB, second.client.value); assertTrue(second.driving.value); assertTrue(second.following.value)145 assertEquals(1, engineA.closeCalls); assertEquals(0, engineB.closeCalls); assertTrue(b.isActive)146 second.closeAndJoin(); b.cancelAndJoin()147 }148149 private fun database() = InMemoryYokanDatabase(emptySnapshot()).also { it.upsertSyncPreference(Preference) }150 private companion object {151 val Preference = DbSyncPreference(syncId = 1, server = "https://hub.test", authToken = "owner-token", deviceId = "owner-device")152 val Hub = HubSession("https://hub.test", "owner-token", "owner-device")153 }154}155