mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-11-25 10:25:09 +00:00
refactor(remote): send every client call through RemoteClient
This commit is contained in:
@@ -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]
|
||||
|
||||
@@ -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
|
||||
@@ -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]
|
||||
@@ -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}
|
||||
|
||||
|
||||
|
||||
@@ -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] = {}
|
||||
|
||||
Reference in New Issue
Block a user