diff --git a/docs/dev/rest-api/authentication.md b/docs/dev/rest-api/authentication.md index 15c44a12..13c3b181 100644 --- a/docs/dev/rest-api/authentication.md +++ b/docs/dev/rest-api/authentication.md @@ -236,6 +236,8 @@ The CORS headers expose these headers and `Retry-After` to a browser client. A `--remote` client that gets a `429` with `Retry-After` shows a countdown, waits that time (one hour at most), and then sends the request again. It stops after 3 waits for one request. +The keep-alive, the poll for CDM calls, the health check and the drain check do not wait: each +tries again at its next interval. !!! warning "`429` is not the `RATE_LIMITED` error body" `RATE_LIMITED` in [Errors](errors.md) is a *service* rate limit that a handler raises, and it diff --git a/docs/reference/configuration/services.md b/docs/reference/configuration/services.md index 41c44d84..76fa5d2d 100644 --- a/docs/reference/configuration/services.md +++ b/docs/reference/configuration/services.md @@ -126,7 +126,8 @@ your choice, and with a service option that runs the remote session on the serve `auth_headers` lists extra header names to send the API key in, tried before the defaults `X-Secret-Key` and `X-Api-Key`, which unshackle always appends as fallbacks. It sends the first name. If the server answers `401`, it retries the same request with the next name, and -keeps the one that works for the rest of the HTTP session. Names you give keep your spelling and +keeps the one that works for the rest of the HTTP session. After a request succeeds, a `401` +no longer moves the API key to another name. Names you give keep your spelling and are not repeated in the fallbacks, so unshackle tries `auth_headers: ["Authorization", "x-secret-key"]` as `Authorization`, `x-secret-key`, `X-Api-Key`. diff --git a/tests/remote/unit/test_remote_client.py b/tests/remote/unit/test_remote_client.py index c54bf2f7..d47ffc8b 100644 --- a/tests/remote/unit/test_remote_client.py +++ b/tests/remote/unit/test_remote_client.py @@ -3,9 +3,11 @@ from __future__ import annotations import json +import logging import click import pytest +import requests import responses from unshackle.core.remote_service import RemoteClient @@ -335,3 +337,47 @@ def test_the_429_wait_gives_up_after_its_tries(client: RemoteClient, monkeypatch with pytest.raises(SystemExit): client.get("/api/services") assert waits == [1] * remote_service.RATE_LIMIT_TRIES + + +@responses.activate +def test_a_401_after_a_header_worked_keeps_that_header(client: RemoteClient) -> None: + responses.add(responses.GET, "http://srv:8786/api/services", json={"services": []}) + responses.add(responses.GET, "http://srv:8786/api/health", status=401, json={"message": "Secret Key is Invalid."}) + responses.add(responses.GET, "http://srv:8786/api/health", json={"status": "ok"}) + + client.get("/api/services") + assert client.probe("/api/health") == {} + assert client.probe("/api/health") == {"status": "ok"} + assert client.session.headers.get("X-Secret-Key") == "secret-xyz" + + +@responses.activate +def test_a_probe_does_not_wait_out_a_429(client: RemoteClient, monkeypatch: pytest.MonkeyPatch) -> None: + waits: list[int] = [] + monkeypatch.setattr("unshackle.core.remote_service.wait_retry_after", waits.append) + responses.add(responses.GET, "http://srv:8786/api/session/s1", status=429, headers={"Retry-After": "5"}, json={}) + + assert client.probe("/api/session/s1") == {} + assert not waits + + +@responses.activate +def test_a_probe_reads_a_gateway_page_as_the_request_does( + client: RemoteClient, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setattr("unshackle.core.remote_service.time.sleep", lambda _s: None) + url = "http://srv:8786/api/health" + responses.add(responses.GET, url, body=PROXY_502, status=502, content_type="text/html") + responses.add(responses.GET, url, json={"status": "ok"}) + + assert client.probe("/api/health") == {"status": "ok"} + responses.replace(responses.GET, url, body=PROXY_502, status=502, content_type="text/html") + assert client.probe("/api/health") == {} + + +@responses.activate +def test_a_probe_that_cannot_connect_logs_no_error(client: RemoteClient, caplog: pytest.LogCaptureFixture) -> None: + responses.add(responses.GET, "http://srv:8786/api/health", body=requests.ConnectionError("refused")) + + assert client.probe("/api/health") == {} + assert not [r for r in caplog.records if r.levelno >= logging.WARNING] diff --git a/tests/remote/unit/test_remote_loopback.py b/tests/remote/unit/test_remote_loopback.py new file mode 100644 index 00000000..75237dce --- /dev/null +++ b/tests/remote/unit/test_remote_loopback.py @@ -0,0 +1,195 @@ +"""The real remote client against the real server routes, over HTTP on a loopback port.""" + +from __future__ import annotations + +import asyncio +import logging +from threading import Semaphore, Thread +from types import SimpleNamespace +from typing import Any, Iterator + +import click +import pytest +import requests +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.api import handlers, routes, session_store +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.config import config +from unshackle.core.remote_protocol import 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 +from unshackle.core.tracks.track import Track + +pytestmark = pytest.mark.unit + +KEY = "loopback-key" +CODE = "1234" + + +class StubService: + """The server side of the remote session: a login that asks for a code, three titles, one audio track each.""" + + logins = 0 + + def __init__(self, beats: Semaphore) -> None: + self.beats = beats + self.log = logging.getLogger("stub-server") + self.session = requests.Session() + self.cache = None + self._input_bridge: Any = None + StubService.logins += 1 + self.login = StubService.logins + + def authenticate(self, cookies: Any, credential: Any) -> None: + if self._input_bridge.request_input("Enter the EXAMPLE code") != CODE: + raise ValueError("wrong code") + self.log.info(f"Logged in to EXAMPLE, login {self.login}") + + def get_titles(self) -> Movies: + return Movies( + [Movie(id_=f"example-{n}", service=StubService, name=f"Example {n}", year=2024) for n in (1, 2, 3)] + ) + + def get_tracks(self, title: Movie) -> Tracks: + """Answer after the route sent its first heartbeat, so every tracks call outlasts one interval.""" + assert self.beats.acquire(timeout=10), "the tracks route sent no heartbeat" + if title.id == "example-3": + raise ValueError("No tracks for OTHER region") + audio = Audio( + url=f"https://cdn.example/{title.id}.m4a", + language=Language.get("en"), + descriptor=Track.Descriptor.URL, + codec=Audio.Codec.AAC, + bitrate=128_000, + channels=2, + id_=f"{title.id}-login{self.login}", + ) + return Tracks([audio]) + + def get_chapters(self, title: Movie) -> Chapters: + return Chapters() + + def decrypts_samples(self, track: Any) -> bool: + return False + + +@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.""" + beats = Semaphore(0) + seen: list[tuple[str, str, int]] = [] + + class CountedHeartbeat(web.StreamResponse): + """Count the first heartbeat of each tracks request; aiohttp calls prepare again when the handler returns.""" + + async def prepare(self, request: web.BaseRequest) -> Any: + first = not self.prepared + writer = await super().prepare(request) + if first and request.path.endswith("/tracks"): + beats.release() + return writer + + @web.middleware + async def record(request: web.Request, handler: Any) -> web.StreamResponse: + response = await handler(request) + seen.append((request.method, request.path, response.status)) + return response + + StubService.logins = 0 + 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_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", {}) + monkeypatch.setattr(config.directories, "cache", tmp_path / "cache") + monkeypatch.setattr(config.directories, "cookies", tmp_path / "cookies") + monkeypatch.setattr(handlers, "validate_service", lambda service, request=None: service) + monkeypatch.setattr(handlers, "resolve_handler_proxy", lambda *args: (None, [])) + monkeypatch.setattr(handlers, "server_account_for", lambda *args: False) + monkeypatch.setattr(handlers.Services, "load", lambda service: StubService) + monkeypatch.setattr(handlers, "create_service_instance", lambda *a, **k: (StubService(beats), None, None)) + + app = web.Application(middlewares=[record, cors_middleware, no_5xx_middleware, api_key_authentication]) + app["config"] = {"users": [KEY]} + setup_routes(app, remote_only=True) + loop = asyncio.new_event_loop() + runner = web.AppRunner(app) + loop.run_until_complete(runner.setup()) + site = web.TCPSite(runner, "127.0.0.1", 0) + loop.run_until_complete(site.start()) + thread = Thread(target=loop.run_forever, daemon=True) + thread.start() + host, port = runner.addresses[0][:2] + try: + yield SimpleNamespace(url=f"http://{host}:{port}", loop=loop, seen=seen) + finally: + asyncio.run_coroutine_threadsafe(runner.cleanup(), loop).result(10) + loop.call_soon_threadsafe(loop.stop) + thread.join(10) + loop.close() + + +def make_client(url: str) -> 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=[]) + parent = click.Context(click.Command("dl"), obj=obj) + parent.params = {"no_proxy": True} + ctx = click.Context(click.Command("EXAMPLE"), parent=parent, obj=obj) + service = RemoteService(ctx, "EXAMPLE", "example-1", url, KEY, {"_auth_headers": ["X-Api-Key", "X-Secret-Key"]}) + service._input_bridge = SimpleNamespace(request_input=lambda prompt: CODE) + return service + + +def forget(server: SimpleNamespace, session_id: str) -> None: + """Drop the session on the server, as a restart does.""" + store = session_store.get_session_store() + 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) + service = make_client(server.url) + try: + service.authenticate() + first = service._session_id + assert first + assert server.seen[0] == ("POST", "/api/session/create", 401) + assert ("GET", f"/api/session/{first}/prompt", 200) in server.seen + 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) + assert wait_until(lambda: len([s for s in server.seen if s[:2] == ("GET", info)]) >= 2, 10) + + titles = service.get_titles() + assert [str(t.id) for t in titles] == ["example-1", "example-2", "example-3"] + m1, m2, m3 = titles + assert [str(t.id) for t in service.get_tracks(m1).audio] == ["example-1-login1"] + + forget(server, first) + assert [str(t.id) for t in service.get_tracks(m2).audio] == ["example-2-login2"] + assert service._session_id not in (None, first) + assert "The remote session was lost, opening a new one" in caplog.messages + + with pytest.raises(RemoteError) as late: + service.get_tracks(m3) + assert late.value.kind not in (APIErrorCode.SESSION_NOT_FOUND, "UNKNOWN") + assert not late.value.session_broke + assert [s for s in server.seen if s[1].endswith("/tracks")][-1][2] == 200 + finally: + second = service._session_id + service.close() + assert service._keepalive_stop.is_set() + assert ("DELETE", SESSION_ROUTE.format(session_id=second), 200) in server.seen + assert not session_store.get_session_store()._sessions diff --git a/tests/remote/unit/test_remote_probes.py b/tests/remote/unit/test_remote_probes.py new file mode 100644 index 00000000..10e1b9a6 --- /dev/null +++ b/tests/remote/unit/test_remote_probes.py @@ -0,0 +1,137 @@ +"""The background and probe calls of a remote session go through RemoteClient and so rotate the auth header.""" + +from __future__ import annotations + +import json +from threading import Event, Thread +from typing import Any, Callable + +import pytest +import responses + +from tests.remote.unit.test_session_reopen import SERVER, make_service +from unshackle.core import remote_service +from unshackle.core.remote_protocol import ClientErrorKind +from unshackle.core.remote_service import RemoteClient + +pytestmark = pytest.mark.unit + +KEY = "k" + + +@pytest.fixture(autouse=True) +def no_reopen_wait(monkeypatch: pytest.MonkeyPatch) -> None: + """Give up on the first unanswered health probe, so a regression fails fast instead of waiting 30 minutes.""" + monkeypatch.setattr(remote_service, "REOPEN_WAIT", 0.0) + + +def second_header_only(body: dict, hit: Callable[[], None] = lambda: None) -> Callable[[Any], tuple]: + """A route that refuses the first candidate header, as a server that reads only X-Api-Key does.""" + + def answer(request: Any) -> tuple: + if request.headers.get("X-Api-Key") != KEY: + return 401, {}, json.dumps({"status": 401, "message": "Secret Key is Invalid."}) + hit() + return 200, {"Content-Type": "application/json"}, json.dumps(body) + + return answer + + +@responses.activate +def test_wait_for_server_moves_to_the_next_auth_header() -> None: + service = make_service() + responses.add_callback(responses.GET, f"{SERVER}/api/health", callback=second_header_only({"status": "ok"})) + + assert service.wait_for_server(accepting=True) + assert [c.response.status_code for c in responses.calls] == [401, 200] + + +@responses.activate +def test_recover_moves_to_the_next_auth_header() -> None: + service = make_service() + responses.add(responses.GET, f"{SERVER}/api/health", json={"status": "ok"}) + responses.add_callback(responses.GET, f"{SERVER}/api/session/s1", callback=second_header_only({"valid": True})) + + assert service.recover("s1", ClientErrorKind.CONNECT) + assert service._session_id == "s1" + + +@responses.activate +def test_server_draining_moves_to_the_next_auth_header() -> None: + service = make_service() + responses.add_callback(responses.GET, f"{SERVER}/api/session/s1", callback=second_header_only({"draining": True})) + + assert service.server_draining() + + +@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}) + 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() + try: + assert pinged.wait(5) + finally: + service._keepalive_stop.set() + 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() + 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) + 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.start() + try: + assert stop.wait(5) + finally: + stop.set() + poller.join(5) + assert answered == [call] + + +@responses.activate +def test_recover_waits_out_a_429_instead_of_reopening(monkeypatch: pytest.MonkeyPatch) -> None: + waits: list[int] = [] + monkeypatch.setattr(remote_service, "wait_retry_after", lambda seconds, *args: waits.append(seconds)) + service = make_service() + responses.add(responses.GET, f"{SERVER}/api/health", json={"status": "ok"}) + url = f"{SERVER}/api/session/s1" + responses.add(responses.GET, url, status=429, headers={"Retry-After": "5"}, json={}) + responses.add(responses.GET, url, json={"valid": True}) + + assert service.recover("s1", ClientErrorKind.CONNECT) + assert waits == [5] + assert service._session_id == "s1" + + +@responses.activate +def test_a_tunnel_copies_the_auth_header_the_server_reads(monkeypatch: pytest.MonkeyPatch) -> None: + sent: list[dict] = [] + + class Tunnel: + def __init__(self, url: str, headers: dict, proxy: Any) -> None: + sent.append(headers) + + def start(self) -> str: + return "t1" + + monkeypatch.setattr(remote_service, "TunnelClient", Tunnel) + client = RemoteClient(server_url=SERVER, api_key=KEY) + responses.add_callback(responses.GET, f"{SERVER}/api/health", callback=second_header_only({"status": "ok"})) + + remote_service.start_tunnel(client) + + assert sent[0].get("X-Api-Key") == KEY and "X-Secret-Key" not in sent[0] diff --git a/tests/remote/unit/test_remote_protocol.py b/tests/remote/unit/test_remote_protocol.py index f8c93335..04c5c3c0 100644 --- a/tests/remote/unit/test_remote_protocol.py +++ b/tests/remote/unit/test_remote_protocol.py @@ -16,7 +16,14 @@ from unshackle.core.api import routes from unshackle.core.api.handlers import SESSION_TRANSPORT_KEYS ROUTE_NAMES = {name for name in vars(protocol) if name.endswith("_ROUTE")} -CLIENT_METHODS = {"get": "GET", "get_optional": "GET", "post": "POST", "post_optional": "POST", "delete": "DELETE"} +CLIENT_METHODS = { + "get": "GET", + "get_optional": "GET", + "probe": "GET", + "post": "POST", + "post_optional": "POST", + "delete": "DELETE", +} SERVED = {(method, path): handler for method, path, handler, _ in routes.ROUTES} diff --git a/tests/remote/unit/test_remote_search.py b/tests/remote/unit/test_remote_search.py index d5a7a65b..fb77594d 100644 --- a/tests/remote/unit/test_remote_search.py +++ b/tests/remote/unit/test_remote_search.py @@ -16,6 +16,7 @@ pytestmark = pytest.mark.unit class FakeClient: server_url = "https://server.example" + _auth_header_found = True def __init__(self) -> None: self.sent: dict[str, Any] = {} diff --git a/tests/test_client_session_auth.py b/tests/test_client_session_auth.py index 60fede74..aa98e7a9 100644 --- a/tests/test_client_session_auth.py +++ b/tests/test_client_session_auth.py @@ -128,7 +128,7 @@ def test_remote_get_tracks_scopes_server_cookies(): _session_id="s", service_tag="EXAMPLE", log=logging.getLogger("test"), - client=SimpleNamespace(post=lambda path, body: {"session_cookie_jar": jar}), + client=SimpleNamespace(post=lambda path, body: {"session_cookie_jar": jar}, probe=lambda endpoint: {}), drain_server_logs=lambda: None, ) service.get_tracks(SimpleNamespace(id="t1")) diff --git a/unshackle/core/remote_service.py b/unshackle/core/remote_service.py index d126ff76..c1c161b1 100644 --- a/unshackle/core/remote_service.py +++ b/unshackle/core/remote_service.py @@ -111,6 +111,8 @@ RETRY_AFTER_MAX = 3600 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 @@ -209,6 +211,8 @@ class RemoteClient: self.api_key = api_key self.auth_headers = list(auth_headers) if auth_headers else list(DEFAULT_AUTH_HEADERS) self._auth_header_index = 0 + self._auth_header_lock = Lock() + self._auth_header_found = False self._session: Optional[requests.Session] = None self.tunnel: Optional[TunnelClient] = None # wraps every request, so the service's CDM calls get answered while the server runs its code @@ -226,14 +230,18 @@ class RemoteClient: return self._session def next_auth_header(self) -> bool: - """Move the api key onto the next candidate header. False when no candidate header remains.""" - if not self.api_key or self._auth_header_index + 1 >= len(self.auth_headers): - return False + """Move the API key onto the next candidate header. False when no candidate header remains. + + Also False once a foreground call succeeded with the current header: a later 401 is about the API key itself. + """ session = self.session - session.headers.pop(self.auth_headers[self._auth_header_index], None) - self._auth_header_index += 1 - session.headers[self.auth_headers[self._auth_header_index]] = self.api_key - return True + with self._auth_header_lock: + if self._auth_header_found or not self.api_key or self._auth_header_index + 1 >= len(self.auth_headers): + return False + session.headers.pop(self.auth_headers[self._auth_header_index], None) + self._auth_header_index += 1 + session.headers[self.auth_headers[self._auth_header_index]] = self.api_key + return True def request( self, @@ -248,47 +256,18 @@ class RemoteClient: A raw ``body`` goes as ``application/octet-stream``, and a binary answer comes back under ``"body"``. """ - url = f"{self.server_url}{endpoint}" payload: Dict[str, Any] = ( {"json": data} if body is None else {"data": body, "headers": {"Content-Type": "application/octet-stream"}} ) - gateway_retried = False - rate_waits = 0 - while True: - try: - with self.in_flight(endpoint): - resp = getattr(self.session, method)(url, timeout=self.timeout, **payload) - except requests.ConnectionError as e: - if isinstance(e.args[0] if e.args else None, urllib3.exceptions.ReadTimeoutError): - raise self.timed_out(endpoint) from None - server_url = safe_display_url(self.server_url) - raise RemoteError( - f"Could not connect to remote server at {server_url}", ClientErrorKind.CONNECT - ) from None - except requests.Timeout: + try: + resp = self.send(method, endpoint, self.timeout, **payload) + except requests.ConnectionError as e: + if isinstance(e.args[0] if e.args else None, urllib3.exceptions.ReadTimeoutError): raise self.timed_out(endpoint) from None - # servers differ on which header carries the key, so retry the rest before giving up - if resp.status_code == 401 and self.next_auth_header(): - continue - if ( - resp.status_code == 429 - and rate_waits < RATE_LIMIT_TRIES - and (retry_after := parse_retry_after(resp.headers.get("Retry-After"))) - ): - rate_waits += 1 - wait_retry_after(retry_after) - continue - # a proxy HTML page, not the server's JSON, means a dropped tunnel stream, which one retry gets past - if ( - resp.status_code in (502, 503, 504) - and not gateway_retried - and "json" not in resp.headers.get("Content-Type", "") - ): - gateway_retried = True - log.debug(f"HTTP {resp.status_code} from the proxy in front of the server on {endpoint}, retrying once") - time.sleep(1) - continue - break + server_url = safe_display_url(self.server_url) + 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 if resp.status_code < 400 and "octet-stream" in resp.headers.get("Content-Type", ""): return {"body": resp.content} try: @@ -319,6 +298,56 @@ class RemoteClient: raise RemoteError(f"Server error [{error_code}]: {error_msg}", error_code) return detail + def send( + self, method: str, endpoint: str, timeout: float, background: bool = False, **kwargs: Any + ) -> requests.Response: + """Send one request through the ``in_flight`` hook and return the response; ``requests`` raises its own errors. + + A 401 moves the API key to the next candidate header, a gateway's error page goes once more, and a 429 with + Retry-After waits on the console. A ``background`` call skips the hook and the 429 wait. + """ + url = f"{self.server_url}{endpoint}" + gateway_retried = False + rate_waits = 0 + while True: + with contextlib.nullcontext() if background else self.in_flight(endpoint): + resp = getattr(self.session, method)(url, timeout=timeout, **kwargs) + # servers differ on which header carries the key, so retry the rest before giving up + if resp.status_code == 401 and self.next_auth_header(): + continue + if ( + not background + and resp.status_code == 429 + and rate_waits < RATE_LIMIT_TRIES + and (retry_after := parse_retry_after(resp.headers.get("Retry-After"))) + ): + rate_waits += 1 + wait_retry_after(retry_after) + continue + # a proxy HTML page, not the server's JSON, means a dropped tunnel stream, which one retry gets past + if ( + resp.status_code in (502, 503, 504) + and not gateway_retried + and "json" not in resp.headers.get("Content-Type", "") + ): + gateway_retried = True + log.debug(f"HTTP {resp.status_code} from the proxy in front of the server on {endpoint}, retrying once") + time.sleep(1) + continue + if not background and resp.status_code < 400: + self._auth_header_found = True + return resp + + def probe(self, endpoint: str, background: bool = True) -> Dict[str, Any]: + """GET a route with a short timeout: the JSON body, or an empty dict when the call fails. Never logs an error.""" + try: + resp = self.send("get", endpoint, PROBE_TIMEOUT, background=background) + body = resp.json() if resp.ok else {} + except (requests.RequestException, ValueError) as e: + log.debug(f"Probe of {endpoint} failed: {e}") + return {} + return body if isinstance(body, dict) else {} + def timed_out(self, endpoint: str) -> RemoteError: return RemoteError( f"Request to remote server timed out after {self.timeout}s: {endpoint}", @@ -638,9 +667,14 @@ def resolve_remote_proxy_arg(proxy_arg: str, providers: Optional[list] = None) - 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.""" + ``proxy`` from this machine. + + A health probe comes first, so the tunnel copies the auth header that the server reads. + """ if proxy and (scheme := urlsplit(proxy).scheme.lower()) not in PROXY_PORTS: 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"} slot_deadline = time.monotonic() + RETRY_AFTER_MAX rate_waits = 0 @@ -1212,16 +1246,13 @@ class RemoteService: 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, 5.0) - url = self.client.server_url + 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): - try: - self.client.session.get(url, timeout=30) - except requests.RequestException: - pass + self.client.probe(endpoint) Thread(target=ping, name=f"{self.service_tag}-keepalive", daemon=True).start() @@ -1253,11 +1284,9 @@ class RemoteService: return self._session_id is not None if session_id is None or not self.wait_for_server(accepting=False): return False - url = self.client.server_url + SESSION_ROUTE.format(session_id=session_id) - try: - alive = kind != ClientErrorKind.TUNNEL_CLOSED and self.client.session.get(url, timeout=30).ok - except requests.RequestException: - alive = False + alive = kind != ClientErrorKind.TUNNEL_CLOSED and bool( + self.client.probe(SESSION_ROUTE.format(session_id=session_id), background=False) + ) if alive: return kind == ClientErrorKind.CONNECT self.log.warning("The remote session was lost, opening a new one") @@ -1269,12 +1298,9 @@ class RemoteService: delay = 1.0 warned = False while True: - try: - health = self.client.session.get(self.client.server_url + HEALTH_ROUTE, timeout=30).json() - if health.get("status") == "ok" and not (accepting and health.get("draining")): - return True - except (requests.RequestException, ValueError, AttributeError): - pass + health = self.client.probe(HEALTH_ROUTE) + if health.get("status") == "ok" and not (accepting and health.get("draining")): + return True if time.monotonic() >= deadline: return False if not warned: @@ -1345,13 +1371,10 @@ 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.""" - try: - url = self.client.server_url + SESSION_ROUTE.format(session_id=self._session_id) - return bool( - self._session_id and cast(SessionInfo, self.client.session.get(url, timeout=30).json()).get("draining") - ) - except (requests.RequestException, ValueError, AttributeError): + 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")) def server_track_id(self, track_id: Any) -> str: """The id the current remote session knows the track with this client id by.""" @@ -1479,11 +1502,11 @@ class RemoteService: self._cdm_stop.set() def poll_cdm_calls(self, stop: Event, interval: float = 0.5) -> None: - url = self.client.server_url + PROMPT_ROUTE.format(session_id=self._session_id) + endpoint = PROMPT_ROUTE.format(session_id=self._session_id) sessions: Dict[str, bytes] = {} while not stop.wait(interval): try: - call = cast(PromptReply, self.client.session.get(url, timeout=30).json()).get("cdm_call") + call = cast(PromptReply, self.client.probe(endpoint)).get("cdm_call") if isinstance(call, dict): with quiet(): self.answer_cdm_call(call, sessions)