recipe: harden auth/metrics, add rate limiting and tests
This commit is contained in:
@@ -37,10 +37,12 @@ def initialize() -> None:
|
||||
""")
|
||||
connection.execute("CREATE INDEX IF NOT EXISTS idx_requests_started_at ON requests(started_at)")
|
||||
connection.execute("CREATE INDEX IF NOT EXISTS idx_requests_status_code ON requests(status_code)")
|
||||
connection.execute(
|
||||
"CREATE INDEX IF NOT EXISTS idx_requests_client_ip_started_at ON requests(client_ip, started_at)"
|
||||
)
|
||||
|
||||
|
||||
def record(**values) -> None:
|
||||
initialize()
|
||||
columns = [
|
||||
"request_id", "started_at", "client_ip", "user_agent", "method",
|
||||
"path", "image_mime", "image_bytes", "prompt_chars", "status_code",
|
||||
@@ -54,6 +56,21 @@ def record(**values) -> None:
|
||||
)
|
||||
|
||||
|
||||
def count_since(client_ip: str, started_at_from: str) -> int:
|
||||
with sqlite3.connect(db_path()) as connection:
|
||||
row = connection.execute(
|
||||
"""
|
||||
SELECT COUNT(*)
|
||||
FROM requests
|
||||
WHERE client_ip = ?
|
||||
AND started_at >= ?
|
||||
AND path IN ('/receipt', '/receipt/', '/recipe', '/recipe/')
|
||||
""",
|
||||
(client_ip, started_at_from),
|
||||
).fetchone()
|
||||
return int(row[0] if row else 0)
|
||||
|
||||
|
||||
def request_context() -> tuple[str, str, float]:
|
||||
return str(uuid.uuid4()), time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), time.monotonic()
|
||||
|
||||
|
||||
Reference in New Issue
Block a user