diff --git a/infra/github-backup/bin/drain_queue.py b/infra/github-backup/bin/drain_queue.py index 963155a0bd..2cd915437a 100644 --- a/infra/github-backup/bin/drain_queue.py +++ b/infra/github-backup/bin/drain_queue.py @@ -3,8 +3,9 @@ The Cloudflare Worker (../worker) receives GitHub App webhooks, validates the HMAC, and stores events in KV. This drainer (timer: every 5 min): - GET /queue (Authorization: Bearer ) - -> {"events": [{"id", "repo", "event", "ts"}]} + GET /queue[?cursor=...] (Authorization: Bearer ) + -> {"events": [{"id", "repo", "event", "ts"}], "cursor": ..., "list_complete": ...} + The drainer follows all pages before applying the ack policy. POST /queue/ack {"ids": [...]} Per-repo coalescing: a repo is fetched at most once per 15 min (state.json key drain_last::) — hatch-personal pushes every ~2 min. @@ -40,7 +41,7 @@ The allowlist fails closed: no owners in config, nothing is fetched. """ -import json, os, sys, time, urllib.request +import json, os, sys, time, urllib.request, urllib.parse from datetime import datetime, timezone sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) @@ -49,6 +50,10 @@ COALESCE_S = 15 * 60 CHRONIC_DRAIN_FAILURES = 5 +# The Worker performs one KV delete per acked id, and Cloudflare caps an +# invocation at 1,000 KV operations — acks are sent in batches well +# under that ceiling so a multi-page backlog can always drain. +ACK_BATCH_SIZE = 500 def worker_req(path, payload=None): @@ -68,6 +73,50 @@ def worker_req(path, payload=None): return json.loads(r.read() or b"{}") +def ack_events(cfg, ids): + """Acknowledge ids in bounded batches (ACK_BATCH_SIZE per request). + + A single /queue/ack request carrying a whole multi-page backlog + exceeds the Worker's per-invocation KV-operation limit once more + than ~1,000 events are ackable; the Worker then fails mid-batch + after partially deleting it. Bounded requests drain any backlog. + """ + path = cfg["worker"]["queue_poll_path"] + "/ack" + for i in range(0, len(ids), ACK_BATCH_SIZE): + worker_req(path, {"ids": ids[i:i + ACK_BATCH_SIZE]}) + + +def queue_events(queue_poll_path): + """Read every Worker KV page before applying the existing ack policy. + + Older Worker responses without pagination metadata remain a one-page + response. An incomplete/malformed cursor fails closed before any event + from this poll can be acknowledged. + """ + events = [] + cursor = None + seen_cursors = set() + while True: + path = queue_poll_path + if cursor is not None: + sep = "&" if "?" in path else "?" + path += sep + urllib.parse.urlencode({"cursor": cursor}) + page = worker_req(path) + page_events = page.get("events", []) + if not isinstance(page_events, list): + raise RuntimeError("Worker queue response events must be a list") + events.extend(page_events) + if page.get("list_complete", True): + return events + next_cursor = page.get("cursor") + if not isinstance(next_cursor, str) or not next_cursor: + raise RuntimeError("Worker queue response is incomplete but has no cursor") + if next_cursor in seen_cursors: + raise RuntimeError("Worker queue pagination cursor repeated") + seen_cursors.add(next_cursor) + cursor = next_cursor + + def event_age_s(ev, now): """Age of a queued event in seconds, or None if its ts is unusable. @@ -143,8 +192,7 @@ def main(): root = backup_root(cfg) state_path = os.path.join(root, "state.json") state = json.load(open(state_path)) if os.path.exists(state_path) else {} - q = worker_req(cfg["worker"]["queue_poll_path"]) - events = q.get("events", []) + events = queue_events(cfg["worker"]["queue_poll_path"]) if not events: print("queue empty") return 0 @@ -233,7 +281,7 @@ def log(line): with open(state_path, "w") as f: json.dump(state, f, indent=0) if ack: - worker_req(cfg["worker"]["queue_poll_path"] + "/ack", {"ids": ack}) + ack_events(cfg, ack) print( json.dumps( { diff --git a/infra/github-backup/tests/test_drain_queue.py b/infra/github-backup/tests/test_drain_queue.py index 530a53c093..612cf95fc5 100644 --- a/infra/github-backup/tests/test_drain_queue.py +++ b/infra/github-backup/tests/test_drain_queue.py @@ -1,6 +1,6 @@ #!/usr/bin/env python3 -"""test_drain_queue.py — regression tests for #3219 ack discipline -and the #3326 owner allowlist. +"""test_drain_queue.py — regression tests for #3219 ack discipline, +the #3326 owner allowlist, and #3476 pagination. Drives the real drain_queue.main() with a stub Worker and a stub fetch_mirrors.fetch_repo, against a temp backup root: @@ -49,6 +49,8 @@ def __init__(self, events, planned, fetch_results, initial_state=None): self.fetch_results = fetch_results # repo -> "ok"|"fail"|"missing" self.fetch_calls = [] self.ack_calls = [] + self.queue_paths = [] + self.queue_pages = None self._saved = ( drain_queue.worker_req, drain_queue.load_config, @@ -69,6 +71,9 @@ def _worker_req(self, path, payload=None): if path.endswith("/ack"): self.ack_calls.append(payload["ids"]) return {} + self.queue_paths.append(path) + if self.queue_pages is not None: + return self.queue_pages[path] return {"events": self.events} def _fetch_repo(self, root, repo, state): @@ -296,7 +301,44 @@ def check(name, cond): ) check("foreign-chronic: no DRAIN-CHRONIC", "DRAIN-CHRONIC" not in h.fetch_log()) -# 14. non-dict repository.owner (#3331): a string/list/number/bool owner is + +# 14. cursor pagination reaches healthy events beyond 500 retained failures; +# only the successful repository is acked. +failing_events = [ev(f"failed-{i}", "owner/failing") for i in range(500)] +healthy_event = ev("healthy-later", "owner/healthy") +h = Harness([], ["owner/failing", "owner/healthy"], + {"owner/failing": "fail", "owner/healthy": "ok"}) +h.queue_pages = { + "/queue": {"events": failing_events, "cursor": "page two/+", "list_complete": False}, + "/queue?cursor=page+two%2F%2B": { + "events": [healthy_event], "cursor": None, "list_complete": True}, +} +buf = io.StringIO() +with contextlib.redirect_stdout(buf): + rc = h.run() +check("pagination: exit 0", rc == 0) +check("pagination: requests both cursor pages", + h.queue_paths == ["/queue", "/queue?cursor=page+two%2F%2B"]) +check("pagination: healthy later repo fetched", "owner/healthy" in h.fetch_calls) +check("pagination: all retained failures stay unacked", + h.acked_ids() == ["healthy-later"]) +summary = json.loads(buf.getvalue().strip().splitlines()[-1]) +check("pagination: all 501 events handled in one run", summary["events"] == 501) + + +# 15. multi-page backlog: acks are batched under the Worker KV ceiling. +# 1,200 ackable (unplanned) events must arrive as bounded /queue/ack +# requests — never one request over the 1,000-KV-operation limit. +h = Harness([ev(f"bulk-{i}", f"owner/bulk-{i}") for i in range(1200)], [], {}) +check("ack batching: exit 0", h.run() == 0) +check("ack batching: every event acked", len(h.acked_ids()) == 1200) +check("ack batching: no request exceeds the batch bound", + all(len(call) <= drain_queue.ACK_BATCH_SIZE for call in h.ack_calls)) +check("ack batching: backlog split across multiple requests", + len(h.ack_calls) == 3) + + +# 16. non-dict repository.owner (#3331): a string/list/number/bool owner is # not a container — event_owner must not raise; with no other owner # source it yields None and the event is dropped + acked, never fetched for bad_owner in ("dezren39", ["dezren39"], 42, True): diff --git a/infra/github-backup/worker/src/index.js b/infra/github-backup/worker/src/index.js index 2f3fda92e9..55d2f4a852 100644 --- a/infra/github-backup/worker/src/index.js +++ b/infra/github-backup/worker/src/index.js @@ -3,7 +3,7 @@ // POST /github GitHub webhook. Verifies X-Hub-Signature-256 (HMAC // SHA-256 with GITHUB_WEBHOOK_SECRET), stores // {id, repo, event, action, ts} in KV (TTL 7 days). -// GET /queue Bearer DRAIN_BEARER. Returns pending events. +// GET /queue Bearer DRAIN_BEARER. Returns a page; ?cursor follows. // POST /queue/ack Bearer DRAIN_BEARER. Body {"ids":[...]} deletes them. // GET /health Liveness. // @@ -52,13 +52,20 @@ export default { } if (url.pathname === "/queue" && req.method === "GET") { if (!authed(req, env)) return new Response("unauthorized", { status: 401 }); - const list = await env.GHB_EVENTS.list({ prefix: "ev:", limit: 500 }); + const cursor = url.searchParams.get("cursor"); + const options = { prefix: "ev:", limit: 500 }; + if (cursor) options.cursor = cursor; + const list = await env.GHB_EVENTS.list(options); const events = []; for (const k of list.keys) { const v = await env.GHB_EVENTS.get(k.name); if (v) events.push(JSON.parse(v)); } - return Response.json({ events }); + return Response.json({ + events, + cursor: list.cursor || null, + list_complete: list.list_complete, + }); } if (url.pathname === "/queue/ack" && req.method === "POST") { if (!authed(req, env)) return new Response("unauthorized", { status: 401 }); diff --git a/infra/github-backup/worker/test/index.test.mjs b/infra/github-backup/worker/test/index.test.mjs new file mode 100644 index 0000000000..ae2347ed61 --- /dev/null +++ b/infra/github-backup/worker/test/index.test.mjs @@ -0,0 +1,67 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import worker from "../src/index.js"; + +test("GET /queue forwards cursor and exposes KV pagination metadata", async () => { + const listCalls = []; + const values = new Map([ + ["ev:first", JSON.stringify({ id: "first", repo: "owner/first" })], + ["ev:second", JSON.stringify({ id: "second", repo: "owner/second" })], + ]); + const kv = { + async list(options) { + listCalls.push(options); + if (options.cursor === "page two/+") { + return { + keys: [{ name: "ev:second" }], + cursor: null, + list_complete: true, + }; + } + return { + keys: [{ name: "ev:first" }], + cursor: "page two/+", + list_complete: false, + }; + }, + async get(name) { + return values.get(name) ?? null; + }, + }; + const env = { GHB_EVENTS: kv, DRAIN_BEARER: "test-bearer" }; + const request = (cursor) => new Request( + "https://worker.test/queue" + (cursor === undefined + ? "" : "?cursor=" + encodeURIComponent(cursor)), + { headers: { Authorization: "Bearer test-bearer" } }, + ); + + const first = await worker.fetch(request(undefined), env); + assert.equal(first.status, 200); + assert.deepEqual(await first.json(), { + events: [{ id: "first", repo: "owner/first" }], + cursor: "page two/+", + list_complete: false, + }); + + const second = await worker.fetch(request("page two/+"), env); + assert.equal(second.status, 200); + assert.deepEqual(await second.json(), { + events: [{ id: "second", repo: "owner/second" }], + cursor: null, + list_complete: true, + }); + assert.deepEqual(listCalls, [ + { prefix: "ev:", limit: 500 }, + { prefix: "ev:", limit: 500, cursor: "page two/+" }, + ]); +}); + +test("GET /queue still requires the bearer token", async () => { + let listed = false; + const response = await worker.fetch( + new Request("https://worker.test/queue"), + { GHB_EVENTS: { async list() { listed = true; return { keys: [] }; } }, DRAIN_BEARER: "secret" }, + ); + assert.equal(response.status, 401); + assert.equal(listed, false); +});