"""Persistent shared-key quota: new cookies and worker restarts cannot reset it.""" import sqlite3 import time from contextlib import closing from .protocol import DecisionError class HostedBudget: def __init__(self, path, hourly=60, daily=600): if not 1 <= hourly <= daily <= 10000: raise ValueError("invalid_hosted_budget") self.path, self.hourly, self.daily = str(path), hourly, daily with closing(sqlite3.connect(self.path)) as db, db: db.execute("CREATE TABLE IF NOT EXISTS calls (created REAL, weight INTEGER)") def reserve(self, weight=1): now = time.time() # Synchronous short transaction, no await between checking and reserving. with closing(sqlite3.connect(self.path, timeout=2)) as db, db: db.execute("BEGIN IMMEDIATE") db.execute("DELETE FROM calls WHERE created < ?", (now - 86400,)) daily = db.execute("SELECT COALESCE(SUM(weight),0) FROM calls").fetchone()[0] hourly = db.execute( "SELECT COALESCE(SUM(weight),0) FROM calls WHERE created >= ?", (now - 3600,) ).fetchone()[0] if hourly + weight > self.hourly or daily + weight > self.daily: raise DecisionError("shared_budget_exceeded", 429) db.execute("INSERT INTO calls VALUES (?,?)", (now, weight))