0.129 audit: lighter first run, bounded collections, guide picture on time
pauljd/davidson-ci: Davidson CI / quality (push) Failing after 3m5s
pauljd/davidson-ci: Davidson CI / ai-review (push) Failing after 1m54s
release-gate / verify (push) Successful in 11m47s

- First run: listed titles the library hasn't got are skipped using the on-box catalogue
  once it is complete (LibraryTitles); setup requests are paced 150 ms apart on their own
  lock; the background round waits until the first-launch flow is over.
- Background limiter: the hourly budget is any 60 minutes, counted when a request is sent.
- Collections: what was read before the budget ran out is kept; a joining room copies the
  finished list and only does the weekly changes-only refresh.
- Guide picture moves on when a programme ends instead of at the next minute (~45 s held).
- Tests: title index, setup pacing, 3,223-collection simulation, joining room, timing;
  env-gated BenchLiveTest for the local bench server.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-11 16:30:59 +00:00
co-authored by Claude Opus 5.5
parent e72a0f12a4
commit 63109a4804
12 changed files with 541 additions and 47 deletions
@@ -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<CatalogueRecord>, 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<String, LibraryTitles>? = 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.")
}
@@ -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")
}
/**
@@ -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) }
}
}
@@ -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<String, JSONObject>? = null): Pair<List<JSONObject>, Int> {
known: Map<String, JSONObject>? = null): Pair<List<JSONObject>, 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<JSONObject>, 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<String, JSONObject>? = 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<String>(); 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<JSONObject>(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<String, JSONObject>?): 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<String>(); 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<PoolSeries>, 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 <T> 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}")
@@ -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) }
@@ -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<Pair<String, String>>): LibraryTitles {
val films = HashSet<Long>(); val series = HashSet<Long>(); val starts = HashSet<Long>()
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
}
}
}
@@ -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 {
@@ -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<Boolean>()
private val inSetup = ThreadLocal<Boolean>()
/** 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<Long>()
/** Runs [block] as background work: its server requests are paced and counted against the hourly budget. */
fun <T> 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 <T> 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. */