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

438 lines
17 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 aiohttp import web
from tests.remote.unit.test_client_presence import close_code, get, logged_in, silent_for, store_token, sweep
from tests.remote.unit.test_process_exit import BOUND, posix, run, settings # noqa: F401
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.events import bus
from unshackle.core.api.session_channel import close_channels
from unshackle.core.api.session_store import SessionEntry, SessionStore
from unshackle.core.config import config
from unshackle.core.remote_protocol import (
CHANNEL_ROUTE,
CHANNEL_SESSION_GONE,
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)
@posix
@pytest.mark.parametrize("work", ["login", "prompt", "cdm"])
async def test_a_stop_ends_the_work_that_waits_for_its_client(serve: Callable[..., Serve], work: str) -> None:
"""The refusal of the open request, and the close code of the channel, make the client open a new session."""
running = serve(work)
async with aiohttp.ClientSession(headers={"X-Secret-Key": KEY}) as http:
sid, socket = await opened(http, running, "prompt" if work == "login" else "status")
titles = None
if work != "login":
titles = asyncio.create_task(http.get(running.url + TITLES_ROUTE.format(session_id=sid)))
await read_until(socket, "cdm_call" if work == "cdm" else "prompt")
assert list(running.sessions.rglob("token.json"))
closed = asyncio.create_task(close_code(socket))
running.send(signal.SIGTERM)
await asyncio.to_thread(running.ended_well)
assert await closed == CHANNEL_SESSION_GONE
if titles:
reply = await titles
assert (reply.status, (await reply.json())["error_code"]) == (404, APIErrorCode.SESSION_NOT_FOUND)
assert f"released {work} Session was cancelled" in running.output
assert "event delete" not in running.output
assert "Closed 1 remote session(s) at shutdown" in running.output
@posix
@pytest.mark.parametrize("options", SERVES.values(), ids=SERVES)
async def test_two_sigterms_at_once_do_not_cut_the_stop(serve: Callable[..., Serve], options: list[str]) -> None:
for _ in range(3):
running = serve(options=options)
async with aiohttp.ClientSession(headers={"X-Secret-Key": KEY}) as http:
sockets = [(await opened(http, running, "status"))[1] for _ in range(4)]
closed = [asyncio.create_task(close_code(socket)) for socket in sockets]
running.send(signal.SIGTERM, signal.SIGTERM)
await asyncio.to_thread(running.ended_well)
assert await asyncio.gather(*closed) == [CHANNEL_SESSION_GONE] * 4
assert "Closed 4 remote session(s) at shutdown" in running.output
@posix
@pytest.mark.parametrize(("work", "line"), [("hold", "stopping"), ("leave", "leaving")], ids=["stop", "exit"])
async def test_a_sigterm_after_the_first_does_not_cut_the_stop(
serve: Callable[..., Serve], work: str, line: str
) -> None:
running = serve(work)
async with aiohttp.ClientSession(headers={"X-Secret-Key": KEY}) as http:
await opened(http, running, "status")
running.send(signal.SIGTERM)
assert running.says(line)
running.send(signal.SIGTERM)
running.release.parent.mkdir(exist_ok=True)
running.release.touch()
await asyncio.to_thread(running.ended_well)
@posix
def test_a_second_ctrl_c_still_forces_the_stop(serve: Callable[..., Serve]) -> None:
running = serve("hold")
running.send(signal.SIGINT)
assert running.says("stopping")
running.send(signal.SIGINT)
assert running.process.wait(DEADLINE) == 1
@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)
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("end", ENDS)
def test_a_late_write_of_a_service_thread_leaves_no_cache(
server: SimpleNamespace, # noqa: F811
entry: SessionEntry,
titles: SimpleNamespace,
end: Callable[[SimpleNamespace, SessionEntry], None],
) -> None:
"""The removal comes after the last request: one that waits behind the writer is refused and writes nothing."""
waiting = in_thread(lambda: get(server, TITLES_ROUTE, entry))
assert wait_until(lambda: len(entry.lock._waiters or ()) == 1, DEADLINE)
end(server, entry)
assert wait_until(lambda: not titles.directory.exists(), DEADLINE)
titles.release.set()
assert titles.reply().status_code == 200
assert error_code(waiting()) == APIErrorCode.SESSION_NOT_FOUND
assert wait_until(lambda: not session_store.get_session_store()._logins, DEADLINE)
assert not titles.directory.exists()
if end is end_by_a_new_create_of_the_id:
(new,) = sessions()
assert (config.directories.cache / str(new.cache_tag) / "token.json").exists()
def test_the_dashboard_gets_one_delete_event_and_no_update_after_it(
server: SimpleNamespace, # noqa: F811
entry: SessionEntry,
titles: SimpleNamespace,
) -> None:
"""A stop ends the work before the store retires the session, so each end runs twice."""
seq = bus.seq
on_loop(server, close_channels(web.Application()))
end_by_delete(server, entry)
titles.release.set()
assert titles.reply().status_code == 200
actions = [e["data"]["action"] for e in bus.since(seq) if e["event"] == "session"]
assert actions.count("delete") == 1 and actions[-1] == "delete"
@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
async def test_the_close_waits_for_a_late_write(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(config.directories, "cache", tmp_path)
directory = tmp_path / "_sessions" / "EXAMPLE"
directory.mkdir(parents=True)
store = SessionStore()
entry = await store.create("EXAMPLE", None, cache_tag="_sessions/EXAMPLE")
await entry.lock.acquire()
closing = asyncio.create_task(store.close())
assert await asyncio.to_thread(wait_until, lambda: not directory.exists(), DEADLINE)
directory.mkdir(parents=True)
entry.lock.release()
await asyncio.wait_for(closing, DEADLINE)
assert not directory.exists()
async def test_a_late_write_holds_the_close_no_longer_than_a_login(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
monkeypatch.setattr(config.directories, "cache", tmp_path)
monkeypatch.setattr(session_store, "LOGIN_WAIT", 0.05)
store = SessionStore()
entry = await store.create("EXAMPLE", None, cache_tag="_sessions/EXAMPLE")
await entry.lock.acquire()
await asyncio.wait_for(store.close(), DEADLINE)
(tmp_path / "_sessions" / "EXAMPLE").mkdir(parents=True)
entry.lock.release()
assert await asyncio.to_thread(wait_until, lambda: not (tmp_path / "_sessions").exists(), DEADLINE)
@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"]