mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-11-26 10:55:08 +00:00
feat(api): stream download job progress over server-sent events
Adds GET /api/download/jobs/{job_id}/events with snapshot, status, progress and terminal events, query-param auth for EventSource in both serve modes, atomic progress-file writes, and stream-safe CORS and compression middleware.
This commit is contained in:
@@ -25,10 +25,13 @@ def safe_inflate(data: bytes, max_size: int = MAX_INFLATE_BYTES) -> bytes:
|
||||
|
||||
|
||||
@web.middleware
|
||||
async def compression_middleware(request: web.Request, handler) -> web.Response:
|
||||
async def compression_middleware(request: web.Request, handler) -> web.StreamResponse:
|
||||
"""Compress JSON responses with gzip when the client supports it."""
|
||||
response = await handler(request)
|
||||
|
||||
if not isinstance(response, web.Response):
|
||||
return response
|
||||
|
||||
accept_encoding = request.headers.get("Accept-Encoding", "")
|
||||
if "gzip" not in accept_encoding:
|
||||
return response
|
||||
@@ -37,7 +40,7 @@ async def compression_middleware(request: web.Request, handler) -> web.Response:
|
||||
return response
|
||||
|
||||
body = response.body
|
||||
if body is None or len(body) < 256:
|
||||
if not isinstance(body, (bytes, bytearray)) or len(body) < 256:
|
||||
return response
|
||||
|
||||
from unshackle.core.config import config
|
||||
|
||||
@@ -623,6 +623,7 @@ class DownloadQueueManager:
|
||||
self._job_temp_files: Dict[str, Dict[str, str]] = {}
|
||||
self._workers_started = False
|
||||
self._shutdown_event = asyncio.Event()
|
||||
self._subscribers: Dict[str, List[asyncio.Queue]] = {}
|
||||
|
||||
log.info(
|
||||
f"Initialized download queue manager: max_concurrent={max_concurrent_downloads}, retention_hours={job_retention_hours}"
|
||||
@@ -655,6 +656,48 @@ class DownloadQueueManager:
|
||||
"""List all jobs."""
|
||||
return list(self._jobs.values())
|
||||
|
||||
def subscribe(self, job_id: str) -> asyncio.Queue:
|
||||
"""Register a listener for a job's events, returning the queue it receives them on."""
|
||||
queue: asyncio.Queue = asyncio.Queue(maxsize=100)
|
||||
self._subscribers.setdefault(job_id, []).append(queue)
|
||||
return queue
|
||||
|
||||
def unsubscribe(self, job_id: str, queue: asyncio.Queue) -> None:
|
||||
"""Drop a listener registered by subscribe()."""
|
||||
queues = self._subscribers.get(job_id)
|
||||
if not queues:
|
||||
return
|
||||
with suppress(ValueError):
|
||||
queues.remove(queue)
|
||||
if not queues:
|
||||
del self._subscribers[job_id]
|
||||
|
||||
def _publish(self, job: DownloadJob, event: str) -> None:
|
||||
"""Fan an event carrying the job's full detail dict out to every listener."""
|
||||
queues = self._subscribers.get(job.job_id)
|
||||
if not queues:
|
||||
return
|
||||
payload = {"event": event, "data": job.to_dict(include_full_details=True)}
|
||||
for queue in queues:
|
||||
self._put(queue, payload)
|
||||
|
||||
def _publish_terminal(self, job: DownloadJob) -> None:
|
||||
"""Publish a job's final state, then close every listener's stream."""
|
||||
self._publish(job, job.status.value)
|
||||
for queue in self._subscribers.pop(job.job_id, []):
|
||||
self._put(queue, None)
|
||||
|
||||
@staticmethod
|
||||
def _put(queue: asyncio.Queue, item: Optional[Dict[str, Any]]) -> 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 if it's queued or downloading."""
|
||||
job = self._jobs.get(job_id)
|
||||
@@ -666,6 +709,7 @@ class DownloadQueueManager:
|
||||
job.cancel_event.set() # Signal cancellation
|
||||
job.completed_time = datetime.now()
|
||||
record_job_history(job) # queued jobs never reach a worker, so persist here
|
||||
self._publish_terminal(job)
|
||||
log.info(f"Cancelled queued job {sanitize_log(job_id)}")
|
||||
return True
|
||||
elif job.status == JobStatus.DOWNLOADING:
|
||||
@@ -763,6 +807,11 @@ class DownloadQueueManager:
|
||||
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()
|
||||
@@ -819,6 +868,7 @@ class DownloadQueueManager:
|
||||
# Start processing the job
|
||||
job.status = JobStatus.DOWNLOADING
|
||||
job.started_time = datetime.now()
|
||||
self._publish(job, "status")
|
||||
|
||||
log.info(f"Worker {worker_name} starting job {job.job_id}")
|
||||
|
||||
@@ -838,6 +888,7 @@ class DownloadQueueManager:
|
||||
finally:
|
||||
job.completed_time = datetime.now()
|
||||
record_job_history(job)
|
||||
self._publish_terminal(job)
|
||||
if job.job_id in self._active_downloads:
|
||||
del self._active_downloads[job.job_id]
|
||||
|
||||
@@ -913,6 +964,7 @@ class DownloadQueueManager:
|
||||
|
||||
stdout_bytes = b""
|
||||
stderr_bytes = b""
|
||||
last_published: Optional[Dict[str, Any]] = None
|
||||
|
||||
try:
|
||||
while True:
|
||||
@@ -957,6 +1009,9 @@ class DownloadQueueManager:
|
||||
if new_progress != job.progress:
|
||||
job.progress = new_progress
|
||||
log.info(f"Job {job.job_id} progress updated: {job.progress}%")
|
||||
if progress_data != last_published:
|
||||
last_published = progress_data
|
||||
self._publish(job, "progress")
|
||||
except (FileNotFoundError, json.JSONDecodeError, ValueError) as e:
|
||||
log.debug(f"Could not read progress for job {job.job_id}: {e}")
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
import traceback
|
||||
from pathlib import Path
|
||||
@@ -20,9 +21,11 @@ def _read_payload(path: Path) -> Dict[str, Any]:
|
||||
|
||||
|
||||
def _write_result(path: Path, payload: Dict[str, Any]) -> None:
|
||||
# Atomic replace: the parent polls this file while it is being rewritten.
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
with path.open("w", encoding="utf-8") as handle:
|
||||
json.dump(payload, handle)
|
||||
tmp = path.with_name(path.name + ".tmp")
|
||||
tmp.write_text(json.dumps(payload), encoding="utf-8")
|
||||
os.replace(tmp, path)
|
||||
|
||||
|
||||
def main(argv: list[str]) -> int:
|
||||
|
||||
@@ -263,7 +263,7 @@ def get_allowed_services(request: Optional[web.Request] = None) -> Optional[List
|
||||
|
||||
key_set: Optional[set[str]] = None
|
||||
if request:
|
||||
secret_key = request.headers.get("X-Secret-Key")
|
||||
secret_key = request_secret_key(request)
|
||||
if secret_key:
|
||||
users = config.serve.get("users", {})
|
||||
user_config = users.get(secret_key, {})
|
||||
@@ -283,9 +283,32 @@ def get_allowed_services(request: Optional[web.Request] = None) -> Optional[List
|
||||
return list(result)
|
||||
|
||||
|
||||
JOB_EVENTS_ROUTE = "/api/download/jobs/{job_id}/events"
|
||||
|
||||
CORS_HEADERS = {
|
||||
"Access-Control-Allow-Origin": "*",
|
||||
"Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS",
|
||||
"Access-Control-Allow-Headers": "Content-Type, X-Secret-Key, Authorization",
|
||||
"Access-Control-Max-Age": "3600",
|
||||
}
|
||||
|
||||
|
||||
def request_secret_key(request: web.Request) -> Optional[str]:
|
||||
"""The caller's key: the X-Secret-Key header, or on the events route the secret_key
|
||||
query param (EventSource cannot send headers)."""
|
||||
key = request.headers.get("X-Secret-Key")
|
||||
if not key:
|
||||
resource = request.match_info.route.resource
|
||||
if resource is not None and resource.canonical == JOB_EVENTS_ROUTE:
|
||||
key = request.query.get("secret_key")
|
||||
return key
|
||||
|
||||
|
||||
def caller_key(request: Optional[web.Request] = None) -> str:
|
||||
"""The authenticating X-Secret-Key for a request, or 'anonymous' when unauthenticated."""
|
||||
return request.headers.get("X-Secret-Key", "anonymous") if request else "anonymous"
|
||||
"""The authenticating key for a request, or 'anonymous' when unauthenticated."""
|
||||
if not request:
|
||||
return "anonymous"
|
||||
return request_secret_key(request) or "anonymous"
|
||||
|
||||
|
||||
def owns_job(job: Any, request: Optional[web.Request] = None) -> bool:
|
||||
@@ -1214,6 +1237,71 @@ async def get_download_job_handler(job_id: str, request: Optional[web.Request] =
|
||||
)
|
||||
|
||||
|
||||
async def download_job_events_handler(job_id: str, request: web.Request) -> web.StreamResponse:
|
||||
"""Stream a download job's progress to the caller as Server-Sent Events."""
|
||||
import json
|
||||
|
||||
from unshackle.core.api.download_manager import TERMINAL_STATUSES, get_download_manager
|
||||
|
||||
manager = get_download_manager()
|
||||
job = manager.get_job(job_id)
|
||||
|
||||
if not job or not owns_job(job, request):
|
||||
raise APIError(
|
||||
APIErrorCode.JOB_NOT_FOUND,
|
||||
"Job not found",
|
||||
details={"job_id": job_id},
|
||||
)
|
||||
|
||||
response = web.StreamResponse(
|
||||
headers={
|
||||
"Content-Type": "text/event-stream",
|
||||
"Cache-Control": "no-cache",
|
||||
# Stops nginx from buffering the stream.
|
||||
"X-Accel-Buffering": "no",
|
||||
**CORS_HEADERS,
|
||||
}
|
||||
)
|
||||
await response.prepare(request)
|
||||
|
||||
async def send(event: str, data: Dict[str, Any]) -> None:
|
||||
payload = json.dumps(data, separators=(",", ":"), default=str)
|
||||
await response.write(f"event: {event}\ndata: {payload}\n\n".encode())
|
||||
|
||||
queue: Optional[asyncio.Queue] = None
|
||||
get_task: Optional[asyncio.Task] = None
|
||||
try:
|
||||
await send("snapshot", job.to_dict(include_full_details=True))
|
||||
|
||||
if job.status not in TERMINAL_STATUSES:
|
||||
queue = manager.subscribe(job_id)
|
||||
if queue is None or job.status in TERMINAL_STATUSES:
|
||||
await send(job.status.value, job.to_dict(include_full_details=True))
|
||||
return response
|
||||
|
||||
while True:
|
||||
if get_task is None:
|
||||
get_task = asyncio.create_task(queue.get())
|
||||
done, _ = await asyncio.wait({get_task}, timeout=15)
|
||||
if not done:
|
||||
await response.write(b": keep-alive\n\n")
|
||||
continue
|
||||
item = get_task.result()
|
||||
get_task = None
|
||||
if item is None:
|
||||
break
|
||||
await send(item["event"], item["data"])
|
||||
except (ConnectionResetError, asyncio.CancelledError):
|
||||
log.debug(f"SSE client disconnected from job {sanitize_log(job_id)}")
|
||||
finally:
|
||||
if get_task is not None:
|
||||
get_task.cancel()
|
||||
if queue is not None:
|
||||
manager.unsubscribe(job_id, queue)
|
||||
|
||||
return response
|
||||
|
||||
|
||||
async def cancel_download_job_handler(job_id: str, request: Optional[web.Request] = None) -> web.Response:
|
||||
"""Handle cancel/remove download job request."""
|
||||
from unshackle.core.api.download_manager import TERMINAL_STATUSES, get_download_manager
|
||||
|
||||
@@ -11,6 +11,8 @@ from aiohttp_swagger3 import SwaggerDocs, SwaggerInfo, SwaggerUiSettings
|
||||
from unshackle.core import __code_hash__, __version__
|
||||
from unshackle.core.api.errors import APIError, APIErrorCode, build_error_response, handle_api_exception
|
||||
from unshackle.core.api.handlers import (
|
||||
CORS_HEADERS,
|
||||
JOB_EVENTS_ROUTE,
|
||||
cancel_download_job_handler,
|
||||
clear_cache_handler,
|
||||
clear_finished_download_jobs_handler,
|
||||
@@ -18,6 +20,7 @@ from unshackle.core.api.handlers import (
|
||||
delete_history_handler,
|
||||
download_handler,
|
||||
download_history_handler,
|
||||
download_job_events_handler,
|
||||
env_check_handler,
|
||||
get_allowed_services,
|
||||
get_download_job_handler,
|
||||
@@ -56,26 +59,22 @@ async def cors_middleware(
|
||||
else:
|
||||
response = await handler(request)
|
||||
|
||||
# Add CORS headers
|
||||
response.headers["Access-Control-Allow-Origin"] = "*"
|
||||
response.headers["Access-Control-Allow-Methods"] = "GET, POST, PUT, DELETE, OPTIONS"
|
||||
response.headers["Access-Control-Allow-Headers"] = "Content-Type, X-Secret-Key, Authorization"
|
||||
response.headers["Access-Control-Max-Age"] = "3600"
|
||||
response.headers.update(CORS_HEADERS)
|
||||
|
||||
return response
|
||||
|
||||
|
||||
log = logging.getLogger("api")
|
||||
|
||||
# Route handler signature: takes the request, returns a response.
|
||||
Handler = Callable[[web.Request], Awaitable[web.Response]]
|
||||
# Route handler signature: takes the request, returns a response (streamed or complete).
|
||||
Handler = Callable[[web.Request], Awaitable[web.StreamResponse]]
|
||||
|
||||
|
||||
def api_handler(handler: Handler) -> Handler:
|
||||
"""Wrap a route handler so any raised APIError becomes a structured error response."""
|
||||
|
||||
@functools.wraps(handler)
|
||||
async def wrapper(request: web.Request) -> web.Response:
|
||||
async def wrapper(request: web.Request) -> web.StreamResponse:
|
||||
try:
|
||||
return await handler(request)
|
||||
except APIError as e:
|
||||
@@ -956,6 +955,46 @@ async def download_job_detail(request: web.Request) -> web.Response:
|
||||
return await get_download_job_handler(job_id, request)
|
||||
|
||||
|
||||
@api_handler
|
||||
async def download_job_events(request: web.Request) -> web.StreamResponse:
|
||||
"""
|
||||
Stream download job events.
|
||||
---
|
||||
summary: Stream download job events
|
||||
description: >
|
||||
Server-Sent Events stream of a job's progress. Emits a `snapshot` event, then
|
||||
`progress` and `status` events, and closes after the terminal `completed`, `failed`
|
||||
or `cancelled` event. Every event carries the same full job object that
|
||||
GET /api/download/jobs/{job_id} returns. A browser EventSource can authenticate with
|
||||
the `secret_key` query parameter instead of the X-Secret-Key header; when both are
|
||||
sent the header is used.
|
||||
parameters:
|
||||
- name: job_id
|
||||
in: path
|
||||
required: true
|
||||
schema:
|
||||
type: string
|
||||
- name: secret_key
|
||||
in: query
|
||||
required: false
|
||||
schema:
|
||||
type: string
|
||||
responses:
|
||||
'200':
|
||||
description: Event stream
|
||||
content:
|
||||
text/event-stream:
|
||||
schema:
|
||||
type: string
|
||||
'404':
|
||||
description: Job not found
|
||||
'500':
|
||||
description: Server error
|
||||
"""
|
||||
job_id = request.match_info["job_id"]
|
||||
return await download_job_events_handler(job_id, request)
|
||||
|
||||
|
||||
@api_handler
|
||||
async def cancel_download_job(request: web.Request) -> web.Response:
|
||||
"""
|
||||
@@ -1801,6 +1840,7 @@ ROUTES: list[tuple[str, str, Handler, bool]] = [
|
||||
("GET", "/api/download/jobs", download_jobs, False),
|
||||
("POST", "/api/download/jobs/clear-finished", clear_finished_download_jobs, False),
|
||||
("GET", "/api/download/jobs/{job_id}", download_job_detail, False),
|
||||
("GET", JOB_EVENTS_ROUTE, download_job_events, False),
|
||||
("DELETE", "/api/download/jobs/{job_id}", cancel_download_job, False),
|
||||
("POST", "/api/download/jobs/{job_id}/retry", retry_download_job, False),
|
||||
("POST", "/api/download/jobs/{job_id}/priority", prioritize_download_job, False),
|
||||
|
||||
Reference in New Issue
Block a user