feat: implement full backend + frontend server detail, settings, and create server pages

Backend:
- Complete FastAPI backend with 42+ REST endpoints (auth, servers, config,
  players, bans, missions, mods, games, system)
- Game adapter architecture with Arma 3 as first-class adapter
- WebSocket real-time events for status, metrics, logs, players
- Background thread system (process monitor, metrics, log tail, RCon poller)
- Fernet encryption for sensitive config fields at rest
- JWT auth with admin/viewer roles, bcrypt password hashing
- SQLite with WAL mode, parameterized queries, migration system
- APScheduler cleanup jobs for logs, metrics, events

Frontend:
- Server Detail page with 7 tabs (overview, config, players, bans,
  missions, mods, logs)
- Settings page with password change and admin user management
- Create Server wizard (4-step; known bug: silent validation failure)
- New hooks: useServerDetail, useAuth, useGames
- New components: ServerHeader, ConfigEditor, PlayerTable, BanTable,
  MissionList, ModList, LogViewer, PasswordChange, UserManager
- WebSocket onEvent callback for real-time log accumulation
- 120 unit tests passing (Vitest + React Testing Library)

Docs:
- Added .gitignore, CLAUDE.md, README.md
- Updated FRONTEND.md, ARCHITECTURE.md with current implementation state
- Added .env.example for backend configuration

Known issues:
- Create Server form: "Next" buttons don't validate before advancing,
  causing silent submit failure when fields are invalid
- Config sub-tabs need UX redesign for non-technical users
This commit is contained in:
Tran G. (Revernomad) Khoa
2026-04-17 11:58:34 +07:00
parent 620429c9b8
commit 6511353b55
119 changed files with 13752 additions and 5000 deletions

View File

@@ -0,0 +1,4 @@
from core.websocket.manager import WebSocketManager
from core.websocket.broadcast_thread import BroadcastThread
__all__ = ["WebSocketManager", "BroadcastThread"]

View File

@@ -0,0 +1,116 @@
"""
BroadcastThread — the single bridge between OS threads and asyncio WebSocket world.
Reads events from a queue.Queue (written by background server threads) and
forwards them to the WebSocketManager running in the asyncio event loop.
Design:
- Runs as a daemon thread — no cleanup needed on shutdown.
- queue.Queue is thread-safe — multiple producer threads, single consumer.
- asyncio.run_coroutine_threadsafe() schedules the WebSocketManager.broadcast()
coroutine on the event loop from this non-asyncio thread.
- If the event loop is closed or the broadcast fails, the event is dropped silently.
Queue item format (dict):
{
"type": str, # "log", "metrics", "players", "server_status", etc.
"server_id": int, # Which server this event belongs to
"data": dict | list, # Payload — varies by type
}
"""
from __future__ import annotations
import asyncio
import logging
import queue
import threading
logger = logging.getLogger(__name__)
_QUEUE_GET_TIMEOUT = 1.0
_DROP_LOG_THRESHOLD = 100
class BroadcastThread(threading.Thread):
"""
Bridge from thread-world to asyncio-world.
Args:
event_queue: The shared queue.Queue that all background threads write to.
ws_manager: The WebSocketManager instance (asyncio-side).
loop: The asyncio event loop running in the main thread.
"""
def __init__(
self,
event_queue: queue.Queue,
ws_manager, # WebSocketManager — type annotation omitted to avoid circular import
loop: asyncio.AbstractEventLoop,
) -> None:
super().__init__(name="BroadcastThread", daemon=True)
self._queue = event_queue
self._ws_manager = ws_manager
self._loop = loop
self._stop_event = threading.Event()
self._dropped = 0
def stop(self) -> None:
self._stop_event.set()
def run(self) -> None:
logger.info("BroadcastThread: started")
while not self._stop_event.is_set():
try:
item = self._queue.get(timeout=_QUEUE_GET_TIMEOUT)
except queue.Empty:
continue
self._forward(item)
# Drain remaining items on shutdown
while not self._queue.empty():
try:
item = self._queue.get_nowait()
self._forward(item)
except queue.Empty:
break
logger.info("BroadcastThread: stopped")
def _forward(self, item: dict) -> None:
"""Schedule a broadcast on the asyncio event loop."""
if self._loop.is_closed():
self._dropped += 1
if self._dropped % _DROP_LOG_THRESHOLD == 0:
logger.warning(
"BroadcastThread: event loop closed, dropped %d messages",
self._dropped,
)
return
server_id = item.get("server_id")
event_type = item.get("type", "unknown")
data = item.get("data", {})
message = {
"type": event_type,
"server_id": server_id,
"data": data,
}
try:
future = asyncio.run_coroutine_threadsafe(
self._ws_manager.broadcast(server_id, message),
self._loop,
)
# Fire and forget — suppress unhandled exception warnings
future.add_done_callback(self._on_broadcast_done)
except RuntimeError as exc:
logger.debug("BroadcastThread: could not schedule broadcast: %s", exc)
def _on_broadcast_done(self, future) -> None:
"""Called when the broadcast coroutine completes. Log exceptions only."""
try:
future.result()
except Exception as exc:
logger.debug("BroadcastThread: broadcast error: %s", exc)

View File

@@ -0,0 +1,96 @@
"""
WebSocketManager — asyncio-side manager for WebSocket connections.
All methods are coroutines and must be called from the asyncio event loop.
No locking needed — the event loop is single-threaded.
Subscription model:
- Each connection subscribes to zero or more server_ids.
- Subscribing to server_id=None means "all servers".
- broadcast(server_id, message) sends to all clients subscribed to that server_id
plus all clients subscribed to None (global subscribers).
"""
from __future__ import annotations
import json
import logging
from typing import Optional
from fastapi import WebSocket
logger = logging.getLogger(__name__)
class WebSocketManager:
"""Manages active WebSocket connections and delivers broadcast messages."""
def __init__(self) -> None:
# Maps WebSocket -> set of subscribed server_ids (None = all)
self._connections: dict[WebSocket, set[Optional[int]]] = {}
# ── Connection lifecycle ──
async def connect(self, ws: WebSocket, server_ids: Optional[list[int]] = None) -> None:
"""
Accept a WebSocket connection and register it.
Args:
ws: The FastAPI WebSocket instance.
server_ids: List of server IDs to subscribe to, or None for all.
"""
await ws.accept()
subscriptions: set[Optional[int]] = set(server_ids) if server_ids else {None}
self._connections[ws] = subscriptions
logger.info(
"WebSocketManager: client connected, subscriptions=%s, total=%d",
subscriptions,
len(self._connections),
)
async def disconnect(self, ws: WebSocket) -> None:
"""Remove a disconnected WebSocket."""
self._connections.pop(ws, None)
logger.info(
"WebSocketManager: client disconnected, total=%d",
len(self._connections),
)
# ── Broadcast ──
async def broadcast(self, server_id: Optional[int], message: dict) -> None:
"""
Send a message to all clients subscribed to the given server_id.
Also sends to clients subscribed to None (global subscribers).
Disconnected clients are removed automatically.
"""
if not self._connections:
return
payload = json.dumps(message)
disconnected = []
for ws, subscriptions in self._connections.items():
if None in subscriptions or server_id in subscriptions:
try:
await ws.send_text(payload)
except Exception as exc:
logger.debug("WebSocketManager: send failed, marking disconnected: %s", exc)
disconnected.append(ws)
for ws in disconnected:
await self.disconnect(ws)
async def send_to_connection(self, ws: WebSocket, message: dict) -> None:
"""Send a message to a single specific connection."""
try:
await ws.send_text(json.dumps(message))
except Exception as exc:
logger.debug("WebSocketManager: direct send failed, disconnecting: %s", exc)
await self.disconnect(ws)
# ── Stats ──
@property
def connection_count(self) -> int:
return len(self._connections)

View File

@@ -0,0 +1,90 @@
"""
WebSocket endpoint.
URL: /ws
/ws?server_id=1
/ws?server_id=1&server_id=2
Authentication: JWT passed as a query parameter `token` because
browser WebSocket API does not support custom headers.
If the token is missing or invalid, the connection is closed with code 4001.
After authentication, the client receives:
- A "connected" welcome message with the list of subscribed server IDs
- All events for subscribed servers pushed by BroadcastThread
"""
from __future__ import annotations
import logging
from typing import Optional
from fastapi import APIRouter, Query, WebSocket, WebSocketDisconnect
from core.auth.utils import decode_access_token
logger = logging.getLogger(__name__)
router = APIRouter(tags=["websocket"])
@router.websocket("/ws")
async def websocket_endpoint(
ws: WebSocket,
token: Optional[str] = Query(default=None),
server_id: Optional[list[int]] = Query(default=None),
) -> None:
"""
WebSocket endpoint for real-time server events.
Query parameters:
token: JWT access token (required)
server_id: One or more server IDs to subscribe to (optional, default=all)
"""
# Authenticate before accepting
if not token:
await ws.close(code=4001, reason="Missing token")
return
try:
user = decode_access_token(token)
except Exception as exc:
logger.warning("WebSocket: token decode failed: %s", exc)
user = None
if user is None:
await ws.close(code=4001, reason="Invalid or expired token")
return
# Get WebSocketManager from app state
ws_manager = ws.app.state.ws_manager
await ws_manager.connect(ws, server_ids=server_id)
logger.info(
"WebSocket: user '%s' connected, subscribed to servers=%s",
user.get("sub"),
server_id,
)
try:
# Send welcome message
await ws_manager.send_to_connection(ws, {
"type": "connected",
"data": {
"user": user.get("sub"),
"subscriptions": server_id or "all",
},
})
# Keep connection alive — wait for client to disconnect
while True:
data = await ws.receive_text()
except WebSocketDisconnect:
logger.info(
"WebSocket: user '%s' disconnected",
user.get("sub"),
)
except Exception as exc:
logger.error("WebSocket: unexpected error: %s", exc)
finally:
await ws_manager.disconnect(ws)