fix(backend): restart the log forwarder and harden three Redis call sites (#4847)

This commit is contained in:
Sam Dornan
2026-09-27 20:10:06 -04:00
committed by GitHub
parent b40919b0c5
commit 29220cd59e
10 changed files with 395 additions and 92 deletions

View File

@@ -16,6 +16,8 @@ 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
@@ -83,74 +85,79 @@ async def start_log_forwarder() -> None:
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.
duplicate lines. Runs until cancelled, retrying after any Redis error.
"""
if DISABLE_LOGS_VIEWER:
return
lock_id = str(uuid.uuid4())
pubsub = None
# 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:
got_lock = await async_cache.set(
FORWARDER_LOCK_KEY, lock_id, nx=True, ex=FORWARDER_LOCK_TTL
)
if not got_lock:
# Another worker owns the forwarder; check back periodically in
# case it dies and the lock expires.
await asyncio.sleep(FORWARDER_LOCK_TTL / 2)
continue
pubsub = async_cache.pubsub()
await pubsub.subscribe(LOG_CHANNEL)
log.info("Log stream forwarder started")
try:
while True:
# Heartbeat the lock, but only while we still own it. If
# another worker took it (after a stall / Redis hiccup),
# stop forwarding to avoid duplicate lines — the outer loop
# will then contend for the lock again.
if await async_cache.get(FORWARDER_LOCK_KEY) != lock_id:
break
await async_cache.set(
FORWARDER_LOCK_KEY, lock_id, ex=FORWARDER_LOCK_TTL
)
message = await pubsub.get_message(
ignore_subscribe_messages=True,
timeout=FORWARDER_LOCK_TTL / 3,
)
if not message:
continue
data = message.get("data")
if not data:
continue
# One bad message or emit must not kill the forwarder —
# 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:
await pubsub.unsubscribe(LOG_CHANNEL)
await pubsub.aclose()
pubsub = None
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:
if pubsub is not None:
await pubsub.aclose()
# 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
except Exception: # noqa: BLE001 - never let the forwarder kill the app
log.exception("Log forwarder crashed")
await _release_lock(lock_id)
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:

View File

@@ -57,6 +57,7 @@ from handler.notification_handler import notify_user_or_admins
from handler.recommendation import top_up_similarity
from handler.redis_handler import (
cancel_job,
get_job_kwargs,
get_job_status,
redis_client,
scan_queue,
@@ -146,14 +147,15 @@ def report_scan_failure(
reason = _SCAN_FAILURE_REASONS.get(exc_type, "it stopped unexpectedly")
log.warning(f"{emoji.EMOJI_STOP_SIGN} Scan {job.id} is over: {reason}")
started_by_user_id = (get_job_kwargs(job) or {}).get("started_by_user_id")
async def report() -> None:
await _get_socket_manager().emit("scan:done_ko", reason)
await notify_scan_end(job.kwargs.get("started_by_user_id"), reason)
await notify_scan_end(started_by_user_id, reason)
record(
AuditAction.SCAN_FINISH,
AuditActor.for_user_id(job.kwargs.get("started_by_user_id")),
AuditActor.for_user_id(started_by_user_id),
data={"status": "failed", "error": reason},
)

View File

@@ -29,6 +29,7 @@ from handler.auth.constants import Scope
from handler.redis_handler import (
ALL_QUEUES,
get_job_func_name,
get_job_kwargs,
get_worker_current_job,
has_live_worker,
low_prio_queue,
@@ -111,7 +112,7 @@ def _build_task_status_response(
job_meta = job.get_meta()
task_type = job_meta.get("task_type")
task_name = job_meta.get("task_name") or get_job_func_name(job)
task_key = job_meta.get("task_key") or job.kwargs.get("name")
task_key = job_meta.get("task_key") or (get_job_kwargs(job) or {}).get("name")
# Convert datetime objects to ISO format strings
created_at = job.created_at.isoformat() if job.created_at else None

View File

@@ -12,6 +12,8 @@ import json
from datetime import datetime, timezone
from typing import Any, TypedDict, cast
from redis.exceptions import WatchError
from endpoints.responses.activity import ActivityClearSchema
from handler.database import (
db_device_handler,
@@ -209,32 +211,79 @@ class ActivityHandler:
async def get_active_for_rom(self, rom_id: int) -> list[ActivityEntry]:
"""Get all active play sessions for a specific ROM."""
rom_key = self._rom_index_key(rom_id)
members = cast(set[str], await async_cache.smembers(rom_key))
members = await async_cache.smembers(rom_key)
entries: list[ActivityEntry] = []
stale_members: list[str] = []
malformed: list[str] = []
keys_by_member: dict[str, str] = {}
for member in members:
for raw_member in members:
# Decoded as the session middleware does, for a client that doesn't.
member = (
raw_member.decode() if isinstance(raw_member, bytes) else raw_member
)
try:
user_id_str, device_id = member.rsplit(":", 1)
user_id = int(user_id_str)
except ValueError, AttributeError:
stale_members.append(member)
continue
raw = await async_cache.get(self._activity_key(user_id, device_id))
if not raw:
# Key expired; clean up the stale set member.
stale_members.append(member)
continue
try:
entries.append(json.loads(raw))
except ValueError:
stale_members.append(member)
malformed.append(member)
continue
keys_by_member[member] = self._activity_key(user_id, device_id)
if stale_members:
await async_cache.srem(rom_key, *stale_members)
raws = (
await async_cache.mget(list(keys_by_member.values()))
if keys_by_member
else []
)
stale: dict[str, str] = {}
for (member, key), raw in zip(keys_by_member.items(), raws, strict=True):
entry = _live_entry(raw, rom_id)
if entry is None:
stale[member] = key
else:
entries.append(entry)
if malformed or stale:
await self._drop_index_members(rom_id, malformed, stale)
return entries
async def _drop_index_members(
self, rom_id: int, malformed: list[str], stale: dict[str, str]
) -> None:
"""Remove members from a ROM's index, sparing any a heartbeat has revived."""
async with async_cache.pipeline() as pipe:
try:
if stale:
await pipe.watch(*stale.values())
raws = await pipe.mget(list(stale.values()))
still_stale = [
member
for member, raw in zip(stale, raws, strict=True)
if _live_entry(raw, rom_id) is None
]
else:
still_stale = []
if not (malformed or still_stale):
return
pipe.multi()
await pipe.srem(self._rom_index_key(rom_id), *malformed, *still_stale)
await pipe.execute()
except WatchError:
# A heartbeat raced this cleanup; the next read retries it.
pass
def _live_entry(raw: str | bytes | None, rom_id: int) -> ActivityEntry | None:
"""The stored session, if it exists, parses and is still playing `rom_id`."""
if not raw:
return None
try:
entry = json.loads(raw)
except ValueError:
return None
if not isinstance(entry, dict) or entry.get("rom_id") != rom_id:
return None
return cast(ActivityEntry, entry)
activity_handler = ActivityHandler()

View File

@@ -4,6 +4,7 @@ import json
from datetime import datetime, timedelta, timezone
from typing import Any, cast
import pytest
from fastapi import status
from fastapi.testclient import TestClient
from httpx2 import Response
@@ -929,3 +930,55 @@ class TestSyncNegotiateBoundTokenInference:
json={"saves": []},
)
assert resp.status_code == status.HTTP_400_BAD_REQUEST
def test_store_pending_writes_neither_key_when_one_write_fails(mocker):
# A device code without its user code is a flow nobody can approve.
real_pipeline = sync_cache.pipeline
def failing_pipeline(*args, **kwargs):
pipe = real_pipeline(*args, **kwargs)
queue_set = pipe.set
def set_(name, *args, **kwargs):
if name.startswith("device_auth:uc:"):
raise ConnectionError("valkey went away")
return queue_set(name, *args, **kwargs)
mocker.patch.object(pipe, "set", side_effect=set_)
return pipe
mocker.patch.object(sync_cache, "pipeline", side_effect=failing_pipeline)
with pytest.raises(ConnectionError):
df.store_pending("dc-atomic", "UCATOMIC", {})
assert sync_cache.get("device_auth:dc:dc-atomic") is None
assert sync_cache.get("device_auth:uc:UCATOMIC") is None
def test_store_pending_sends_both_keys_in_one_transaction(mocker):
real_pipeline = sync_cache.pipeline
sent: list[tuple[bool, list[tuple[str, str]]]] = []
def spying_pipeline(*args, **kwargs):
pipe = real_pipeline(*args, **kwargs)
real_execute = pipe.execute
def execute(*args, **kwargs):
commands = [(cmd[0], cmd[1]) for cmd, _ in pipe.command_stack]
# The instance flag, which the stubs mistake for the transaction() method.
sent.append((vars(pipe)["transaction"], commands))
return real_execute(*args, **kwargs)
mocker.patch.object(pipe, "execute", side_effect=execute)
return pipe
mocker.patch.object(sync_cache, "pipeline", side_effect=spying_pipeline)
df.store_pending("dc-tx", "UCTX", {})
assert sent == [
(True, [("SET", "device_auth:dc:dc-tx"), ("SET", "device_auth:uc:UCTX")])
]
assert sync_cache.get("device_auth:uc:UCTX") == b"dc-tx"

View File

@@ -1,11 +1,15 @@
import time
from types import SimpleNamespace
from typing import cast
from unittest.mock import AsyncMock, MagicMock, Mock
from unittest.mock import AsyncMock, MagicMock, Mock, PropertyMock
import pytest
import socketio
from rq.exceptions import AbandonedJobError, InvalidJobOperation
from rq.exceptions import (
AbandonedJobError,
DeserializationError,
InvalidJobOperation,
)
from rq.job import JobStatus
from rq.timeouts import JobTimeoutException
from tests.scan_job_stubs import (
@@ -2617,6 +2621,24 @@ class TestReportScanFailure:
9, "the worker running it stopped unexpectedly"
)
def test_reports_a_scan_whose_kwargs_can_no_longer_be_loaded(self, emit, mocker):
# An abandoned scan pickled by an older release must not crash the
# registry sweep that calls this.
notify_scan_end = mocker.patch.object(
scan_module, "notify_scan_end", AsyncMock()
)
job = make_job(SCAN_PLATFORMS_FUNC)
type(job).kwargs = PropertyMock(side_effect=DeserializationError("stale"))
scan_module.report_scan_failure(
job, MagicMock(), AbandonedJobError, AbandonedJobError("boom"), None
)
emit.assert_awaited_once()
notify_scan_end.assert_awaited_once_with(
None, "the worker running it stopped unexpectedly"
)
def test_swallows_a_report_that_cannot_be_sent(self, emit):
# RQ re-raises out of the registry sweep that calls this, which would
# leave the abandoned scans in the registry and stop the worker.

View File

@@ -1,10 +1,15 @@
import asyncio
from typing import Any
from unittest.mock import AsyncMock, MagicMock, patch
from fastapi import status
from endpoints.logs import MAX_LOG_LIMIT
from endpoints.sockets.logs import get_recent_logs
from endpoints.sockets.logs import (
FORWARDER_LOCK_KEY,
get_recent_logs,
start_log_forwarder,
)
from utils import json_module
SAMPLE_ENTRY = {"ts": 1, "level": "INFO", "module": "startup", "message": "hello"}
@@ -83,3 +88,79 @@ def test_get_recent_logs_returns_oldest_first_and_skips_malformed():
result = asyncio.run(get_recent_logs(10))
assert [entry["ts"] for entry in result] == [1, 2, 3]
def _fake_lock_cache() -> MagicMock:
"""A str-valued lock store, since the test fakeredis returns bytes."""
store: dict[str, Any] = {}
async def set_(key, value, nx=False, ex=None):
if nx and key in store:
return None
store[key] = value
return True
async def get(key):
return store.get(key)
async def delete(key):
store.pop(key, None)
cache = MagicMock()
cache.store = store
cache.set = AsyncMock(side_effect=set_)
cache.get = AsyncMock(side_effect=get)
cache.delete = AsyncMock(side_effect=delete)
return cache
def test_log_forwarder_resumes_after_a_redis_error():
broken = MagicMock()
broken.subscribe = AsyncMock(side_effect=ConnectionError("valkey restarted"))
broken.aclose = AsyncMock()
healthy = MagicMock()
healthy.subscribe = AsyncMock()
healthy.aclose = AsyncMock()
messages = [{"data": json_module.dumps(SAMPLE_ENTRY)}]
async def get_message(**kwargs):
if messages:
return messages.pop()
await asyncio.sleep(kwargs["timeout"])
return None
healthy.get_message = AsyncMock(side_effect=get_message)
cache = _fake_lock_cache()
cache.pubsub = MagicMock(side_effect=[broken, healthy])
manager = MagicMock()
async def run() -> None:
forwarded = asyncio.Event()
manager.emit = AsyncMock(side_effect=lambda *a, **kw: forwarded.set())
task = asyncio.create_task(start_log_forwarder())
await asyncio.wait_for(forwarded.wait(), timeout=5)
task.cancel()
try:
await task
except asyncio.CancelledError:
pass
with (
patch("endpoints.sockets.logs.DISABLE_LOGS_VIEWER", False),
patch("endpoints.sockets.logs.FORWARDER_LOCK_TTL", 0.03),
patch("endpoints.sockets.logs.async_cache", cache),
patch(
"endpoints.sockets.logs.socket_handler.write_manager",
return_value=manager,
),
):
asyncio.run(run())
manager.emit.assert_any_await("logs:entry", SAMPLE_ENTRY, room="admin")
# The dead connection is closed even though it never subscribed.
broken.aclose.assert_awaited_once()
healthy.aclose.assert_awaited_once()
# Cancelling releases the lock so a restart picks up straight away.
assert FORWARDER_LOCK_KEY not in cache.store

View File

@@ -1,9 +1,9 @@
from typing import Any
from unittest.mock import Mock, patch
from unittest.mock import Mock, PropertyMock, patch
import pytest
from fastapi import status
from rq.exceptions import NoSuchJobError
from rq.exceptions import DeserializationError, NoSuchJobError
from handler.redis_handler import low_prio_queue, redis_client
from tasks.manual.cleanup_missing_firmware import CleanupMissingFirmwareStats
@@ -458,6 +458,23 @@ class TestGetTaskById:
"errors": 0,
}
@patch("endpoints.tasks.Job.fetch")
def test_a_job_whose_kwargs_can_no_longer_be_loaded_still_reports(
self, mock_job_fetch, client, access_token
):
"""A job pickled by an older release may not unpickle after an upgrade."""
job = _job_with_meta({})
type(job).kwargs = PropertyMock(side_effect=DeserializationError("stale"))
mock_job_fetch.return_value = job
response = client.get(
"/api/tasks/test-job-id-123",
headers={"Authorization": f"Bearer {access_token}"},
)
assert response.status_code == status.HTTP_200_OK
assert response.json()["task_key"] is None
@patch("endpoints.tasks.Job.fetch")
def test_get_task_by_id_success(self, mock_job_fetch, client, access_token):
"""Test successful retrieval of a task by job ID"""

View File

@@ -1,9 +1,12 @@
import asyncio
import json
from contextlib import contextmanager
from unittest.mock import AsyncMock, patch
import pytest
from handler.activity_handler import activity_handler
from handler.redis_handler import async_cache
from handler.redis_handler import async_cache, sync_cache
from handler.socket_handler import socket_handler
from models.rom import Rom
from models.user import User
@@ -149,3 +152,66 @@ def test_clearing_broadcasts_only_when_there_was_something_to_clear(
asyncio.run(async_cache.get(f"activity:user:{admin_user.id}:container-1"))
is None
)
@pytest.fixture
def clean_cache():
sync_cache.flushall()
yield
sync_cache.flushall()
def _session(device_id: str, rom_id: int) -> dict[str, object]:
return {"user_id": 1, "device_id": device_id, "rom_id": rom_id}
async def _seed(rom_id: int, sessions: dict[str, object], *members: str) -> None:
for device_id, value in sessions.items():
raw = value if isinstance(value, str) else json.dumps(value)
await async_cache.set(f"activity:user:1:{device_id}", raw)
await async_cache.sadd(f"activity:rom:{rom_id}", *members)
def test_active_for_rom_reads_every_session_at_once_and_drops_stale_members(
clean_cache,
):
live = _session("live", 7)
asyncio.run(
_seed(
7,
{
"live": live,
"corrupt": "not-json",
"listed": "[]",
"moved": _session("moved", 9),
},
"1:live",
"1:expired",
"1:corrupt",
"1:listed",
"1:moved",
"not-a-member",
)
)
with patch.object(async_cache, "get", wraps=async_cache.get) as get:
assert asyncio.run(activity_handler.get_active_for_rom(7)) == [live]
get.assert_not_called()
assert asyncio.run(async_cache.smembers("activity:rom:7")) == {b"1:live"}
def test_active_for_rom_spares_a_member_a_heartbeat_revived(clean_cache):
"""A device that moves back to the ROM mid-read keeps its index entry."""
asyncio.run(_seed(7, {"dev": _session("dev", 9)}, "1:dev"))
real_mget = async_cache.mget
async def mget_then_heartbeat(keys):
raws = await real_mget(keys)
await async_cache.set("activity:user:1:dev", json.dumps(_session("dev", 7)))
return raws
with patch.object(async_cache, "mget", side_effect=mget_then_heartbeat):
assert asyncio.run(activity_handler.get_active_for_rom(7)) == []
assert asyncio.run(async_cache.smembers("activity:rom:7")) == {b"1:dev"}

View File

@@ -115,10 +115,12 @@ def store_pending(device_code: str, user_code: str, data: dict[str, Any]) -> Non
"status": FlowStatus.PENDING,
"user_code": user_code,
}
sync_cache.set(
_KEY_DC.format(device_code), json.dumps(payload), ex=PENDING_TTL_SECONDS
)
sync_cache.set(_KEY_UC.format(user_code), device_code, ex=PENDING_TTL_SECONDS)
with sync_cache.pipeline() as pipe:
pipe.set(
_KEY_DC.format(device_code), json.dumps(payload), ex=PENDING_TTL_SECONDS
)
pipe.set(_KEY_UC.format(user_code), device_code, ex=PENDING_TTL_SECONDS)
pipe.execute()
def load_pending(device_code: str) -> dict[str, Any] | None:
@@ -165,13 +167,9 @@ def mark_approved(
remaining = sync_cache.ttl(_KEY_DC.format(device_code))
if remaining is None or remaining < 1:
remaining = PENDING_TTL_SECONDS
sync_cache.set(
_KEY_DC.format(device_code),
json.dumps(approved),
ex=min(remaining, PENDING_TTL_SECONDS),
_finish_flow(
device_code, user_code, approved, ttl=min(remaining, PENDING_TTL_SECONDS)
)
if user_code:
sync_cache.delete(_KEY_UC.format(user_code))
def mark_denied(device_code: str) -> None:
@@ -180,11 +178,18 @@ def mark_denied(device_code: str) -> None:
return
user_code = pending.get("user_code")
denied = {"status": FlowStatus.DENIED}
sync_cache.set(
_KEY_DC.format(device_code), json.dumps(denied), ex=DENIED_TTL_SECONDS
)
if user_code:
sync_cache.delete(_KEY_UC.format(user_code))
_finish_flow(device_code, user_code, denied, ttl=DENIED_TTL_SECONDS)
def _finish_flow(
device_code: str, user_code: str | None, result: dict[str, Any], *, ttl: int
) -> None:
"""Store a flow's outcome and retire its user code in one transaction."""
with sync_cache.pipeline() as pipe:
pipe.set(_KEY_DC.format(device_code), json.dumps(result), ex=ttl)
if user_code:
pipe.delete(_KEY_UC.format(user_code))
pipe.execute()
def consume_approved(device_code: str) -> dict[str, Any] | None: