Files
romm/backend/endpoints/sockets/logs.py
Claude 42e5b5d119 Remove the no-emdash Trunk linter after a one-time sweep
The linter ran over every Markdown file and Python comment, so full-repo
trunk runs on master kept failing on em-dashes that predate it. Replace
the existing ones once and drop the check. The AGENTS.md rule stays, the
v2 ESLint rule stays, and pr-ready's humanizer pass catches new ones in
prose.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RyamrxVw5BzEidVzm68LY7
2026-09-28 16:59:56 +00:00

171 lines
6.9 KiB
Python

"""Real-time backend log streaming over Socket.IO (admin only).
Pieces:
- ``connect`` handler on the main socket server: resolves the session user,
joins them to their own ``user:{id}`` room, and, if they are an admin, also
joins the ``admin`` room. It never rejects a connection, so the existing
scan/sync sockets keep working for everyone. It also ties the socket to its
login session, which ``disconnect`` undoes.
- ``start_log_forwarder``: a single background task (Redis-lock guarded) that
subscribes to the ``romm:logs`` pub/sub channel — fed by ``LogStreamHandler``
in every backend process — and relays each line to the ``admin`` room.
- ``get_recent_logs``: reads the capped ring buffer for backfill on view open.
"""
import asyncio
import uuid
from typing import Any, Final
import socketio
from config import DISABLE_LOGS_VIEWER
from endpoints.sockets.activity import activity_on_disconnect, store_authenticated_user
from handler.redis_handler import async_cache
from handler.socket_handler import socket_handler
from logger.log_stream_handler import LOG_BUFFER_KEY, LOG_CHANNEL
from logger.logger import log
from models.user import Role
from utils import json_module
ADMIN_ROOM: Final = "admin"
FORWARDER_LOCK_KEY: Final = "romm:logs:forwarder"
FORWARDER_LOCK_TTL: Final = 30 # seconds
@socket_handler.on("connect")
async def connect(sid: str, environ: dict[str, Any], auth: Any = None) -> None:
"""Resolve the authenticated user on socket connect.
Stores the user id in the socket session so activity events can trust the
server-resolved identity instead of a client-supplied ``user_id``, joins
every authenticated user to their own ``user:{id}`` room (the target for
sync and streaming push notifications), and joins admins to the
log-streaming room. Always returns ``None`` (accepts the connection):
only identity storage and room membership are gated, so the existing
scan/sync sockets keep working for everyone.
"""
try:
user = await socket_handler.authenticate(sid, environ)
if user is None:
return
await store_authenticated_user(sid, user.id)
await socket_handler.socket_server.enter_room(sid, f"user:{user.id}")
if not DISABLE_LOGS_VIEWER and user.role == Role.ADMIN:
await socket_handler.socket_server.enter_room(sid, ADMIN_ROOM)
except Exception: # noqa: BLE001 - never let auth resolution refuse a socket
log.exception("Failed to resolve user on socket connect")
# A server takes one handler per event, so this one does every module's cleanup.
@socket_handler.on("disconnect")
async def disconnect(sid: str) -> None:
"""Undo what ``connect`` and the activity events tied to the socket."""
await socket_handler.unbind_from_login_session(sid)
await activity_on_disconnect(sid)
async def get_recent_logs(limit: int) -> list[dict[str, Any]]:
"""Return the most recent buffered log lines in chronological order."""
raw = await async_cache.lrange(LOG_BUFFER_KEY, 0, max(0, limit - 1))
entries: list[dict[str, Any]] = []
for item in raw:
try:
entries.append(json_module.loads(item))
except Exception: # noqa: BLE001 - skip malformed entry # nosec B112
continue
# The buffer is newest-first (LPUSH); callers want oldest-first.
entries.reverse()
return entries
async def start_log_forwarder() -> None:
"""Relay log lines from Redis pub/sub to admin Socket.IO clients.
Guarded by a Redis lock so that, when more than one web worker is running
(WEB_SERVER_CONCURRENCY > 1), exactly one forwards and clients don't receive
duplicate lines. Runs until cancelled, retrying after any Redis error.
"""
if DISABLE_LOGS_VIEWER:
return
lock_id = str(uuid.uuid4())
# Write-only manager for emitting: the same proven path scan/sync use. It
# publishes the room emit to Redis; the main socket server's read-side
# manager resolves `admin` room membership and delivers.
socket_manager = socket_handler.write_manager()
try:
while True:
try:
await _forward_while_locked(lock_id, socket_manager)
except Exception: # noqa: BLE001 - never let the forwarder kill the app
log.exception("Log forwarder failed, retrying")
await _release_lock(lock_id)
# Another worker owns the forwarder, or we just lost Redis; check
# back periodically in case the lock expires or Redis recovers.
await asyncio.sleep(FORWARDER_LOCK_TTL / 2)
except asyncio.CancelledError:
# Release the lock on shutdown so a restart (e.g. uvicorn --reload)
# resumes forwarding immediately instead of waiting out the TTL.
await _release_lock(lock_id)
raise
async def _forward_while_locked(
lock_id: str, socket_manager: socketio.AsyncRedisManager
) -> None:
"""Forward log lines for as long as this worker holds the lock."""
got_lock = await async_cache.set(
FORWARDER_LOCK_KEY, lock_id, nx=True, ex=FORWARDER_LOCK_TTL
)
if not got_lock:
return
loop = asyncio.get_running_loop()
refresh_interval = FORWARDER_LOCK_TTL / 3
last_refresh = loop.time()
pubsub = async_cache.pubsub()
try:
await pubsub.subscribe(LOG_CHANNEL)
log.info("Log stream forwarder started")
while True:
if loop.time() - last_refresh >= refresh_interval:
# Another worker took the lock after a stall, so stop before
# both relay every line.
if await async_cache.get(FORWARDER_LOCK_KEY) != lock_id:
return
await async_cache.set(
FORWARDER_LOCK_KEY, lock_id, ex=FORWARDER_LOCK_TTL
)
last_refresh = loop.time()
message = await pubsub.get_message(
ignore_subscribe_messages=True,
timeout=refresh_interval,
)
if not message:
continue
data = message.get("data")
if not data:
continue
# One bad message or emit must not kill the forwarder, so swallow
# per-line and keep relaying.
try:
payload = json_module.loads(data)
await socket_manager.emit("logs:entry", payload, room=ADMIN_ROOM)
except Exception: # noqa: BLE001 - keep forwarding # nosec B112
continue
finally:
# Closing drops the subscription and works on a dead connection.
await pubsub.aclose()
async def _release_lock(lock_id: str) -> None:
"""Delete the forwarder lock only if we still own it."""
try:
current = await async_cache.get(FORWARDER_LOCK_KEY)
if current == lock_id:
await async_cache.delete(FORWARDER_LOCK_KEY)
except Exception: # noqa: BLE001 - best-effort cleanup # nosec B110
pass