mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-11-26 19:05:13 +00:00
fix(api): stop a service's sys.exit from killing the serve process
Catch SystemExit at service import, in the heartbeat task, the 5xx middleware, search, samples and chapters, and answer it as SERVICE_ERROR.
This commit is contained in:
@@ -179,7 +179,7 @@ def build_error_response(
|
||||
|
||||
|
||||
def categorize_exception(
|
||||
exc: Exception,
|
||||
exc: BaseException,
|
||||
context: dict[str, Any] | None = None,
|
||||
) -> APIError:
|
||||
"""
|
||||
@@ -196,6 +196,14 @@ def categorize_exception(
|
||||
APIError with appropriate error code and details
|
||||
"""
|
||||
context = context or {}
|
||||
if isinstance(exc, SystemExit):
|
||||
exited = f"Service {context['service']} exited" if context.get("service") else "Service exited"
|
||||
return APIError(
|
||||
error_code=APIErrorCode.SERVICE_ERROR,
|
||||
message=redact_secrets(getattr(exc, "message", None)) or exited,
|
||||
details={**context, "reason": "service_exit"},
|
||||
retryable=False,
|
||||
)
|
||||
root = exc.__cause__ or exc
|
||||
exc_str = f"{exc} {root}".lower()
|
||||
exc_type = type(root).__name__
|
||||
@@ -296,7 +304,7 @@ def categorize_exception(
|
||||
|
||||
|
||||
def handle_api_exception(
|
||||
exc: Exception,
|
||||
exc: BaseException,
|
||||
context: dict[str, Any] | None = None,
|
||||
debug_mode: bool = False,
|
||||
extra_debug_info: dict[str, Any] | None = None,
|
||||
|
||||
@@ -15,7 +15,7 @@ from datetime import date as date_
|
||||
from functools import partial
|
||||
from http.cookiejar import CookieJar
|
||||
from pathlib import Path
|
||||
from typing import Any, Callable, Dict, Iterable, List, Optional, cast
|
||||
from typing import Any, Callable, Dict, Iterable, List, Optional, Set, cast
|
||||
|
||||
import click
|
||||
from aiohttp import web
|
||||
@@ -1088,6 +1088,8 @@ def live_licence_refusal(session: Any, track: Any) -> Optional[APIError]:
|
||||
|
||||
|
||||
_account_counters: Dict[str, int] = {}
|
||||
# the event loop holds only weak references to tasks, so a running login task needs a strong one
|
||||
_auth_tasks: Set["asyncio.Task[None]"] = set()
|
||||
|
||||
|
||||
def validate_server_accounts() -> Dict[str, Any]:
|
||||
@@ -1885,6 +1887,14 @@ async def search_handler(data: Dict[str, Any], request: Optional[web.Request] =
|
||||
try:
|
||||
results = await asyncio.to_thread(run_service_search, data, normalized_service, query, request, request_cache)
|
||||
return request_cache.json_response({"results": results, "count": len(results)})
|
||||
except APIError:
|
||||
raise
|
||||
except (Exception, SystemExit) as e:
|
||||
log.exception("Error searching")
|
||||
debug_mode = request.app.get("debug_api", False) if request else False
|
||||
return handle_api_exception(
|
||||
e, context={"operation": "search", "service": normalized_service}, debug_mode=debug_mode
|
||||
)
|
||||
finally:
|
||||
request_cache.cleanup()
|
||||
|
||||
@@ -3987,7 +3997,9 @@ async def session_create_handler(data: Dict[str, Any], request: Optional[web.Req
|
||||
if store.peek(session_id) is not session:
|
||||
SessionStore.cleanup_cache_dir(session_cache_tag)
|
||||
|
||||
asyncio.create_task(run_auth())
|
||||
auth_task = asyncio.create_task(run_auth())
|
||||
_auth_tasks.add(auth_task)
|
||||
auth_task.add_done_callback(_auth_tasks.discard)
|
||||
|
||||
return web.json_response(
|
||||
{
|
||||
@@ -4173,7 +4185,7 @@ async def session_tracks_handler(
|
||||
try:
|
||||
chapters = await asyncio.to_thread(service_instance.get_chapters, title)
|
||||
session.chapters_by_title[str(title_id)] = chapters if chapters else []
|
||||
except (NotImplementedError, Exception):
|
||||
except (Exception, SystemExit):
|
||||
session.chapters_by_title[str(title_id)] = []
|
||||
|
||||
video_tracks = sorted(tracks.videos, key=lambda t: t.bitrate or 0, reverse=True)
|
||||
@@ -5271,14 +5283,14 @@ async def session_samples_handler(
|
||||
details={"track_id": track_id, "session_id": session_id},
|
||||
)
|
||||
service = session.service_instance
|
||||
if not service.decrypts_samples(track):
|
||||
raise APIError(APIErrorCode.INVALID_INPUT, f"The service does not decrypt the samples of track {track_id}")
|
||||
if not server_cdm_allowed(request, session.service_tag):
|
||||
raise APIError(
|
||||
APIErrorCode.FORBIDDEN, f"This API key may not decrypt {session.service_tag} samples on the server"
|
||||
)
|
||||
|
||||
def run() -> web.Response:
|
||||
if not service.decrypts_samples(track):
|
||||
raise APIError(APIErrorCode.INVALID_INPUT, f"The service does not decrypt the samples of track {track_id}")
|
||||
decrypter = service.get_sample_decrypter(track, index)
|
||||
if isinstance(decrypter, (bytes, bytearray)):
|
||||
return web.json_response({"key": bytes(decrypter).hex()})
|
||||
|
||||
@@ -11,7 +11,13 @@ 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.errors import APIError, APIErrorCode, build_error_response, handle_api_exception
|
||||
from unshackle.core.api.errors import (
|
||||
APIError,
|
||||
APIErrorCode,
|
||||
build_error_response,
|
||||
categorize_exception,
|
||||
handle_api_exception,
|
||||
)
|
||||
from unshackle.core.api.handlers import (
|
||||
CORS_HEADERS,
|
||||
DASHBOARD_EVENTS_ROUTE,
|
||||
@@ -104,12 +110,13 @@ async def no_5xx_middleware(
|
||||
"""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:
|
||||
except (Exception, SystemExit) 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"))
|
||||
error = categorize_exception(e) if isinstance(e, SystemExit) else None
|
||||
response = build_error_response(error or 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
|
||||
@@ -147,9 +154,17 @@ def heartbeat(handler: Handler) -> Handler:
|
||||
work continues if the client disconnects, so the remote session state stays complete.
|
||||
"""
|
||||
|
||||
async def guarded(request: web.Request) -> web.StreamResponse:
|
||||
# a SystemExit leaving any task is re-raised into the event loop, so it must stop inside the task
|
||||
try:
|
||||
return await handler(request)
|
||||
except SystemExit as e:
|
||||
log.exception(f"Service exited in {sanitize_log(request.path)}")
|
||||
raise categorize_exception(e) from e
|
||||
|
||||
@functools.wraps(handler)
|
||||
async def wrapper(request: web.Request) -> web.StreamResponse:
|
||||
task = asyncio.ensure_future(handler(request))
|
||||
task = asyncio.ensure_future(guarded(request))
|
||||
done, _ = await asyncio.wait({task}, timeout=HEARTBEAT_INTERVAL)
|
||||
if done:
|
||||
return task.result()
|
||||
|
||||
@@ -97,7 +97,7 @@ def load_service(path: Path) -> object:
|
||||
tag = path.parent.stem
|
||||
try:
|
||||
module = import_module_by_path(path)
|
||||
except Exception as e:
|
||||
except (Exception, SystemExit) as e:
|
||||
hint = compiled_import_hint(e.name, path) if isinstance(e, ModuleNotFoundError) and e.name else ""
|
||||
raise RuntimeError(f"{tag}: failed to import - {type(e).__name__}: {e}{hint} ({path.name})") from e
|
||||
try:
|
||||
|
||||
Reference in New Issue
Block a user