From 7713f8df3f14101bef22c25a1236bf6c73624875 Mon Sep 17 00:00:00 2001 From: imSp4rky Date: Sat, 28 Nov 2026 21:11:48 -0700 Subject: [PATCH] fix(api): stop serve cleanly with jobs, streams and remote sessions open --- docs/dev/rest-api/dashboard.md | 4 +- docs/dev/rest-api/endpoints.md | 2 +- docs/dev/rest-api/remote-sessions.md | 5 +- tests/remote/conftest.py | 6 +- tests/remote/unit/test_dashboard.py | 24 ++++++ tests/remote/unit/test_download_manager.py | 91 ++++++++++++++++++++++ tests/remote/unit/test_session_store.py | 13 ++++ unshackle/commands/serve.py | 8 +- unshackle/core/api/download_manager.py | 64 +++++++-------- unshackle/core/api/events.py | 21 +++++ unshackle/core/api/handlers.py | 8 ++ unshackle/core/api/routes.py | 4 + unshackle/core/api/session_store.py | 17 ++-- 13 files changed, 222 insertions(+), 45 deletions(-) diff --git a/docs/dev/rest-api/dashboard.md b/docs/dev/rest-api/dashboard.md index 7dc1c25d..4f1d4e0d 100644 --- a/docs/dev/rest-api/dashboard.md +++ b/docs/dev/rest-api/dashboard.md @@ -72,8 +72,8 @@ characters of the API key. ## Event stream `/api/dashboard/events` sends a `stats` event (the same body as `/status`) on connect and -then every 5 seconds, so the connection stays alive and the counters stay current. Between -those it sends: +then every 5 seconds, so the connection stays alive and the counters stay current. The server +closes the connection when it stops. Between those it sends: | Event | Data | |-------|------| diff --git a/docs/dev/rest-api/endpoints.md b/docs/dev/rest-api/endpoints.md index 6fc58728..02f4ae63 100644 --- a/docs/dev/rest-api/endpoints.md +++ b/docs/dev/rest-api/endpoints.md @@ -405,7 +405,7 @@ Every track carries the same fields as a local track: `is_original_lang`, `name` Downloads are asynchronous. `POST /api/download` enqueues a job and returns immediately with a `job_id`. The server runs each job in a background job worker subprocess. You then poll the job endpoints for progress and results. !!! info "Job states" - A job moves through `queued` → `downloading` → one of the terminal states `completed`, `failed`, or `cancelled`. You can prioritise only queued jobs. You can retry or remove only terminal jobs. + A job moves through `queued` → `downloading` → one of the terminal states `completed`, `failed`, or `cancelled`. You can prioritise only queued jobs. You can retry or remove only terminal jobs. When the server stops, it cancels each queued and downloading job and refuses a new job with `SERVER_DRAINING` (409). ### `POST /api/download` diff --git a/docs/dev/rest-api/remote-sessions.md b/docs/dev/rest-api/remote-sessions.md index 17726d49..2afd80c8 100644 --- a/docs/dev/rest-api/remote-sessions.md +++ b/docs/dev/rest-api/remote-sessions.md @@ -617,8 +617,9 @@ Source: `unshackle/core/api/session_store.py`. A singleton you get from `ttl`, in-flight-auth remote sessions expire at `AUTH_INPUT_TIMEOUT`. The removal of a remote session cancels its `InputBridge` and deletes its cache directory (pruning empty parent dirs up to, but not including, the cache root). -- The server calls **`cancel_all_bridges()`** on shutdown, to unblock any waiting - auth threads. +- The server calls **`cancel_all_bridges()`** on shutdown. It ends each open remote session, which + unblocks any waiting auth threads, and deletes the cache directory of each one. The server then waits up + to 5 seconds for each login that still runs, and deletes its cache directory again when it ends. `SessionEntry` fields: diff --git a/tests/remote/conftest.py b/tests/remote/conftest.py index 24f49695..882e8c26 100644 --- a/tests/remote/conftest.py +++ b/tests/remote/conftest.py @@ -88,10 +88,14 @@ def wait_for_health(url: str, secret_key: str, timeout: float = 60.0) -> bool: @pytest.fixture(autouse=True) def isolated_job_history(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: - """Redirect job history writes to tmp_path so tests don't append to the server's api_history.jsonl.""" + """Redirect job history writes to tmp_path and give each test its own download manager. + + An app teardown shuts the global manager down, and a shut-down manager refuses new jobs. + """ from unshackle.core.api import download_manager monkeypatch.setattr(download_manager, "history_path", lambda: tmp_path / "api_history.jsonl") + monkeypatch.setattr(download_manager, "download_manager", None) @pytest.fixture(scope="session") diff --git a/tests/remote/unit/test_dashboard.py b/tests/remote/unit/test_dashboard.py index 398d6ed9..6ed9f39a 100644 --- a/tests/remote/unit/test_dashboard.py +++ b/tests/remote/unit/test_dashboard.py @@ -175,6 +175,30 @@ async def test_events_burst_mode(aiohttp_client, dashboard_cfg) -> None: assert [e["data"]["action"] for e in body["events"] if e["event"] == "session"] == ["create", "delete"] +def test_bus_close_ends_a_full_subscriber_queue() -> None: + local = EventBus() + queue: asyncio.Queue = asyncio.Queue(maxsize=1) + local._subs.append(queue) + local.publish("session", {"action": "create"}) + local.close() + assert queue.get_nowait() is None + + +async def test_the_event_stream_ends_at_serve_shutdown(aiohttp_client, dashboard_cfg) -> None: + from unshackle.core.api.download_manager import shutdown_download_manager + from unshackle.core.api.events import close_event_streams + + app = make_app() + assert {close_event_streams, shutdown_download_manager} <= set(app.on_shutdown) + client = await aiohttp_client(app) + resp = await client.get("/api/dashboard/events", headers={"X-Secret-Key": "dash-secret"}) + assert resp.status == 200 + await asyncio.wait_for(resp.content.readuntil(b"\n\n"), timeout=10) + await close_event_streams(app) + await asyncio.wait_for(resp.content.read(), timeout=10) + assert resp.content.at_eof() + + async def test_session_action_log() -> None: store = SessionStore() entry = await store.create("EXAMPLE", object(), owner_key="k") diff --git a/tests/remote/unit/test_download_manager.py b/tests/remote/unit/test_download_manager.py index 6f3fe392..5391fcb0 100644 --- a/tests/remote/unit/test_download_manager.py +++ b/tests/remote/unit/test_download_manager.py @@ -6,6 +6,9 @@ cleanup/serialize); they do not exercise the actual subprocess download path. from __future__ import annotations +import asyncio +from collections.abc import Callable +from contextlib import suppress from datetime import datetime, timedelta from pathlib import Path from typing import Any @@ -764,3 +767,91 @@ def test_a_download_error_keeps_the_code_its_raiser_named( download_manager.perform_download("job-1", "EXAMPLE1", "t1", {}) assert exc.value.error_code == (APIErrorCode.WORKER_ERROR if carrier == "none" else APIErrorCode.DRM_ERROR) + + +async def _until(condition: Callable[[], bool], timeout: float = 10.0) -> None: + """Wait for ``condition`` with a deadline.""" + loop = asyncio.get_running_loop() + deadline = loop.time() + timeout + while not condition(): + assert loop.time() < deadline, "condition not met before the deadline" + await asyncio.sleep(0.01) + + +@pytest.fixture +def downloading(monkeypatch: pytest.MonkeyPatch, manager: DownloadQueueManager) -> Any: + """A manager whose jobs download until cancelled, with no history file written.""" + from unshackle.core.api import download_manager + + started = asyncio.Event() + + async def block(job: DownloadJob) -> None: + started.set() + await asyncio.Event().wait() + + monkeypatch.setattr(manager, "execute_download", block) + monkeypatch.setattr(download_manager, "record_job_history", lambda job: None) + return started + + +async def test_a_cancel_of_the_worker_task_ends_it_while_a_job_downloads( + manager: DownloadQueueManager, downloading: Any +) -> None: + worker = asyncio.create_task(manager.download_worker("w")) + job = manager.create_job("EXAMPLE", "t") + await asyncio.wait_for(downloading.wait(), timeout=10) + + worker.cancel() + with pytest.raises(asyncio.CancelledError): + await asyncio.wait_for(worker, timeout=10) + assert job.status is JobStatus.CANCELLED + assert job.completed_time is not None + + +async def test_a_cancel_of_the_job_download_keeps_the_worker_running( + manager: DownloadQueueManager, downloading: Any +) -> None: + worker = asyncio.create_task(manager.download_worker("w")) + try: + job = manager.create_job("EXAMPLE", "t") + await asyncio.wait_for(downloading.wait(), timeout=10) + manager._active_downloads[job.job_id].cancel() + await _until(lambda: job.completed_time is not None) + assert job.status is JobStatus.CANCELLED + assert not worker.done() + finally: + worker.cancel() + with suppress(asyncio.CancelledError): + await worker + + +async def test_shutdown_cancels_every_job_and_ends_each_stream_on_its_terminal_event( + manager: DownloadQueueManager, downloading: Any +) -> None: + from unshackle.core.api.errors import APIError + + worker = asyncio.create_task(manager.download_worker("w")) + running = manager.create_job("EXAMPLE", "t") + await asyncio.wait_for(downloading.wait(), timeout=10) + queued = manager.create_job("EXAMPLE", "u") + streams = {job.job_id: manager.subscribe(job.job_id) for job in (running, queued)} + + await manager.shutdown() + await asyncio.wait_for(worker, timeout=10) + for job in (running, queued): + assert job.status is JobStatus.CANCELLED + assert job.completed_time is not None + events = [] + while (item := await asyncio.wait_for(streams[job.job_id].get(), timeout=10)) is not None: + events.append(item["event"]) + assert events[-1] == "cancelled" + with pytest.raises(APIError): + manager.create_job("EXAMPLE", "v") + + +async def test_the_shutdown_hook_makes_no_manager(monkeypatch: pytest.MonkeyPatch) -> None: + from unshackle.core.api import download_manager + + monkeypatch.setattr(download_manager, "download_manager", None) + await download_manager.shutdown_download_manager(object()) + assert download_manager.download_manager is None diff --git a/tests/remote/unit/test_session_store.py b/tests/remote/unit/test_session_store.py index 209d6136..7d903a75 100644 --- a/tests/remote/unit/test_session_store.py +++ b/tests/remote/unit/test_session_store.py @@ -134,6 +134,19 @@ async def test_cancel_all_bridges(store: SessionStore) -> None: entry.input_bridge.ensure_active() +async def test_cancel_all_bridges_removes_the_session_cache_dirs( + store: SessionStore, monkeypatch: pytest.MonkeyPatch +) -> None: + removed: list = [] + monkeypatch.setattr(SessionStore, "cleanup_cache_dir", staticmethod(removed.append)) + entry = await store.create("EXAMPLE", _FakeService(), cache_tag="_sessions/k/s/EXAMPLE") + await store.create("OTHER", _FakeService()) + + await store.cancel_all_bridges() + assert removed == [entry.cache_tag, None] + assert store.session_count == 0 + + async def test_get_session_store_returns_singleton() -> None: a = get_session_store() b = get_session_store() diff --git a/unshackle/commands/serve.py b/unshackle/commands/serve.py index 151f098b..ebbb4f5a 100644 --- a/unshackle/commands/serve.py +++ b/unshackle/commands/serve.py @@ -58,7 +58,12 @@ class _MaskAccessKey(logging.Filter): def _install_session_store(app: web.Application) -> None: - """Start the remote session store's idle sweep with the app and stop it, bridges included, on cleanup.""" + """Start the remote session store's idle sweep with the app and stop it, bridges included, on cleanup. + + A login thread can still write the remote session cache after its bridge ends, so cleanup waits for the + logins, and each login that ends removes that cache directory again. + """ + from unshackle.core.api.handlers import wait_for_logins from unshackle.core.api.session_store import get_session_store session_store = get_session_store() @@ -68,6 +73,7 @@ def _install_session_store(app: web.Application) -> None: async def stop(_app: web.Application) -> None: await session_store.cancel_all_bridges() + await wait_for_logins(5) await session_store.stop_cleanup_loop() app.on_startup.append(start) diff --git a/unshackle/core/api/download_manager.py b/unshackle/core/api/download_manager.py index b5248238..211d2a04 100644 --- a/unshackle/core/api/download_manager.py +++ b/unshackle/core/api/download_manager.py @@ -17,7 +17,7 @@ from enum import Enum from pathlib import Path from typing import TYPE_CHECKING, Any -from unshackle.core.api.events import bus, publish_service_event +from unshackle.core.api.events import bus, publish_service_event, put_latest from unshackle.core.api.sanitize import sanitize_log from unshackle.core.credential import Credential from unshackle.core.utils.redact import REDACTED, URL_USERINFO_RE, redact_all, redact_path, redact_text @@ -531,9 +531,15 @@ class DownloadQueueManager: def create_job(self, service: str, title_id: str, owner_key: str | None = None, **parameters: Any) -> DownloadJob: """Make a new download job and add it to the queue.""" + from unshackle.core.api.errors import APIError from unshackle.core.api.session_store import refuse_while_draining + from unshackle.core.remote_protocol import APIErrorCode refuse_while_draining() + if self._shutdown_event.is_set(): + raise APIError( + APIErrorCode.SERVER_DRAINING, "This server is stopping and starts no new downloads", retryable=True + ) job_id = str(uuid.uuid4()) job = DownloadJob( job_id=job_id, @@ -585,13 +591,13 @@ class DownloadQueueManager: return payload = {"event": event, "data": data} for queue in queues: - self.put(queue, payload) + put_latest(queue, payload) def publish_terminal(self, job: DownloadJob) -> None: """Publish a job's final state, close every listener's event stream, then apply staged service reloads.""" self.publish(job, job.status.value) for queue in self._subscribers.pop(job.job_id, []): - self.put(queue, None) + put_latest(queue, None) self.schedule_pending_reload() def busy_services(self) -> set[str]: @@ -602,17 +608,6 @@ class DownloadQueueManager: """Swap in staged service updates whose last job has finished, off the event loop.""" schedule_pending_reload() - @staticmethod - def put(queue: asyncio.Queue, item: dict[str, Any] | None) -> None: - """Enqueue an item, discarding the oldest when a slow listener has filled the queue.""" - try: - queue.put_nowait(item) - except asyncio.QueueFull: - with suppress(asyncio.QueueEmpty): - queue.get_nowait() - with suppress(asyncio.QueueFull): - queue.put_nowait(item) - def cancel_job(self, job_id: str) -> bool: """Cancel a job that has the queued or the downloading status.""" job = self._jobs.get(job_id) @@ -734,32 +729,20 @@ class DownloadQueueManager: log.info(f"Started {self.max_concurrent_downloads} download workers") async def shutdown(self) -> None: - """Shutdown the queue manager and cancel all active downloads.""" + """Cancel every queued and downloading job, so each job event stream ends on its terminal event.""" log.info("Shutting down download queue manager") self._shutdown_event.set() - for queues in list(self._subscribers.values()): - for queue in queues: - self.put(queue, None) - self._subscribers.clear() - - # Cancel all active downloads - for task in self._active_downloads.values(): - task.cancel() - - # Terminate worker processes - for job_id, process in list(self._download_processes.items()): - try: - process.terminate() - except ProcessLookupError: - log.debug(f"Worker process for job {job_id} already exited during shutdown") + for job_id in list(self._jobs): + self.cancel_job(job_id) for job_id, process in list(self._download_processes.items()): try: await asyncio.wait_for(process.wait(), timeout=5) except TimeoutError: log.warning(f"Worker process for job {job_id} did not exit, killing") - process.kill() + with suppress(ProcessLookupError): + process.kill() await process.wait() finally: self._download_processes.pop(job_id, None) @@ -777,8 +760,16 @@ class DownloadQueueManager: if self._active_downloads: await asyncio.gather(*self._active_downloads.values(), return_exceptions=True) + for queues in list(self._subscribers.values()): + for queue in queues: + put_latest(queue, None) + self._subscribers.clear() + async def download_worker(self, worker_name: str) -> None: - """Job worker task that processes jobs from the queue.""" + """Job worker task that processes jobs from the queue. + + A cancel of one job's download task keeps the worker running; a cancel of the worker task itself ends it. + """ log.debug(f"Download worker {worker_name} started") while not self._shutdown_event.is_set(): @@ -811,6 +802,8 @@ class DownloadQueueManager: except asyncio.CancelledError: job.status = JobStatus.CANCELLED log.info(f"Job {job.job_id} was cancelled") + if (worker := asyncio.current_task()) is not None and worker.cancelling(): + raise except Exception as e: job.status = JobStatus.FAILED job.error_message = str(e) @@ -828,6 +821,7 @@ class DownloadQueueManager: continue except Exception as e: log.error(f"Worker {worker_name} error: {e}") + await asyncio.sleep(1) async def execute_download(self, job: DownloadJob) -> None: """Do the actual download for a job.""" @@ -1087,6 +1081,12 @@ def get_download_manager() -> DownloadQueueManager: return download_manager +async def shutdown_download_manager(_app: object) -> None: + """Stop the download manager at serve shutdown, when this process made one.""" + if download_manager is not None: + await download_manager.shutdown() + + def busy_services() -> set[str]: """Tags a hot reload must not swap: those with an unfinished job and those a live remote session uses.""" from unshackle.core.api.session_store import get_session_store diff --git a/unshackle/core/api/events.py b/unshackle/core/api/events.py index b150550a..bb0d6a0b 100644 --- a/unshackle/core/api/events.py +++ b/unshackle/core/api/events.py @@ -31,6 +31,11 @@ class EventBus: with suppress(ValueError): self._subs.remove(queue) + def close(self) -> None: + """End every subscriber's stream with a None item.""" + for queue in list(self._subs): + put_latest(queue, None) + def since(self, seq: int) -> list[dict[str, Any]]: """Return the history after ``seq``. @@ -67,9 +72,25 @@ def _put_drop(queue: asyncio.Queue, item: dict[str, Any]) -> None: queue.put_nowait(item) +def put_latest(queue: asyncio.Queue, item: dict[str, Any] | None) -> None: + """Enqueue an item, discarding the oldest when a slow listener has filled the queue.""" + try: + queue.put_nowait(item) + except asyncio.QueueFull: + with suppress(asyncio.QueueEmpty): + queue.get_nowait() + with suppress(asyncio.QueueFull): + queue.put_nowait(item) + + bus = EventBus() +async def close_event_streams(_app: object) -> None: + """End the dashboard event streams at serve shutdown, so none holds the exit for the shutdown timeout.""" + bus.close() + + def publish_service_event(action: str, tags: list[str], errors: list[str] | None = None) -> None: """Tell dashboard listeners that services were staged, applied, or failed to reload. diff --git a/unshackle/core/api/handlers.py b/unshackle/core/api/handlers.py index 1e21a84d..a35ee981 100644 --- a/unshackle/core/api/handlers.py +++ b/unshackle/core/api/handlers.py @@ -1032,6 +1032,12 @@ _account_counters: dict[str, int] = {} _auth_tasks: set["asyncio.Task[None]"] = set() +async def wait_for_logins(timeout: float) -> None: + """Wait up to ``timeout`` seconds for the remote session logins that still run, at serve shutdown.""" + if _auth_tasks: + await asyncio.wait(set(_auth_tasks), timeout=timeout) + + def validate_server_accounts() -> dict[str, Any]: """Check ``serve.server_accounts`` at startup; raise ValueError on a bad shape or unknown profile.""" accounts = config.serve.get("server_accounts") or {} @@ -2275,6 +2281,8 @@ async def dashboard_events_handler(request: web.Request) -> web.StreamResponse: continue item = get_task.result() get_task = None + if item is None: + break await send(item["event"], item["data"], item["seq"]) except (ConnectionResetError, asyncio.CancelledError): log.debug("SSE dashboard client disconnected") diff --git a/unshackle/core/api/routes.py b/unshackle/core/api/routes.py index 76dc1dea..80174fc0 100644 --- a/unshackle/core/api/routes.py +++ b/unshackle/core/api/routes.py @@ -13,7 +13,9 @@ from aiohttp_swagger3 import SwaggerDocs, SwaggerInfo, SwaggerUiSettings from unshackle.core import __code_hash__, __version__ from unshackle.core import services as services_module +from unshackle.core.api.download_manager import shutdown_download_manager from unshackle.core.api.errors import APIError, build_error_response, categorize_exception, handle_api_exception +from unshackle.core.api.events import close_event_streams from unshackle.core.api.handlers import ( CORS_HEADERS, DASHBOARD_EVENTS_ROUTE, @@ -3571,6 +3573,8 @@ def setup_routes( app.on_response_prepare.append(generic_server_header) app.on_shutdown.append(close_tunnels) app.on_shutdown.append(close_channels) + app.on_shutdown.append(shutdown_download_manager) + app.on_shutdown.append(close_event_streams) async def generic_server_header(request: web.Request, response: web.StreamResponse) -> None: diff --git a/unshackle/core/api/session_store.py b/unshackle/core/api/session_store.py index 84f6bc84..0f876a05 100644 --- a/unshackle/core/api/session_store.py +++ b/unshackle/core/api/session_store.py @@ -341,13 +341,18 @@ class SessionStore: self._cleanup_task = None async def cancel_all_bridges(self) -> None: - """Cancel all active input bridges and close every remote session channel (called on server shutdown).""" + """End every remote session and remove its cache directory (called on server shutdown). + + The store forgets the sessions too, so a login task that ends after this removes the directory again. + """ async with self._lock: - for entry in self._sessions.values(): - entry.end() - count = len(self._sessions) - if count: - log.info(f"Cancelled bridges for {count} active session(s)") + entries = list(self._sessions.values()) + self._sessions.clear() + for entry in entries: + entry.end() + if entries: + log.info(f"Cancelled bridges for {len(entries)} active session(s)") + await self.remove_cache_dirs([entry.cache_tag for entry in entries]) @classmethod async def remove_cache_dirs(cls, cache_tags: builtins.list[str | None]) -> None: