Files
romm/backend/endpoints/sockets/netplay.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

225 lines
7.1 KiB
Python

from typing import Any, NotRequired, TypedDict
from endpoints.netplay import DEFAULT_MAX_PLAYERS
from handler.netplay_handler import NetplayPlayerInfo, NetplayRoom, netplay_handler
from handler.socket_handler import netplay_socket_handler
class RoomDataExtra(TypedDict):
sessionid: str | None
userid: str | None
playerId: str | None
room_name: NotRequired[str]
game_id: NotRequired[str]
domain: NotRequired[str]
player_name: NotRequired[str]
room_password: NotRequired[str]
class RoomData(TypedDict):
extra: RoomDataExtra
maxPlayers: NotRequired[int]
@netplay_socket_handler.socket_server.on("open-room")
async def open_room(sid: str, data: RoomData):
extra_data = data["extra"]
session_id = extra_data.get("sessionid")
player_id = extra_data.get("userid") or extra_data.get("playerId")
if not session_id or not player_id:
return "Invalid data: sessionId and playerId required"
if await netplay_handler.get(session_id):
return "Room already exists"
new_room = NetplayRoom(
owner=sid,
players={
player_id: NetplayPlayerInfo(
socketId=sid,
player_name=extra_data.get("player_name") or f"Player {player_id}",
userid=extra_data.get("userid"),
playerId=extra_data.get("playerId"),
)
},
peers=[],
room_name=extra_data.get("room_name") or f"Room {session_id}",
game_id=extra_data.get("game_id") or "default",
domain=extra_data.get("domain", None),
password=extra_data.get("room_password", None),
max_players=data.get("maxPlayers") or DEFAULT_MAX_PLAYERS,
)
await netplay_handler.set(session_id, new_room)
await netplay_socket_handler.socket_server.enter_room(sid, session_id)
await netplay_socket_handler.socket_server.save_session(
sid,
{
"session_id": session_id,
"player_id": player_id,
},
)
await netplay_socket_handler.socket_server.emit(
"users-updated", new_room["players"], room=session_id
)
@netplay_socket_handler.socket_server.on("join-room")
async def join_room(sid: str, data: RoomData):
extra_data = data["extra"]
session_id = extra_data.get("sessionid")
player_id = extra_data.get("userid") or extra_data.get("playerId")
if not session_id or not player_id:
return "Invalid data: sessionId and playerId required"
current_room = await netplay_handler.get(session_id)
if not current_room:
return "Room not found"
if current_room["password"] and current_room["password"] != extra_data.get(
"room_password"
):
return "Incorrect password"
if len(current_room["players"].keys()) >= current_room["max_players"]:
return "Room is full"
current_room["players"][player_id] = NetplayPlayerInfo(
socketId=sid,
player_name=extra_data.get("player_name") or f"Player {player_id}",
userid=extra_data.get("userid"),
playerId=extra_data.get("playerId"),
)
await netplay_handler.set(session_id, current_room)
await netplay_socket_handler.socket_server.enter_room(sid, session_id)
await netplay_socket_handler.socket_server.save_session(
sid,
{
"session_id": session_id,
"player_id": player_id,
},
)
await netplay_socket_handler.socket_server.emit(
"users-updated", current_room["players"], room=session_id
)
return None, current_room["players"]
async def _handle_leave(sid: str, session_id: str, player_id: str):
current_room = await netplay_handler.get(session_id)
if not current_room:
return
current_room["players"].pop(player_id, None)
if not current_room["players"]:
await netplay_handler.delete([session_id])
# Notify clients that the room is now empty
await netplay_socket_handler.socket_server.emit(
"users-updated", {}, room=session_id
)
return
if sid == current_room["owner"]:
# Owner left, assign a new one
remaining_players = list(current_room["players"].values())
if remaining_players:
current_room["owner"] = remaining_players[0]["socketId"]
await netplay_handler.set(session_id, current_room)
await netplay_socket_handler.socket_server.emit(
"users-updated", current_room["players"], room=session_id
)
@netplay_socket_handler.socket_server.on("leave-room")
async def leave_room(sid: str):
stored_session = await netplay_socket_handler.socket_server.get_session(sid)
session_id = stored_session.get("session_id")
player_id = stored_session.get("player_id")
if session_id and player_id:
await _handle_leave(sid, session_id, player_id)
await netplay_socket_handler.socket_server.leave_room(sid, session_id)
class WebRTCSignalData(TypedDict, total=False):
target: str
candidate: Any
offer: Any
answer: Any
requestRenegotiate: bool
@netplay_socket_handler.socket_server.on("webrtc-signal")
async def webrtc_signal(sid: str, data: WebRTCSignalData):
target = data.get("target")
request_renegotiate = data.get("requestRenegotiate", False)
if request_renegotiate:
if not target:
return
await netplay_socket_handler.socket_server.emit(
"webrtc-signal",
{"sender": sid, "requestRenegotiate": True},
to=target,
)
else:
if not target:
return # drop message, no recipient
await netplay_socket_handler.socket_server.emit(
"webrtc-signal",
{
"sender": sid,
"candidate": data.get("candidate"),
"offer": data.get("offer"),
"answer": data.get("answer"),
},
to=target,
)
@netplay_socket_handler.socket_server.on("webrtc-signal-error")
async def webrtc_signal_error(_sid: str, _error: str, _data: Any):
pass
@netplay_socket_handler.socket_server.on("disconnect")
async def disconnect(sid: str):
stored_session = await netplay_socket_handler.socket_server.get_session(sid)
session_id = stored_session.get("session_id")
player_id = stored_session.get("player_id")
if session_id and player_id:
await _handle_leave(sid, session_id, player_id)
async def _broadcast_to_room(sid: str, event: str, data: Any):
stored_session = await netplay_socket_handler.socket_server.get_session(sid)
session_id = stored_session.get("session_id")
if session_id:
await netplay_socket_handler.socket_server.emit(
event, data, room=session_id, skip_sid=sid
)
@netplay_socket_handler.socket_server.on("data-message")
async def data_message(sid: str, data: Any):
await _broadcast_to_room(sid, "data-message", data)
@netplay_socket_handler.socket_server.on("snapshot")
async def snapshot(sid: str, data: Any):
await _broadcast_to_room(sid, "snapshot", data)
@netplay_socket_handler.socket_server.on("input")
async def input(sid: str, data: Any):
await _broadcast_to_room(sid, "input", data)