refactor(remote): keep the session protocol in core/remote_protocol.py

This commit is contained in:
imSp4rky
2026-11-24 16:20:33 -07:00
parent 6c334d31a7
commit 8d5234130a
31 changed files with 797 additions and 305 deletions
+2 -1
View File
@@ -6,8 +6,9 @@ import zlib
import pytest
from unshackle.core.api import handlers
from unshackle.core.api.errors import APIError, APIErrorCode
from unshackle.core.api.errors import APIError
from unshackle.core.api.handlers import load_client_cookies
from unshackle.core.remote_protocol import APIErrorCode
COOKIE_FILE = "\n".join(
[
+2 -1
View File
@@ -57,7 +57,8 @@ def test_a_request_with_no_user_fails_at_once():
def test_no_user_message_is_an_authentication_error():
from unshackle.core.api.errors import APIErrorCode, categorize_exception
from unshackle.core.api.errors import categorize_exception
from unshackle.core.remote_protocol import APIErrorCode
assert categorize_exception(RuntimeError(NO_USER_MESSAGE)).error_code == APIErrorCode.AUTH_FAILED
+2 -1
View File
@@ -209,7 +209,8 @@ def test_the_worker_keeps_the_code_of_an_api_error(tmp_path, monkeypatch):
import json
from unshackle.core.api import download_worker
from unshackle.core.api.errors import APIError, APIErrorCode
from unshackle.core.api.errors import APIError
from unshackle.core.remote_protocol import APIErrorCode
def refuse(*args, **kwargs):
raise APIError(APIErrorCode.INVALID_PARAMETERS, "Invalid workers: expected a number, not a boolean")
@@ -9,8 +9,9 @@ import pytest
from unshackle.core.api import download_manager as dm
from unshackle.core.api import handlers
from unshackle.core.api.errors import APIError, APIErrorCode
from unshackle.core.api.errors import APIError
from unshackle.core.dl_options import DEFAULT_DOWNLOAD_PARAMS
from unshackle.core.remote_protocol import APIErrorCode
pytestmark = pytest.mark.unit
+2 -1
View File
@@ -16,8 +16,9 @@ from pywidevine.pssh import PSSH
from unshackle.core.api import handlers
from unshackle.core.api.errors import APIError
from unshackle.core.api.input_bridge import AuthStatus, InputBridge
from unshackle.core.api.input_bridge import InputBridge
from unshackle.core.cdm.client_relay import ClientDeviceCdm, answer_cdm_call
from unshackle.core.remote_protocol import AuthStatus
pytestmark = pytest.mark.unit
@@ -16,7 +16,8 @@ from unshackle.core.api.download_manager import (
redact_parameters,
secret_values,
)
from unshackle.core.api.errors import APIError, APIErrorCode
from unshackle.core.api.errors import APIError
from unshackle.core.remote_protocol import APIErrorCode
pytestmark = pytest.mark.unit
+4 -2
View File
@@ -386,8 +386,9 @@ def test_a_prompt_discards_an_answer_sent_before_it(tmp_path: Path, monkeypatch:
import threading
from unshackle.core.api import download_worker
from unshackle.core.api.errors import APIErrorCode, categorize_exception
from unshackle.core.api.errors import categorize_exception
from unshackle.core.console import prompt_user, set_prompt_handler
from unshackle.core.remote_protocol import APIErrorCode
answers = tmp_path / "stdin"
answers.write_text('"stale"\n', encoding="utf-8")
@@ -558,8 +559,9 @@ async def test_input_handler_rejects_bad_requests(
monkeypatch: pytest.MonkeyPatch, manager: DownloadQueueManager
) -> None:
from unshackle.core.api import download_manager
from unshackle.core.api.errors import APIError, APIErrorCode
from unshackle.core.api.errors import APIError
from unshackle.core.api.handlers import download_job_input_handler
from unshackle.core.remote_protocol import APIErrorCode
monkeypatch.setattr(download_manager, "get_download_manager", lambda: manager)
job = manager.create_job("EXAMPLE", "t")
+2 -7
View File
@@ -6,13 +6,8 @@ import json
import pytest
from unshackle.core.api.errors import (
APIError,
APIErrorCode,
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.remote_protocol import APIErrorCode
pytestmark = pytest.mark.unit
@@ -5,7 +5,8 @@ from types import SimpleNamespace
import pytest
from unshackle.core.api import handlers
from unshackle.core.api.errors import APIError, APIErrorCode
from unshackle.core.api.errors import APIError
from unshackle.core.remote_protocol import APIErrorCode
from unshackle.core.utils import ip_info
pytestmark = pytest.mark.unit
+3 -2
View File
@@ -8,7 +8,7 @@ import pytest
import requests
from langcodes import Language
from unshackle.core.api.errors import APIError, APIErrorCode
from unshackle.core.api.errors import APIError
from unshackle.core.api.handlers import (
drm_preference_name,
listed_titles,
@@ -18,6 +18,7 @@ from unshackle.core.api.handlers import (
validate_service,
)
from unshackle.core.config import config
from unshackle.core.remote_protocol import APIErrorCode
from unshackle.core.titles.episode import Episode
from unshackle.core.titles.movie import Movie
from unshackle.core.tracks import Audio, Subtitle, Video
@@ -367,8 +368,8 @@ async def test_search_unknown_service_raises_invalid_service() -> None:
def test_resolve_vcodec_rejects_junk_as_invalid_input() -> None:
"""Session routes skip validate_download_parameters, so a bad codec must be a 400, not a 500."""
from unshackle.core.api.errors import APIErrorCode
from unshackle.core.api.handlers import resolve_vcodec
from unshackle.core.remote_protocol import APIErrorCode
from unshackle.core.tracks import Video
assert resolve_vcodec(["H265"]) == [Video.Codec.HEVC]
+2 -1
View File
@@ -7,7 +7,8 @@ import time
import pytest
from unshackle.core.api.input_bridge import AuthStatus, InputBridge
from unshackle.core.api.input_bridge import InputBridge
from unshackle.core.remote_protocol import AuthStatus
pytestmark = pytest.mark.unit
+1 -1
View File
@@ -10,9 +10,9 @@ import pytest
from unshackle.core.api import handlers
from unshackle.core.api.errors import APIError
from unshackle.core.api.input_bridge import AuthStatus
from unshackle.core.api.session_store import get_session_store
from unshackle.core.config import config
from unshackle.core.remote_protocol import AuthStatus
@pytest.fixture
+191
View File
@@ -0,0 +1,191 @@
"""The remote session protocol: what a remote client sends must be what the server serves."""
from __future__ import annotations
import ast
import functools
from pathlib import Path
from typing import Any, Optional
import pytest
import yaml
from unshackle.core import remote_protocol as protocol
from unshackle.core import remote_service
from unshackle.core.api import routes
from unshackle.core.api.handlers import SESSION_TRANSPORT_KEYS
ROUTE_NAMES = {name for name in vars(protocol) if name.endswith("_ROUTE")}
CLIENT_METHODS = {"get": "GET", "get_optional": "GET", "post": "POST", "post_optional": "POST", "delete": "DELETE"}
SERVED = {(method, path): handler for method, path, handler, _ in routes.ROUTES}
@functools.cache
def client_tree() -> ast.Module:
return ast.parse(Path(remote_service.__file__).read_text(encoding="utf-8"))
def client_calls() -> tuple[set[tuple[str, str]], set[str]]:
"""The (method, route) pairs the client sends, and every route name the client module reads.
A URL a function keeps in a local variable counts at the call that sends it.
"""
tree = client_tree()
referenced = {n.id for n in ast.walk(tree) if isinstance(n, ast.Name) and n.id in ROUTE_NAMES}
calls: set[tuple[str, str]] = set()
for function in ast.walk(tree):
if not isinstance(function, ast.FunctionDef):
continue
local = {
target.id: node.value
for node in ast.walk(function)
if isinstance(node, ast.Assign)
for target in node.targets
if isinstance(target, ast.Name)
}
for call in ast.walk(function):
if not (isinstance(call, ast.Call) and isinstance(call.func, ast.Attribute) and call.args):
continue
if call.func.attr == "request" and isinstance(call.args[0], ast.Constant) and len(call.args) > 1:
method, target = str(call.args[0].value).upper(), call.args[1]
elif call.func.attr in CLIENT_METHODS:
method, target = CLIENT_METHODS[call.func.attr], call.args[0]
else:
continue
if isinstance(target, ast.Name):
target = local.get(target.id, target)
calls |= {
(method, getattr(protocol, n.id))
for n in ast.walk(target)
if isinstance(n, ast.Name) and n.id in ROUTE_NAMES
}
return calls, referenced
def test_the_client_writes_no_api_path_of_its_own():
"""A path the client writes out by hand escapes the route check below."""
tree = client_tree()
docstrings = {id(node.value) for node in ast.walk(tree) if isinstance(node, ast.Expr)}
assert not [
node.lineno
for node in ast.walk(tree)
if isinstance(node, ast.Constant)
and isinstance(node.value, str)
and "/api/" in node.value
and id(node) not in docstrings
]
def test_every_route_the_client_calls_is_served_with_that_method():
calls, referenced = client_calls()
assert calls, "the scan found no client calls"
assert {path for _, path in calls} >= {getattr(protocol, name) for name in referenced}
assert calls <= SERVED.keys()
def test_the_server_takes_its_remote_session_routes_from_the_protocol():
protocol_paths = {getattr(protocol, name) for name in ROUTE_NAMES}
served_paths = {path for _, path in SERVED}
assert protocol_paths <= served_paths
assert {path for path in served_paths if path.startswith("/api/session")} <= protocol_paths
def test_the_wire_values_stay_what_older_peers_send():
"""Both halves read one record, so only this list catches a renamed value that an older peer still sends."""
assert {name: getattr(protocol, name) for name in ROUTE_NAMES} == {
"HEALTH_ROUTE": "/api/health",
"SERVICES_ROUTE": "/api/services",
"SEARCH_ROUTE": "/api/search",
"SESSION_CREATE_ROUTE": "/api/session/create",
"SESSION_ROUTE": "/api/session/{session_id}",
"TITLES_ROUTE": "/api/session/{session_id}/titles",
"TRACKS_ROUTE": "/api/session/{session_id}/tracks",
"SEGMENTS_ROUTE": "/api/session/{session_id}/segments",
"SEGMENT_FILTER_ROUTE": "/api/session/{session_id}/segment_filter",
"SAMPLES_ROUTE": "/api/session/{session_id}/samples",
"LICENSE_ROUTE": "/api/session/{session_id}/license",
"BAD_KEY_ROUTE": "/api/session/{session_id}/keys/bad",
"LOGS_ROUTE": "/api/session/{session_id}/logs",
"PROMPT_ROUTE": "/api/session/{session_id}/prompt",
}
assert [s.value for s in protocol.AuthStatus] == ["authenticating", "pending_input", "authenticated", "failed"]
assert {c.name for c in protocol.APIErrorCode} >= {"SESSION_NOT_FOUND", "SERVER_CDM_CAPPED", "SERVER_DRAINING"}
assert [k.value for k in protocol.ClientErrorKind] == [
"CONNECT",
"TIMEOUT",
"AUTH",
"TUNNEL_CLOSED",
"GRANTS_CHANGED",
"UNKNOWN",
]
def test_session_transport_keys_are_the_create_body():
"""The server keeps these out of the flat service options; it reads them from the session create body."""
assert SESSION_TRANSPORT_KEYS == {
"service",
"title_id",
"profile",
"service_params",
"season",
"episode",
"part",
"wanted",
"proxy",
"no_proxy",
"credentials",
"cookies",
"cache",
"client_region",
"proxy_region",
"server_cdm",
"cdm_type",
"cdm_security_level",
"cdm_relay",
"cdm_system_id",
"cdm_device_type",
"service_config",
"range_",
"vcodec",
"quality",
"best_available",
"generate_dv",
"dl_params",
}
def test_a_client_error_kind_is_never_a_server_error_code():
assert not {k.value for k in protocol.ClientErrorKind} & {c.value for c in protocol.APIErrorCode}
def keys(shape: Any) -> set[str]:
return set(shape.__required_keys__ | shape.__optional_keys__)
def properties(schema: Optional[dict]) -> set[str]:
return set(
((schema or {}).get("content", {}).get("application/json", {}).get("schema", {}) or {}).get("properties", {})
)
@pytest.mark.parametrize(
"method,route,request_shape,reply_shape",
[
("POST", protocol.SESSION_CREATE_ROUTE, protocol.SessionCreate, protocol.SessionCreated),
("POST", protocol.TRACKS_ROUTE, protocol.TracksRequest, None),
("POST", protocol.SEGMENT_FILTER_ROUTE, protocol.SegmentFilterRequest, protocol.SegmentFilterReply),
("POST", protocol.LICENSE_ROUTE, protocol.LicenseRequest, protocol.LicenseReply),
("POST", protocol.BAD_KEY_ROUTE, protocol.BadKeyReport, None),
("GET", protocol.LOGS_ROUTE, None, protocol.LogsReply),
("GET", protocol.PROMPT_ROUTE, None, protocol.PromptReply),
("POST", protocol.PROMPT_ROUTE, protocol.PromptAnswer, None),
("GET", protocol.SESSION_ROUTE, None, protocol.SessionInfo),
],
)
def test_the_openapi_yaml_names_only_protocol_keys(method, route, request_shape, reply_shape):
"""The Swagger docs of a route list a subset of the keys its protocol shapes declare."""
spec = yaml.safe_load((SERVED[(method, route)].__doc__ or "").split("---", 1)[1])
if request_shape:
assert properties(spec.get("requestBody")) <= keys(request_shape)
if reply_shape:
assert properties(spec["responses"].get("200")) <= keys(reply_shape)
+2 -1
View File
@@ -7,8 +7,9 @@ import pytest
from unshackle.core import remote_service
from unshackle.core.api import handlers
from unshackle.core.api.errors import APIError, APIErrorCode
from unshackle.core.api.errors import APIError
from unshackle.core.config import config
from unshackle.core.remote_protocol import APIErrorCode
SERVICES = [
{
+2 -1
View File
@@ -16,8 +16,9 @@ from aiohttp import web
from unshackle.core.api import routes
from unshackle.core.api.compression import compression_middleware
from unshackle.core.api.errors import APIError, APIErrorCode
from unshackle.core.api.errors import APIError
from unshackle.core.api.routes import api_handler, cors_middleware, heartbeat, setup_routes
from unshackle.core.remote_protocol import APIErrorCode
pytestmark = pytest.mark.unit
+2 -1
View File
@@ -6,7 +6,8 @@ from types import SimpleNamespace
import pytest
from unshackle.core.api import handlers
from unshackle.core.api.errors import APIError, APIErrorCode
from unshackle.core.api.errors import APIError
from unshackle.core.remote_protocol import APIErrorCode
pytestmark = pytest.mark.unit
@@ -16,10 +16,11 @@ from tests.core.key_resolver import key_table, resolver
from tests.remote.key_source import CAPPED, PR_DEVICE, one_title, remote_keys, remote_session
from unshackle.commands.dl import dl
from unshackle.core.api import handlers
from unshackle.core.api.errors import APIError, APIErrorCode
from unshackle.core.api.errors import APIError
from unshackle.core.api.session_store import SessionEntry
from unshackle.core.config import cdm_entry_names_device
from unshackle.core.drm import Widevine
from unshackle.core.remote_protocol import APIErrorCode
from unshackle.core.remote_service import RemoteClient, RemoteService
from unshackle.core.tracks import Audio, Video
+2 -1
View File
@@ -7,8 +7,9 @@ import time
import pytest
from unshackle.core.api.input_bridge import AuthStatus, InputBridge
from unshackle.core.api.input_bridge import InputBridge
from unshackle.core.api.session_store import SessionEntry, SessionStore, get_session_store
from unshackle.core.remote_protocol import AuthStatus
pytestmark = pytest.mark.unit
+4 -3
View File
@@ -276,7 +276,8 @@ def test_absent_key_keeps_server_devices(monkeypatch):
def test_safe_inflate_rejects_non_str_via_isinstance():
# A non-string cache value must be caught before base64.b64decode raises a 500.
# Mirror the guard used in session_create_handler.
from unshackle.core.api.errors import APIError, APIErrorCode
from unshackle.core.api.errors import APIError
from unshackle.core.remote_protocol import APIErrorCode
def guard(content):
if not isinstance(content, str):
@@ -296,9 +297,9 @@ def _run_session(monkeypatch, tmp_path, data, answer, server_account=False, fail
import zlib
from unshackle.core.api import handlers
from unshackle.core.api.input_bridge import AuthStatus
from unshackle.core.api.session_store import get_session_store
from unshackle.core.config import config
from unshackle.core.remote_protocol import AuthStatus
class PromptingService:
_input_bridge = None
@@ -356,7 +357,7 @@ def test_prompt_post_rejects_response_the_bridge_refused(monkeypatch):
import asyncio
from unshackle.core.api import handlers
from unshackle.core.api.input_bridge import AuthStatus
from unshackle.core.remote_protocol import AuthStatus
bridge = SimpleNamespace(status=AuthStatus.PENDING_INPUT, submit_response=lambda text: False)