TogetherCreationLifecycleTest.kt
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/together/TogetherCreationLifecycleTest.kt
1@file:OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)23package eu.friedcutlet.yokan.services.together45import eu.friedcutlet.yokan.domain.ProfileId6import eu.friedcutlet.yokan.data.DefaultYokanRepository7import eu.friedcutlet.yokan.database.DbManga8import eu.friedcutlet.yokan.database.DbSyncPreference9import eu.friedcutlet.yokan.database.InMemoryYokanDatabase10import eu.friedcutlet.yokan.database.SyncServerProvider11import eu.friedcutlet.yokan.database.emptySnapshot12import eu.friedcutlet.yokan.services.http.HttpRequest13import eu.friedcutlet.yokan.services.http.HttpResponse14import eu.friedcutlet.yokan.services.http.RecordingHttpService15import eu.friedcutlet.yokan.services.http.ProfileHttpService16import eu.friedcutlet.yokan.services.http.ProfileTestEngine17import eu.friedcutlet.yokan.ui.screens.together.TogetherActions18import kotlinx.coroutines.CancellationException19import kotlinx.coroutines.CompletableDeferred20import kotlinx.coroutines.CoroutineScope21import kotlinx.coroutines.NonCancellable22import kotlinx.coroutines.SupervisorJob23import kotlinx.coroutines.awaitCancellation24import kotlinx.coroutines.cancel25import kotlinx.coroutines.cancelAndJoin26import kotlinx.coroutines.currentCoroutineContext27import kotlinx.coroutines.launch28import kotlinx.coroutines.test.StandardTestDispatcher29import kotlinx.coroutines.test.UnconfinedTestDispatcher30import kotlinx.coroutines.test.runTest31import kotlinx.coroutines.withContext32import kotlinx.serialization.json.jsonObject33import kotlinx.serialization.json.jsonPrimitive34import kotlin.test.Test35import kotlin.test.assertEquals36import kotlin.test.assertFailsWith37import kotlin.test.assertFalse38import kotlin.test.assertNotNull39import kotlin.test.assertNull40import kotlin.test.assertSame41import kotlin.test.assertTrue4243class TogetherCreationLifecycleTest {44 @Test fun creationUsesCapturedCredentialsAndReturnsTheJoinedClient() = runTest {45 val parent = SupervisorJob()46 val scope = CoroutineScope(parent + StandardTestDispatcher(testScheduler))47 val engine = ProfileTestEngine(StandardTestDispatcher(testScheduler)) { awaitCancellation() }48 val together = ProfileTogetherSession(ProfileId.Default, database(), scope) { engine }49 val http = RecordingHttpService { Created }50 val joined = assertNotNull(together.createAndJoin(http, Media)).getOrThrow()51 val rest = http.requests.single()52 assertEquals("https://hub.test/api/v1/rooms", rest.url)53 assertEquals("POST", rest.method)54 assertEquals("Bearer owner-token", rest.headers["Authorization"])55 assertEquals("owner-device", rest.headers["X-Device"])56 val body = RoomJson.parseToJsonElement(requireNotNull(rest.body)).jsonObject57 assertEquals("approve", body["policy"]?.jsonPrimitive?.content)58 assertEquals("suggest", body["playlist_policy"]?.jsonPrimitive?.content)59 assertEquals(Media, RoomJson.decodeFromJsonElement(RoomMedia.serializer(), requireNotNull(body["media"])))60 val socket = engine.requests.receive()61 assertEquals("Bearer owner-token", socket.headers["Authorization"])62 assertEquals("owner-device", socket.headers["X-Device"])63 assertEquals("ABCDEF", joined.client.code)64 assertSame(joined.client, together.client.value)65 assertTrue(together.owns(joined.client))66 together.leave()67 assertFalse(together.owns(joined.client))68 together.closeAndJoin(); parent.cancelAndJoin()69 }7071 @Test fun changedAccountDuringCreationCannotAllocateAJoinedRoom() = runTest {72 val mutations: List<(DbSyncPreference) -> DbSyncPreference> = listOf(73 { it.copy(authToken = null, syncOn = false) },74 { it.copy(authToken = "new-token") },75 { it.copy(server = "https://new-hub.test") },76 { it.copy(deviceId = "new-device") },77 { it.copy(serverProvider = SyncServerProvider.Mangayomi) },78 { it.copy(syncId = 2) }, // Even identical server/token/device cannot retarget another preference.79 )80 for (mutate in mutations) {81 val parent = SupervisorJob(); val db = database(); var allocations = 082 val together = ProfileTogetherSession(ProfileId.Default, db, CoroutineScope(parent + StandardTestDispatcher(testScheduler))) {83 allocations++; error("Stale REST result allocated a socket")84 }85 val replacement = mutate(Preference)86 val http = RecordingHttpService {87 db.replaceAll(db.snapshot().copy(syncPreferences = listOf(replacement)))88 Created89 }90 assertFailsWith<CancellationException> { together.createAndJoin(http, Media) }91 assertEquals(0, allocations); assertNull(together.client.value)92 assertEquals(replacement, db.syncPreferences().single())93 together.closeAndJoin(); parent.cancelAndJoin()94 }95 }9697 @Test fun controllerRetirementJoinsRestFinalizersThroughTheProfileHttpWrapper() = runTest {98 val parent = SupervisorJob(); val entered = CompletableDeferred<Unit>(); val release = CompletableDeferred<Unit>()99 val scope = CoroutineScope(parent + StandardTestDispatcher(testScheduler))100 val together = ProfileTogetherSession(ProfileId.Default, database(), scope) { error("Retired socket") }101 var finalized = false102 val delegate = RecordingHttpService { request ->103 if (request.method == "POST") {104 entered.complete(Unit)105 try { awaitCancellation() } finally { withContext(NonCancellable) { release.await(); finalized = true } }106 }107 HttpResponse(200, "sibling")108 }109 val http = ProfileHttpService(ProfileId.Default, delegate, scope)110 val caller = launch { together.createAndJoin(http, Media) }111 entered.await()112 val closing = launch { together.closeAndJoin() }113 testScheduler.runCurrent()114 assertFalse(closing.isCompleted); assertFalse(caller.isCompleted); assertFalse(finalized)115 assertNull(together.hubSession()); assertTrue(parent.isActive)116 release.complete(Unit); closing.join(); caller.join()117 assertTrue(finalized); assertNull(together.client.value)118 assertEquals("sibling", http.request(HttpRequest("https://hub.test/sibling")).body)119 assertFailsWith<CancellationException> { together.createAndJoin(http, Media) }120 parent.cancelAndJoin()121 }122123 @Test fun callerExpiryJoinsCreationWithoutRetiringItsControllerOrSiblingOwner() = runTest {124 val a = SupervisorJob(); val b = SupervisorJob()125 val release = CompletableDeferred<Unit>(); val entered = CompletableDeferred<Unit>()126 val first = ProfileTogetherSession(ProfileId.Default, database(), CoroutineScope(a + StandardTestDispatcher(testScheduler))) { error("Expired socket") }127 val engine = ProfileTestEngine(StandardTestDispatcher(testScheduler)) { awaitCancellation() }128 val second = ProfileTogetherSession(ProfileId.Default, database(), CoroutineScope(b + StandardTestDispatcher(testScheduler))) { engine }129 val caller = launch {130 first.createAndJoin(RecordingHttpService {131 entered.complete(Unit)132 try { awaitCancellation() } finally { withContext(NonCancellable) { release.await() } }133 }, Media)134 }135 entered.await(); caller.cancel(); testScheduler.runCurrent()136 assertFalse(caller.isCompleted); assertTrue(a.isActive)137 assertNotNull(second.createAndJoin(RecordingHttpService { Created }, Media)).getOrThrow()138 assertNotNull(second.client.value)139 release.complete(Unit); caller.join()140 assertNull(first.client.value); assertNotNull(first.hubSession()); assertTrue(b.isActive)141 first.closeAndJoin(); second.closeAndJoin(); a.cancelAndJoin(); b.cancelAndJoin()142 }143144 @Test fun queuedAndAlreadyExpiredCreationCannotDispatch() = runTest {145 val parent = SupervisorJob(); val http = RecordingHttpService { Created }146 val together = ProfileTogetherSession(ProfileId.Default, database(), CoroutineScope(parent + StandardTestDispatcher(testScheduler))) { error("Queued socket") }147 val queued = launch { together.createAndJoin(http, Media) }148 together.closeAndJoin(); queued.join()149 assertTrue(http.requests.isEmpty()); assertTrue(parent.isActive)150 val immediate = ProfileTogetherSession(ProfileId.Default, database(), CoroutineScope(parent + UnconfinedTestDispatcher(testScheduler))) { error("Expired socket") }151 val expired = launch {152 currentCoroutineContext().cancel()153 assertFailsWith<CancellationException> { immediate.createAndJoin(http, Media) }154 }155 expired.join(); assertTrue(http.requests.isEmpty()); assertTrue(parent.isActive)156 immediate.closeAndJoin(); parent.cancelAndJoin()157 }158159 @Test fun creationFailurePreservesAnExistingRoomAndCanBeRetried() = runTest {160 val parent = SupervisorJob()161 val engine = ProfileTestEngine(StandardTestDispatcher(testScheduler)) { awaitCancellation() }162 val together = ProfileTogetherSession(ProfileId.Default, database(), CoroutineScope(parent + StandardTestDispatcher(testScheduler))) { engine }163 val current = assertNotNull(together.join(Hub, "OLD")); engine.requests.receive()164 for (response in listOf(HttpResponse(401, "{\"error\":\"Unauthorized\"}"), HttpResponse(200, "{}"), HttpResponse(200, "invalid"))) {165 assertTrue(assertNotNull(together.createAndJoin(RecordingHttpService { response }, Media)).isFailure)166 assertSame(current, together.client.value); assertTrue(together.owns(current)); assertEquals(0, engine.closeCalls)167 }168 together.closeAndJoin(); parent.cancelAndJoin()169 }170171 @Test fun preferenceChangeDuringOldRoomCleanupCannotJoinTheCreatedRoom() = runTest {172 val parent = SupervisorJob(); val db = database(); val release = CompletableDeferred<Unit>(); var allocations = 0173 val engine = ProfileTestEngine(StandardTestDispatcher(testScheduler)) {174 try { awaitCancellation() } finally { withContext(NonCancellable) { release.await() } }175 }176 val together = ProfileTogetherSession(ProfileId.Default, db, CoroutineScope(parent + StandardTestDispatcher(testScheduler))) { allocations++; engine }177 together.join(Hub, "OLD"); engine.requests.receive()178 val caller = launch { together.createAndJoin(RecordingHttpService { Created }, Media) }179 testScheduler.runCurrent(); assertFalse(caller.isCompleted); assertNull(together.client.value)180 db.replaceAll(db.snapshot().copy(syncPreferences = listOf(Preference.copy(syncId = 2))))181 release.complete(Unit); caller.join()182 assertEquals(1, allocations); assertEquals(1, engine.closeCalls); assertNull(together.client.value)183 together.closeAndJoin(); parent.cancelAndJoin()184 }185186 @Test fun titleActionSuppressesLateNavigationAndDeliversItsOwnSuccessfulRoom() = runTest {187 val parent = SupervisorJob(); val db = database(); var opened = 0188 val engine = ProfileTestEngine(StandardTestDispatcher(testScheduler)) { awaitCancellation() }189 val together = ProfileTogetherSession(ProfileId.Default, db, CoroutineScope(parent + StandardTestDispatcher(testScheduler))) { engine }190 val title = assertNotNull(DefaultYokanRepository(db).manga(1))191 val changed = RecordingHttpService { db.upsertSyncPreference(Preference.copy(authToken = "new-token")); Created }192 assertFailsWith<CancellationException> { TogetherActions.startRoom(together, changed, title, null) { opened++ } }193 assertEquals(0, opened); assertNull(together.client.value)194 db.upsertSyncPreference(Preference)195 val message = TogetherActions.startRoom(together, RecordingHttpService { Created }, title, null) { opened++ }196 assertEquals(1, opened); assertTrue(message.contains("ABCDEF")); assertEquals("ABCDEF", together.client.value?.code)197 together.closeAndJoin(); parent.cancelAndJoin()198 }199200 @Test fun lateNonCancellableResponseCannotJoinAfterOwnerRetirement() = runTest {201 val parent = SupervisorJob(); val entered = CompletableDeferred<Unit>(); val release = CompletableDeferred<Unit>(); var allocations = 0202 val together = ProfileTogetherSession(ProfileId.Default, database(), CoroutineScope(parent + StandardTestDispatcher(testScheduler))) {203 allocations++; error("Late owner socket")204 }205 val http = RecordingHttpService {206 entered.complete(Unit)207 withContext(NonCancellable) { release.await() }208 Created209 }210 val caller = launch { together.createAndJoin(http, Media) }211 entered.await(); parent.cancel(); testScheduler.runCurrent()212 assertFalse(caller.isCompleted); assertEquals(0, allocations)213 release.complete(Unit); parent.join(); caller.join()214 assertEquals(0, allocations); assertNull(together.client.value)215 together.closeAndJoin()216 }217218 @Test fun unrelatedBookkeepingDuringCreationPreservesTheAccount() = runTest {219 val parent = SupervisorJob(); val db = database()220 val engine = ProfileTestEngine(StandardTestDispatcher(testScheduler)) { awaitCancellation() }221 val together = ProfileTogetherSession(ProfileId.Default, db, CoroutineScope(parent + StandardTestDispatcher(testScheduler))) { engine }222 val http = RecordingHttpService {223 db.upsertSyncPreference(Preference.copy(hubHead = 10, syncSettings = true, email = "label"))224 Created225 }226 val joined = assertNotNull(together.createAndJoin(http, Media)).getOrThrow()227 assertTrue(together.owns(joined.client)); assertEquals(10L, db.syncPreferences().single().hubHead)228 together.closeAndJoin(); parent.cancelAndJoin()229 }230231 private fun database() = InMemoryYokanDatabase(emptySnapshot().copy(232 syncPreferences = listOf(Preference), mangas = listOf(DbManga(id = 1, name = "Title", link = "/title")),233 ))234235 private companion object {236 val Preference = DbSyncPreference(syncId = 1, server = "https://hub.test/", authToken = "owner-token", deviceId = "owner-device")237 val Hub = HubSession("https://hub.test", "owner-token", "owner-device")238 val Media = RoomMedia("manga", 1, "/title", title = "Title")239 val Created = HttpResponse(201, "{\"code\":\"ABCDEF\",\"join_url\":\"https://hub.test/rooms/ABCDEF\"}")240 }241}242