Files

80 lines
2.7 KiB
Python

"""Configuration, HTTP errors and shared representation helpers."""
import base64
import json
import os
import uuid
from datetime import datetime, timezone
from fastapi import Request
INSTANCE_ID = os.getenv("API_INSTANCE_ID", uuid.uuid4().hex[:12])
SESSION_TTL = int(os.getenv("SESSION_TTL_SECONDS", "3600"))
IDEMPOTENCY_TTL = max(86400, int(os.getenv("IDEMPOTENCY_TTL_SECONDS", "86400")))
class APIError(Exception):
def __init__(self, status: int, code: str, message: str):
super().__init__(message)
self.status = status
self.code = code
self.message = message
def iso(value: datetime) -> str:
return value.astimezone(timezone.utc).isoformat(timespec="microseconds").replace("+00:00", "Z")
def invalid(message: str = "Invalid request") -> APIError:
return APIError(400, "invalid_request", message)
def parse_uuid(value: str) -> str:
try:
return str(uuid.UUID(value))
except (ValueError, TypeError, AttributeError):
raise invalid("Invalid UUID") from None
def parse_limit(raw: str | None) -> int:
if raw is None:
return 50
try:
if not raw.isascii() or not raw.isdecimal():
raise ValueError()
value = int(raw)
except (ValueError, AttributeError):
raise invalid("Invalid limit") from None
if not 1 <= value <= 100:
raise invalid("Invalid limit")
return value
def make_cursor(kind: str, scope: str, created: datetime, ident: str) -> str:
b = json.dumps({"kind": kind, "scope": scope, "created_at": iso(created), "id": ident}, separators=(",", ":")).encode()
return base64.urlsafe_b64encode(b).decode().rstrip("=")
def read_cursor(raw: str | None, kind: str, scope: str):
if raw is None:
return None
try:
if not raw or len(raw) > 2048 or any(ch not in "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_" for ch in raw):
raise ValueError()
data = json.loads(base64.b64decode(raw + "=" * (-len(raw) % 4), altchars=b"-_", validate=True))
if not isinstance(data, dict) or data.get("kind") != kind or data.get("scope") != scope:
raise ValueError()
created = datetime.fromisoformat(data["created_at"].replace("Z", "+00:00"))
if created.tzinfo is None:
raise ValueError()
ident = str(uuid.UUID(data["id"]))
return created, ident
except (ValueError, TypeError, KeyError, UnicodeError, json.JSONDecodeError):
raise invalid("Invalid cursor") from None
def request_id(req: Request) -> str:
return getattr(req.state, "request_id", uuid.uuid4().hex)
def error_body(req: Request, code: str, message: str):
return {"error": {"code": code, "message": message, "request_id": request_id(req)}}