feat(3.1): /health endpoint (503 при недоступности БД) + db.ping для мониторинга

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
anor
2026-06-10 17:42:29 +10:00
co-authored by Claude Fable 5
parent 52f087aeb0
commit f7995a3b3a
2 changed files with 27 additions and 2 deletions
+6
View File
@@ -70,6 +70,12 @@ def _conn() -> sqlite3.Connection:
return conn
def ping():
"""Лёгкая проверка доступности БД для /health."""
with _conn() as conn:
conn.execute("SELECT 1").fetchone()
def init_db():
with _conn() as conn:
conn.executescript(_CREATE)
+21 -2
View File
@@ -9,11 +9,11 @@ import time
from pathlib import Path
from fastapi import FastAPI, HTTPException, Request, UploadFile
from fastapi.responses import FileResponse, HTMLResponse, StreamingResponse
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, StreamingResponse
from fastapi.staticfiles import StaticFiles
from auth import authenticate, verify_token, make_download_ticket, verify_download_ticket
from db import clear_history, get_audit_log, get_history, get_history_any_user, init_db, list_sessions, log_action, save_message
from db import clear_history, get_audit_log, get_history, get_history_any_user, init_db, list_sessions, log_action, ping as db_ping, save_message
from tus_upload import register_tus
# Backend: "claude" (Docker sandbox), "glm" (GLM-5 + CAG), "auto" (route by task)
@@ -341,6 +341,25 @@ def _compute_data_periods():
return result
@app.get("/health")
async def health():
"""Public health-check для мониторинга: 503 если БД недоступна (критично),
иначе 200 с состоянием знаниевой базы. Чтобы владелец узнавал о падении не
от пользователя."""
checks = {}
healthy = True
try:
await asyncio.to_thread(db_ping)
checks["db"] = "ok"
except Exception as e: # noqa: BLE001
checks["db"] = f"error: {e}"
healthy = False
proj = os.environ.get("SMETA_PROJECT_DIR", "")
checks["knowledge_base"] = "ok" if (proj and Path(proj).exists()) else "missing"
payload = {"status": "ok" if healthy else "down", "checks": checks, "version": APP_VERSION}
return JSONResponse(payload, status_code=200 if healthy else 503)
@app.get("/api/data-version")
async def data_version():
"""Public — на какой ценовой период актуальна корпусная база (свежесть данных)."""