caelum0x d56639a594
Some checks are pending
build-images / api (push) Waiting to run
build-images / worker-gpu (push) Waiting to run
build-images / web (push) Waiting to run
codeql / Analyze (javascript-typescript) (push) Waiting to run
codeql / Analyze (python) (push) Waiting to run
perf / API hot-path micro-smoke (budgeted) (push) Waiting to run
perf / Desktop engine crates (release build check) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (comfy-workflow-schema) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (effects-core) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (eventbus-types) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (growth-analytics) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (trends-schema) (push) Waiting to run
vision2026-ci / API phase modules (ruff + pytest) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (provider-adapter-kit) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (publishing-connectors) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (render-core) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (shot-template-schema) (push) Waiting to run
vision2026-ci / Python SDK resource tests (push) Waiting to run
vision2026-ci / Desktop engine crates (test + clippy + fmt) (push) Waiting to run
vision2026-ci / Alembic upgrade + drift check (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (caption-engine) (push) Waiting to run
Menivor — open source release (MIT), free to use and fork
Paid, hosted product at menivor.com, now retired as a company project.
Fresh squashed history of the cleaned working tree (secret-scanned,
no .env, no customer data, no outreach logs). Built on
MoneyPrinterTurbo (MIT, harry0703) — see NOTICE.
2026-12-04 02:10:26 +03:00

245 lines
9.6 KiB
Python

"""Per-key spend cap + request rate limiting for the Prism public edge.
A leaked or runaway Prism key is bounded here two independent ways:
* a per-fingerprint **daily spend cap** (integer microdollars, resetting at
midnight UTC), gated through the tested
:func:`app.domains.gateway.provisioning.check_spend` decision core; and
* a per-fingerprint **request rate limit** (a sliding one-minute window).
Both default to *unlimited* so the edge stays opt-in through environment
configuration and existing callers are unaffected until an owner sets a ceiling.
The spend cap is enforced two ways at once and a charge must pass **both**:
* a fast, in-process sliding window that protects a single gateway worker from a
flood even when the durable ledger is momentarily slow; and
* an authoritative sum from the durable settlement ledger (the Mint hold rows the
gateway persists) when one is wired in. Because every worker writes to the same
ledger, this is what makes the daily cap hold *across processes* — a leaked key
can no longer exceed the cap by fanning requests across workers, each of which
would otherwise keep its own in-memory tally. Without a durable source wired in
(ephemeral stores), only the in-process window applies, exactly as before.
The rate limiter's state stays purely in-process and thread-safe: it protects a
single gateway worker from a request flood.
"""
from __future__ import annotations
import os
import threading
from collections import deque
from dataclasses import dataclass, field
from datetime import datetime, timedelta, timezone
from typing import Protocol
from app.domains.gateway.provisioning import (
ProvisioningKey,
SpendDecision,
check_spend,
window_start,
)
class DurableSpendSource(Protocol):
"""Cross-process settlement ledger the daily cap sums for its authoritative check.
``spent_since`` returns the total committed daily spend (integer microdollars)
for one key fingerprint since ``since_epoch`` — the midnight-UTC window start as
a Unix timestamp — read from durable, shared storage so every gateway worker
observes the same running total.
"""
def spent_since(self, owner: str, since_epoch: int) -> int: ...
def _utcnow() -> datetime:
return datetime.now(timezone.utc)
def _env_int(name: str, default: int) -> int:
"""Read a non-negative integer environment override, failing fast if malformed."""
raw = os.getenv(name, "").strip()
if not raw:
return default
try:
value = int(raw)
except ValueError as exc:
raise ValueError(f"{name} must be an integer, got {raw!r}") from exc
if value < 0:
raise ValueError(f"{name} must be non-negative, got {value}")
return value
@dataclass
class _WindowState:
"""A fingerprint's spend within one UTC day window (guarded by the ledger lock)."""
start: datetime
spent_micros: int = 0
committed: set[str] = field(default_factory=set)
class SpendLedger:
"""Per-fingerprint daily (UTC) spend ceiling for leaked-key containment.
``daily_cap_micros == 0`` disables the ceiling (every charge is allowed and no
per-key state is retained). Otherwise each fingerprint accumulates committed
charges until midnight UTC, when the window rolls and the allowance resets.
When a :class:`DurableSpendSource` is attached the cap becomes authoritative
across worker processes: a charge is admitted only if it fits under the cap
both in this worker's in-memory window (the cheap pre-check) and against the
durable ledger's cross-process running total. Without a source the ledger is
in-process only, unchanged from its original behaviour.
"""
def __init__(
self,
daily_cap_micros: int = 0,
*,
spend_source: DurableSpendSource | None = None,
) -> None:
if daily_cap_micros < 0:
raise ValueError("daily_cap_micros must be non-negative")
self._daily_cap_micros = daily_cap_micros
self._lock = threading.Lock()
self._windows: dict[str, _WindowState] = {}
self._spend_source = spend_source
@classmethod
def from_environment(cls) -> "SpendLedger":
return cls(daily_cap_micros=_env_int("PRISM_DAILY_CAP_MICROS", 0))
@property
def enabled(self) -> bool:
return self._daily_cap_micros > 0
@property
def durable(self) -> bool:
"""Whether an authoritative cross-process spend source is wired in."""
return self._spend_source is not None
def attach_spend_source(self, source: DurableSpendSource) -> None:
"""Bind the durable settlement ledger used for the authoritative cap check.
Wiring happens once, at service construction. The in-memory window stays
the fast per-worker pre-check; the source is what makes the cap hold
across worker processes.
"""
self._spend_source = source
def try_reserve(
self,
fingerprint: str,
charge_micros: int,
*,
correlation_id: str,
now: datetime | None = None,
) -> SpendDecision:
"""Atomically gate ``charge_micros`` against the key's daily allowance.
The check and the debit happen under one lock so two concurrent charges
cannot both slip past a nearly-exhausted cap. The commit is idempotent per
``correlation_id`` within the current window, so retrying the same
idempotent request never double-counts against the cap. A denied charge
leaves the ledger untouched; the caller must surface ``429``.
With a :class:`DurableSpendSource` attached the charge must additionally
fit under the cap when measured against the ledger's cross-process total
(summed for the current UTC window). That authoritative check is what
prevents a leaked key from exceeding the cap by fanning across workers; the
in-memory window is only the fast pre-check in front of it. An authoritative
denial never debits the in-memory window.
"""
if charge_micros < 0:
raise ValueError("charge_micros must be non-negative")
if self._daily_cap_micros <= 0:
return SpendDecision(True, -1, "unlimited")
key = ProvisioningKey(
key_id=fingerprint,
owner_id=fingerprint,
daily_cap_micros=self._daily_cap_micros,
)
current_window = window_start(now or _utcnow())
with self._lock:
state = self._windows.get(fingerprint)
if state is None or state.start != current_window:
state = _WindowState(start=current_window)
self._windows[fingerprint] = state
if correlation_id in state.committed:
# Idempotent replay: already counted this request in this window.
return check_spend(key, 0, spent_today_micros=state.spent_micros)
# Fast in-process pre-check: bounds a single worker and short-circuits
# before any durable read when this worker alone is already over cap.
decision = check_spend(
key, charge_micros, spent_today_micros=state.spent_micros
)
if not decision.allow:
return decision
if self._spend_source is not None:
# Authoritative cross-process check: sum spend every worker has
# already committed to the settlement ledger this UTC window.
durable_spent = self._spend_source.spent_since(
fingerprint, int(current_window.timestamp())
)
decision = check_spend(
key, charge_micros, spent_today_micros=durable_spent
)
if not decision.allow:
# Authoritative denial: leave the in-memory window untouched.
return decision
state.spent_micros += charge_micros
state.committed.add(correlation_id)
return decision
class RateLimiter:
"""Per-fingerprint sliding-window request-rate limiter.
``max_requests == 0`` disables limiting. Otherwise at most ``max_requests``
requests are admitted per fingerprint within any ``window_seconds`` interval.
"""
def __init__(self, max_requests: int = 0, window_seconds: int = 60) -> None:
if max_requests < 0:
raise ValueError("max_requests must be non-negative")
if window_seconds <= 0:
raise ValueError("window_seconds must be positive")
self._max_requests = max_requests
self._window = timedelta(seconds=window_seconds)
self._lock = threading.Lock()
self._hits: dict[str, deque[datetime]] = {}
@classmethod
def from_environment(cls) -> "RateLimiter":
window = _env_int("PRISM_RATE_LIMIT_WINDOW_SECONDS", 60) or 60
return cls(
max_requests=_env_int("PRISM_RATE_LIMIT_PER_MINUTE", 0),
window_seconds=window,
)
@property
def enabled(self) -> bool:
return self._max_requests > 0
def allow(self, fingerprint: str, *, now: datetime | None = None) -> bool:
"""Return whether this fingerprint may make one more request right now."""
if self._max_requests <= 0:
return True
moment = now or _utcnow()
cutoff = moment - self._window
with self._lock:
hits = self._hits.get(fingerprint)
if hits is None:
hits = deque()
self._hits[fingerprint] = hits
while hits and hits[0] <= cutoff:
hits.popleft()
if len(hits) >= self._max_requests:
return False
hits.append(moment)
return True