diff --git a/android/app/src/main/java/tv/orbit/classic/CatalogueStore.kt b/android/app/src/main/java/tv/orbit/classic/CatalogueStore.kt index 88ec5a9e..4ccafd04 100644 --- a/android/app/src/main/java/tv/orbit/classic/CatalogueStore.kt +++ b/android/app/src/main/java/tv/orbit/classic/CatalogueStore.kt @@ -36,6 +36,7 @@ internal class CatalogueStore(context: Context, private val file: File) : Catalo return if (meta(db, "user") == userId) meta(db, "next")?.toLongOrNull() ?: 0 else 0 } @Synchronized override fun write(userId: String, records: List, nextStart: Long, total: Long?, finished: Boolean) { + if (records.isNotEmpty()) titlesCache = null val db = writableDatabase db.beginTransaction() try { @@ -99,6 +100,22 @@ internal class CatalogueStore(context: Context, private val file: File) : Catalo }.toList() } }.toMap() + private var titlesCache: Pair? = null + /** + * Which titles the library has, for skipping searches for titles it hasn't got ([LibraryTitles]). Null until the whole + * library has been read once for this account, so a partly read catalogue never rules a title out. + */ + @Synchronized fun libraryTitles(userId: String): LibraryTitles? { + titlesCache?.takeIf { it.first == userId }?.let { return it.second } + val db = readableDatabase + if (meta(db, "user") != userId || !summary().finished) return null + val titles = db.rawQuery("SELECT type, title FROM items", null).use { c -> + LibraryTitles.of(generateSequence { if (c.moveToNext()) c.getString(0) to c.getString(1) else null }) + } + titlesCache = userId to titles + return titles + } + /** Whether the whole library has been read once: only after that is anything read new. */ @Synchronized fun complete(): Boolean = summary().finished @@ -146,6 +163,7 @@ internal class CatalogueStore(context: Context, private val file: File) : Catalo return tally.result(scanMs, timings, file.length()) } @Synchronized fun clear() { + titlesCache = null close() if (file.exists() && !SQLiteDatabase.deleteDatabase(file)) throw IllegalStateException("The catalogue could not be removed.") } diff --git a/android/app/src/main/java/tv/orbit/classic/ChannelScheduler.kt b/android/app/src/main/java/tv/orbit/classic/ChannelScheduler.kt index f29dc69a..29e0df05 100644 --- a/android/app/src/main/java/tv/orbit/classic/ChannelScheduler.kt +++ b/android/app/src/main/java/tv/orbit/classic/ChannelScheduler.kt @@ -127,7 +127,7 @@ internal class ChannelScheduler(private val store: ScheduleStore, Log.i("OrbitSchedule", "evidence asked=${ids.distinct().size} missing=${missing.size} read=$read failedBatches=$failed") } - private fun readCollectionsOnly(session: EmbySampleSession, refresh: CollectionRefresh) { + internal fun readCollectionsOnly(session: EmbySampleSession, refresh: CollectionRefresh) { // Emby's collections, for verified franchise links: resumable from where the last read stopped, a bounded number per run. val collections = store.collectionsFile() // Read before collections were paged (every one stopped at 300): set aside once and read again in full. @@ -142,19 +142,21 @@ internal class ChannelScheduler(private val store: ScheduleStore, val known = if (refreshing && !refresh.fullDue()) runCatching { collections.useLines { lines -> lines.mapNotNull { runCatching { JSONObject(it) }.getOrNull() } .associateBy { it.optString("id") } } }.getOrNull() else null val done = if (target.exists()) target.useLines { it.count() } else 0 - var start = done; var sets = 0; var total = -1; var finished = false + var start = done; var sets = 0; var total = -1; var finished = false; var paced = false try { while (sets < COLLECTIONS_MAX_PER_RUN) { - val (page, all) = session.readCollections(start, COLLECTIONS_PAGE, known) - total = all - if (page.isEmpty()) { finished = true; break } - target.appendText(page.joinToString("") { it.toString() + "\n" }) + val read = session.readCollectionsPage(start, COLLECTIONS_PAGE, known) + val page = read.sets + total = read.total + // Whatever was read before the hour's budget ran out is kept, and the next round starts after it (0.129 audit). + if (page.isNotEmpty()) target.appendText(page.joinToString("") { it.toString() + "\n" }) start += page.size; sets += page.size - if (start >= all) { finished = true; break } + if (read.pacedOut) { paced = true; break } + if (page.isEmpty() || start >= read.total) { finished = true; break } } - } catch (failure: EmbyCheckException) { Log.w("OrbitSchedule", "collections failed status=${failure.httpStatus}") } + } catch (failure: EmbyCheckException) { paced = failure is PacedOut; Log.w("OrbitSchedule", "collections failed status=${failure.httpStatus} paced=$paced") } if (finished) refresh.finish(refreshing, clock()) - Log.i("OrbitSchedule", "collections read=$sets total=$total kept=${done + sets} refresh=$refreshing finished=$finished") + Log.i("OrbitSchedule", "collections read=$sets total=$total kept=${done + sets} refresh=$refreshing finished=$finished paced=$paced") } /** diff --git a/android/app/src/main/java/tv/orbit/classic/EmbyConnectionScreen.kt b/android/app/src/main/java/tv/orbit/classic/EmbyConnectionScreen.kt index b54dfc0f..6eb55643 100644 --- a/android/app/src/main/java/tv/orbit/classic/EmbyConnectionScreen.kt +++ b/android/app/src/main/java/tv/orbit/classic/EmbyConnectionScreen.kt @@ -342,6 +342,8 @@ internal fun EmbyConnectionScreen(modifier: Modifier = Modifier, visible: Boolea // The first-launch flow's channels, one after another, as switching each on in Settings does. In the tour, it only counts. LaunchedEffect(ChannelSetup.wanted, session) { val active = session ?: return@LaunchedEffect + // Listed titles the library hasn't got are skipped, once the catalogue has read the whole library (0.129 audit). + if (ChannelSetup.wanted.isNotEmpty()) withContext(Dispatchers.IO) { active.libraryTitles = runCatching { catalogue.libraryTitles(active.accountId) }.getOrNull() } for (number in ChannelSetup.wanted) { if (number in ChannelSetup.found) continue val programming = SmartChannels.firstOrNull { it.number == number } ?: continue @@ -352,8 +354,9 @@ internal fun EmbyConnectionScreen(modifier: Modifier = Modifier, visible: Boolea else { val context = coroutineContext scheduler.setEnabled(active.accountId, number, true) - val loop = smartLoop(programming) ?: scheduler.seedLoop(active, active.accountId, programming) { context.ensureActive() }.also { extraChannels = extraChannels + it } - scheduler.topUp(active, active.accountId, programming, loop) { context.ensureActive() }.also { + // Paced, a request at most every 150 ms (0.129 audit): see BackgroundPacing.setup. + val loop = smartLoop(programming) ?: BackgroundPacing.setup { scheduler.seedLoop(active, active.accountId, programming) { context.ensureActive() } }.also { extraChannels = extraChannels + it } + BackgroundPacing.setup { scheduler.topUp(active, active.accountId, programming, loop) { context.ensureActive() } }.also { scheduler.load(active.accountId, loop)?.let { on -> scheduledChannels = scheduledChannels + (number to on) } }.shows.size } @@ -420,9 +423,13 @@ internal fun EmbyConnectionScreen(modifier: Modifier = Modifier, visible: Boolea // Setting channels up adds each to extraChannels, which restarts this round from the first channel every time: with // 30 channels that was hundreds of needless top-ups (seen on the upstairs box, 6 November 2026). Wait until setting up // is over, and a moment more so a run of changes counts once. - androidx.compose.runtime.snapshotFlow { ChannelSetup.wanted.isEmpty() || ChannelSetup.finished }.first { it } + // On a new box, also until the first-launch flow is over (0.129 audit): signing in left nothing wanted yet, so the + // round began at once and its paced reads (3,000 collections on a big library) ran alongside the channel setup. + androidx.compose.runtime.snapshotFlow { (ChannelSetup.wanted.isEmpty() && Onboarding.step == null) || ChannelSetup.finished }.first { it } delay(3_000) while (true) { + // Refreshed each round, so it's there once the catalogue finishes its first full read (0.129 audit). + withContext(Dispatchers.IO) { active.libraryTitles = runCatching { catalogue.libraryTitles(active.accountId) }.getOrNull() } for (programming in SmartChannels) { val loop = smartLoop(programming) ?: run { // A channel of your own that is switched on but whose first plan never finished (an update arrived mid-read, @@ -585,8 +592,9 @@ internal fun EmbyConnectionScreen(modifier: Modifier = Modifier, visible: Boolea val report = withContext(Dispatchers.IO) { val context = coroutineContext scheduler.setEnabled(active.accountId, programming.number, true) - val loop = existing ?: scheduler.seedLoop(active, active.accountId, programming) { context.ensureActive() }.also { extraChannels = extraChannels + it } - scheduler.topUp(active, active.accountId, programming, loop) { context.ensureActive() }.also { + active.libraryTitles = runCatching { catalogue.libraryTitles(active.accountId) }.getOrNull() + val loop = existing ?: BackgroundPacing.setup { scheduler.seedLoop(active, active.accountId, programming) { context.ensureActive() } }.also { extraChannels = extraChannels + it } + BackgroundPacing.setup { scheduler.topUp(active, active.accountId, programming, loop) { context.ensureActive() } }.also { scheduler.load(active.accountId, loop)?.let { on -> scheduledChannels = scheduledChannels + (programming.number to on) } } } diff --git a/android/app/src/main/java/tv/orbit/classic/EmbyPlaybackProtocol.kt b/android/app/src/main/java/tv/orbit/classic/EmbyPlaybackProtocol.kt index 9bde1269..6d22d956 100644 --- a/android/app/src/main/java/tv/orbit/classic/EmbyPlaybackProtocol.kt +++ b/android/app/src/main/java/tv/orbit/classic/EmbyPlaybackProtocol.kt @@ -77,6 +77,13 @@ internal class EmbySampleSession(private val transport: EmbyTransport, private v @Volatile private var active: EmbyPlaybackPlan? = null @Volatile private var lastPositionMs = 0L val accountId get() = userId + /** The library's titles from the catalogue on this box, when it has read the whole library: listed titles it hasn't got aren't searched for. */ + @Volatile var libraryTitles: LibraryTitles? = null + /** Listed titles not searched for because the library hasn't got them, since this session began (for the timing log). */ + @Volatile var skippedSearches = 0 + private set + private fun hasSeries(title: String) = libraryTitles?.mayHaveSeries(title) != false || run { skippedSearches++; false } + private fun hasFilm(entry: String) = libraryTitles?.mayHaveFilm(entry) != false || run { skippedSearches++; false } /** The server this session belongs to, for good: its media addresses and token go nowhere else. */ val origin: String get() = (transport as? HttpsEmbyTransport)?.origin ?: EmbyServer.origin /** Where this server's API starts: /emby on Emby, the root on Jellyfin. */ @@ -199,6 +206,7 @@ internal class EmbySampleSession(private val transport: EmbyTransport, private v for (search in preset.searches) { if (groups.size == 3) break checkActive() + if (!hasSeries(search)) { missing += search; continue } val match = bestSeriesMatch(search, searchSeries(transport, userId, ::currentToken, search).candidates) val usable = match?.takeIf { series -> groups.none { it.series.id == series.id } }?.let { series -> regularEpisodes(discoverSeriesEpisodes(transport, userId, ::currentToken, listOf(series), checkActive, PRESET_EPISODE_READ)).singleOrNull() @@ -318,30 +326,44 @@ internal class EmbySampleSession(private val transport: EmbyTransport, private v * Collections already read, by ID (0.129): one whose member count (ChildCount) is unchanged is kept as it was, with no * request for its members. A whole refresh then costs a request per page of collections, not one per collection. */ - known: Map? = null): Pair, Int> { + known: Map? = null): Pair, Int> = + readCollectionsPage(start, limit, known).let { if (it.pacedOut && it.sets.isEmpty()) throw PacedOut() else it.sets to it.total } + + /** A page of collections; [pacedOut] when the hour's background budget ran out part-way, with the collections finished before it. */ + internal class CollectionsPage(val sets: List, val total: Int, val pacedOut: Boolean) + + /** + * [readCollections], keeping what it read when the background budget runs out part-way (0.129 audit): before, a page of + * 200 collections cut short threw away every member list already read on it, and the next round read them all again. + */ + fun readCollectionsPage(start: Int, limit: Int, known: Map? = null): CollectionsPage { val reply = transport.execute(EmbyRequest("GET", "/Items?UserId=$userId&IncludeItemTypes=BoxSet&Recursive=true&StartIndex=$start&Limit=$limit&Fields=ProviderIds,ChildCount" + "&SortBy=SortName&SortOrder=Ascending&EnableImages=false&EnableUserData=false", token = currentToken(), readTimeoutMs = WHOLE_SERIES_TIMEOUT_MS)) EmbyClient.expectSuccess(reply.status, false) val body = EmbyClient.parse(reply.body) val rows = body.optJSONArray("Items") val sets = (0 until (rows?.length() ?: 0)).mapNotNull { rows!!.optJSONObject(it) }.filter { EmbyClient.validId(it.optString("Id")) } - return sets.map { set -> - unchangedCollection(set, known)?.let { return@map it } - // Every member, a page at a time (Paul, 7 November 2026: it stopped at 300, so big collections were cut short), up to - // COLLECTION_MAX; "complete" says whether all of them were read. - val members = ArrayList(); var total = 0 - while (members.size < COLLECTION_MAX) { - val page = transport.execute(EmbyRequest("GET", "/Items?UserId=$userId&ParentId=${set.optString("Id")}&StartIndex=${members.size}&Limit=$COLLECTION_PAGE&SortBy=SortName&SortOrder=Ascending&Fields=ProviderIds&EnableImages=false&EnableUserData=false", - token = currentToken(), readTimeoutMs = WHOLE_SERIES_TIMEOUT_MS)).let { r -> EmbyClient.expectSuccess(r.status, false); EmbyClient.parse(r.body) } - val items = page.optJSONArray("Items") - total = page.optInt("TotalRecordCount", members.size + (items?.length() ?: 0)) - val ids = (0 until (items?.length() ?: 0)).mapNotNull { items!!.optJSONObject(it)?.optString("Id")?.takeIf(EmbyClient::validId) } - members += ids - if (ids.size < COLLECTION_PAGE || members.size >= total) break - } - JSONObject().put("id", set.optString("Id")).put("name", EmbyClient.clean(set.optString("Name"), 120)) - .put("members", org.json.JSONArray(members.take(COLLECTION_MAX))).put("total", total).put("complete", members.size >= total) - } to body.optInt("TotalRecordCount", sets.size) + val read = ArrayList(sets.size) + for (set in sets) read += try { readCollection(set, known) } catch (paced: PacedOut) { return CollectionsPage(read, body.optInt("TotalRecordCount", sets.size), true) } + return CollectionsPage(read, body.optInt("TotalRecordCount", sets.size), false) + } + + private fun readCollection(set: JSONObject, known: Map?): JSONObject { + unchangedCollection(set, known)?.let { return it } + // Every member, a page at a time (Paul, 7 November 2026: it stopped at 300, so big collections were cut short), up to + // COLLECTION_MAX; "complete" says whether all of them were read. + val members = ArrayList(); var total = 0 + while (members.size < COLLECTION_MAX) { + val page = transport.execute(EmbyRequest("GET", "/Items?UserId=$userId&ParentId=${set.optString("Id")}&StartIndex=${members.size}&Limit=$COLLECTION_PAGE&SortBy=SortName&SortOrder=Ascending&Fields=ProviderIds&EnableImages=false&EnableUserData=false", + token = currentToken(), readTimeoutMs = WHOLE_SERIES_TIMEOUT_MS)).let { r -> EmbyClient.expectSuccess(r.status, false); EmbyClient.parse(r.body) } + val items = page.optJSONArray("Items") + total = page.optInt("TotalRecordCount", members.size + (items?.length() ?: 0)) + val ids = (0 until (items?.length() ?: 0)).mapNotNull { items!!.optJSONObject(it)?.optString("Id")?.takeIf(EmbyClient::validId) } + members += ids + if (ids.size < COLLECTION_PAGE || members.size >= total) break + } + return JSONObject().put("id", set.optString("Id")).put("name", EmbyClient.clean(set.optString("Name"), 120)) + .put("members", org.json.JSONArray(members.take(COLLECTION_MAX))).put("total", total).put("complete", members.size >= total) } internal class PoolRead(val series: List, val requests: Int, @@ -364,6 +386,7 @@ internal class EmbySampleSession(private val transport: EmbyTransport, private v for (entry in programming.searches) { if (found >= programming.seriesCount) break checkActive() + if (!hasFilm(entry)) continue requests++ val lookup = try { findFilm(transport, userId, ::currentToken, entry, BoxDecoders::canDecode) } catch (failure: EmbyCheckException) { android.util.Log.w("OrbitSchedule", "channel=${programming.number} film failed=${failure.javaClass.simpleName} status=${failure.httpStatus}") @@ -378,6 +401,7 @@ internal class EmbySampleSession(private val transport: EmbyTransport, private v // A series this film channel carries in an event: read whole, like a series channel, kept as one series rather than as films. for (title in programming.filmSeries) { checkActive() + if (!hasSeries(title)) continue requests++ val match = searchSeries(transport, userId, ::currentToken, title).candidates.filter { seriesKey(it.title) == seriesKey(title) }.take(MAX_SERIES_COPIES) val read = match.map { copy -> readWholeSeries(transport, userId, ::currentToken, copy, checkActive, onRequest = { requests++ }, canDecode = BoxDecoders::canDecode, englishAudio = programming.englishAudio) } @@ -388,6 +412,7 @@ internal class EmbySampleSession(private val transport: EmbyTransport, private v } else for ((index, search) in programming.searches.withIndex()) { if (pool.size == programming.seriesCount) break checkActive() + if (!hasSeries(search)) continue requests++ // Counts and the failure's kind only, never titles: which list entry a failed pool read stopped at. fun traced(step: String, block: () -> T): T = try { block() } catch (failure: Exception) { @@ -423,6 +448,7 @@ internal class EmbySampleSession(private val transport: EmbyTransport, private v // Films this series channel carries in an event, found exactly as a film channel finds them. Nothing stands in for one that isn't there. if (programming.filmRestMs == null) for (entry in programming.channelFilms) { checkActive() + if (!hasFilm(entry)) continue requests++ val lookup = findFilm(transport, userId, ::currentToken, entry, BoxDecoders::canDecode) if (lookup.note.isNotEmpty()) android.util.Log.i("OrbitSchedule", "channel=${programming.number} ${lookup.note}") diff --git a/android/app/src/main/java/tv/orbit/classic/GuidePicture.kt b/android/app/src/main/java/tv/orbit/classic/GuidePicture.kt index b0119573..f2caee89 100644 --- a/android/app/src/main/java/tv/orbit/classic/GuidePicture.kt +++ b/android/app/src/main/java/tv/orbit/classic/GuidePicture.kt @@ -64,6 +64,9 @@ internal fun channelMediaItem(plan: EmbyPlaybackPlan): MediaItem = MediaItem.Bui .setLanguage(subtitle.language).setLabel(subtitle.label).build() }).build() +/** How long until [endMs], plus a moment so the programme at that time is the next one; never negative. */ +internal fun programmeEndDelayMs(endMs: Long, nowMs: Long) = (endMs - nowMs).coerceAtLeast(0L) + 50L + /** * The guide's picture slot: the tuned channel, live, on the channel's own clock. Artwork covers it until the * first frame and stays if the programme can't open. It holds one stream, so it stops when [live] goes false. @@ -80,9 +83,15 @@ internal fun GuidePicture(session: EmbySampleSession, channel: SampleChannel, li lifecycle.addObserver(observer) onDispose { lifecycle.removeObserver(observer) } } - // Moves on as the minute turns: nothing here shows seconds. - val now by rememberMinuteClock() - val current = channel.at(now) + // Moves on as the minute turns: nothing here shows seconds. The picture also moves on the moment a programme ends (0.129 + // audit): on the minute alone, the last frame sat on screen for up to a minute (about 45 s seen) before the next began. + val minute by rememberMinuteClock() + var ended by remember(channel.number) { mutableLongStateOf(0L) } + val current = channel.at(maxOf(minute, ended)) + LaunchedEffect(channel.number, current.endMs) { + delay(programmeEndDelayMs(current.endMs, System.currentTimeMillis())) + ended = System.currentTimeMillis() + } var ready by remember(channel.number, current.startMs, live, foreground) { mutableStateOf(false) } // A file that can't play here leaves the artwork up until the next programme. var cantPlay by remember(channel.number, current.startMs) { mutableStateOf(false) } diff --git a/android/app/src/main/java/tv/orbit/classic/LibraryTitles.kt b/android/app/src/main/java/tv/orbit/classic/LibraryTitles.kt new file mode 100644 index 00000000..2b8389d2 --- /dev/null +++ b/android/app/src/main/java/tv/orbit/classic/LibraryTitles.kt @@ -0,0 +1,59 @@ +package tv.orbit.classic + +/** + * Which titles the library has, from the catalogue already on this box (0.129 audit, 11 November 2026). A channel's list + * names dozens of shows and films; before this, each one was a search on the server, found or not: 385 searches for the + * eight first-run channels, and about 2,250 for all 36 at their weekly refresh. A title this index says the library hasn't + * got is skipped without asking the server. + * + * It only answers "no" when that is certain: it's built only from a catalogue that has read the whole library once, for the + * same account, and it matches as loosely as the searches it stands in for ([bestSeriesMatch]: the same title, or that + * title with something after it; [resolveFilm]: the same title). A "yes" still goes to the server as before, so programme + * selection is unchanged. Titles are kept as 64-bit hashes of their keys (about 1 MB for Paul's 132,000 titles); a hash + * collision can only cause a needless search, never a missed one. + */ +internal class LibraryTitles private constructor(private val films: LongArray, private val series: LongArray, private val seriesStarts: LongArray) { + val size get() = films.size + series.size + + /** False only if no film of this title is in the library. [entry] is a channel list entry, such as "Halloween (1978)". */ + fun mayHaveFilm(entry: String): Boolean { + val key = seriesKey(FilmIdentity.of(entry).title) + return key.isBlank() || films.binarySearch(hash(key)) >= 0 + } + + /** False only if no series of this title, or of this title with something after it (Blue Planet II), is in the library. */ + fun mayHaveSeries(title: String): Boolean { + val key = seriesKey(title) + if (key.isBlank()) return true + val h = hash(key) + return series.binarySearch(h) >= 0 || seriesStarts.binarySearch(h) >= 0 + } + + companion object { + /** From (type, title) rows: type is "Movie" or "Series"; anything else is ignored. */ + fun of(rows: Sequence>): LibraryTitles { + val films = HashSet(); val series = HashSet(); val starts = HashSet() + for ((type, title) in rows) { + val key = seriesKey(title) + if (key.isBlank()) continue + when (type) { + "Movie" -> films += hash(key) + "Series" -> { + series += hash(key) + // Every shorter run of whole words it starts with: "blue planet ii" answers for "blue" and "blue planet". + var space = key.indexOf(' ') + while (space > 0) { starts += hash(key.substring(0, space)); space = key.indexOf(' ', space + 1) } + } + } + } + return LibraryTitles(films.toLongArray().apply { sort() }, series.toLongArray().apply { sort() }, starts.toLongArray().apply { sort() }) + } + + /** FNV-1a, 64-bit. */ + internal fun hash(key: String): Long { + var h = -0x340d631b7bdddcdbL + for (c in key) { h = h xor c.code.toLong(); h *= 0x100000001b3L } + return h + } + } +} diff --git a/android/app/src/main/java/tv/orbit/classic/Rooms.kt b/android/app/src/main/java/tv/orbit/classic/Rooms.kt index db8240f6..de94159d 100644 --- a/android/app/src/main/java/tv/orbit/classic/Rooms.kt +++ b/android/app/src/main/java/tv/orbit/classic/Rooms.kt @@ -189,7 +189,7 @@ internal object RoomBundle { .put("people", gzip(files(dir, dir.list().orEmpty().filter { FamilyFiles.matches(it) || GoneFiles.matches(it) }.sorted() + File(dir, "taste").list().orEmpty().filter { TasteFiles.matches(it) }.sorted().map { "taste/$it" }).toString()))) .put(RoomPart.Look.name, prefsJson(context, "orbit_settings", LookKeys)) - .put(RoomPart.Director.name, files(dir, DirectorFiles)) + .put(RoomPart.Director.name, files(dir, DirectorFiles).also { d -> collectionsCopy(dir)?.let { d.put(COLLECTIONS_COPY, it) } }) .put(RoomPart.Arcade.name, prefsJson(context, "orbit_settings", ArcadeKeys)) } @@ -222,7 +222,10 @@ internal object RoomBundle { c.optString("pools").takeIf { it.isNotBlank() }?.let { packed -> runCatching { write(JSONObject(gunzip(packed))) } } lineup = c.optJSONArray("lineup")?.let { a -> (0 until minOf(a.length(), 200)).map { a.getInt(it) } }.orEmpty() } - if (RoomPart.Director in parts) write(bundle.optJSONObject(RoomPart.Director.name)) + if (RoomPart.Director in parts) bundle.optJSONObject(RoomPart.Director.name)?.let { d -> + write(d) + d.optString(COLLECTIONS_COPY).takeIf { it.isNotBlank() }?.let { packed -> runCatching { applyCollectionsCopy(dir, JSONObject(gunzip(packed))) } } + } if (RoomPart.Family in parts) bundle.optJSONObject(RoomPart.Family.name)?.optString("people")?.takeIf { it.isNotBlank() }?.let { packed -> runCatching { mergeFamilyFiles(dir, JSONObject(gunzip(packed))) } } // Only with the channels: a schedule is for a channel that's on. Never over a schedule this box already has. @@ -234,7 +237,31 @@ internal object RoomBundle { } fun limit(text: String) = text.length <= BUNDLE_LIMIT + + /** + * The library's collections, read whole, so a new room doesn't read them all again (0.129 audit: about 3,200 requests + * per TV on Paul's library). Only a finished read travels, and only if it fits well inside the bundle; otherwise the + * new room reads them itself, paced, as before. It then refreshes weekly like any room, changes only. + */ + private fun collectionsCopy(dir: File): String? { + val file = File(dir, "collections-0.jsonl"); val state = File(dir, "collections-0.jsonl.state") + if (!file.isFile || !state.isFile || file.length() > 32L * 1024 * 1024) return null + val finishedAt = runCatching { JSONObject(state.readText()).getLong("finishedAt") }.getOrNull() ?: return null + return gzip(JSONObject().put("list", file.readText()).put("finishedAt", finishedAt).toString()).takeIf { it.length <= COLLECTIONS_COPY_LIMIT } + } + /** Never over collections this box already has. The refresh clock carries over, so the next read is the weekly changes-only one. */ + internal fun applyCollectionsCopy(dir: File, copy: JSONObject) { + val file = File(dir, "collections-0.jsonl") + if (file.exists()) return + val list = copy.getString("list") + require(list.lineSequence().filter { it.isNotBlank() }.all { runCatching { JSONObject(it).getString("id") }.isSuccess }) + writeSafely(file, list) + writeSafely(File(dir, "collections-0.jsonl.state"), JSONObject().put("finishedAt", copy.getLong("finishedAt")).put("reads", 1).toString()) + } } +private const val COLLECTIONS_COPY = "collections" +/** A third of the bundle at most, so the collections can never stop a room joining. */ +private const val COLLECTIONS_COPY_LIMIT = 4 * 1024 * 1024 /** This room's name, and the rooms that have copied it. Kept on this box only. */ internal object Rooms { diff --git a/android/app/src/main/java/tv/orbit/classic/ServerRequests.kt b/android/app/src/main/java/tv/orbit/classic/ServerRequests.kt index 9ed96759..6c912e19 100644 --- a/android/app/src/main/java/tv/orbit/classic/ServerRequests.kt +++ b/android/app/src/main/java/tv/orbit/classic/ServerRequests.kt @@ -98,14 +98,20 @@ internal object BackgroundPacing { const val GAP_MS = 1_500L /** Background requests per TV per hour (Paul: never thousands an hour again). */ const val HOURLY_BUDGET = 600 + /** + * First-run and switch-on channel setup (0.129 audit): not on the hourly budget, since someone is waiting for it, but + * at most one request every [SETUP_GAP_MS], so a library check can't arrive as a burst (230 in 10 seconds before this). + */ + const val SETUP_GAP_MS = 150L private val inBackground = ThreadLocal() + private val inSetup = ThreadLocal() /** This thread is doing the background round's work. */ val active: Boolean get() = inBackground.get() == true internal var clock: () -> Long = System::currentTimeMillis internal var sleep: (Long) -> Unit = { Thread.sleep(it) } private var lastMs = 0L - private var hourStart = 0L - private var used = 0 + /** When each background request of the last hour was sent: the budget is any 60 minutes, not the clock hour (0.129 audit). */ + private val sent = ArrayDeque() /** Runs [block] as background work: its server requests are paced and counted against the hourly budget. */ fun run(block: () -> T): T { @@ -114,20 +120,39 @@ internal object BackgroundPacing { try { return block() } finally { inBackground.set(was) } } + /** Runs [block] as channel setup: its server requests keep [SETUP_GAP_MS] apart, with no hourly budget. */ + fun setup(block: () -> T): T { + val was = inSetup.get() + inSetup.set(true) + try { return block() } finally { inSetup.set(was) } + } + private var lastSetupMs = 0L + private val setupLock = Any() + /** Called before each request; waits its turn for background work, or refuses once the hour's budget is spent. */ fun beforeRequest() { - if (!active) return + if (!active) { + // Its own lock: a background request waiting out its 1.5 s must never hold up setup (seen on the emulator, 0.129 audit). + if (inSetup.get() == true) synchronized(setupLock) { + val wait = lastSetupMs + SETUP_GAP_MS - clock() + if (wait > 0) sleep(wait) + lastSetupMs = clock() + } + return + } synchronized(this) { - val now = clock() - if (now - hourStart >= 60 * 60_000L) { hourStart = now - now % (60 * 60_000L); used = 0 } - if (used >= HOURLY_BUDGET) throw PacedOut() + // Wait first, then count the request when it is actually sent, against the 60 minutes before it (0.129 audit: a + // clock-hour count let one round spend the end of one hour and all of the next, about 1,000 in 60 minutes). + var now = clock() val wait = lastMs + GAP_MS - now - if (wait > 0) sleep(wait) - lastMs = clock(); used++ + if (wait > 0) { sleep(wait); now = clock() } + while (sent.isNotEmpty() && sent.first() <= now - 60 * 60_000L) sent.removeFirst() + if (sent.size >= HOURLY_BUDGET) throw PacedOut() + lastMs = now; sent.addLast(now) } } - internal fun resetForTest() { lastMs = 0; hourStart = 0; used = 0; clock = System::currentTimeMillis; sleep = { Thread.sleep(it) } } - internal fun usedThisHour() = used + internal fun resetForTest() { lastMs = 0; lastSetupMs = 0; sent.clear(); clock = System::currentTimeMillis; sleep = { Thread.sleep(it) } } + @Synchronized internal fun usedThisHour(): Int { val now = clock(); return sent.count { it > now - 60 * 60_000L } } } /** Orbit's version as the server sees it in its logs (0.129: it said 0.110.9 whatever was installed). Set at start. */ diff --git a/android/app/src/test/java/tv/orbit/classic/BenchLiveTest.kt b/android/app/src/test/java/tv/orbit/classic/BenchLiveTest.kt new file mode 100644 index 00000000..ebefe62b --- /dev/null +++ b/android/app/src/test/java/tv/orbit/classic/BenchLiveTest.kt @@ -0,0 +1,74 @@ +package tv.orbit.classic + +import org.junit.After +import org.junit.Assume.assumeTrue +import org.junit.Test +import java.io.File + +/** + * Orbit's own code against the disposable bench Emby on this computer (0.129 audit, 11 November 2026), through the request + * meter. Fictional library and account only; skipped unless asked for: + * ORBIT_BENCH=http://127.0.0.1:18297 ORBIT_BENCH_ACCOUNT= ORBIT_BENCH_CASE= + * ./gradlew :app:testHouseholdDebugUnitTest --tests '*BenchLiveTest*' + * The background limiter runs on a virtual clock, so hours of pacing take minutes; the server's answers and timings are real. + */ +class BenchLiveTest { + private var now = 1_800_000_000_000L + @After fun reset() { EmbyServer.origin = ""; BackgroundPacing.resetForTest() } + + private fun connect(): EmbySampleSession? { + val origin = System.getenv("ORBIT_BENCH")?.let(EmbyServer::normalise) ?: return null + val account = System.getenv("ORBIT_BENCH_ACCOUNT")?.let(::File)?.takeIf { it.isFile } ?: return null + val fields = account.readLines().filter { '=' in it }.associate { it.substringBefore('=') to it.substringAfter('=') } + EmbyServer.origin = origin + BackgroundPacing.clock = { now }; BackgroundPacing.sleep = { now += it } + return EmbyClient(HttpsEmbyTransport("orbit-bench-test", origin)).connect(fields.getValue("EMBY_BENCH_USER"), fields.getValue("EMBY_BENCH_PASSWORD")) + } + private fun case(name: String) = System.getenv("ORBIT_BENCH_CASE") == name + + /** The collections job as the app runs it, an hour between rounds, until the first read and then a weekly refresh finish. */ + @Test fun collections() { + assumeTrue(case("collections")) + val session = connect() ?: return + val store = ScheduleStore(kotlin.io.path.createTempDirectory("bench-collections").toFile()) + val scheduler = ChannelScheduler(store) { now } + val state = File(store.collectionsFile().path + ".state") + fun untilDone(label: String) { + val before = state.takeIf { it.exists() }?.readText(); val started = now; var rounds = 0 + while (state.takeIf { it.exists() }?.readText() == before && rounds < 48) { + BackgroundPacing.run { scheduler.readCollectionsOnly(session, CollectionRefresh(store.collectionsFile())) } + rounds++; now += 60 * 60_000L + } + println("bench $label rounds=$rounds virtualHours=${(now - started) / 3_600_000.0} collections=${store.collectionsFile().readLines().size}") + } + untilDone("collections-first") + now += COLLECTIONS_REFRESH_MS + untilDone("collections-refresh") + session.close() + } + + /** First-run setup for the eight default channels: as 0.129 did it; paced, as a new box does it now; paced with the title index, as a box whose catalogue is complete. */ + @Test fun firstRun() { + assumeTrue(case("firstrun-before") || case("firstrun-paced") || case("firstrun-after")) + val session = connect() ?: return + BackgroundPacing.resetForTest() + val firstRun = SmartChannels.filter { it.number in OnboardStartChannels } + if (case("firstrun-after")) { + val catalogue = object : CatalogueSink { + val rows = mutableListOf>(); var next = 0L + override fun position(userId: String) = next + override fun write(userId: String, records: List, nextStart: Long, total: Long?, finished: Boolean) { records.forEach { rows += it.type to it.title }; next = nextStart } + } + session.importCatalogue(catalogue, CATALOGUE_PAGES_FULL_RUN) + session.libraryTitles = LibraryTitles.of(catalogue.rows.asSequence()) + println("bench catalogue titles=${catalogue.rows.size}") + } + val started = System.currentTimeMillis() + for (p in firstRun) { + val read = runCatching { if (case("firstrun-before")) session.readChannelPool(p, null) else BackgroundPacing.setup { session.readChannelPool(p, null) } } + println("bench ${p.number} ${read.map { "found=${it.series.size}" }.getOrElse { it.javaClass.simpleName }} at=${System.currentTimeMillis() - started}ms") + } + println("bench firstrun skipped=${session.skippedSearches} ms=${System.currentTimeMillis() - started}") + session.close() + } +} diff --git a/android/app/src/test/java/tv/orbit/classic/CollectionScaleTest.kt b/android/app/src/test/java/tv/orbit/classic/CollectionScaleTest.kt new file mode 100644 index 00000000..effaa7ba --- /dev/null +++ b/android/app/src/test/java/tv/orbit/classic/CollectionScaleTest.kt @@ -0,0 +1,135 @@ +package tv.orbit.classic + +import org.json.JSONArray +import org.json.JSONObject +import org.junit.After +import org.junit.Assert.* +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder + +/** + * 0.129 audit, item 2: collections at the scale of Paul's library (about 3,223), on a made-up library with a virtual clock. + * The real collections job and the real background limiter run unchanged; only time is simulated, an hour between rounds. + */ +class CollectionScaleTest { + @get:Rule val tmp = TemporaryFolder() + private var now = 1_800_000_000_000L + @Before fun up() { BackgroundPacing.resetForTest(); BackgroundPacing.clock = { now }; BackgroundPacing.sleep = { now += it } } + @After fun down() { BackgroundPacing.resetForTest() } + + /** A made-up server: [count] collections sorted by name, each with its own number of members. */ + private inner class Server(count: Int) : EmbyTransport { + val sets = (0 until count).map { i -> "%032x".format(0x5e7000000L + i) to (if (i % 400 == 7) 600 else if (i % 50 == 3) 120 else 2 + i % 12) }.toMutableList() + val times = mutableListOf(); var lists = 0; var members = 0 + var failAt: Int? = null + override fun execute(request: EmbyRequest): EmbyReply { + BackgroundPacing.beforeRequest() + times += now + if (failAt == times.size) throw EmbyCheckException("The provider took too long to answer.", retryable = true) + val q = request.path + fun num(k: String) = Regex("$k=(\\d+)").find(q)!!.groupValues[1].toInt() + return if ("IncludeItemTypes=BoxSet" in q) { + lists++ + val page = sets.drop(num("StartIndex")).take(num("Limit")) + EmbyReply(200, JSONObject().put("TotalRecordCount", sets.size).put("Items", JSONArray(page.map { (id, n) -> JSONObject().put("Id", id).put("Name", "Set $id").put("ChildCount", n) })).toString()) + } else { + members++ + val id = Regex("ParentId=(\\w+)").find(q)!!.groupValues[1] + val n = sets.first { it.first == id }.second + val start = num("StartIndex"); val take = minOf(num("Limit"), n - start) + EmbyReply(200, JSONObject().put("TotalRecordCount", n).put("Items", JSONArray((0 until take).map { JSONObject().put("Id", "%032x".format((id.takeLast(8).toLong(16) shl 16) + start + it)) })).toString()) + } + } + fun peak(windowMs: Long) = times.indices.maxOfOrNull { i -> times.count { it in times[i] until times[i] + windowMs } } ?: 0 + } + + private fun scheduler(dir: java.io.File) = ScheduleStore(dir).let { it to ChannelScheduler(it) { now } } + private fun session(t: EmbyTransport) = EmbySampleSession(t, "fixture-token", "fixture-user", EmbySample(listOf(SampleItem("Fixture", "Movie", 90, "mkv", "one")), 1)) + /** Background rounds an hour apart, as the app runs them, until the read finishes. Returns the number of rounds. */ + private fun roundsUntilDone(server: Server, store: ScheduleStore, scheduler: ChannelScheduler, max: Int = 48): Int { + val s = session(server) + val state = java.io.File(store.collectionsFile().path + ".state") + val before = state.takeIf { it.exists() }?.readText() + repeat(max) { round -> + BackgroundPacing.run { scheduler.readCollectionsOnly(s, CollectionRefresh(store.collectionsFile())) } + if (state.exists() && state.readText() != before) return round + 1 + now += 60 * 60_000L + } + fail("never finished"); return -1 + } + private fun lines(store: ScheduleStore) = store.collectionsFile().readLines().map { JSONObject(it) } + + @Test fun firstReadOfThreeThousandCollectionsStaysWithinTheBudgetAndWastesNothing() { + val (store, scheduler) = scheduler(tmp.newFolder()) + val server = Server(3_223) + val start = now + val rounds = roundsUntilDone(server, store, scheduler) + val got = lines(store) + // Every collection once, every member list whole. + assertEquals(3_223, got.size); assertEquals(3_223, got.map { it.getString("id") }.distinct().size); assertTrue(got.all { it.getBoolean("complete") }) + // One list page per 200, one member page per collection (two for the 600s); nothing read twice. + val expectedMembers = server.sets.sumOf { (_, n) -> (n + COLLECTION_PAGE - 1) / COLLECTION_PAGE } + assertEquals(expectedMembers, server.members) + assertTrue("list pages ${server.lists}", server.lists <= 17 + rounds) + // Within the background limits: one request every 1.5 s, at most 600 an hour. + assertTrue("per minute ${server.peak(60_000)}", server.peak(60_000) <= 41); // The budget is per clock hour; a sliding hour that straddles two can see a few more. + assertTrue(server.times.groupingBy { it / 3_600_000 }.eachCount().values.all { it <= BackgroundPacing.HOURLY_BUDGET }) + println("collections first read: requests=${server.times.size} lists=${server.lists} members=${server.members} rounds=$rounds hours=${(now - start) / 3_600_000.0} peakPerMinute=${server.peak(60_000)} peakPerHour=${server.peak(3_600_000)}") + } + + @Test fun anInterruptedReadCarriesOnWhereItStopped() { + val (store, scheduler) = scheduler(tmp.newFolder()) + val server = Server(3_223).apply { failAt = 250 } + roundsUntilDone(server, store, scheduler) + val got = lines(store) + assertEquals(3_223, got.size); assertEquals(3_223, got.map { it.getString("id") }.distinct().size) + // The failed request's page is read again from the collection it stopped at, so at most one page's lists repeat. + val expectedMembers = server.sets.sumOf { (_, n) -> (n + COLLECTION_PAGE - 1) / COLLECTION_PAGE } + assertTrue("members ${server.members} of $expectedMembers", server.members <= expectedMembers + COLLECTIONS_PAGE) + } + + @Test fun theWeeklyRefreshReadsOnlyWhatChanged() { + val (store, scheduler) = scheduler(tmp.newFolder()) + val server = Server(3_223) + roundsUntilDone(server, store, scheduler) + // A week on: 25 collections gain a member and 10 new ones appear (sorted last). + now += COLLECTIONS_REFRESH_MS + for (i in 0 until 25) server.sets[i * 100] = server.sets[i * 100].let { it.first to it.second + 1 } + repeat(10) { server.sets += "%032x".format(0x5e8000000L + it) to 3 } + val before = server.times.size; val listsBefore = server.lists; val membersBefore = server.members + val rounds = roundsUntilDone(server, store, scheduler) + val requests = server.times.size - before + assertEquals(17, server.lists - listsBefore) + assertEquals(35, server.members - membersBefore) + // At most 1,000 collections a round, so four rounds an hour apart. + assertEquals(4, rounds) + assertEquals(3_233, lines(store).size) + println("collections weekly refresh: requests=$requests lists=${server.lists - listsBefore} members=${server.members - membersBefore} rounds=$rounds") + // Nothing more is due until the next week. + now += 24 * 60 * 60_000L + assertFalse(CollectionRefresh(store.collectionsFile()).due(now)) + } + + @Test fun aJoiningRoomTakesTheFinishedListAndOnlyRefreshes() { + val (store, scheduler) = scheduler(tmp.newFolder()) + val server = Server(3_223) + roundsUntilDone(server, store, scheduler) + val dir = store.collectionsFile().parentFile + val copy = JSONObject().put("list", store.collectionsFile().readText()).put("finishedAt", now) + val newRoom = tmp.newFolder() + RoomBundle.applyCollectionsCopy(newRoom, copy) + val refresh = CollectionRefresh(ScheduleStore(newRoom).collectionsFile()) + assertTrue(refresh.complete()); assertFalse(refresh.due(now + 60_000)) + // Never over a list the room already has. + RoomBundle.applyCollectionsCopy(newRoom, JSONObject().put("list", "{\"id\":\"x\"}\n").put("finishedAt", 1L)) + assertEquals(3_223, ScheduleStore(newRoom).collectionsFile().readLines().size) + // A week later its refresh is the changes-only one: 17 list pages, no member reads. + now += COLLECTIONS_REFRESH_MS + val joined = Server(3_223); val (_, roomScheduler) = scheduler(newRoom) + roundsUntilDone(joined, ScheduleStore(newRoom), roomScheduler) + assertEquals(17, joined.lists); assertEquals(0, joined.members) + assertTrue(dir.exists()) + } +} diff --git a/android/app/src/test/java/tv/orbit/classic/GuidePictureTimingTest.kt b/android/app/src/test/java/tv/orbit/classic/GuidePictureTimingTest.kt new file mode 100644 index 00000000..58496c67 --- /dev/null +++ b/android/app/src/test/java/tv/orbit/classic/GuidePictureTimingTest.kt @@ -0,0 +1,13 @@ +package tv.orbit.classic + +import org.junit.Assert.assertEquals +import org.junit.Test + +/** 0.129 audit, item 4: the guide's picture moves on when a programme ends, not when the next minute turns. */ +class GuidePictureTimingTest { + @Test fun waitsUntilTheProgrammeEndsThenALittleMore() { + assertEquals(15_050L, programmeEndDelayMs(endMs = 1_000_000L, nowMs = 985_000L)) + // Already over (the box was busy): straight away. + assertEquals(50L, programmeEndDelayMs(endMs = 1_000_000L, nowMs = 1_200_000L)) + } +} diff --git a/android/app/src/test/java/tv/orbit/classic/LibraryTitlesTest.kt b/android/app/src/test/java/tv/orbit/classic/LibraryTitlesTest.kt new file mode 100644 index 00000000..4fce1087 --- /dev/null +++ b/android/app/src/test/java/tv/orbit/classic/LibraryTitlesTest.kt @@ -0,0 +1,98 @@ +package tv.orbit.classic + +import org.json.JSONArray +import org.json.JSONObject +import org.junit.After +import org.junit.Assert.* +import org.junit.Before +import org.junit.Test + +/** 0.129 audit, item 1: first-run setup skips searches for titles the library hasn't got, and is paced. Fictional titles only. */ +class LibraryTitlesTest { + private var now = 1_000_000L + @Before fun up() { BackgroundPacing.resetForTest(); BackgroundPacing.clock = { now }; BackgroundPacing.sleep = { now += it } } + @After fun down() { BackgroundPacing.resetForTest() } + + private fun titles(vararg rows: Pair) = LibraryTitles.of(rows.asSequence()) + + @Test fun answersNoOnlyWhenTheSearchCouldNotMatch() { + val t = titles("Series" to "Comet Patrol II", "Series" to "The Lantern Files", "Movie" to "Harbour Lights", "Movie" to "Night Bus: Return") + // The same title, or that title with something after it, as bestSeriesMatch accepts. + assertTrue(t.mayHaveSeries("Comet Patrol II")); assertTrue(t.mayHaveSeries("Comet Patrol")); assertTrue(t.mayHaveSeries("comet")) + assertTrue(t.mayHaveSeries("Lantern Files")); assertTrue(t.mayHaveSeries("THE LANTERN FILES!")) + assertFalse(t.mayHaveSeries("Comet Patrol III")); assertFalse(t.mayHaveSeries("Come")); assertFalse(t.mayHaveSeries("Harbour Lights")) + // Films by exact title, as resolveFilm accepts; the year in a list entry doesn't matter here. + assertTrue(t.mayHaveFilm("Harbour Lights (1987)")); assertTrue(t.mayHaveFilm("Night Bus Return")) + assertFalse(t.mayHaveFilm("Harbour")); assertFalse(t.mayHaveFilm("Comet Patrol II")) + // A title with nothing to key on is never ruled out. + assertTrue(t.mayHaveSeries("!!")); assertTrue(t.mayHaveFilm("?")) + } + + /** A fictional library: answers searches by name, and episode lists empty. Records every path asked for. */ + private class Library(val series: List, val films: List) : EmbyTransport { + val paths = mutableListOf() + override fun execute(request: EmbyRequest): EmbyReply { + paths += request.path + val term = Regex("SearchTerm=([^&]+)").find(request.path)?.groupValues?.get(1)?.let { java.net.URLDecoder.decode(it, "UTF-8") } + val type = Regex("IncludeItemTypes=(\\w+)").find(request.path)?.groupValues?.get(1) + val names = when { term == null -> emptyList(); type == "Series" -> series; else -> films } + .filter { it.contains(term ?: "", ignoreCase = true) } + val items = JSONArray(names.mapIndexed { i, name -> JSONObject().put("Id", "%032x".format(name.hashCode().toLong() and 0xffffffffL) + "").put("Name", name).put("Type", type).put("ProductionYear", 1990 + i) }) + return EmbyReply(200, JSONObject().put("Items", items).put("TotalRecordCount", items.length()).toString()) + } + } + private fun session(transport: EmbyTransport) = EmbySampleSession(transport, "fixture-token", "fixture-user", EmbySample(listOf(SampleItem("Fixture", "Movie", 90, "mkv", "one")), 1)) + private val firstRun get() = SmartChannels.filter { it.number in OnboardStartChannels } + + private fun readAll(library: Library, index: LibraryTitles?): List> { + val s = session(library); s.libraryTitles = index + return firstRun.map { p -> p.number to runCatching { s.readChannelPool(p, null).series.size }.getOrDefault(-1) } + } + + @Test fun firstRunAsksOnlyForTitlesTheLibraryHasAndFindsTheSame() { + // Two listed shows per channel are in this library, under their own names; films the same for the film channel. + val listedSeries = firstRun.filter { it.filmRestMs == null }.flatMap { it.searches.take(2) } + val listedFilms = firstRun.filter { it.filmRestMs != null }.flatMap { it.searches.take(2) }.map { FilmIdentity.of(it).title } + val before = Library(listedSeries, listedFilms) + val after = Library(listedSeries, listedFilms) + val index = LibraryTitles.of((listedSeries.map { "Series" to it } + listedFilms.map { "Movie" to it } + (1..500).map { "Movie" to "Bench Film $it" }).asSequence()) + assertEquals(readAll(before, null), readAll(after, index)) + // Everything the library has is still asked about, in the same order; only the misses are gone. + val searches = { l: Library -> l.paths.filter { "SearchTerm=" in it } } + assertEquals(385, searches(before).size) + assertEquals(before.paths.filter { "SearchTerm=" !in it }, after.paths.filter { "SearchTerm=" !in it }) + // 17 of 385: the 16 listed titles it has, and one listed show whose name starts another it has (which the old search also matched). + assertEquals(17, searches(after).size) + assertEquals(searches(before).filter { p -> searches(after).contains(p) }, searches(after)) + } + + @Test fun withoutAFinishedCatalogueEverythingIsSearchedAsBefore() { + val library = Library(emptyList(), emptyList()) + readAll(library, null) + assertEquals(385, library.paths.size) + } + + @Test fun setupRequestsKeepTheirGapButHaveNoHourlyBudget() { + val times = mutableListOf() + BackgroundPacing.setup { repeat(1_000) { BackgroundPacing.beforeRequest(); times += now } } + assertEquals(1_000, times.size) + assertTrue(times.zipWithNext().all { (a, b) -> b - a >= BackgroundPacing.SETUP_GAP_MS }) + // At most 10 s / 150 ms + 1 in any ten seconds: 67, where first run made 230. + val peak = times.indices.maxOf { i -> times.count { it in times[i] until times[i] + 10_000 } } + assertTrue("peak $peak", peak <= 67) + // Outside setup nothing waits. + val before = now; BackgroundPacing.beforeRequest(); assertEquals(before, now) + assertFalse(BackgroundPacing.active) + } + + @Test fun setupNeverWaitsBehindABackgroundRequestsPause() { + BackgroundPacing.resetForTest() // real time: a background request really sleeps its 1.5 s here + val background = Thread { BackgroundPacing.run { BackgroundPacing.beforeRequest(); BackgroundPacing.beforeRequest() } }.apply { start() } + Thread.sleep(200) + val started = System.nanoTime() + BackgroundPacing.setup { BackgroundPacing.beforeRequest() } + val tookMs = (System.nanoTime() - started) / 1_000_000 + background.join() + assertTrue("setup waited $tookMs ms", tookMs < 500) + } +}