diff --git a/docs/dev/rest-api/endpoints.md b/docs/dev/rest-api/endpoints.md index a2004d86..0493cc4f 100644 --- a/docs/dev/rest-api/endpoints.md +++ b/docs/dev/rest-api/endpoints.md @@ -17,7 +17,7 @@ Start the server with [`unshackle serve`](../../guide/cli-reference.md). By defa - **CORS.** Every response carries permissive CORS headers, and the server answers `OPTIONS` preflight requests automatically. - **Compression.** JSON responses of 256 bytes or more are gzip-compressed when the client sends `Accept-Encoding: gzip`. A [slow response](#slow-responses) is not compressed. - **Service allowlist.** The effective allowlist for your API key filters the service-facing endpoints (the intersection of the global `serve.services` list and your per-key list). The server treats services you cannot use as unknown. -- **Remote services.** A full-mode server can run a service through one of its own `remote_services` servers (see [Remote sessions](remote-sessions.md)). `GET /api/config` lists their names in `remote_services`, and `GET /api/services?remote=` lists that server's services, each with `remote` set to the name. Add `"remote": ""` to `POST /api/search`, `/api/list-titles`, `/api/list-tracks` or `/api/download`, and the server opens a remote session with its own key for that server: the remote logs in and resolves titles, tracks and licences, and a download still runs, decrypts and muxes here. The tag may be any case or an alias, and your allowlist applies to it. An unknown name is `400 INVALID_PARAMETERS`, a server that does not answer is `SERVICE_UNAVAILABLE`, and a tag it does not offer is `INVALID_SERVICE`. List calls from the same API key for the same title, profile, proxy, client region and service options share one remote session, which closes after 120 seconds unused. An optional `client_name` names your client on the remote server's dashboard as `serve ()`. A relayed search opens no remote session. The server sends its own credentials, cookies and cache for the `profile` with the search. A service that searches with no login gets none of them. A `--remote-only` server does not relay. A remote login that waits on you (a pair code or URL to approve on another device) cannot answer through a list call, so poll `GET /api/remote/logins` alongside it: each entry carries the login's `notice`, its `qr` (the text of a QR code to scan, or null), and its `prompt` when it asks a question (an OTP), which you answer with `POST /api/remote/logins/{id}/input` and `{"response": "..."}`. A remote download job shows the same text as its own `notice`, and asks a question (an OTP) through `input_prompt` as a local job does. +- **Remote services.** A full-mode server can run a service through one of its own `remote_services` servers (see [Remote sessions](remote-sessions.md)). `GET /api/config` lists their names in `remote_services`, and `GET /api/services?remote=` lists that server's services, each with `remote` set to the name. Add `"remote": ""` to `POST /api/search`, `/api/list-titles`, `/api/list-tracks` or `/api/download`, and the server opens a remote session with its own key for that server: the remote logs in and resolves titles, tracks and licences, and a download still runs, decrypts and muxes here. The tag may be any case or an alias, and your allowlist applies to it. An unknown name is `400 INVALID_PARAMETERS`, a server that does not answer is `SERVICE_UNAVAILABLE`, and a tag it does not offer is `INVALID_SERVICE`. List calls from the same API key for the same title, profile, proxy, client region and service options share one remote session, which closes after 120 seconds unused. When the server stops, a list call that waits on the login of a new remote session, or starts one, gets `SERVER_DRAINING` (409). A call that opens a lost remote session again can be cut too: `list-titles` then gets `SERVER_DRAINING`, and `list-tracks` that or `SERVICE_ERROR` (422). An optional `client_name` names your client on the remote server's dashboard as `serve ()`. A relayed search opens no remote session. The server sends its own credentials, cookies and cache for the `profile` with the search. A service that searches with no login gets none of them. A `--remote-only` server does not relay. A remote login that waits on you (a pair code or URL to approve on another device) cannot answer through a list call, so poll `GET /api/remote/logins` alongside it: each entry carries the login's `notice`, its `qr` (the text of a QR code to scan, or null), and its `prompt` when it asks a question (an OTP), which you answer with `POST /api/remote/logins/{id}/input` and `{"response": "..."}`. A remote download job shows the same text as its own `notice`, and asks a question (an OTP) through `input_prompt` as a local job does. !!! warning "Error responses have two shapes" Structured application errors (raised inside a handler) return `{"status": "error", "error_code": "...", "message": "...", "timestamp": "..."}`. The authentication middleware, however, returns a **different** shape: `{"status": 401, "message": "..."}` with an integer `status` and no `error_code`. The same middleware answers `429` in that shape when an API key goes over its rate limit. Clients must accept both shapes. The [Error responses](#error-responses) section at the bottom of this page gives the full error model. diff --git a/docs/dev/rest-api/errors.md b/docs/dev/rest-api/errors.md index 6061d5d0..f8a2fe54 100644 --- a/docs/dev/rest-api/errors.md +++ b/docs/dev/rest-api/errors.md @@ -127,7 +127,7 @@ while the server restarts. | `SESSION_NOT_FOUND` | 404 | The remote-dl session does not exist or has expired. | | `TRACK_NOT_FOUND` | 404 | A referenced track ID is not present in the remote session. | | `CONFLICT` | 409 | The target resource is in a state that disallows the action (retrying a running job, prioritising a non-queued job, clearing cache during an active download). | -| `SERVER_DRAINING` | 409 | The server is about to restart and starts no new remote session or download job. Open work continues. Retryable after the restart. A `dl --remote` client waits for the restart and opens a new remote session. | +| `SERVER_DRAINING` | 409 | The server is about to restart or stops, and starts no new remote session, remote login or download job. Open work continues. Retryable after the restart. A `dl --remote` client waits for the restart and opens a new remote session. | | `SERVICE_ERROR` | 422 | The streaming service's API returned an error, or the service does not support the requested operation, or the service code exited (`sys.exit`). | | `DRM_ERROR` | 422 | DRM or license acquisition failed. | | `RATE_LIMITED` | 429 | The streaming service is rate-limiting requests. Retryable. | diff --git a/docs/dev/rest-api/remote-sessions.md b/docs/dev/rest-api/remote-sessions.md index 1d4332e9..d952b35c 100644 --- a/docs/dev/rest-api/remote-sessions.md +++ b/docs/dev/rest-api/remote-sessions.md @@ -643,6 +643,12 @@ Source: `unshackle/core/api/session_store.py`. A singleton you get from remote session and deletes the cache directory of each one. It sends no dashboard event and schedules no reload. It then waits up to 5 seconds for each tracked task that still runs, and stops the sweep. Within that time, a login that ends deletes its cache directory again. +- **Relay.** A server that relays to a `remote_services` server runs **`end_remote_pool()`** after `close_channels()`. + It starts the end of each remote login that waits, and of all idle pooled remote sessions at the same time. A list + call whose login it ends, or whose login comes later, gets `SERVER_DRAINING`. A request in flight finishes first. Every + 5 seconds until it has stopped, the server ends each request that opens its lost remote session again. Then + **`close_remote_pool()`** ends the rest and waits up to 5 seconds for each `DELETE` request. The exit of the process + waits for an end that still runs. - **Signals.** The first `SIGTERM` starts the shutdown, and the server ignores each later one. A second Ctrl+C forces the end. On Windows only Ctrl+C starts the shutdown. @@ -817,6 +823,7 @@ saves the returned cache and then stops the tunnel. It does so: - when a signal or a closed console stops the process, or the cancel of a download job stops its worker - when the login or any other step of the opening fails, or `create` times out or its answer is cut off - when a serve that relays for a REST client closes its pooled remote session +- when such a serve stops: each remote login that waits, and all idle pooled remote sessions at the same time The `DELETE` has a connect and read timeout of 15s each. The client sends it again only once, when a gateway answers with an error page or asks for the API key in the other header. It does not wait for a rate limit. diff --git a/tests/remote/unit/test_relay_stop.py b/tests/remote/unit/test_relay_stop.py new file mode 100644 index 00000000..05f1a423 --- /dev/null +++ b/tests/remote/unit/test_relay_stop.py @@ -0,0 +1,532 @@ +"""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 +import time +from collections.abc import Callable +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path +from threading import Event, Lock, Semaphore +from types import SimpleNamespace +from typing import Any + +import pytest +import requests +from aiohttp import web + +from tests.remote.unit.test_process_exit 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 tests.remote.unit.test_tunnel import wait_until +from unshackle.core.api import handlers, routes +from unshackle.core.api.errors import APIError +from unshackle.core.api.handlers import ( + RelayStop, + RemoteLease, + RemoteLogin, + close_remote_pool, + end_remote_pool, + end_reopening, + setup_remote_service, +) +from unshackle.core.api.routes import setup_routes +from unshackle.core.remote_protocol import ( + PROMPT_ROUTE, + SESSION_ROUTE, + TITLES_ROUTE, + APIErrorCode, +) + +pytestmark = pytest.mark.unit + +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 poll_a_device(stub: StubService) -> None: + while True: + stub._input_bridge.ensure_active() + time.sleep(0.01) + + +def lose_session(server: SimpleNamespace, stub: StubService) -> None: # noqa: F811 + for entry in sessions(): + forget(server, entry.session_id) + stub._input_bridge.ensure_active() + + +def nothing(stub: StubService) -> None: + pass + + +@posix +@pytest.mark.parametrize( + ("server", "login", "titles"), + [ + (True, ask, nothing), + (True, poll_a_device, nothing), + (True, nothing, ask), + (False, ask, nothing), + (False, poll_a_device, nothing), + ], + ids=["prompt", "device", "prompt-after-login", "prompt-polling", "device-polling"], + indirect=["server"], +) +def test_a_stop_ends_a_remote_login( + server: SimpleNamespace, # noqa: F811 + relay: Relay, + monkeypatch: pytest.MonkeyPatch, + login: Callable[[StubService], None], + titles: Callable[[StubService], None], +) -> None: + """The login waits on the user, so nothing but the stop can end it, and its list call gets an answer.""" + monkeypatch.setattr(StubService, "authenticate", lambda self, cookies, credential: login(self)) + StubService.hooks["titles"] = titles + reply = relay.list() + assert wait_until( + lambda: count(server, "GET", PROMPT_ROUTE) > 0 or any(entry.channel.attached for entry in sessions()), DEADLINE + ) + assert ask not in (login, titles) or wait_until(relay.asks, DEADLINE) + relay.stop() + relay.ended_well() + assert (reply().status_code, error_code(reply())) == (409, APIErrorCode.SERVER_DRAINING) + + +@posix +def test_no_other_shutdown_hook_delays_the_end_of_a_login( + run: Callable[..., Any], # noqa: F811 + server: SimpleNamespace, # noqa: F811 + tmp_path: Path, +) -> None: + released = tmp_path / "released" + relay = Relay(run, server.url, tmp_path / "relay", str(released)) + relay.list() + assert wait_until(relay.asks, DEADLINE) + relay.stop() + assert wait_until(lambda: sessions() == [], DEADLINE) + released.touch() + relay.ended_well() + + +@posix +@pytest.mark.parametrize("in_flight", [False, True], ids=["idle", "in-flight"]) +def test_a_stop_ends_the_pooled_sessions_at_the_same_time( + server: SimpleNamespace, # noqa: F811 + logins: list[Any], # noqa: F811 + relay: Relay, + monkeypatch: pytest.MonkeyPatch, + in_flight: bool, +) -> None: + """No DELETE is answered before the last one has arrived.""" + ids = ("example-1", "example-2", "example-3") + started, release = Semaphore(0), Event() + + def hold(stub: StubService) -> None: + started.release() + assert release.wait(DEADLINE), "the test did not release the titles" + + if in_flight: + StubService.hooks["titles"] = hold + replies = [relay.list(title=title) for title in ids] + for reply in replies: + assert started.acquire(timeout=DEADLINE) if in_flight else reply().status_code == 200 + assert len(sessions()) == len(ids) + together = asyncio.Barrier(len(ids)) + handler = routes.session_delete_handler + + async def held(session_id: str, request: Any) -> Any: + await asyncio.wait_for(together.wait(), DEADLINE) + return await handler(session_id, request) + + monkeypatch.setattr(routes, "session_delete_handler", held) + relay.stop() + if in_flight: + wait_line(relay.process, "the shutdown hooks ended") + release.set() + relay.ended_well() + assert [reply().status_code for reply in replies] == [200] * len(ids) + + +@posix +@pytest.mark.parametrize("pooled", [False, True], ids=["first-call", "pooled-session"]) +def test_a_request_in_flight_finishes_on_its_own_session( + run: Callable[..., Any], # noqa: F811 + server: SimpleNamespace, # noqa: F811 + logins: list[Any], # noqa: F811 + tmp_path: Path, + pooled: bool, +) -> None: + """The first call of a session fetches its titles while its login is still listed.""" + relay = Relay(run, server.url, tmp_path / "relay", wait=0.2) + started, release = Event(), Event() + + def hold(stub: StubService) -> None: + started.set() + assert release.wait(DEADLINE), "the test did not release the titles" + + if pooled: + assert relay.list("list-tracks")().status_code == 200 + StubService.hooks["titles"] = hold + reply = relay.list("list-titles" if pooled else "list-tracks") + assert started.wait(DEADLINE) + relay.stop() + wait_line(relay.process, "the reopens ended") + release.set() + assert reply().status_code == 200 + relay.ended_well() + assert len(logins) == 1 + assert count(server, "GET", TITLES_ROUTE) == 1 + pooled + assert count(server, "DELETE", SESSION_ROUTE) == 1 + + +@posix +def test_a_session_lost_late_in_the_stop_does_not_hold_it( + run: Callable[..., Any], # noqa: F811 + server: SimpleNamespace, # noqa: F811 + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + relay = Relay(run, server.url, tmp_path / "relay", wait=0.2) + started, release = Event(), Event() + + def lose(stub: StubService) -> None: + started.set() + assert release.wait(DEADLINE), "the test did not release the titles" + lose_session(server, stub) + + def login(stub: StubService, cookies: Any, credential: Any) -> None: + if release.is_set(): + poll_a_device(stub) + + monkeypatch.setattr(StubService, "authenticate", login) + StubService.hooks["titles"] = lose + reply = relay.list() + assert started.wait(DEADLINE) + relay.stop() + wait_line(relay.process, "the reopens ended") + release.set() + assert reply().status_code == 409 + relay.ended_well() + + +@posix +@pytest.mark.parametrize("waits", [True, False], ids=["waits", "finishes"]) +@pytest.mark.parametrize("pooled", [False, True], ids=["first-call", "pooled-session"]) +def test_a_request_that_opens_its_lost_session_again_finishes_in_time_or_is_cut( + run: Callable[..., Any], # noqa: F811 + server: SimpleNamespace, # noqa: F811 + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + pooled: bool, + waits: bool, +) -> None: + """The upstream server loses the remote session, and the login of the next one waits for an approval.""" + relay = Relay(run, server.url, tmp_path / "relay", wait=0.2 if waits else DEADLINE) + lost, reopening, approved = Event(), Event(), Event() + + def lose(stub: StubService) -> None: + StubService.hooks.clear() + lost.set() + lose_session(server, stub) + + def login(stub: StubService, cookies: Any, credential: Any) -> None: + if lost.is_set(): + reopening.set() + while not approved.wait(0.01): + stub._input_bridge.ensure_active() + + monkeypatch.setattr(StubService, "authenticate", login) + if pooled: + assert relay.list("list-tracks")().status_code == 200 + StubService.hooks["titles"] = lose + reply = relay.list() + assert reopening.wait(DEADLINE) + relay.stop() + wait_line(relay.process, "the shutdown hooks ended") + if not waits: + approved.set() + assert reply().status_code == (409 if waits else 200) + relay.ended_well() + + +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_login_that_the_stop_reaches_before_its_create_opens_no_session( + server: SimpleNamespace, # noqa: F811 + logins: list[Any], # noqa: F811 + pool: dict[tuple, RemoteLease], + monkeypatch: pytest.MonkeyPatch, +) -> None: + app, client = relay_app(), make_client(server.url) + authenticate = client.authenticate + + def stop_first() -> None: + asyncio.run(end_remote_pool(app)) + authenticate() + + monkeypatch.setattr(client, "authenticate", stop_first) + with pytest.raises(APIError) as refused: + log_in(app, client, monkeypatch) + assert refused.value.error_code == APIErrorCode.SERVER_DRAINING + assert server.seen == [] + + +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_the_stop_refuses_before_it_reads_the_logins( + pool: dict[tuple, RemoteLease], monkeypatch: pytest.MonkeyPatch +) -> None: + app = relay_app() + started: list[bool] = [] + + class Logins(dict[str, Any]): + def values(self) -> Any: + started.append(app["relay_stop"].started) + return super().values() + + monkeypatch.setattr(handlers, "_remote_logins", Logins()) + asyncio.run(end_remote_pool(app)) + assert started == [True] + + +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_stop_waits_for_the_ends_and_not_for_the_default_executor( + pool: dict[tuple, RemoteLease], monkeypatch: pytest.MonkeyPatch +) -> None: + """The ends finish while the stop waits. A busy remote session stays open.""" + closed: list[str] = [] + begun, finish, free_workers = Event(), Event(), Event() + workers = ThreadPoolExecutor(1) + asyncio.get_running_loop().set_default_executor(workers) + workers.submit(free_workers.wait, DEADLINE) + + def end(name: str) -> None: + begun.set() + assert finish.wait(DEADLINE) + closed.append(name) + + async def finish_later() -> None: + while not begun.is_set(): + await asyncio.sleep(0.01) + finish.set() + + monkeypatch.setattr(handlers, "LOGIN_WAIT", DEADLINE / 4) + for name in ("a", "b", "busy"): + service = SimpleNamespace(close=lambda name=name: end(name)) + pool[(name,)] = RemoteLease((name,), service=service, busy=int(name == "busy")) + app = relay_app() + try: + later = asyncio.create_task(finish_later()) + await close_remote_pool(app) + assert sorted(closed) == ["a", "b"] and list(pool) == [("busy",)] + assert all(thread.daemon for thread in app["relay_stop"].ends) + await later + finally: + free_workers.set() + finish.set() + + +async def test_an_end_that_does_not_finish_holds_the_stop_no_longer_than_the_wait( + pool: dict[tuple, RemoteLease], monkeypatch: pytest.MonkeyPatch +) -> None: + closed, release = Event(), Event() + + def end() -> None: + release.wait(DEADLINE) + closed.set() + + monkeypatch.setattr(handlers, "LOGIN_WAIT", 0.05) + pool[("stuck",)] = RemoteLease(("stuck",), service=SimpleNamespace(close=end)) + try: + await asyncio.wait_for(close_remote_pool(relay_app()), DEADLINE / 2) + assert not closed.is_set() + finally: + release.set() + + +async def test_a_reopen_is_ended_once(pool: dict[tuple, RemoteLease], monkeypatch: pytest.MonkeyPatch) -> None: + lifetime = SimpleNamespace(ended=False) + service = SimpleNamespace(lifetime=lifetime, _reopen_lock=Lock(), close=lambda: setattr(lifetime, "ended", True)) + monkeypatch.setattr(handlers, "LOGIN_WAIT", DEADLINE) + pool[("EXAMPLE",)] = RemoteLease(("EXAMPLE",), service=service, busy=1) + stop = RelayStop() + with service._reopen_lock: + for _ in range(2): + end_reopening(stop) + stop.ends[0].join(DEADLINE) + assert len(stop.ends) == 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"] diff --git a/unshackle/core/api/handlers.py b/unshackle/core/api/handlers.py index d490f490..9fd9680b 100644 --- a/unshackle/core/api/handlers.py +++ b/unshackle/core/api/handlers.py @@ -40,7 +40,14 @@ from unshackle.core.api.sanitize import ( ) from unshackle.core.api.session_channel import status_message from unshackle.core.api.session_log import SessionLogBuffer, SessionLogMirror, capture_service_logs -from unshackle.core.api.session_store import PendingCreate, SessionEntry, SessionStore, holds, session_not_found +from unshackle.core.api.session_store import ( + LOGIN_WAIT, + PendingCreate, + SessionEntry, + SessionStore, + holds, + session_not_found, +) from unshackle.core.binaries import binary_version from unshackle.core.cacher import Cacher from unshackle.core.cdm.choice import choose_cdm, drm_system @@ -499,21 +506,49 @@ def relay_service( return make_remote_service(ctx, server, data["service"], title_id, data, apply_overrides=False) +@dataclass +class RelayStop: + """The stop of one app: whether it has started, and the threads that end its remote sessions.""" + + started: bool = False + ends: list[threading.Thread] = field(default_factory=list) + + def end(self, *services: Any) -> None: + """Start the ends, each on a daemon thread, because the logins can fill the default executor.""" + for service in services: + self.ends.append(threading.Thread(target=close_remote_services, args=([service],), daemon=True)) + self.ends[-1].start() + + +def refuse_stopped_relay(request: web.Request | None) -> None: + """Raise SERVER_DRAINING for a remote login once the server of *request* stops.""" + if request is not None and request.app["relay_stop"].started: + raise APIError( + APIErrorCode.SERVER_DRAINING, "This server is stopping and opens no remote session", retryable=True + ) + + def setup_remote_service( data: dict[str, Any], server: str, profile: str | None, title_id: str, request: web.Request | None = None ) -> Any: """Open and authenticate a remote session and fetch its titles; the caller must close() it.""" from unshackle.core.remote_service import RemoteError + refuse_stopped_relay(request) service_instance = relay_service(data, server, profile, title_id, request) login = RemoteLogin(caller_key(request), server, data["service"], title_id, service_instance) service_instance._input_bridge = login.bridge _remote_logins[login.id] = login try: + refuse_stopped_relay(request) service_instance.authenticate() + login.done = True service_instance.get_titles() except BaseException as exc: + cut = login.bridge.cut or service_instance.lifetime.ended service_instance.close() + if cut: + refuse_stopped_relay(request) if isinstance(exc, RemoteError): raise relay_error(exc, data["service"]) from None raise @@ -538,6 +573,7 @@ class RemoteLogin: instance: Any id: str = field(default_factory=lambda: uuid.uuid4().hex) bridge: InputBridge = field(default_factory=InputBridge) + done: bool = False _remote_logins: dict[str, RemoteLogin] = {} @@ -665,6 +701,47 @@ def reset_remote_pool() -> None: threading.Thread(target=close_remote_services, args=(idle,), name="remote-pool-reset", daemon=True).start() +async def end_remote_pool(app: web.Application, last: bool = False) -> None: + """Start the end of each remote login and of each idle pooled remote session, at server shutdown. + + A login that is done belongs to a request in flight, which finishes unless this is the ``last`` call, or unless + :func:`end_reopening` finds it. + """ + stop: RelayStop = app["relay_stop"] + stop.started = True + logins = list(_remote_logins.values()) + for entry in logins: + entry.bridge.cancel() + idle = [lease for lease in _remote_pool.values() if not lease.busy] + for lease in idle: + del _remote_pool[lease.key] + stop.end(*(entry.instance for entry in logins if last or not entry.done), *(lease.service for lease in idle)) + if not last: + asyncio.get_running_loop().call_later(LOGIN_WAIT, end_reopening, stop) + + +def end_reopening(stop: RelayStop) -> None: + """End each remote session that a request in flight opens again: its upstream server can be gone for a long time. + + It repeats every LOGIN_WAIT seconds until the loop stops, for a remote session lost later in the stop. + """ + services = [entry.instance for entry in list(_remote_logins.values())] + services += [lease.service for lease in _remote_pool.values() if lease.service] + stop.end(*(s for s in services if s._reopen_lock.locked() and not s.lifetime.ended)) + asyncio.get_running_loop().call_later(LOGIN_WAIT, end_reopening, stop) + + +async def close_remote_pool(app: web.Application) -> None: + """End what the last requests returned to the pool, and wait LOGIN_WAIT seconds at most for every end. + + The exit hook of each remote session waits for an end that still runs. + """ + await end_remote_pool(app, last=True) + deadline = time.monotonic() + LOGIN_WAIT + while any(end.is_alive() for end in app["relay_stop"].ends) and time.monotonic() < deadline: + await asyncio.sleep(0.01) + + async def lease_remote_service( data: dict[str, Any], server: str, diff --git a/unshackle/core/api/routes.py b/unshackle/core/api/routes.py index 4bd3cf46..a120c3f1 100644 --- a/unshackle/core/api/routes.py +++ b/unshackle/core/api/routes.py @@ -21,10 +21,12 @@ from unshackle.core.api.handlers import ( DASHBOARD_EVENTS_ROUTE, DASHBOARD_PREFIX, JOB_EVENTS_ROUTE, + RelayStop, cancel_download_job_handler, clear_cache_handler, clear_finished_download_jobs_handler, clear_temp_handler, + close_remote_pool, dashboard_cdm_logs_handler, dashboard_drain_start_handler, dashboard_drain_stop_handler, @@ -42,6 +44,7 @@ from unshackle.core.api.handlers import ( download_history_handler, download_job_events_handler, download_job_input_handler, + end_remote_pool, env_check_handler, get_download_job_handler, list_download_jobs_handler, @@ -832,6 +835,8 @@ async def list_titles(request: web.Request) -> web.Response: timestamp: type: string format: date-time + '409': + description: The server stops, so it ends or does not start the remote login of the request (SERVER_DRAINING) '422': description: Server error content: @@ -934,6 +939,8 @@ async def list_tracks(request: web.Request) -> web.Response: cookies or cache. '400': description: Invalid request + '409': + description: The server stops, so it ends or does not start the remote login of the request (SERVER_DRAINING) """ data = await json_body(request) @@ -3591,8 +3598,11 @@ def setup_routes( app.on_response_prepare.append(generic_server_header) app.on_shutdown.append(close_tunnels) app.on_shutdown.append(close_channels) + app["relay_stop"] = RelayStop() + app.on_shutdown.append(end_remote_pool) app.on_shutdown.append(shutdown_download_manager) app.on_shutdown.append(close_event_streams) + app.on_cleanup.append(close_remote_pool) async def generic_server_header(request: web.Request, response: web.StreamResponse) -> None: