@file:OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class) package eu.friedcutlet.yokan.services.together import eu.friedcutlet.yokan.domain.ProfileId import eu.friedcutlet.yokan.data.DefaultYokanRepository import eu.friedcutlet.yokan.database.DbManga 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.HttpRequest import eu.friedcutlet.yokan.services.http.HttpResponse import eu.friedcutlet.yokan.services.http.RecordingHttpService import eu.friedcutlet.yokan.services.http.ProfileHttpService import eu.friedcutlet.yokan.services.http.ProfileTestEngine import eu.friedcutlet.yokan.ui.screens.together.TogetherActions 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 kotlinx.serialization.json.jsonObject import kotlinx.serialization.json.jsonPrimitive 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 TogetherCreationLifecycleTest { @Test fun creationUsesCapturedCredentialsAndReturnsTheJoinedClient() = runTest { val parent = SupervisorJob() val scope = CoroutineScope(parent + StandardTestDispatcher(testScheduler)) val engine = ProfileTestEngine(StandardTestDispatcher(testScheduler)) { awaitCancellation() } val together = ProfileTogetherSession(ProfileId.Default, database(), scope) { engine } val http = RecordingHttpService { Created } val joined = assertNotNull(together.createAndJoin(http, Media)).getOrThrow() val rest = http.requests.single() assertEquals("https://hub.test/api/v1/rooms", rest.url) assertEquals("POST", rest.method) assertEquals("Bearer owner-token", rest.headers["Authorization"]) assertEquals("owner-device", rest.headers["X-Device"]) val body = RoomJson.parseToJsonElement(requireNotNull(rest.body)).jsonObject assertEquals("approve", body["policy"]?.jsonPrimitive?.content) assertEquals("suggest", body["playlist_policy"]?.jsonPrimitive?.content) assertEquals(Media, RoomJson.decodeFromJsonElement(RoomMedia.serializer(), requireNotNull(body["media"]))) val socket = engine.requests.receive() assertEquals("Bearer owner-token", socket.headers["Authorization"]) assertEquals("owner-device", socket.headers["X-Device"]) assertEquals("ABCDEF", joined.client.code) assertSame(joined.client, together.client.value) assertTrue(together.owns(joined.client)) together.leave() assertFalse(together.owns(joined.client)) together.closeAndJoin(); parent.cancelAndJoin() } @Test fun changedAccountDuringCreationCannotAllocateAJoinedRoom() = runTest { val mutations: List<(DbSyncPreference) -> DbSyncPreference> = listOf( { it.copy(authToken = null, syncOn = false) }, { it.copy(authToken = "new-token") }, { it.copy(server = "https://new-hub.test") }, { it.copy(deviceId = "new-device") }, { it.copy(serverProvider = SyncServerProvider.Mangayomi) }, { it.copy(syncId = 2) }, // Even identical server/token/device cannot retarget another preference. ) for (mutate in mutations) { val parent = SupervisorJob(); val db = database(); var allocations = 0 val together = ProfileTogetherSession(ProfileId.Default, db, CoroutineScope(parent + StandardTestDispatcher(testScheduler))) { allocations++; error("Stale REST result allocated a socket") } val replacement = mutate(Preference) val http = RecordingHttpService { db.replaceAll(db.snapshot().copy(syncPreferences = listOf(replacement))) Created } assertFailsWith { together.createAndJoin(http, Media) } assertEquals(0, allocations); assertNull(together.client.value) assertEquals(replacement, db.syncPreferences().single()) together.closeAndJoin(); parent.cancelAndJoin() } } @Test fun controllerRetirementJoinsRestFinalizersThroughTheProfileHttpWrapper() = runTest { val parent = SupervisorJob(); val entered = CompletableDeferred(); val release = CompletableDeferred() val scope = CoroutineScope(parent + StandardTestDispatcher(testScheduler)) val together = ProfileTogetherSession(ProfileId.Default, database(), scope) { error("Retired socket") } var finalized = false val delegate = RecordingHttpService { request -> if (request.method == "POST") { entered.complete(Unit) try { awaitCancellation() } finally { withContext(NonCancellable) { release.await(); finalized = true } } } HttpResponse(200, "sibling") } val http = ProfileHttpService(ProfileId.Default, delegate, scope) val caller = launch { together.createAndJoin(http, Media) } entered.await() val closing = launch { together.closeAndJoin() } testScheduler.runCurrent() assertFalse(closing.isCompleted); assertFalse(caller.isCompleted); assertFalse(finalized) assertNull(together.hubSession()); assertTrue(parent.isActive) release.complete(Unit); closing.join(); caller.join() assertTrue(finalized); assertNull(together.client.value) assertEquals("sibling", http.request(HttpRequest("https://hub.test/sibling")).body) assertFailsWith { together.createAndJoin(http, Media) } parent.cancelAndJoin() } @Test fun callerExpiryJoinsCreationWithoutRetiringItsControllerOrSiblingOwner() = runTest { val a = SupervisorJob(); val b = SupervisorJob() val release = CompletableDeferred(); val entered = CompletableDeferred() val first = ProfileTogetherSession(ProfileId.Default, database(), CoroutineScope(a + StandardTestDispatcher(testScheduler))) { error("Expired socket") } val engine = ProfileTestEngine(StandardTestDispatcher(testScheduler)) { awaitCancellation() } val second = ProfileTogetherSession(ProfileId.Default, database(), CoroutineScope(b + StandardTestDispatcher(testScheduler))) { engine } val caller = launch { first.createAndJoin(RecordingHttpService { entered.complete(Unit) try { awaitCancellation() } finally { withContext(NonCancellable) { release.await() } } }, Media) } entered.await(); caller.cancel(); testScheduler.runCurrent() assertFalse(caller.isCompleted); assertTrue(a.isActive) assertNotNull(second.createAndJoin(RecordingHttpService { Created }, Media)).getOrThrow() assertNotNull(second.client.value) release.complete(Unit); caller.join() assertNull(first.client.value); assertNotNull(first.hubSession()); assertTrue(b.isActive) first.closeAndJoin(); second.closeAndJoin(); a.cancelAndJoin(); b.cancelAndJoin() } @Test fun queuedAndAlreadyExpiredCreationCannotDispatch() = runTest { val parent = SupervisorJob(); val http = RecordingHttpService { Created } val together = ProfileTogetherSession(ProfileId.Default, database(), CoroutineScope(parent + StandardTestDispatcher(testScheduler))) { error("Queued socket") } val queued = launch { together.createAndJoin(http, Media) } together.closeAndJoin(); queued.join() assertTrue(http.requests.isEmpty()); assertTrue(parent.isActive) val immediate = ProfileTogetherSession(ProfileId.Default, database(), CoroutineScope(parent + UnconfinedTestDispatcher(testScheduler))) { error("Expired socket") } val expired = launch { currentCoroutineContext().cancel() assertFailsWith { immediate.createAndJoin(http, Media) } } expired.join(); assertTrue(http.requests.isEmpty()); assertTrue(parent.isActive) immediate.closeAndJoin(); parent.cancelAndJoin() } @Test fun creationFailurePreservesAnExistingRoomAndCanBeRetried() = runTest { val parent = SupervisorJob() val engine = ProfileTestEngine(StandardTestDispatcher(testScheduler)) { awaitCancellation() } val together = ProfileTogetherSession(ProfileId.Default, database(), CoroutineScope(parent + StandardTestDispatcher(testScheduler))) { engine } val current = assertNotNull(together.join(Hub, "OLD")); engine.requests.receive() for (response in listOf(HttpResponse(401, "{\"error\":\"Unauthorized\"}"), HttpResponse(200, "{}"), HttpResponse(200, "invalid"))) { assertTrue(assertNotNull(together.createAndJoin(RecordingHttpService { response }, Media)).isFailure) assertSame(current, together.client.value); assertTrue(together.owns(current)); assertEquals(0, engine.closeCalls) } together.closeAndJoin(); parent.cancelAndJoin() } @Test fun preferenceChangeDuringOldRoomCleanupCannotJoinTheCreatedRoom() = runTest { val parent = SupervisorJob(); val db = database(); val release = CompletableDeferred(); var allocations = 0 val engine = ProfileTestEngine(StandardTestDispatcher(testScheduler)) { try { awaitCancellation() } finally { withContext(NonCancellable) { release.await() } } } val together = ProfileTogetherSession(ProfileId.Default, db, CoroutineScope(parent + StandardTestDispatcher(testScheduler))) { allocations++; engine } together.join(Hub, "OLD"); engine.requests.receive() val caller = launch { together.createAndJoin(RecordingHttpService { Created }, Media) } testScheduler.runCurrent(); assertFalse(caller.isCompleted); assertNull(together.client.value) db.replaceAll(db.snapshot().copy(syncPreferences = listOf(Preference.copy(syncId = 2)))) release.complete(Unit); caller.join() assertEquals(1, allocations); assertEquals(1, engine.closeCalls); assertNull(together.client.value) together.closeAndJoin(); parent.cancelAndJoin() } @Test fun titleActionSuppressesLateNavigationAndDeliversItsOwnSuccessfulRoom() = runTest { val parent = SupervisorJob(); val db = database(); var opened = 0 val engine = ProfileTestEngine(StandardTestDispatcher(testScheduler)) { awaitCancellation() } val together = ProfileTogetherSession(ProfileId.Default, db, CoroutineScope(parent + StandardTestDispatcher(testScheduler))) { engine } val title = assertNotNull(DefaultYokanRepository(db).manga(1)) val changed = RecordingHttpService { db.upsertSyncPreference(Preference.copy(authToken = "new-token")); Created } assertFailsWith { TogetherActions.startRoom(together, changed, title, null) { opened++ } } assertEquals(0, opened); assertNull(together.client.value) db.upsertSyncPreference(Preference) val message = TogetherActions.startRoom(together, RecordingHttpService { Created }, title, null) { opened++ } assertEquals(1, opened); assertTrue(message.contains("ABCDEF")); assertEquals("ABCDEF", together.client.value?.code) together.closeAndJoin(); parent.cancelAndJoin() } @Test fun lateNonCancellableResponseCannotJoinAfterOwnerRetirement() = runTest { val parent = SupervisorJob(); val entered = CompletableDeferred(); val release = CompletableDeferred(); var allocations = 0 val together = ProfileTogetherSession(ProfileId.Default, database(), CoroutineScope(parent + StandardTestDispatcher(testScheduler))) { allocations++; error("Late owner socket") } val http = RecordingHttpService { entered.complete(Unit) withContext(NonCancellable) { release.await() } Created } val caller = launch { together.createAndJoin(http, Media) } entered.await(); parent.cancel(); testScheduler.runCurrent() assertFalse(caller.isCompleted); assertEquals(0, allocations) release.complete(Unit); parent.join(); caller.join() assertEquals(0, allocations); assertNull(together.client.value) together.closeAndJoin() } @Test fun unrelatedBookkeepingDuringCreationPreservesTheAccount() = runTest { val parent = SupervisorJob(); val db = database() val engine = ProfileTestEngine(StandardTestDispatcher(testScheduler)) { awaitCancellation() } val together = ProfileTogetherSession(ProfileId.Default, db, CoroutineScope(parent + StandardTestDispatcher(testScheduler))) { engine } val http = RecordingHttpService { db.upsertSyncPreference(Preference.copy(hubHead = 10, syncSettings = true, email = "label")) Created } val joined = assertNotNull(together.createAndJoin(http, Media)).getOrThrow() assertTrue(together.owns(joined.client)); assertEquals(10L, db.syncPreferences().single().hubHead) together.closeAndJoin(); parent.cancelAndJoin() } private fun database() = InMemoryYokanDatabase(emptySnapshot().copy( syncPreferences = listOf(Preference), mangas = listOf(DbManga(id = 1, name = "Title", link = "/title")), )) 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") val Media = RoomMedia("manga", 1, "/title", title = "Title") val Created = HttpResponse(201, "{\"code\":\"ABCDEF\",\"join_url\":\"https://hub.test/rooms/ABCDEF\"}") } }