feat(api)!: add a server drain and never answer with a 5xx

POST/DELETE /api/dashboard/drain refuses new sessions and jobs (SERVER_DRAINING, 409) and warns open sessions. A CDN can replace a 5xx body, so server errors are now 422, retryable ones and the tunnel check 424, and a new middleware turns any 5xx into 422.

BREAKING CHANGE: INTERNAL_ERROR, DOWNLOAD_ERROR, WORKER_ERROR and the fallback return 422 instead of 500; NETWORK_ERROR and SERVICE_UNAVAILABLE return 424 instead of 503; /api/tunnel/check failures return 424 instead of 502.
This commit is contained in:
imSp4rky
2026-10-21 17:15:33 -06:00
parent 23614fd938
commit 5086dafff3
14 changed files with 264 additions and 71 deletions
+11 -2
View File
@@ -16,7 +16,7 @@ from aiohttp import web
import unshackle.core.config as config_module
from unshackle.core import binaries
from unshackle.core.api import cors_middleware, setup_routes, setup_swagger
from unshackle.core.api import cors_middleware, no_5xx_middleware, setup_routes, setup_swagger
from unshackle.core.api.compression import compression_middleware
from unshackle.core.api.events import publish_refresh_events, publish_service_event
from unshackle.core.api.handlers import (
@@ -495,12 +495,19 @@ def serve(
log.info("Starting REST API server (pywidevine/pyplayready CDM disabled)")
if no_key:
app = web.Application(
middlewares=[cors_middleware, stats_middleware, dashboard_authentication, compression_middleware]
middlewares=[
cors_middleware,
no_5xx_middleware,
stats_middleware,
dashboard_authentication,
compression_middleware,
]
)
else:
app = web.Application(
middlewares=[
cors_middleware,
no_5xx_middleware,
stats_middleware,
dashboard_authentication,
api_key_authentication,
@@ -569,6 +576,7 @@ def serve(
app = web.Application(
middlewares=[
cors_middleware,
no_5xx_middleware,
stats_middleware,
cdm_log_middleware,
dashboard_authentication,
@@ -580,6 +588,7 @@ def serve(
app = web.Application(
middlewares=[
cors_middleware,
no_5xx_middleware,
stats_middleware,
cdm_log_middleware,
dashboard_authentication,
+2 -2
View File
@@ -1,3 +1,3 @@
from unshackle.core.api.routes import cors_middleware, setup_routes, setup_swagger
from unshackle.core.api.routes import cors_middleware, no_5xx_middleware, setup_routes, setup_swagger
__all__ = ["setup_routes", "setup_swagger", "cors_middleware"]
__all__ = ["setup_routes", "setup_swagger", "cors_middleware", "no_5xx_middleware"]
+3
View File
@@ -735,6 +735,9 @@ class DownloadQueueManager:
def create_job(self, service: str, title_id: str, owner_key: Optional[str] = None, **parameters) -> DownloadJob:
"""Make a new download job and add it to the queue."""
from unshackle.core.api.session_store import refuse_while_draining
refuse_while_draining()
job_id = str(uuid.uuid4())
job = DownloadJob(
job_id=job_id,
+14 -10
View File
@@ -47,6 +47,7 @@ class APIErrorCode(str, Enum):
DRM_ERROR = "DRM_ERROR"
DOWNLOAD_ERROR = "DOWNLOAD_ERROR"
SERVICE_UNAVAILABLE = "SERVICE_UNAVAILABLE"
SERVER_DRAINING = "SERVER_DRAINING"
WORKER_ERROR = "WORKER_ERROR"
@@ -79,7 +80,11 @@ class APIError(Exception):
@staticmethod
def default_http_status(error_code: APIErrorCode) -> int:
"""Map error codes to default HTTP status codes."""
"""Map error codes to default HTTP status codes.
No code maps to a 5xx: a CDN in front of the server can replace a 5xx body with its own page.
Server-side failures are 422, and the ones worth a retry are 424, which the client retries.
"""
status_map = {
APIErrorCode.INVALID_INPUT: 400,
APIErrorCode.INVALID_SERVICE: 400,
@@ -95,16 +100,17 @@ class APIError(Exception):
APIErrorCode.SESSION_NOT_FOUND: 404,
APIErrorCode.TRACK_NOT_FOUND: 404,
APIErrorCode.CONFLICT: 409,
APIErrorCode.SERVER_DRAINING: 409,
APIErrorCode.SERVICE_ERROR: 422,
APIErrorCode.DRM_ERROR: 422,
APIErrorCode.INTERNAL_ERROR: 422,
APIErrorCode.DOWNLOAD_ERROR: 422,
APIErrorCode.WORKER_ERROR: 422,
APIErrorCode.NETWORK_ERROR: 424,
APIErrorCode.SERVICE_UNAVAILABLE: 424,
APIErrorCode.RATE_LIMITED: 429,
APIErrorCode.INTERNAL_ERROR: 500,
APIErrorCode.NETWORK_ERROR: 503,
APIErrorCode.SERVICE_UNAVAILABLE: 503,
APIErrorCode.DOWNLOAD_ERROR: 500,
APIErrorCode.WORKER_ERROR: 500,
}
return status_map.get(error_code, 500)
return status_map.get(error_code, 422)
def build_error_response(
@@ -136,7 +142,7 @@ def build_error_response(
error_code = APIErrorCode.INTERNAL_ERROR.value
message = str(error) or "An unexpected error occurred"
details = {}
http_status = 500
http_status = APIError.default_http_status(APIErrorCode.INTERNAL_ERROR)
retryable = False
ref = secrets.token_hex(3)
@@ -235,7 +241,6 @@ def categorize_exception(
message=f"Network error occurred: {redact_secrets(str(exc))}",
details={**context, "reason": "network_connectivity"},
retryable=True,
http_status=503,
)
if any(keyword in exc_str for keyword in ["not found", "404", "does not exist", "invalid id"]):
@@ -269,7 +274,6 @@ def categorize_exception(
message=f"Service temporarily unavailable: {redact_secrets(str(exc))}",
details={**context, "reason": "service_unavailable"},
retryable=True,
http_status=503,
)
if any(keyword in exc_str for keyword in ["invalid", "malformed", "validation"]) or exc_type in [
+21 -3
View File
@@ -2716,10 +2716,27 @@ async def dashboard_status_handler(request: web.Request) -> web.Response:
"max_sessions": store.max_sessions,
"session_ttl": store.ttl,
"jobs": dict(jobs),
"draining": store.draining,
}
)
async def dashboard_drain_start_handler(request: web.Request) -> web.Response:
"""Start a drain before a restart; answer with the status body."""
from unshackle.core.api.session_store import get_session_store
get_session_store().start_drain()
return await dashboard_status_handler(request)
async def dashboard_drain_stop_handler(request: web.Request) -> web.Response:
"""Cancel the drain; answer with the status body."""
from unshackle.core.api.session_store import get_session_store
get_session_store().stop_drain()
return await dashboard_status_handler(request)
async def dashboard_sessions_handler(request: web.Request) -> web.Response:
"""Every live remote session, not owner-scoped."""
from unshackle.core.api.session_store import get_session_store
@@ -3857,8 +3874,9 @@ async def session_create_handler(data: Dict[str, Any], request: Optional[web.Req
remote session on the server with the authenticated service instance, fetches all
titles and tracks, and returns everything the client needs for track selection.
"""
from unshackle.core.api.session_store import get_session_store
from unshackle.core.api.session_store import get_session_store, refuse_while_draining
refuse_while_draining()
service_tag = data.get("service")
title_id = data.get("title_id")
profile = client_profile(data)
@@ -5691,12 +5709,12 @@ async def tunnel_check_handler(request: web.Request) -> web.Response:
try:
info = await asyncio.to_thread(verify_proxy_exit, session)
except ConnectionError as e:
raise APIError(APIErrorCode.INVALID_PROXY, str(e), http_status=502)
raise APIError(APIErrorCode.INVALID_PROXY, str(e), http_status=424)
if not info:
raise APIError(
APIErrorCode.INVALID_PROXY,
"The server could not look up an IP address through the tunnel.",
http_status=502,
http_status=424,
)
ms = round((time.perf_counter() - started) * 1000)
return web.json_response({"ip": info.get("ip"), "country": info.get("country"), "ms": ms})
+79 -18
View File
@@ -22,6 +22,8 @@ from unshackle.core.api.handlers import (
clear_finished_download_jobs_handler,
clear_temp_handler,
dashboard_cdm_logs_handler,
dashboard_drain_start_handler,
dashboard_drain_stop_handler,
dashboard_events_handler,
dashboard_health_handler,
dashboard_jobs_handler,
@@ -69,6 +71,7 @@ from unshackle.core.api.handlers import (
tunnel_check_handler,
tunnel_handler,
)
from unshackle.core.api.sanitize import sanitize_log
from unshackle.core.drm import cbcs
from unshackle.core.services import Services
from unshackle.core.tunnel import CHECK_ROUTE as TUNNEL_CHECK_ROUTE
@@ -94,6 +97,24 @@ async def cors_middleware(
return response
@web.middleware
async def no_5xx_middleware(
request: web.Request, handler: Callable[[web.Request], Awaitable[web.StreamResponse]]
) -> web.StreamResponse:
"""Answer an uncaught exception or any unsent 5xx (a CDM subapplication's own) as a 422; see errors.py."""
try:
response = await handler(request)
except Exception as e:
if isinstance(e, web.HTTPException) and e.status < 500:
raise
# the exception text can hold a caller's key, so the answer gets a generic message
log.exception(f"Unhandled error in {sanitize_log(request.path)}")
response = build_error_response(APIError(APIErrorCode.INTERNAL_ERROR, "Internal server error"))
if response.status >= 500 and not response.prepared:
response.set_status(APIError.default_http_status(APIErrorCode.INTERNAL_ERROR))
return response
log = logging.getLogger("api")
# Route handler signature: takes the request, returns a response (streamed or complete).
@@ -291,7 +312,7 @@ async def services(request: web.Request) -> web.Response:
type: string
nullable: true
description: Full service documentation
'500':
'422':
description: Server error
content:
application/json:
@@ -698,7 +719,7 @@ async def list_titles(request: web.Request) -> web.Response:
timestamp:
type: string
format: date-time
'500':
'422':
description: Server error
content:
application/json:
@@ -1229,7 +1250,7 @@ async def download_jobs(request: web.Request) -> web.Response:
type: number
'400':
description: Invalid query parameters
'500':
'422':
description: Server error
"""
# Extract query parameters
@@ -1261,7 +1282,7 @@ async def download_job_detail(request: web.Request) -> web.Response:
description: Download job details
'404':
description: Job not found
'500':
'422':
description: Server error
"""
job_id = request.match_info["job_id"]
@@ -1301,7 +1322,7 @@ async def download_job_events(request: web.Request) -> web.StreamResponse:
type: string
'404':
description: Job not found
'500':
'422':
description: Server error
"""
job_id = request.match_info["job_id"]
@@ -1330,7 +1351,7 @@ async def cancel_download_job(request: web.Request) -> web.Response:
description: The server cannot cancel the job
'404':
description: Job not found
'500':
'422':
description: Server error
"""
job_id = request.match_info["job_id"]
@@ -1355,7 +1376,7 @@ async def clear_finished_download_jobs(request: web.Request) -> web.Response:
removed:
type: integer
description: Number of jobs removed
'500':
'422':
description: Server error
"""
return await clear_finished_download_jobs_handler(request)
@@ -1392,7 +1413,7 @@ async def retry_download_job(request: web.Request) -> web.Response:
description: Job not found
'409':
description: Job is not in a terminal state
'500':
'422':
description: Server error
"""
job_id = request.match_info["job_id"]
@@ -1429,7 +1450,7 @@ async def prioritize_download_job(request: web.Request) -> web.Response:
description: Job not found
'409':
description: Job is not queued
'500':
'422':
description: Server error
"""
job_id = request.match_info["job_id"]
@@ -1517,7 +1538,7 @@ async def profiles(request: web.Request) -> web.Response:
type: array
items:
type: string
'500':
'422':
description: Server error
"""
return await profiles_handler(request)
@@ -1585,7 +1606,7 @@ async def server_config(request: web.Request) -> web.Response:
items:
type: string
description: Available service tags (allowlist-filtered)
'500':
'422':
description: Server error
"""
return await server_config_handler(request)
@@ -1656,7 +1677,7 @@ async def download_history(request: web.Request) -> web.Response:
type: integer
'400':
description: Invalid query parameters
'500':
'422':
description: Server error
"""
query_params = {"limit": request.query.get("limit"), "service": request.query.get("service")}
@@ -1681,7 +1702,7 @@ async def delete_history(request: web.Request) -> web.Response:
description: History entry removed
'404':
description: History entry not found
'500':
'422':
description: Server error
"""
return await delete_history_handler(request.match_info["job_id"], request)
@@ -1706,7 +1727,7 @@ async def maintenance_clear_cache(request: web.Request) -> web.Response:
type: boolean
freed_bytes:
type: integer
'500':
'422':
description: Server error
"""
return await clear_cache_handler(request)
@@ -1731,7 +1752,7 @@ async def maintenance_clear_temp(request: web.Request) -> web.Response:
type: boolean
freed_bytes:
type: integer
'500':
'422':
description: Server error
"""
return await clear_temp_handler(request)
@@ -1783,7 +1804,7 @@ async def maintenance_refresh_services(request: web.Request) -> web.Response:
description: Services whose new code failed to import
items:
type: string
'500':
'422':
description: Server error
"""
return await refresh_services_handler(request)
@@ -1818,7 +1839,7 @@ async def env_check(request: web.Request) -> web.Response:
nullable: true
required:
type: boolean
'500':
'422':
description: Server error
"""
return await env_check_handler(request)
@@ -2048,7 +2069,7 @@ async def tunnel_check(request: web.Request) -> web.Response:
description: The exit IP and country through the tunnel, and the lookup time in ms
'404':
description: No open tunnel with this id for this API key
'502':
'424':
description: No IP lookup got through the tunnel, or the requests left from the server itself
"""
return await tunnel_check_handler(request)
@@ -2653,6 +2674,44 @@ async def dashboard_status(request: web.Request) -> web.Response:
return await dashboard_status_handler(request)
@api_handler
async def dashboard_drain_start(request: web.Request) -> web.Response:
"""
Dashboard: start a drain before a restart.
---
summary: Dashboard drain start
description: >
Refuses every new remote session, download job and job retry with `SERVER_DRAINING` (409)
until the server restarts or the operator cancels the drain. Open remote sessions continue, and
each one gets a warning in its service log. Poll `/api/dashboard/status` until `sessions`
and the active jobs reach 0, then restart. A second call changes nothing.
tags: [Dashboard]
responses:
'200':
description: The status body, with `draining` true
'401':
description: Dashboard key missing or invalid
"""
return await dashboard_drain_start_handler(request)
@api_handler
async def dashboard_drain_stop(request: web.Request) -> web.Response:
"""
Dashboard: cancel a drain.
---
summary: Dashboard drain cancel
description: The server accepts new remote sessions and download jobs again.
tags: [Dashboard]
responses:
'200':
description: The status body, with `draining` false
'401':
description: Dashboard key missing or invalid
"""
return await dashboard_drain_stop_handler(request)
@api_handler
async def dashboard_sessions(request: web.Request) -> web.Response:
"""
@@ -3335,6 +3394,8 @@ ROUTES: list[tuple[str, str, Handler, bool]] = [
DASHBOARD_ROUTES: list[tuple[str, str, Handler, bool]] = [
("GET", DASHBOARD_PREFIX + "status", dashboard_status, True),
("POST", DASHBOARD_PREFIX + "drain", dashboard_drain_start, True),
("DELETE", DASHBOARD_PREFIX + "drain", dashboard_drain_stop, True),
("GET", DASHBOARD_PREFIX + "sessions", dashboard_sessions, True),
("GET", DASHBOARD_PREFIX + "jobs", dashboard_jobs, True),
("GET", DASHBOARD_PREFIX + "logs", dashboard_logs, True),
+34
View File
@@ -24,6 +24,11 @@ from unshackle.core.tracks import Track
log = logging.getLogger("api.session")
DRAIN_WARNING = (
"This server restarts for an update when the open downloads finish. "
"This download continues. Start new downloads after the restart."
)
@dataclass
class SessionEntry:
@@ -129,6 +134,7 @@ class SessionStore:
self._sessions: Dict[str, SessionEntry] = {}
self._lock = asyncio.Lock()
self._cleanup_task: Optional[asyncio.Task] = None
self.draining = False
@property
def ttl(self) -> int:
@@ -322,6 +328,21 @@ class SessionStore:
"""Snapshot of every live session."""
return list(self._sessions.values())
def start_drain(self) -> None:
"""Refuse new sessions and jobs until the restart, and warn each open session through its service log."""
if self.draining:
return
self.draining = True
log.warning(f"Draining: new sessions and jobs are refused, {len(self._sessions)} session(s) open")
for entry in self._sessions.values():
if entry.log_buffer is not None:
entry.log_buffer.append(logging.WARNING, DRAIN_WARNING)
def stop_drain(self) -> None:
if self.draining:
self.draining = False
log.warning("Drain cancelled: new sessions and jobs are accepted again")
@property
def session_count(self) -> int:
"""Number of active sessions."""
@@ -331,6 +352,19 @@ class SessionStore:
session_store: Optional[SessionStore] = None
def refuse_while_draining() -> None:
"""Raise SERVER_DRAINING for a new session or job once the operator has started a drain."""
from unshackle.core.api.errors import APIError, APIErrorCode
if get_session_store().draining:
raise APIError(
APIErrorCode.SERVER_DRAINING,
"This server restarts for an update and does not start new sessions or downloads now. "
"Try again in a few minutes.",
retryable=True,
)
def get_session_store() -> SessionStore:
"""Get or make the global remote session store singleton."""
global session_store