diff --git a/plugins/kosync.koplugin/KOSyncClient.lua b/plugins/kosync.koplugin/KOSyncClient.lua index 6c06971f0..8a4f31e4c 100644 --- a/plugins/kosync.koplugin/KOSyncClient.lua +++ b/plugins/kosync.koplugin/KOSyncClient.lua @@ -134,10 +134,10 @@ function KOSyncClient:update_progress( }) end) if ok then - callback(res.status == 200, res.body) + callback(res.status == 200, res.status, res.body) else logger.dbg("KOSyncClient:update_progress failure:", res) - callback(false, res.body) + callback(false, nil, nil) end end) self.client:enable("AsyncHTTP", {thread = co}) diff --git a/plugins/kosync.koplugin/KOSyncQueue.lua b/plugins/kosync.koplugin/KOSyncQueue.lua new file mode 100644 index 000000000..93c84af8b --- /dev/null +++ b/plugins/kosync.koplugin/KOSyncQueue.lua @@ -0,0 +1,106 @@ +local DataStorage = require("datastorage") +local Persist = require("persist") +local logger = require("logger") + +local QUEUE_PATH = DataStorage:getSettingsDir() .. "/kosync_queue.lua" +local MAX_AGE = 28 * 24 * 3600 -- 4 weeks in seconds +local MAX_ENTRIES = 200 -- paranoia cap + +local KOSyncQueue = {} + +function KOSyncQueue:_storage() + if not self._persist then + self._persist = Persist:new{ path = QUEUE_PATH, codec = "dump" } + end + return self._persist +end + +function KOSyncQueue:load() + local storage = self:_storage() + if not storage:exists() then return {} end + local data, err = storage:load() + if not data then + logger.warn("KOSyncQueue: failed to load queue:", err) + return {} + end + return data +end + +function KOSyncQueue:save(queue) + local ok, err = self:_storage():save(queue) + if not ok then + logger.warn("KOSyncQueue: failed to save queue:", err) + end +end + +--- Queue a failed progress update for later retry. +-- Keeps one entry per document per day (for statistics granularity). +-- Expires entries older than 4 weeks. +function KOSyncQueue:push(item) + local queue = self:load() + local now = os.time() + item.queued_at = now + + local today = math.floor(now / 86400) + + -- Filter: expire old entries, deduplicate same document+same day + local filtered = {} + for _, entry in ipairs(queue) do + local dominated = entry.document == item.document + and math.floor((entry.queued_at or 0) / 86400) == today + if (now - (entry.queued_at or 0)) < MAX_AGE and not dominated then + table.insert(filtered, entry) + end + end + + table.insert(filtered, item) + + -- Paranoia cap: drop oldest + while #filtered > MAX_ENTRIES do + table.remove(filtered, 1) + end + + self:save(filtered) + logger.dbg("KOSyncQueue: queued progress for", item.document, "total:", #filtered) +end + +--- Attempt to send all queued items in order. +-- @param send_func function(item) -> bool: sends one item, returns true on success +-- @return number of successfully sent items +function KOSyncQueue:drain(send_func) + local queue = self:load() + if #queue == 0 then return 0 end + + logger.info("KOSyncQueue: draining", #queue, "queued items") + local sent = 0 + + for i, item in ipairs(queue) do + if send_func(item) then + sent = sent + 1 + else + -- Server still unreachable, keep remaining items + local remaining = {} + for j = i, #queue do + table.insert(remaining, queue[j]) + end + self:save(remaining) + logger.info("KOSyncQueue: sent", sent, ", remaining", #remaining) + return sent + end + end + + -- All sent + self:save({}) + logger.info("KOSyncQueue: sent all", sent, "items") + return sent +end + +function KOSyncQueue:count() + return #self:load() +end + +function KOSyncQueue:clear() + self:save({}) +end + +return KOSyncQueue diff --git a/plugins/kosync.koplugin/main.lua b/plugins/kosync.koplugin/main.lua index d40356533..b4f70806e 100644 --- a/plugins/kosync.koplugin/main.lua +++ b/plugins/kosync.koplugin/main.lua @@ -639,6 +639,9 @@ end function KOSync:logout(menu) self.settings.userkey = nil self.settings.auto_sync = true + -- Clear any queued progress for the old account + local KOSyncQueue = require("KOSyncQueue") + KOSyncQueue:clear() if menu then menu:updateItems() end @@ -736,6 +739,14 @@ function KOSync:updateProgress(ensure_networking, interactive, on_suspend) local progress = self:getLastProgress() local percentage = self:getLastPercent() local chosen_device_name = self.settings.kosync_hostname or Device.model + local queue_item = { + document = doc_digest, + metadata = metadata, + progress = progress, + percentage = percentage, + device = chosen_device_name, + device_id = self.device_id, + } local ok, err = pcall(client.update_progress, client, self.settings.username, @@ -746,23 +757,31 @@ function KOSync:updateProgress(ensure_networking, interactive, on_suspend) percentage, chosen_device_name, self.device_id, - function(ok, body) + function(ok, status, body) logger.dbg("KOSync: [Push] progress to", percentage * 100, "% =>", progress, "for", self.view.document.file) logger.dbg("KOSync: ok:", ok, "body:", body) - if interactive then - if ok then + if ok then + if interactive then UIManager:show(InfoMessage:new{ text = _("Progress has been pushed."), timeout = 3, }) - else - showSyncError() end + else + -- Queue for retry unless it's an auth failure + if status ~= 401 then + local KOSyncQueue = require("KOSyncQueue") + KOSyncQueue:push(queue_item) + end + if interactive then showSyncError() end end end) if not ok then if interactive then showSyncError() end if err then logger.dbg("err:", err) end + -- Network unreachable: queue for retry + local KOSyncQueue = require("KOSyncQueue") + KOSyncQueue:push(queue_item) else -- This is solely for onSuspend's sake, to clear the ghosting left by the "Connected" InfoMessage if on_suspend then @@ -926,14 +945,24 @@ function KOSync:_onCloseDocument() -- and we handle those system focus events via... Suspend & Resume events, so we need to neuter those handlers early. self.onResume = nil self.onSuspend = nil - -- NOTE: Because we'll lose the document instance on return, we need to *block* until the connection is actually up here, - -- we cannot rely on willRerunWhenOnline, because if we're not currently online, - -- it *will* return early, and that means the actual callback *will* run *after* teardown of the document instance - -- (and quite likely ours, too). - NetworkMgr:goOnlineToRun(function() - -- Drop the inner willRerunWhenOnline ;). + -- If we're already online, push normally. + -- Otherwise, queue progress for later instead of blocking with goOnlineToRun. + if NetworkMgr:isOnline() then self:updateProgress(false, false) - end) + else + local doc_digest = self:getDocumentDigest() + if doc_digest then + local KOSyncQueue = require("KOSyncQueue") + KOSyncQueue:push({ + document = doc_digest, + metadata = self:getMetadata(), + progress = self:getLastProgress(), + percentage = self:getLastPercent(), + device = self.settings.kosync_hostname or Device.model, + device_id = self.device_id, + }) + end + end end function KOSync:schedulePeriodicPush() @@ -983,11 +1012,39 @@ end function KOSync:_onNetworkConnected() logger.dbg("KOSync: onNetworkConnected") UIManager:scheduleIn(0.5, function() - -- Network is supposed to be on already, don't wrap this in willRerunWhenOnline + -- Drain any queued progress updates first + self:drainQueue() + -- Then pull as normal self:getProgress(false, false) end) end +function KOSync:drainQueue() + local KOSyncQueue = require("KOSyncQueue") + if KOSyncQueue:count() == 0 then return end + + local KOSyncClient = require("KOSyncClient") + local client = KOSyncClient:new{ + custom_url = self.settings.custom_server, + service_spec = self.path .. "/api.json" + } + + KOSyncQueue:drain(function(item) + local ok = pcall(client.update_progress, + client, + self.settings.username, + self.settings.userkey, + item.document, + item.metadata, + item.progress, + item.percentage, + item.device, + item.device_id, + function() end) + return ok + end) +end + function KOSync:_onNetworkDisconnecting() logger.dbg("KOSync: onNetworkDisconnecting") -- Network is supposed to be on already, don't wrap this in willRerunWhenOnline diff --git a/spec/unit/kosync_queue_spec.lua b/spec/unit/kosync_queue_spec.lua new file mode 100644 index 000000000..f1ca8291b --- /dev/null +++ b/spec/unit/kosync_queue_spec.lua @@ -0,0 +1,164 @@ +describe("KOSyncQueue module", function() + local KOSyncQueue + local orig_time + + setup(function() + require("commonrequire") + package.path = "plugins/kosync.koplugin/?.lua;" .. package.path + KOSyncQueue = require("KOSyncQueue") + end) + + before_each(function() + KOSyncQueue:clear() + orig_time = os.time -- luacheck: ignore + end) + + after_each(function() + KOSyncQueue:clear() + os.time = orig_time -- luacheck: ignore + end) + + it("should start with an empty queue", function() + assert.are.equal(0, KOSyncQueue:count()) + end) + + it("should push and persist an item", function() + KOSyncQueue:push({ + document = "abc123", + progress = "100", + percentage = 0.5, + device = "TestDevice", + device_id = "dev-1", + }) + assert.are.equal(1, KOSyncQueue:count()) + end) + + it("should deduplicate same document on same day", function() + KOSyncQueue:push({ + document = "abc123", + progress = "100", + percentage = 0.5, + device = "TestDevice", + device_id = "dev-1", + }) + KOSyncQueue:push({ + document = "abc123", + progress = "200", + percentage = 0.75, + device = "TestDevice", + device_id = "dev-1", + }) + assert.are.equal(1, KOSyncQueue:count()) + local queue = KOSyncQueue:load() + assert.are.equal("200", queue[1].progress) + end) + + it("should keep entries from different days for same document", function() + -- Push an entry "from yesterday" + local yesterday = os.time() - 86400 + os.time = function() return yesterday end -- luacheck: ignore + KOSyncQueue:push({ + document = "abc123", + progress = "100", + percentage = 0.5, + device = "TestDevice", + device_id = "dev-1", + }) + -- Push an entry "today" + os.time = orig_time -- luacheck: ignore + KOSyncQueue:push({ + document = "abc123", + progress = "200", + percentage = 0.75, + device = "TestDevice", + device_id = "dev-1", + }) + assert.are.equal(2, KOSyncQueue:count()) + end) + + it("should keep different documents on same day", function() + KOSyncQueue:push({ + document = "book1", + progress = "100", + percentage = 0.5, + device = "TestDevice", + device_id = "dev-1", + }) + KOSyncQueue:push({ + document = "book2", + progress = "50", + percentage = 0.25, + device = "TestDevice", + device_id = "dev-1", + }) + assert.are.equal(2, KOSyncQueue:count()) + end) + + it("should expire entries older than 4 weeks", function() + -- Push an entry "5 weeks ago" + local old = os.time() - (35 * 86400) + os.time = function() return old end -- luacheck: ignore + KOSyncQueue:push({ + document = "old_book", + progress = "100", + percentage = 0.5, + device = "TestDevice", + device_id = "dev-1", + }) + -- Push a new entry (triggers expiry filter) + os.time = orig_time -- luacheck: ignore + KOSyncQueue:push({ + document = "new_book", + progress = "50", + percentage = 0.25, + device = "TestDevice", + device_id = "dev-1", + }) + assert.are.equal(1, KOSyncQueue:count()) + local queue = KOSyncQueue:load() + assert.are.equal("new_book", queue[1].document) + end) + + it("should drain successfully", function() + KOSyncQueue:push({ document = "a", progress = "1", percentage = 0.1, device = "D", device_id = "d1" }) + KOSyncQueue:push({ document = "b", progress = "2", percentage = 0.2, device = "D", device_id = "d1" }) + + local sent = KOSyncQueue:drain(function() return true end) + assert.are.equal(2, sent) + assert.are.equal(0, KOSyncQueue:count()) + end) + + it("should stop draining on first failure and keep remaining", function() + KOSyncQueue:push({ document = "a", progress = "1", percentage = 0.1, device = "D", device_id = "d1" }) + KOSyncQueue:push({ document = "b", progress = "2", percentage = 0.2, device = "D", device_id = "d1" }) + KOSyncQueue:push({ document = "c", progress = "3", percentage = 0.3, device = "D", device_id = "d1" }) + + local call_count = 0 + local sent = KOSyncQueue:drain(function() + call_count = call_count + 1 + return call_count <= 1 -- first succeeds, second fails + end) + assert.are.equal(1, sent) + assert.are.equal(2, KOSyncQueue:count()) + end) + + it("should clear the queue", function() + KOSyncQueue:push({ document = "a", progress = "1", percentage = 0.1, device = "D", device_id = "d1" }) + KOSyncQueue:clear() + assert.are.equal(0, KOSyncQueue:count()) + end) + + it("should respect the hard cap", function() + for i = 1, 210 do + -- Different documents to avoid dedup + KOSyncQueue:push({ + document = "book_" .. i, + progress = tostring(i), + percentage = i / 210, + device = "D", + device_id = "d1", + }) + end + assert.is_true(KOSyncQueue:count() <= 200) + end) +end)