diff --git a/backend/endpoints/streaming.py b/backend/endpoints/streaming.py index fbe8598e4..9cd4d1f65 100644 --- a/backend/endpoints/streaming.py +++ b/backend/endpoints/streaming.py @@ -100,6 +100,7 @@ from handler.streaming.config import ( first_claim_targets, streaming_enabled, ) +from handler.streaming.notices import record_termination from handler.streaming.protocol import room_url_on from handler.streaming.session_store import ( STREAMING_SESSION_DRAIN_SECONDS, @@ -117,7 +118,6 @@ from handler.streaming.session_store import ( iter_live_sessions, iter_session_keys, mutate_session, - record_termination, refresh_session, release_own_session, same_claim, diff --git a/backend/handler/streaming/launch.py b/backend/handler/streaming/launch.py index 4e13edbb2..3badd7e8c 100644 --- a/backend/handler/streaming/launch.py +++ b/backend/handler/streaming/launch.py @@ -25,10 +25,10 @@ from handler.streaming import ( webstation, ) from handler.streaming.config import ResolvedContainer +from handler.streaming.notices import push_to_user from handler.streaming.session_store import ( StreamingSession, hold_session_claim, - push_to_user, set_session_disc, stamp_launched, ) diff --git a/backend/handler/streaming/lifecycle.py b/backend/handler/streaming/lifecycle.py index fdcaebf70..890acc97e 100644 --- a/backend/handler/streaming/lifecycle.py +++ b/backend/handler/streaming/lifecycle.py @@ -22,6 +22,7 @@ from handler.streaming.config import ( container_for_session, containers_by_key, ) +from handler.streaming.notices import record_termination from handler.streaming.session_store import ( DRAIN_MARKER_TTL, DiscSwap, @@ -33,7 +34,6 @@ from handler.streaming.session_store import ( drop_drain_marker, hold_drain_marker, hold_session_claim, - record_termination, release_own_session, replace_session_if, restore_drained_session, diff --git a/backend/handler/streaming/notices.py b/backend/handler/streaming/notices.py new file mode 100644 index 000000000..7a1d09d6b --- /dev/null +++ b/backend/handler/streaming/notices.py @@ -0,0 +1,73 @@ +"""Telling a player what happened to their streaming session. + +Kept apart from session_store because delivery loads the socket server and the +database, which the streaming worker's parent must not hold. +""" + +from datetime import datetime, timezone +from typing import Any + +from handler.notification_handler import notify +from handler.socket_handler import socket_handler +from handler.streaming.session_store import ( + StreamingSession, + save_termination, + session_is_desktop, +) +from models.notification import NotificationKind, NotificationLevel + + +async def record_termination( + session: StreamingSession, + session_key: str, + *, + ended_by: str | None, + reason: str | None, + ended_by_user_id: int | None = None, +) -> None: + """Leave a note for the player whose session was taken away, and push it + over the socket so the poll isn't the only way that tab finds out. No-op + when the session records no owner, since there is nobody to notify.""" + user_id = session.get("user_id") + if not isinstance(user_id, int): + return + notice = { + "ended_by": ended_by, + "reason": reason or None, + "ended_at": datetime.now(timezone.utc).isoformat(), + "platform": session.get("platform"), + "rom_id": session.get("rom_id"), + "rom_name": session.get("rom_name"), + # Which claim ended: a user can hold one per container, plus a desktop, + # and only the tab that holds this one should act on the notice. + "container": session_key, + # A re-claim of the container keeps its key, so the stamp names the claim. + "claimed_at": session.get("claimed_at"), + "desktop": session_is_desktop(session), + } + await save_termination(session_key, user_id, notice) + await push_to_user(user_id, "streaming:session-ended", notice) + + if ended_by_user_id is not None and ended_by_user_id != user_id: + await notify( + user_id, + NotificationKind.STREAMING_SESSION_ENDED, + NotificationLevel.WARNING, + { + "rom_id": notice["rom_id"], + "rom_name": notice["rom_name"], + "platform": notice["platform"], + "reason": notice["reason"], + }, + actor_id=ended_by_user_id, + ) + + +async def push_to_user(user_id: Any, event: str, payload: dict[str, Any]) -> None: + """Tell one user's open tabs something happened to their session. + + Best-effort by design: every event pushed here also has a poll behind it, + so a dropped socket costs latency rather than correctness. + """ + if isinstance(user_id, int): + await socket_handler.emit_to_user(user_id, event, payload) diff --git a/backend/handler/streaming/session_store.py b/backend/handler/streaming/session_store.py index ceb0261b2..70908d046 100644 --- a/backend/handler/streaming/session_store.py +++ b/backend/handler/streaming/session_store.py @@ -24,12 +24,9 @@ from typing import Any, NamedTuple, TypedDict, cast from redis.exceptions import WatchError -from handler.notification_handler import notify from handler.redis_handler import as_text, async_cache -from handler.socket_handler import socket_handler from handler.streaming.config import HOLD_CEILING_SECONDS from logger.logger import log -from models.notification import NotificationKind, NotificationLevel # Sessions are stored in Redis so they are shared across uvicorn workers and # survive backend restarts (the emulator container keeps running either way). @@ -695,64 +692,14 @@ def _termination_redis_key(session_key: str, user_id: int) -> str: return f"{_TERMINATION_KEY_PREFIX}{session_key}:{user_id}" -async def record_termination( - session: StreamingSession, - session_key: str, - *, - ended_by: str | None, - reason: str | None, - ended_by_user_id: int | None = None, +async def save_termination( + session_key: str, user_id: int, notice: dict[str, Any] ) -> None: - """Leave a note for the player whose session was taken away, and push it - over the socket so the poll isn't the only way that tab finds out. No-op - when the session records no owner, since there is nobody to notify.""" - user_id = session.get("user_id") - if not isinstance(user_id, int): - return - notice = { - "ended_by": ended_by, - "reason": reason or None, - "ended_at": datetime.now(timezone.utc).isoformat(), - "platform": session.get("platform"), - "rom_id": session.get("rom_id"), - "rom_name": session.get("rom_name"), - # Which claim ended: a user can hold one per container, plus a desktop, - # and only the tab that holds this one should act on the notice. - "container": session_key, - # A re-claim of the container keeps its key, so the stamp names the claim. - "claimed_at": session.get("claimed_at"), - "desktop": session_is_desktop(session), - } await async_cache.set( _termination_redis_key(session_key, user_id), json.dumps(notice), ex=_TERMINATION_TTL_SECONDS, ) - await push_to_user(user_id, "streaming:session-ended", notice) - - if ended_by_user_id is not None and ended_by_user_id != user_id: - await notify( - user_id, - NotificationKind.STREAMING_SESSION_ENDED, - NotificationLevel.WARNING, - { - "rom_id": notice["rom_id"], - "rom_name": notice["rom_name"], - "platform": notice["platform"], - "reason": notice["reason"], - }, - actor_id=ended_by_user_id, - ) - - -async def push_to_user(user_id: Any, event: str, payload: dict[str, Any]) -> None: - """Tell one user's open tabs something happened to their session. - - Best-effort by design: every event pushed here also has a poll behind it, - so a dropped socket costs latency rather than correctness. - """ - if isinstance(user_id, int): - await socket_handler.emit_to_user(user_id, event, payload) async def get_termination(session_key: str, user_id: int) -> dict[str, Any] | None: diff --git a/backend/tasks/scheduled/reap_streaming_sessions.py b/backend/tasks/scheduled/reap_streaming_sessions.py index 1bde5cfe0..e746f5db7 100644 --- a/backend/tasks/scheduled/reap_streaming_sessions.py +++ b/backend/tasks/scheduled/reap_streaming_sessions.py @@ -6,7 +6,6 @@ from handler.streaming.config import ( containers_by_key, streaming_enabled, ) -from handler.streaming.lifecycle import teardown_abandoned_session from handler.streaming.session_store import ( get_abandoned_session, in_restart_grace, @@ -26,6 +25,9 @@ async def _reap( record = container_for_session(grouped, container_key, session.get("platform")) if record is None: return + # Imported here so the streaming worker's parent never loads the database. + from handler.streaming.lifecycle import teardown_abandoned_session + if await teardown_abandoned_session( record, container_key, session, claimed_by=None ): diff --git a/backend/tests/endpoints/test_streaming.py b/backend/tests/endpoints/test_streaming.py index 446b55649..3a2e31402 100644 --- a/backend/tests/endpoints/test_streaming.py +++ b/backend/tests/endpoints/test_streaming.py @@ -3480,7 +3480,7 @@ def test_taking_over_ones_own_stale_session_pushes_no_notice( _age_session(rom, session_store._STREAMING_SESSION_STALE_SECONDS + 60) with ( _stub_stop(), - patch("handler.streaming.session_store.push_to_user", new=_capture), + patch("handler.streaming.notices.push_to_user", new=_capture), ): _claim_ok(client, access_token, rom.id) diff --git a/backend/tests/tasks/test_reap_streaming_sessions.py b/backend/tests/tasks/test_reap_streaming_sessions.py index ccbf9b3a3..23bac504c 100644 --- a/backend/tests/tasks/test_reap_streaming_sessions.py +++ b/backend/tests/tasks/test_reap_streaming_sessions.py @@ -90,7 +90,7 @@ async def _hold( def _stub_teardown(teardown: Any = None) -> Any: return patch( - "tasks.scheduled.reap_streaming_sessions.teardown_abandoned_session", + "handler.streaming.lifecycle.teardown_abandoned_session", new=teardown or AsyncMock(return_value=True), ) diff --git a/backend/tests/tasks/test_task_func_paths.py b/backend/tests/tasks/test_task_func_paths.py index aa2e5a65c..a073a04d8 100644 --- a/backend/tests/tasks/test_task_func_paths.py +++ b/backend/tests/tasks/test_task_func_paths.py @@ -40,10 +40,42 @@ def test_task_func_resolves_in_a_fresh_interpreter(func): assert result.returncode == 0, f"{func} is not importable by RQ:\n{result.stderr}" +def _loaded_after( + setup: str, watched: tuple[str, ...], base_path: Path, then: str = "" +) -> str: + """List the `watched` modules a fresh interpreter loads for `setup`, then run `then`.""" + result = subprocess.run( + [ + sys.executable, + "-c", + "import sys\n" + f"{setup}\n" + "watched = sys.argv[1:]\n" + "loaded = ','.join(m for m in sys.modules\n" + " if any(m == w or m.startswith(w + '.') for w in watched))\n" + f"{then}\n" + "print('LOADED:' + loaded)\n", + *watched, + ], + cwd=BACKEND_ROOT, + env={ + **os.environ, + "PYTHONPATH": str(BACKEND_ROOT), + "ROMM_BASE_PATH": str(base_path), + # A developer's .env could otherwise turn telemetry on. + "OTEL_SDK_DISABLED": "true", + }, + capture_output=True, + text=True, + ) + + assert result.returncode == 0, result.stderr + return result.stdout.rpartition("LOADED:")[2].strip() + + # Loaded only by the jobs that need them, so the long-lived scheduler and # worker parents stay small. Each name covers its submodules too. -JOB_ONLY_MODULES = ( - "tasks.scheduled", +HEAVY_MODULES = ( "tasks.manual", "tasks.sync_push_pull_task", "handler.database", @@ -52,6 +84,7 @@ JOB_ONLY_MODULES = ( "httpx2", "sqlalchemy", ) +JOB_ONLY_MODULES = ("tasks.scheduled", *HEAVY_MODULES) @pytest.mark.parametrize("module", ["tasks.cron_config", "handler.rq_worker"]) @@ -64,30 +97,37 @@ def test_the_scheduler_and_worker_load_no_task_code( ) -> None: (tmp_path / "config").mkdir() (tmp_path / "config" / "config.yml").write_text(config_yml) - result = subprocess.run( - [ - sys.executable, - "-c", - "import importlib, sys\n" - "importlib.import_module(sys.argv[1])\n" - "watched = sys.argv[2:]\n" - "print('LOADED:' + ','.join(m for m in sys.modules\n" - " if any(m == w or m.startswith(w + '.') for w in watched)))\n", - module, - *JOB_ONLY_MODULES, - ], - cwd=BACKEND_ROOT, - env={ - **os.environ, - "PYTHONPATH": str(BACKEND_ROOT), - "ROMM_BASE_PATH": str(tmp_path), - # A developer's .env could otherwise turn telemetry on. - "OTEL_SDK_DISABLED": "true", - }, - capture_output=True, - text=True, + loaded = _loaded_after(f"import {module}", JOB_ONLY_MODULES, tmp_path) + + assert loaded == "", f"{module} loads {loaded}" + + +# The streaming work horse loads these only when it tears down a session or sends a notice. +PRELOAD_DEFERRED_MODULES = ( + *HEAVY_MODULES, + "handler.scan", + "handler.metadata", + "handler.streaming.lifecycle", + "handler.socket_handler", + "endpoints", +) + + +def test_the_streaming_worker_preloads_its_tasks_without_their_teardown( + tmp_path: Path, +) -> None: + """The parent keeps what it preloads, and a work horse can still import the rest.""" + # PreloadingWorker loads only the enabled tasks, and this loads all of them. + loaded = _loaded_after( + "import handler.rq_worker\n" + "from handler.redis_handler import STREAMING_QUEUE_NAME\n" + "from tasks.registry import SCHEDULED_TASKS, get_task\n" + "for name, spec in SCHEDULED_TASKS.items():\n" + " if spec.queue_name == STREAMING_QUEUE_NAME:\n" + " get_task(name)", + PRELOAD_DEFERRED_MODULES, + tmp_path, + then="import handler.streaming.lifecycle, handler.notification_handler", ) - assert result.returncode == 0, result.stderr - loaded = result.stdout.rpartition("LOADED:")[2].strip() - assert loaded == "", f"{module} loads {loaded}" + assert loaded == "", f"the streaming preload loads {loaded}"