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
+14 -3
View File
@@ -948,7 +948,8 @@ The server holds remote sessions in memory. They expire after `serve.session_ttl
```text
POST /api/session/create → returns session_id, status "authenticating"
GET /api/session/{id}/prompt → poll until authenticated (submit answers via POST)
GET /api/session/{id}/channel → WebSocket: prompts, CDM calls, logs, login state, drain
GET /api/session/{id}/prompt → without the channel: poll until authenticated (submit answers via POST)
GET /api/session/{id}/titles → list titles
POST /api/session/{id}/tracks → tracks + chapters (with URLs) for one title
POST /api/session/{id}/segments → resolve segment URLs / DRM / headers per track
@@ -1004,9 +1005,19 @@ The `proxy` value must be a full proxy URI, unless the operator gives your API k
| `400` | `INVALID_INPUT` | Missing `service` or `title_id`. |
| `400` | `INVALID_SERVICE` | Unknown or disallowed service. |
### `GET /api/session/{session_id}/channel`
Open the remote session channel: a WebSocket that carries the prompts, CDM calls, log records, login state and drain state of the remote session, and the client's answers. Pass `since=<seq>` to get only the log records newer than that sequence number. The server closes the WebSocket with code `4404` when the remote session ends. See [The remote session channel](remote-sessions.md#the-remote-session-channel) for the messages.
| Status | Error code | Meaning |
| --- | --- | --- |
| `101` | - | WebSocket open. |
| `403` | `FORBIDDEN` | Request IP differs from the remote session creator. |
| `404` | `SESSION_NOT_FOUND` | No such session. |
### `GET /api/session/{session_id}/prompt`
Poll for the authentication status and any pending interactive prompt (OTP, PIN, device code). Response variants:
The polling fallback of the remote session channel. Poll for the authentication status and any pending interactive prompt (OTP, PIN, device code). Response variants:
=== "Authenticating"
@@ -1056,7 +1067,7 @@ Submit a response to a pending prompt. Body: `{ "response": "..." }` (required).
### `GET /api/session/{session_id}/logs`
Drain the service's server-side log output for this remote session. The server mirrors every log call the service makes (`self.log.info`, warnings, errors) into a bounded per-session buffer, so a remote client can see why an auth, title, or license step failed. Pass `since=<seq>` to get only records newer than the last drained sequence number. Works in every auth state, including `failed`.
The polling fallback of the remote session channel. Drain the service's server-side log output for this remote session. The server mirrors every log call the service makes (`self.log.info`, warnings, errors) into a bounded per-session buffer, so a remote client can see why an auth, title, or license step failed. Pass `since=<seq>` to get only records newer than the last drained sequence number. Works in every auth state, including `failed`.
=== "Response `200`"
+1
View File
@@ -208,6 +208,7 @@ request and response in full.
| `POST` | `/api/session/{session_id}/samples` | Server-side cbcs sample decryption for one track. |
| `POST` | `/api/session/{session_id}/license` | Proxy or server-side DRM licensing. |
| `POST` | `/api/session/{session_id}/keys/bad` | Report a server-vault content key that did not decrypt. |
| `GET` | `/api/session/{session_id}/channel` | WebSocket of the remote session channel: prompts, CDM calls, logs, login state. |
| `GET` | `/api/session/{session_id}/logs` | Drain the service's server-side log output. |
| `GET` | `/api/session/{session_id}/prompt` | Poll for interactive auth status/prompt. |
| `POST` | `/api/session/{session_id}/prompt` | Submit an answer to an auth prompt. |
+60 -23
View File
@@ -188,8 +188,8 @@ hood the client walks a remote session through its lifecycle.
Some services need a one-time code, PIN, or device confirmation. When the
server's auth flow asks for input, the remote session enters `pending_input`. The
client polls, displays the prompt to you locally, collects your answer, and
sends it back. The server's auth thread resumes with your response.
server sends the prompt to the client, the client shows it to you locally, collects
your answer, and sends it back. The server's auth thread resumes with your response.
```text
Enter the 6-digit code sent to your email: 483920
@@ -203,8 +203,7 @@ hood the client walks a remote session through its lifecycle.
`service_params`.
The server also mirrors the service's own log output (`self.log`) into a
per-session buffer. The client drains it through
`GET /api/session/{id}/logs` after each step and prints the records
per-session buffer and sends each record to the client, which prints the records
locally, so you see the server-side reason when a step fails.
=== "3. Titles + tracks"
@@ -237,9 +236,9 @@ hood the client walks a remote session through its lifecycle.
=== "5. Download + close"
The client downloads, decrypts, and muxes locally. While it works, it sends a
keep-alive request to the remote session at an interval of one third of
`session_ttl`, so a long download does not let the remote session expire. On
The client downloads, decrypts, and muxes locally. While it works, the open
[remote session channel](#the-remote-session-channel) keeps the remote session alive,
so a long download does not let the remote session expire. On
completion, and also when `dl` exits early (`--list`, Ctrl+C, an error), it
deletes the remote session. If the login belongs to the client, the `DELETE`
request returns the updated cache files (for example a refreshed token) and the
@@ -340,8 +339,9 @@ the wire:
- **CDM calls.** When the service calls the CDM, the server sends a `cdm_call` to the client
and waits. The client makes the challenge, or parses the licence, on its own CDM. When
the service closes a CDM session, the server sends a `close` call, because a CDM holds
only a few sessions. The client polls for calls during login and while one of its own
requests runs service code, so an idle remote session sends nothing extra.
only a few sessions. The server sends each call on the remote session channel. Without
the channel, the client polls for calls during login and while one of its own requests
runs service code, so an idle remote session sends nothing extra.
- **Session keys only.** A `keys` call returns Widevine `OPERATOR_SESSION` and `SIGNING`
keys. It never returns a content key, and the client refuses a PlayReady `keys` call.
So a server cannot use your device to license titles for itself.
@@ -380,7 +380,7 @@ generally never touch this directly, but it explains behaviour you might observe
| Behavior | Value | Notes |
|---|---|---|
| Idle session TTL | **300s** (5 min) default | Refreshed on every request to the session and when a `titles` or `tracks` request ends. A remote session does not expire while a request works on it |
| Idle session TTL | **300s** (5 min) default | Refreshed on every request to the session and when a `titles` or `tracks` request ends. A remote session does not expire while a request works on it or while its remote session channel is open |
| Max concurrent sessions | **100** default | When full, the least recently used remote session of the API key that holds the most is evicted. A remote session that a request works on goes last |
| Auth/input timeout | **600s** (10 min) | Sessions still authenticating or awaiting a prompt use this longer window instead of the TTL |
| Cleanup sweep | every 60s | Expired sessions are removed and their input prompts cancelled |
@@ -462,9 +462,10 @@ The server mounts all these routes, even in `--remote-only` mode. Paths use the
| `POST` | `/api/session/{id}/samples` | Decrypt the cbcs samples of a track the service decrypts itself |
| `POST` | `/api/session/{id}/license` | DRM licensing (proxy or server CDM) |
| `POST` | `/api/session/{id}/keys/bad` | Report a server-vault content key that did not decrypt |
| `GET` | `/api/session/{id}/logs` | Drain the service's server-side log output |
| `GET` | `/api/session/{id}/prompt` | Poll interactive auth status / pending prompt |
| `POST` | `/api/session/{id}/prompt` | Submit an answer to a pending prompt |
| `GET` | `/api/session/{id}/channel` | WebSocket of the [remote session channel](#the-remote-session-channel): the messages the server starts, and the client's answers; `?since=` is the last log `seq` the client has |
| `GET` | `/api/session/{id}/logs` | Drain the service's server-side log output (polling fallback) |
| `GET` | `/api/session/{id}/prompt` | Poll interactive auth status / pending prompt (polling fallback) |
| `POST` | `/api/session/{id}/prompt` | Submit an answer to a pending prompt (polling fallback) |
| `GET` | `/api/session/{id}` | Session info (validity, TTL, counts) |
| `DELETE` | `/api/session/{id}` | Close the remote session, return updated cache, clean up |
@@ -515,8 +516,9 @@ licenses. `server_device` tells it that the service runs on the server's device,
content key comes from a vault.
Authentication runs on a background thread (`asyncio.to_thread(authenticate, ...)`).
The remote session starts in `AUTHENTICATING`. The client must poll the prompt
endpoint until it reaches `authenticated` (or `failed`).
The remote session starts in `AUTHENTICATING`. The client opens the remote session
channel and waits on it until the login state is `authenticated` (or `failed`). A client
without the channel polls the prompt endpoint for that state.
### Interactive auth: the `InputBridge`
@@ -528,11 +530,11 @@ layer.
- `InputBridge.request_input(prompt, timeout=600)` blocks the sync auth thread on a
`threading.Event` until `submit_response()` or `cancel()` fires.
- A timeout raises `TimeoutError` and marks the remote session `FAILED`.
- A prompt after authentication (in `get_titles()`, `get_tracks()` or licensing) raises
`RuntimeError` at once. The client polls for prompts only during authentication, so
no answer can come.
- A prompt after authentication (in `get_titles()`, `get_tracks()` or licensing) goes to
the client on an open remote session channel. Without the channel it raises `RuntimeError`
at once: the client polls for prompts only during authentication, so no answer can come.
- A CDM call (`InputBridge.request_cdm`) works during and after authentication, because the
client also polls while its own requests run. A call that no client fetches within 10 seconds
channel carries it, or the client polls while its own requests run. A call that no client fetches within 10 seconds
fails then, because no client is listening. A fetched call waits 60 seconds for its answer.
The call leaves the auth status as it was. An answer never marks the remote session as client-authenticated.
- `AUTH_INPUT_TIMEOUT = 600.0` seconds. This is also the TTL granted to
@@ -560,6 +562,40 @@ A missing remote session returns `404 SESSION_NOT_FOUND`. An IP mismatch returns
returns `{ "status": "accepted" }`. A post with no pending prompt is an
`INVALID_INPUT` error.
### The remote session channel
`GET /api/session/{id}/channel` is a WebSocket that carries only the messages the server
starts. Titles, tracks, licences, samples, the segment filter, bad content key reports, create
and delete stay HTTP requests. The route takes the same API key and ownership checks as the
other remote session routes.
Each message is a JSON text frame with a `type` field:
| `type` | From | Fields | Meaning |
|---|---|---|---|
| `prompt` | server | `id`, `prompt` | The service asks the user for input |
| `cdm_call` | server | `id`, `call` | The service calls the client's CDM; `call` has the shape of the prompt route's `cdm_call` |
| `log` | server | `seq`, `level`, `message`, `ts` | One record of the service log, with the same redaction as `GET /logs` |
| `status` | server | `status`, `error` | The login state, as the `status` of `GET /prompt` |
| `drain` | server | `draining` | The operator started or stopped a drain before a restart |
| `answer` | client | `id`, `response`, `error` | The answer to the `prompt` or `cdm_call` with this `id`; `error` says why the client cannot answer a prompt, and the service stops at once |
When the client connects, the server first sends the log records after `since`, the drain
state, the prompts and CDM calls that the client did not answer, and the login state. A log
record can arrive twice, after a reconnect; the client skips a `seq` it already has. Each
prompt and CDM call goes to one path only: the channel, or the prompt routes.
The server closes the channel with code `4404` when the remote session ends: a delete, an
expiry, an eviction, or a server shutdown. The client then stops reconnecting, and its next
request finds the remote session gone.
The client polls the prompt and logs routes, and sends keep-alive requests, in these cases:
- A gateway in front of the server refuses the WebSocket upgrade, or the connection fails, when
the client creates the remote session. The client polls for the life of the process and logs
the refusal at debug level only.
- The channel drops. The client polls until it reconnects, with a backoff from 1 to 30 seconds.
### `SessionStore` internals
Source: `unshackle/core/api/session_store.py`. A singleton you get from
@@ -646,8 +682,9 @@ existing file as a directory, and logs a warning.
}
```
`draining` is `true` after the operator starts a drain before a restart. The client reads
it before each title, so it knows of the restart before it occurs.
`draining` is `true` after the operator starts a drain before a restart. The client checks
it before each title, so it knows of the restart before it occurs. With an open remote session
channel the client reads the `drain` message and sends no request.
!!! warning "`expires_in` is the configured TTL, not time remaining"
The `expires_in` value reports the store's configured `session_ttl`, not the
@@ -675,8 +712,8 @@ the error codes and the request and reply shapes that it shares with the server
output cannot start before the body is ready.
- **Retries.** The download-side HTTP session mounts an adapter with
`Retry(total=5, backoff_factor=0.2, status_forcelist=[429, 500, 502, 503, 504])`.
- **Flow.** `authenticate()` → `create` (+ poll `prompt` every 2s up to a 600s
deadline, answering `pending_input` prompts. With stdin closed the client logs an
- **Flow.** `authenticate()` → `create` (+ open the remote session channel, or poll `prompt`
every 2s without it, up to a 600s deadline, answering `pending_input` prompts. With stdin closed the client logs an
error and raises `SystemExit(1)` instead of posting an empty answer) → `get_titles()` → `get_tracks()`
(merging returned `session_headers`/`session_cookie_jar`, re-parsing `manifests`) →
get the licence in proxy mode or `server_cdm` mode → `close()` (`DELETE`, saving any returned
+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
+17
View File
@@ -28,6 +28,7 @@ from unshackle.core.api.errors import APIError, categorize_exception, handle_api
from unshackle.core.api.input_bridge import InputBridge, NoUserBridge
from unshackle.core.api.progress import track_log_label
from unshackle.core.api.sanitize import MAX_SESSION_CACHE_KEYS, safe_cache_key, safe_cache_payload, sanitize_log
from unshackle.core.api.session_channel import status_message
from unshackle.core.api.session_log import SessionLogBuffer, SessionLogMirror, capture_service_logs
from unshackle.core.api.session_store import SessionStore
from unshackle.core.binaries import binary_version
@@ -535,6 +536,7 @@ def setup_remote_service(
raise
finally:
_remote_logins.pop(login.id, None)
service_instance._input_bridge = NoUserBridge() # nobody can answer a prompt once the login is gone
return service_instance
@@ -3657,6 +3659,9 @@ async def session_create_handler(data: Dict[str, Any], request: Optional[web.Req
session.input_bridge = bridge
session.log_buffer = log_buffer
session.auth_status = AuthStatus.AUTHENTICATING
bridge.channel = session.channel
if log_buffer:
log_buffer.listener = session.channel.log
async def run_auth() -> None:
try:
@@ -3671,6 +3676,7 @@ async def session_create_handler(data: Dict[str, Any], request: Optional[web.Req
session.auth_error = redact_secrets(str(e))
bridge.status = AuthStatus.FAILED
finally:
session.channel.send(status_message(session))
if store.peek(session_id) is not session:
SessionStore.cleanup_cache_dir(session_cache_tag)
@@ -5454,6 +5460,17 @@ async def session_delete_handler(session_id: str, request: Optional[web.Request]
return web.json_response(response)
async def session_channel_handler(session_id: str, request: web.Request) -> web.StreamResponse:
"""Attach the caller's session channel, which carries the messages the server starts for the remote session."""
from unshackle.core.api.session_store import get_session_store
session = await get_validated_session(session_id, request)
ws = web.WebSocketResponse(heartbeat=HEARTBEAT)
await ws.prepare(request) # a request that is not a WebSocket upgrade fails here
await session.channel.serve(ws, session, _since(request), get_session_store().draining)
return ws
def shared_key_client(request: web.Request) -> Optional[str]:
"""The person behind a ``shared: true`` API key, from the ``X-Client-Id`` its gateway sets; None for other keys.
+142 -86
View File
@@ -1,21 +1,24 @@
"""Thread-safe bridge for interactive input during remote authentication.
"""Thread-safe bridge for the prompts and CDM calls that service code on the server sends to the remote client.
When a service calls ``request_input()`` during ``authenticate()`` on the
server, the InputBridge pauses the auth thread and exposes the prompt to
the HTTP layer so a remote client can poll for it, collect the user's
response, and submit it back. The auth thread then resumes with the
response value.
When a service calls ``request_input()`` or its client-device CDM makes a call, the InputBridge blocks the
service thread on an *ask* until the remote client answers it. The remote session channel carries an ask when one is
attached; otherwise the prompt routes serve it, one at a time. Each ask belongs to the path that carried it
first, and only that path can answer it.
"""
from __future__ import annotations
import json
import threading
import uuid
from dataclasses import dataclass, field
from typing import Any, Optional
from typing import TYPE_CHECKING, Any, Optional
from unshackle.core.remote_protocol import AuthStatus
if TYPE_CHECKING:
from unshackle.core.api.session_channel import SessionChannel
# Seconds the server waits for a remote client to answer an input prompt before
# giving up; also the TTL SessionStore grants AUTHENTICATING/PENDING_INPUT sessions.
AUTH_INPUT_TIMEOUT = 600.0
@@ -27,63 +30,81 @@ CDM_CALL_FALLBACK_PROMPT = (
"This service needs your local CDM during login, and your unshackle cannot answer it. Update unshackle"
)
CHANNEL = "channel"
POLL = "poll"
@dataclass(eq=False)
class Ask:
"""One prompt or CDM call that service code waits on."""
id: str
prompt: str
cdm_call: Optional[dict[str, Any]] = None
owner: Optional[str] = None # CHANNEL or POLL: the path that carried the ask, and the only one that answers it
response: Optional[str] = None
error: Optional[str] = None # the client could not answer, and says why
picked_up: threading.Event = field(default_factory=threading.Event)
answered: threading.Event = field(default_factory=threading.Event)
@dataclass
class InputBridge:
"""Thread-safe bridge between a sync auth thread and the async HTTP layer.
"""Thread-safe bridge between the service threads and the async HTTP layer.
The auth thread calls :meth:`request_input` which blocks until the
remote client submits a response through the HTTP prompt endpoints.
A service thread calls :meth:`request_input` or :meth:`request_cdm`, which block until the remote client
answers through the remote session channel or the prompt routes.
"""
_prompt: Optional[str] = field(default=None, init=False, repr=False)
_response: Optional[str] = field(default=None, init=False, repr=False)
channel: Optional[SessionChannel] = field(default=None, init=False, repr=False)
_asks: dict[str, Ask] = field(default_factory=dict, init=False, repr=False)
_status: AuthStatus = field(default=AuthStatus.AUTHENTICATING, init=False)
_cancelled: bool = field(default=False, init=False, repr=False)
_cdm_call: Optional[dict[str, Any]] = field(default=None, init=False, repr=False)
_response_ready: threading.Event = field(default_factory=threading.Event, init=False, repr=False)
_picked_up: threading.Event = field(default_factory=threading.Event, init=False, repr=False)
_lock: threading.Lock = field(default_factory=threading.Lock, init=False, repr=False)
def _open(self, prompt: str, cdm_call: Optional[dict[str, Any]] = None) -> Ask:
"""Register an ask and offer it to the attached channel; call it with the lock held."""
if self._cancelled:
raise RuntimeError("Session was cancelled")
ask = Ask(uuid.uuid4().hex, prompt, cdm_call)
if self.channel is not None and self.channel.offer(ask):
ask.owner = CHANNEL
ask.picked_up.set()
self._asks[ask.id] = ask
return ask
def request_input(self, prompt: str, timeout: float = AUTH_INPUT_TIMEOUT) -> str:
"""Block until the remote client submits a response for *prompt*.
Args:
prompt: The message to display to the remote user.
timeout: Maximum seconds to wait for a response.
Returns:
The string response from the remote client.
After authentication only an attached session channel can carry a prompt, as a polling client stops
asking for prompts once it is logged in.
Raises:
TimeoutError: If the bridge gets no response within *timeout*.
RuntimeError: If the server cancelled the bridge, or authentication is complete.
RuntimeError: If the server cancelled the bridge, or authentication is complete and no channel is attached.
"""
with self._lock:
if self._cancelled:
raise RuntimeError("Session was cancelled")
if self._status == AuthStatus.AUTHENTICATED:
if self._status == AuthStatus.AUTHENTICATED and not (self.channel and self.channel.attached):
if self._cancelled:
raise RuntimeError("Session was cancelled")
raise RuntimeError(f"Remote mode cannot relay a prompt after authentication: {prompt}")
self._prompt = prompt
self._response = None
self._status = AuthStatus.PENDING_INPUT
self._response_ready.clear()
# cancel() and submit_response() both .set() the event, so a single wait
# returns on signal-or-cancel; no poll loop needed.
if not self._response_ready.wait(timeout=timeout):
ask = self._open(prompt)
try:
# cancel() and an answer both set the event, so a single wait returns on signal-or-cancel
if not ask.answered.wait(timeout=timeout):
with self._lock:
if self._status != AuthStatus.AUTHENTICATED:
self._status = AuthStatus.FAILED
raise TimeoutError(f"No client response for prompt within {timeout}s")
with self._lock:
self._status = AuthStatus.FAILED
raise TimeoutError(f"No client response for prompt within {timeout}s")
with self._lock:
if self._cancelled:
raise RuntimeError("Session was cancelled")
response = self._response or ""
self._prompt = None
self._response = None
self._status = AuthStatus.AUTHENTICATING
return response
if self._cancelled:
raise RuntimeError("Session was cancelled")
if ask.error is not None:
raise RuntimeError(f"The client could not answer the prompt: {ask.error}")
return ask.response or ""
finally:
with self._lock:
self._asks.pop(ask.id, None)
def request_cdm(
self, call: dict[str, Any], timeout: float = CDM_CALL_TIMEOUT, pickup: float = CDM_PICKUP_TIMEOUT
@@ -95,25 +116,16 @@ class InputBridge:
service thread for seconds, not for the full ``timeout``.
"""
with self._lock:
if self._cancelled:
raise RuntimeError("Session was cancelled")
previous = self._status
self._prompt = CDM_CALL_FALLBACK_PROMPT
self._cdm_call = call
self._response = None
self._status = AuthStatus.PENDING_INPUT
self._response_ready.clear()
self._picked_up.clear()
picked_up = self._picked_up.wait(timeout=pickup)
answered = picked_up and self._response_ready.wait(timeout=timeout)
with self._lock:
answer = self._response
self._prompt = self._response = self._cdm_call = None
cancelled = self._cancelled
if not cancelled:
self._status = previous
ask = self._open(CDM_CALL_FALLBACK_PROMPT, call)
try:
picked_up = ask.picked_up.wait(timeout=pickup)
answered = picked_up and ask.answered.wait(timeout=timeout)
with self._lock:
answer = ask.response
cancelled = self._cancelled
finally:
with self._lock:
self._asks.pop(ask.id, None)
if cancelled:
raise RuntimeError("Session was cancelled")
if not picked_up:
@@ -130,51 +142,92 @@ class InputBridge:
raise RuntimeError(f"The client's CDM refused the call: {result['error']}")
return result
def _pollable(self) -> list[Ask]:
"""The asks the prompt routes can serve: unanswered, and not carried by the channel; call it under the lock.
An answered ask stops being pending at once, before the waiting thread wakes, so a client that polls again
straight away never sees it twice.
"""
return [a for a in self._asks.values() if not a.answered.is_set() and a.owner != CHANNEL]
def get_pending_cdm_call(self) -> Optional[dict[str, Any]]:
"""Return the CDM call that service code waits on, if any, and mark it as fetched by a client."""
with self._lock:
if self._awaiting_answer() and self._cdm_call is not None:
self._picked_up.set()
return self._cdm_call
return None
ask = next((a for a in self._pollable() if a.cdm_call is not None), None)
if ask is None:
return None
ask.owner = POLL
ask.picked_up.set()
return ask.cdm_call
def get_pending_prompt(self) -> Optional[str]:
"""Return the current prompt when the auth thread waits for input."""
"""Return the prompt of the first ask the prompt routes can serve, and keep that ask on them."""
with self._lock:
if self._awaiting_answer():
return self._prompt
return None
ask = next(iter(self._pollable()), None)
if ask is None:
return None
ask.owner = POLL
return ask.prompt
def submit_response(self, response: str) -> bool:
"""Deliver the client's response and unblock the auth thread.
"""Answer the oldest ask that the prompt routes served, else the oldest one they can serve.
Returns:
``True`` if a prompt was pending and the bridge accepted the response,
``False`` otherwise.
``True`` if an ask was pending and the bridge accepted the response, ``False`` otherwise.
"""
with self._lock:
if not self._awaiting_answer():
pending = self._pollable()
ask = next((a for a in pending if a.owner == POLL), pending[0] if pending else None)
if ask is None:
return False
self._response = response
self._picked_up.set()
self._response_ready.set()
self._answer(ask, response)
return True
def _awaiting_answer(self) -> bool:
"""True while a prompt or CDM call waits and no answer has arrived; call it under the lock.
def answer(self, ask_id: str, response: str, error: Optional[str] = None) -> bool:
"""Answer the ask with this id that the remote session channel carried; False when no such ask waits."""
with self._lock:
ask = self._asks.get(ask_id)
if ask is None or ask.owner != CHANNEL or ask.answered.is_set():
return False
ask.error = error
self._answer(ask, response)
return True
An answered call stops being pending at once, before the waiting thread wakes, so a client
that polls again straight away never sees it twice.
@staticmethod
def _answer(ask: Ask, response: str) -> None:
ask.response = response
ask.picked_up.set()
ask.answered.set()
def claim_for_channel(self) -> list[Ask]:
"""Give every unanswered ask that the prompt routes did not serve to a newly attached session channel."""
with self._lock:
asks = [a for a in self._asks.values() if not a.answered.is_set() and a.owner != POLL]
for ask in asks:
ask.owner = CHANNEL
ask.picked_up.set()
return asks
def release_channel_asks(self) -> None:
"""Hand the unanswered asks of a detached channel back to the prompt routes, so none waits on a dead socket.
A prompt after login stays with the channel, as a polling client asks for prompts only while it logs in.
"""
return self._status == AuthStatus.PENDING_INPUT and not self._response_ready.is_set()
with self._lock:
for ask in self._asks.values():
pollable = ask.cdm_call is not None or self._status != AuthStatus.AUTHENTICATED
if ask.owner == CHANNEL and pollable and not ask.answered.is_set():
ask.owner = None
def cancel(self) -> None:
"""Cancel the bridge, unblocking any waiting auth thread."""
"""Cancel the bridge, unblocking any waiting service thread."""
with self._lock:
self._cancelled = True
self._status = AuthStatus.FAILED
self._picked_up.set()
self._response_ready.set()
asks = list(self._asks.values())
for ask in asks:
ask.picked_up.set()
ask.answered.set()
def ensure_active(self) -> None:
"""Raise RuntimeError once the server cancelled the bridge, so a login loop stops."""
@@ -184,7 +237,10 @@ class InputBridge:
@property
def status(self) -> AuthStatus:
"""``pending_input`` while an ask waits for its answer, else the login state."""
with self._lock:
if self._status != AuthStatus.FAILED and any(not a.answered.is_set() for a in self._asks.values()):
return AuthStatus.PENDING_INPUT
return self._status
@status.setter
+42
View File
@@ -59,6 +59,7 @@ from unshackle.core.api.handlers import (
server_accounts_allowed,
server_config_handler,
session_bad_key_handler,
session_channel_handler,
session_create_handler,
session_delete_handler,
session_info_handler,
@@ -75,9 +76,11 @@ from unshackle.core.api.handlers import (
tunnel_handler,
)
from unshackle.core.api.sanitize import sanitize_log
from unshackle.core.api.session_channel import close_channels
from unshackle.core.drm import cbcs
from unshackle.core.remote_protocol import (
BAD_KEY_ROUTE,
CHANNEL_ROUTE,
HEALTH_ROUTE,
LICENSE_ROUTE,
LOGS_ROUTE,
@@ -2537,6 +2540,43 @@ async def session_delete(request: web.Request) -> web.Response:
return await session_delete_handler(session_id, request)
@api_handler
async def session_channel(request: web.Request) -> web.StreamResponse:
"""
Open the remote session channel.
---
summary: Open session channel
description: >-
A WebSocket that a --remote client holds open for its remote session. The server sends each message it
starts as a JSON text frame with a type field - prompt and cdm_call (each with an id), log, status, and drain
(with draining true or false).
The client answers a prompt or a CDM call with {"type": "answer", "id": <id>, "response": <text>}.
On attach the server first sends the log records after since, the drain state, the waiting prompts and
CDM calls, then the login state. The remote session does not expire while the channel is open. When the
server removes the remote session, it closes the channel with code 4404.
parameters:
- name: session_id
in: path
required: true
schema:
type: string
- name: since
in: query
required: false
description: Send the log records after this sequence number first (default - 0)
schema:
type: integer
responses:
'101':
description: WebSocket open
'403':
description: The remote session belongs to another API key
'404':
description: Remote session not found
"""
return await session_channel_handler(request.match_info["session_id"], request)
@api_handler
async def session_prompt_get(request: web.Request) -> web.Response:
"""
@@ -3450,6 +3490,7 @@ ROUTES: list[tuple[str, str, Handler, bool]] = [
("GET", LOGS_ROUTE, session_logs, True),
("GET", PROMPT_ROUTE, session_prompt_get, True),
("POST", PROMPT_ROUTE, session_prompt_submit, True),
("GET", CHANNEL_ROUTE, session_channel, True),
("GET", SESSION_ROUTE, session_info, True),
("DELETE", SESSION_ROUTE, session_delete, True),
]
@@ -3494,6 +3535,7 @@ def setup_routes(
add[method](path, handler)
app.on_response_prepare.append(generic_server_header)
app.on_shutdown.append(close_tunnels)
app.on_shutdown.append(close_channels)
async def generic_server_header(request: web.Request, response: web.StreamResponse) -> None:
+180
View File
@@ -0,0 +1,180 @@
"""The messages a remote session's server starts, and the session channel that carries them to the client.
Service threads (prompts and CDM calls in the input bridge, the session log mirror), the drain and the session
store hand each message to the remote session's :class:`SessionChannel`. While the client holds the channel's
WebSocket open, the channel sends the message at once. Otherwise the message waits where the polling routes read
it (the input bridge, the log buffer of the remote session, the drain flag), as for a client without the channel.
"""
from __future__ import annotations
import asyncio
import json
from typing import TYPE_CHECKING, Any, Optional, Union, cast
from aiohttp import WSMsgType, web
from unshackle.core.api.sanitize import sanitize_log
from unshackle.core.remote_protocol import (
CHANNEL_SESSION_GONE,
ChannelAnswer,
ChannelCdmCall,
ChannelDrain,
ChannelLog,
ChannelMessage,
ChannelPrompt,
ChannelStatus,
LogRecord,
)
from unshackle.core.tunnel import HEARTBEAT
if TYPE_CHECKING:
from unshackle.core.api.input_bridge import Ask
from unshackle.core.api.session_store import SessionEntry
Message = Union[ChannelPrompt, ChannelCdmCall, ChannelLog, ChannelStatus, ChannelDrain]
GONE = object()
def drain_message(draining: bool) -> ChannelDrain:
return ChannelDrain(type=ChannelMessage.DRAIN, draining=draining)
def status_message(session: SessionEntry) -> ChannelStatus:
"""The login state of the remote session, with the same redacted error that the prompt route gives."""
message = ChannelStatus(type=ChannelMessage.STATUS, status=session.auth_status.value)
if session.auth_error:
message["error"] = session.auth_error
return message
class SessionChannel:
"""The WebSocket of one remote session, while the client holds it open.
Any thread can hand a message to :meth:`send`: it goes to the event loop through ``call_soon_threadsafe``,
and one writer task sends the messages in order. Nothing here takes a lock or waits on a worker.
"""
def __init__(self) -> None:
self.ws: Optional[web.WebSocketResponse] = None
self.queue: Optional[asyncio.Queue[Any]] = None
self.loop: Optional[asyncio.AbstractEventLoop] = None
self.ended = False
@property
def attached(self) -> bool:
return self.ws is not None
def send(self, message: Any) -> bool:
"""Queue *message* for the attached WebSocket, from any thread; False when no WebSocket is attached."""
loop, queue = self.loop, self.queue
if loop is None or queue is None:
return False
try:
loop.call_soon_threadsafe(queue.put_nowait, message)
except RuntimeError: # the loop closed at server shutdown
return False
return True
def offer(self, ask: Ask) -> bool:
"""Send a prompt or CDM call that service code waits on; False when the polling routes must serve it."""
return self.send(ask_message(ask))
def log(self, record: LogRecord) -> None:
"""Send one record of the service log mirror; the buffer keeps it for the logs route too."""
if self.queue is not None:
self.send(log_message(record))
def end(self) -> None:
"""Close the channel for good, with the close code that tells the client the remote session is gone."""
self.ended = True
self.send(GONE)
async def serve(self, ws: web.WebSocketResponse, session: SessionEntry, since: int, draining: bool) -> None:
"""Attach *ws* until the client or the server closes it.
The client first gets what it missed: the log records after *since*, a drain notice, the prompts and CDM
calls the polling routes did not serve, then the login state. A log record can come twice; its ``seq``
tells the client.
"""
if self.ended:
await ws.close(code=CHANNEL_SESSION_GONE, message=b"session closed")
return
previous = self.ws
queue: asyncio.Queue[Any] = asyncio.Queue()
self.loop, self.ws, self.queue = asyncio.get_running_loop(), ws, queue
backlog: list[Any] = []
if session.log_buffer is not None:
backlog += [log_message(r) for r in session.log_buffer.since(since)]
backlog.append(drain_message(draining))
bridge = session.input_bridge
backlog += [ask_message(ask) for ask in (bridge.claim_for_channel() if bridge else [])]
backlog.append(status_message(session))
for message in backlog:
queue.put_nowait(message)
writer = asyncio.create_task(self.write(ws, queue, session))
try:
if previous is not None:
await previous.close()
async for msg in ws:
if msg.type == WSMsgType.TEXT and bridge is not None:
receive(msg.data, bridge)
finally:
writer.cancel()
if self.ws is ws:
self.ws = self.queue = None
if bridge is not None:
bridge.release_channel_asks()
session.touch()
@staticmethod
async def write(ws: web.WebSocketResponse, queue: asyncio.Queue[Any], session: SessionEntry) -> None:
"""Send the queued messages in order; the idle timer moves while the channel is open, for the dashboard."""
try:
while True:
try:
message = await asyncio.wait_for(queue.get(), HEARTBEAT)
except asyncio.TimeoutError:
session.touch()
continue
if message is GONE:
await ws.close(code=CHANNEL_SESSION_GONE, message=b"session closed")
return
await ws.send_json(message)
session.touch()
except Exception: # a writer that cannot send closes the socket, so the session does not stay attached
await ws.close()
def log_message(record: LogRecord) -> ChannelLog:
return cast(ChannelLog, {"type": ChannelMessage.LOG, **record})
def ask_message(ask: Ask) -> Union[ChannelPrompt, ChannelCdmCall]:
if ask.cdm_call is not None:
return ChannelCdmCall(type=ChannelMessage.CDM_CALL, id=ask.id, call=ask.cdm_call)
return ChannelPrompt(type=ChannelMessage.PROMPT, id=ask.id, prompt=ask.prompt)
def receive(text: str, bridge: Any) -> None:
"""Hand the client's answer to the ask it names; any other message is ignored."""
try:
data: ChannelAnswer = json.loads(text)
except ValueError:
return
if (
isinstance(data, dict)
and data.get("type") == ChannelMessage.ANSWER
and isinstance(data.get("id"), str)
and isinstance(data.get("response"), str)
):
error = data.get("error")
bridge.answer(data["id"], data["response"], sanitize_log(error)[:500] if isinstance(error, str) else None)
async def close_channels(_: web.Application) -> None:
"""End every attached channel at server shutdown, so no WebSocket holds the shutdown open."""
from unshackle.core.api.session_store import get_session_store
for entry in get_session_store().list():
entry.channel.end()
+14 -9
View File
@@ -18,7 +18,7 @@ import threading
import time
import traceback
from collections import deque
from typing import Any, Deque, List, MutableMapping, Optional, Tuple
from typing import Any, Callable, Deque, List, MutableMapping, Optional, Tuple
from unshackle.core.api.sanitize import sanitize_log
from unshackle.core.remote_protocol import LogRecord
@@ -28,24 +28,29 @@ MAX_MESSAGE_LEN = 2000
class SessionLogBuffer:
"""Thread-safe bounded buffer of log records with a monotonic sequence."""
"""Thread-safe bounded buffer of log records with a monotonic sequence.
``listener`` gets each new record under the lock, so records reach it in sequence order; it must not block.
"""
def __init__(self, maxlen: int = MAX_RECORDS) -> None:
self._records: Deque[LogRecord] = deque(maxlen=maxlen)
self._seq = 0
self._lock = threading.Lock()
self.listener: Optional[Callable[[LogRecord], None]] = None
def append(self, level: int, message: str) -> None:
with self._lock:
self._seq += 1
self._records.append(
LogRecord(
seq=self._seq,
level=logging.getLevelName(level),
message=sanitize_log(message)[:MAX_MESSAGE_LEN],
ts=time.time(),
)
record = LogRecord(
seq=self._seq,
level=logging.getLevelName(level),
message=sanitize_log(message)[:MAX_MESSAGE_LEN],
ts=time.time(),
)
self._records.append(record)
if self.listener is not None:
self.listener(record)
def since(self, seq: int) -> List[LogRecord]:
"""Records with a sequence number greater than *seq*, oldest first."""
+21 -13
View File
@@ -19,6 +19,7 @@ from typing import Any, Deque, Dict, List, Optional
from unshackle.core.api.events import bus
from unshackle.core.api.input_bridge import AUTH_INPUT_TIMEOUT, InputBridge
from unshackle.core.api.sanitize import sanitize_log
from unshackle.core.api.session_channel import SessionChannel, drain_message
from unshackle.core.config import config
from unshackle.core.remote_protocol import AuthStatus
from unshackle.core.tracks import Track
@@ -57,6 +58,7 @@ class SessionEntry:
user_config: Optional[Dict[str, Any]] = None # the serve.users entry the session was created with
input_bridge: Optional[InputBridge] = None
log_buffer: Optional[Any] = None # SessionLogBuffer mirroring the service's self.log
channel: SessionChannel = field(default_factory=SessionChannel, repr=False, compare=False)
auth_status: AuthStatus = AuthStatus.AUTHENTICATED
auth_error: Optional[str] = None
client: Dict[str, Any] = field(default_factory=dict) # version/argv/platform the client reported
@@ -70,12 +72,18 @@ class SessionEntry:
@property
def in_use(self) -> bool:
"""True while a request holds the lock for service work; the store does not expire such a remote session.
"""True while a request holds the lock for service work, or the client holds its remote session channel open.
A request can run for longer than the TTL, and expiry would remove the cache directory
that the worker thread still writes to.
The store does not expire such a remote session. A request can run for longer than the TTL, and expiry
would remove the cache directory that the worker thread still writes to.
"""
return self.lock.locked()
return self.lock.locked() or self.channel.attached
def end(self) -> None:
"""Unblock the service threads that wait on the client, and close the remote session channel."""
if self.input_bridge:
self.input_bridge.cancel()
self.channel.end()
def summary(self, include_actions: bool = True) -> Dict[str, Any]:
"""Dashboard view of the session: no service instance, no raw owner key."""
@@ -177,8 +185,7 @@ class SessionStore:
)
log.warning(f"Max sessions reached ({max_sessions}), evicting oldest of the busiest key: {oldest_id}")
evicted = self._sessions.pop(oldest_id)
if evicted.input_bridge:
evicted.input_bridge.cancel()
evicted.end()
evicted_tag = evicted.cache_tag
_publish("delete", evicted, "evicted")
_schedule_pending_reload(evicted.service_tag)
@@ -211,6 +218,7 @@ class SessionStore:
if elapsed > self.ttl:
log.info(f"Session {sanitize_log(session_id)} expired (elapsed={elapsed:.0f}s, ttl={self.ttl}s)")
_publish("delete", self._sessions.pop(session_id), "expired")
entry.end()
_schedule_pending_reload(entry.service_tag)
expired = True
if not expired:
@@ -233,8 +241,7 @@ class SessionStore:
entry = self._sessions.pop(session_id, None)
if not entry:
return False
if entry.input_bridge:
entry.input_bridge.cancel()
entry.end()
_publish("delete", entry, "closed")
log.info(f"Deleted session {sanitize_log(session_id)}")
_schedule_pending_reload(entry.service_tag)
@@ -259,8 +266,7 @@ class SessionStore:
cache_tags: list[Optional[str]] = []
for sid in expired:
entry = self._sessions.pop(sid)
if entry.input_bridge:
entry.input_bridge.cancel()
entry.end()
cache_tags.append(entry.cache_tag)
_publish("delete", entry, "expired")
ended_tags.add(entry.service_tag)
@@ -294,11 +300,10 @@ class SessionStore:
self._cleanup_task = None
async def cancel_all_bridges(self) -> None:
"""Cancel all active input bridges (called on server shutdown)."""
"""Cancel all active input bridges and close every remote session channel (called on server shutdown)."""
async with self._lock:
for entry in self._sessions.values():
if entry.input_bridge:
entry.input_bridge.cancel()
entry.end()
count = len(self._sessions)
if count:
log.info(f"Cancelled bridges for {count} active session(s)")
@@ -357,11 +362,14 @@ class SessionStore:
for entry in self._sessions.values():
if entry.log_buffer is not None:
entry.log_buffer.append(logging.WARNING, DRAIN_WARNING)
entry.channel.send(drain_message(True))
def stop_drain(self) -> None:
if self.draining:
self.draining = False
log.warning("Drain cancelled: new sessions and jobs are accepted again")
for entry in self._sessions.values():
entry.channel.send(drain_message(False))
@property
def session_count(self) -> int:
+490
View File
@@ -0,0 +1,490 @@
"""The messages a remote server starts for a remote session, on the client.
The server starts some messages itself: a login prompt, a call on this machine's CDM, a service log record, a
login state change and a drain notice. :func:`open_channel` gives :class:`RemoteService` one of two adapters with
the same methods. :class:`WebSocketChannel` gets the messages on the remote session channel. :class:`PollingChannel` asks
the server for them, when the channel upgrade is refused or fails, and while the channel is down.
"""
from __future__ import annotations
import asyncio
import contextlib
import json
import logging
import time
from collections import deque
from threading import Event, Lock, Thread
from typing import TYPE_CHECKING, Any, Callable, ContextManager, Dict, Iterator, Optional, Union, cast
import aiohttp
import requests
from aiohttp import WSMsgType
from unshackle.core.console import prompt_user, show_notice
from unshackle.core.remote_protocol import (
CHANNEL_ROUTE,
CHANNEL_SESSION_GONE,
LOGS_ROUTE,
PROMPT_ROUTE,
SAMPLES_ROUTE,
SESSION_ROUTE,
AuthStatus,
ChannelAnswer,
ChannelMessage,
ClientErrorKind,
LogRecord,
LogsReply,
PromptAnswer,
PromptReply,
SessionInfo,
)
from unshackle.core.remote_service import RemoteError, quiet, ws_headers
from unshackle.core.tunnel import HEARTBEAT, retry_after
if TYPE_CHECKING:
from unshackle.core.remote_service import RemoteService
log = logging.getLogger("remote_channel")
AUTH_TIMEOUT = 600.0
AUTH_POLL_INTERVAL = 2.0
CDM_POLL_INTERVAL = 0.5
KEEPALIVE_MIN_INTERVAL = 5.0
CONNECT_TIMEOUT = 10.0
RECONNECT_DELAY = 1.0
GONE_STATUSES = (401, 403, 404) # the API key or the remote session is gone, so a reconnect cannot help
SEND_TIMEOUT = 10.0
KEPT_ANSWERS = 64
LEVELS = logging.getLevelNamesMapping()
class ServerMessages:
"""What this client does with each message the server starts, whichever adapter brought it."""
def __init__(self, service: RemoteService) -> None:
self.service = service
self.log_seq = 0
self.recent_logs: deque[str] = deque(maxlen=3)
self.log_lock = Lock()
self.cdm_lock = Lock()
self.cdm_sessions: Dict[str, bytes] = {}
def route(self, route: str) -> str:
return route.format(session_id=self.service._session_id)
def show_logs(self, records: list[LogRecord]) -> None:
"""Log the service's server-side records here, each once: a record that the other path brought is skipped."""
from unshackle.core.api.sanitize import sanitize_log
with self.log_lock:
for record in records:
seq = int(record.get("seq", 0))
if seq <= self.log_seq:
continue
message = sanitize_log(record.get("message", ""), keep_lines=True)
self.service.log.log(LEVELS.get(str(record.get("level", "INFO")), logging.INFO), message)
self.recent_logs.append(message.strip())
self.log_seq = seq
def answer_cdm(self, call: Dict[str, Any]) -> Dict[str, Any]:
"""Run one of the server's CDM calls on this machine's device; both adapters share its CDM sessions."""
from unshackle.core.cdm.client_relay import answer_cdm_call
with self.cdm_lock:
answer = answer_cdm_call(self.service.local_cdm, call, self.cdm_sessions)
self.service.log.debug(
f"Answered a server CDM call: {call.get('op')} ({'refused' if 'error' in answer else 'ok'})"
)
return answer
def ask_user(self, prompt: str) -> str:
"""Ask the user the server's prompt, with control characters stripped as the server text can hold any."""
from unshackle.core.api.sanitize import sanitize_log
prompt = sanitize_log(prompt, keep_lines=True)
bridge = self.service._input_bridge
try:
return str(bridge.request_input(prompt) if bridge else prompt_user(prompt))
except EOFError:
raise RemoteError("Remote auth needs interactive input but stdin is closed", ClientErrorKind.AUTH) from None
def note_waiting(self, seen: int) -> None:
"""Show the last service log lines while the login waits on the user (a pair code, an approval link)."""
if self.log_seq == seen and self.recent_logs:
notice = "\n".join(self.recent_logs)
if notice != self.service.auth_notice:
self.service.auth_notice = notice
show_notice(notice)
def close_cdm_sessions(self) -> None:
"""Close the local CDM sessions that the server's calls opened; best effort."""
cdm = self.service.local_cdm
with self.cdm_lock:
for session_id in self.cdm_sessions.values():
with contextlib.suppress(Exception):
cdm.close(session_id)
self.cdm_sessions.clear()
def login_done(self) -> None:
self.close_cdm_sessions()
if self.service.auth_notice is not None:
self.service.auth_notice = None
show_notice(None)
class PollingChannel:
"""The fallback: the client asks the server for each message.
The client uses it when a gateway or the server refuses the channel upgrade, when the connection fails, and while
the channel is down. It goes together with the polling routes.
"""
def __init__(self, messages: ServerMessages) -> None:
self.messages = messages
self.service = messages.service
self.keepalive_stop = Event()
self.keepalive_stop.set()
self.drain_lock = Lock()
self.cdm_lock = Lock()
self.cdm_requests = 0
self.cdm_stop = Event()
self.paused: Callable[[], bool] = lambda: False
def wait_auth(self, timeout: float = AUTH_TIMEOUT, step: Optional[Callable[[], bool]] = None) -> None:
"""Poll the server until authentication completes, and answer its prompts and CDM calls.
``step`` replaces :meth:`auth_step` for an adapter that learns the login state another way.
"""
deadline = time.monotonic() + timeout
try:
while time.monotonic() < deadline:
if (step or self.auth_step)():
return
raise RemoteError("Remote authentication timed out", ClientErrorKind.AUTH)
finally:
self.messages.login_done()
def auth_step(self) -> bool:
"""Poll the login state once: True when authenticated. Answer a prompt or a CDM call, or wait one interval."""
resp = cast(PromptReply, self.service.client.get(self.messages.route(PROMPT_ROUTE)))
status = resp.get("status")
seen = self.messages.log_seq
self.drain_logs()
if status == AuthStatus.AUTHENTICATED:
return True
if status == AuthStatus.AUTHENTICATING:
self.messages.note_waiting(seen)
if status == AuthStatus.FAILED:
raise RemoteError(
f"Remote auth failed: {resp.get('error', 'Authentication failed on server')}", ClientErrorKind.AUTH
)
if status == AuthStatus.PENDING_INPUT and isinstance(resp.get("cdm_call"), dict):
self.answer(json.dumps(self.messages.answer_cdm(resp["cdm_call"])))
elif status == AuthStatus.PENDING_INPUT:
self.answer(self.messages.ask_user(resp.get("prompt") or "Enter input: "))
else:
time.sleep(AUTH_POLL_INTERVAL)
return False
def answer(self, response: str) -> None:
self.service.client.post(self.messages.route(PROMPT_ROUTE), PromptAnswer(response=response))
def keep_alive(self) -> None:
"""Send keep-alive requests so that a long download or mux operation does not outlive the server's idle TTL.
``GET /api/session/{session_id}`` refreshes the idle timer and reports the TTL, so the thread sends a request
at an interval of one third of it, until :meth:`stop_keepalive`. A client that dies stops sending requests,
so the server still expires an abandoned remote session.
"""
if not self.keepalive_stop.is_set():
return
stop = self.keepalive_stop = Event()
endpoint = self.messages.route(SESSION_ROUTE)
def ping() -> None:
info = cast(SessionInfo, self.service.client.probe(endpoint))
interval = max(float(info.get("expires_in") or 300) / 3, KEEPALIVE_MIN_INTERVAL)
while not stop.wait(interval):
self.service.client.probe(endpoint)
Thread(target=ping, name=f"{self.service.service_tag}-keepalive", daemon=True).start()
def stop_keepalive(self) -> None:
self.keepalive_stop.set()
def runs_service_code(self, endpoint: str) -> bool:
"""Whether a request to *endpoint* runs service code on the server, which can make CDM calls."""
own = {self.messages.route(route) for route in (PROMPT_ROUTE, LOGS_ROUTE, SAMPLES_ROUTE)}
return endpoint.startswith(self.messages.route(SESSION_ROUTE) + "/") and endpoint.partition("?")[0] not in own
@contextlib.contextmanager
def in_flight(self, endpoint: str) -> Iterator[None]:
"""Answer the server's CDM calls while a remote session request runs service code.
One poller serves every concurrent request, and the local CDM sessions close when the last one ends.
"""
if not self.runs_service_code(endpoint):
yield
return
with self.cdm_lock:
self.cdm_requests += 1
if self.cdm_requests == 1:
self.cdm_stop = Event()
Thread(
target=self.poll_cdm_calls,
args=(self.cdm_stop,),
name=f"{self.service.service_tag}-cdm",
daemon=True,
).start()
try:
yield
finally:
with self.cdm_lock:
self.cdm_requests -= 1
last = self.cdm_requests == 0
if last:
self.cdm_stop.set()
if last:
self.messages.close_cdm_sessions()
def poll_cdm_calls(self, stop: Event, interval: Optional[float] = None) -> None:
endpoint = self.messages.route(PROMPT_ROUTE)
while not stop.wait(CDM_POLL_INTERVAL if interval is None else interval):
if self.paused():
continue
try:
call = cast(PromptReply, self.service.client.probe(endpoint)).get("cdm_call")
if isinstance(call, dict):
with quiet():
self.answer(json.dumps(self.messages.answer_cdm(call)))
except (requests.RequestException, ValueError, SystemExit) as e:
self.service.log.debug(f"CDM call poll failed: {e}")
def drain_logs(self) -> None:
"""Fetch the service's server-side log records for this remote session and log them here.
A relay failure must never break the operation itself, so this method swallows every error.
"""
if not self.service._session_id:
return
with self.drain_lock:
try:
with quiet():
endpoint = self.messages.route(LOGS_ROUTE) + f"?since={self.messages.log_seq}"
resp = cast(LogsReply, self.service.client.get_optional(endpoint))
except (Exception, SystemExit):
return
if resp:
self.messages.show_logs(resp.get("logs", []))
def draining(self) -> bool:
"""Whether the server announced a restart."""
info = cast(SessionInfo, self.service.client.probe(self.messages.route(SESSION_ROUTE)))
return bool(info.get("draining"))
def close(self) -> None:
self.stop_keepalive()
class WebSocketChannel:
"""The remote session channel: the server sends its messages on a WebSocket that a daemon thread holds open.
While the WebSocket is down, :attr:`fallback` polls and the thread reconnects with a backoff. The thread never
reopens a session: a close with ``CHANNEL_SESSION_GONE`` ends it, and the next call finds the session gone.
"""
def __init__(self, messages: ServerMessages, fallback: PollingChannel) -> None:
self.messages = messages
self.service = messages.service
self.fallback = fallback
self.headers = ws_headers(self.service.client)
self.connected = Event()
self.attempted = Event()
self.changed = Event()
self.status: Optional[str] = None
self.error = ""
self.failure: Optional[RemoteError] = None
self.draining_now = False
self.answers: Dict[str, Optional[ChannelAnswer]] = {} # None while this client still works on the ask
fallback.paused = self.connected.is_set
self.ws: Optional[aiohttp.ClientWebSocketResponse] = None
self.loop: Optional[asyncio.AbstractEventLoop] = None
self.task: Optional[asyncio.Task[None]] = None
self.thread = Thread(
target=lambda: asyncio.run(self.run()), name=f"{self.service.service_tag}-channel", daemon=True
)
def open(self, timeout: float = CONNECT_TIMEOUT) -> bool:
"""Connect once; False when the server or a gateway refuses the channel, or the connection fails."""
self.thread.start()
self.attempted.wait(timeout)
if not self.connected.is_set():
self.close()
return False
return True
async def run(self) -> None:
self.loop, self.task = asyncio.get_running_loop(), asyncio.current_task()
try:
await self.connect()
except asyncio.CancelledError:
pass
finally:
self.attempted.set()
self.changed.set()
async def connect(self) -> None:
backoff = RECONNECT_DELAY
async with aiohttp.ClientSession(headers=self.headers) as http:
while True:
code = None
url = (
self.service.client.server_url
+ self.messages.route(CHANNEL_ROUTE)
+ f"?since={self.messages.log_seq}"
)
try:
async with http.ws_connect(url, heartbeat=HEARTBEAT) as ws:
self.ws = ws
self.connected.set()
self.attempted.set()
self.fallback.stop_keepalive()
backoff = RECONNECT_DELAY
await self.read(ws)
code = ws.close_code
except aiohttp.WSServerHandshakeError as e:
log.debug(f"The server refused the session channel: HTTP {e.status}")
if not self.attempted.is_set() or e.status in GONE_STATUSES:
return
backoff = max(backoff, retry_after(e) or 0)
except (aiohttp.ClientError, asyncio.TimeoutError, OSError) as e:
log.debug(f"The session channel could not connect: {e!r}")
if not self.attempted.is_set():
return
finally:
self.ws = None
self.connected.clear()
self.changed.set()
if code == CHANNEL_SESSION_GONE:
log.debug("The server closed the session channel: the remote session is gone")
return
self.fallback.keep_alive()
log.debug(f"The session channel dropped, reconnecting in {backoff:.1f}s")
await asyncio.sleep(backoff)
backoff = min(backoff * 2, 30.0)
async def read(self, ws: aiohttp.ClientWebSocketResponse) -> None:
async for msg in ws:
if msg.type != WSMsgType.TEXT:
continue
try:
data = json.loads(msg.data)
except ValueError:
continue
if isinstance(data, dict):
await self.receive(ws, data)
async def receive(self, ws: aiohttp.ClientWebSocketResponse, data: Dict[str, Any]) -> None:
kind = data.get("type")
if kind == ChannelMessage.LOG:
self.messages.show_logs([cast(LogRecord, data)])
elif kind == ChannelMessage.STATUS:
self.status, self.error = data.get("status"), str(data.get("error") or "")
self.changed.set()
elif kind == ChannelMessage.DRAIN:
self.draining_now = bool(data.get("draining"))
elif kind in (ChannelMessage.PROMPT, ChannelMessage.CDM_CALL) and isinstance(data.get("id"), str):
ask_id = data["id"]
if ask_id not in self.answers:
self.answers[ask_id] = None
if len(self.answers) > KEPT_ANSWERS:
self.answers.pop(next(iter(self.answers)))
Thread(target=self.answer, args=(data,), name=f"{self.service.service_tag}-ask", daemon=True).start()
elif kept := self.answers[ask_id]:
await ws.send_json(kept) # the server sends an ask again after a reconnect when its answer was lost
def answer(self, data: Dict[str, Any]) -> None:
"""Answer one prompt or CDM call on this thread, so the channel keeps reading while the user types."""
cdm_call = data["type"] == ChannelMessage.CDM_CALL
answer = ChannelAnswer(type=ChannelMessage.ANSWER, id=data["id"], response="")
try:
if cdm_call:
answer["response"] = json.dumps(self.messages.answer_cdm(data.get("call") or {}))
else:
answer["response"] = self.messages.ask_user(str(data.get("prompt") or "Enter input: "))
except (Exception, RemoteError) as e: # an unanswered ask would hold the service thread until it times out
if isinstance(e, RemoteError):
self.failure = e
self.changed.set()
log.debug(f"Could not answer the server's {data['type']}: {e!r}")
if cdm_call:
answer["response"] = json.dumps({"error": str(e) or type(e).__name__})
else:
answer["error"] = str(e) or type(e).__name__
self.answers[data["id"]] = answer
loop, ws = self.loop, self.ws
if loop is not None and ws is not None:
with contextlib.suppress(Exception): # a lost answer goes again when the server sends the ask again
asyncio.run_coroutine_threadsafe(ws.send_json(answer), loop).result(SEND_TIMEOUT)
def wait_auth(self, timeout: float = AUTH_TIMEOUT) -> None:
"""Wait for the login state on the channel, and poll while the channel is down."""
self.fallback.wait_auth(timeout, self.auth_step)
def auth_step(self) -> bool:
"""Wait one interval for the login state: True when authenticated."""
if self.failure is not None:
raise self.failure
if not self.connected.is_set():
return self.fallback.auth_step()
self.changed.clear()
if self.status == AuthStatus.AUTHENTICATED:
return True
if self.status == AuthStatus.FAILED:
raise RemoteError(
f"Remote auth failed: {self.error or 'Authentication failed on server'}", ClientErrorKind.AUTH
)
seen = self.messages.log_seq
if not self.changed.wait(AUTH_POLL_INTERVAL) and self.status == AuthStatus.AUTHENTICATING:
self.messages.note_waiting(seen)
return False
def keep_alive(self) -> None:
"""An open channel keeps the remote session alive; the fallback pings while the channel is down."""
if not self.connected.is_set():
self.fallback.keep_alive()
def in_flight(self, endpoint: str) -> ContextManager[None]:
"""The fallback's CDM call poller, which polls only while the channel is down."""
return self.fallback.in_flight(endpoint)
def drain_logs(self) -> None:
if not self.connected.is_set():
self.fallback.drain_logs()
def draining(self) -> bool:
return self.draining_now if self.connected.is_set() else self.fallback.draining()
def close(self) -> None:
if self.loop and self.task and self.thread.is_alive():
self.loop.call_soon_threadsafe(self.task.cancel)
self.thread.join(5)
self.fallback.close()
self.messages.close_cdm_sessions()
Channel = Union[PollingChannel, WebSocketChannel]
def open_channel(service: RemoteService) -> Channel:
"""The remote session channel when the server takes it, else the polling fallback, also for every later session."""
messages = ServerMessages(service)
fallback = PollingChannel(messages)
if service.client.no_channel:
return fallback
channel = WebSocketChannel(messages, fallback)
if channel.open():
return channel
service.client.no_channel = True
return fallback
+65 -1
View File
@@ -9,7 +9,7 @@ older peer.
from __future__ import annotations
from enum import Enum, StrEnum
from typing import Any, Optional, TypedDict
from typing import Any, NotRequired, Optional, TypedDict
HEALTH_ROUTE = "/api/health"
SERVICES_ROUTE = "/api/services"
@@ -25,6 +25,10 @@ LICENSE_ROUTE = SESSION_ROUTE + "/license"
BAD_KEY_ROUTE = SESSION_ROUTE + "/keys/bad"
LOGS_ROUTE = SESSION_ROUTE + "/logs"
PROMPT_ROUTE = SESSION_ROUTE + "/prompt"
CHANNEL_ROUTE = SESSION_ROUTE + "/channel"
CHANNEL_SESSION_GONE = 4404
"""The close code of a session channel whose remote session the server removed: deleted, expired, evicted or stopped."""
class AuthStatus(StrEnum):
@@ -243,6 +247,66 @@ class SessionClosed(TypedDict, total=False):
cache: dict[str, str]
class ChannelMessage(StrEnum):
"""The ``type`` of a remote session channel message. The server sends each type except ``answer``, which the client sends."""
PROMPT = "prompt"
CDM_CALL = "cdm_call"
LOG = "log"
STATUS = "status"
DRAIN = "drain"
ANSWER = "answer"
class ChannelPrompt(TypedDict):
"""A prompt for the user; the answer names its ``id``."""
type: str
id: str
prompt: str
class ChannelCdmCall(TypedDict):
"""A call the service makes on the client's CDM, in the shape of the prompt route's ``cdm_call``."""
type: str
id: str
call: dict[str, Any]
class ChannelLog(LogRecord):
"""One service log record, as the logs route gives it."""
type: str
class ChannelStatus(TypedDict):
"""The login state of the remote session: on attach, and each time it changes."""
type: str
status: str
error: NotRequired[str]
class ChannelDrain(TypedDict):
"""Whether the server restarts after its open sessions finish: on attach, at a drain, and when a drain stops."""
type: str
draining: bool
class ChannelAnswer(TypedDict):
"""The client's answer to a prompt or CDM call. A CDM call's answer is the JSON object as a string.
``error`` says why the client could not answer a prompt, so the service stops at once.
"""
type: str
id: str
response: str
error: NotRequired[str]
class SessionInfo(TypedDict, total=False):
session_id: str
service: str
+44 -196
View File
@@ -11,7 +11,6 @@ import atexit
import base64
import contextlib
import hashlib
import json
import logging
import math
import random
@@ -19,10 +18,22 @@ import re
import shlex
import sys
import time
from collections import deque
from http.cookiejar import CookieJar
from threading import Event, Lock, Thread, local
from typing import Any, Callable, Dict, Iterable, Iterator, Mapping, Optional, Protocol, TypeVar, Union, cast
from threading import Lock, local
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
Iterable,
Iterator,
Mapping,
Optional,
Protocol,
TypeVar,
Union,
cast,
)
from urllib.parse import urlencode, urlsplit
from uuid import UUID
@@ -35,7 +46,7 @@ from rich.rule import Rule
from rich.spinner import Spinner
from unshackle.core.config import config
from unshackle.core.console import SyncLive, console, prompt_user, show_notice
from unshackle.core.console import SyncLive, console
from unshackle.core.constants import AnyTrack
from unshackle.core.credential import Credential
from unshackle.core.dl_options import remote_dl_params
@@ -46,8 +57,6 @@ from unshackle.core.remote_protocol import (
BAD_KEY_ROUTE,
HEALTH_ROUTE,
LICENSE_ROUTE,
LOGS_ROUTE,
PROMPT_ROUTE,
SAMPLES_ROUTE,
SEARCH_ROUTE,
SEGMENT_FILTER_ROUTE,
@@ -63,15 +72,11 @@ from unshackle.core.remote_protocol import (
ClientLogin,
LicenseReply,
LicenseRequest,
LogsReply,
PromptAnswer,
PromptReply,
SegmentFilterReply,
SegmentFilterRequest,
SessionClosed,
SessionCreate,
SessionCreated,
SessionInfo,
TitlesReply,
TracksReply,
TracksRequest,
@@ -92,6 +97,9 @@ from unshackle.core.utils.service_params import service_options
from unshackle.core.vault import Vault
from unshackle.core.wire import apply_title_fields, build_title, build_tracks
if TYPE_CHECKING:
from unshackle.core.remote_channel import Channel
log = logging.getLogger("remote_service")
SENSITIVE_DATA_KEYS = ("credential", "credentials", "password", "token", "api_key")
@@ -112,7 +120,6 @@ RETRY_AFTER_LOCK = Lock()
RATE_LIMIT_TRIES = 3
TUNNEL_SLOT_POLL = 15
PROBE_TIMEOUT = 30.0
KEEPALIVE_MIN_INTERVAL = 5.0
REOPEN_WAIT = 1800.0 # seconds a lost session waits for its server to come back; covers a deploy's whole drain
@@ -226,6 +233,7 @@ class RemoteClient:
self._auth_header_found = False
self._session: Optional[requests.Session] = None
self.tunnel: Optional[TunnelClient] = None
self.no_channel = False # this server or a gateway in front of it refused the remote session channel
# wraps every request, so the service's CDM calls get answered while the server runs its code
self.in_flight: Callable[[str], contextlib.AbstractContextManager[Any]] = lambda _: contextlib.nullcontext()
@@ -682,6 +690,11 @@ def resolve_remote_proxy_arg(proxy_arg: str, providers: Optional[list] = None) -
raise click.ClickException(str(e))
def ws_headers(client: RemoteClient) -> dict[str, str]:
"""The headers of a WebSocket to the server, the API key under the header that the server reads among them."""
return {k: str(v) for k, v in client.session.headers.items() if k.lower() != "connection"}
def start_tunnel(client: RemoteClient, proxy: Optional[str] = None) -> TunnelClient:
"""Open a tunnel that sends the server's requests out through this machine's own connection, or through
``proxy`` from this machine.
@@ -692,7 +705,7 @@ def start_tunnel(client: RemoteClient, proxy: Optional[str] = None) -> TunnelCli
raise click.ClickException(f"--local-proxy cannot use a {scheme} proxy")
if not client._auth_header_found:
client.probe(HEALTH_ROUTE)
headers = {k: str(v) for k, v in client.session.headers.items() if k.lower() != "connection"}
headers = ws_headers(client)
slot_deadline = time.monotonic() + RETRY_AFTER_MAX
rate_waits = 0
while True:
@@ -861,6 +874,7 @@ class RemoteService:
ANIME: bool = False
DAILY: bool = False
server_cdm_type: str = "widevine"
channel: Optional[Channel] = None
def __init__(
self,
@@ -896,13 +910,9 @@ class RemoteService:
self.server_vault = ServerVault(self)
self._segment_filters: Dict[str, Callable[[Any], bool]] = {}
self._sample_decrypt_tracks: set[str] = set()
self._log_seq = 0
self._recent_logs: deque[str] = deque(maxlen=3)
self._input_bridge: Any = None # a serve relaying for a REST client sets one, as it does for a Service
# what a login waiting on the user (a pair code, an approval link) last showed; None otherwise
self.auth_notice: Optional[str] = None
self._log_drain_lock = Lock()
self._keepalive_stop = Event()
self._reopen_lock = Lock()
self._current_title: Optional[Title_T] = None
# client title and track id -> the id a reopened session gave the same title or track
@@ -936,10 +946,6 @@ class RemoteService:
# read before apply_service_config merges the server's values into the same section
own = config.services.get(service_tag) or {}
self._client_config = {k: own[k] for k in services_config.get("_client_config") or [] if k in own}
self._cdm_sessions: Dict[str, bytes] = {}
self._cdm_lock = Lock()
self._cdm_requests = 0
self._cdm_stop = Event()
self.apply_service_config(svc_config)
def apply_service_config(self, svc_config: dict) -> None:
@@ -1202,13 +1208,15 @@ class RemoteService:
# without the server vault grant the server refuses every key request, so none is sent
self._local_vaults_only = self._server_device and not vault
status = result.get("status", AuthStatus.AUTHENTICATED)
if status == AuthStatus.AUTHENTICATING:
self.poll_auth_completion()
from unshackle.core.remote_channel import open_channel
self.channel = open_channel(self)
if result.get("status", AuthStatus.AUTHENTICATED) == AuthStatus.AUTHENTICATING:
self.channel.wait_auth()
if create_data.get("cdm_relay"):
self.client.in_flight = self.answering_cdm_calls
self.client.in_flight = self.channel.in_flight
self.drain_server_logs()
self.start_keepalive()
self.channel.keep_alive()
@property
def local_cdm(self) -> Any:
@@ -1257,24 +1265,6 @@ class RemoteService:
message += "; pass a higher -q to license above it with your own device"
self.log.info(message)
def start_keepalive(self) -> None:
"""Send keep-alive requests so that a long download or mux operation does not outlive the server's idle TTL.
``GET /api/session/{session_id}`` refreshes the idle timer and reports the TTL, so the thread sends
a request at an interval of one third of it. The thread stops when ``close()`` or a reopen runs. A client
that dies stops sending requests, so the server still expires an abandoned remote session.
"""
info = cast(SessionInfo, self.client.get_optional(SESSION_ROUTE.format(session_id=self._session_id)))
interval = max(float(info.get("expires_in") or 300) / 3, KEEPALIVE_MIN_INTERVAL)
endpoint = SESSION_ROUTE.format(session_id=self._session_id)
stop = self._keepalive_stop = Event()
def ping() -> None:
while not stop.wait(interval):
self.client.probe(endpoint)
Thread(target=ping, name=f"{self.service_tag}-keepalive", daemon=True).start()
def session_call(self, call: Callable[[Optional[str]], T]) -> T:
"""Run ``call`` with the session id, and once more on a new session when the server lost the old one."""
session_id = self._session_id
@@ -1335,12 +1325,11 @@ class RemoteService:
A track the new remote session gives another id keeps its old one here, and calls translate it.
"""
grants = (self._server_cdm, self._server_device, self._server_vault)
self._keepalive_stop.set()
self.close_channel()
self._session_id = None
if self.client.tunnel: # the server forgot the tunnel too
self.client.tunnel.stop()
self.client.tunnel = None
self._log_seq = 0
self._segment_filters.clear()
if not self.wait_for_server(accepting=True):
return False
@@ -1390,162 +1379,21 @@ class RemoteService:
def server_draining(self) -> bool:
"""Whether the server announced a restart; asked once per title, as an episode can be shorter than the keepalive."""
if not self._session_id:
return False
info = cast(SessionInfo, self.client.probe(SESSION_ROUTE.format(session_id=self._session_id)))
return bool(info.get("draining"))
return bool(self._session_id and self.channel and self.channel.draining())
def server_track_id(self, track_id: Any) -> str:
"""The id the current remote session knows the track with this client id by."""
return self._track_alias.get(str(track_id), str(track_id))
def drain_server_logs(self) -> None:
"""Fetch the service's server-side log records for this remote session and re-emit them locally.
"""Show the service's server-side log records that the remote session channel has not brought already."""
if self.channel:
self.channel.drain_logs()
The server mirrors every ``self.log`` call the service makes into a
per-session buffer. Draining after each remote call shows the client
why a step failed. A relay failure must never break the operation
itself, so this method swallows every error.
"""
if not self._session_id:
return
with self._log_drain_lock:
try:
with quiet():
endpoint = LOGS_ROUTE.format(session_id=self._session_id) + f"?since={self._log_seq}"
resp = cast(LogsReply, self.client.get_optional(endpoint))
except (Exception, SystemExit):
return
if not resp:
return
from unshackle.core.api.sanitize import sanitize_log
level_names = logging.getLevelNamesMapping()
for record in resp.get("logs", []):
level = level_names.get(str(record.get("level", "INFO")), logging.INFO)
message = sanitize_log(record.get("message", ""), keep_lines=True)
self.log.log(level, message)
self._recent_logs.append(message.strip())
self._log_seq = int(resp.get("last_seq", self._log_seq))
def poll_auth_completion(self, poll_interval: float = 2.0, timeout: float = 600.0) -> None:
"""Poll the server until authentication completes, handling interactive prompts.
When the server needs user input (OTP, device code, PIN), it returns
``pending_input`` with a prompt. We display it locally, collect the
response, and POST it back. The server resumes its auth flow.
"""
deadline = time.monotonic() + timeout
try:
self.poll_auth(deadline, poll_interval)
finally:
self.close_cdm_sessions()
if self.auth_notice is not None:
self.auth_notice = None
show_notice(None)
def poll_auth(self, deadline: float, poll_interval: float) -> None:
while time.monotonic() < deadline:
resp = cast(PromptReply, self.client.get(PROMPT_ROUTE.format(session_id=self._session_id)))
status = resp.get("status")
seen = self._log_seq
self.drain_server_logs()
if status == AuthStatus.AUTHENTICATED:
return
if status == AuthStatus.AUTHENTICATING and self._log_seq == seen and self._recent_logs:
notice = "\n".join(self._recent_logs)
if notice != self.auth_notice:
self.auth_notice = notice
show_notice(notice)
if status == AuthStatus.FAILED:
raise RemoteError(
f"Remote auth failed: {resp.get('error', 'Authentication failed on server')}", ClientErrorKind.AUTH
)
if status == AuthStatus.PENDING_INPUT and isinstance(resp.get("cdm_call"), dict):
self.answer_cdm_call(resp["cdm_call"], self._cdm_sessions)
continue
if status == AuthStatus.PENDING_INPUT:
from unshackle.core.api.sanitize import sanitize_log
prompt = sanitize_log(resp.get("prompt") or "Enter input: ", keep_lines=True)
bridge = self._input_bridge
try:
user_response = bridge.request_input(prompt) if bridge else prompt_user(prompt)
except EOFError:
raise RemoteError(
"Remote auth needs interactive input but stdin is closed", ClientErrorKind.AUTH
) from None
self.client.post(
PROMPT_ROUTE.format(session_id=self._session_id),
PromptAnswer(response=user_response),
)
continue
time.sleep(poll_interval)
raise RemoteError("Remote authentication timed out", ClientErrorKind.AUTH)
def answer_cdm_call(self, call: Dict[str, Any], sessions: Dict[str, bytes]) -> None:
"""Run one of the server's CDM calls on this machine's device and post the answer."""
from unshackle.core.cdm.client_relay import answer_cdm_call
answer = answer_cdm_call(self.local_cdm, call, sessions)
self.log.debug(f"Answered a server CDM call: {call.get('op')} ({'refused' if 'error' in answer else 'ok'})")
self.client.post(PROMPT_ROUTE.format(session_id=self._session_id), PromptAnswer(response=json.dumps(answer)))
@contextlib.contextmanager
def answering_cdm_calls(self, endpoint: str) -> Iterator[None]:
"""Answer the server's CDM calls while a remote session request runs service code.
One poller serves every concurrent request, and the local CDM sessions close when the last one ends.
"""
own = {route.format(session_id=self._session_id) for route in (PROMPT_ROUTE, LOGS_ROUTE, SAMPLES_ROUTE)}
if not endpoint.startswith(SESSION_ROUTE.format(session_id=self._session_id) + "/") or (
endpoint.partition("?")[0] in own
):
yield
return
with self._cdm_lock:
self._cdm_requests += 1
if self._cdm_requests == 1:
self._cdm_stop = Event()
Thread(
target=self.poll_cdm_calls, args=(self._cdm_stop,), name=f"{self.service_tag}-cdm", daemon=True
).start()
try:
yield
finally:
with self._cdm_lock:
self._cdm_requests -= 1
if self._cdm_requests == 0:
self._cdm_stop.set()
def poll_cdm_calls(self, stop: Event, interval: float = 0.5) -> None:
endpoint = PROMPT_ROUTE.format(session_id=self._session_id)
sessions: Dict[str, bytes] = {}
while not stop.wait(interval):
try:
call = cast(PromptReply, self.client.probe(endpoint)).get("cdm_call")
if isinstance(call, dict):
with quiet():
self.answer_cdm_call(call, sessions)
except (requests.RequestException, ValueError, SystemExit) as e:
self.log.debug(f"CDM call poll failed: {e}")
self.close_cdm_sessions(sessions)
def close_cdm_sessions(self, sessions: Optional[Dict[str, bytes]] = None) -> None:
"""Close the local CDM sessions that the server's calls opened; best effort."""
sessions = self._cdm_sessions if sessions is None else sessions
cdm = self.local_cdm
for session_id in sessions.values():
with contextlib.suppress(Exception):
cdm.close(session_id)
sessions.clear()
def close_channel(self) -> None:
channel, self.channel = self.channel, None
if channel:
channel.close()
def get_titles(self) -> Titles_T:
if self._titles is not None:
@@ -2036,7 +1884,7 @@ class RemoteService:
def close(self) -> None:
# a long-lived serve opens many of these; the atexit hook would keep every one alive
atexit.unregister(self.close)
self._keepalive_stop.set()
self.close_channel()
session_id, self._session_id = self._session_id, None
if session_id:
try: