Rate-limit report ingestion per host

Reports arriving sooner than report_min_interval_seconds (default 30) after
the host's previous one are refused with 429 and a Retry-After header. The
check shares the insert's transaction so concurrent requests can't bypass it.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
patrickandClaude Sonnet 5.5 committed 2026-10-29 20:46:09 -04:00
1 parent 8cb7ef5e8b
commit a6a43b142f
6 files changed
+71 -3

No files matched your search

+4
View File
@@ -30,6 +30,8 @@ class Config:
# Package lists older than this make "no updates" untrustworthy.
apt_stale_after_hours: float = 48.0
report_retention_days: int = 30
# A host's reports closer together than this are refused with 429; 0 disables.
report_min_interval_seconds: int = 30
session_hours: int = 12
# Leave on unless you serve the dashboard over plain HTTP on a non-localhost name.
@@ -74,6 +76,8 @@ def load(path: str | None = None) -> Config:
raise SystemExit(f"{path}: stale_after_hours must be positive and finite")
if not math.isfinite(cfg.ntfy_timeout_seconds) or cfg.ntfy_timeout_seconds <= 0:
raise SystemExit(f"{path}: ntfy_timeout_seconds must be positive and finite")
if cfg.report_min_interval_seconds < 0:
raise SystemExit(f"{path}: report_min_interval_seconds must be zero or positive")
if not math.isfinite(cfg.status_alert_after_hours) or cfg.status_alert_after_hours < 0:
raise SystemExit(f"{path}: status_alert_after_hours must be zero or positive and finite")
if any(ord(c) < 32 or ord(c) == 127 for c in cfg.ntfy_url + cfg.ntfy_token):
+12 -2
View File
@@ -127,10 +127,18 @@ def list_hosts(conn: sqlite3.Connection) -> list[sqlite3.Row]:
# --- reports ----------------------------------------------------------------
def add_report(conn: sqlite3.Connection, host: str, payload: dict[str, Any],
retention_days: int) -> None:
retention_days: int, min_interval: int = 0) -> int:
"""Store a report. Returns 0, or the seconds to wait if the host's previous report
is newer than min_interval (nothing is stored then). The check and the insert share
one transaction, so concurrent requests can't both slip past it."""
now = int(time.time())
conn.execute("BEGIN IMMEDIATE")
try:
last = conn.execute("SELECT MAX(received_at) FROM reports WHERE host = ?",
(host,)).fetchone()[0]
if last is not None and 0 <= now - last < min_interval:
conn.execute("ROLLBACK")
return min_interval - (now - last)
conn.execute(
"INSERT INTO reports (host, received_at, payload) VALUES (?, ?, ?)",
(host, now, json.dumps(payload, separators=(",", ":"))),
@@ -140,8 +148,10 @@ def add_report(conn: sqlite3.Connection, host: str, payload: dict[str, Any],
(host, now - retention_days * 86400),
)
conn.execute("COMMIT")
return 0
except BaseException:
conn.execute("ROLLBACK")
if conn.in_transaction:
conn.execute("ROLLBACK")
raise
+5 -1
View File
@@ -334,9 +334,13 @@ class Handler(BaseHTTPRequestHandler):
report = sanitize(json.loads(body))
except (ValueError, ReportError) as exc:
return self.send_json(HTTPStatus.BAD_REQUEST, {"error": str(exc)})
db.add_report(conn, host, report, self.cfg.report_retention_days)
wait = db.add_report(conn, host, report, self.cfg.report_retention_days,
self.cfg.report_min_interval_seconds)
finally:
conn.close()
if wait:
return self.send(HTTPStatus.TOO_MANY_REQUESTS, json.dumps({"error": "reporting too often"}),
"application/json", {"Retry-After": str(wait)})
self.send(HTTPStatus.NO_CONTENT, b"", "text/plain")
# -- auth pages --