first prototype

This commit is contained in:
2026-09-27 09:52:00 +02:00
parent 4635199a41
commit 6d011d474f
109 changed files with 6354 additions and 507 deletions
+77
View File
@@ -0,0 +1,77 @@
"""FastAPI application of the Wizard game server.
Routes:
- ``GET /api/health`` health check
- ``WS /api/ws`` web clients (see ``app.protocol``)
- ``WS /internal/ai`` AI service (see ``app.ai_bridge``); not meant to be
exposed by the reverse proxy and protected by ``AI_SHARED_SECRET``
"""
from __future__ import annotations
import asyncio
import contextlib
import logging
import secrets
from collections.abc import AsyncIterator
from fastapi import FastAPI, WebSocket
from .config import Settings, settings
from .service import WizardService
logger = logging.getLogger(__name__)
def create_app(config: Settings = settings) -> FastAPI:
service = WizardService(config)
@contextlib.asynccontextmanager
async def lifespan(_: FastAPI) -> AsyncIterator[None]:
if not config.ai_shared_secret:
logger.warning("AI_SHARED_SECRET is not set, /internal/ai is unauthenticated")
cleanup = asyncio.create_task(service.cleanup_loop())
try:
yield
finally:
cleanup.cancel()
app = FastAPI(title="Wizard game server", lifespan=lifespan, docs_url=None, redoc_url=None)
app.state.service = service
@app.get("/api/health")
async def health() -> dict:
return {
"status": "ok",
"lobbies": len(service.lobbies),
"sessions": len(service.sessions),
"ai_available": service.bridge.available,
}
@app.websocket("/api/ws")
async def client_socket(websocket: WebSocket) -> None:
await service.handle_client(websocket)
@app.websocket("/internal/ai")
async def ai_socket(websocket: WebSocket) -> None:
if not _ai_authorized(websocket, config.ai_shared_secret):
await websocket.close(code=1008)
return
await service.handle_ai(websocket)
return app
def _ai_authorized(websocket: WebSocket, secret: str) -> bool:
if not secret:
return True
header = websocket.headers.get("authorization", "")
token = header.removeprefix("Bearer ").strip() if header.startswith("Bearer ") else ""
return secrets.compare_digest(token.encode(), secret.encode())
logging.basicConfig(
level=settings.log_level.upper(),
format="%(asctime)s %(levelname)s %(name)s: %(message)s",
)
app = create_app()