chore(backend): enforce mypy's disallow_untyped_calls and disallow_untyped_decorators (#4827)

This commit is contained in:
Sam Dornan
2026-09-26 20:21:54 -04:00
committed by GitHub
parent 7c2b049b70
commit e0df54cba5
10 changed files with 46 additions and 31 deletions

View File

@@ -1,10 +1,10 @@
[mypy]
strict = True
# Not yet clean. Delete a line once its errors are fixed.
disallow_untyped_calls = False
disallow_untyped_decorators = False
disable_error_code = import-untyped
enable_error_code = ignore-without-code
# Packages that leave the methods we call unannotated. mypy matches a method by
# its receiver's class, so the worker that subclasses rq's is listed too.
untyped_calls_exclude = apprise,mutagen,rq,handler.rq_worker.RomMWorker
# INI configs take a regex here, not a TOML-style list.
exclude = (?x)(^|/)alembic/
@@ -12,6 +12,8 @@ exclude = (?x)(^|/)alembic/
[mypy-tests.*,conftest]
disallow_untyped_defs = False
disallow_incomplete_defs = False
disallow_untyped_calls = False
disallow_untyped_decorators = False
# mutagen ships types but re-exports FileType, File and APIC without __all__.
[mypy-mutagen.*]

View File

@@ -4,6 +4,7 @@ import glob
import json
import os
import sys
from collections.abc import Callable
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Final, NotRequired, Self, TextIO, TypedDict
@@ -938,7 +939,7 @@ class ConfigManager:
Ignoring one would relocate the library under the user.
"""
retired = {
retired: dict[str, tuple[str, Callable[[str], str]]] = {
"filesystem.roms_folder": (
STRUCTURE_DEFAULT_KEY,
lambda folder: f"{folder}/{{platform}}/{{game}}",

View File

@@ -99,7 +99,7 @@ def _extract_payload(data: object) -> tuple[str | None, int | None]:
return device_id, rom_id
@socket_handler.socket_server.on("activity:start")
@socket_handler.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)
@@ -120,7 +120,7 @@ async def activity_start(sid: str, data: ActivityEventPayload) -> None:
await activity_handler.publish_active(entry)
@socket_handler.socket_server.on("activity:heartbeat")
@socket_handler.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)
@@ -140,7 +140,7 @@ async def activity_heartbeat(sid: str, data: ActivityEventPayload) -> None:
await activity_handler.publish_active(entry)
@socket_handler.socket_server.on("activity:stop")
@socket_handler.on("activity:stop")
async def activity_stop(sid: str, data: ActivityEventPayload | None = None) -> None:
user_id = await _authenticated_user_id(sid)

View File

@@ -30,7 +30,7 @@ FORWARDER_LOCK_KEY: Final = "romm:logs:forwarder"
FORWARDER_LOCK_TTL: Final = 30 # seconds
@socket_handler.socket_server.on("connect")
@socket_handler.on("connect")
async def connect(sid: str, environ: dict[str, Any], auth: Any = None) -> None:
"""Resolve the authenticated user on socket connect.
@@ -57,7 +57,7 @@ async def connect(sid: str, environ: dict[str, Any], auth: Any = None) -> None:
# A server takes one handler per event, so this one does every module's cleanup.
@socket_handler.socket_server.on("disconnect")
@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)

View File

@@ -104,7 +104,7 @@ def _socket_room(session_id: str) -> str:
return f"netplay-room:{session_id}"
@netplay_socket_handler.socket_server.on("connect")
@netplay_socket_handler.on("connect")
async def connect(sid: str, environ: dict[str, Any], auth: Any = None) -> None:
"""Accept every socket, since guests join by password, storing the session's user."""
try:
@@ -138,7 +138,7 @@ async def _enter_room(
)
@netplay_socket_handler.socket_server.on("open-room")
@netplay_socket_handler.on("open-room")
async def open_room(sid: str, data: RoomData) -> str | None:
extra_data = data["extra"]
@@ -178,7 +178,7 @@ async def open_room(sid: str, data: RoomData) -> str | None:
return None
@netplay_socket_handler.socket_server.on("join-room")
@netplay_socket_handler.on("join-room")
async def join_room(
sid: str, data: RoomData
) -> str | tuple[None, dict[str, NetplayPlayerInfo]]:
@@ -252,7 +252,7 @@ async def _handle_leave(sid: str, session_id: str, player_id: str) -> None:
)
@netplay_socket_handler.socket_server.on("leave-room")
@netplay_socket_handler.on("leave-room")
async def leave_room(sid: str) -> None:
session = await netplay_socket_handler.get_session(sid)
session_id = session.pop(ROOM_SESSION_KEY, None)
@@ -266,7 +266,7 @@ async def leave_room(sid: str) -> None:
await netplay_socket_handler.socket_server.save_session(sid, session)
@netplay_socket_handler.socket_server.on("webrtc-signal")
@netplay_socket_handler.on("webrtc-signal")
async def webrtc_signal(sid: str, data: WebRTCSignalData) -> None:
target = data.get("target")
# Signals relay only between peers of one room, so a client cannot inject an
@@ -288,12 +288,12 @@ async def webrtc_signal(sid: str, data: WebRTCSignalData) -> None:
await netplay_socket_handler.socket_server.emit("webrtc-signal", payload, to=target)
@netplay_socket_handler.socket_server.on("webrtc-signal-error")
@netplay_socket_handler.on("webrtc-signal-error")
async def webrtc_signal_error(_sid: str, _error: str, _data: Any) -> None:
pass
@netplay_socket_handler.socket_server.on("disconnect")
@netplay_socket_handler.on("disconnect")
async def disconnect(sid: str) -> None:
await netplay_socket_handler.unbind_from_login_session(sid)
await leave_room(sid)
@@ -307,16 +307,16 @@ async def _broadcast_to_room(sid: str, event: str, data: Any) -> None:
)
@netplay_socket_handler.socket_server.on("data-message")
@netplay_socket_handler.on("data-message")
async def data_message(sid: str, data: Any) -> None:
await _broadcast_to_room(sid, "data-message", data)
@netplay_socket_handler.socket_server.on("snapshot")
@netplay_socket_handler.on("snapshot")
async def snapshot(sid: str, data: Any) -> None:
await _broadcast_to_room(sid, "snapshot", data)
@netplay_socket_handler.socket_server.on("input")
@netplay_socket_handler.on("input")
async def input(sid: str, data: Any) -> None:
await _broadcast_to_room(sid, "input", data)

View File

@@ -1515,7 +1515,7 @@ async def authorize_scan(sid: str) -> User | None:
return None
@socket_handler.socket_server.on("scan")
@socket_handler.on("scan")
async def scan_handler(sid: str, options: dict[str, Any]) -> None:
"""Scan socket endpoint
@@ -1582,7 +1582,7 @@ async def scan_handler(sid: str, options: dict[str, Any]) -> None:
)
@socket_handler.socket_server.on("scan:stop")
@socket_handler.on("scan:stop")
async def stop_scan_handler(sid: str) -> None:
"""Stop scan socket endpoint"""

View File

@@ -44,7 +44,8 @@ class RomMWorker(Worker):
def handle_work_horse_killed(
self, job: Job, retpid: int, ret_val: int, rusage: Any
) -> None:
super().handle_work_horse_killed(job, retpid, ret_val, rusage)
# mypy's untyped_calls_exclude cannot name the receiver of a super() call.
super().handle_work_horse_killed(job, retpid, ret_val, rusage) # type: ignore[no-untyped-call]
# RQ runs neither the failure callback nor the exception handlers for a
# killed horse, only for a job whose whole worker died.
exc_info = (AbandonedJobError, AbandonedJobError(), None)

View File

@@ -1,5 +1,5 @@
import asyncio
from collections.abc import Iterable
from collections.abc import Awaitable, Callable, Iterable
from typing import TYPE_CHECKING, Any, Final
import socketio
@@ -37,6 +37,15 @@ class SocketHandler:
self._write_manager: socketio.AsyncRedisManager | None = None
self._write_manager_loop: asyncio.AbstractEventLoop | None = None
def on[F: Callable[..., Awaitable[object]]](self, event: str) -> Callable[[F], F]:
"""Register a socket event handler without changing its signature."""
def register(handler: F) -> F:
self.socket_server.on(event, handler)
return handler
return register
def _login_session_sockets_key(self, session_id: str) -> str:
# Per channel, since a sid only means something to the server that issued it.
return f"session_sockets:{self.channel}:{session_id}"

View File

@@ -161,7 +161,7 @@ class TestOpenRoomAuthorization:
result = await open_room("sid", _open())
assert "Not authorized" in result
assert result is not None and "Not authorized" in result
rooms.handler.set.assert_not_awaited()
server.enter_room.assert_not_awaited()
@@ -174,7 +174,7 @@ class TestOpenRoomAuthorization:
result = await open_room("sid", _open())
assert "Not authorized" in result
assert result is not None and "Not authorized" in result
rooms.handler.set.assert_not_awaited()
async def test_rejects_a_user_disabled_after_connecting(
@@ -188,7 +188,7 @@ class TestOpenRoomAuthorization:
result = await open_room("sid", _open())
assert "Not authorized" in result
assert result is not None and "Not authorized" in result
rooms.handler.set.assert_not_awaited()
async def test_rejects_hidden_rom(self, mocker, server, rooms):
@@ -201,7 +201,7 @@ class TestOpenRoomAuthorization:
result = await open_room("sid", _open())
assert "Not authorized" in result
assert result is not None and "Not authorized" in result
rooms.handler.set.assert_not_awaited()
async def test_rejects_unknown_rom(self, mocker, server, rooms):
@@ -214,7 +214,7 @@ class TestOpenRoomAuthorization:
result = await open_room("sid", _open())
assert "Not authorized" in result
assert result is not None and "Not authorized" in result
rooms.handler.set.assert_not_awaited()
async def test_rejects_missing_game_id(self, mocker, server, rooms):
@@ -226,7 +226,7 @@ class TestOpenRoomAuthorization:
result = await open_room("sid", _open(game_id=None))
assert "Not authorized" in result
assert result is not None and "Not authorized" in result
rooms.handler.set.assert_not_awaited()
async def test_allows_visible_rom(self, mocker, server, rooms):
@@ -545,4 +545,5 @@ class TestConnectIdentity:
async def test_never_refuses_the_connection(self, server, authenticate):
authenticate.side_effect = RuntimeError("redis down")
assert await connect("sid", {}) is None
# socketio refuses the connection when the handler returns False.
assert await connect("sid", {}) is None # type: ignore[func-returns-value]

View File

@@ -9,6 +9,7 @@ import mutagen
from mutagen.flac import FLAC, Picture
from mutagen.id3 import APIC, ID3
from mutagen.mp4 import MP4
from mutagen.ogg import OggFileType
from mutagen.oggopus import OggOpus
from mutagen.oggvorbis import OggVorbis
@@ -283,7 +284,7 @@ def _extract_picture_from_flac(audio: FLAC) -> tuple[bytes, str] | None:
return None
def _extract_picture_from_ogg(audio: OggVorbis | OggOpus) -> tuple[bytes, str] | None:
def _extract_picture_from_ogg(audio: OggFileType) -> tuple[bytes, str] | None:
import base64
pics = audio.get("metadata_block_picture") or []