feat(remote): add a session channel for the messages the server starts

This commit is contained in:
imSp4rky
2026-11-24 17:50:10 -07:00
parent 5da940a5d3
commit ed090affc3
22 changed files with 1606 additions and 400 deletions
+13 -6
View File
@@ -200,16 +200,23 @@ def test_a_relaying_client_gets_a_stand_in_with_its_device_facts(monkeypatch: py
assert built["params"]["client_identity"] is True
def test_an_answered_call_is_no_longer_pending_before_the_service_wakes() -> None:
def test_an_answered_call_is_no_longer_pending_before_the_service_wakes(monkeypatch: pytest.MonkeyPatch) -> None:
bridge = InputBridge()
release = threading.Event()
real_wait = bridge._response_ready.wait
real_open = bridge._open
def slow_wait(timeout: float) -> bool:
release.wait(5) # hold the service thread asleep after the answer arrives
return real_wait(timeout)
def open_slowly(prompt: str, cdm_call: Any = None) -> Any:
ask = real_open(prompt, cdm_call)
real_wait = ask.answered.wait
bridge._response_ready.wait = slow_wait # type: ignore[method-assign]
def slow_wait(timeout: float) -> bool:
release.wait(5) # hold the service thread asleep after the answer arrives
return real_wait(timeout)
ask.answered.wait = slow_wait # type: ignore[method-assign]
return ask
monkeypatch.setattr(bridge, "_open", open_slowly)
worker = threading.Thread(target=lambda: bridge.request_cdm({"op": "challenge"}, timeout=5))
worker.start()
for _ in range(100):
+11 -7
View File
@@ -4,8 +4,6 @@ from __future__ import annotations
import base64
import logging
from collections import deque
from threading import Lock
from types import SimpleNamespace
from typing import Any
@@ -18,6 +16,7 @@ from unshackle.core import remote_service
from unshackle.core.api import handlers
from unshackle.core.api.errors import APIError, APIErrorCode
from unshackle.core.api.routes import setup_routes
from unshackle.core.remote_channel import PollingChannel, ServerMessages
from unshackle.core.remote_service import RemoteClient, RemoteError, RemoteService
pytestmark = pytest.mark.unit
@@ -236,13 +235,18 @@ def test_server_text_loses_its_control_characters() -> None:
def test_relayed_server_logs_lose_their_control_characters(monkeypatch: pytest.MonkeyPatch) -> None:
service = RemoteService.__new__(RemoteService)
service._session_id = "sid"
service._log_seq = 0
service._recent_logs = deque(maxlen=5)
service._log_drain_lock = Lock()
seen: list[str] = []
service.log = SimpleNamespace(log=lambda level, message: seen.append(message)) # type: ignore[assignment]
service.client = SimpleNamespace(
get_optional=lambda _: {"logs": [{"level": "INFO", "message": "a\x1b[2Jb\nc"}], "last_seq": 1}
get_optional=lambda _: {"logs": [{"seq": 1, "level": "INFO", "message": "a\x1b[2Jb\nc"}], "last_seq": 1}
)
service.drain_server_logs()
PollingChannel(ServerMessages(service)).drain_logs()
assert seen == ["a[2Jb\nc"]
def test_a_relayed_login_prompt_loses_its_control_characters() -> None:
service = RemoteService.__new__(RemoteService)
asked: list[str] = []
service._input_bridge = SimpleNamespace(request_input=lambda prompt: asked.append(prompt) or "1234")
assert ServerMessages(service).ask_user("Code\x1b[2J:\n") == "1234"
assert asked == ["Code[2J:\n"]
+294 -19
View File
@@ -3,11 +3,15 @@
from __future__ import annotations
import asyncio
import json
import logging
from threading import Semaphore, Thread
import threading
from datetime import datetime, timezone
from threading import Event, Semaphore, Thread
from types import SimpleNamespace
from typing import Any, Iterator
from typing import Any, Callable, Iterator, Optional
import aiohttp
import click
import pytest
import requests
@@ -15,12 +19,15 @@ from aiohttp import web
from langcodes import Language
from tests.remote.unit.test_tunnel import wait_until
from unshackle.core import remote_service
from unshackle.core import remote_channel, remote_service
from unshackle.core.api import handlers, routes, session_store
from unshackle.core.api.errors import APIError
from unshackle.core.api.handlers import api_key_authentication
from unshackle.core.api.routes import cors_middleware, no_5xx_middleware, setup_routes
from unshackle.core.cdm import client_relay
from unshackle.core.config import config
from unshackle.core.remote_protocol import SESSION_ROUTE, APIErrorCode
from unshackle.core.remote_channel import PollingChannel, WebSocketChannel
from unshackle.core.remote_protocol import CHANNEL_ROUTE, LOGS_ROUTE, PROMPT_ROUTE, SESSION_ROUTE, APIErrorCode
from unshackle.core.remote_service import RemoteError, RemoteService
from unshackle.core.titles.movie import Movie, Movies
from unshackle.core.tracks import Audio, Chapters, Tracks
@@ -33,9 +40,13 @@ CODE = "1234"
class StubService:
"""The server side of the remote session: a login that asks for a code, three titles, one audio track each."""
"""The server side of the remote session: a login that asks for a code, three titles, one audio track each.
A test puts extra service work in ``hooks``: "titles" runs inside get_titles, on the service thread.
"""
logins = 0
hooks: dict[str, Callable[["StubService"], None]] = {}
def __init__(self, beats: Semaphore) -> None:
self.beats = beats
@@ -52,6 +63,8 @@ class StubService:
self.log.info(f"Logged in to EXAMPLE, login {self.login}")
def get_titles(self) -> Movies:
if hook := self.hooks.get("titles"):
hook(self)
return Movies(
[Movie(id_=f"example-{n}", service=StubService, name=f"Example {n}", year=2024) for n in (1, 2, 3)]
)
@@ -80,10 +93,15 @@ class StubService:
@pytest.fixture
def server(monkeypatch: pytest.MonkeyPatch, tmp_path: Any) -> Iterator[SimpleNamespace]:
"""The real route table and API key middleware on a loopback port, with the stub as the only service."""
def server(request: pytest.FixtureRequest, monkeypatch: pytest.MonkeyPatch, tmp_path: Any) -> Iterator[SimpleNamespace]:
"""The real route table and API key middleware on a loopback port, with the stub as the only service.
A test parametrized with ``server=False`` gets a gateway in front of it that answers the channel upgrade with 502.
"""
refuse = not getattr(request, "param", True)
beats = Semaphore(0)
seen: list[tuple[str, str, int]] = []
bodies: list[tuple[str, bytes]] = []
class CountedHeartbeat(web.StreamResponse):
"""Count the first heartbeat of each tracks request; aiohttp calls prepare again when the handler returns."""
@@ -97,19 +115,26 @@ def server(monkeypatch: pytest.MonkeyPatch, tmp_path: Any) -> Iterator[SimpleNam
@web.middleware
async def record(request: web.Request, handler: Any) -> web.StreamResponse:
response = await handler(request)
if refuse and request.path.endswith("/channel"):
seen.append((request.method, request.path, 502))
return web.Response(status=502, text="Bad gateway")
try:
response = await handler(request)
except web.HTTPException as e:
seen.append((request.method, request.path, e.status))
raise
seen.append((request.method, request.path, response.status))
if isinstance(response, web.Response) and response.body is not None:
bodies.append((request.path, bytes(response.body))) # type: ignore[arg-type]
return response
StubService.logins = 0
monkeypatch.setattr(StubService, "hooks", {})
monkeypatch.setattr(routes, "HEARTBEAT_INTERVAL", 0.02)
monkeypatch.setattr(routes.web, "StreamResponse", CountedHeartbeat)
monkeypatch.setattr(remote_service, "KEEPALIVE_MIN_INTERVAL", 0.05)
monkeypatch.setattr(remote_channel, "KEEPALIVE_MIN_INTERVAL", 0.05)
monkeypatch.setattr(remote_channel, "AUTH_POLL_INTERVAL", 0.01)
monkeypatch.setattr(remote_service, "REOPEN_WAIT", 5.0)
poll_auth_completion = RemoteService.poll_auth_completion
monkeypatch.setattr(
RemoteService, "poll_auth_completion", lambda self: poll_auth_completion(self, poll_interval=0.01)
)
monkeypatch.setattr(session_store, "session_store", None)
monkeypatch.setattr(config, "serve", {"session_ttl": 1.5})
monkeypatch.setattr(config, "credentials", {})
@@ -133,7 +158,7 @@ def server(monkeypatch: pytest.MonkeyPatch, tmp_path: Any) -> Iterator[SimpleNam
thread.start()
host, port = runner.addresses[0][:2]
try:
yield SimpleNamespace(url=f"http://{host}:{port}", loop=loop, seen=seen)
yield SimpleNamespace(url=f"http://{host}:{port}", loop=loop, seen=seen, bodies=bodies)
finally:
asyncio.run_coroutine_threadsafe(runner.cleanup(), loop).result(10)
loop.call_soon_threadsafe(loop.stop)
@@ -141,9 +166,9 @@ def server(monkeypatch: pytest.MonkeyPatch, tmp_path: Any) -> Iterator[SimpleNam
loop.close()
def make_client(url: str) -> RemoteService:
def make_client(url: str, cdm: Any = None) -> RemoteService:
"""A client whose first candidate header is not the one the server reads, so it must move to the second."""
obj = SimpleNamespace(cdm=None, cdm_entry=False, proxy_providers=[])
obj = SimpleNamespace(cdm=cdm, cdm_entry=False, proxy_providers=[])
parent = click.Context(click.Command("dl"), obj=obj)
parent.params = {"no_proxy": True}
ctx = click.Context(click.Command("EXAMPLE"), parent=parent, obj=obj)
@@ -158,8 +183,55 @@ def forget(server: SimpleNamespace, session_id: str) -> None:
asyncio.run_coroutine_threadsafe(store.delete(session_id), server.loop).result(10)
def test_a_remote_session_runs_end_to_end_over_http(server: SimpleNamespace, caplog: pytest.LogCaptureFixture) -> None:
caplog.set_level(logging.INFO)
def on_loop(server: SimpleNamespace, coroutine: Any) -> Any:
return asyncio.run_coroutine_threadsafe(coroutine, server.loop).result(10)
def count(server: SimpleNamespace, method: str, route: str, session_id: Optional[str] = None) -> int:
"""The requests the server saw for one route; without a session id, for any session."""
if session_id is None:
prefix, _, suffix = route.partition("{session_id}")
return len(
[
s
for s in server.seen
if s[0] == method
and s[1].startswith(prefix)
and s[1].endswith(suffix)
and "/" not in s[1][len(prefix) : len(s[1]) - len(suffix) or None]
]
)
return len([s for s in server.seen if s[:2] == (method, route.format(session_id=session_id))])
def example_messages(caplog: pytest.LogCaptureFixture) -> list[str]:
"""What the client logged as the service's own lines, which the server relayed."""
return [r.getMessage() for r in caplog.records if r.name == "EXAMPLE"]
def idle_seconds(entry: Any) -> float:
return (datetime.now(timezone.utc) - entry.last_accessed).total_seconds()
@pytest.mark.parametrize(
"server,channel",
[(True, "none"), (False, "refused"), (True, "failed")],
ids=["old-client", "refused-upgrade", "failed-connect"],
indirect=["server"],
)
def test_a_remote_session_runs_end_to_end_over_http(
server: SimpleNamespace, channel: str, caplog: pytest.LogCaptureFixture, monkeypatch: pytest.MonkeyPatch
) -> None:
"""A client that does not open the channel, or whose upgrade is refused or fails, polls with the same replies."""
caplog.set_level(logging.DEBUG)
if channel == "none":
monkeypatch.setattr(WebSocketChannel, "open", lambda self, timeout=0: False)
if channel == "failed":
async def unreachable(self: Any, url: str, **kwargs: Any) -> Any:
raise aiohttp.ClientConnectionError("EXAMPLE connect failed")
monkeypatch.setattr(aiohttp.ClientSession, "_ws_connect", unreachable)
service = make_client(server.url)
try:
service.authenticate()
@@ -167,6 +239,11 @@ def test_a_remote_session_runs_end_to_end_over_http(server: SimpleNamespace, cap
assert first
assert server.seen[0] == ("POST", "/api/session/create", 401)
assert ("GET", f"/api/session/{first}/prompt", 200) in server.seen
assert isinstance(service.channel, PollingChannel)
assert count(server, "GET", CHANNEL_ROUTE, first) == int(channel == "refused")
channel_lines = [r for r in caplog.records if r.name == "remote_channel"]
assert all(r.levelno == logging.DEBUG for r in channel_lines)
assert bool(channel_lines) == (channel != "none")
assert any(r.name == "EXAMPLE" and r.message == "Logged in to EXAMPLE, login 1" for r in caplog.records)
info = SESSION_ROUTE.format(session_id=first)
@@ -190,6 +267,204 @@ def test_a_remote_session_runs_end_to_end_over_http(server: SimpleNamespace, cap
finally:
second = service._session_id
service.close()
assert service._keepalive_stop.is_set()
assert service.channel is None
assert ("DELETE", SESSION_ROUTE.format(session_id=second), 200) in server.seen
assert not session_store.get_session_store()._sessions
prompts = {body for path, body in server.bodies if path.endswith("/prompt")}
assert prompts <= {
b'{"status": "authenticating"}',
b'{"status": "pending_input", "prompt": "Enter the EXAMPLE code"}',
b'{"status": "authenticated"}',
b'{"status": "accepted"}',
}
assert b'{"status": "pending_input", "prompt": "Enter the EXAMPLE code"}' in prompts
logs = [json.loads(body) for path, body in server.bodies if path.endswith("/logs")]
assert logs and all(list(reply) == ["session_id", "logs", "last_seq"] for reply in logs)
assert [list(r) for reply in logs for r in reply["logs"]][:1] == [["seq", "level", "message", "ts"]]
def test_the_session_channel_carries_what_the_server_starts(
server: SimpleNamespace, caplog: pytest.LogCaptureFixture, monkeypatch: pytest.MonkeyPatch
) -> None:
caplog.set_level(logging.INFO)
monkeypatch.setattr(client_relay, "answer_cdm_call", lambda cdm, call, sessions: {"op": call["op"]})
answers: list[Any] = []
release = Event()
def titles(stub: StubService) -> None:
stub.log.info("Listing EXAMPLE titles")
assert release.wait(10)
answers.append(stub._input_bridge.request_cdm({"op": "close", "session": "EXAMPLE"}))
answers.append(stub._input_bridge.request_input("Pick an EXAMPLE profile"))
StubService.hooks["titles"] = titles
service = make_client(server.url, cdm=SimpleNamespace())
store = session_store.get_session_store()
try:
service.authenticate()
first = service._session_id
assert first
assert isinstance(service.channel, WebSocketChannel) and service.channel.connected.is_set()
assert "Logged in to EXAMPLE, login 1" in example_messages(caplog)
listed: list[Any] = []
listing = Thread(target=lambda: listed.append(service.get_titles()), daemon=True)
listing.start()
assert wait_until(lambda: "Listing EXAMPLE titles" in example_messages(caplog), 10)
assert listing.is_alive(), "the log record must arrive while its call still runs"
release.set()
listing.join(10)
assert [str(t.id) for t in listed[0]] == ["example-1", "example-2", "example-3"]
assert answers == [{"op": "close"}, CODE]
assert service.get_tracks(listed[0][0]).audio
assert count(server, "GET", PROMPT_ROUTE) == count(server, "GET", LOGS_ROUTE) == 0
forget(server, first)
assert wait_until(lambda: not service.channel.connected.is_set(), 5)
assert [str(t.id) for t in service.get_tracks(listed[0][1]).audio] == ["example-2-login2"]
second = service._session_id
assert second not in (None, first)
assert isinstance(service.channel, WebSocketChannel) and service.channel.connected.is_set()
assert wait_until(lambda: store.peek(second).channel.attached, 5)
info = count(server, "GET", SESSION_ROUTE, second)
server.loop.call_soon_threadsafe(store.start_drain)
assert wait_until(lambda: service.channel.draining_now, 5)
assert count(server, "GET", SESSION_ROUTE, second) == info
assert wait_until(lambda: session_store.DRAIN_WARNING in example_messages(caplog), 5)
assert service.server_draining()
server.loop.call_soon_threadsafe(store.stop_drain)
assert wait_until(lambda: not store.draining, 5)
assert not service.server_draining()
assert count(server, "GET", PROMPT_ROUTE) == count(server, "GET", LOGS_ROUTE) == 0
finally:
release.set()
service.close()
def test_an_open_channel_keeps_the_session_alive(server: SimpleNamespace, monkeypatch: pytest.MonkeyPatch) -> None:
ttl = 0.3
monkeypatch.setitem(config.serve, "session_ttl", ttl)
service = make_client(server.url)
store = session_store.get_session_store()
try:
service.authenticate()
session_id = service._session_id
entry = store.peek(session_id)
assert wait_until(lambda: entry.channel.attached, 5)
assert wait_until(lambda: idle_seconds(entry) > 3 * ttl, 10)
assert on_loop(server, store.cleanup_expired()) == 0
assert store.peek(session_id) is entry
assert count(server, "GET", SESSION_ROUTE, session_id) == 0
assert count(server, "GET", LOGS_ROUTE) == count(server, "GET", PROMPT_ROUTE) == 0
service.close_channel()
assert wait_until(lambda: not entry.channel.attached, 5)
assert wait_until(lambda: idle_seconds(entry) > 2 * ttl, 10)
assert on_loop(server, store.cleanup_expired()) == 1
assert store.peek(session_id) is None
assert count(server, "GET", SESSION_ROUTE, session_id) == 0
finally:
service.close()
def gate_channel(monkeypatch: pytest.MonkeyPatch) -> threading.Event:
"""Make the channel route refuse while the returned event is set, as a gateway that drops WebSockets does."""
monkeypatch.setattr(remote_channel, "RECONNECT_DELAY", 0.05)
refuse = threading.Event()
channel_handler = routes.session_channel_handler
async def gated(session_id: str, request: web.Request) -> web.StreamResponse:
if refuse.is_set():
raise APIError(APIErrorCode.SERVICE_UNAVAILABLE, "The EXAMPLE channel is down")
return await channel_handler(session_id, request)
monkeypatch.setattr(routes, "session_channel_handler", gated)
return refuse
def test_a_dropped_channel_falls_back_to_polling_until_it_reconnects(
server: SimpleNamespace, caplog: pytest.LogCaptureFixture, monkeypatch: pytest.MonkeyPatch
) -> None:
caplog.set_level(logging.INFO)
refuse = gate_channel(monkeypatch)
StubService.hooks["titles"] = lambda stub: stub.log.info("Listing EXAMPLE titles")
service = make_client(server.url)
store = session_store.get_session_store()
try:
service.authenticate()
session_id = service._session_id
entry = store.peek(session_id)
channel = service.channel
assert isinstance(channel, WebSocketChannel)
assert wait_until(lambda: entry.channel.attached, 5)
refuse.set()
on_loop(server, entry.channel.ws.close())
assert wait_until(lambda: not channel.connected.is_set(), 5)
titles = service.get_titles()
assert count(server, "GET", LOGS_ROUTE, session_id) >= 1
assert "Listing EXAMPLE titles" in example_messages(caplog)
assert wait_until(lambda: count(server, "GET", SESSION_ROUTE, session_id) >= 1, 5), "no keepalive took over"
refuse.clear()
assert wait_until(lambda: channel.connected.is_set() and entry.channel.attached, 10)
assert wait_until(lambda: channel.fallback.keepalive_stop.is_set(), 5)
logs = count(server, "GET", LOGS_ROUTE, session_id)
assert service.get_tracks(titles[0]).audio
assert count(server, "GET", LOGS_ROUTE, session_id) == logs
assert example_messages(caplog).count("Listing EXAMPLE titles") == 1
finally:
service.close()
def test_a_cdm_call_made_while_the_channel_is_down_goes_through_polling(
server: SimpleNamespace, monkeypatch: pytest.MonkeyPatch
) -> None:
refuse = gate_channel(monkeypatch)
monkeypatch.setattr(client_relay, "answer_cdm_call", lambda cdm, call, sessions: {"op": call["op"]})
service = make_client(server.url, cdm=SimpleNamespace())
store = session_store.get_session_store()
answers: list[Any] = []
def titles(stub: StubService) -> None:
refuse.set()
entry = store.peek(service._session_id)
asyncio.run_coroutine_threadsafe(entry.channel.ws.close(), server.loop).result(5)
assert wait_until(lambda: not service.channel.connected.is_set() and not entry.channel.attached, 5)
answers.append(stub._input_bridge.request_cdm({"op": "close", "session": "EXAMPLE"}))
StubService.hooks["titles"] = titles
try:
service.authenticate()
assert isinstance(service.channel, WebSocketChannel)
service.get_titles()
assert answers == [{"op": "close"}]
assert count(server, "GET", PROMPT_ROUTE, service._session_id) >= 1
finally:
service.close()
def test_a_prompt_the_client_cannot_answer_fails_the_login_at_once(server: SimpleNamespace) -> None:
def refuse(prompt: str) -> str:
raise RuntimeError("the EXAMPLE caller left")
service = make_client(server.url)
service._input_bridge = SimpleNamespace(request_input=refuse)
failed: list[BaseException] = []
def login() -> None:
try:
service.authenticate()
except BaseException as e:
failed.append(e)
try:
thread = Thread(target=login, daemon=True)
thread.start()
thread.join(10)
assert not thread.is_alive(), "the login waited for an answer that cannot come"
assert isinstance(failed[0], RemoteError)
assert "the EXAMPLE caller left" in failed[0].message
finally:
service.close()
+11 -10
View File
@@ -10,7 +10,8 @@ import pytest
import responses
from tests.remote.unit.test_session_reopen import SERVER, make_service
from unshackle.core import remote_service
from unshackle.core import remote_channel, remote_service
from unshackle.core.remote_channel import PollingChannel, ServerMessages
from unshackle.core.remote_protocol import ClientErrorKind
from unshackle.core.remote_service import RemoteClient
@@ -59,6 +60,7 @@ def test_recover_moves_to_the_next_auth_header() -> None:
@responses.activate
def test_server_draining_moves_to_the_next_auth_header() -> None:
service = make_service()
service.channel = PollingChannel(ServerMessages(service))
responses.add_callback(responses.GET, f"{SERVER}/api/session/s1", callback=second_header_only({"draining": True}))
assert service.server_draining()
@@ -66,33 +68,32 @@ def test_server_draining_moves_to_the_next_auth_header() -> None:
@responses.activate
def test_keepalive_moves_to_the_next_auth_header(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(remote_service, "KEEPALIVE_MIN_INTERVAL", 0.01)
service = make_service()
monkeypatch.setattr(service.client, "get_optional", lambda endpoint: {"expires_in": 0.03})
monkeypatch.setattr(remote_channel, "KEEPALIVE_MIN_INTERVAL", 0.01)
polling = PollingChannel(ServerMessages(make_service()))
pinged = Event()
info = {"valid": True, "expires_in": 0.03}
responses.add_callback(responses.GET, f"{SERVER}/api/session/s1", callback=second_header_only(info, pinged.set))
service.start_keepalive()
polling.keep_alive()
try:
assert pinged.wait(5)
finally:
service._keepalive_stop.set()
polling.stop_keepalive()
assert [c.response.status_code for c in responses.calls[:2]] == [401, 200]
@responses.activate
def test_cdm_poller_moves_to_the_next_auth_header(monkeypatch: pytest.MonkeyPatch) -> None:
service = make_service()
polling = PollingChannel(ServerMessages(make_service()))
stop = Event()
answered: list[dict] = []
monkeypatch.setattr(service, "answer_cdm_call", lambda call, sessions: (answered.append(call), stop.set()))
monkeypatch.setattr(service, "close_cdm_sessions", lambda sessions=None: None)
monkeypatch.setattr(polling.messages, "answer_cdm", lambda call: (answered.append(call), stop.set()))
monkeypatch.setattr(polling, "answer", lambda response: None)
call = {"id": "c1", "op": "open"}
reply = {"status": "pending_input", "cdm_call": call}
responses.add_callback(responses.GET, f"{SERVER}/api/session/s1/prompt", callback=second_header_only(reply))
poller = Thread(target=service.poll_cdm_calls, args=(stop, 0.01), daemon=True)
poller = Thread(target=polling.poll_cdm_calls, args=(stop, 0.01), daemon=True)
poller.start()
try:
assert stop.wait(5)
+25 -2
View File
@@ -10,6 +10,7 @@ from typing import Any, Optional
import pytest
import yaml
from unshackle.core import remote_channel
from unshackle.core import remote_protocol as protocol
from unshackle.core import remote_service
from unshackle.core.api import routes
@@ -23,13 +24,16 @@ CLIENT_METHODS = {
"post": "POST",
"post_optional": "POST",
"delete": "DELETE",
"ws_connect": "GET",
}
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"))
"""The client modules as one tree: the remote service and the session channel adapters."""
modules = [ast.parse(Path(m.__file__).read_text(encoding="utf-8")) for m in (remote_service, remote_channel)]
return ast.Module(body=[node for module in modules for node in module.body], type_ignores=[])
def client_calls() -> tuple[set[tuple[str, str]], set[str]]:
@@ -41,7 +45,7 @@ def client_calls() -> tuple[set[tuple[str, str]], set[str]]:
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):
if not isinstance(function, (ast.FunctionDef, ast.AsyncFunctionDef)):
continue
local = {
target.id: node.value
@@ -114,7 +118,10 @@ def test_the_wire_values_stay_what_older_peers_send():
"BAD_KEY_ROUTE": "/api/session/{session_id}/keys/bad",
"LOGS_ROUTE": "/api/session/{session_id}/logs",
"PROMPT_ROUTE": "/api/session/{session_id}/prompt",
"CHANNEL_ROUTE": "/api/session/{session_id}/channel",
}
assert [m.value for m in protocol.ChannelMessage] == ["prompt", "cdm_call", "log", "status", "drain", "answer"]
assert protocol.CHANNEL_SESSION_GONE == 4404
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] == [
@@ -161,6 +168,22 @@ def test_session_transport_keys_are_the_create_body():
}
@pytest.mark.parametrize(
"shape,fields",
[
(protocol.ChannelPrompt, {"type", "id", "prompt"}),
(protocol.ChannelCdmCall, {"type", "id", "call"}),
(protocol.ChannelLog, {"type", "seq", "level", "message", "ts"}),
(protocol.ChannelStatus, {"type", "status", "error"}),
(protocol.ChannelDrain, {"type", "draining"}),
(protocol.ChannelAnswer, {"type", "id", "response", "error"}),
],
)
def test_the_channel_messages_keep_their_fields(shape, fields):
"""A session channel message is a JSON text frame; an older peer reads these keys."""
assert keys(shape) == fields
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}
+10 -8
View File
@@ -211,11 +211,12 @@ def test_a_geofenced_remote_service_gets_its_first_allowed_region_as_proxy(monke
def test_a_quiet_remote_login_shows_its_last_server_lines_as_a_notice(monkeypatch):
import logging
from threading import Lock
from unshackle.core import remote_channel
shown = []
monkeypatch.setattr(remote_service, "show_notice", shown.append)
monkeypatch.setattr(remote_service.time, "sleep", lambda s: None)
monkeypatch.setattr(remote_channel, "show_notice", shown.append)
monkeypatch.setattr(remote_channel, "AUTH_POLL_INTERVAL", 0)
logs = iter([["+ IP Region: CA"], ["+ Open URL: https://example.test/start\n+ Enter pair code: 9835-2503"], []])
statuses = iter(["authenticating", "authenticating", "authenticating", "authenticated"])
@@ -225,17 +226,18 @@ def test_a_quiet_remote_login_shows_its_last_server_lines_as_a_notice(monkeypatc
def get_optional(self, endpoint):
batch = next(logs, [])
first = remote.seq + 1
remote.seq += len(batch)
return {"logs": [{"level": "INFO", "message": m} for m in batch], "last_seq": remote.seq}
records = [{"seq": first + i, "level": "INFO", "message": m} for i, m in enumerate(batch)]
return {"logs": records, "last_seq": remote.seq}
remote = object.__new__(remote_service.RemoteService)
remote.seq = 0
remote.client, remote._session_id, remote._log_seq = Client(), "sid", 0
remote._recent_logs, remote.auth_notice, remote._log_drain_lock = [], None, Lock()
remote.log, remote._cdm_sessions = logging.getLogger("test"), {}
remote.client, remote._session_id, remote.auth_notice = Client(), "sid", None
remote.log = logging.getLogger("test")
monkeypatch.setattr(remote_service.RemoteService, "local_cdm", None)
remote.poll_auth_completion(poll_interval=0)
remote_channel.PollingChannel(remote_channel.ServerMessages(remote)).wait_auth()
# silent while the remote was still logging; the pair code once it went quiet; cleared when done
assert shown == ["+ IP Region: CA\n+ Open URL: https://example.test/start\n+ Enter pair code: 9835-2503", None]
assert remote.auth_notice is None
@@ -15,6 +15,7 @@ import unshackle.core.drm as drm_mod
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 import remote_channel
from unshackle.core.api import handlers
from unshackle.core.api.errors import APIError
from unshackle.core.api.session_store import SessionEntry
@@ -756,26 +757,28 @@ def test_a_client_with_no_device_does_not_decline():
assert "server_cdm" not in data
def created(answer):
def created(answer, monkeypatch):
"""Run ``authenticate()`` to its end for a device the service's cdm entry loaded."""
svc, _ = sent_create(None, cdm_entry=True, cdm_map={"EXAMPLE1": "my_device"})
svc._server_cdm = None
svc.client = SimpleNamespace(post=lambda path, data: {"session_id": "sess", **answer})
svc.close = svc.start_keepalive = lambda: None
svc.close = lambda: None
channel = SimpleNamespace(keep_alive=lambda: None, drain_logs=lambda: None, in_flight=None)
monkeypatch.setattr(remote_channel, "open_channel", lambda service: channel)
svc.authenticate()
return svc
def test_the_client_says_when_a_cdm_entry_gave_the_licensing_to_its_device(caplog):
def test_the_client_says_when_a_cdm_entry_gave_the_licensing_to_its_device(caplog, monkeypatch):
with caplog.at_level(logging.INFO):
svc = created({"server_cdm": False})
svc = created({"server_cdm": False}, monkeypatch)
assert svc._server_cdm is False
assert "cdm config has an entry for EXAMPLE1" in caplog.text
def test_the_client_does_not_claim_its_device_when_the_server_keeps_the_server_cdm(caplog):
def test_the_client_does_not_claim_its_device_when_the_server_keeps_the_server_cdm(caplog, monkeypatch):
with caplog.at_level(logging.INFO):
svc = created({"server_cdm": True, "server_cdm_max_height": 1080})
svc = created({"server_cdm": True, "server_cdm_max_height": 1080}, monkeypatch)
assert svc._server_cdm is True
assert "your own device is not used" in caplog.text
assert "cdm config has an entry" not in caplog.text
+136
View File
@@ -0,0 +1,136 @@
"""The server side of the remote session channel: what it sends on attach, and how it lets go of a socket."""
from __future__ import annotations
import asyncio
import logging
import threading
from typing import Any
import pytest
from tests.remote.unit.test_tunnel import wait_until
from unshackle.core.api.input_bridge import InputBridge
from unshackle.core.api.session_log import SessionLogBuffer
from unshackle.core.api.session_store import SessionEntry
pytestmark = pytest.mark.unit
class FakeSocket:
"""A server WebSocket that records what it sends, and ends its read loop when it closes."""
def __init__(self) -> None:
self.sent: list[dict[str, Any]] = []
self.closed = asyncio.Event()
async def send_json(self, message: dict[str, Any]) -> None:
self.sent.append(message)
async def close(self, code: int = 1000, message: bytes = b"") -> bool:
self.closed.set()
return True
def __aiter__(self) -> FakeSocket:
return self
async def __anext__(self) -> Any:
await self.closed.wait()
raise StopAsyncIteration
def entry_with_logs(count: int) -> SessionEntry:
entry = SessionEntry("s", "EXAMPLE", None)
entry.log_buffer = SessionLogBuffer()
entry.log_buffer.listener = entry.channel.log
entry.input_bridge = InputBridge()
entry.input_bridge.channel = entry.channel
for n in range(count):
entry.log_buffer.append(logging.INFO, f"EXAMPLE line {n + 1}")
return entry
def log_seqs(socket: FakeSocket) -> list[int]:
return [m["seq"] for m in socket.sent if m["type"] == "log"]
async def test_the_backlog_goes_before_a_record_logged_while_the_old_socket_closes() -> None:
entry = entry_with_logs(4)
old = FakeSocket()
async def close_slowly(code: int = 1000, message: bytes = b"") -> bool:
entry.log_buffer.append(logging.INFO, "EXAMPLE line 5")
await asyncio.sleep(0)
old.closed.set()
return True
old.close = close_slowly # type: ignore[method-assign]
entry.channel.ws = old # type: ignore[assignment]
new = FakeSocket()
serving = asyncio.create_task(entry.channel.serve(new, entry, 2, False)) # type: ignore[arg-type]
for _ in range(200):
if len(log_seqs(new)) >= 3:
break
await asyncio.sleep(0.01)
assert log_seqs(new) == [3, 4, 5]
assert {"type": "status", "status": "authenticated"} in new.sent
await new.close()
await serving
assert not entry.channel.attached
async def test_a_socket_that_cannot_send_is_closed_and_detached() -> None:
entry = entry_with_logs(1)
broken = FakeSocket()
async def fail(message: dict[str, Any]) -> None:
raise RuntimeError("EXAMPLE socket gone")
broken.send_json = fail # type: ignore[method-assign]
await asyncio.wait_for(entry.channel.serve(broken, entry, 0, False), 5) # type: ignore[arg-type]
assert broken.closed.is_set()
assert not entry.channel.attached
async def test_a_detached_channel_hands_its_waiting_asks_back_to_the_prompt_routes() -> None:
entry = entry_with_logs(0)
bridge = entry.input_bridge
assert bridge is not None
socket = FakeSocket()
serving = asyncio.create_task(entry.channel.serve(socket, entry, 0, False)) # type: ignore[arg-type]
await asyncio.sleep(0)
answers: list[Any] = []
worker = threading.Thread(target=lambda: answers.append(bridge.request_cdm({"op": "close"}, timeout=5)))
worker.start()
for _ in range(200):
if any(m["type"] == "cdm_call" for m in socket.sent):
break
await asyncio.sleep(0.01)
assert bridge.get_pending_cdm_call() is None, "the channel carries the call, so polling must not see it"
await socket.close()
await serving
assert bridge.get_pending_cdm_call() == {"op": "close"}
assert bridge.submit_response('{"op": "close"}')
worker.join(5)
assert answers == [{"op": "close"}]
def test_a_prompt_the_client_refuses_stops_the_service_at_once() -> None:
bridge = InputBridge()
offered: list[Any] = []
bridge.channel = type("Attached", (), {"attached": True, "offer": lambda self, ask: offered.append(ask) or True})()
failed: list[BaseException] = []
def ask() -> None:
try:
bridge.request_input("Enter the EXAMPLE code", timeout=30)
except RuntimeError as e:
failed.append(e)
worker = threading.Thread(target=ask)
worker.start()
assert wait_until(lambda: bool(offered), 5)
assert bridge.answer(offered[0].id, "", "stdin is closed")
worker.join(5)
assert not worker.is_alive()
assert "stdin is closed" in str(failed[0])
+6 -8
View File
@@ -1,7 +1,6 @@
"""Session log forwarding: buffer semantics, mirror wrapping, handler drain."""
import logging
import threading
import pytest
@@ -166,12 +165,12 @@ def test_service_params_keyed_by_flag_reach_an_option_with_another_name() -> Non
def test_drain_server_logs_survives_client_systemexit() -> None:
"""RemoteClient raises SystemExit on transport errors; the drain must swallow it."""
from unshackle.core.remote_channel import PollingChannel, ServerMessages
from unshackle.core.remote_service import RemoteService
svc = RemoteService.__new__(RemoteService)
svc._session_id = "abc"
svc._log_seq = 0
svc._log_drain_lock = threading.Lock()
svc.channel = PollingChannel(ServerMessages(svc))
class ExitingClient:
def get_optional(self, endpoint: str) -> dict:
@@ -179,17 +178,16 @@ def test_drain_server_logs_survives_client_systemexit() -> None:
svc.client = ExitingClient()
svc.drain_server_logs() # must not raise
assert svc._log_seq == 0
assert svc.channel.messages.log_seq == 0
def test_drain_server_logs_reemits_and_advances_seq() -> None:
from unshackle.core.remote_channel import PollingChannel, ServerMessages
from unshackle.core.remote_service import RemoteService
svc = RemoteService.__new__(RemoteService)
svc._session_id = "abc"
svc._log_seq = 0
svc._log_drain_lock = threading.Lock()
svc._recent_logs = []
svc.channel = PollingChannel(ServerMessages(svc))
svc.log = logging.getLogger("test-drain-reemit")
class StubClient:
@@ -210,7 +208,7 @@ def test_drain_server_logs_reemits_and_advances_seq() -> None:
svc.drain_server_logs()
finally:
svc.log.removeHandler(handler)
assert svc._log_seq == 1
assert svc.channel.messages.log_seq == 1
assert [(r.levelno, r.getMessage()) for r in records] == [(logging.WARNING, "server says")]
+1 -3
View File
@@ -4,7 +4,7 @@ from __future__ import annotations
import json
import logging
from threading import Event, Lock
from threading import Lock
import pytest
import requests
@@ -42,14 +42,12 @@ def make_service() -> RemoteService:
service.service_tag = service.title_id = "TEST"
service._session_id = "s1"
service._reopen_lock = Lock()
service._keepalive_stop = Event()
service._segment_filters = {}
service._tracks_by_title = {}
service._titles = None
service._title_alias = {}
service._track_alias = {}
service._current_title = None
service._log_seq = 0
service._server_cdm = service._server_device = service._server_vault = False
return service