Files
smeta-web/gateway.py
T
anorandClaude Code 9254155797 feat(проверка): шлюз модели, HTTP-инструменты, ручки, уборка, уведомления, отчёт (T2–T4, T7–T10)
- T2: шлюз к модели — одна дверь, привязка расхода к проверке или диалогу, пределы ДО
  вызова, атомарная бронь под замком, заготовка строки расхода и закрытие фактическими
  числами, обрыв/таймаут оставляют бронь, пауза по суточному пределу и возврат в работу.
- T3: инструменты по HTTP (JSON-RPC) — замороженный перечень 15 имён, права на каждом
  вызове, уведомления без ответа, ошибки JSON-RPC вместо 500, изоляция панели по человеку.
- T4: ручки проверки — две двери (сайт/программа), владелец только из входа или пропуска,
  оценка по своей истории, статусы 409/402/429/403, журнал действий; поток проверки (T6).
- T7: отчёт xlsx — колонки §1.9а, текст как есть для =+-@, оговорка договора.
- T8: уборка (30/7 дней от finished_at, недоставленное держит), гашение молчащих проверок,
  квота теми же числами, три проверки сторожа, запрет удаления диалога с живой проверкой.
- T10: уведомление в Телеграм — право одной условной вставкой, привязка, три попытки,
  пауза между сообщениями, текст без замечаний; повтор из часовой задачи.
- T1/T9 — в предыдущем коммите; находки рецензентов закрыты.

Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-11-18 06:10:39 +10:00

303 lines
16 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Шлюз к модели (T2): одна дверь к провайдерам для программы на машине человека.
Клиент знает только этот адрес и псевдоним модели; ключи провайдеров остаются на
сервере. Расход привязан ровно к одному месту — проверке (X-Review-Id) или диалогу
(X-Tab-Id); пределы проверяются ДО вызова провайдера, на вызов ставится бронь,
а строка расхода заводится заготовкой и закрывается фактическими числами. Обрыв
потока и гибель процесса не делают расход бесплатным: бронь остаётся в строке.
"""
from __future__ import annotations
import asyncio
import json
import logging
import os
import threading
import time
from fastapi import HTTPException, Request
from fastapi.responses import JSONResponse, StreamingResponse
import db
_log = logging.getLogger("smeta_web.gateway")
RESERVE_RUB = float(os.environ.get("GATEWAY_RESERVE_RUB", "1.0"))
CALL_TIMEOUT_SEC = float(os.environ.get("GATEWAY_TIMEOUT_SEC", "120"))
_lock = threading.RLock() # _admit зовёт _reserve под тем же замком
_inflight_user: dict[str, int] = {}
_inflight_review: dict[int, int] = {}
def _reserve(username: str, review_id: int | None) -> None:
with _lock:
_inflight_user[username] = _inflight_user.get(username, 0) + 1
if review_id is not None:
_inflight_review[review_id] = _inflight_review.get(review_id, 0) + 1
def _release(username: str, review_id: int | None) -> None:
with _lock:
if _inflight_user.get(username):
_inflight_user[username] -= 1
if not _inflight_user[username]:
_inflight_user.pop(username, None)
if review_id is not None and _inflight_review.get(review_id):
_inflight_review[review_id] -= 1
if not _inflight_review[review_id]:
_inflight_review.pop(review_id, None)
def _inflight(username: str, review_id: int | None) -> tuple[int, int]:
with _lock:
return (_inflight_user.get(username, 0),
_inflight_review.get(review_id, 0) if review_id is not None else 0)
def _openai_sse(text: str) -> str:
chunk = {"choices": [{"delta": {"content": text}, "index": 0}]}
return f"data: {json.dumps(chunk, ensure_ascii=False)}\n\n"
async def _provider_stream(profile, body): # noqa: ANN001 — подменяется в проверках
"""Поток провайдера: события {"delta": текст} и последним {"usage": {...}}.
Провайдеры у нас Anthropic-совместимые (base URL и ключ лежат в settings-файле
профиля), поэтому запрос переводится из OpenAI-вида в Messages API.
"""
import httpx
settings = json.loads(open(profile.settings_path, encoding="utf-8").read())
env = settings.get("env") or {}
base = (env.get("ANTHROPIC_BASE_URL") or "").rstrip("/")
token = env.get("ANTHROPIC_AUTH_TOKEN") or env.get("ANTHROPIC_API_KEY")
if not base or not token:
raise RuntimeError("провайдер не настроен: нет адреса или ключа")
messages = body.get("messages") or []
system = "\n\n".join(m.get("content") or "" for m in messages
if m.get("role") == "system")
cap = int(os.environ.get("GATEWAY_MAX_TOKENS", "4096"))
want = int(body.get("max_tokens") or cap)
payload = {"model": profile.model, "max_tokens": min(want, cap),
"stream": True,
"messages": [{"role": m.get("role"), "content": m.get("content") or ""}
for m in messages if m.get("role") in ("user", "assistant")]}
if system:
payload["system"] = system
usage = {}
async with httpx.AsyncClient(timeout=None) as client:
async with client.stream("POST", base + "/v1/messages", json=payload,
headers={"Authorization": f"Bearer {token}",
"anthropic-version": "2023-06-01"}) as resp:
if resp.status_code >= 400:
text = (await resp.aread()).decode("utf-8", "replace")[:300]
raise RuntimeError(f"провайдер ответил {resp.status_code}: {text}")
async for line in resp.aiter_lines():
if not line.startswith("data:"):
continue
try:
ev = json.loads(line[5:].strip())
except ValueError:
continue
kind = ev.get("type")
if kind == "error":
detail = (ev.get("error") or {}).get("message") or "провайдер вернул ошибку"
raise RuntimeError(str(detail))
if kind == "content_block_delta":
text = (ev.get("delta") or {}).get("text")
if text:
yield {"delta": text}
elif kind == "message_start":
u = (ev.get("message") or {}).get("usage") or {}
usage["input_tokens"] = u.get("input_tokens")
usage["cache_read_input_tokens"] = u.get("cache_read_input_tokens")
usage["cache_creation_input_tokens"] = u.get("cache_creation_input_tokens")
elif kind == "message_delta":
u = ev.get("usage") or {}
if "output_tokens" in u:
usage["output_tokens"] = u["output_tokens"]
yield {"usage": usage}
def _price(username: str, model: str | None, usage: dict, started: float) -> dict:
try:
import billing
priced = billing.price_run(usage, model or "", started, time.time(), username)
except Exception: # noqa: BLE001 — цена не должна ронять поток
_log.exception("gateway: не удалось посчитать цену")
return {"price_rub": None, "cost_rub": None, "cost_usd": None, "cost_basis": "unknown"}
return priced
async def _pump(username: str, review_id: int | None, profile, body: dict,
usage_id: int, model: str | None, started: float,
queue: asyncio.Queue) -> None:
"""Читает провайдера до конца и закрывает строку. Отключение клиента не отменяет:
провайдер уже получил запрос, и его расход обязан остаться в учёте."""
usage: dict = {}
error: Exception | None = None
try:
async for ev in _provider_stream(profile, body):
if "usage" in ev:
usage = ev["usage"] or {}
else:
await queue.put(ev)
except asyncio.CancelledError:
error = RuntimeError("вызов отменён")
raise
except Exception as e: # noqa: BLE001 — обрыв провайдера: закрываем как «неизвестно»
error = e
_log.warning("gateway: провайдер оборвал поток: %s", e)
try:
await queue.put({"error": str(e) or type(e).__name__})
except Exception: # noqa: BLE001 — очередь могла закрыться вместе с ответом
pass
finally:
try:
if error is not None and not usage:
await asyncio.to_thread(
db.settle_llm_usage_stub, usage_id, input_tokens=0, cache_tokens=0,
output_tokens=0, price_rub=RESERVE_RUB, cost_basis="unknown",
provider=profile.name, model=model)
if review_id is not None:
await asyncio.to_thread(db.add_cost, review_id, RESERVE_RUB)
else:
if "price_rub" in usage: # цена пришла от подменённого провайдера
priced = {"price_rub": usage.get("price_rub"), "cost_rub": None,
"cost_usd": None, "cost_basis": "usd"}
else:
priced = await asyncio.to_thread(_price, username, model, usage, started)
price = priced.get("price_rub")
await asyncio.to_thread(
db.settle_llm_usage_stub, usage_id,
input_tokens=usage.get("input_tokens"),
cache_tokens=usage.get("cache_tokens"),
output_tokens=usage.get("output_tokens"),
price_rub=RESERVE_RUB if price is None else price,
cost_rub=priced.get("cost_rub"), cost_usd=priced.get("cost_usd"),
provider=profile.name, model=model,
cost_basis=priced.get("cost_basis") or ("unknown" if price is None else "usd"))
if price is not None and review_id is not None:
await asyncio.to_thread(db.add_cost, review_id, price)
if review_id is not None:
await asyncio.to_thread(db.resume_paused, review_id)
finally:
_release(username, review_id)
await queue.put(None)
async def completions(request: Request):
import device_auth
device = await asyncio.to_thread(device_auth.require_device, request)
username = device["username"]
user = await asyncio.to_thread(db.get_user_by_email, username)
if not user or user.get("blocked") or user.get("deleted_at") or user.get("read_only"):
raise HTTPException(403, "Учётная запись не может пользоваться программой")
review_header = (request.headers.get("X-Review-Id") or "").strip()
tab_header = (request.headers.get("X-Tab-Id") or "").strip()
if bool(review_header) == bool(tab_header):
raise HTTPException(400, "Нужен ровно один заголовок: X-Review-Id или X-Tab-Id")
review = None
review_id = None
if review_header:
try:
review_id = int(review_header)
except ValueError:
raise HTTPException(400, "X-Review-Id: ожидается номер")
data = await asyncio.to_thread(db.get_review, username, review_id)
if data is None or data["review"]["status"] in ("done", "stopped", "failed", "abandoned"):
raise HTTPException(404, "Проверка не найдена или закрыта")
review = data["review"]
tab_id = review["tab_id"]
else:
owner = await asyncio.to_thread(db.tab_owner, tab_header)
if owner and owner != username:
raise HTTPException(404, "Диалог не найден")
if owner is None:
raise HTTPException(404, "Диалог не найден")
tab_id = tab_header
body = {}
try:
body = await request.json()
except Exception: # noqa: BLE001
raise HTTPException(400, "Тело запроса не разобралось")
# Пределы — ДО вызова провайдера и АТОМАРНО с бронью: проверка и запись брони идут
# под одним замком, иначе два одновременных вызова оба проходят одну и ту же проверку.
import quotas
def _admit() -> tuple[int, dict | None]:
"""0 — можно; иначе код отказа и тело. Вызывается под _lock."""
limits = quotas.limits_snapshot(username)
release_at = (limits.get("next_release") or {}).get("at")
retry = (max(1, int(release_at - time.time())) if release_at
else 3600) # окно суточное: через секунду предел не освободится
if not limits.get("unlimited"):
rub_left = (limits.get("rub") or {}).get("left")
if rub_left is not None and rub_left < RESERVE_RUB:
return 429, {"error": "limit", "axis": "rub", "retry_seconds": retry,
"message": f"Суточный предел исчерпан; повторите через {retry} с."}
req_left = (limits.get("requests") or {}).get("left")
if req_left is not None and req_left < 1:
return 429, {"error": "limit", "axis": "requests", "retry_seconds": retry,
"message": "Предел числа обращений исчерпан."}
tok_left = (limits.get("tokens") or {}).get("left")
if tok_left is not None and tok_left <= 0:
return 429, {"error": "limit", "axis": "tokens", "retry_seconds": retry,
"message": "Предел токенов исчерпан."}
if review is not None and review_id is not None:
budget = float(review.get("budget_rub") or 0)
price = float(review.get("price_rub") or 0)
inflight = _inflight_review.get(review_id, 0)
if budget > 0 and price + (inflight + 1) * RESERVE_RUB > budget:
return 402, {"error": "budget",
"message": "Потолок проверки исчерпан — проверка остановлена."}
_reserve(username, review_id)
return 0, None
with _lock:
code, refusal = _admit()
if code == 429:
if review_id is not None:
await asyncio.to_thread(db.pause_review, review_id)
return JSONResponse(status_code=429, content=refusal)
if code == 402:
await asyncio.to_thread(db.finish_review, review_id, "stopped", None, "budget")
return JSONResponse(status_code=402, content=refusal)
import agent_provider
chain = await asyncio.to_thread(agent_provider.provider_chain, username)
if not chain:
return JSONResponse(status_code=503, content={
"error": "provider", "message": "Провайдер модели не настроен."})
profile = chain[0]
model = profile.model
started = time.time()
usage_path = "gateway:review" if review_id is not None else "gateway:tab"
usage_id = await asyncio.to_thread(db.create_llm_usage_stub, username, tab_id, usage_path,
RESERVE_RUB, profile.name, model)
queue: asyncio.Queue = asyncio.Queue()
task = asyncio.create_task(_pump(username, review_id, profile, body, usage_id, model,
started, queue))
# Ждём первое событие (или конец) в пределах общего времени вызова: до первого байта
# ещё можно ответить 504 и не начинать поток.
try:
first = await asyncio.wait_for(queue.get(), timeout=CALL_TIMEOUT_SEC)
except asyncio.TimeoutError:
task.cancel()
await asyncio.gather(task, return_exceptions=True)
return JSONResponse(status_code=504, content={
"error": "timeout", "message": "Провайдер не ответил вовремя."})
first_done = {"value": first}
async def stream():
ev = first_done["value"]
while ev is not None:
if "delta" in ev:
yield _openai_sse(ev["delta"])
elif "error" in ev:
yield ("data: " + json.dumps({"error": {"message": ev["error"]}},
ensure_ascii=False) + "\n\n")
ev = await queue.get()
yield "data: [DONE]\n\n"
return StreamingResponse(stream(), media_type="text/event-stream")