Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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 <T> 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 <T> phase(name: String, job: () -> T): T {
val cpu = SystemClock.currentThreadTimeMillis()
try { return job() } finally { OLog.i("bulk: $name CPU ${SystemClock.currentThreadTimeMillis() - cpu} ms") }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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())
Expand Down Expand Up @@ -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>()
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)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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")
Expand All @@ -189,19 +194,29 @@ class FastCatalogRefresh(
private fun pages(endpoint: String, query: Map<String, String>, 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)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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(),
Expand All @@ -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<String, Entry>, val end: Int)
Expand All @@ -49,12 +50,17 @@ object StatusMarginRepair {
val out = ArrayList<Token>()
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 }
Expand Down Expand Up @@ -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<String>()
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.
Expand All @@ -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() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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? {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<String>()
calls = 0
assertEquals("incomplete coverage", FastCatalogRefresh(store, plan("resume"), {
calls++
mapOf("items" to emptyList<Any>(), "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<String>()
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 {
Expand Down
Loading
Loading