diff --git a/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/BulkWork.kt b/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/BulkWork.kt index 5b26cf6d..ef0dca05 100644 --- a/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/BulkWork.kt +++ b/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/BulkWork.kt @@ -38,6 +38,24 @@ object BulkWork { internal fun awaitIdle(blocked: () -> Boolean, wait: () -> Unit) { while (blocked()) { if (Thread.currentThread().isInterrupted) throw InterruptedException(); wait() } } + /** Keep the sole cache writer available to commands while a bulk HTTP page is in flight. */ + internal fun awaitReply(factory: (String, Runnable) -> Thread, commands: () -> Unit, fetch: () -> T): T { + val future = java.util.concurrent.FutureTask(java.util.concurrent.Callable { fetch() }) + val thread = factory("orbit-bulk-page", future) + thread.start() + val started = System.nanoTime() + try { + while (true) { + try { return future.get(100, java.util.concurrent.TimeUnit.MILLISECONDS) } + catch (_: java.util.concurrent.TimeoutException) { + check(System.nanoTime() - started < 90_000_000_000L) { "network no-progress watchdog" } + commands() + } catch (e: java.util.concurrent.ExecutionException) { + throw (e.cause as? Exception ?: e) + } + } + } finally { if (!future.isDone) { future.cancel(true); thread.interrupt() } } + } fun phase(name: String, job: () -> T): T { val cpu = SystemClock.currentThreadTimeMillis() try { return job() } finally { OLog.i("bulk: $name CPU ${SystemClock.currentThreadTimeMillis() - cpu} ms") } diff --git a/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/CacheWorker.kt b/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/CacheWorker.kt index d0c511a4..6bcb027a 100644 --- a/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/CacheWorker.kt +++ b/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/CacheWorker.kt @@ -965,7 +965,9 @@ class CacheWorker( if(plan.limit!=null)storage(StorageAsk("before refresh",plan.limit,plan.coverDir,plan.coversOn)) coverUsage=if(plan.limit!=null)CoverUsage(storageItems(plan.coverDir,plan.coversOn)) else null val fast = FastCatalogRefresh(st, plan, { path -> - val reply = http.get(url(creds, path), headers(creds), null, MAX_BODY) + val reply = BulkWork.awaitReply(threadFactory, yieldTo) { + http.get(url(creds, path), headers(creds), null, MAX_BODY) + } if(reply.code != 200 || reply.body == null) throw FastCatalogRefresh.FetchFailure(reply.body?.size?.toLong() ?: 0L) val body = try { decodeJson(String(reply.body, Charsets.UTF_8)) as? Map<*, *> } catch(_:Exception) { null } ?: throw FastCatalogRefresh.FetchFailure(reply.body.size.toLong()) @@ -1148,7 +1150,7 @@ class CacheWorker( // BATCH): one commit for many replies (a commit on shared storage costs milliseconds), // while the pool keeps fetching from the jobs queued ahead. val batch = ArrayList() - landed.poll(30, TimeUnit.SECONDS)?.let { batch.add(it) } ?: continue + landed.poll(100, TimeUnit.MILLISECONDS)?.let { batch.add(it) } ?: continue val until = clockMs() + BATCH_MS while (batch.size < BATCH && batch.size < inFlight.size) { landed.drainTo(batch, BATCH - batch.size) diff --git a/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/FastCatalogRefresh.kt b/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/FastCatalogRefresh.kt index 09ac38f6..786dfbc1 100644 --- a/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/FastCatalogRefresh.kt +++ b/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/FastCatalogRefresh.kt @@ -136,6 +136,10 @@ class FastCatalogRefresh( outcome = "finished" return outcome } catch (e: Exception) { + if (e.message?.contains("watchdog") == true || e.message == "page total changed during enumeration") { + log("bulk: no-progress watchdog; staged cursor discarded") + set("identity", null) + } set("pct", percent) log("bulk: paused (${e.message?.takeIf { it in setOf("stopped", "storage limit") } ?: "incomplete coverage"}); published generation retained") outcome = if (stopped()) "stopped" else if (e.message == "storage limit") "storage limit" else "incomplete coverage" @@ -163,9 +167,10 @@ class FastCatalogRefresh( } cursor = null; continue } + log("bulk: manifest page=$requests rows=${items(body).size}") val next = body["nextCursor"] as? String val more = body["hasNext"] == true - check(!more || (!next.isNullOrEmpty() && next != cursor && !done("cursor:$next"))) { "manifest cursor did not advance" } + check(!more || (items(body).isNotEmpty() && !next.isNullOrEmpty() && next != cursor && !done("cursor:$next"))) { "manifest no-progress watchdog" } store.transaction { for (book in items(body)) { val id = (book["id"] as? Number)?.toLong() ?: error("manifest id missing") @@ -189,19 +194,29 @@ class FastCatalogRefresh( private fun pages(endpoint: String, query: Map, tag: String, g: Long = generation, onPage: (Map<*, *>) -> Unit = {}, consume: (Map<*, *>, Int) -> Unit) { var page = 1 var total = meta("total:$tag")?.toIntOrNull() ?: 0 + var previousPage = meta("fingerprint:$tag") + var expectedTotal: Int? = meta("total:$tag")?.toIntOrNull() do { + boundary() // Even a durable page hit must yield and honour cancellation. + check(page <= 100_000) { "page watchdog: no completion" } val request = path(endpoint, query + mapOf("page" to page.toString(), "size" to "100")) if (!done(request, g)) { val body = ask(request) val rows = items(body) + val signature = java.util.Base64.getEncoder().encodeToString(java.security.MessageDigest.getInstance("SHA-256").digest(LuaValue.encode(rows))) + check(rows.isEmpty() || previousPage != signature) { "page no-progress watchdog" } + previousPage = signature total = (body["total"] as? Number)?.toInt() ?: rows.size + check(expectedTotal == null || expectedTotal == total) { "page total changed during enumeration" } + expectedTotal = total check(total >= 0 && (rows.isNotEmpty() || (page-1)*100 >= total)) { "incomplete page" } store.transaction { onPage(body) rows.forEachIndexed { i, row -> consume(row, (page-1)*100+i) } - mark(request, g); set("total:$tag", total) + mark(request, g); set("total:$tag", total); set("fingerprint:$tag", signature) } } + log("bulk: page page=$page total=$total") tick(minOf(phaseLimit, percent + 1)) page++ } while ((page-1)*100 < total) diff --git a/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/StatusMarginRepair.kt b/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/StatusMarginRepair.kt index d76062e8..2b88d911 100644 --- a/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/StatusMarginRepair.kt +++ b/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/StatusMarginRepair.kt @@ -8,6 +8,8 @@ import java.security.MessageDigest * Never execute Lua, infer a default, restore horizontal margins, or replace whole settings tables. */ object StatusMarginRepair { + // A settings scan must never own the catalog/command executor. + internal val maintenance = java.util.concurrent.Executors.newSingleThreadExecutor { BulkWork.thread("orbit-repair", it) } private val queued = java.util.concurrent.atomic.AtomicBoolean() @Volatile private var closedReported = false @Volatile private var finished = false @@ -22,7 +24,7 @@ object StatusMarginRepair { if (finished || !queued.compareAndSet(false, true)) return val app = ctx.applicationContext val epoch = bookEpoch - BulkWork.executor.execute { + maintenance.execute { try { val prefs = Prefs(app) val complete = run(android.os.Environment.getExternalStorageDirectory(), @@ -39,7 +41,6 @@ object StatusMarginRepair { internal val bookKeys = setOf("copt_t_page_margin", "copt_b_page_margin", "copt_sync_t_b_page_margins") // The only global key written by the old status controller (onToggleFooterMode). internal val footerKeys = setOf("reader_footer_mode") - private val longOpen = Regex("\\[(=*)\\[") private data class Token(val text: String, val start: Int, val end: Int) private data class Entry(val start: Int, val end: Int, val value: String) private data class Table(val entries: Map, val end: Int) @@ -49,12 +50,17 @@ object StatusMarginRepair { val out = ArrayList() var i = 0 fun longEnd(at: Int): Int? { - val m = longOpen.matchAt(s, at) ?: return null - val end = s.indexOf("]${m.groupValues[1]}]", m.range.last + 1) + if (s.getOrNull(at) != '[') return null + var open = at + 1 + while (s.getOrNull(open) == '=') open++ + if (s.getOrNull(open) != '[') return null + val close = "]" + "=".repeat(open - at - 1) + "]" + val end = s.indexOf(close, open + 1) require(end >= 0) - return end + m.groupValues[1].length + 2 + return end + close.length } while (i < s.length) { + require(out.size < 250_000) { "settings token budget exceeded" } val start = i when { s[i].isWhitespace() -> { i++; continue } @@ -124,17 +130,22 @@ object StatusMarginRepair { return result } - fun run(root: File, checkpoint: () -> Unit, log: (String) -> Unit, target: File? = null, globalRepair: (String, String, String) -> Unit = { _, _, _ -> }, canApply: () -> Boolean = { true }): Boolean { + fun run(root: File, checkpoint: () -> Unit, log: (String) -> Unit, target: File? = null, globalRepair: (String, String, String) -> Unit = { _, _, _ -> }, clock: () -> Long = { System.nanoTime() / 1_000_000 }, canApply: () -> Boolean = { true }): Boolean { val base = root.canonicalFile val done = File(base, "koreader/settings/booksync-w31-repair.done") + val started = clock() + var visited = 0 var deferred = false val seen = HashSet() fun walk(dir: File) { checkpoint() + check(clock() - started < 30_000L) { "status repair scan watchdog" } if (dir.canonicalFile != dir.absoluteFile || !seen.add(dir.path)) return val files = target?.let { arrayOf(it.canonicalFile) } ?: dir.listFiles() ?: error("repair folder unavailable") for (file in files) { checkpoint() + check(clock() - started < 30_000L) { "status repair scan watchdog" } + if (++visited % 100 == 0) log("status repair: scanned $visited entries") if (file.canonicalFile != file.absoluteFile) continue if (file.isDirectory) { // Android app-private trees cannot contain KOReader's external sidecars. @@ -160,6 +171,7 @@ object StatusMarginRepair { val keys = if (global) footerKeys else bookKeys + footerKeys val oldBytes = old.readBytes() val oldText = String(oldBytes, Charsets.ISO_8859_1) + log("status repair: parsing settings bytes=${bytes.size} backupBytes=${oldBytes.size}") val repaired = restore(text, oldText, keys) val id = MessageDigest.getInstance("SHA-256").digest(file.path.toByteArray()).take(6).joinToString("") { "%02x".format(it) } fun notifyGlobal() { diff --git a/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/Worker.kt b/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/Worker.kt index 5f6ce9da..359b1068 100644 --- a/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/Worker.kt +++ b/android/companion/app/src/main/java/net/fledgewing/orbitcompanion/Worker.kt @@ -72,7 +72,10 @@ object Worker { }).also { worker = it } internal fun nativeFooterRepair(before: String, after: String, token: String) { - worker().event(mapOf("kind" to "native_footer_repair", "before" to before, "after" to after, "token" to token)) + synchronized(lock) { + patches.addLast { worker().event(mapOf("kind" to "native_footer_repair", "before" to before, "after" to after, "token" to token)) } + } + start() } private fun creds(i: Intent): CacheWorker.Creds? { diff --git a/android/companion/app/src/test/java/net/fledgewing/orbitcompanion/BulkWorkTest.kt b/android/companion/app/src/test/java/net/fledgewing/orbitcompanion/BulkWorkTest.kt index dff37e33..28d54147 100644 --- a/android/companion/app/src/test/java/net/fledgewing/orbitcompanion/BulkWorkTest.kt +++ b/android/companion/app/src/test/java/net/fledgewing/orbitcompanion/BulkWorkTest.kt @@ -86,6 +86,28 @@ class BulkWorkTest { } } + @Test fun commandsRunWhileBulkNetworkWaitsAndRepairCannotOccupyTheirExecutor() { + val fetching = CountDownLatch(1) + val release = CountDownLatch(1) + var handled = false + val reply = BulkWork.awaitReply({ name, task -> Thread(task, name) }, { + assertTrue(fetching.await(1, TimeUnit.SECONDS)) + handled = true + release.countDown() + }) { fetching.countDown(); assertTrue(release.await(2, TimeUnit.SECONDS)); 42 } + assertTrue(handled) + assertEquals(42, reply) + val repairStarted = CountDownLatch(1) + val repairRelease = CountDownLatch(1) + val command = CountDownLatch(1) + StatusMarginRepair.maintenance.execute { repairStarted.countDown(); repairRelease.await(3, TimeUnit.SECONDS) } + try { + assertTrue(repairStarted.await(1, TimeUnit.SECONDS)) + BulkWork.executor.execute { command.countDown() } + assertTrue(command.await(1, TimeUnit.SECONDS)) + } finally { repairRelease.countDown() } + } + @Test fun repeatedNetUpAndWifiCallbacksShareOneVpnAttemptUntilDisconnect() { val gate = VpnConnectGate() assertFalse(gate.request(false, false)) diff --git a/android/companion/app/src/test/java/net/fledgewing/orbitcompanion/FastCatalogTest.kt b/android/companion/app/src/test/java/net/fledgewing/orbitcompanion/FastCatalogTest.kt index 54bd3953..38c5fd1b 100644 --- a/android/companion/app/src/test/java/net/fledgewing/orbitcompanion/FastCatalogTest.kt +++ b/android/companion/app/src/test/java/net/fledgewing/orbitcompanion/FastCatalogTest.kt @@ -57,6 +57,95 @@ class FastCatalogTest { private fun run(store: CacheStore, op: String = "full", request: (String) -> Map<*, *> = ::reply, progress: (Int)->Unit = {}) = FastCatalogRefresh(store, plan(op), request, {}, {false}, {1000}, progress, { println(it) }).run() + @Test fun resumedManifestWithNoRowsAndAnEndlessCursorFailsCleanly() { + val root = Files.createTempDirectory("bulk-stalled-resume").toFile() + try { + CacheStore(root, {}, ::JdbcSql).use { store -> + var calls = 0 + assertEquals("incomplete coverage", run(store, request = { request -> + if (++calls == 1) mapOf("items" to books.take(1), "hasNext" to true, "nextCursor" to "saved") + else throw CatalogFailure() + })) + assertEquals("saved", store.meta("bulk_stage_cursor")) + val logs = arrayListOf() + calls = 0 + assertEquals("incomplete coverage", FastCatalogRefresh(store, plan("resume"), { + calls++ + mapOf("items" to emptyList(), "hasNext" to true, "nextCursor" to "endless-$calls") + }, {}, { false }, { 1000 }, {}, logs::add).run()) + assertEquals(1, calls) + assertNull(store.meta("bulk_active")) + assertNull(store.meta("bulk_stage_identity")) + assertTrue(logs.any { "no-progress watchdog" in it }) + } + } finally { root.deleteRecursively() } + } + + @Test fun resumedPagingRejectsTheSamePageInsteadOfCountingItAsProgress() { + val root = Files.createTempDirectory("bulk-repeated-page").toFile() + try { + CacheStore(root, {}, ::JdbcSql).use { store -> + val first = reply("$base/sections/libraries?page=1&size=100") + mapOf("total" to 200L) + var pages = 0 + assertEquals("incomplete coverage", run(store, request = { request -> + if (request.contains("/sections/libraries")) { + if (++pages > 1) throw CatalogFailure() + first + } else reply(request) + })) + val logs = arrayListOf() + pages = 0 + assertEquals("incomplete coverage", FastCatalogRefresh(store, plan("resume"), { request -> + if (request.contains("/sections/libraries")) { pages++; first } else reply(request) + }, {}, { false }, { 1000 }, {}, logs::add).run()) + assertEquals("the saved first page is skipped, the repeated second page stops", 1, pages) + assertTrue(logs.any { "no-progress watchdog" in it }) + assertNull(store.meta("bulk_active")) + assertNull(store.meta("bulk_stage_identity")) + } + } finally { root.deleteRecursively() } + } + + @Test fun checkStorageRecheckAndMirrorAdmissionAnswerDuringBlockedBulkPage() { + val root = Files.createTempDirectory("bulk-commands").toFile() + val fetching = java.util.concurrent.CountDownLatch(1) + val release = java.util.concurrent.CountDownLatch(1) + val runs = MirrorRuns { root } + val creds = CacheWorker.Creds("https://books.example/api/v1", "reader", "key") + val p = plan() + var commands = false + val worker = CacheWorker(root, { url, _, _, _ -> + val request = url.substringAfter("https://books.example/api/v1") + if (request.contains("/manifest")) { + fetching.countDown() + check(release.await(3, java.util.concurrent.TimeUnit.SECONDS)) + } + CacheWorker.Reply(200, JSONObject(reply(request)).toString().toByteArray()) + }, log = {}, openSql = ::JdbcSql, onRunState = runs::progress) + try { + assertTrue(runs.admit(p.run, "full", 0, 100)) + runs.started(p.run) + assertEquals("finished", worker.run(p, creds) { + if (!commands && fetching.count == 0L) { + commands = true + worker.check(CacheWorker.Check("dashboard", "$base/dashboard", "open", creds, p.owner)) + worker.storage(CacheWorker.StorageAsk("test", null, null, false)) + worker.recheckCovers("test", creds, emptyList()) + assertFalse(runs.admit("joined", "full", 0, 100)) + val state = LuaValue.parse(File(root, "mirror/run.lua").readBytes()) as Map<*, *> + assertEquals(p.run, state["run"]) + assertEquals("joined", state["query_for"]) + val events = File(root, "events").listFiles()!!.mapNotNull { LuaValue.parse(it.readBytes()) as? Map<*, *> } + assertTrue(events.any { it["kind"] == "checked" }) + assertTrue(events.any { it["kind"] == "storage" }) + assertTrue(events.any { it["kind"] == "covers_rechecked" }) + release.countDown() + } + }) + assertTrue(commands) + } finally { release.countDown(); worker.store.close(); root.deleteRecursively() } + } + @Test fun refreshLogsStartEachPhaseAndFinish() { val root = Files.createTempDirectory("bulk-observable").toFile() try { diff --git a/android/companion/app/src/test/java/net/fledgewing/orbitcompanion/StatusMarginRepairTest.kt b/android/companion/app/src/test/java/net/fledgewing/orbitcompanion/StatusMarginRepairTest.kt index b28c54a7..5101a034 100644 --- a/android/companion/app/src/test/java/net/fledgewing/orbitcompanion/StatusMarginRepairTest.kt +++ b/android/companion/app/src/test/java/net/fledgewing/orbitcompanion/StatusMarginRepairTest.kt @@ -166,6 +166,38 @@ return { } finally { root.deleteRecursively() } } + @Test(timeout = 3000) fun oversizedSettingsTokenStreamStopsWithoutChangingAnyFile() { + val root = Files.createTempDirectory("repair-budget").toFile() + try { + val book = File(root, "Book.sdr/metadata.epub.lua").apply { parentFile!!.mkdirs() } + val text = "return {" + "[1]=1,".repeat(50_000) + "}" + book.writeText(text) + File(book.path + ".old").writeText(lua(15)) + val logs = arrayListOf() + assertTrue(StatusMarginRepair.run(root, {}, logs::add)) + assertEquals(text, book.readText()) + assertTrue(logs.any { "unsupported settings" in it }) + assertFalse(File(book.path + ".booksync-w31.done").exists()) + } finally { root.deleteRecursively() } + } + + @Test fun scanWatchdogStopsWithoutCompletionAndKeepsAlreadyCheckedFiles() { + val root = Files.createTempDirectory("repair-watchdog").toFile() + try { + val book = File(root, "Book.sdr/metadata.epub.lua").apply { parentFile!!.mkdirs(); writeText(lua(10)) } + File(book.path + ".old").writeText(lua(15)) + var time = 0L + try { + StatusMarginRepair.run(root, {}, {}, clock = { time.also { time += 30_001 } }) + fail("scan must stop") + } catch (e: IllegalStateException) { assertEquals("status repair scan watchdog", e.message) } + assertFalse(File(root, "koreader/settings/booksync-w31-repair.done").exists()) + assertEquals(lua(10), book.readText()) + assertTrue(StatusMarginRepair.run(root, {}, {})) + assertEquals(lua(15), book.readText()) + } finally { root.deleteRecursively() } + } + @Test fun interruptionDoesNotMarkMigrationComplete() { val root=Files.createTempDirectory("margin-paused").toFile() try { @@ -174,7 +206,7 @@ return { val source=File("src/main/java/net/fledgewing/orbitcompanion/StatusMarginRepair.kt").readText() assertTrue(source.contains("BulkWork::checkpoint")) assertTrue(source.contains("closedReported && prefs.koreaderBook == \"0\"")) - assertTrue(source.indexOf("BulkWork.executor.execute") < source.indexOf("val complete = run(android.os.Environment")) + assertTrue(source.indexOf("maintenance.execute") < source.indexOf("val complete = run(android.os.Environment")) } finally { root.deleteRecursively() } } } diff --git a/android/koreader/orbit.koplugin/ko/badge.lua b/android/koreader/orbit.koplugin/ko/badge.lua index 6b332806..709e0ad7 100644 --- a/android/koreader/orbit.koplugin/ko/badge.lua +++ b/android/koreader/orbit.koplugin/ko/badge.lua @@ -155,7 +155,7 @@ function Badge.start(manual, s) Badge.notices = {} if Badge.closing then UIManager:unschedule(Badge.closing); Badge.closing = nil end Badge.pct, Badge.text_now, Badge.expanded, Badge.status, Badge.running = math.max(0, tonumber(s and s.pct) or 0), nil, nil, s, true - if manual then orbitNote(Badge.popupText(Badge.pct), Badge.POPUP_S, true) end + if manual then orbitNote(_("Full refresh starting…"), Badge.POPUP_S, true) end Badge.draw() end diff --git a/android/koreader/orbit.koplugin/ko/mirror.lua b/android/koreader/orbit.koplugin/ko/mirror.lua index c2fe9865..c19c3543 100644 --- a/android/koreader/orbit.koplugin/ko/mirror.lua +++ b/android/koreader/orbit.koplugin/ko/mirror.lua @@ -236,15 +236,17 @@ end function Mirror.fullRunning() local s = Mirror.status() return Mirror.active == true and Mirror.busy == true - and (Mirror.op == "full" or Mirror.op == "resume" and s.op == "full" and s.engine == "bulk") + and (Mirror.op == "full" or Mirror.op == "resume" and s.op == "full" and s.engine == "bulk" + or Mirror.manual and s.engine == "bulk") end -- A Full refresh pressed while one is saving: keep that run and show where it is. function Mirror.showProgress(why) local s = Mirror.status() Mirror.manual = true + Mirror.no_ack, Mirror.sent_at, Mirror.queried_at = nil, nowT(), nil log("mirror: Full refresh already running (" .. tostring(why) .. "); kept,", s.done or 0, "of", s.total or 0, "saved") - if not Badge.running then Badge.start(false, s) else Badge.update(s) end + if not Badge.running then Badge.start(true, s) else Badge.update(s) end Badge.expand() end @@ -270,6 +272,7 @@ function Mirror.poll() local s = load("status.lua") if s and s.run == Mirror.run_id then Mirror._status = s end if state and state.run == Mirror.run_id then + Mirror.acknowledged = true if state.state == "stopped" then -- The summary can arrive between our reads above; check once more. local ended = load("summary.lua") @@ -283,9 +286,14 @@ function Mirror.poll() Mirror._status = current end end - -- A stale heartbeat is a reason to ask, never evidence that work stopped. - if not Mirror.queried_at or nowT() - Mirror.queried_at >= Mirror.POLL_S then + if not Mirror.acknowledged and not Mirror.no_ack and nowT() - (Mirror.sent_at or nowT()) >= 6 then + Mirror.no_ack = true + if Mirror.manual then orbitNote(_("BookSync's companion isn't responding · Retry"), 6, true) end + end + -- Back off unanswered liveness queries; local status still polls every three seconds. + if not Mirror.queried_at or nowT() - Mirror.queried_at >= (Mirror.query_wait or Mirror.POLL_S) then Mirror.queried_at = nowT() + Mirror.query_wait = math.min(60, (Mirror.query_wait or Mirror.POLL_S) * 2) Companion.send(Companion.ACTION.MIRROR, { query_run = Mirror.run_id }) end Badge.update(Mirror._status) @@ -349,6 +357,7 @@ function Mirror.launch(op, reason) if coroutine.status(co) ~= "dead" then return UIManager:scheduleIn(0.01, advance) end Mirror.preparing = nil Mirror.run_id, Mirror.queried_at = plan.run, nil + Mirror.sent_at, Mirror.acknowledged, Mirror.no_ack, Mirror.query_wait = nowT(), nil, nil, nil if op == "full" then Mirror._status.run = plan.run OC.writeFile(Mirror.dir() .. "/status.lua", Cache.encode(Mirror._status)) @@ -361,7 +370,7 @@ function Mirror.launch(op, reason) UIManager:nextTick(advance) -- The progress: a Full refresh (or its run resumed) shows the badge; a Refresh's recheck doesn't. if Mirror.manual and op == "full" then Badge.start(true, Mirror._status) - elseif Mirror.manual and op == "resume" and Mirror.status().op == "full" and not Badge.running then Badge.start(false, Mirror.status()) end + elseif Mirror.manual and op == "resume" and Mirror.status().op == "full" and not Badge.running then Badge.start(true, Mirror.status()) end return true end @@ -463,9 +472,9 @@ function Mirror.start(reason, manual) end Mirror.manual = manual if Mirror.busy and not Mirror.preparing and Mirror.status().engine == "bulk" then - -- Finish stopping the owned run before admitting an explicit replacement. - Mirror.next = { op = "full", reason = reason } - OC.writeFile(Mirror.stopFile(), "stop") + -- The companion's bulk catalog already saves the whole catalog. Join its + -- admission instead of waiting silently for a queued incremental run to stop. + if manual then Mirror.showProgress(reason) end return true end if manual and Mirror.preparing then diff --git a/android/koreader/test/test_flows.lua b/android/koreader/test/test_flows.lua index c73b443b..6fb6bf38 100644 --- a/android/koreader/test/test_flows.lua +++ b/android/koreader/test/test_flows.lua @@ -4046,6 +4046,8 @@ test("mirror: missing, queued and stale working states never time out; only comp local client, Cat = cacheSetup() local send = E.Companion.send local queries, launches = 0, 0 + local note, notices = E.orbitNote, {} + E.orbitNote = function(text) notices[#notices + 1] = text end E.Companion.send = function(action, extras) if action == E.Companion.ACTION.MIRROR then if extras.query_run then queries = queries + 1 else launches = launches + 1 end @@ -4056,8 +4058,13 @@ test("mirror: missing, queued and stale working states never time out; only comp E.Mirror._status_dir = E.Mirror.dir() E.Mirror.run_id, E.Mirror.busy, E.Mirror.active = "queued", true, true E.Mirror._status = { engine = "bulk", op = "full", done = 0, total = 100, left = 100 } + E.Mirror.manual, E.Mirror.sent_at = true, W.clock + E.Mirror.acknowledged, E.Mirror.no_ack, E.Mirror.query_wait = nil, nil, nil E.Mirror.poll() run(180) + eq(notices[1], "BookSync's companion isn't responding · Retry") + eq(#notices, 1, "unanswered companion warns once") + ok(queries <= 7, "unanswered liveness queries back off: " .. queries) ok(E.Mirror.busy, "missing acknowledgement is never a timer-only death") local function state(name) E.OC.writeFile(E.Mirror.dir() .. "/run.lua", E.Cache.encode({run="queued", state=name, @@ -4081,7 +4088,7 @@ test("mirror: missing, queued and stale working states never time out; only comp state("stopped"); run(3) ok(not E.Mirror.busy and not E.Mirror.active, "explicit companion stop ends ownership") end) - E.Companion.send = send + E.Companion.send, E.orbitNote = send, note cacheTeardown() ok(success, err) end) @@ -5027,6 +5034,74 @@ test("mirror: pressing Full refresh after a failed bulk run resumes saved progre cacheTeardown() end) +test("mirror: Full refresh joins a stalled incremental job and warns even after a silent background timeout", function() + local client, Cat = cacheSetup() + W.wifi = true + local cat = pluginCatalog(Cat, client) + local note, send = E.orbitNote, E.Companion.send + local notices, launches = {}, 0 + E.orbitNote = function(text) notices[#notices + 1] = text end + E.Companion.send = function(action, extras) + if action == E.Companion.ACTION.MIRROR and not extras.query_run then launches = launches + 1 end + return true + end + local success, err = pcall(function() + withHost(cat, function() + E.Mirror.cat = cat + E.Mirror.active, E.Mirror.busy, E.Mirror.op = true, true, "incremental" + E.Mirror.preparing, E.Mirror.manual = nil, nil + E.Mirror._status_dir = E.Mirror.dir() + E.Mirror._status = { engine = "bulk", op = "incremental", done = 37, total = 100, left = 63, pct = 37 } + E.Mirror.run_id, E.Mirror.sent_at = "background", W.clock + E.Mirror.acknowledged, E.Mirror.no_ack = nil, nil + E.Badge.close(); E.Badge.running = nil + E.Mirror.poll(); run(9) + eq(#notices, 0, "automatic work is silent") + E.OC.fullRefresh(cat) + eq(notices[1], "Full refresh starting…", "joining responds immediately") + eq(E.Badge.pct, 37, "the active job's real progress is shown") + ok(not E.Mirror.next and not E.OC.readFile(E.Mirror.stopFile()), "joining never stops the job") + ok(E.Mirror.fullRunning(), "a joined bulk run owns subsequent taps") + run(9) + eq(notices[2], "BookSync's companion isn't responding · Retry", "the background timeout cannot swallow manual feedback") + E.OC.writeFile(E.Mirror.dir() .. "/run.lua", E.Cache.encode({run="background", state="progress"})) + E.OC.writeFile(E.Mirror.dir() .. "/status.lua", E.Cache.encode({run="background", engine="bulk", op="incremental", pct=60, done=60, total=100, left=40})) + run(3) + eq(E.Badge.pct, 60, "live progress replaces the starting state") + eq(launches, 0, "no duplicate bulk request") + end) + end) + E.orbitNote, E.Companion.send = note, send + cacheTeardown() + ok(success, err) +end) + +test("mirror: an explicit resumed Full refresh shows immediate startup feedback before acknowledgement", function() + local client, Cat = cacheSetup() + W.wifi = true + local cat = pluginCatalog(Cat, client) + local note, send = E.orbitNote, E.Companion.send + local notices = {} + E.orbitNote = function(text) notices[#notices + 1] = text end + E.Companion.send = function() return true end + local success, err = pcall(function() + withHost(cat, function() + E.Mirror.cat = cat + E.Mirror.active, E.Mirror.busy = nil, nil + E.Mirror._status_dir = E.Mirror.dir() + E.Mirror._status = { engine = "bulk", op = "full", done = 15, total = 100, left = 85, pct = 15 } + E.Badge.close(); E.Badge.running = nil + E.OC.fullRefresh(cat) + eq(notices[1], "Full refresh starting…", "the tap responds before any companion work") + ok(E.Badge.running, "saved progress is visible") + eq(E.Badge.pct, 15, "resumed progress is preserved") + end) + end) + E.orbitNote, E.Companion.send = note, send + cacheTeardown() + ok(success, err) +end) + test("mirror: background full runs and resumes never display a badge", function() local client, Cat = cacheSetup() W.wifi = true @@ -5528,7 +5603,7 @@ test("mirror: the Full refresh badge: a popup at the start, then one % that only run(1200) local m = E.Mirror.status() ok(m.at and m.left == 0 and m.total > 450, "finished: " .. tostring(m.done) .. "/" .. tostring(m.total)) - ok(#popups == 1 and popups[1].text:find("^Full refresh in progress · about %d+%% done · you can keep reading and browsing while it loads$"), "one popup: " .. tostring(popups[1] and popups[1].text)) + ok(#popups == 1 and popups[1].text == "Full refresh starting…", "one popup: " .. tostring(popups[1] and popups[1].text)) ok(#notes == 0, "no other note: " .. table.concat(notes, " | ")) local h, last = E.Badge.history, -1 ok(#h > 5, "the % moved along: " .. table.concat(h, " ")) diff --git a/docs/FEATURES.md b/docs/FEATURES.md index c11f3d3a..5d4adcfb 100644 --- a/docs/FEATURES.md +++ b/docs/FEATURES.md @@ -32,7 +32,7 @@ Counts include settings exposure as separate rows; they are not feature quality | Catalog lists, search and detail through the BookOrbit integration | ✅ (v0.11.3-rc.17) Cached catalog adapter. [android/koreader/orbit.koplugin/ko/cache.lua:24](../android/koreader/orbit.koplugin/ko/cache.lua#L24) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Catalog cache and facet queries. [xteink/orbify/CatalogRefresh.inc:31](../xteink/orbify/CatalogRefresh.inc#L31) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Catalog cache and facet queries. [xteink/orbify/CatalogRefresh.inc:31](../xteink/orbify/CatalogRefresh.inc#L31) | 🟡 Online catalog; no BookSync offline cache; **hardware: cache uses PSRAM; X3 flash cuts**. [xteink/tailnet/tailnet_build.py:292](../xteink/tailnet/tailnet_build.py#L292) | | Group every catalog list by series or author | ✅ (v0.11.3-rc.17) Series/author chips and grouped rows. [android/koreader/orbit.koplugin/ko/grouping.lua:40](../android/koreader/orbit.koplugin/ko/grouping.lua#L40) | ❌ Facet lists exist; no group-every-list control; **deliberately deferred: ROADMAP Next 6a**. [xteink/overlay/patches/v2.0/0054-orbify-bulk-catalog.patch:6](../xteink/overlay/patches/v2.0/0054-orbify-bulk-catalog.patch#L6) | ❌ Facet lists exist; no group-every-list control; **deliberately deferred: ROADMAP Next 6a**. [xteink/overlay/patches/v2.0/0054-orbify-bulk-catalog.patch:6](../xteink/overlay/patches/v2.0/0054-orbify-bulk-catalog.patch#L6) | ❌ No grouping control; **hardware: current cached implementation excluded on X3; ROADMAP Next 6a**. [xteink/tailnet/tailnet_build.py:292](../xteink/tailnet/tailnet_build.py#L292) | | Offline catalog pages and retained book details | ✅ (v0.11.3-rc.17) SQLite cache via companion; local window queries. [android/companion/app/src/main/java/net/fledgewing/orbitcompanion/CacheStore.kt:15](../android/companion/app/src/main/java/net/fledgewing/orbitcompanion/CacheStore.kt#L15) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Ranked SD rows serve every refreshed list window without Wi-Fi, independent of source page size. [xteink/orbify/CacheStore.cpp:396](../xteink/orbify/CacheStore.cpp#L396) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Ranked SD rows serve every refreshed list window without Wi-Fi, independent of source page size. [xteink/orbify/CacheStore.cpp:396](../xteink/orbify/CacheStore.cpp#L396) | ❌ Online catalog; no refreshed SD windows; **hardware: X3 flash gate; no PSRAM**. [xteink/tailnet/tailnet_build.py:292](../xteink/tailnet/tailnet_build.py#L292) | -| Explicit resumable Full refresh; monotone percentage | ✅ (v0.11.3-rc.17) Refresh tap always refreshes normally; hold offers Full refresh; companion owns queued/active progress and completion stamps without timer-only failure. [android/companion/app/src/main/java/net/fledgewing/orbitcompanion/Worker.kt:60](../android/companion/app/src/main/java/net/fledgewing/orbitcompanion/Worker.kt#L60) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Refreshed SD lists serve browser windows offline; live list, book and cover counts; finish-time BookSync stamp. [xteink/orbify/RefreshRunner.cpp:32](../xteink/orbify/RefreshRunner.cpp#L32) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Refreshed SD lists serve browser windows offline; live list, book and cover counts; finish-time BookSync stamp. [xteink/orbify/RefreshRunner.cpp:32](../xteink/orbify/RefreshRunner.cpp#L32) | ❌ X3 flash gate; no PSRAM; **hardware: X3 flash gate and no PSRAM exclude the bulk catalog worker and its progress counts; Home sync keeps its finish-time stamp**. [xteink/tailnet/tailnet_build.py:295](../xteink/tailnet/tailnet_build.py#L295) | +| Explicit resumable Full refresh; monotone percentage | ✅ (v0.11.3-rc.17) Refresh tap always refreshes normally; hold offers Full refresh; companion owns queued/active progress and completion stamps without timer-only failure; explicit resumes show immediate startup feedback, missing acknowledgements warn once, and liveness queries back off; Full refresh joins an active incremental bulk run and displays its progress. [android/companion/app/src/main/java/net/fledgewing/orbitcompanion/Worker.kt:60](../android/companion/app/src/main/java/net/fledgewing/orbitcompanion/Worker.kt#L60) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Refreshed SD lists serve browser windows offline; live list, book and cover counts; finish-time BookSync stamp; runs in firmware without an Android companion or companion acknowledgement path. [xteink/orbify/RefreshRunner.cpp:32](../xteink/orbify/RefreshRunner.cpp#L32) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Refreshed SD lists serve browser windows offline; live list, book and cover counts; finish-time BookSync stamp; runs in firmware without an Android companion or companion acknowledgement path. [xteink/orbify/RefreshRunner.cpp:32](../xteink/orbify/RefreshRunner.cpp#L32) | ❌ X3 flash gate; no PSRAM; **hardware: X3 flash gate and no PSRAM exclude the bulk catalog worker and its progress counts; Home sync keeps its finish-time stamp; Android companion acknowledgement and startup-repair recovery do not apply to firmware**. [xteink/tailnet/tailnet_build.py:295](../xteink/tailnet/tailnet_build.py#L295) | | Bulk manifest, derived lists and batched state reconciliation | ✅ (v0.11.3-rc.17) Bulk catalog plan. [android/companion/app/src/main/java/net/fledgewing/orbitcompanion/BulkWork.kt:10](../android/companion/app/src/main/java/net/fledgewing/orbitcompanion/BulkWork.kt#L10) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Bulk catalog derived author/series lists. [xteink/orbify/BulkCatalog.cpp:22](../xteink/orbify/BulkCatalog.cpp#L22) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Bulk catalog derived author/series lists. [xteink/orbify/BulkCatalog.cpp:22](../xteink/orbify/BulkCatalog.cpp#L22) | ❌ X3 flash gate; no PSRAM; **hardware: X3 flash gate; no PSRAM**. [xteink/tailnet/tailnet_build.py:295](../xteink/tailnet/tailnet_build.py#L295) | | Refresh continues away from the catalog; foreground remains usable | ✅ (v0.11.3-rc.17) Companion worker. [android/companion/app/src/main/java/net/fledgewing/orbitcompanion/Worker.kt:17](../android/companion/app/src/main/java/net/fledgewing/orbitcompanion/Worker.kt#L17) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Separate refresh task. [xteink/orbify/RefreshRunner.cpp:38](../xteink/orbify/RefreshRunner.cpp#L38) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Separate refresh task. [xteink/orbify/RefreshRunner.cpp:38](../xteink/orbify/RefreshRunner.cpp#L38) | ❌ X3 flash gate; no PSRAM; **hardware: X3 flash gate; no PSRAM**. [xteink/tailnet/tailnet_build.py:295](../xteink/tailnet/tailnet_build.py#L295) | | Saved pages retained indefinitely; silent incremental refresh | ✅ (v0.11.3-rc.17) Companion reconciliation. [android/companion/app/src/main/java/net/fledgewing/orbitcompanion/Worker.kt:60](../android/companion/app/src/main/java/net/fledgewing/orbitcompanion/Worker.kt#L60), [android/koreader/orbit.koplugin/ko/cache.lua:24](../android/koreader/orbit.koplugin/ko/cache.lua#L24) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Opening does not evict/revalidate; worker incremental requests. [xteink/orbify/CacheStore.cpp:496](../xteink/orbify/CacheStore.cpp#L496), [xteink/orbify/RefreshRunner.cpp:36](../xteink/orbify/RefreshRunner.cpp#L36) | ✅ (xteink-v2.0.0.373+bookorbit.1-rc3) Opening does not evict/revalidate; worker incremental requests. [xteink/orbify/CacheStore.cpp:496](../xteink/orbify/CacheStore.cpp#L496), [xteink/orbify/RefreshRunner.cpp:36](../xteink/orbify/RefreshRunner.cpp#L36) | ❌ X3 flash gate; no PSRAM; **hardware: X3 flash gate; no PSRAM**. [xteink/tailnet/tailnet_build.py:292](../xteink/tailnet/tailnet_build.py#L292) | diff --git a/shared/features.json b/shared/features.json index 2f745c47..3307e521 100644 --- a/shared/features.json +++ b/shared/features.json @@ -197,7 +197,7 @@ "platforms": { "android": { "status": "supported", - "note": "Refresh tap always refreshes normally; hold offers Full refresh; companion owns queued/active progress and completion stamps without timer-only failure", + "note": "Refresh tap always refreshes normally; hold offers Full refresh; companion owns queued/active progress and completion stamps without timer-only failure; explicit resumes show immediate startup feedback, missing acknowledgements warn once, and liveness queries back off; Full refresh joins an active incremental bulk run and displays its progress", "reason": null, "evidence": [ { @@ -209,7 +209,7 @@ }, "x4_pro": { "status": "supported", - "note": "Refreshed SD lists serve browser windows offline; live list, book and cover counts; finish-time BookSync stamp", + "note": "Refreshed SD lists serve browser windows offline; live list, book and cover counts; finish-time BookSync stamp; runs in firmware without an Android companion or companion acknowledgement path", "reason": null, "evidence": [ { @@ -221,7 +221,7 @@ }, "x4": { "status": "supported", - "note": "Refreshed SD lists serve browser windows offline; live list, book and cover counts; finish-time BookSync stamp", + "note": "Refreshed SD lists serve browser windows offline; live list, book and cover counts; finish-time BookSync stamp; runs in firmware without an Android companion or companion acknowledgement path", "reason": null, "evidence": [ { @@ -234,7 +234,7 @@ "x3": { "status": "missing", "note": "X3 flash gate; no PSRAM", - "reason": "hardware: X3 flash gate and no PSRAM exclude the bulk catalog worker and its progress counts; Home sync keeps its finish-time stamp", + "reason": "hardware: X3 flash gate and no PSRAM exclude the bulk catalog worker and its progress counts; Home sync keeps its finish-time stamp; Android companion acknowledgement and startup-repair recovery do not apply to firmware", "evidence": [ { "path": "xteink/tailnet/tailnet_build.py",