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
60 changes: 54 additions & 6 deletions infra/github-backup/bin/drain_queue.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 <GHB_WORKER_URL>/queue (Authorization: Bearer <GHB_WORKER_BEARER>)
-> {"events": [{"id", "repo", "event", "ts"}]}
GET <GHB_WORKER_URL>/queue[?cursor=...] (Authorization: Bearer <GHB_WORKER_BEARER>)
-> {"events": [{"id", "repo", "event", "ts"}], "cursor": ..., "list_complete": ...}
The drainer follows all pages before applying the ack policy.
POST <GHB_WORKER_URL>/queue/ack {"ids": [...]}
Per-repo coalescing: a repo is fetched at most once per 15 min
(state.json key drain_last::<repo>) — hatch-personal pushes every ~2 min.
Expand Down Expand Up @@ -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__)))
Expand All @@ -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):
Expand All @@ -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
Comment on lines +108 to +110

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Batch acknowledgements after collecting multiple queue pages

When a backlog contains more than 1,000 ackable events, collecting every page makes main() send all their IDs in a single /queue/ack request. That Worker handler performs one awaited KV delete per ID, but Cloudflare limits each invocation to 1,000 KV operations, so the request fails after partially deleting the batch and the drainer exits with an error. Previously, the 500-event polling limit kept acknowledgements below this ceiling. Split acknowledgements into bounded requests so multi-page backlogs can drain successfully.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed: acknowledgements are now sent through ack_events(), which batches ids at ACK_BATCH_SIZE = 500 per /queue/ack request — well under the Worker's 1,000-KV-operation invocation limit — so multi-page backlogs drain completely instead of failing mid-batch. Regression test in test_drain_queue.py case 15: 1,200 ackable events produce 3 bounded ack requests with every event acked (63/63 checks pass).

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.

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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(
{
Expand Down
48 changes: 45 additions & 3 deletions infra/github-backup/tests/test_drain_queue.py
Original file line number Diff line number Diff line change
@@ -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:
Expand Down Expand Up @@ -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,
Expand All @@ -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):
Expand Down Expand Up @@ -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):
Expand Down
13 changes: 10 additions & 3 deletions infra/github-backup/worker/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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.
//
Expand Down Expand Up @@ -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 });
Expand Down
67 changes: 67 additions & 0 deletions infra/github-backup/worker/test/index.test.mjs
Original file line number Diff line number Diff line change
@@ -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);
});