fix(remote): map a cut-off answer to a recoverable error and stop trusting an empty optional answer

This commit is contained in:
imSp4rky
2026-11-28 21:03:54 -07:00
parent 74fa29b6f1
commit f5c8858e6e
12 changed files with 279 additions and 76 deletions
+1 -1
View File
@@ -1171,7 +1171,7 @@ Get the download URL, DRM info, headers, cookies, and raw track data for the sel
### `POST /api/session/{session_id}/segment_filter` ### `POST /api/session/{session_id}/segment_filter`
Get the HLS segments a service drops (ads, bumpers, dub cards). The server runs the service's own segment filter over the track's media playlist and returns only the URIs, so the client drops the same segments the service does. Body: `{ "track_id": "v-1" }` (required). `unwanted` is `null` when the track has no filter. The client keeps every segment when the server does not have this route. Get the HLS segments a service drops (ads, bumpers, dub cards). The server runs the service's own segment filter over the track's media playlist and returns only the URIs, so the client drops the same segments the service does. Body: `{ "track_id": "v-1" }` (required). `unwanted` is `null` when the track has no filter. The client keeps every segment when the server does not have this route. When the server answers with an error, the client stops the track download.
=== "Response `200`" === "Response `200`"
+13 -9
View File
@@ -727,14 +727,14 @@ the error codes and the request and reply shapes that it shares with the server
closes its remote session, so the drain can end and the refreshed cache comes back. closes its remote session, so the drain can end and the refreshed cache comes back.
It waits until `/api/health` reports the restarted server without `draining`, It waits until `/api/health` reports the restarted server without `draining`,
opens a new remote session, and continues with the next title. opens a new remote session, and continues with the next title.
- A lost remote session (`SESSION_NOT_FOUND`, a connection error, a timeout, a closed - A lost remote session (`SESSION_NOT_FOUND`, a connection error, an answer cut off
tunnel or a gateway error page): the client waits for `/api/health`, then checks the after its headers, a timeout, a closed tunnel or a gateway error page): the client waits
old remote session. A live remote session takes the call again only after a connection for `/api/health`, then checks the old remote session. A live remote session takes the
error, because a timed-out call can already have run. A lost one is replaced: the call again only after a connection error, because a timed-out call can already have run.
A cut-off answer counts as a connection error, so the server can run that call twice. A lost one is replaced: the
client opens a new remote session, sends `titles` and the current title's `tracks` client opens a new remote session, sends `titles` and the current title's `tracks`
again, and then sends the failed call again. A title or track that the new remote again, and then sends the failed call again. A title or track that the new remote session
session gives another ID keeps its old ID on the client, and the client sends the gives another ID keeps its old ID on the client, and the client sends the new ID. The client matches a title by season and episode number, and a track by its
new ID. The client matches a title by season and episode number, and a track by its
attributes. attributes.
The client waits up to 30 minutes for the server, which covers a deploy's drain. It The client waits up to 30 minutes for the server, which covers a deploy's drain. It
@@ -742,8 +742,12 @@ the error codes and the request and reply shapes that it shares with the server
for example after a change to the API key's `server_cdm` grant. An interactive login for example after a change to the API key's `server_cdm` grant. An interactive login
asks for its input again. asks for its input again.
- **Server resolution.** `resolve_server()` reads `config.remote_services.<name>` - **Server resolution.** `resolve_server()` reads `config.remote_services.<name>`
into `{url, api_key, services, server_cdm}`, injecting the `server_cdm` flag into into `{url, api_key, services, server_cdm}`. It puts the `server_cdm` flag into a
the services map as `_server_cdm`. copy of the services map as `_server_cdm`, and never changes the loaded config.
- **Optional routes.** A call to a route that an older server can lack (the segment filter,
bad content key reports, the log poll) counts as empty only when the server answers 404
with no `error_code`. Any other error stops the call: a segment filter that fails on the
server stops the track download, and the client never keeps every segment in its place.
--- ---
+2 -1
View File
@@ -413,7 +413,7 @@ def test_a_body_over_the_limit_is_cut_and_marked(server, debug_log, monkeypatch,
assert (response["body"], response["body_size"], response["body_cut"]) == ('{"xyz', 13, True) assert (response["body"], response["body_size"], response["body_cut"]) == ('{"xyz', 13, True)
def test_a_failed_body_read_is_recorded_and_left_to_the_caller(debug_log): def test_a_failed_body_read_is_recorded_and_raised_again(debug_log):
class Broken: class Broken:
status_code = 200 status_code = 200
headers = {"content-type": "application/json"} headers = {"content-type": "application/json"}
@@ -423,6 +423,7 @@ def test_a_failed_body_read_is_recorded_and_left_to_the_caller(debug_log):
raise rq.exceptions.ChunkedEncodingError("cut short") raise rq.exceptions.ChunkedEncodingError("cut short")
response = Broken() response = Broken()
with pytest.raises(rq.exceptions.ChunkedEncodingError):
http_session.record_request("GET", "http://h/api", 1, response=response, body=True) http_session.record_request("GET", "http://h/api", 1, response=response, body=True)
(entry,) = records(debug_log) (entry,) = records(debug_log)
+20
View File
@@ -10,6 +10,7 @@ from types import SimpleNamespace
from typing import Any, cast from typing import Any, cast
from unittest.mock import Mock from unittest.mock import Mock
import click
import pytest import pytest
import requests import requests
from aiohttp import WSMsgType, web from aiohttp import WSMsgType, web
@@ -322,3 +323,22 @@ async def test_a_failed_login_status_shows_the_server_error_without_control_char
with pytest.raises(RemoteError) as caught: with pytest.raises(RemoteError) as caught:
channel.auth_step() channel.auth_step()
assert caught.value.message == "Remote auth failed: [2Jbadforged" assert caught.value.message == "Remote auth failed: [2Jbadforged"
@pytest.mark.parametrize("answer", [{"license": None}, {}, {"license": "x"}, {"license": 5}])
def test_a_relayed_licence_with_no_licence_is_one_click_error(answer: dict[str, Any]) -> None:
service = RemoteService.__new__(RemoteService)
service._track_alias = {}
service.session_call = lambda call: answer # type: ignore[method-assign]
service.drain_server_logs = lambda: None # type: ignore[method-assign]
track = SimpleNamespace(id="v1", drm=[])
with pytest.raises(click.ClickException, match="no valid licence for track v1"):
service.proxy_license(b"challenge", cast(Any, track), "widevine")
@pytest.mark.parametrize("chapters", [[{"name": "x"}], [{"timestamp": "not a time"}], [5]])
def test_malformed_chapters_from_the_server_are_one_remote_error(chapters: list[Any]) -> None:
service = RemoteService.__new__(RemoteService)
service._chapters_by_title = {"t": chapters}
with pytest.raises(RemoteError, match="malformed chapters"):
service.get_chapters(cast(Any, SimpleNamespace(id="t")))
+77 -2
View File
@@ -4,13 +4,19 @@ from __future__ import annotations
import json import json
import logging import logging
import socket
import threading
from pathlib import Path
import click import click
import pytest import pytest
import requests import requests
import responses import responses
from unshackle.core.remote_service import RemoteClient from unshackle.core.config import config
from unshackle.core.remote_protocol import ClientErrorKind
from unshackle.core.remote_service import RemoteClient, RemoteError
from unshackle.core.utilities import close_debug_logger, init_debug_logger
pytestmark = pytest.mark.unit pytestmark = pytest.mark.unit
@@ -216,7 +222,65 @@ def test_late_error_after_heartbeat_is_fatal(client: RemoteClient) -> None:
responses.add(responses.GET, "http://srv:8786/api/session/s/titles", body=body, status=200) responses.add(responses.GET, "http://srv:8786/api/session/s/titles", body=body, status=200)
with pytest.raises(SystemExit): with pytest.raises(SystemExit):
client.get("/api/session/s/titles") client.get("/api/session/s/titles")
assert client.request("get", "/api/session/s/titles", optional=True) == {} with pytest.raises(RemoteError):
client.request("get", "/api/session/s/titles", optional=True)
@responses.activate
def test_an_optional_route_the_server_lacks_answers_empty(client: RemoteClient) -> None:
responses.add(responses.POST, "http://srv:8786/api/session/s/segment_filter", body="404: Not Found", status=404)
assert client.post_optional("/api/session/s/segment_filter", {}) == {}
@pytest.mark.parametrize(
("status", "code"),
[(422, "SERVICE_ERROR"), (404, "TRACK_NOT_FOUND"), (404, "SESSION_NOT_FOUND"), (503, "SERVER_DRAINING")],
)
@responses.activate
def test_an_optional_route_that_fails_on_the_server_raises(client: RemoteClient, status: int, code: str) -> None:
body = {"status": "error", "error_code": code, "message": "no"}
responses.add(responses.POST, "http://srv:8786/api/session/s/segment_filter", json=body, status=status)
with pytest.raises(RemoteError) as e:
client.post_optional("/api/session/s/segment_filter", {})
assert e.value.kind == code
@pytest.mark.parametrize("recorded", [False, True], ids=["plain", "debug-requests"])
@pytest.mark.parametrize(
("headers", "body"),
[
(b"Content-Length: 100\r\n", b'{"titles": ['),
(b"Content-Encoding: gzip\r\nContent-Length: 13\r\n", b'{"titles": ['),
(b"Transfer-Encoding: chunked\r\n", b'2\r\n\n\n\r\nc\r\n{"titles": ['),
],
ids=["short-body", "bad-gzip", "cut-chunked"],
)
def test_an_answer_cut_off_after_its_headers_is_a_connect_error(
headers: bytes, body: bytes, recorded: bool, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
"""A body that stops early, or a gzip body that does not decode, is a broken connection the session can survive."""
if recorded:
monkeypatch.setattr(config, "debug_requests", True)
init_debug_logger(log_path=tmp_path / "debug.jsonl", enabled=True)
with socket.create_server(("127.0.0.1", 0)) as server:
def answer() -> None:
conn, _ = server.accept()
with conn:
conn.recv(65536)
conn.sendall(b"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n" + headers + b"\r\n" + body)
thread = threading.Thread(target=answer, daemon=True)
thread.start()
client = RemoteClient(server_url=f"http://127.0.0.1:{server.getsockname()[1]}", api_key="k")
try:
with pytest.raises(RemoteError) as e:
client.get("/api/session/s/titles")
finally:
close_debug_logger()
thread.join(5)
assert e.value.kind == ClientErrorKind.CONNECT
assert e.value.session_broke
@responses.activate @responses.activate
@@ -381,3 +445,14 @@ def test_a_probe_that_cannot_connect_logs_no_error(client: RemoteClient, caplog:
assert client.probe("/api/health") == {} assert client.probe("/api/health") == {}
assert not [r for r in caplog.records if r.levelno >= logging.WARNING] assert not [r for r in caplog.records if r.levelno >= logging.WARNING]
@responses.activate
def test_any_other_requests_failure_is_one_remote_error(client: RemoteClient) -> None:
leak = requests.TooManyRedirects("http://user:pw@gw.example/login?token=SECRET")
responses.add(responses.GET, "http://srv:8786/api/session/s/titles", body=leak)
with pytest.raises(RemoteError) as e:
client.get("/api/session/s/titles")
assert e.value.kind == ClientErrorKind.UNKNOWN
assert e.value.message == "Request to remote server failed on /api/session/s/titles: TooManyRedirects"
assert not e.value.session_broke
+8
View File
@@ -152,3 +152,11 @@ def test_resolve_proxy_value_error_becomes_click(monkeypatch: pytest.MonkeyPatch
with pytest.raises(click.ClickException) as exc: with pytest.raises(click.ClickException) as exc:
resolve_proxy_arg("xx") resolve_proxy_arg("xx")
assert "no such country" in str(exc.value.message) assert "no such country" in str(exc.value.message)
def test_resolve_server_leaves_the_config_services_untouched(single_remote_service) -> None:
from unshackle.core import remote_service as rs
_, _, services = resolve_server("primary")
assert services["_server_cdm"] is True
assert rs.config.remote_services["primary"]["services"] == {"EXAMPLE": True, "DEMO": True}
+7
View File
@@ -116,3 +116,10 @@ def test_local_proxy_is_refused_for_a_server_account_service() -> None:
with pytest.raises(click.ClickException, match="its own account"): with pytest.raises(click.ClickException, match="its own account"):
list(svc.search()) list(svc.search())
def test_malformed_search_results_from_the_server_are_one_remote_error() -> None:
svc, client, _ = make_service({"no_proxy": True}, server_accounts={"global": True})
client.post = lambda endpoint, data: {"results": [{"title": "no id"}]} # type: ignore[method-assign]
with pytest.raises(remote_service.RemoteError, match="malformed search results"):
list(svc.search())
+28 -2
View File
@@ -5,6 +5,7 @@ from __future__ import annotations
import json import json
from types import SimpleNamespace from types import SimpleNamespace
import click
import pytest import pytest
import responses import responses
@@ -58,7 +59,7 @@ async def test_handler_returns_null_without_a_filter(monkeypatch):
assert json.loads(response.body) == {"unwanted": None} assert json.loads(response.body) == {"unwanted": None}
def make_service(unwanted, status=200): def make_service(unwanted, status=200, error=None):
service = RemoteService.__new__(RemoteService) service = RemoteService.__new__(RemoteService)
service._track_alias = {} service._track_alias = {}
service._title_alias = {} service._title_alias = {}
@@ -68,7 +69,7 @@ def make_service(unwanted, status=200):
responses.add( responses.add(
responses.POST, responses.POST,
"http://srv:8786/api/session/s1/segment_filter", "http://srv:8786/api/session/s1/segment_filter",
json={"unwanted": unwanted} if status == 200 else {"message": "no"}, json={"unwanted": unwanted} if status == 200 else error or {"message": "no"},
status=status, status=status,
) )
return service return service
@@ -93,3 +94,28 @@ def test_client_filter_keeps_everything_when_the_server_has_no_route():
segment_filter = service.remote_segment_filter("t1") segment_filter = service.remote_segment_filter("t1")
assert segment_filter(SimpleNamespace(absolute_uri="https://cdn.test/hls/ad1.ts")) is False assert segment_filter(SimpleNamespace(absolute_uri="https://cdn.test/hls/ad1.ts")) is False
@responses.activate
def test_a_filter_that_fails_on_the_server_stops_the_track_and_caches_nothing():
error = {"status": "error", "error_code": "SERVICE_ERROR", "message": "Could not run the segment filter"}
service = make_service(None, status=422, error=error)
segment_filter = service.remote_segment_filter("t1")
with pytest.raises(click.ClickException, match="segment filter"):
segment_filter(SimpleNamespace(absolute_uri="https://cdn.test/hls/ad1.ts"))
assert service._segment_filters == {}
@responses.activate
def test_a_replayed_filter_call_sends_the_reopened_track_id():
service = make_service([])
def session_call(call):
service._track_alias["t1"] = "t1-new"
return call("s1")
service.session_call = session_call
service.remote_segment_filter("t1")(SimpleNamespace(absolute_uri="https://cdn.test/hls/ad1.ts"))
assert json.loads(responses.calls[0].request.body) == {"track_id": "t1-new"}
+32 -2
View File
@@ -6,6 +6,7 @@ import json
import logging import logging
from threading import Lock from threading import Lock
import click
import pytest import pytest
import requests import requests
import responses import responses
@@ -85,11 +86,20 @@ def test_a_lost_session_reopens_and_replays_the_call_under_the_new_ids(monkeypat
assert service._title_alias == {"ep3-aaaa": "ep3-bbbb"} assert service._title_alias == {"ep3-aaaa": "ep3-bbbb"}
@pytest.mark.parametrize(
"broken",
[
requests.ConnectionError("reset"),
requests.exceptions.ChunkedEncodingError("cut"),
requests.exceptions.ContentDecodingError("cut"),
],
ids=["reset", "cut-body", "cut-gzip"],
)
@responses.activate @responses.activate
def test_a_connect_error_on_a_live_session_runs_again_on_the_same_session(): def test_a_connect_error_on_a_live_session_runs_again_on_the_same_session(broken):
service = make_service() service = make_service()
url = f"{SERVER}/api/session/s1/license" url = f"{SERVER}/api/session/s1/license"
responses.add(responses.POST, url, body=requests.ConnectionError("reset")) responses.add(responses.POST, url, body=broken)
responses.add(responses.POST, url, json={"license": "AA=="}) responses.add(responses.POST, url, json={"license": "AA=="})
responses.add(responses.GET, f"{SERVER}/api/health", json={"status": "ok"}) responses.add(responses.GET, f"{SERVER}/api/health", json={"status": "ok"})
responses.add(responses.GET, f"{SERVER}/api/session/s1", json={"valid": True}) responses.add(responses.GET, f"{SERVER}/api/session/s1", json={"valid": True})
@@ -151,3 +161,23 @@ def test_closing_a_session_the_server_lost_logs_no_error(caplog):
assert service._session_id is None assert service._session_id is None
assert not [r for r in caplog.records if r.levelname in ("WARNING", "ERROR")] assert not [r for r in caplog.records if r.levelname in ("WARNING", "ERROR")]
@responses.activate
def test_a_certificate_the_server_fails_to_fetch_is_no_certificate():
service = make_service()
error = {"status": "error", "error_code": "SERVICE_ERROR", "message": "no certificate"}
responses.add(responses.POST, f"{SERVER}/api/session/s1/license", json=error, status=422)
track = audio("a1")
assert service.get_widevine_service_certificate(challenge=b"c", title=None, track=track) is None
@responses.activate
def test_a_certificate_call_whose_session_is_gone_is_one_click_error(monkeypatch):
service = make_service()
monkeypatch.setattr(service, "recover", lambda session_id, kind: False)
responses.add(responses.POST, f"{SERVER}/api/session/s1/license", json=GONE, status=404)
with pytest.raises(click.ClickException, match="Remote session not found"):
service.get_widevine_service_certificate(challenge=b"c", title=None, track=audio("a1"))
+56 -29
View File
@@ -292,6 +292,14 @@ class RemoteClient:
raise RemoteError(f"Could not connect to remote server at {server_url}", ClientErrorKind.CONNECT) from None raise RemoteError(f"Could not connect to remote server at {server_url}", ClientErrorKind.CONNECT) from None
except requests.Timeout: except requests.Timeout:
raise self.timed_out(endpoint) from None raise self.timed_out(endpoint) from None
except (requests.exceptions.ChunkedEncodingError, requests.exceptions.ContentDecodingError):
raise RemoteError(
f"The remote server's answer to {endpoint} was cut off", ClientErrorKind.CONNECT
) from None
except requests.RequestException as e:
raise RemoteError(
f"Request to remote server failed on {endpoint}: {type(e).__name__}", ClientErrorKind.UNKNOWN
) from None
if resp.status_code < 400 and "octet-stream" in resp.headers.get("Content-Type", ""): if resp.status_code < 400 and "octet-stream" in resp.headers.get("Content-Type", ""):
return {"body": resp.content} return {"body": resp.content}
try: try:
@@ -317,8 +325,9 @@ class RemoteClient:
) )
if error_code in expect: if error_code in expect:
return detail return detail
if optional and error_code != APIErrorCode.SESSION_NOT_FOUND: # an older server without the route answers aiohttp's own 404, which names no error code
log.debug(f"Optional endpoint {endpoint} unavailable [{error_code}]: {error_msg}") if optional and resp.status_code == 404 and "error_code" not in detail:
log.debug(f"Optional endpoint {endpoint} is not on this server: {error_msg}")
return {} return {}
if self.tunnel and self.tunnel.lost: if self.tunnel and self.tunnel.lost:
raise RemoteError( raise RemoteError(
@@ -506,31 +515,25 @@ def resolve_server(server_name: str | None) -> tuple[str, str, dict]:
if not remote_services: if not remote_services:
raise click.ClickException("No 'remote_services' in your unshackle.yaml") raise click.ClickException("No 'remote_services' in your unshackle.yaml")
if server_name:
svc = remote_services.get(server_name)
if not svc:
available = ", ".join(remote_services.keys()) available = ", ".join(remote_services.keys())
if server_name:
name, svc = server_name, remote_services.get(server_name)
if not svc:
raise click.ClickException(f"Remote service '{server_name}' not found, available: {available}") raise click.ClickException(f"Remote service '{server_name}' not found, available: {available}")
services = svc.get("services", {}) elif len(remote_services) == 1:
services["_server_cdm"] = svc.get("server_cdm")
services["_auth_headers"] = resolve_auth_headers(svc, server_name)
services["_timeout"] = svc.get("timeout")
return svc["url"], svc.get("api_key", ""), services
if len(remote_services) == 1:
name, svc = next(iter(remote_services.items())) name, svc = next(iter(remote_services.items()))
if name not in ANNOUNCED_SERVERS: if name not in ANNOUNCED_SERVERS:
ANNOUNCED_SERVERS.add(name) ANNOUNCED_SERVERS.add(name)
log.info(f"Using remote service: {name}") log.info(f"Using remote service: {name}")
services = svc.get("services", {}) else:
raise click.ClickException(f"Multiple remote services configured, pick one with --server: {available}")
services = dict(svc.get("services") or {})
services["_server_cdm"] = svc.get("server_cdm") services["_server_cdm"] = svc.get("server_cdm")
services["_auth_headers"] = resolve_auth_headers(svc, name) services["_auth_headers"] = resolve_auth_headers(svc, name)
services["_timeout"] = svc.get("timeout") services["_timeout"] = svc.get("timeout")
return svc["url"], svc.get("api_key", ""), services return svc["url"], svc.get("api_key", ""), services
available = ", ".join(remote_services.keys())
raise click.ClickException(f"Multiple remote services configured, pick one with --server: {available}")
REMOTE_LIST_TTL = 300.0 REMOTE_LIST_TTL = 300.0
REMOTE_LIST_FAILURE_TTL = 30.0 REMOTE_LIST_FAILURE_TTL = 30.0
@@ -603,11 +606,10 @@ def make_remote_service(
``apply_overrides`` False keeps the per-service ``remote_services.<name>.services`` overrides out of this ``apply_overrides`` False keeps the per-service ``remote_services.<name>.services`` overrides out of this
process's global config. process's global config.
""" """
url, api_key, live = resolve_server(server_name) url, api_key, services = resolve_server(server_name)
own = ci_get(live, service_tag) own = ci_get(services, service_tag)
# resolve_server hands back the live config dict; concurrent requests for other tags must not share it
tag = service_tag.lower() tag = service_tag.lower()
services_config = {k: v for k, v in live.items() if not (isinstance(k, str) and k.lower() == tag)} services_config = {k: v for k, v in services.items() if not (isinstance(k, str) and k.lower() == tag)}
if isinstance(own, dict) and "server_cdm" in own: if isinstance(own, dict) and "server_cdm" in own:
own = dict(own) own = dict(own)
services_config["_server_cdm"] = own.pop("server_cdm") services_config["_server_cdm"] = own.pop("server_cdm")
@@ -966,10 +968,14 @@ class RemoteService(TitleSource):
if self.client.tunnel: # a search is one request, so its tunnel ends with it if self.client.tunnel: # a search is one request, so its tunnel ends with it
self.client.tunnel.stop() self.client.tunnel.stop()
self.save_returned_cache(response.get("cache") or {}, profile) self.save_returned_cache(response.get("cache") or {}, profile)
for result in response.get("results") or []: with malformed_answer("search results"):
yield SearchResult( results = [
SearchResult(
result["id"], result["title"], result.get("description"), result.get("label"), result.get("url") result["id"], result["title"], result.get("description"), result.get("label"), result.get("url")
) )
for result in response.get("results") or []
]
yield from results
def client_login(self, profile: str | None) -> ClientLogin: def client_login(self, profile: str | None) -> ClientLogin:
"""The credentials, cookies and cache to send, or nothing when the server manages the account.""" """The credentials, cookies and cache to send, or nothing when the server manages the account."""
@@ -1252,7 +1258,8 @@ class RemoteService(TitleSource):
def recover(self, session_id: str | None, kind: str) -> bool: def recover(self, session_id: str | None, kind: str) -> bool:
"""Whether a call that failed with ``kind`` can run again, on the same session or on a new one. """Whether a call that failed with ``kind`` can run again, on the same session or on a new one.
The same session takes the call again only after a connect error, as a timed-out call may have run. The same session takes the call again only after a connect error, an answer cut off after its headers
included, as a timed-out call may have run.
""" """
with self._reopen_lock: with self._reopen_lock:
if self._session_id != session_id: # another thread already reopened it if self._session_id != session_id: # another thread already reopened it
@@ -1478,15 +1485,19 @@ class RemoteService(TitleSource):
def segment_filter(segment: Any) -> bool: def segment_filter(segment: Any) -> bool:
unwanted = self._segment_filters.get(track_id) unwanted = self._segment_filters.get(track_id)
if unwanted is None: if unwanted is None:
server_id = self.server_track_id(track_id) try:
with quiet():
result = cast( result = cast(
SegmentFilterReply, SegmentFilterReply,
self.session_call( self.session_call(
lambda sid: self.client.post_optional( lambda sid: self.client.post_optional(
SEGMENT_FILTER_ROUTE.format(session_id=sid), SegmentFilterRequest(track_id=server_id) SEGMENT_FILTER_ROUTE.format(session_id=sid),
SegmentFilterRequest(track_id=self.server_track_id(track_id)),
) )
), ),
) )
except RemoteError as e:
raise click.ClickException(e.message) from None
unwanted = segment_uri_filter(result.get("unwanted") or []) unwanted = segment_uri_filter(result.get("unwanted") or [])
self._segment_filters[track_id] = unwanted self._segment_filters[track_id] = unwanted
return unwanted(segment) return unwanted(segment)
@@ -1690,6 +1701,7 @@ class RemoteService(TitleSource):
if title_id not in self._chapters_by_title: if title_id not in self._chapters_by_title:
self.get_tracks(title) self.get_tracks(title)
raw = self._chapters_by_title.get(title_id, []) raw = self._chapters_by_title.get(title_id, [])
with malformed_answer("chapters"):
return Chapters([Chapter(ch["timestamp"], ch.get("name")) for ch in raw]) return Chapters([Chapter(ch["timestamp"], ch.get("name")) for ch in raw])
def get_widevine_license(self, *, challenge: bytes, title: Title_T, track: AnyTrack) -> bytes | str | None: def get_widevine_license(self, *, challenge: bytes, title: Title_T, track: AnyTrack) -> bytes | str | None:
@@ -1706,10 +1718,12 @@ class RemoteService(TitleSource):
track: AnyTrack, track: AnyTrack,
) -> bytes | str | None: ) -> bytes | str | None:
# a missing certificate is legal (services may not use one), so a failed fetch continues without one # a missing certificate is legal (services may not use one), so a failed fetch continues without one
try:
with quiet():
resp = cast( resp = cast(
LicenseReply, LicenseReply,
self.session_call( self.session_call(
lambda sid: self.client.post_optional( lambda sid: self.client.post(
LICENSE_ROUTE.format(session_id=sid), LICENSE_ROUTE.format(session_id=sid),
LicenseRequest( LicenseRequest(
track_id=self.server_track_id(track.id), track_id=self.server_track_id(track.id),
@@ -1721,6 +1735,13 @@ class RemoteService(TitleSource):
), ),
) )
return base64.b64decode(certificate) if (certificate := resp.get("license")) else None return base64.b64decode(certificate) if (certificate := resp.get("license")) else None
except RemoteError as e:
if e.session_broke:
raise click.ClickException(e.message) from None
self.log.debug(f"No service certificate from the server: {e.message}")
except (TypeError, ValueError):
self.log.debug("The server sent a service certificate that is not Base64")
return None
def license_track(self, track: AnyTrack, drm: Any, kid: UUID | None = None) -> dict[UUID, str] | None: def license_track(self, track: AnyTrack, drm: Any, kid: UUID | None = None) -> dict[UUID, str] | None:
"""The content keys the server CDM licenses for ``drm`` of ``track``, or None when the server hands it to this machine. """The content keys the server CDM licenses for ``drm`` of ``track``, or None when the server hands it to this machine.
@@ -1793,19 +1814,19 @@ class RemoteService(TitleSource):
def track_url(self, track: Track) -> str: def track_url(self, track: Track) -> str:
"""The URL that the server looks up for a track it sent with ``resolve_url``, or raise ClickException.""" """The URL that the server looks up for a track it sent with ``resolve_url``, or raise ClickException."""
server_id = self.server_track_id(track.id)
try: try:
with quiet(): with quiet():
resp = self.session_call( resp = self.session_call(
lambda sid: self.client.post( lambda sid: self.client.post(
SEGMENTS_ROUTE.format(session_id=sid), SegmentsRequest(track_ids=[server_id]) SEGMENTS_ROUTE.format(session_id=sid),
SegmentsRequest(track_ids=[self.server_track_id(track.id)]),
) )
) )
except RemoteError as e: except RemoteError as e:
raise click.ClickException(e.message) from None raise click.ClickException(e.message) from None
finally: finally:
self.drain_server_logs() self.drain_server_logs()
if not (url := ((resp.get("tracks") or {}).get(server_id) or {}).get("url")): if not (url := ((resp.get("tracks") or {}).get(self.server_track_id(track.id)) or {}).get("url")):
raise click.ClickException(f"The server sent no URL for track {track.id}") raise click.ClickException(f"The server sent no URL for track {track.id}")
return str(url) return str(url)
@@ -1832,7 +1853,13 @@ class RemoteService(TitleSource):
raise click.ClickException(e.message) from None raise click.ClickException(e.message) from None
finally: finally:
self.drain_server_logs() self.drain_server_logs()
try:
return base64.b64decode(resp["license"]) return base64.b64decode(resp["license"])
except (KeyError, TypeError, ValueError):
raise coded(
click.ClickException(f"The remote server sent no valid licence for track {track.id}"),
APIErrorCode.DRM_ERROR,
) from None
def close(self) -> None: def close(self) -> None:
# a long-lived serve opens many of these; the atexit hook would keep every one alive # a long-lived serve opens many of these; the atexit hook would keep every one alive
+1 -1
View File
@@ -409,7 +409,7 @@ class Services(click.Group):
return [s["tag"] for s in remote_services] return [s["tag"] for s in remote_services]
tags = Services.get_tags() tags = Services.get_tags()
for svc_cfg in config.remote_services.values(): for svc_cfg in config.remote_services.values():
for remote_tag in svc_cfg.get("services", {}).keys(): for remote_tag in (svc_cfg.get("services") or {}).keys():
if remote_tag not in tags: if remote_tag not in tags:
tags.append(remote_tag) tags.append(remote_tag)
return tags return tags
+9 -4
View File
@@ -20,7 +20,7 @@ from typing import Any
from urllib.parse import urlencode, urlparse, urlsplit, urlunparse from urllib.parse import urlencode, urlparse, urlsplit, urlunparse
import rnet import rnet
from requests import HTTPError, PreparedRequest, Request, Response, Session from requests import HTTPError, PreparedRequest, Request, RequestException, Response, Session
from requests.adapters import BaseAdapter from requests.adapters import BaseAdapter
from requests.cookies import create_cookie from requests.cookies import create_cookie
from requests.structures import CaseInsensitiveDict from requests.structures import CaseInsensitiveDict
@@ -672,9 +672,9 @@ def record_request(
"""Write one ``http_request`` debug-log entry for an HTTP attempt, with its values as received. """Write one ``http_request`` debug-log entry for an HTTP attempt, with its values as received.
With ``body`` set, a text response body goes in the entry too, and ``sent`` (content type, body) adds a With ``body`` set, a text response body goes in the entry too, and ``sent`` (content type, body) adds a
text request body, except in a server process. A body read text request body, except in a server process. A body read that fails writes ``body_error``, and the entry
that fails writes ``body_error``, and the caller's own read raises the error. The duration stops at the then raises a requests read error again, because a second read of a cut chunked body returns what arrived
response headers. without an error. The duration stops at the response headers.
""" """
debug_logger = get_debug_logger() debug_logger = get_debug_logger()
if not debug_logger or not debug_logger.enabled: if not debug_logger or not debug_logger.enabled:
@@ -682,6 +682,7 @@ def record_request(
parts = urlsplit(url) parts = urlsplit(url)
size: Any = None size: Any = None
received: dict[str, Any] = {} received: dict[str, Any] = {}
read_error: RequestException | None = None
request_fields: dict[str, Any] = {} request_fields: dict[str, Any] = {}
if sent is not None and record_bodies: if sent is not None and record_bodies:
try: try:
@@ -696,6 +697,8 @@ def record_request(
received = response_body(response, parts.path) received = response_body(response, parts.path)
except Exception as e: except Exception as e:
received = {"body_error": failure_reason(e)} received = {"body_error": failure_reason(e)}
if isinstance(e, RequestException):
read_error = e
if not str(size).isdigit() and "body" in received: if not str(size).isdigit() and "body" in received:
size = len(response.content) size = len(response.content)
log_event( log_event(
@@ -713,6 +716,8 @@ def record_request(
duration_ms=None if duration is None else round(duration * 1000, 1), duration_ms=None if duration is None else round(duration * 1000, 1),
failure=failure_reason(error) if error is not None else None, failure=failure_reason(error) if error is not None else None,
) )
if read_error is not None:
raise read_error
class RecordedAdapter: class RecordedAdapter: