fix(api): stop serve cleanly with jobs, streams and remote sessions open

This commit is contained in:
imSp4rky
2026-11-28 21:11:50 -07:00
parent f5c8858e6e
commit 7713f8df3f
13 changed files with 222 additions and 45 deletions
+2 -2
View File
@@ -72,8 +72,8 @@ characters of the API key.
## Event stream ## Event stream
`/api/dashboard/events` sends a `stats` event (the same body as `/status`) on connect and `/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 then every 5 seconds, so the connection stays alive and the counters stay current. The server
those it sends: closes the connection when it stops. Between those it sends:
| Event | Data | | Event | Data |
|-------|------| |-------|------|
+1 -1
View File
@@ -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. 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" !!! 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` ### `POST /api/download`
+3 -2
View File
@@ -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 `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 a remote session cancels its `InputBridge` and deletes its cache directory (pruning
empty parent dirs up to, but not including, the cache root). empty parent dirs up to, but not including, the cache root).
- The server calls **`cancel_all_bridges()`** on shutdown, to unblock any waiting - The server calls **`cancel_all_bridges()`** on shutdown. It ends each open remote session, which
auth threads. 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: `SessionEntry` fields:
+5 -1
View File
@@ -88,10 +88,14 @@ def wait_for_health(url: str, secret_key: str, timeout: float = 60.0) -> bool:
@pytest.fixture(autouse=True) @pytest.fixture(autouse=True)
def isolated_job_history(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: 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 from unshackle.core.api import download_manager
monkeypatch.setattr(download_manager, "history_path", lambda: tmp_path / "api_history.jsonl") monkeypatch.setattr(download_manager, "history_path", lambda: tmp_path / "api_history.jsonl")
monkeypatch.setattr(download_manager, "download_manager", None)
@pytest.fixture(scope="session") @pytest.fixture(scope="session")
+24
View File
@@ -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"] 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: async def test_session_action_log() -> None:
store = SessionStore() store = SessionStore()
entry = await store.create("EXAMPLE", object(), owner_key="k") entry = await store.create("EXAMPLE", object(), owner_key="k")
@@ -6,6 +6,9 @@ cleanup/serialize); they do not exercise the actual subprocess download path.
from __future__ import annotations from __future__ import annotations
import asyncio
from collections.abc import Callable
from contextlib import suppress
from datetime import datetime, timedelta from datetime import datetime, timedelta
from pathlib import Path from pathlib import Path
from typing import Any 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", {}) download_manager.perform_download("job-1", "EXAMPLE1", "t1", {})
assert exc.value.error_code == (APIErrorCode.WORKER_ERROR if carrier == "none" else APIErrorCode.DRM_ERROR) 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
+13
View File
@@ -134,6 +134,19 @@ async def test_cancel_all_bridges(store: SessionStore) -> None:
entry.input_bridge.ensure_active() 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: async def test_get_session_store_returns_singleton() -> None:
a = get_session_store() a = get_session_store()
b = get_session_store() b = get_session_store()
+7 -1
View File
@@ -58,7 +58,12 @@ class _MaskAccessKey(logging.Filter):
def _install_session_store(app: web.Application) -> None: 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 from unshackle.core.api.session_store import get_session_store
session_store = 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: async def stop(_app: web.Application) -> None:
await session_store.cancel_all_bridges() await session_store.cancel_all_bridges()
await wait_for_logins(5)
await session_store.stop_cleanup_loop() await session_store.stop_cleanup_loop()
app.on_startup.append(start) app.on_startup.append(start)
+32 -32
View File
@@ -17,7 +17,7 @@ from enum import Enum
from pathlib import Path from pathlib import Path
from typing import TYPE_CHECKING, Any 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.api.sanitize import sanitize_log
from unshackle.core.credential import Credential from unshackle.core.credential import Credential
from unshackle.core.utils.redact import REDACTED, URL_USERINFO_RE, redact_all, redact_path, redact_text 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: 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.""" """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.api.session_store import refuse_while_draining
from unshackle.core.remote_protocol import APIErrorCode
refuse_while_draining() 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_id = str(uuid.uuid4())
job = DownloadJob( job = DownloadJob(
job_id=job_id, job_id=job_id,
@@ -585,13 +591,13 @@ class DownloadQueueManager:
return return
payload = {"event": event, "data": data} payload = {"event": event, "data": data}
for queue in queues: for queue in queues:
self.put(queue, payload) put_latest(queue, payload)
def publish_terminal(self, job: DownloadJob) -> None: def publish_terminal(self, job: DownloadJob) -> None:
"""Publish a job's final state, close every listener's event stream, then apply staged service reloads.""" """Publish a job's final state, close every listener's event stream, then apply staged service reloads."""
self.publish(job, job.status.value) self.publish(job, job.status.value)
for queue in self._subscribers.pop(job.job_id, []): for queue in self._subscribers.pop(job.job_id, []):
self.put(queue, None) put_latest(queue, None)
self.schedule_pending_reload() self.schedule_pending_reload()
def busy_services(self) -> set[str]: 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.""" """Swap in staged service updates whose last job has finished, off the event loop."""
schedule_pending_reload() 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: def cancel_job(self, job_id: str) -> bool:
"""Cancel a job that has the queued or the downloading status.""" """Cancel a job that has the queued or the downloading status."""
job = self._jobs.get(job_id) job = self._jobs.get(job_id)
@@ -734,32 +729,20 @@ class DownloadQueueManager:
log.info(f"Started {self.max_concurrent_downloads} download workers") log.info(f"Started {self.max_concurrent_downloads} download workers")
async def shutdown(self) -> None: 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") log.info("Shutting down download queue manager")
self._shutdown_event.set() self._shutdown_event.set()
for queues in list(self._subscribers.values()): for job_id in list(self._jobs):
for queue in queues: self.cancel_job(job_id)
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, process in list(self._download_processes.items()): for job_id, process in list(self._download_processes.items()):
try: try:
await asyncio.wait_for(process.wait(), timeout=5) await asyncio.wait_for(process.wait(), timeout=5)
except TimeoutError: except TimeoutError:
log.warning(f"Worker process for job {job_id} did not exit, killing") log.warning(f"Worker process for job {job_id} did not exit, killing")
process.kill() with suppress(ProcessLookupError):
process.kill()
await process.wait() await process.wait()
finally: finally:
self._download_processes.pop(job_id, None) self._download_processes.pop(job_id, None)
@@ -777,8 +760,16 @@ class DownloadQueueManager:
if self._active_downloads: if self._active_downloads:
await asyncio.gather(*self._active_downloads.values(), return_exceptions=True) 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: 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") log.debug(f"Download worker {worker_name} started")
while not self._shutdown_event.is_set(): while not self._shutdown_event.is_set():
@@ -811,6 +802,8 @@ class DownloadQueueManager:
except asyncio.CancelledError: except asyncio.CancelledError:
job.status = JobStatus.CANCELLED job.status = JobStatus.CANCELLED
log.info(f"Job {job.job_id} was 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: except Exception as e:
job.status = JobStatus.FAILED job.status = JobStatus.FAILED
job.error_message = str(e) job.error_message = str(e)
@@ -828,6 +821,7 @@ class DownloadQueueManager:
continue continue
except Exception as e: except Exception as e:
log.error(f"Worker {worker_name} error: {e}") log.error(f"Worker {worker_name} error: {e}")
await asyncio.sleep(1)
async def execute_download(self, job: DownloadJob) -> None: async def execute_download(self, job: DownloadJob) -> None:
"""Do the actual download for a job.""" """Do the actual download for a job."""
@@ -1087,6 +1081,12 @@ def get_download_manager() -> DownloadQueueManager:
return download_manager 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]: def busy_services() -> set[str]:
"""Tags a hot reload must not swap: those with an unfinished job and those a live remote session uses.""" """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 from unshackle.core.api.session_store import get_session_store
+21
View File
@@ -31,6 +31,11 @@ class EventBus:
with suppress(ValueError): with suppress(ValueError):
self._subs.remove(queue) 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]]: def since(self, seq: int) -> list[dict[str, Any]]:
"""Return the history after ``seq``. """Return the history after ``seq``.
@@ -67,9 +72,25 @@ def _put_drop(queue: asyncio.Queue, item: dict[str, Any]) -> None:
queue.put_nowait(item) 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() 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: 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. """Tell dashboard listeners that services were staged, applied, or failed to reload.
+8
View File
@@ -1032,6 +1032,12 @@ _account_counters: dict[str, int] = {}
_auth_tasks: set["asyncio.Task[None]"] = set() _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]: def validate_server_accounts() -> dict[str, Any]:
"""Check ``serve.server_accounts`` at startup; raise ValueError on a bad shape or unknown profile.""" """Check ``serve.server_accounts`` at startup; raise ValueError on a bad shape or unknown profile."""
accounts = config.serve.get("server_accounts") or {} accounts = config.serve.get("server_accounts") or {}
@@ -2275,6 +2281,8 @@ async def dashboard_events_handler(request: web.Request) -> web.StreamResponse:
continue continue
item = get_task.result() item = get_task.result()
get_task = None get_task = None
if item is None:
break
await send(item["event"], item["data"], item["seq"]) await send(item["event"], item["data"], item["seq"])
except (ConnectionResetError, asyncio.CancelledError): except (ConnectionResetError, asyncio.CancelledError):
log.debug("SSE dashboard client disconnected") log.debug("SSE dashboard client disconnected")
+4
View File
@@ -13,7 +13,9 @@ from aiohttp_swagger3 import SwaggerDocs, SwaggerInfo, SwaggerUiSettings
from unshackle.core import __code_hash__, __version__ from unshackle.core import __code_hash__, __version__
from unshackle.core import services as services_module 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.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 ( from unshackle.core.api.handlers import (
CORS_HEADERS, CORS_HEADERS,
DASHBOARD_EVENTS_ROUTE, DASHBOARD_EVENTS_ROUTE,
@@ -3571,6 +3573,8 @@ def setup_routes(
app.on_response_prepare.append(generic_server_header) app.on_response_prepare.append(generic_server_header)
app.on_shutdown.append(close_tunnels) app.on_shutdown.append(close_tunnels)
app.on_shutdown.append(close_channels) 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: async def generic_server_header(request: web.Request, response: web.StreamResponse) -> None:
+11 -6
View File
@@ -341,13 +341,18 @@ class SessionStore:
self._cleanup_task = None self._cleanup_task = None
async def cancel_all_bridges(self) -> 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: async with self._lock:
for entry in self._sessions.values(): entries = list(self._sessions.values())
entry.end() self._sessions.clear()
count = len(self._sessions) for entry in entries:
if count: entry.end()
log.info(f"Cancelled bridges for {count} active session(s)") 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 @classmethod
async def remove_cache_dirs(cls, cache_tags: builtins.list[str | None]) -> None: async def remove_cache_dirs(cls, cache_tags: builtins.list[str | None]) -> None: