Files
unshackle/tests/remote/unit/test_serve_stop.py
T

306 lines
11 KiB
Python

"""What ends with a remote session: the work of a server that stops, and the cache that a service thread writes late.
A stop is a signal to a real ``serve`` process. The sessions of the late writes end on a server in this process.
"""
from __future__ import annotations
import asyncio
import contextlib
import json
import signal
import time
import uuid
from collections.abc import Callable, Iterator
from itertools import count
from pathlib import Path
from threading import Event
from types import SimpleNamespace
from typing import Any
import aiohttp
import pytest
from tests.remote.process import BOUND, posix, run, settings # noqa: F401
from tests.remote.unit.test_client_presence import get, logged_in, silent_for, store_token, sweep
from tests.remote.unit.test_remote_loopback import KEY, StubService, on_loop, server # noqa: F401
from tests.remote.unit.test_remote_service_helpers import blob
from tests.remote.unit.test_session_lifetime import ( # noqa: F401
DEADLINE,
create,
delete,
error_code,
in_thread,
logins,
sessions,
)
from tests.remote.unit.test_tunnel import wait_until
from unshackle.core.api import session_store
from unshackle.core.api.client_presence import AWAY_LIMIT
from unshackle.core.api.session_store import SessionEntry, SessionStore
from unshackle.core.config import config
from unshackle.core.remote_protocol import (
CHANNEL_ROUTE,
TITLES_ROUTE,
APIErrorCode,
AuthStatus,
)
pytestmark = [pytest.mark.unit, pytest.mark.process]
SERVES = {
"api-only": ["--api-only", "--remote-only"],
"with-cdm": ["--no-widevine", "--no-playready"],
}
SERVER = """
import asyncio, json, os, sys, time
from threading import Semaphore
import pytest
from aiohttp import web
from unshackle.core.config import config
config.__init__(**json.loads(sys.argv[1]))
from tests.remote.sessions import stub_service_build
from tests.remote.unit.test_remote_loopback import StubService
from unshackle.commands.serve import serve
from unshackle.core import services
from unshackle.core.api import events, handlers, routes
work = sys.argv[2]
def say(*line):
print(*line, flush=True)
class Stub(StubService):
def ask(self, part):
if part != work:
return
try:
if part == "cdm":
self._input_bridge.request_cdm({"op": "x"})
else:
self._input_bridge.request_input("Enter the EXAMPLE code")
except RuntimeError as e:
say("released", part, e)
raise
def authenticate(self, cookies, credential):
self.ask("login")
def get_titles(self):
self.ask("prompt")
self.ask("cdm")
return super().get_titles()
start, publish = web.TCPSite.start, events.bus.publish
async def started(site):
await start(site)
say("port", site._server.sockets[0].getsockname()[1])
def published(kind, data):
if kind == "session":
say("event", data["action"])
publish(kind, data)
async def hold(app):
say("stopping")
while work == "hold" and not (config.directories.temp / "release").exists():
await asyncio.sleep(0.01)
web.TCPSite.start = started
routes.close_event_streams = hold
events.bus.publish = published
patch = pytest.MonkeyPatch()
patch.setattr(services, "load_all", lambda: None)
patch.setattr(handlers, "validate_service", lambda service, request=None: service)
patch.setattr(handlers, "resolve_handler_proxy", lambda *args: (None, []))
patch.setattr(handlers, "server_account_for", lambda *args: False)
patch.setattr(handlers.Services, "load", lambda service: Stub)
stub_service_build(patch, lambda: Stub(Semaphore(0)))
class Leave:
def __del__(self, held=work == "leave", path=str(config.directories.temp / "release"), write=os.write,
access=os.access, sleep=time.sleep):
write(1, b"leaving\\n")
while held and not access(path, 0):
sleep(0.01)
sys.leave = Leave()
serve(args=["-q", "-h", "127.0.0.1", "-p", "0", *sys.argv[3:]])
"""
class Serve:
"""A ``serve`` process whose output goes to a file."""
def __init__(self, run: Callable[..., Any], path: Path, work: str, options: list[str]) -> None: # noqa: F811
path.mkdir()
self.sessions = path / "cache" / "_sessions"
self.log = path / "serve.log"
self.release = path / "temp" / "release"
data = {"serve": {"api_secret": KEY}, "update_checks": False, "directories": settings("", path)["directories"]}
with self.log.open("w", encoding="utf-8") as log:
self.process = run("-c", SERVER, json.dumps(data), work, *options, stdout=log)
assert wait_until(lambda: "port " in self.output or self.process.poll() is not None, DEADLINE)
assert self.process.poll() is None, self.output
self.url = f"http://127.0.0.1:{self.output.split('port ')[1].split()[0]}"
@property
def output(self) -> str:
return self.log.read_text(encoding="utf-8", errors="replace")
def send(self, *signals: signal.Signals) -> None:
for one in signals:
self.process.send_signal(one)
def says(self, line: str) -> bool:
return wait_until(lambda: line in self.output, DEADLINE)
def ended_well(self) -> None:
"""The process ends at once with code 0, has removed each session cache, and logs no unhandled exception."""
since = time.monotonic()
assert self.process.wait(DEADLINE) == 0, self.output
assert time.monotonic() - since < BOUND
assert not list(self.sessions.rglob("*")), self.output
for trace in ("nhandled exception", "InvalidStateError", "never retrieved", "was destroyed"):
assert trace not in self.output
@pytest.fixture
def serve(tmp_path: Path, run: Callable[..., Any]) -> Callable[..., Serve]: # noqa: F811
paths = (tmp_path / str(n) for n in count())
return lambda work="", options=SERVES["api-only"]: Serve(run, next(paths), work, options)
def session_id() -> str:
return str(uuid.uuid4())
async def opened(http: aiohttp.ClientSession, running: Serve, until: str) -> tuple[str, Any]:
"""A remote session with a login cache on the server, and its channel once a message of the type *until* came."""
sid = session_id()
reply = await asyncio.to_thread(create, running.url, sid, cache={"token": blob('"EXAMPLE"')})
assert reply.status_code == 200, reply.text
socket = await http.ws_connect(running.url + CHANNEL_ROUTE.format(session_id=sid))
await read_until(socket, until)
return sid, socket
async def read_until(socket: Any, kind: str) -> None:
while (message := await socket.receive_json(timeout=DEADLINE)).get("type") != kind:
pass
if kind == "status":
while message["status"] != AuthStatus.AUTHENTICATED:
message = await socket.receive_json(timeout=DEADLINE)
@pytest.fixture
def entry(
server: SimpleNamespace, # noqa: F811
logins: list[Any], # noqa: F811
monkeypatch: pytest.MonkeyPatch,
) -> SessionEntry:
"""A remote session with a login cache."""
monkeypatch.setitem(config.serve, "session_ttl", 300)
assert create(server.url, session_id(), cache={"token": blob('"EXAMPLE"')}).status_code == 200
(entry,) = sessions()
assert logged_in(entry)
entry.presence.attached()
return entry
@pytest.fixture
def titles(server: SimpleNamespace, entry: SessionEntry) -> Iterator[SimpleNamespace]: # noqa: F811
"""A titles call that waits for ``release``, and then writes the login cache again."""
held = SimpleNamespace(directory=config.directories.cache / str(entry.cache_tag), started=Event(), release=Event())
def write_late(stub: StubService) -> None:
held.started.set()
assert held.release.wait(DEADLINE), "the test did not release the titles"
store_token(entry)
StubService.hooks["titles"] = write_late
held.reply = in_thread(lambda: get(server, TITLES_ROUTE, entry))
assert held.started.wait(DEADLINE)
try:
yield held
finally:
held.release.set()
def end_by_delete(server: SimpleNamespace, entry: SessionEntry) -> None: # noqa: F811
assert delete(server.url, entry.session_id).status_code == 200
def end_by_eviction(server: SimpleNamespace, entry: SessionEntry) -> None: # noqa: F811
config.serve["max_sessions"] = 1
assert create(server.url, session_id()).status_code == 200
def end_by_a_client_that_is_gone(server: SimpleNamespace, entry: SessionEntry) -> None: # noqa: F811
entry.presence.detached(left=False)
silent_for(entry, AWAY_LIMIT + 1)
assert sweep(server) == 1
def end_by_a_new_create_of_the_id(server: SimpleNamespace, entry: SessionEntry) -> None: # noqa: F811
assert create(server.url, entry.session_id, cache={"token": blob('"EXAMPLE"')}).status_code == 200
ENDS = [end_by_delete, end_by_eviction, end_by_a_client_that_is_gone, end_by_a_new_create_of_the_id]
@pytest.mark.parametrize(("cache_tag", "busy"), [("_sessions/EXAMPLE", False), (None, True)], ids=["idle", "no-cache"])
async def test_an_end_with_nothing_to_write_late_starts_no_task(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, cache_tag: str | None, busy: bool
) -> None:
monkeypatch.setattr(config.directories, "cache", tmp_path)
store = SessionStore()
entry = await store.create("EXAMPLE", None, cache_tag=cache_tag)
if busy:
await entry.lock.acquire()
assert await store.delete(entry.session_id) and not store._logins
@pytest.mark.parametrize("error", [None, RuntimeError, SystemExit], ids=["answers", "fails", "exits"])
@pytest.mark.parametrize(("call", "args"), [("request_input", ["code?"]), ("request_cdm", [{}]), ("ensure_active", [])])
def test_a_request_that_the_end_cuts_is_refused(
server: SimpleNamespace, # noqa: F811
entry: SessionEntry,
call: str,
args: list[Any],
error: type[BaseException] | None,
) -> None:
"""Also when the service goes on without the answer of its client, or exits."""
def ask(stub: StubService) -> None:
on_loop(server, session_store.get_session_store().delete(entry.session_id))
with contextlib.suppress(RuntimeError):
getattr(stub._input_bridge, call)(*args)
if error:
raise error(1)
StubService.hooks["titles"] = ask
assert error_code(get(server, TITLES_ROUTE, entry)) == APIErrorCode.SESSION_NOT_FOUND
@pytest.mark.parametrize("ended", [True, False], ids=["ended", "open"])
@pytest.mark.parametrize("error", [RuntimeError("EXAMPLE failed"), SystemExit(1)], ids=["error", "exit"])
def test_an_error_of_the_service_stays_that_error(
server: SimpleNamespace, # noqa: F811
entry: SessionEntry,
error: BaseException,
ended: bool,
) -> None:
def fail(stub: StubService) -> None:
if ended:
on_loop(server, session_store.get_session_store().delete(entry.session_id))
raise error
StubService.hooks["titles"] = fail
reply = get(server, TITLES_ROUTE, entry)
if isinstance(error, SystemExit):
assert error_code(reply) == APIErrorCode.SERVICE_ERROR
else:
assert error_code(reply) == APIErrorCode.INTERNAL_ERROR and "EXAMPLE failed" in reply.json()["message"]