package eu.friedcutlet.yokan.services.library import eu.friedcutlet.yokan.database.* import eu.friedcutlet.yokan.services.http.* import kotlinx.coroutines.* import kotlinx.coroutines.test.* import kotlinx.serialization.json.* import kotlin.test.* @OptIn(ExperimentalCoroutinesApi::class) class LibraryAiringServiceTest { private val now = 1_800_000_000_000L private fun database(count: Int = 1) = InMemoryYokanDatabase(emptySnapshot().copy( mangas = (1L..count.toLong()).map { DbManga(id = it, name = "Private title $it", link = "/title/$it", sourceId = 1, itemType = DbItemType.Anime, favorite = true) }, tracks = (1L..count.toLong()).map { DbTrack(id = it, mangaId = it, mediaId = it + 100, syncId = 2, itemType = DbItemType.Anime, status = DbTrackStatus.Watching) }, trackPreferences = listOf(DbTrackPreference(syncId = 2, oauth = "private-token")), )) private fun ids(request: HttpRequest) = DatabaseJson.parseToJsonElement(checkNotNull(request.body)).jsonObject .getValue("variables").jsonObject.getValue("ids").jsonArray.map { it.jsonPrimitive.int } private fun response(request: HttpRequest, at: Long = now + 100_000, missing: Boolean = false): HttpResponse { val mal = checkNotNull(request.body).contains("idMal_in") return HttpResponse(200, buildJsonObject { putJsonObject("data") { putJsonObject("Page") { putJsonArray("media") { ids(request).forEach { id -> add(buildJsonObject { put("id", if (mal) id + 1000 else id); put("idMal", if (mal) id else id + 1000); put("type", "ANIME") put("nextAiringEpisode", if (missing) JsonNull else buildJsonObject { put("airingAt", at / 1000); put("episode", 12) }) }) } } } } }.toString()) } private fun TestScope.service(db: InMemoryYokanDatabase, http: HttpService, timeout: Long = 20_000) = LibraryAiringService(db, http, backgroundScope, { now }, requestIntervalMillis = 0, requestTimeoutMillis = timeout) @Test fun refreshIsExplicitAndPersistsPublicSchedulesWithoutSendingTitlesOrCredentials() = runTest { val db = database() val http = RecordingHttpService { response(it) } val service = service(db, http) assertTrue(http.requests.isEmpty()) val before = db.snapshot() assertEquals(LibraryAiringRefreshResult(updated = 1), service.refresh()) val saved = checkNotNull(db.manga(1)) assertEquals(now + 100_000, saved.nextEpisodeAiringAt) assertEquals(12, saved.nextEpisodeNumber) assertEquals(now, saved.airingScheduleUpdatedAt) assertNotEquals(before, db.snapshot()) val request = http.requests.single() assertEquals("https://graphql.anilist.co", request.url) assertEquals("POST", request.method) assertFalse(checkNotNull(request.body).contains("Private title")) assertFalse(checkNotNull(request.body).contains("private-token")) assertTrue(request.headers.keys.none { it.equals("Authorization", true) || it.equals("Cookie", true) }) val restarted = InMemoryYokanDatabase(checkNotNull(decodeDatabaseSnapshot(encodeDatabaseSnapshot(db.snapshot())))) assertEquals(saved.nextEpisodeAiringAt, restarted.manga(1)?.nextEpisodeAiringAt) } @Test fun requestsAreBatchedByPublicIdentityAndDuplicateSourceEntriesShareOneLookup() = runTest { val db = database(105) db.upsertTrack(checkNotNull(db.tracks().lastOrNull()).copy(mediaId = 101)) val batches = mutableListOf>() val result = service(db, HttpService { batches += ids(it); response(it) }).refresh() assertEquals(listOf(50, 50, 4), batches.map { it.size }) assertEquals(104, batches.flatten().toSet().size) assertEquals(105, result.updated) assertTrue(db.mangas().all { it.nextEpisodeAiringAt == now + 100_000 }) } @Test fun malAndExplicitMetadataIdsUseTheCorrectNamespaceAndUnsupportedEntriesMakeNoRequests() = runTest { val db = database(4) db.upsertTrack(checkNotNull(db.tracks().firstOrNull()).copy(syncId = 1)) db.removeTrack(2) db.updateSettings(db.settings().copy(titleMetadata = listOf(DbTitleMetadata(2, "222", "MyAnimeList")))) db.upsertTrack(checkNotNull(db.tracks().firstOrNull { it.id == 3L }).copy(itemType = DbItemType.Manga)) db.upsertManga(checkNotNull(db.manga(4)).copy(favorite = false)) val http = RecordingHttpService { response(it) } val result = service(db, http).refresh() assertEquals(2, result.updated) assertEquals(1, result.unavailable) assertEquals(1, http.requests.size) assertTrue(checkNotNull(http.requests.single().body).contains("idMal_in")) assertEquals(setOf(101, 222), ids(http.requests.single()).toSet()) assertEquals(0L, db.manga(3)?.nextEpisodeAiringAt) val unsupported = database() unsupported.removeTrack(1) assertEquals(LibraryAiringRefreshResult(unavailable = 1), service(unsupported, HttpService { error("Unexpected lookup") }).refresh()) } @Test fun sourceReplacementDeletionUnfavoriteAndRebindingRejectLateResponses() = runTest { for (mutation in listOf<(InMemoryYokanDatabase) -> Unit>( { db -> db.upsertManga(checkNotNull(db.manga(1)).copy(sourceId = 8, link = "/replacement")) }, { db -> db.removeManga(1) }, { db -> db.upsertManga(checkNotNull(db.manga(1)).copy(favorite = false)) }, { db -> db.upsertTrack(checkNotNull(db.tracks().singleOrNull()).copy(mediaId = 999)) }, )) { val db = database() val result = service(db, HttpService { request -> mutation(db); response(request) }).refresh() assertEquals(0, result.updated) assertTrue(db.manga(1)?.nextEpisodeAiringAt in listOf(null, 0L)) } } @Test fun providerFailuresAndMalformedResponsesPreserveSavedSchedules() = runTest { val malformed = listOf( HttpResponse(429, "rate limited"), HttpResponse(500, "failed"), HttpResponse(200, "not json"), HttpResponse(200, "{\"errors\":[{\"message\":\"private remote detail\"}],\"data\":{\"Page\":{\"media\":[]}}}"), HttpResponse(200, "{\"data\":{\"Page\":{\"media\":[{\"id\":101,\"type\":\"ANIME\"}]}}}"), HttpResponse(200, "{\"data\":{\"Page\":{\"media\":[{\"id\":101,\"type\":\"MANGA\",\"nextAiringEpisode\":null}]}}}"), ) malformed.forEach { reply -> val db = database() db.upsertManga(checkNotNull(db.manga(1)).copy(nextEpisodeAiringAt = now + 1_000_000)) assertEquals(1, service(db, HttpService { reply }).refresh().failed) assertEquals(now + 1_000_000, db.manga(1)?.nextEpisodeAiringAt) } } @Test fun explicitNoScheduleClearsAnOldAnnouncementButMissingIdentityDoesNot() = runTest { val db = database() db.upsertManga(checkNotNull(db.manga(1)).copy(nextEpisodeAiringAt = now + 1_000_000)) assertEquals(1, service(db, HttpService { HttpResponse(200, "{\"data\":{\"Page\":{\"media\":[]}}}") }).refresh().unavailable) assertEquals(now + 1_000_000, db.manga(1)?.nextEpisodeAiringAt) assertEquals(1, service(db, HttpService { response(it, missing = true) }).refresh().unavailable) assertEquals(0L, db.manga(1)?.nextEpisodeAiringAt) } @Test fun streamingResponseBoundStopsTheTransferBeforeUnboundedAllocation() = runTest { val db = database() var chunks = 0 val transport = object : HttpService { override suspend fun request(request: HttpRequest): HttpResponse = error("Must stream") override suspend fun stream(request: HttpRequest, onChunk: suspend (ByteArray) -> Unit): HttpStreamResponse { repeat(100) { chunks++; onChunk(ByteArray(32 * 1024)) } return HttpStreamResponse(200) } } assertEquals(1, service(db, transport).refresh().failed) assertEquals(9, chunks) assertEquals(0L, db.manga(1)?.nextEpisodeAiringAt) } @Test fun timeoutIsAnOrdinaryFailureAndDoesNotKillTheProfileOrFutureRefreshes() = runTest { val db = database() var slow = true val service = service(db, HttpService { if (slow) delay(100); response(it) }, timeout = 5) assertEquals(1, service.refresh().failed) assertTrue(backgroundScope.isActive) slow = false assertEquals(1, service.refresh().updated) } @Test fun callerCancellationJoinsItsTransferAndLeavesTheOwnerAvailable() = runTest { val db = database() val started = CompletableDeferred() var finalized = false val service = service(db, HttpService { started.complete(Unit); try { awaitCancellation() } finally { finalized = true } }) val request = async { service.refresh() } started.await() request.cancelAndJoin() assertTrue(finalized) assertTrue(backgroundScope.isActive) assertEquals(0L, db.manga(1)?.nextEpisodeAiringAt) } @Test fun retiringOneProfileCancelsAndJoinsOnlyItsCapturedWork() = runTest { val a = database() val b = database() val owner = CoroutineScope(SupervisorJob() + StandardTestDispatcher(testScheduler)) val started = CompletableDeferred() var finalized = false val serviceA = LibraryAiringService(a, HttpService { started.complete(Unit); try { awaitCancellation() } finally { finalized = true } }, owner, { now }, requestIntervalMillis = 0) val request = async { serviceA.refresh() } try { started.await() owner.coroutineContext[Job]?.cancelAndJoin() request.join() assertTrue(finalized) assertTrue(request.isCancelled) assertEquals(0L, a.manga(1)?.nextEpisodeAiringAt) assertEquals(1, service(b, HttpService { response(it) }).refresh().updated) assertEquals(now + 100_000, b.manga(1)?.nextEpisodeAiringAt) } finally { owner.cancel(); request.cancelAndJoin() } } @Test fun requestsAreRateSpacedAcrossBatches() = runTest { val db = database(51) val times = mutableListOf() val service = LibraryAiringService(db, HttpService { times += testScheduler.currentTime; response(it) }, backgroundScope, { now + testScheduler.currentTime }, requestIntervalMillis = 2100) assertEquals(51, service.refresh().updated) assertEquals(listOf(0L, 2100L), times) } }