File size: 4,166 Bytes
aff259f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
"""
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)