"""The stop of a serve that relays: it ends the remote logins and the idle pooled sessions on the upstream server. A stop is a signal to a real ``serve`` process whose upstream is a server in this process. """ from __future__ import annotations import asyncio import json import signal from collections.abc import Callable from pathlib import Path from types import SimpleNamespace from typing import Any import pytest import requests from aiohttp import web from tests.remote.process import BOUND, lasting_sessions, posix, run, settings, wait_line # noqa: F401 from tests.remote.unit.test_remote_loopback import KEY, StubService, count, forget, make_client, server # noqa: F401 from tests.remote.unit.test_session_lifetime import DEADLINE, error_code, in_thread, logins, sessions # noqa: F401 from unshackle.core.api import handlers from unshackle.core.api.errors import APIError from unshackle.core.api.handlers import ( RemoteLease, RemoteLogin, close_remote_pool, end_remote_pool, setup_remote_service, ) from unshackle.core.api.routes import setup_routes from unshackle.core.remote_protocol import ( APIErrorCode, ) pytestmark = [pytest.mark.unit, pytest.mark.process] RELAY = """ import asyncio, json, sys from pathlib import Path from aiohttp import web from unshackle.core.config import config config.__init__(**json.loads(sys.argv[1])) from unshackle.commands.serve import serve from unshackle.core import remote_channel, remote_service, services from unshackle.core.api import handlers, routes handlers.LOGIN_WAIT = float(sys.argv[2]) remote_channel.AUTH_POLL_INTERVAL = 0.05 services.load_all = lambda: None remote_service.remote_service_list = lambda name: [{"tag": "EXAMPLE", "aliases": [], "cli_params": []}] start, shutdown = web.TCPSite.start, web.Application.shutdown async def started(site): await start(site) print("port", site._server.sockets[0].getsockname()[1], flush=True) async def shut_down(app): await shutdown(app) print("the shutdown hooks ended", flush=True) async def hold(app): while not Path(sys.argv[3]).exists(): await asyncio.sleep(0.01) if sys.argv[3:]: routes.shutdown_download_manager = hold reopens = handlers.end_reopening def end_reopening(stop): reopens(stop) print("the reopens ended", flush=True) handlers.end_reopening = end_reopening web.TCPSite.start = started web.Application.shutdown = shut_down serve(args=["-q", "-h", "127.0.0.1", "-p", "0", "--api-only"]) """ class Relay: """A ``serve`` process that relays to the upstream server of the test.""" def __init__(self, run: Callable[..., Any], url: str, path: Path, *hold: str, wait: float = 5) -> None: # noqa: F811 data = {**settings(url.replace("127.0.0.1", "localhost"), path), "serve": {"api_secret": KEY}} self.process = run("-c", RELAY, json.dumps(data), str(wait), *hold) self.url = f"http://127.0.0.1:{wait_line(self.process, 'port ').split()[1]}" def list(self, route: str = "list-titles", title: str = "example-1") -> Callable[[], requests.Response]: """Send a list call; the returned function waits for its answer.""" body = {"service": "EXAMPLE", "title_id": title, "remote": "test", "no_proxy": True} url, headers = f"{self.url}/api/{route}", {"X-Secret-Key": KEY} return in_thread(lambda: requests.post(url, json=body, headers=headers, timeout=DEADLINE)) def asks(self) -> bool: reply = requests.get(self.url + "/api/remote/logins", headers={"X-Secret-Key": KEY}, timeout=DEADLINE) return any(login["prompt"] for login in reply.json()["logins"]) def stop(self) -> None: self.process.send_signal(signal.SIGTERM) def ended_well(self) -> None: """The process ends in time, and its upstream server has no remote session left.""" output, _ = self.process.communicate(timeout=BOUND) assert self.process.returncode == 0, output assert "Traceback" not in output assert sessions() == [] @pytest.fixture def relay(run: Callable[..., Any], server: SimpleNamespace, tmp_path: Path) -> Relay: # noqa: F811 return Relay(run, server.url, tmp_path / "relay") def ask(stub: StubService) -> None: stub._input_bridge.request_input("Enter the EXAMPLE code") def nothing(stub: StubService) -> None: pass def relay_app() -> web.Application: app = web.Application() setup_routes(app) return app @pytest.fixture def pool(monkeypatch: pytest.MonkeyPatch) -> dict[tuple, RemoteLease]: monkeypatch.setattr(handlers, "_remote_pool", {}) monkeypatch.setattr(handlers, "_remote_logins", {}) return handlers._remote_pool def log_in(app: web.Application, client: Any, monkeypatch: pytest.MonkeyPatch) -> Any: """Log *client* in as a list call of *app* does. With no client, the call must not build one.""" monkeypatch.setattr(handlers, "relay_service", lambda *args: client or pytest.fail("the relay built a service")) request: Any = SimpleNamespace(app=app, headers={"X-Secret-Key": KEY}) return setup_remote_service({"service": "EXAMPLE"}, "test", None, "example-1", request) class Registry(dict[str, Any]): """The logins in progress of a relay that stops when the thread of a login adds itself, before or after the add.""" def __init__(self, app: web.Application, before: bool) -> None: super().__init__() self.app, self.before = app, before def __setitem__(self, key: str, login: Any) -> None: if self.before: asyncio.run(end_remote_pool(self.app)) super().__setitem__(key, login) if not self.before: asyncio.run(end_remote_pool(self.app)) @pytest.mark.parametrize("before", [True, False], ids=["before-the-add", "after-the-add"]) def test_a_login_that_starts_as_the_relay_stops_is_refused( server: SimpleNamespace, # noqa: F811 logins: list[Any], # noqa: F811 pool: dict[tuple, RemoteLease], monkeypatch: pytest.MonkeyPatch, before: bool, ) -> None: app = relay_app() monkeypatch.setattr(handlers, "_remote_logins", Registry(app, before)) with pytest.raises(APIError) as refused: log_in(app, make_client(server.url), monkeypatch) assert refused.value.error_code == APIErrorCode.SERVER_DRAINING assert (refused.value.retryable, "\n" in refused.value.message) == (True, False) assert server.seen == [] and not handlers._remote_logins def test_a_request_in_flight_keeps_its_own_error( server: SimpleNamespace, # noqa: F811 logins: list[Any], # noqa: F811 pool: dict[tuple, RemoteLease], monkeypatch: pytest.MonkeyPatch, ) -> None: app = relay_app() def fail(stub: StubService) -> None: asyncio.run(end_remote_pool(app)) raise ValueError("EXAMPLE failed") StubService.hooks["titles"] = fail with pytest.raises(APIError, match="EXAMPLE failed"): log_in(app, make_client(server.url), monkeypatch) assert sessions() == [] def test_another_app_of_the_process_still_logs_in( server: SimpleNamespace, # noqa: F811 logins: list[Any], # noqa: F811 pool: dict[tuple, RemoteLease], monkeypatch: pytest.MonkeyPatch, ) -> None: stopped, app = relay_app(), relay_app() asyncio.run(end_remote_pool(stopped)) with pytest.raises(APIError): log_in(stopped, None, monkeypatch) log_in(app, make_client(server.url), monkeypatch).close() assert len(logins) == 1 async def test_the_last_call_ends_also_the_login_of_a_request_that_did_not_finish( pool: dict[tuple, RemoteLease], ) -> None: closed: list[str] = [] login = RemoteLogin("owner", "test", "EXAMPLE", "example-1", SimpleNamespace(close=lambda: closed.append("login"))) login.done = True handlers._remote_logins[login.id] = login app = relay_app() await end_remote_pool(app) assert not app["relay_stop"].ends await close_remote_pool(app) assert closed == ["login"]