Files
romm/backend/endpoints/sockets/activity.py
Sam Dornan 4542998510 fix(backend): make type ignores honest and replace mypy trunk-ignores with fixes (#4711)
* fix(backend): make type ignores match what mypy reports

Third in the staged series clearing the errors #4655 made visible.
Whole-project mypy: 91 errors in 26 files -> 64 in 23.

Twenty `# type: ignore[assignment]` comments in
endpoints/responses/rom.py never suppressed anything. The request-scoped
values `from_orm_with_request` attaches to a Rom (rom_user, has_notes,
user_saves and the rest) are not declared on the model, so mypy reports
`attr-defined`; it does so under 1.19 as well as 2.3, so the code was
wrong when the comments were written rather than drifting since. They
now name the error they were meant to silence.

Seventy-nine ignores across 24 files suppressed nothing at all under
`--warn-unused-ignores`, and are removed. One of them,
`utils/zip_cache.py`, keeps its `attr-defined` code for the private
`zipfile._get_compressor` and drops only `assignment`. The unused set is
identical under mypy 2.3.0 and 2.3.1, and removing them leaves the error
count unchanged under both, so none was quietly needed.

The two `filter` helpers typed as `[QueryT: Select | Update | Delete]`
bound the TypeVar to the union, so `query.filter(...)` returned the union
and could not be assigned back to `QueryT`. Constraining it to the three
types lets mypy check each one separately, and the callers are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SPpv6W2ygP9tQ61fTQxdYp

* fix(backend): replace mypy and ASYNC240 trunk-ignores with real fixes

A `trunk-ignore` only suppresses when Trunk runs the linter. Plain mypy
does not read them, so the 13 on mypy findings were all still errors to
`mypy .` and would fail a whole-project check. Each now has a fix.

endpoints/tasks.py: `common_data` was a plain dict literal unpacked into
eight TypedDict constructors, so mypy saw `dict[str, Any]` and could not
match its keys. It holds exactly the fields of BaseTaskStatusResponse and
is now annotated as one, so the unpacking is checked.

handler/metadata/gamelist_handler.py: both media maps were inferred as
`dict[str, str]`, so indexing the TypedDict with their keys was
unprovable. Their keys are now typed `GamelistMediaKey`, the Literal of
the TypedDict's fields. A misspelt map key is now an error at the entry;
before, only the index site could have noticed, and it was suppressed.

handler/metadata/playmatch_handler.py: `attr` was a bare `str`. A TypeIs
guard narrows it to the five lookup attributes, and the frozenset is
derived from that Literal so the names live in one place. mypy now checks
that each name is a real PlaymatchRomMatch key. It does not check that
each takes an int, since mypy is lenient about value types on a union key;
that still rests on which five names are listed.

endpoints/search.py: the per-source tuples mixed ROM-list and handler
types, which mypy joined to `object`. The dict is now annotated with what
the loop uses: Mapping rows and the MetadataHandler base.

tests/handler/metadata/test_launchbox_handler.py: `Path.stat()` inside an
async test (ASYNC240) now goes through `anyio.Path`, as the rest of the
codebase already does.

Whole-project mypy: 64 errors in 23 files -> 51 in 20, identical under
2.3.0 and 2.3.1.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SPpv6W2ygP9tQ61fTQxdYp

* fix(backend): keep gamelist media keys in one place

Review pointed out that `GamelistMediaKey` repeated all fourteen fields
of GamelistMetadataMedia. Python has no `keyof`, so any Literal of a
TypedDict's keys is a second declaration of them, and a field added to
the TypedDict would be left out of it without any error.

The three index sites go back to suppressing `literal-required`, now as
`# type: ignore[literal-required]` so plain mypy reads it as well as
Trunk. The TypedDict stays the only declaration of the key set.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SPpv6W2ygP9tQ61fTQxdYp

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-22 16:02:39 -05:00

171 lines
5.9 KiB
Python

"""Socket.IO events for real-time user game activity.
Handles:
- activity:start - client reports starting a game (emits activity:update)
- activity:heartbeat - client refreshes TTL while playing (emits activity:update)
- activity:stop - client reports stopping (emits activity:clear)
- disconnect - safety net: clears any activity registered for the socket
The acting user is never taken from the client payload — it is resolved from
the authenticated socket session (stored on connect, see ``endpoints.sockets``)
so a client cannot broadcast a "now playing" session on behalf of another user.
Only ``rom_id`` / ``device_id`` come from the client.
All events broadcast to every connected client on the main `/ws` namespace.
"""
from __future__ import annotations
from typing import TYPE_CHECKING, Any, TypedDict
from handler.activity_handler import activity_handler
from handler.database import db_user_handler
from handler.socket_handler import socket_handler
from logger.logger import log
if TYPE_CHECKING:
from models.user import User
# Socket-session key holding the authenticated user id, written by the connect
# handler. Identity for every activity event is derived from this, not payload.
AUTH_USER_SESSION_KEY = "activity_auth_user_id"
class ActivityEventPayload(TypedDict, total=False):
rom_id: int
device_id: str
async def _session(sid: str) -> dict[str, Any]:
try:
return await socket_handler.socket_server.get_session(sid) or {}
except KeyError:
return {}
async def store_authenticated_user(sid: str, user_id: int) -> None:
"""Record the authenticated user for a socket so activity events trust it.
Called from the connect handler once the session has been resolved. Without
this, activity events have no identity to act on and are ignored.
"""
existing = await _session(sid)
existing[AUTH_USER_SESSION_KEY] = user_id
await socket_handler.socket_server.save_session(sid, existing)
async def _authenticated_user_id(sid: str) -> int | None:
"""Return the user id resolved at connect time, or ``None`` if unauthenticated."""
user_id = (await _session(sid)).get(AUTH_USER_SESSION_KEY)
return int(user_id) if user_id is not None else None
async def get_authenticated_user(sid: str) -> User | None:
"""Return the ``User`` resolved for this socket at connect time, or ``None``.
Identity comes from the server-resolved session stored on connect, never
from the client, so socket event handlers can enforce authorization.
"""
user_id = await _authenticated_user_id(sid)
if user_id is None:
return None
return db_user_handler.get_user(user_id)
async def _store_session(sid: str, user_id: int, device_id: str) -> None:
"""Remember the user/device associated with a socket for disconnect cleanup."""
existing = await _session(sid)
existing["activity_user_id"] = user_id
existing["activity_device_id"] = device_id
await socket_handler.socket_server.save_session(sid, existing)
def _extract_payload(data: object) -> tuple[str | None, int | None]:
"""Return ``(device_id, rom_id)`` parsed from an event payload.
``user_id`` is deliberately not read from the client — identity comes from
the authenticated socket session, never the payload.
"""
if not isinstance(data, dict):
return None, None
device_id = data.get("device_id")
if not isinstance(device_id, str) or not device_id:
device_id = None
try:
data_rom_id = data.get("rom_id")
rom_id = int(data_rom_id) if data_rom_id else None
except TypeError, ValueError:
rom_id = None
return device_id, rom_id
@socket_handler.socket_server.on("activity:start")
async def activity_start(sid: str, data: ActivityEventPayload) -> None:
user_id = await _authenticated_user_id(sid)
device_id, rom_id = _extract_payload(data)
if user_id is None or device_id is None or rom_id is None:
log.debug(f"activity:start ignored (unauthenticated or invalid): {data}")
return
entry = await activity_handler.build_entry(
user_id=user_id,
device_id=device_id,
rom_id=rom_id,
preserve_started_at=False,
)
if entry is None:
return
await _store_session(sid, user_id, device_id)
await activity_handler.publish_active(entry)
@socket_handler.socket_server.on("activity:heartbeat")
async def activity_heartbeat(sid: str, data: ActivityEventPayload) -> None:
user_id = await _authenticated_user_id(sid)
device_id, rom_id = _extract_payload(data)
if user_id is None or device_id is None or rom_id is None:
return
entry = await activity_handler.build_entry(
user_id=user_id,
device_id=device_id,
rom_id=rom_id,
preserve_started_at=True,
)
if entry is None:
return
await _store_session(sid, user_id, device_id)
await activity_handler.publish_active(entry)
@socket_handler.socket_server.on("activity:stop")
async def activity_stop(sid: str, data: ActivityEventPayload | None = None) -> None:
user_id = await _authenticated_user_id(sid)
device_id: str | None = None
if data:
device_id, _ = _extract_payload(data)
# Fall back to the device stored at start time if the payload omits it.
if not device_id:
device_id = (await _session(sid)).get("activity_device_id")
if user_id is None or not device_id:
return
await activity_handler.publish_clear(int(user_id), device_id)
@socket_handler.socket_server.on("disconnect")
async def activity_on_disconnect(sid: str) -> None:
"""Safety net: clear any activity tied to a disconnecting socket."""
session = await _session(sid)
user_id = session.get("activity_user_id")
device_id = session.get("activity_device_id")
if user_id is None or not device_id:
return
await activity_handler.publish_clear(int(user_id), device_id)