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
+32 -32
View File
@@ -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
+21
View File
@@ -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.
+8
View File
@@ -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")
+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 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:
+11 -6
View File
@@ -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: