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:
1 parent
8cb7ef5e8b
commit
a6a43b142f
6 files changed
+71
-3
No files matched your search
@@ -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
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user