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
+80 -53
View File
@@ -292,6 +292,14 @@ class RemoteClient:
raise RemoteError(f"Could not connect to remote server at {server_url}", ClientErrorKind.CONNECT) from None
except requests.Timeout:
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", ""):
return {"body": resp.content}
try:
@@ -317,8 +325,9 @@ class RemoteClient:
)
if error_code in expect:
return detail
if optional and error_code != APIErrorCode.SESSION_NOT_FOUND:
log.debug(f"Optional endpoint {endpoint} unavailable [{error_code}]: {error_msg}")
# an older server without the route answers aiohttp's own 404, which names no error code
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 {}
if self.tunnel and self.tunnel.lost:
raise RemoteError(
@@ -506,30 +515,24 @@ def resolve_server(server_name: str | None) -> tuple[str, str, dict]:
if not remote_services:
raise click.ClickException("No 'remote_services' in your unshackle.yaml")
available = ", ".join(remote_services.keys())
if server_name:
svc = remote_services.get(server_name)
name, svc = server_name, remote_services.get(server_name)
if not svc:
available = ", ".join(remote_services.keys())
raise click.ClickException(f"Remote service '{server_name}' not found, available: {available}")
services = svc.get("services", {})
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:
elif len(remote_services) == 1:
name, svc = next(iter(remote_services.items()))
if name not in ANNOUNCED_SERVERS:
ANNOUNCED_SERVERS.add(name)
log.info(f"Using remote service: {name}")
services = svc.get("services", {})
services["_server_cdm"] = svc.get("server_cdm")
services["_auth_headers"] = resolve_auth_headers(svc, name)
services["_timeout"] = svc.get("timeout")
return svc["url"], svc.get("api_key", ""), services
else:
raise click.ClickException(f"Multiple remote services configured, pick one with --server: {available}")
available = ", ".join(remote_services.keys())
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["_auth_headers"] = resolve_auth_headers(svc, name)
services["_timeout"] = svc.get("timeout")
return svc["url"], svc.get("api_key", ""), services
REMOTE_LIST_TTL = 300.0
@@ -603,11 +606,10 @@ def make_remote_service(
``apply_overrides`` False keeps the per-service ``remote_services.<name>.services`` overrides out of this
process's global config.
"""
url, api_key, live = resolve_server(server_name)
own = ci_get(live, service_tag)
# resolve_server hands back the live config dict; concurrent requests for other tags must not share it
url, api_key, services = resolve_server(server_name)
own = ci_get(services, service_tag)
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:
own = dict(own)
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
self.client.tunnel.stop()
self.save_returned_cache(response.get("cache") or {}, profile)
for result in response.get("results") or []:
yield SearchResult(
result["id"], result["title"], result.get("description"), result.get("label"), result.get("url")
)
with malformed_answer("search results"):
results = [
SearchResult(
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:
"""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:
"""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:
if self._session_id != session_id: # another thread already reopened it
@@ -1478,15 +1485,19 @@ class RemoteService(TitleSource):
def segment_filter(segment: Any) -> bool:
unwanted = self._segment_filters.get(track_id)
if unwanted is None:
server_id = self.server_track_id(track_id)
result = cast(
SegmentFilterReply,
self.session_call(
lambda sid: self.client.post_optional(
SEGMENT_FILTER_ROUTE.format(session_id=sid), SegmentFilterRequest(track_id=server_id)
try:
with quiet():
result = cast(
SegmentFilterReply,
self.session_call(
lambda sid: self.client.post_optional(
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 [])
self._segment_filters[track_id] = unwanted
return unwanted(segment)
@@ -1690,7 +1701,8 @@ class RemoteService(TitleSource):
if title_id not in self._chapters_by_title:
self.get_tracks(title)
raw = self._chapters_by_title.get(title_id, [])
return Chapters([Chapter(ch["timestamp"], ch.get("name")) for ch in raw])
with malformed_answer("chapters"):
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:
return self.proxy_license(challenge, track, "widevine")
@@ -1706,21 +1718,30 @@ class RemoteService(TitleSource):
track: AnyTrack,
) -> bytes | str | None:
# a missing certificate is legal (services may not use one), so a failed fetch continues without one
resp = cast(
LicenseReply,
self.session_call(
lambda sid: self.client.post_optional(
LICENSE_ROUTE.format(session_id=sid),
LicenseRequest(
track_id=self.server_track_id(track.id),
challenge=base64.b64encode(challenge).decode("ascii"),
drm_type="widevine",
is_certificate=True,
try:
with quiet():
resp = cast(
LicenseReply,
self.session_call(
lambda sid: self.client.post(
LICENSE_ROUTE.format(session_id=sid),
LicenseRequest(
track_id=self.server_track_id(track.id),
challenge=base64.b64encode(challenge).decode("ascii"),
drm_type="widevine",
is_certificate=True,
),
)
),
)
),
)
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:
"""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:
"""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:
with quiet():
resp = self.session_call(
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:
raise click.ClickException(e.message) from None
finally:
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}")
return str(url)
@@ -1832,7 +1853,13 @@ class RemoteService(TitleSource):
raise click.ClickException(e.message) from None
finally:
self.drain_server_logs()
return base64.b64decode(resp["license"])
try:
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:
# 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]
tags = Services.get_tags()
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:
tags.append(remote_tag)
return tags
+9 -4
View File
@@ -20,7 +20,7 @@ from typing import Any
from urllib.parse import urlencode, urlparse, urlsplit, urlunparse
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.cookies import create_cookie
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.
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
that fails writes ``body_error``, and the caller's own read raises the error. The duration stops at the
response headers.
text request body, except in a server process. A body read that fails writes ``body_error``, and the entry
then raises a requests read error again, because a second read of a cut chunked body returns what arrived
without an error. The duration stops at the response headers.
"""
debug_logger = get_debug_logger()
if not debug_logger or not debug_logger.enabled:
@@ -682,6 +682,7 @@ def record_request(
parts = urlsplit(url)
size: Any = None
received: dict[str, Any] = {}
read_error: RequestException | None = None
request_fields: dict[str, Any] = {}
if sent is not None and record_bodies:
try:
@@ -696,6 +697,8 @@ def record_request(
received = response_body(response, parts.path)
except Exception as e:
received = {"body_error": failure_reason(e)}
if isinstance(e, RequestException):
read_error = e
if not str(size).isdigit() and "body" in received:
size = len(response.content)
log_event(
@@ -713,6 +716,8 @@ def record_request(
duration_ms=None if duration is None else round(duration * 1000, 1),
failure=failure_reason(error) if error is not None else None,
)
if read_error is not None:
raise read_error
class RecordedAdapter: