@file:OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::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 kotlinx.coroutines.CancellationException import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.awaitCancellation import kotlinx.coroutines.cancel import kotlinx.coroutines.cancelAndJoin import kotlinx.coroutines.currentCoroutineContext import kotlinx.coroutines.launch import kotlinx.coroutines.test.StandardTestDispatcher import kotlinx.coroutines.test.UnconfinedTestDispatcher import kotlinx.coroutines.test.runTest import kotlinx.coroutines.withContext import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFailsWith import kotlin.test.assertFalse import kotlin.test.assertNotNull import kotlin.test.assertNull import kotlin.test.assertSame import kotlin.test.assertTrue class ProfileTogetherSessionTest { @Test fun connectionUsesCapturedCredentialsAndLeavePreservesOwner() = runTest { val parent = SupervisorJob() val engine = ProfileTestEngine(StandardTestDispatcher(testScheduler)) { awaitCancellation() } val together = ProfileTogetherSession(ProfileId.Default, database(), CoroutineScope(parent + StandardTestDispatcher(testScheduler))) { engine } val client = assertNotNull(together.join(Hub, "abc")) val request = engine.requests.receive() assertEquals("Bearer owner-token", request.headers["Authorization"]) assertEquals("owner-device", request.headers["X-Device"]) assertTrue(request.url.toString().endsWith("/rooms/ABC/ws")) assertEquals("ABC", client.code) together.leave(); assertNull(together.client.value); assertEquals(1, engine.closeCalls) assertTrue(parent.isActive) client.connect(); testScheduler.runCurrent(); assertTrue(engine.requests.tryReceive().isFailure) together.closeAndJoin(); parent.cancelAndJoin() } @Test fun replacementJoinsOldSocketBeforeAllocatingOrPublishingAnother() = runTest { val parent = SupervisorJob(); val release = CompletableDeferred() val first = ProfileTestEngine(StandardTestDispatcher(testScheduler)) { try { awaitCancellation() } finally { withContext(NonCancellable) { release.await() } } } val second = ProfileTestEngine(StandardTestDispatcher(testScheduler)) { awaitCancellation() } var allocations = 0 val together = ProfileTogetherSession(ProfileId.Default, database(), CoroutineScope(parent + StandardTestDispatcher(testScheduler))) { allocations++; if (allocations == 1) first else second } together.join(Hub, "OLD"); first.requests.receive() val replacing = launch { together.join(Hub, "NEW") } testScheduler.runCurrent() assertFalse(replacing.isCompleted); assertEquals(1, allocations); assertEquals(0, first.closeCalls) assertNull(together.client.value) release.complete(Unit); replacing.join() assertEquals(1, first.closeCalls); assertEquals("NEW", together.client.value?.code) together.closeAndJoin(); parent.cancelAndJoin(); assertEquals(1, second.closeCalls) } @Test fun retirementJoinsSocketFinalizerThenReleasesTransportAndState() = runTest { val parent = SupervisorJob(); val release = CompletableDeferred(); var finalized = false val engine = ProfileTestEngine(StandardTestDispatcher(testScheduler)) { try { awaitCancellation() } finally { withContext(NonCancellable) { release.await(); finalized = true } } } val together = ProfileTogetherSession(ProfileId.Default, database(), CoroutineScope(parent + StandardTestDispatcher(testScheduler))) { engine } together.join(Hub, "ABC"); engine.requests.receive(); together.setDriving(true) val retiring = launch { parent.cancelAndJoin(); together.closeAndJoin() } testScheduler.runCurrent(); assertFalse(retiring.isCompleted); assertEquals(0, engine.closeCalls) assertNull(together.hubSession()) release.complete(Unit); retiring.join() assertTrue(finalized); assertNull(together.client.value); assertFalse(together.driving.value) assertEquals(1, engine.closeCalls); together.closeAndJoin(); assertEquals(1, engine.closeCalls) } @Test fun staleAccountOrOtherSyncProviderCannotAllocateARoomTransport() = runTest { val parent = SupervisorJob(); val db = database(); var allocations = 0 val together = ProfileTogetherSession(ProfileId.Default, db, CoroutineScope(parent + StandardTestDispatcher(testScheduler))) { allocations++; error("Stale credential transport") } db.upsertSyncPreference(Preference.copy(authToken = "replacement")) assertNull(together.join(Hub, "ABC")) db.upsertSyncPreference(Preference.copy(serverProvider = SyncServerProvider.Mangayomi)) assertNull(together.hubSession()); assertNull(together.join(Hub, "ABC")); assertEquals(0, allocations) together.closeAndJoin(); parent.cancelAndJoin() } @Test fun expiredAndRetiredCallsCannotReadCredentialsOrDispatch() = runTest { val parent = SupervisorJob(); var allocations = 0 val together = ProfileTogetherSession(ProfileId.Default, database(), CoroutineScope(parent + UnconfinedTestDispatcher(testScheduler))) { allocations++; error("Expired transport") } val caller = launch { currentCoroutineContext().cancel() assertFailsWith { together.join(Hub, "ABC") } } caller.join(); assertEquals(0, allocations); assertTrue(parent.isActive) parent.cancelAndJoin(); together.closeAndJoin() assertNull(together.hubSession()) assertFailsWith { together.join(Hub, "ABC") } together.setDriving(true); together.setFollowing(false) assertFalse(together.driving.value); assertTrue(together.following.value) } @Test fun callerExpiryDuringReplacementJoinsCleanupAndDoesNotRetireOwner() = runTest { val parent = SupervisorJob(); val release = CompletableDeferred(); var allocations = 0 val first = ProfileTestEngine(StandardTestDispatcher(testScheduler)) { try { awaitCancellation() } finally { withContext(NonCancellable) { release.await() } } } val second = ProfileTestEngine(StandardTestDispatcher(testScheduler)) { awaitCancellation() } val together = ProfileTogetherSession(ProfileId.Default, database(), CoroutineScope(parent + StandardTestDispatcher(testScheduler))) { allocations++; if (allocations == 1) first else second } together.join(Hub, "OLD"); first.requests.receive() val caller = launch { together.join(Hub, "ABANDONED") } testScheduler.runCurrent(); caller.cancel(); testScheduler.runCurrent() assertFalse(caller.isCompleted); assertTrue(parent.isActive); assertEquals(1, allocations) release.complete(Unit); caller.join(); assertNull(together.client.value) assertNotNull(together.join(Hub, "RETRY")); assertEquals(2, allocations) together.closeAndJoin(); parent.cancelAndJoin() } @Test fun independentOwnersRetainTheirRoomStateAndCleanupTargets() = runTest { val a = SupervisorJob(); val b = SupervisorJob() val engineA = ProfileTestEngine(StandardTestDispatcher(testScheduler)) { awaitCancellation() } val engineB = ProfileTestEngine(StandardTestDispatcher(testScheduler)) { awaitCancellation() } val idA = ProfileId("p_11111111111111111111111111111111") val idB = ProfileId("p_22222222222222222222222222222222") val first = ProfileTogetherSession(idA, database(), CoroutineScope(a + StandardTestDispatcher(testScheduler))) { assertEquals(idA, it); engineA } val second = ProfileTogetherSession(idB, database(), CoroutineScope(b + StandardTestDispatcher(testScheduler))) { assertEquals(idB, it); engineB } first.join(Hub, "AAA"); val currentB = second.join(Hub, "BBB") first.setFollowing(false); second.setDriving(true) a.cancelAndJoin(); first.closeAndJoin() assertSame(currentB, second.client.value); assertTrue(second.driving.value); assertTrue(second.following.value) assertEquals(1, engineA.closeCalls); assertEquals(0, engineB.closeCalls); assertTrue(b.isActive) second.closeAndJoin(); b.cancelAndJoin() } 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") } }