readest/apps/readest.koplugin/readest_syncclient.lua
Huang Xin 4000a85797
fix(koplugin): collect sync workers before KOReader exits (#7293)
* fix(koplugin): collect sync workers before KOReader exits

Exiting KOReader from inside a book quits about a second after the
close-time pushes fork their workers. UIManager:quit() empties the task
queue, so the polls that would collect those workers never run and the
workers keep going after KOReader is gone. The reporter's Kindle often
segfaulted at exit when that happened.

The sync client now keeps the pid of every forked worker (sync RPCs,
book and cover downloads) and wraps UIManager.quit: running workers get
up to 5 s to finish, then the rest are killed and reaped before the
original quit runs.

Verified:
- New syncclient specs: a worker that finishes in the grace period is
  waited for, a stuck one is killed after 50 x 100 ms, and quit doesn't
  wait with no workers. Without the change the first two fail
  ("Expected 3, passed 0" and "Expected 50, passed 0").
- pnpm test:lua (510 passed), pnpm lint:lua.
- Kindle Voyage, firmware 5.13.6, KOReader v2026.07.2-300 (no Turbo),
  exiting from inside the book with auto sync on. origin/main: 2 of 5
  exits left workers running after KOReader was gone (reparented to
  init). This change: 4 of 4 exits logged "waiting for sync workers
  before exit", then killed and reaped the 3 workers still stuck in TLS;
  none outlived KOReader. No segfault in either build on this device, so
  the crash itself was not reproduced.
- Not verified: a worker finishing within the grace period on a device
  (every push on the test network timed out in TLS), and Android.

Fixes #6685. Reported by tramch on GitHub.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(koplugin): deliver finished worker results at exit and keep partial covers out of the cache

Review follow-up for #6685:
- The exit wait reaped a worker that finished inside the grace period
  but never ran its poll, so a token refresh that completed there lost
  its rotated refresh token. Sync RPC workers now register their poll
  with trackWorker, and the exit wait runs it for every worker that has
  finished. Workers that callbacks start then share the same 5 s budget.
- A cover worker killed at exit left a partial <hash>.png that the cover
  cache treats as complete. The worker now writes <hash>.png.part and
  renames it only after a 200; failures remove the .part.

Verified: two new specs fail without this change
("delivers the response of a worker that finishes while KOReader quits":
expected 1 reply, got 0; "keeps a cover under a temporary name until it
is complete": the file was at dst mid-transfer). pnpm test:lua (512
passed), pnpm lint:lua. Not run on the device: the Kindle could not
reach the Readest API at the time (curl timed out after 10 s).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(koplugin): give each cover download worker its own temporary file

Review follow-up for #6685. The manual Download Cover action bypasses
the automatic cover queue, so two workers can download the same cover
at once. With one shared <hash>.png.part, one worker could rename it
while the other was still writing, and the second then reported a
failure. Each worker now writes <hash>.png.<pid>.part.

Verified: "keeps a cover under a temporary name until it is complete"
fails without the change (no h1.png.123.part mid-transfer: expected
"file", got nil). pnpm test:lua (512 passed), pnpm lint:lua.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 16:41:51 +01:00

346 lines
15 KiB
Lua

local UIManager = require("ui/uimanager")
local logger = require("logger")
local socketutil = require("socketutil")
local sporeResponse = require("readest_sporeresponse")
local SyncError = require("readest_syncerror")
-- Sync operation timeouts
local SYNC_TIMEOUTS = { 5, 10 }
local RETRY_TIMEOUTS = { 10, 20 }
local READ_METHODS = { pullChanges = true, pullBooks = true, getDownloadUrl = true, listFiles = true }
local response_seq = 0
local swept_stale_responses = false
-- Forked workers not yet collected, by pid.
local workers = {}
-- LuaSec reports TLS handshake timeouts as "wantread"/"wantwrite";
-- Spore wraps these strings with a source location. Only retry transport
-- failures on read-only RPCs, never an HTTP error or an ambiguous write.
local function isTransientTransportError(err)
local response = sporeResponse(err)
if response then
return response.status == 0 and (response.readest_timeout
or (type(response.body) == "table" and response.body.error == "timeout")) or false
end
if type(err) ~= "string" then return false end
local code = err:match("([^%s:]+)%s*$")
return code == "wantread" or code == "wantwrite" or code == "timeout"
end
local ReadestSyncClient = {
service_spec = nil,
access_token = nil,
}
function ReadestSyncClient:new(o)
if o == nil then o = {} end
setmetatable(o, self)
self.__index = self
if o.init then o:init() end
return o
end
function ReadestSyncClient:init()
local Spore = require("Spore")
self.client = Spore.new_from_spec(self.service_spec)
-- Readest API headers middleware
package.loaded["Spore.Middleware.ReadestHeaders"] = {}
require("Spore.Middleware.ReadestHeaders").call = function(args, req)
req.headers["content-type"] = "application/json"
req.headers["accept"] = "application/json"
end
-- Readest Bearer token auth middleware
package.loaded["Spore.Middleware.ReadestAuth"] = {}
require("Spore.Middleware.ReadestAuth").call = function(args, req)
if args.access_token then
req.headers["authorization"] = "Bearer " .. args.access_token
else
logger.err("ReadestSyncClient:access_token is not set, cannot authenticate")
return false, "Access token is required for Readest API"
end
end
package.loaded["Spore.Middleware.AsyncHTTP"] = require("readest_asynchttp")
end
-- Internal: prepare the Spore client with our standard middleware stack.
-- Call before each RPC.
function ReadestSyncClient:_prepare()
self.client:reset_middlewares()
self.client:enable("Format.JSON")
self.client:enable("ReadestHeaders", {})
-- Sign-in requests (requestDeviceCode, pollDeviceToken) have no token yet.
if self.access_token then
self.client:enable("ReadestAuth", { access_token = self.access_token })
end
end
-- macOS 26+ crashes a fork()ed child in getaddrinfo when an AF_UNSPEC
-- lookup returns only IPv4 addresses (its NAT64 pass, Apple FB21364061,
-- #6933). AF_INET lookups skip that pass, so workers connect over IPv4
-- there. Call in the child before its first request.
function ReadestSyncClient.useIPv4InWorker()
if jit.os ~= "OSX" then return end
local socket = require("socket")
local socketutil = require("socketutil")
-- Keep the timeouts socketutil's own socket.tcp patch applies.
socket.tcp = function()
local sock = socket.tcp4()
sock:settimeout(socketutil.block_timeout, "b")
sock:settimeout(socketutil.total_timeout, "t")
return sock
end
end
-- Workers record their pid here so KOReader's exit can wait for them, with
-- the poll that delivers their result when they have one.
function ReadestSyncClient.trackWorker(pid, collect) workers[pid] = collect or true end
function ReadestSyncClient.untrackWorker(pid) workers[pid] = nil end
-- Exiting from a book quits about a second after the close-time pushes
-- start, before their polls run (#6685). Give running workers up to 5 s:
-- a finished worker's result is delivered here, so a rotated refresh token
-- is still saved. Then kill and collect the rest before KOReader tears
-- down, so no worker outlives it (a Kindle reported segfaults at exit then).
local quit = UIManager.quit
UIManager.quit = function(...)
if next(workers) then
local FFIUtil = require("ffi/util")
logger.info("ReadestSyncClient: waiting for sync workers before exit")
for _ = 1, 50 do
local done = {}
for pid in pairs(workers) do
if FFIUtil.isSubProcessDone(pid) then done[#done + 1] = pid end
end
for _, pid in ipairs(done) do
local collect = workers[pid]
workers[pid] = nil
if type(collect) == "function" then pcall(collect) end
end
if not next(workers) then break end
FFIUtil.usleep(100000)
end
for pid in pairs(workers) do
logger.warn("ReadestSyncClient: killing sync worker", pid, "at exit")
FFIUtil.terminateSubProcess(pid)
FFIUtil.isSubProcessDone(pid, true)
workers[pid] = nil
end
end
return quit(...)
end
-- Internal: dispatch a Spore RPC and invoke `callback(success, body, status)`
-- when the async response arrives. The status is forwarded so callers can
-- distinguish 401/403/404 from generic failure (codex round 1 finding 15).
-- Without Turbo, Spore performs blocking TLS/HTTP even inside a coroutine.
-- Run only the RPC in a child; callbacks always run in the UI process.
function ReadestSyncClient:_dispatchInSubprocess(name, args, timeouts, receive, options)
local FFIUtil = require("ffi/util")
local json = require("json")
-- Stats/notes responses can exceed a pipe buffer; a response file
-- avoids deadlocking a child while the parent waits for its exit.
-- Not os.tmpname: /tmp is unwritable for the app on Android and a
-- small, often full tmpfs on Kindle. The settings dir already holds
-- the access token, so the response is no less private there.
local settings_dir = require("datastorage"):getSettingsDir()
-- A request dispatched while KOReader exits never reaches its poll, so
-- its file outlives the run. Nothing from this run exists before the
-- first request: remove whatever earlier runs left behind.
if not swept_stale_responses then
swept_stale_responses = true
local lfs = require("libs/libkoreader-lfs")
pcall(function()
for name in lfs.dir(settings_dir) do
if name:match("^readest_sync_%d+_%d+%.json$") then
os.remove(settings_dir .. "/" .. name)
end
end
end)
end
response_seq = response_seq + 1
local result_path = string.format("%s/readest_sync_%d_%d.json",
settings_dir, os.time(), response_seq)
local created = io.open(result_path, "wb")
if not created then receive(false, "cannot create sync response file"); return end
created:close()
local pid = FFIUtil.runInSubProcess(function()
-- No exceptions may escape, and _exit avoids inherited graphics
-- driver destructors on Android (same rule as background covers).
pcall(function()
local ok, res = pcall(function()
ReadestSyncClient.useIPv4InWorker()
self:_prepare()
socketutil:set_timeout(timeouts[1], timeouts[2])
return self.client[name](self.client, args)
end)
-- Do not serialize Spore's request object: it includes auth headers.
local raw, reason = sporeResponse(res)
local response = raw and { status = raw.status, body = raw.body,
readest_timeout = raw.readest_timeout, reason = reason } or tostring(res)
local f = assert(io.open(result_path, "wb"))
f:write(json.encode({ ok = ok, response = response }))
f:close()
end)
local ffi = require("ffi")
pcall(ffi.cdef, "void _exit(int status);")
ffi.C._exit(0)
end)
if not pid then
os.remove(result_path)
receive(false, "cannot start sync worker")
return
end
-- Bound every RPC, including DNS stalls. Refreshes pass a longer
-- deadline: the auth coordinator releases UI waiters separately, and a
-- late rotation must still be received unless the worker is truly stuck.
local deadline = os.time() + (options and options.deadline or timeouts[2] + 5)
local timed_out = false
local poll
poll = function()
if not FFIUtil.isSubProcessDone(pid) then
if not timed_out and os.time() >= deadline then
timed_out = true
FFIUtil.terminateSubProcess(pid)
end
UIManager:scheduleIn(0.1, poll)
return
end
ReadestSyncClient.untrackWorker(pid)
local f = io.open(result_path, "rb")
local data = f and f:read("*a")
if f then f:close() end
os.remove(result_path)
if timed_out then receive(false, "timeout"); return end
local ok, result = pcall(json.decode, data or "")
if ok and type(result) == "table" and type(result.ok) == "boolean" then
receive(result.ok, result.response)
else
receive(false, "sync worker returned no response")
end
end
ReadestSyncClient.trackWorker(pid, poll)
UIManager:scheduleIn(0.1, poll)
end
function ReadestSyncClient:_dispatch(name, args, callback, retried)
local timeouts = retried and RETRY_TIMEOUTS or SYNC_TIMEOUTS
local function receive(ok, res)
local response, reason = sporeResponse(res)
if not retried and READ_METHODS[name] and isTransientTransportError(res) then
logger.dbg("ReadestSyncClient:" .. name .. " transient transport timeout; retrying once")
UIManager:scheduleIn(1, function()
self:_dispatch(name, args, callback, true)
end)
elseif ok and response then
callback(response.status == 200, response.body, response.status)
else
response = response or {}
local body = response.body
-- Keep transport errors (timeout, TLS, DNS) and Spore's reason so
-- failure messages can say what went wrong.
if type(body) ~= "table" then
local text = type(body) == "string" and body ~= "" and not body:match("^%s*<") and body
body = { error = text or reason or tostring(res) }
elseif reason and body.reason == nil then
body.reason = reason
end
-- Do not log `res`: Spore's request object carries auth headers.
logger.warn("ReadestSyncClient:" .. name .. " failed:", SyncError.describe(body, response.status))
callback(false, body, response.status)
end
end
if not UIManager.looper then
self:_dispatchInSubprocess(name, args, timeouts, receive)
return
end
self:_prepare()
socketutil:set_timeout(timeouts[1], timeouts[2])
local co = coroutine.create(function()
receive(pcall(function() return self.client[name](self.client, args) end))
end)
self.client:enable("AsyncHTTP", {thread = co, timeout = timeouts[2] + 5})
coroutine.resume(co)
UIManager:setInputTimeout()
socketutil:reset_timeout()
end
function ReadestSyncClient:pullChanges(params, callback)
self:_dispatch("pullChanges", {
since = params.since,
type = params.type,
book = params.book,
meta_hash = params.meta_hash,
limit = params.limit,
}, callback)
end
function ReadestSyncClient:pushChanges(changes, callback)
self:_dispatch("pushChanges", changes or {}, callback)
end
-- pullBooks: incremental fetch of the books table since the watermark.
-- Returns body shape `{ books: [...] }`. Drives Library:open() refresh.
function ReadestSyncClient:pullBooks(params, callback)
self:_dispatch("pullBooks", { since = params.since }, callback)
end
-- getDownloadUrl: resolve a storage fileKey to a signed URL. The server's
-- processFileKeys fallback at apps/readest-app/src/pages/api/storage/
-- download.ts:99-107 lets us send the simple {hash}/{hash}.{ext} variant
-- and have R2 deployments resolve to the actual stored filename
-- transparently. Body shape on success: { downloadUrl }.
function ReadestSyncClient:getDownloadUrl(params, callback)
self:_dispatch("getDownloadUrl", { fileKey = params.fileKey }, callback)
end
-- listFiles: enumerate the rows of the `files` table for a given book
-- hash. Used to discover the EXACT fileKeys (book object + cover.png)
-- before deletion — the DELETE endpoint requires a literal match (no
-- extension fallback like /storage/download has). Body shape on success:
-- { files: [ { file_key, file_size, book_hash, ... } ] }.
function ReadestSyncClient:listFiles(params, callback)
self:_dispatch("listFiles", { bookHash = params.bookHash }, callback)
end
-- deleteFile: remove one storage object plus its `files` row. Caller
-- usually iterates over listFiles output. The `books` row stays put;
-- cleanup of the books table is a separate /sync push (with deletedAt).
function ReadestSyncClient:deleteFile(params, callback)
self:_dispatch("deleteFile", { fileKey = params.fileKey }, callback)
end
-- getUploadUrl: ask the server to issue a presigned PUT URL for a new
-- storage object. Two-step flow (`apps/readest-app/src/pages/api/storage/
-- upload.ts`): server inserts a row in the `files` table for
-- (user, bookHash, fileKey) BEFORE the actual bytes move. Body shape on
-- success: { uploadUrl, fileKey, usage, quota }. Quota-exceeded → 403.
-- The fileName must be the cloud-relative path (eg
-- "Readest/Books/<hash>/<hash>.epub"); the server prepends "<user.id>/"
-- to form the final fileKey.
function ReadestSyncClient:getUploadUrl(params, callback)
self:_dispatch("getUploadUrl", {
fileName = params.fileName,
fileSize = params.fileSize,
bookHash = params.bookHash,
}, callback)
end
-- Sign-in with a code (no access token): the server answers like an OAuth
-- device authorization grant. requestDeviceCode returns { device_code,
-- user_code, verification_uri, verification_uri_complete, expires_in,
-- interval }; pollDeviceToken answers 400 { error = "authorization_pending" }
-- until the code is approved on the web, then a Readest session once.
function ReadestSyncClient:requestDeviceCode(callback)
self:_dispatch("requestDeviceCode", {}, callback)
end
function ReadestSyncClient:pollDeviceToken(device_code, callback)
self:_dispatch("pollDeviceToken", { device_code = device_code, grant = "session" }, callback)
end
return ReadestSyncClient