Spaces:
Running

File size: 2,351 Bytes
fd5dd94
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Global, per-tenant and per-tool kill switches, checked before every tool call."""

from __future__ import annotations

import uuid

from sqlalchemy import and_, or_, select, update
from sqlalchemy.ext.asyncio import AsyncSession

from core.gateway.models import KillSwitch


async def active_switch(session: AsyncSession, tenant_id: uuid.UUID, tool: str) -> str | None:
    """Return the reason of the first matching enabled switch, or None."""
    row = (
        await session.execute(
            select(KillSwitch.scope, KillSwitch.target, KillSwitch.reason)
            .where(
                KillSwitch.enabled.is_(True),
                or_(
                    and_(KillSwitch.scope == "global"),
                    and_(KillSwitch.scope == "tenant", KillSwitch.target == str(tenant_id)),
                    and_(
                        KillSwitch.scope == "tool",
                        KillSwitch.target == tool,
                        or_(KillSwitch.tenant_id.is_(None), KillSwitch.tenant_id == tenant_id),
                    ),
                ),
            )
            .limit(1)
        )
    ).first()
    if row is None:
        return None
    return f"kill switch ({row.scope}:{row.target}) {row.reason}".strip()


async def set_switch(

    session: AsyncSession,

    *,

    scope: str,

    target: str,

    enabled: bool,

    reason: str = "",

    tenant_id: uuid.UUID | None = None,

) -> None:
    if scope not in {"global", "tenant", "tool"}:
        raise ValueError(f"bad scope {scope}")
    existing = (
        await session.execute(
            select(KillSwitch.id).where(
                KillSwitch.scope == scope,
                KillSwitch.target == target,
                KillSwitch.tenant_id.is_(None)
                if tenant_id is None
                else KillSwitch.tenant_id == tenant_id,
            )
        )
    ).scalar_one_or_none()
    if existing:
        await session.execute(
            update(KillSwitch)
            .where(KillSwitch.id == existing)
            .values(enabled=enabled, reason=reason)
        )
    else:
        session.add(
            KillSwitch(
                tenant_id=tenant_id, scope=scope, target=target, enabled=enabled, reason=reason
            )
        )
    await session.flush()