drpig-web / app /cloud_switch.py
CJR61's picture
D-42 cloud LLM switch (default off) + M-1 HF allowlist + LITE 0.8B manifest (1571424) (prompt_source 60dcc41a)
aff259f verified
Raw History Blame Contribute Delete
4.17 kB
"""
cloud_switch.py — the cloud LLM (OpenAI chat + Whisper) master switch (FR-CLOUD-01…05, D-42, 2026-11-09).
Default OFF and fail-closed: no row, an unreadable row, a broken JSON value or an expired `until` all mean off.
State lives in SQLite `server_meta` (key `cloud_llm`) so it survives Space restarts through the regular backup and
can be flipped from the admin page without touching Space Secrets (which would restart the Space). Reads are cached
for ≤ 5 s; a write clears the cache. Every change is written to `admin_audit`.
"""
from __future__ import annotations
import json
import logging
import time
from datetime import datetime, timedelta, timezone
from sqlalchemy import insert, select
from app import db
from app.db import admin_audit, server_meta
log = logging.getLogger("drpig.cloud")
KEY = "cloud_llm"
CACHE_S = 5.0
MAX_HOURS = 168
_cache: tuple[float, bool] = (0.0, False)
class CloudOff(Exception):
"""The cloud LLM is switched off: callers answer with fixed_replies.cloud_off (or 503 for partners)."""
def _now() -> datetime:
return datetime.now(timezone.utc)
def state() -> dict:
"""Raw stored state (for the admin page). Fail-closed: anything unreadable → disabled."""
try:
with db.read_connection() as conn:
raw = conn.execute(select(server_meta.c.value).where(server_meta.c.key == KEY)).scalar()
if not raw:
return {"enabled": False, "at": None, "by": None, "until": None}
v = json.loads(raw)
enabled = v.get("enabled") is True
until = v.get("until")
if enabled and until:
if datetime.fromisoformat(until) <= _now():
enabled = False
return {"enabled": enabled, "at": v.get("at"), "by": v.get("by"), "until": until}
except Exception as e: # noqa: BLE001 — fail closed
log.warning("cloud switch unreadable → off: %s", e)
return {"enabled": False, "at": None, "by": None, "until": None, "error": "unreadable"}
def is_enabled() -> bool:
global _cache
t = time.monotonic()
if t - _cache[0] < CACHE_S:
return _cache[1]
on = state()["enabled"]
_cache = (t, on)
return on
def require_enabled() -> None:
if not is_enabled():
raise CloudOff("cloud LLM switched off")
def set_enabled(enabled: bool, *, actor: str, ip: str = "", ua: str = "", hours: int | None = None) -> dict:
global _cache
old = state()
now = _now()
until = (now + timedelta(hours=hours)).isoformat() if enabled and hours else None
value = json.dumps({"enabled": bool(enabled), "at": now.isoformat(), "by": actor, "until": until})
with db.engine().begin() as conn:
if conn.execute(select(server_meta.c.key).where(server_meta.c.key == KEY)).first():
conn.execute(server_meta.update().where(server_meta.c.key == KEY).values(value=value))
else:
conn.execute(insert(server_meta).values(key=KEY, value=value))
conn.execute(insert(admin_audit).values(
ts=now.isoformat(), action="cloud_llm.enable" if enabled else "cloud_llm.disable",
old="on" if old["enabled"] else "off", new=("on" if enabled else "off") + (f" until {until}" if until else ""),
actor=actor, ip=ip[:64], ua=ua[:200]))
_cache = (0.0, False)
return state()
def audit_event(action: str, *, actor: str, ip: str = "", ua: str = "", detail: str = "") -> None:
"""Admin actions that spend OpenAI money while the switch is off (`force=1`), FR-CLOUD-04 / security §二 A.1."""
with db.engine().begin() as conn:
conn.execute(insert(admin_audit).values(ts=_now().isoformat(), action=action, old=None, new=detail[:200] or None,
actor=actor, ip=ip[:64], ua=ua[:200]))
def audit(limit: int = 20) -> list[dict]:
with db.read_connection() as conn:
return [dict(r._mapping) for r in conn.execute(
select(admin_audit).order_by(admin_audit.c.id.desc()).limit(max(1, min(limit, 200))))]
def reset_cache() -> None:
"""Tests only."""
global _cache
_cache = (0.0, False)