diff --git a/docs/dev/rest-api/endpoints.md b/docs/dev/rest-api/endpoints.md index 089fb9ac..e9df0a8b 100644 --- a/docs/dev/rest-api/endpoints.md +++ b/docs/dev/rest-api/endpoints.md @@ -987,7 +987,9 @@ the newlines must go out at once. ### `POST /api/session/create` -Make a remote session for a service and title. Authentication runs asynchronously in the background. This call returns immediately with `status: "authenticating"`, and you then poll the prompt endpoint. The body accepts `service` and `title_id` (both required). It also accepts a broad set of optional keys, because the body allows `additionalProperties`. These are `credentials` (`{username, password, extra?}`), `cookies` (base64 of zlib-compressed Netscape cookie file), `proxy`, `no_proxy`, `profile`, `cache` (map of forwarded cache files, keyed by the file path relative to the service cache directory with `/` separators and no `.json` suffix, so a nested key such as `session_web/` lands in a subdirectory), `client_region`, `proxy_region`, `cdm_type`, `range_`, `vcodec`, `quality`, `best_available`, `dl_params`, `client`, and any service CLI options. `proxy_region` is the country code the client resolved `proxy` from; the server matches it against its own accounts. `client` is a freeform object the dashboard shows as sent (the CLI puts `version`, `code_hash`, `platform` and a redacted `argv` in it); the server ignores it above 4096 bytes of JSON. +Make a remote session for a service and title. Authentication runs asynchronously in the background. This call returns immediately with `status: "authenticating"`, and you then poll the prompt endpoint. The body accepts `service` and `title_id` (both required). It also accepts a broad set of optional keys, because the body allows `additionalProperties`. These are `session_id`, `credentials` (`{username, password, extra?}`), `cookies` (base64 of zlib-compressed Netscape cookie file), `proxy`, `no_proxy`, `profile`, `cache` (map of forwarded cache files, keyed by the file path relative to the service cache directory with `/` separators and no `.json` suffix, so a nested key such as `session_web/` lands in a subdirectory), `client_region`, `proxy_region`, `cdm_type`, `range_`, `vcodec`, `quality`, `best_available`, `dl_params`, `client`, and any service CLI options. `proxy_region` is the country code the client resolved `proxy` from; the server matches it against its own accounts. `client` is a freeform object the dashboard shows as sent (the CLI puts `version`, `code_hash`, `platform` and a redacted `argv` in it); the server ignores it above 4096 bytes of JSON. + +`session_id` is the ID that you give the remote session, so that you can delete it before this call answers. It must be the canonical text of a version 4 UUID. Without it, the server makes the ID. A second create with the same ID from the same API key and IP ends the first one if the first one has not answered, and replaces its remote session when the new one is stored. A second create that fails leaves that remote session open. `dl_params` is an object with the `dl` track selection: `lang`, `v_lang`, `a_lang` and `s_lang` (arrays of language strings), `acodec` (an array of audio codec names or `dl -a` aliases such as `ddp`), and `forced_subs` and `exact_lang` (booleans). The service reads these values from `ctx.parent.params`. The server uses the `dl` default for each absent value. It refuses a malformed value, an unknown codec, range or vcodec name, and a height of 0 or less with `INVALID_PARAMETERS`. The flat `range_`, `vcodec`, `quality`, `best_available` and `generate_dv` keys are `dl` values on this route. On the list and search routes they are `dl` values only when the body has `service_params`. @@ -1011,8 +1013,10 @@ The `proxy` value must be a full proxy URI, unless the operator gives your API k | Status | Error code | Meaning | | --- | --- | --- | | `200` | - | Session created; authentication in progress. | -| `400` | `INVALID_INPUT` | Missing `service` or `title_id`. | +| `400` | `INVALID_INPUT` | Missing `service` or `title_id`, or a `session_id` that is not the canonical text of a version 4 UUID. | | `400` | `INVALID_PARAMETERS` | Invalid `range_`, `vcodec`, `quality` or `dl_params` value. | +| `403` | `FORBIDDEN` | Another API key or another IP has the `session_id`. | +| `404` | `SESSION_NOT_FOUND` | A `DELETE` or a newer create with the same `session_id` ended this create. | | `400` | `INVALID_SERVICE` | Unknown or disallowed service. | ### `GET /api/session/{session_id}/channel` @@ -1307,7 +1311,7 @@ Return remote session metadata and validity. ### `DELETE /api/session/{session_id}` -Tear down a remote session. The server cancels its input bridge, harvests any updated cache files, and deletes the remote session and its cache directory. +Tear down a remote session. The server cancels its input bridge, harvests any updated cache files, and deletes the remote session and its cache directory. A create of the same API key and IP that still runs under this ID ends too: it makes no remote session and answers `404 SESSION_NOT_FOUND`. If no remote session exists yet, the `DELETE` answers `200` with no `cache`. === "Response `200`" diff --git a/docs/dev/rest-api/remote-sessions.md b/docs/dev/rest-api/remote-sessions.md index 489701b2..29617902 100644 --- a/docs/dev/rest-api/remote-sessions.md +++ b/docs/dev/rest-api/remote-sessions.md @@ -246,7 +246,8 @@ hood the client walks a remote session through its lifecycle. [remote session channel](#the-remote-session-channel) keeps the remote session alive, so a long download does not let the remote session expire. On completion, and also when `dl` exits early (`--list`, Ctrl+C, an error), it - deletes the remote session. If the login belongs to the client, the `DELETE` + deletes the remote session (see [When the client ends a remote session](#when-the-client-ends-a-remote-session)). + If the login belongs to the client, the `DELETE` request returns the updated cache files (for example a refreshed token) and the client saves them locally, so the **next** remote session can skip interactive authentication. The login belongs to the client when it succeeds and the @@ -480,7 +481,9 @@ The server mounts all these routes, even in `--remote-only` mode. Paths use the ### Create: request and response -`POST /api/session/create` requires `service` and `title_id`. It also accepts +`POST /api/session/create` requires `service` and `title_id`. It also accepts `session_id` (the ID of the remote session, +as the canonical text of a version 4 UUID; a create of the same API key and IP with the same ID replaces that remote +session when the new one is stored, and the server answers the ID of another API key or IP with `403 FORBIDDEN`), `credentials`, `cookies` (base64 of zlib-compressed Netscape cookie file), `proxy`, `no_proxy`, `profile`, `cache` (a map of `filename → base64(zlib(bytes))`), `client_region`, `server_cdm` (`false` when the user picked the local CDM), `cdm_type`, `cdm_security_level`, `cdm_relay` (`true` when the client @@ -614,6 +617,8 @@ Source: `unshackle/core/api/session_store.py`. A singleton you get from - **Config-driven limits.** `serve.session_ttl` (default `300`) and `serve.max_sessions` (default `100`) are read as properties, so config changes take effect without recreating the store. +- **`creating()`** holds the ID of a remote session while its `create` handler works, and refuses an ID that another API + key or IP has. **`end_pending()`** ends such a create for a `DELETE`, and then `create()` stores nothing. - **`create()`** evicts the least-recently-accessed remote session of the API key that holds the most when at capacity, then stores a complete `SessionEntry` from the fields of the `create` handler and publishes the `create` event. - **Expiry.** `get()` and `cleanup_expired()` use one rule. A remote session that no request holds @@ -635,7 +640,7 @@ Source: `unshackle/core/api/session_store.py`. A singleton you get from | Field | Description | |---|---| -| `session_id` | UUID4 string | +| `session_id` | UUID4 string: the one of the create request, else one that the server makes | | `service_tag` | Normalized service tag | | `service_instance` | The authenticated service object kept alive between calls | | `titles` / `title_map` | Result of `get_titles()` and a `title_id → Title` map | @@ -651,9 +656,12 @@ Source: `unshackle/core/api/session_store.py`. A singleton you get from The `create` handler builds a `Cacher` namespaced as: ```text -_sessions/// +_sessions/// ``` +The server makes a new UUID for each `create`, so a `create` that takes over a session ID never shares a directory +with the one before it. + The handler writes forwarded `cache` files into that directory before authentication. On `DELETE`, when the login belongs to the client (`client_auth`) and the remote session does not run on the server's device, the handler harvests updated cache files from the whole directory tree (compressing each @@ -732,10 +740,12 @@ the error codes and the request and reply shapes that it shares with the server (merging returned `session_headers`/`session_cookie_jar`, re-parsing `manifests`) → get the licence in proxy mode or `server_cdm` mode → `close()` (`DELETE`, saving any returned `cache`). +- **ID.** The client gives the remote session its ID: a version 4 UUID in the `session_id` of `create`. It uses + the ID of the reply, so a server that ignores the field also works. - **Server restarts.** The server keeps remote sessions in memory only, so a restart loses them all. The client recovers in two ways: - A drain announced through `draining`: the client finishes the current title, then - closes its remote session, so the drain can end and the refreshed cache comes back. + deletes its remote session, so the drain can end and the refreshed cache comes back. It waits until `/api/health` reports the restarted server without `draining`, opens a new remote session, and continues with the next title. - A lost remote session (`SESSION_NOT_FOUND`, a connection error, an answer cut off @@ -743,7 +753,8 @@ the error codes and the request and reply shapes that it shares with the server for `/api/health`, then checks the old remote session. A live remote session takes the call again only after a connection error, because a timed-out call can already have run. A cut-off answer counts as a connection error, so the server can run that call twice. A lost one is replaced: the - client opens a new remote session, sends `titles` and the current title's `tracks` + client deletes the old one when the server did not answer `SESSION_NOT_FOUND` for the call, and + saves the cache that comes back. It then opens a new remote session, sends `titles` and the current title's `tracks` again, and then sends the failed call again. A title or track that the new remote session gives another ID keeps its old ID on the client, and the client sends the new ID. The client matches a title by season and episode number, and a track by its attributes. @@ -760,6 +771,31 @@ the error codes and the request and reply shapes that it shares with the server with no `error_code`. Any other error stops the call: a segment filter that fails on the server stops the track download, and the client never keeps every segment in its place. +### When the client ends a remote session + +Source: `unshackle/core/remote_lifetime.py`. One owner holds the remote session, its tunnel and its channel +from before the first request until the server answers the `DELETE`. It closes the channel, sends the `DELETE`, +saves the returned cache and then stops the tunnel. It does so: + +- when `dl` has finished every title, before the run post-scripts +- when the process exits: `--list`, an error, or Ctrl+C in any step, also before `create` answers +- 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 + +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. A process that ends without its exit hooks (`SIGHUP`, +`SIGTERM`, `SIGKILL`, a closed console window) sends no `DELETE`, so the remote session stays until its TTL. Ctrl+C +waits for the download threads before it ends the remote session. + +While the client ends a remote session, it ignores the first Ctrl+C, so it does not lose the returned cache. The next +Ctrl+C stops the wait at once, and the process then waits for no other end. The count of Ctrl+C is one for the process. +When the run itself called the end, after the last title, that Ctrl+C also stops the run. On Windows, a Ctrl+C +counts when the network read that blocks returns, so the 15s timeout limits the wait. After the end, no thread of the +client opens a remote session again. + +The `DELETE` can arrive while the server still works on `create`. The server then answers `200` with no cache, and +the `create` makes no remote session, starts no login and answers `404 SESSION_NOT_FOUND`. + --- ## Troubleshooting diff --git a/tests/remote/e2e/test_live_remote_client.py b/tests/remote/e2e/test_live_remote_client.py index 6acddee1..fa7b968b 100644 --- a/tests/remote/e2e/test_live_remote_client.py +++ b/tests/remote/e2e/test_live_remote_client.py @@ -22,8 +22,3 @@ def test_remote_client_get_services(remote_client) -> None: def test_remote_client_get_404_raises_systemexit(remote_client) -> None: with pytest.raises(SystemExit): remote_client.get("/api/session/this-does-not-exist") - - -def test_remote_client_delete_404_raises_systemexit(remote_client) -> None: - with pytest.raises(SystemExit): - remote_client.delete("/api/session/this-does-not-exist") diff --git a/tests/remote/key_source.py b/tests/remote/key_source.py index dfb17fbd..6f1bcc0d 100644 --- a/tests/remote/key_source.py +++ b/tests/remote/key_source.py @@ -4,6 +4,7 @@ from types import SimpleNamespace from typing import Any from uuid import UUID +from tests.remote.sessions import hold_session from unshackle.core.remote_protocol import LicensingMode, Licensor from unshackle.core.remote_service import RemoteService, ServerVault from unshackle.core.title_source import KeyArrival @@ -71,7 +72,7 @@ def remote_session(local_cdm: Any, answer: dict) -> RemoteService: svc = remote_keys(server_cdm_type="playready", local_cdm=local_cdm) svc._track_alias = {} svc._title_alias = {} - svc._session_id = "sess" + hold_session(svc, "sess") svc.log = logging.getLogger("test-remote-session") posts: list = [] svc.client = SimpleNamespace(post=lambda endpoint, payload, expect=(): posts.append(payload) or answer) diff --git a/tests/remote/sessions.py b/tests/remote/sessions.py index 8b09b3db..8de1b8a8 100644 --- a/tests/remote/sessions.py +++ b/tests/remote/sessions.py @@ -2,16 +2,19 @@ from collections.abc import Callable from types import SimpleNamespace -from typing import Any +from typing import Any, NoReturn import pytest +import requests from unshackle.core.api import handlers, key_policy from unshackle.core.api.handlers import Launched, SessionLaunch from unshackle.core.api.input_bridge import InputBridge from unshackle.core.api.key_policy import KeyPolicy from unshackle.core.api.session_store import SessionEntry +from unshackle.core.remote_lifetime import RemoteSessionLifetime from unshackle.core.remote_protocol import LicensingMode, Licensor +from unshackle.core.remote_service import RemoteClient def session_entry(**fields: Any) -> SessionEntry: @@ -59,3 +62,17 @@ def stub_service_build(monkeypatch: pytest.MonkeyPatch, build: Callable[[], Any] monkeypatch.setattr(key_policy, "load_service_config", lambda tag: {}) monkeypatch.setattr(handlers, "load_full_cdm", lambda *a: None) monkeypatch.setattr(handlers, "instantiate_service", lambda *a, **k: build()) + + +def hold_session(service: Any, session_id: str | None = "sess") -> None: + """Give a remote client built without its constructor a session lifetime, with *session_id* open in it.""" + + def unreachable(*args: Any, **kwargs: Any) -> NoReturn: + raise requests.ConnectionError("EXAMPLE server is down") + + client = getattr(service, "client", None) + if not isinstance(client, RemoteClient): + client = SimpleNamespace(send=unreachable, timeout=1, tunnel=None) + service.lifetime = RemoteSessionLifetime(client, lambda cache: None) # type: ignore[arg-type] + if session_id: + service.lifetime.adopt(service.lifetime.name(), session_id) diff --git a/tests/remote/unit/test_client_device_cdm.py b/tests/remote/unit/test_client_device_cdm.py index 6cc83b50..c864c897 100644 --- a/tests/remote/unit/test_client_device_cdm.py +++ b/tests/remote/unit/test_client_device_cdm.py @@ -14,7 +14,7 @@ import pytest from pywidevine import DeviceTypes from pywidevine.pssh import PSSH -from tests.remote.sessions import launch_session, session_entry +from tests.remote.sessions import hold_session, launch_session, session_entry from unshackle.core.api import handlers, key_policy, server_keys from unshackle.core.api.errors import APIError from unshackle.core.api.input_bridge import InputBridge @@ -447,12 +447,8 @@ def test_a_lent_device_session_returns_no_cache_at_the_end(monkeypatch: pytest.M async def validated(session_id: str, request: Any) -> Any: return session - class Store: - async def delete(self, session_id: str) -> bool: - return True - monkeypatch.setattr(handlers, "get_validated_session", validated) - monkeypatch.setattr(session_store, "get_session_store", lambda: Store()) + monkeypatch.setattr(session_store, "get_session_store", session_store.SessionStore) monkeypatch.setattr(handlers, "collect_cache_files", lambda tag, withhold=(): {"MSL/server-esn": "tokens"}) response = asyncio.run(handlers.session_delete_handler("sid", None)) @@ -477,7 +473,7 @@ def test_a_lent_device_without_the_vault_grant_asks_the_server_for_no_key() -> N svc = object.__new__(RemoteService) svc.log = logging.getLogger("test") - svc._session_id = "sid" + hold_session(svc, "sid") svc.licensing = LicensingMode(Licensor.LENT_DEVICE) svc.client_licensed = set() svc.deferred_refusals = {} diff --git a/tests/remote/unit/test_licensing_mode.py b/tests/remote/unit/test_licensing_mode.py index 5ca05bd9..47540e9d 100644 --- a/tests/remote/unit/test_licensing_mode.py +++ b/tests/remote/unit/test_licensing_mode.py @@ -5,6 +5,7 @@ from types import SimpleNamespace import pytest +from tests.remote.sessions import hold_session from unshackle.core.api import handlers from unshackle.core.api.key_policy import KeyPolicy from unshackle.core.remote_protocol import LicensingMode, Licensor @@ -113,7 +114,6 @@ def test_the_tracks_reply_settles_the_mode_an_older_server_left_out(held, reques _chapters_by_title={}, _title_alias={}, _sample_decrypt_tracks=set(), - _session_id="s", service_tag="EXAMPLE", ctx=SimpleNamespace(obj=None), log=logging.getLogger("test"), @@ -121,6 +121,7 @@ def test_the_tracks_reply_settles_the_mode_an_older_server_left_out(held, reques drain_server_logs=lambda: None, ) service.session = SimpleNamespace(headers={}) + hold_session(service) with caplog.at_level(logging.INFO): service.get_tracks(SimpleNamespace(id="t1")) assert service.licensing == mode diff --git a/tests/remote/unit/test_malformed_input.py b/tests/remote/unit/test_malformed_input.py index a627dfa0..addc130d 100644 --- a/tests/remote/unit/test_malformed_input.py +++ b/tests/remote/unit/test_malformed_input.py @@ -16,6 +16,7 @@ import requests from aiohttp import WSMsgType, web from click.testing import CliRunner +from tests.remote.sessions import hold_session from tests.remote.unit.test_session_reopen import make_service from unshackle.core import remote_service from unshackle.core.api import handlers @@ -240,7 +241,7 @@ def test_server_text_loses_its_control_characters() -> None: def test_relayed_server_logs_lose_their_control_characters(monkeypatch: pytest.MonkeyPatch) -> None: service = RemoteService.__new__(RemoteService) - service._session_id = "sid" + hold_session(service, "sid") seen: list[str] = [] service.log = SimpleNamespace(log=lambda level, message: seen.append(message)) # type: ignore[assignment] service.client = SimpleNamespace( diff --git a/tests/remote/unit/test_remote_client.py b/tests/remote/unit/test_remote_client.py index acbc9ded..66ca358a 100644 --- a/tests/remote/unit/test_remote_client.py +++ b/tests/remote/unit/test_remote_client.py @@ -69,17 +69,6 @@ def test_post_sends_json_body(client: RemoteClient) -> None: assert captured["body"] == {"service": "EXAMPLE"} -@responses.activate -def test_delete_returns_json(client: RemoteClient) -> None: - responses.add( - responses.DELETE, - "http://srv:8786/api/session/abc", - json={"status": "deleted"}, - status=200, - ) - assert client.delete("/api/session/abc") == {"status": "deleted"} - - @responses.activate def test_4xx_raises_systemexit_with_logged_error(client: RemoteClient, caplog: pytest.LogCaptureFixture) -> None: responses.add( diff --git a/tests/remote/unit/test_remote_loopback.py b/tests/remote/unit/test_remote_loopback.py index ee5b7346..75f166c3 100644 --- a/tests/remote/unit/test_remote_loopback.py +++ b/tests/remote/unit/test_remote_loopback.py @@ -44,6 +44,7 @@ from unshackle.core.utilities import close_debug_logger, init_debug_logger pytestmark = pytest.mark.unit KEY = "loopback-key" +OTHER_KEY = "other-key" CODE = "1234" @@ -157,7 +158,7 @@ def server(request: pytest.FixtureRequest, monkeypatch: pytest.MonkeyPatch, tmp_ stub_service_build(monkeypatch, lambda: StubService(beats)) app = web.Application(middlewares=[record, cors_middleware, no_5xx_middleware, api_key_authentication]) - app["config"] = {"users": [KEY]} + app["config"] = {"users": [KEY, OTHER_KEY]} setup_routes(app, remote_only=True) loop = asyncio.new_event_loop() runner = web.AppRunner(app) @@ -501,7 +502,7 @@ def test_an_open_channel_keeps_the_session_alive(server: SimpleNamespace, monkey assert count(server, "GET", SESSION_ROUTE, session_id) == 0 assert count(server, "GET", LOGS_ROUTE) == count(server, "GET", PROMPT_ROUTE) == 0 - service.close_channel() + service.lifetime.close_channel() assert wait_until(lambda: not entry.channel.attached, 5) assert wait_until(lambda: idle_seconds(entry) > 2 * ttl, 10) assert on_loop(server, store.cleanup_expired()) == 1 diff --git a/tests/remote/unit/test_remote_music_collection.py b/tests/remote/unit/test_remote_music_collection.py index 71062b7f..e31ca86a 100644 --- a/tests/remote/unit/test_remote_music_collection.py +++ b/tests/remote/unit/test_remote_music_collection.py @@ -12,7 +12,7 @@ import pytest import responses from tests.core.test_music_renderer import OWN_FACTS, OWN_ROWS, header, mixed -from tests.remote.sessions import session_entry +from tests.remote.sessions import hold_session, session_entry from tests.remote.unit.test_session_reopen import SERVER, make_service from unshackle.core.api import handlers from unshackle.core.remote_service import RemoteError, RemoteService @@ -144,7 +144,7 @@ def test_the_title_map_keeps_the_facts(monkeypatch: pytest.MonkeyPatch) -> None: def test_a_reopened_session_keeps_the_facts(monkeypatch: pytest.MonkeyPatch) -> None: client = client_of(titles_reply(monkeypatch, served(mixed(**FACTS)))) client.get_titles() - monkeypatch.setattr(client, "authenticate", lambda credential=None: setattr(client, "_session_id", "s2")) + monkeypatch.setattr(client, "authenticate", lambda credential=None: hold_session(client, "s2")) responses.add(responses.GET, f"{SERVER}/api/health", json={"status": "ok", "draining": False}) responses.add( responses.GET, diff --git a/tests/remote/unit/test_remote_probes.py b/tests/remote/unit/test_remote_probes.py index 619c4783..d94855e0 100644 --- a/tests/remote/unit/test_remote_probes.py +++ b/tests/remote/unit/test_remote_probes.py @@ -64,7 +64,7 @@ def test_recover_moves_to_the_next_auth_header() -> None: @responses.activate def test_server_draining_moves_to_the_next_auth_header() -> None: service = make_service() - service.channel = PollingChannel(ServerMessages(service)) + service.lifetime.channel = PollingChannel(ServerMessages(service)) responses.add_callback(responses.GET, f"{SERVER}/api/session/s1", callback=second_header_only({"draining": True})) assert service.server_draining() diff --git a/tests/remote/unit/test_remote_protocol.py b/tests/remote/unit/test_remote_protocol.py index 0745afce..ecc866e0 100644 --- a/tests/remote/unit/test_remote_protocol.py +++ b/tests/remote/unit/test_remote_protocol.py @@ -10,7 +10,7 @@ from typing import Any import pytest import yaml -from unshackle.core import remote_channel +from unshackle.core import remote_channel, remote_lifetime from unshackle.core import remote_protocol as protocol from unshackle.core import remote_service from unshackle.core.api import routes @@ -23,7 +23,6 @@ CLIENT_METHODS = { "probe": "GET", "post": "POST", "post_optional": "POST", - "delete": "DELETE", "ws_connect": "GET", } SERVED = {(method, path): handler for method, path, handler, _ in routes.ROUTES} @@ -31,8 +30,11 @@ SERVED = {(method, path): handler for method, path, handler, _ in routes.ROUTES} @functools.cache def client_tree() -> ast.Module: - """The client modules as one tree: the remote service and the session channel adapters.""" - modules = [ast.parse(Path(m.__file__).read_text(encoding="utf-8")) for m in (remote_service, remote_channel)] + """The client modules as one tree: the remote service, the session channel adapters and the session lifetime.""" + modules = [ + ast.parse(Path(m.__file__).read_text(encoding="utf-8")) + for m in (remote_service, remote_channel, remote_lifetime) + ] return ast.Module(body=[node for module in modules for node in module.body], type_ignores=[]) @@ -140,6 +142,7 @@ def test_session_transport_keys_are_the_create_body(): assert SESSION_TRANSPORT_KEYS == { "service", "title_id", + "session_id", "profile", "service_params", "season", diff --git a/tests/remote/unit/test_remote_relay.py b/tests/remote/unit/test_remote_relay.py index 7c682e6e..5bbd0624 100644 --- a/tests/remote/unit/test_remote_relay.py +++ b/tests/remote/unit/test_remote_relay.py @@ -5,6 +5,7 @@ from types import SimpleNamespace import pytest +from tests.remote.sessions import hold_session from unshackle.core import remote_service from unshackle.core.api import handlers from unshackle.core.api.errors import APIError @@ -173,7 +174,7 @@ def test_remote_error_carries_its_reason_and_exits_a_cli_run(): def test_quiet_mutes_a_remote_error_the_caller_reports(caplog): with caplog.at_level("DEBUG", logger="remote_service"), remote_service.quiet(): - with remote_service.quiet(): + with remote_service.quiet(lambda: False): remote_service.RemoteError("Server error [SERVICE_ERROR]: refused", "SERVICE_ERROR") remote_service.RemoteError("Remote auth failed: bad key", "AUTH") remote_service.RemoteError("Server error [NOT_FOUND]: outside", "NOT_FOUND") @@ -234,7 +235,8 @@ def test_a_quiet_remote_login_shows_its_last_server_lines_as_a_notice(monkeypatc remote = object.__new__(remote_service.RemoteService) remote.seq = 0 - remote.client, remote._session_id, remote.auth_notice, remote.auth_qr = Client(), "sid", None, None + remote.client, remote.auth_notice, remote.auth_qr = Client(), None, None + hold_session(remote) remote.log = logging.getLogger("test") monkeypatch.setattr(remote_service.RemoteService, "local_cdm", None) diff --git a/tests/remote/unit/test_remote_service_helpers.py b/tests/remote/unit/test_remote_service_helpers.py index 7a7e3f4c..b27c9d40 100644 --- a/tests/remote/unit/test_remote_service_helpers.py +++ b/tests/remote/unit/test_remote_service_helpers.py @@ -8,7 +8,7 @@ from enum import Enum import pytest -from tests.remote.sessions import session_entry, stub_service_build +from tests.remote.sessions import hold_session, session_entry, stub_service_build from unshackle.core.manifests.snapshot import match_track from unshackle.core.remote_service import RemoteService from unshackle.core.titles.episode import Episode @@ -569,12 +569,8 @@ async def test_session_delete_returns_nested_cache_keys(tmp_path, monkeypatch) - async def fake_validated(session_id, request): return session - class FakeStore: - async def delete(self, session_id): - return True - monkeypatch.setattr(handlers, "get_validated_session", fake_validated) - monkeypatch.setattr(session_store, "get_session_store", lambda: FakeStore()) + monkeypatch.setattr(session_store, "get_session_store", session_store.SessionStore) response = await handlers.session_delete_handler("sid", None) body = json.loads(response.body) @@ -663,6 +659,7 @@ def test_a_session_create_that_fails_after_the_cache_write_leaves_no_cache_dir(t from types import SimpleNamespace from unshackle.core.api import handlers + from unshackle.core.api.session_store import SessionStore class Stop(Exception): pass @@ -685,14 +682,14 @@ def test_a_session_create_that_fails_after_the_cache_write_leaves_no_cache_dir(t stub_service_build(monkeypatch, lambda: SimpleNamespace(log=logging.getLogger("Svc"))) monkeypatch.setattr("unshackle.core.api.session_store.refuse_while_draining", lambda: None) - class RefusingStore: + class RefusingStore(SessionStore): async def create(self, *args, **kwargs): + if stop_at == "after_insert": + await super().create(*args, **kwargs) raise Stop() - def peek(self, session_id): - return object() if stop_at == "after_insert" else None - - monkeypatch.setattr("unshackle.core.api.session_store.get_session_store", RefusingStore) + store = RefusingStore() + monkeypatch.setattr("unshackle.core.api.session_store.get_session_store", lambda: store) data = {"service": "TESTSVC", "title_id": "t", "cache": {"token": blob('"t"')}} response = asyncio.run(handlers.session_create_handler(data)) @@ -725,6 +722,7 @@ def _remote_service(parent_params: dict, service_params: dict) -> RemoteService: svc.session = requests.Session() svc.log = logging.getLogger("test") svc.client = SimpleNamespace(post=post, server_url="https://server.example") + hold_session(svc, None) return svc diff --git a/tests/remote/unit/test_remote_service_server_cdm_license.py b/tests/remote/unit/test_remote_service_server_cdm_license.py index 34aed845..7e27b299 100644 --- a/tests/remote/unit/test_remote_service_server_cdm_license.py +++ b/tests/remote/unit/test_remote_service_server_cdm_license.py @@ -14,6 +14,7 @@ import pytest from tests.core.key_resolver import key_table, resolver from tests.remote.key_source import remote_keys +from tests.remote.sessions import hold_session from unshackle.core.api.errors import categorize_exception from unshackle.core.remote_protocol import APIErrorCode, LicensingMode, Licensor @@ -53,7 +54,7 @@ def _service(server_type, answer): svc = remote_keys(server_cdm_type=server_type) svc._track_alias = {} svc._title_alias = {} - svc._session_id = "sess" + hold_session(svc, "sess") svc.log = logging.getLogger("test-remote-license") svc.client = _Client(answer) return svc diff --git a/tests/remote/unit/test_segment_filter.py b/tests/remote/unit/test_segment_filter.py index b313d5fb..db752dd0 100644 --- a/tests/remote/unit/test_segment_filter.py +++ b/tests/remote/unit/test_segment_filter.py @@ -9,7 +9,7 @@ import click import pytest import responses -from tests.remote.sessions import session_entry +from tests.remote.sessions import hold_session, session_entry from unshackle.core.api import handlers from unshackle.core.remote_service import RemoteClient, RemoteService @@ -64,7 +64,7 @@ def make_service(unwanted, status=200, error=None): service._track_alias = {} service._title_alias = {} service.client = RemoteClient(server_url="http://srv:8786", api_key="k") - service._session_id = "s1" + hold_session(service, "s1") service._segment_filters = {} responses.add( responses.POST, diff --git a/tests/remote/unit/test_server_cdm_key_verification.py b/tests/remote/unit/test_server_cdm_key_verification.py index 9561307b..98daeaef 100644 --- a/tests/remote/unit/test_server_cdm_key_verification.py +++ b/tests/remote/unit/test_server_cdm_key_verification.py @@ -15,7 +15,7 @@ import pytest from tests.core.key_resolver import vaults_of from tests.remote.key_source import one_title, remote_keys -from tests.remote.sessions import session_entry +from tests.remote.sessions import hold_session, session_entry from unshackle.core.api import handlers, server_keys from unshackle.core.api.errors import APIError from unshackle.core.drm import BlowfishStripe, ClearKeyCTR @@ -34,7 +34,7 @@ def remote_service() -> RemoteService: svc = remote_keys(server_cdm=None) svc._track_alias = {} svc._title_alias = {} - svc._session_id = "sess" + hold_session(svc, "sess") svc.log = SimpleNamespace(warning=lambda *a, **k: None) return svc diff --git a/tests/remote/unit/test_server_cdm_max_height.py b/tests/remote/unit/test_server_cdm_max_height.py index 98b1b451..c5bc4e27 100644 --- a/tests/remote/unit/test_server_cdm_max_height.py +++ b/tests/remote/unit/test_server_cdm_max_height.py @@ -634,9 +634,9 @@ def created(answer, monkeypatch): svc, _ = sent_create(None, cdm_entry=True, cdm_map={"EXAMPLE1": "my_device"}) svc._server_cdm_request = None svc.client = SimpleNamespace(post=lambda path, data: {"session_id": "sess", **answer}) - svc.close = lambda: None channel = SimpleNamespace(keep_alive=lambda: None, drain_logs=lambda: None, in_flight=None) monkeypatch.setattr(remote_channel, "open_channel", lambda service: channel) + monkeypatch.setattr("atexit.register", lambda hook: None) svc.authenticate() return svc diff --git a/tests/remote/unit/test_server_vault_push.py b/tests/remote/unit/test_server_vault_push.py index 8f5d2620..0f9afcf7 100644 --- a/tests/remote/unit/test_server_vault_push.py +++ b/tests/remote/unit/test_server_vault_push.py @@ -18,7 +18,7 @@ from pywidevine.pssh import PSSH from tests.core.key_resolver import key_table, resolver from tests.remote.key_source import remote_keys -from tests.remote.sessions import session_entry +from tests.remote.sessions import hold_session, session_entry from unshackle.core import remote_channel from unshackle.core.api import handlers, server_keys from unshackle.core.cdm.detect import cdm_type_stub @@ -51,7 +51,7 @@ class Remote(SQLite): def client(posts: list) -> RemoteService: svc = remote_keys(server_cdm=False) - svc._session_id = "sess" + hold_session(svc, "sess") svc._track_alias = {"v1": "v9"} svc.client = SimpleNamespace( send=lambda method, endpoint, timeout, background, json: posts.append((method, endpoint, background, json)) diff --git a/tests/remote/unit/test_session_lifetime.py b/tests/remote/unit/test_session_lifetime.py new file mode 100644 index 00000000..d8741e8d --- /dev/null +++ b/tests/remote/unit/test_session_lifetime.py @@ -0,0 +1,1092 @@ +"""Who ends a remote session, and when: the client before and after the create reply, and the server during the build.""" + +from __future__ import annotations + +import asyncio +import atexit +import contextlib +import signal +import subprocess +import sys +import uuid +from collections.abc import Callable, Iterator +from pathlib import Path +from threading import Event, Thread +from types import SimpleNamespace +from typing import Any + +import pytest +import requests +import responses +from requests.adapters import HTTPAdapter + +from tests.remote.unit.test_remote_loopback import server # noqa: F401 +from tests.remote.unit.test_remote_loopback import ( + KEY, + OTHER_KEY, + StubService, + count, + make_client, +) +from tests.remote.unit.test_remote_service_helpers import blob +from tests.remote.unit.test_session_reopen import SERVER, make_service +from tests.remote.unit.test_tunnel import wait_until +from unshackle.core import remote_channel, remote_service +from unshackle.core.api import handlers, routes, session_store +from unshackle.core.api.download_manager import busy_services +from unshackle.core.api.session_store import SessionEntry +from unshackle.core.config import config +from unshackle.core.remote_channel import PollingChannel, ServerMessages, WebSocketChannel +from unshackle.core.remote_lifetime import Presses, RemoteSessionLifetime +from unshackle.core.remote_protocol import SESSION_CREATE_ROUTE, SESSION_ROUTE, APIErrorCode, ClientErrorKind +from unshackle.core.remote_service import RemoteError, RemoteService +from unshackle.core.tunnel import TunnelClient + +pytestmark = pytest.mark.unit + +ROOT = Path(__file__).parents[3] +DEADLINE = 20.0 +posix_signals = pytest.mark.skipif(sys.platform == "win32", reason="a test cannot send SIGINT to one process") + +CLIENT = """ +import sys, time +from pathlib import Path +import click +from unshackle.core.config import config +config.directories.cache = Path(sys.argv[2]) +config.directories.cookies = Path(sys.argv[2]) / "cookies" +config.credentials = {} +from tests.remote.unit.test_remote_loopback import make_client +service = make_client(sys.argv[1]) +@click.command() +def run(): + service.authenticate() + print("authenticated", flush=True) + if sys.argv[3:]: + service.close() + print("closed", flush=True) + time.sleep(120) +run(args=[]) +""" + + +def sessions() -> list[SessionEntry]: + return session_store.get_session_store().list() + + +def cache_files() -> list[Path]: + return list(config.directories.cache.rglob("*.json")) + + +@pytest.fixture(autouse=True) +def no_presses(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(Presses, "count", 0) + + +@pytest.fixture +def logins(monkeypatch: pytest.MonkeyPatch) -> list[Any]: + """The logins that the server started; each one succeeds at once.""" + started: list[Any] = [] + monkeypatch.setattr(StubService, "authenticate", lambda self, cookies, credential: started.append(self)) + return started + + +@pytest.fixture +def build(server: SimpleNamespace, logins: list[Any]) -> Iterator[SimpleNamespace]: # noqa: F811 + """A server whose first service build waits for ``release``.""" + barrier = SimpleNamespace(server=server, logins=logins, started=Event(), release=Event()) + + def hold(stub: StubService) -> None: + if not barrier.started.is_set(): + barrier.started.set() + assert barrier.release.wait(DEADLINE), "the test did not release the build" + + StubService.hooks["init"] = hold + try: + yield barrier + finally: + barrier.release.set() + + +def create(url: str, session_id: Any, key: str = KEY, **body: Any) -> requests.Response: + data = {"service": "EXAMPLE", "title_id": "example-1", "session_id": session_id, **body} + return requests.post(url + SESSION_CREATE_ROUTE, json=data, headers={"X-Secret-Key": key}, timeout=DEADLINE) + + +def delete(url: str, session_id: str, key: str = KEY) -> requests.Response: + route = SESSION_ROUTE.format(session_id=session_id) + return requests.delete(url + route, headers={"X-Secret-Key": key}, timeout=DEADLINE) + + +def in_thread(call: Callable[[], Any]) -> Callable[[], Any]: + """Run *call* on a thread; the returned function waits for its result, or for the exception it raised.""" + result: list[Any] = [] + + def run() -> None: + try: + result.append(call()) + except BaseException as e: + result.append(e) + + thread = Thread(target=run, daemon=True) + thread.start() + + def wait() -> Any: + thread.join(DEADLINE) + assert not thread.is_alive() + return result[0] + + return wait + + +def error_code(response: requests.Response) -> str: + return response.json()["error_code"] + + +def answered(server: SimpleNamespace, status: int) -> bool: # noqa: F811 + return ("POST", SESSION_CREATE_ROUTE, status) in server.seen + + +@pytest.fixture +def client(tmp_path: Path) -> Iterator[Callable[..., subprocess.Popen[str]]]: + """Start a client process that logs in and then waits; its returned cache goes to ``client-cache``.""" + started: list[subprocess.Popen[str]] = [] + + def start(url: str, *then: str) -> subprocess.Popen[str]: + process = subprocess.Popen( + [sys.executable, "-c", CLIENT, url, str(tmp_path / "client-cache"), *then], + cwd=ROOT, + stdin=subprocess.DEVNULL, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + text=True, + encoding="utf-8", + errors="replace", + start_new_session=True, + ) + started.append(process) + return process + + yield start + for process in started: + process.kill() + process.communicate() + + +def wait_authenticated(process: subprocess.Popen[str]) -> None: + assert process.stdout is not None + for line in process.stdout: + if "authenticated" in line: + return + pytest.fail("the client did not log in") + + +@posix_signals +def test_a_ctrl_c_before_the_create_reply_leaves_no_session( + build: SimpleNamespace, client: Callable[[str], subprocess.Popen[str]] +) -> None: + process = client(build.server.url) + assert build.started.wait(DEADLINE) + process.send_signal(signal.SIGINT) + process.communicate(timeout=DEADLINE) + assert count(build.server, "DELETE", SESSION_ROUTE) == 1 + + build.release.set() + assert wait_until(lambda: answered(build.server, 404) or answered(build.server, 200), DEADLINE) + assert sessions() == [] + assert build.logins == [] + + +class HeldDelete: + """The DELETE route of the server, which waits for ``release`` before it does its work.""" + + def __init__(self, monkeypatch: pytest.MonkeyPatch) -> None: + self.started, self.release = Event(), Event() + handler = routes.session_delete_handler + + async def held(session_id: str, request: Any) -> Any: + self.started.set() + while not self.release.is_set(): + await asyncio.sleep(0.01) + return await handler(session_id, request) + + monkeypatch.setattr(routes, "session_delete_handler", held) + + +@pytest.fixture +def held_delete(monkeypatch: pytest.MonkeyPatch) -> Iterator[HeldDelete]: + held = HeldDelete(monkeypatch) + yield held + held.release.set() + + +def press_while_it_waits(process: subprocess.Popen[str]) -> None: + """Send one Ctrl+C that the client must survive.""" + process.send_signal(signal.SIGINT) + with pytest.raises(subprocess.TimeoutExpired): + process.wait(0.3) + + +@posix_signals +@pytest.mark.parametrize("gives_up", [False, True], ids=["one-press", "two-presses"]) +@pytest.mark.parametrize("phase", ["create", "idle"]) +def test_a_ctrl_c_during_the_end_is_ignored_once( + build: SimpleNamespace, + held_delete: HeldDelete, + client: Callable[[str], subprocess.Popen[str]], + tmp_path: Path, + phase: str, + gives_up: bool, +) -> None: + """The first Ctrl+C starts the end, and the two that count come while its DELETE waits for the server.""" + process = client(build.server.url) + assert build.started.wait(DEADLINE) + if phase == "idle": + build.release.set() + wait_authenticated(process) + (entry,) = sessions() + stored = config.directories.cache / str(entry.cache_tag) / "token.json" + stored.parent.mkdir(parents=True) + stored.write_text('"EXAMPLE"', encoding="utf-8") + + process.send_signal(signal.SIGINT) + assert held_delete.started.wait(DEADLINE) + press_while_it_waits(process) + if gives_up: + process.send_signal(signal.SIGINT) + else: + held_delete.release.set() + output, _ = process.communicate(timeout=DEADLINE) + held_delete.release.set() + assert wait_until(lambda: count(build.server, "DELETE", SESSION_ROUTE) == 1, DEADLINE) + build.release.set() + assert wait_until(lambda: answered(build.server, 404 if phase == "create" else 200), DEADLINE) + + assert "Traceback" not in output and "KeyboardInterrupt" not in output + saved = (tmp_path / "client-cache" / "EXAMPLE" / "token.json").exists() + assert saved is (phase == "idle" and not gives_up) + assert count(build.server, "DELETE", SESSION_ROUTE) == 1 and sessions() == [] + assert len(build.logins) == (phase == "idle") + + +@posix_signals +def test_giving_up_on_the_close_of_the_run_stops_the_run( + server: SimpleNamespace, # noqa: F811 + logins: list[Any], + held_delete: HeldDelete, + client: Callable[..., subprocess.Popen[str]], +) -> None: + process = client(server.url, "close") + assert held_delete.started.wait(DEADLINE) + press_while_it_waits(process) + process.send_signal(signal.SIGINT) + output, _ = process.communicate(timeout=DEADLINE) + + assert "closed" not in output and "Aborted" in output and "Traceback" not in output + + +def test_a_delete_of_the_owner_ends_a_create_in_progress(build: SimpleNamespace) -> None: + session_id = str(uuid.uuid4()) + reply = in_thread(lambda: create(build.server.url, session_id, cache={"token": blob('"EXAMPLE"')})) + assert build.started.wait(DEADLINE) + + assert delete(build.server.url, session_id, OTHER_KEY).status_code == 404 + assert delete(build.server.url, session_id).status_code == 200 + build.release.set() + + assert error_code(reply()) == APIErrorCode.SESSION_NOT_FOUND + assert sessions() == [] and build.logins == [] + assert not (config.directories.cache / "_sessions").exists() + assert delete(build.server.url, session_id).status_code == 404 + + +def test_a_delete_of_another_key_leaves_a_create_in_progress(build: SimpleNamespace) -> None: + session_id = str(uuid.uuid4()) + reply = in_thread(lambda: create(build.server.url, session_id)) + assert build.started.wait(DEADLINE) + + assert error_code(delete(build.server.url, session_id, OTHER_KEY)) == APIErrorCode.SESSION_NOT_FOUND + build.release.set() + + assert reply().json()["session_id"] == session_id + assert [s.session_id for s in sessions()] == [session_id] + + +def test_the_id_of_another_key_is_refused(build: SimpleNamespace) -> None: + session_id = str(uuid.uuid4()) + reply = in_thread(lambda: create(build.server.url, session_id)) + assert build.started.wait(DEADLINE) + + assert error_code(create(build.server.url, session_id, OTHER_KEY)) == APIErrorCode.FORBIDDEN + build.release.set() + assert reply().status_code == 200 + (entry,) = sessions() + + assert error_code(create(build.server.url, session_id, OTHER_KEY)) == APIErrorCode.FORBIDDEN + assert sessions() == [entry] and not entry.channel.ended + + +def test_a_create_sent_again_takes_over_from_the_one_in_progress(build: SimpleNamespace) -> None: + """A gateway error page makes the client send the same create again while the server still builds the first.""" + session_id = str(uuid.uuid4()) + cache = {"token": blob('"EXAMPLE"')} + first = in_thread(lambda: create(build.server.url, session_id, cache=cache)) + assert build.started.wait(DEADLINE) + + assert create(build.server.url, session_id, cache=cache).status_code == 200 + (entry,) = sessions() + build.release.set() + + assert error_code(first()) == APIErrorCode.SESSION_NOT_FOUND + assert sessions() == [entry] and entry.owner_key == KEY + assert cache_files() == [config.directories.cache / str(entry.cache_tag) / "token.json"] + + +def test_a_create_sent_again_after_its_delete_is_refused(build: SimpleNamespace) -> None: + session_id = str(uuid.uuid4()) + first = in_thread(lambda: create(build.server.url, session_id)) + assert build.started.wait(DEADLINE) + assert delete(build.server.url, session_id).status_code == 200 + + assert error_code(create(build.server.url, session_id)) == APIErrorCode.SESSION_NOT_FOUND + build.release.set() + assert error_code(first()) == APIErrorCode.SESSION_NOT_FOUND + assert sessions() == [] + + +def test_a_create_sent_again_replaces_the_open_session_when_it_is_stored(build: SimpleNamespace) -> None: + build.started.set() + session_id = str(uuid.uuid4()) + assert create(build.server.url, session_id, cache={"token": blob('"EXAMPLE"')}).status_code == 200 + (first,) = sessions() + + build.started.clear() + reply = in_thread(lambda: create(build.server.url, session_id, cache={"token": blob('"EXAMPLE"')})) + assert build.started.wait(DEADLINE) + assert sessions() == [first] and not first.channel.ended + build.release.set() + + assert reply().status_code == 200 + (second,) = sessions() + assert second is not first and second.session_id == session_id + assert first.channel.ended and not second.channel.ended + assert cache_files() == [config.directories.cache / str(second.cache_tag) / "token.json"] + + +@pytest.mark.parametrize("fault", ["body", "build", "cache"]) +def test_a_create_sent_again_that_fails_leaves_the_open_session( + server: SimpleNamespace, # noqa: F811 + logins: list[Any], + monkeypatch: pytest.MonkeyPatch, + fault: str, +) -> None: + session_id = str(uuid.uuid4()) + assert create(server.url, session_id, cache={"token": blob('"EXAMPLE"')}).status_code == 200 + (first,) = sessions() + stored = cache_files() + + if fault == "build": + monkeypatch.setitem(StubService.hooks, "init", lambda stub: 1 / 0) + body: dict[str, Any] = {"body": {"title_id": ""}, "build": {}, "cache": {"cache": [1]}}[fault] + assert create(server.url, session_id, **body).status_code >= 400 + assert sessions() == [first] and not first.channel.ended + assert cache_files() == stored and len(stored) == 1 + + +def test_a_delete_ends_both_the_open_session_and_the_create_that_would_replace_it(build: SimpleNamespace) -> None: + build.started.set() + session_id = str(uuid.uuid4()) + assert create(build.server.url, session_id).status_code == 200 + build.started.clear() + reply = in_thread(lambda: create(build.server.url, session_id)) + assert build.started.wait(DEADLINE) + + assert delete(build.server.url, session_id).status_code == 200 + assert sessions() == [] + build.release.set() + assert error_code(reply()) == APIErrorCode.SESSION_NOT_FOUND + assert sessions() == [] + + +@pytest.mark.skipif(sys.platform == "darwin", reason="macOS has only one loopback address") +@pytest.mark.parametrize("state", ["pending", "open"]) +def test_an_id_stays_with_the_address_that_made_it(build: SimpleNamespace, state: str) -> None: + """Every address is a different client, as in no-key mode, where all of them have the same API key.""" + + class OtherAddress(HTTPAdapter): + def init_poolmanager(self, *args: Any, **kwargs: Any) -> None: + super().init_poolmanager(*args, source_address=("127.0.0.2", 0), **kwargs) + + other = requests.Session() + other.mount("http://", OtherAddress()) + headers = {"X-Secret-Key": KEY} + session_id = str(uuid.uuid4()) + body = {"service": "EXAMPLE", "title_id": "example-1", "session_id": session_id} + reply = in_thread(lambda: create(build.server.url, session_id)) + assert build.started.wait(DEADLINE) + if state == "open": + build.release.set() + assert reply().status_code == 200 + + url = build.server.url + refused = other.post(url + SESSION_CREATE_ROUTE, json=body, headers=headers, timeout=DEADLINE) + assert error_code(refused) == APIErrorCode.FORBIDDEN + deleted = other.delete(url + SESSION_ROUTE.format(session_id=session_id), headers=headers, timeout=DEADLINE) + assert deleted.status_code == (404 if state == "pending" else 403) + build.release.set() + + assert reply().status_code == 200 + (entry,) = sessions() + assert entry.session_id == session_id and not entry.channel.ended + + +def test_the_end_of_a_replaced_create_leaves_the_next_one_pending(build: SimpleNamespace) -> None: + """The first create finishes while the second one still builds, and a DELETE must still find the second.""" + session_id = str(uuid.uuid4()) + second = SimpleNamespace(started=Event(), release=Event()) + hold_first = StubService.hooks["init"] + + def hold(stub: StubService) -> None: + if not build.started.is_set(): + hold_first(stub) + else: + second.started.set() + assert second.release.wait(DEADLINE) + + StubService.hooks["init"] = hold + first = in_thread(lambda: create(build.server.url, session_id)) + assert build.started.wait(DEADLINE) + again = in_thread(lambda: create(build.server.url, session_id)) + assert second.started.wait(DEADLINE) + build.release.set() + assert error_code(first()) == APIErrorCode.SESSION_NOT_FOUND + + assert delete(build.server.url, session_id).status_code == 200 + second.release.set() + assert error_code(again()) == APIErrorCode.SESSION_NOT_FOUND + assert sessions() == [] + + +def test_a_create_ended_before_its_build_builds_nothing( + server: SimpleNamespace, # noqa: F811 + logins: list[Any], + monkeypatch: pytest.MonkeyPatch, +) -> None: + started, release = Event(), Event() + + def resolve(*args: Any) -> Any: + started.set() + assert release.wait(DEADLINE) + return None, [] + + monkeypatch.setattr(handlers, "resolve_handler_proxy", resolve) + session_id = str(uuid.uuid4()) + reply = in_thread(lambda: create(server.url, session_id)) + assert started.wait(DEADLINE) + assert delete(server.url, session_id).status_code == 200 + release.set() + assert error_code(reply()) == APIErrorCode.SESSION_NOT_FOUND + assert StubService.logins == 0 + + +def test_a_session_deleted_between_its_store_and_its_login_starts_no_login( + server: SimpleNamespace, # noqa: F811 + logins: list[Any], + monkeypatch: pytest.MonkeyPatch, +) -> None: + """The store removes the cache directory of an evicted session after it stored the new one.""" + store = session_store.get_session_store() + real = store.create + + async def create_then_delete(*args: Any, **kwargs: Any) -> SessionEntry: + entry = await real(*args, **kwargs) + await store.delete(entry.session_id) + return entry + + monkeypatch.setattr(store, "create", create_then_delete) + assert error_code(create(server.url, str(uuid.uuid4()))) == APIErrorCode.SESSION_NOT_FOUND + assert logins == [] + + +def test_a_service_that_a_create_builds_is_not_reloaded( + build: SimpleNamespace, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setattr("unshackle.core.api.stats.stats.mode", "remote_only") + scheduled: list[str] = [] + monkeypatch.setattr(session_store, "_schedule_pending_reload", scheduled.append) + reply = in_thread(lambda: create(build.server.url, str(uuid.uuid4()))) + assert build.started.wait(DEADLINE) + assert busy_services() == {"EXAMPLE"} and scheduled == [] + build.release.set() + assert reply().status_code == 200 + assert scheduled == ["EXAMPLE"] + + +def test_a_create_that_is_refused_holds_no_id( + server: SimpleNamespace, # noqa: F811 + logins: list[Any], + monkeypatch: pytest.MonkeyPatch, +) -> None: + session_id = str(uuid.uuid4()) + with monkeypatch.context() as broken: + broken.setitem(StubService.hooks, "init", lambda stub: 1 / 0) + assert create(server.url, session_id).status_code == 422 + assert delete(server.url, session_id).status_code == 404 + assert create(server.url, session_id, OTHER_KEY).status_code == 200 + + +@pytest.mark.parametrize( + "session_id", + [ + None, + "", + 7, + "../../etc", + "0f9e1c52-7b1c-11ef-9cd2-0242ac120002", + "0F9E1C52-7B1C-41EF-9CD2-0242AC120002", + "{0f9e1c52-7b1c-41ef-9cd2-0242ac120002}", + "0f9e1c527b1c41ef9cd20242ac120002", + "0f9e1c52-7b1c-41ef-9cd2-0242ac120002 ", + ], + ids=["null", "empty", "number", "path", "version-1", "upper-case", "braces", "no-dashes", "space"], +) +def test_an_id_that_is_not_a_canonical_uuid4_is_refused(server: SimpleNamespace, session_id: Any) -> None: # noqa: F811 + reply = create(server.url, session_id) + assert reply.status_code == 400 and error_code(reply) == APIErrorCode.INVALID_INPUT + assert StubService.logins == 0 + + +def test_the_server_takes_the_id_that_the_client_names() -> None: + named = RemoteSessionLifetime(SimpleNamespace(), lambda cache: None).name() # type: ignore[arg-type] + assert handlers.new_session_id({"session_id": named}) == named + assert uuid.UUID(handlers.new_session_id({})).version == 4 + + +def test_a_create_that_times_out_is_deleted(build: SimpleNamespace) -> None: + service = make_client(build.server.url) + service.client.timeout = 1.0 + with pytest.raises(RemoteError) as e: + service.authenticate() + assert e.value.kind == ClientErrorKind.TIMEOUT + assert count(build.server, "DELETE", SESSION_ROUTE) == 1 + assert service._session_id is None + + build.release.set() + assert wait_until(lambda: answered(build.server, 404) or answered(build.server, 200), DEADLINE) + assert sessions() == [] and build.logins == [] + service.close() + assert count(build.server, "DELETE", SESSION_ROUTE) == 1 + + +@pytest.mark.parametrize("older", [False, True], ids=["server", "older-server"]) +def test_a_create_that_answers_after_the_end_leaves_no_session( + build: SimpleNamespace, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture, older: bool +) -> None: + """An older server picks the id itself, so the DELETE of the named id finds nothing and the reply is deleted.""" + if older: + monkeypatch.setattr(handlers, "new_session_id", lambda data: str(uuid.uuid4())) + service = make_client(build.server.url) + opened = in_thread(service.authenticate) + assert build.started.wait(DEADLINE) + + service.close() + build.release.set() + + error = opened() + assert isinstance(error, RemoteError) and error.kind == APIErrorCode.SESSION_NOT_FOUND + assert sessions() == [] + assert service._session_id is None and service.channel is None + assert not [seen for seen in build.server.seen if seen[0] == "GET"] + assert not [r for r in caplog.records if r.levelname == "ERROR"] + + +def test_the_client_takes_the_id_that_an_older_server_picks( + server: SimpleNamespace, # noqa: F811 + logins: list[Any], + monkeypatch: pytest.MonkeyPatch, +) -> None: + picked = str(uuid.uuid4()) + monkeypatch.setattr(handlers, "new_session_id", lambda data: picked) + service = make_client(server.url) + service.authenticate() + assert service._session_id == picked + + service.close() + assert sessions() == [] + assert count(server, "DELETE", SESSION_ROUTE) == 1 + + +def test_an_ended_owner_never_opens_again(server: SimpleNamespace, logins: list[Any]) -> None: # noqa: F811 + service = make_client(server.url) + service.authenticate() + service.close() + + assert not service.wait_for_server(accepting=True) + assert not service.recover(None, ClientErrorKind.CONNECT) + assert not service.reopen() + with pytest.raises(RemoteError): + service.authenticate() + assert len(logins) == 1 and sessions() == [] + + +def test_the_end_does_not_wait_for_a_reopen(server: SimpleNamespace, logins: list[Any]) -> None: # noqa: F811 + service = make_client(server.url) + service.authenticate() + with service._reopen_lock: + assert in_thread(service.close)() is None + assert sessions() == [] + + +@pytest.fixture +def exit_hooks(monkeypatch: pytest.MonkeyPatch) -> list[Any]: + hooks: list[Any] = [] + monkeypatch.setattr(atexit, "register", hooks.append) + monkeypatch.setattr(atexit, "unregister", lambda hook: hooks.remove(hook) if hook in hooks else None) + return hooks + + +def local_proxy_client(monkeypatch: pytest.MonkeyPatch, start: Callable[[], str]) -> tuple[RemoteService, list[Any]]: + """A client with --local-proxy whose tunnel starts with *start*, and the tunnels that it stopped.""" + stopped: list[Any] = [] + + class Tunnel: + id = "t1" + lost = False + + def __init__(self, *args: Any) -> None: + self.start = start + + def stop(self) -> None: + stopped.append(self) + + monkeypatch.setattr(remote_service, "TunnelClient", Tunnel) + monkeypatch.setattr("unshackle.core.utils.ip_info.get_ip_info", lambda *args, **kwargs: None) + service = make_client(SERVER) + service.client._auth_header_found = True + service.ctx.parent.params = {"local_proxy": True} + return service, stopped + + +def interrupt(*args: Any) -> Any: + raise KeyboardInterrupt + + +@pytest.mark.parametrize("at", ["start", "log", "argv"]) +def test_an_exit_before_the_create_stops_the_tunnel( + monkeypatch: pytest.MonkeyPatch, exit_hooks: list[Any], at: str +) -> None: + hooked: list[int] = [] + + def start() -> str: + hooked.append(len(exit_hooks)) + return interrupt() if at == "start" else "t1" + + service, stopped = local_proxy_client(monkeypatch, start) + if at == "log": + monkeypatch.setattr(service.log, "info", interrupt) + elif at == "argv": + monkeypatch.setattr(remote_service, "launch_keys", interrupt) + + with pytest.raises(KeyboardInterrupt): + service.authenticate() + assert hooked == [1] + assert len(stopped) == 1 and service.client.tunnel is None + service.close() + assert exit_hooks == [] + + +def test_an_interrupted_end_can_run_again(exit_hooks: list[Any]) -> None: + service = make_service() + sent: list[str] = [] + saved: list[dict[str, str]] = [] + answers = [interrupt, lambda: SimpleNamespace(ok=True, json=lambda: {"cache": {"token": "x"}})] + + def send(method: str, endpoint: str, timeout: float, background: bool = False) -> Any: + assert background and timeout <= 15 + sent.append(endpoint) + return answers[len(sent) - 1]() + + service.client.send = send # type: ignore[method-assign,assignment] + service.lifetime.save_cache = saved.append + hook = service.lifetime.end_at_exit + exit_hooks.append(hook) + + with pytest.raises(KeyboardInterrupt): + service.close() + assert saved == [] and exit_hooks == [hook] + hook() + service.close() + assert sent == ["/api/session/s1"] * 2 + assert saved == [{"token": "x"}] and exit_hooks == [] + + +def test_the_end_gives_up_after_a_failed_delete_and_saves_before_the_rest( + exit_hooks: list[Any], caplog: pytest.LogCaptureFixture +) -> None: + service = make_service() + order: list[str] = [] + service.lifetime.channel = SimpleNamespace(close=lambda: order.append("channel")) # type: ignore[assignment] + service.client.tunnel = SimpleNamespace(stop=lambda: order.append("tunnel"), lost=False) # type: ignore[assignment] + service.lifetime.save_cache = lambda cache: order.append("cache") + + with responses.RequestsMock() as mocked: + mocked.add(responses.DELETE, f"{SERVER}/api/session/s1", body=requests.Timeout()) + service.close() + service.close() + assert order == ["channel", "cache", "tunnel"] + assert not [r for r in caplog.records if r.levelname in ("WARNING", "ERROR")] + + +def test_the_end_on_another_thread_leaves_the_signal_handlers() -> None: + before = signal.getsignal(signal.SIGINT) + seen: list[Any] = [] + service = make_service() + service.client.send = lambda *a, **k: seen.append(signal.getsignal(signal.SIGINT)) or interrupt() # type: ignore + + assert isinstance(in_thread(service.close)(), KeyboardInterrupt) + service.lifetime.end_at_exit() + assert seen[0] is before and seen[1] is not before + assert signal.getsignal(signal.SIGINT) is before + + +@pytest.mark.parametrize( + "kind,deleted", + [(ClientErrorKind.TUNNEL_CLOSED, True), (ClientErrorKind.TIMEOUT, True), (APIErrorCode.SESSION_NOT_FOUND, False)], +) +@responses.activate +def test_a_reopen_ends_the_session_it_gives_up(monkeypatch: pytest.MonkeyPatch, kind: str, deleted: bool) -> None: + service = make_service() + order: list[Any] = [] + service.lifetime.save_cache = order.append + monkeypatch.setattr(service, "reopen", lambda: order.append("reopen") or True) + responses.add(responses.GET, f"{SERVER}/api/health", json={"status": "ok"}) + responses.add(responses.GET, f"{SERVER}/api/session/s1", status=503, json={}) + responses.add(responses.DELETE, f"{SERVER}/api/session/s1", json={"status": "ok", "cache": {"token": "x"}}) + + assert service.recover("s1", kind) + assert order == ([{"token": "x"}] if deleted else []) + ["reopen"] + assert service._session_id is None and not service.lifetime.ended + + +def test_a_search_interrupted_in_its_tunnel_stops_it(monkeypatch: pytest.MonkeyPatch) -> None: + service, stopped = local_proxy_client(monkeypatch, interrupt) + with pytest.raises(KeyboardInterrupt): + list(service.search()) + assert len(stopped) == 1 + + +@pytest.mark.parametrize("channel", ["socket", "polling"]) +def test_an_end_during_the_login_is_silent( + server: SimpleNamespace, # noqa: F811 + monkeypatch: pytest.MonkeyPatch, + caplog: pytest.LogCaptureFixture, + channel: str, +) -> None: + asked, release = Event(), Event() + + def login(stub: StubService, cookies: Any, credential: Any) -> None: + asked.set() + release.wait(DEADLINE) + + monkeypatch.setattr(StubService, "authenticate", login) + if channel == "polling": + monkeypatch.setattr(WebSocketChannel, "open", lambda self, timeout=0: False) + service = make_client(server.url) + opened = in_thread(service.authenticate) + try: + assert asked.wait(DEADLINE) + assert wait_until(lambda: isinstance(service.channel, WebSocketChannel | PollingChannel), DEADLINE) + service.close() + assert isinstance(opened(), RemoteError) + finally: + release.set() + assert sessions() == [] + assert not [seen for seen in server.seen if "/None" in seen[1]] + assert not [r for r in caplog.records if r.levelname == "ERROR" and r.name.startswith("remote_")] + assert channel == "polling" or not service.client.no_channel + + +def test_an_end_during_the_channel_open_is_silent( + server: SimpleNamespace, # noqa: F811 + logins: list[Any], + monkeypatch: pytest.MonkeyPatch, + caplog: pytest.LogCaptureFixture, +) -> None: + service = make_client(server.url) + connect = WebSocketChannel.open + + def end_then_open(self: WebSocketChannel, timeout: float = 10) -> bool: + assert in_thread(service.close)() is None + self.stopped = False + return connect(self, timeout) + + monkeypatch.setattr(WebSocketChannel, "open", end_then_open) + with pytest.raises(RemoteError): + service.authenticate() + assert not [seen for seen in server.seen if "/None" in seen[1]] + assert not [r for r in caplog.records if r.levelname == "ERROR"] + assert not service.client.no_channel + + +def test_an_exit_in_the_channel_open_closes_the_channel( + server: SimpleNamespace, # noqa: F811 + logins: list[Any], + monkeypatch: pytest.MonkeyPatch, +) -> None: + closed: list[Any] = [] + monkeypatch.setattr(WebSocketChannel, "open", interrupt) + monkeypatch.setattr(WebSocketChannel, "close", lambda self: closed.append(self)) + service = make_client(server.url) + with pytest.raises(KeyboardInterrupt): + service.authenticate() + assert len(closed) == 1 and sessions() == [] + + +def test_a_reopen_after_a_drain_ends_the_session_and_not_its_owner( + server: SimpleNamespace, # noqa: F811 + logins: list[Any], + exit_hooks: list[Any], +) -> None: + service = make_client(server.url) + service.authenticate() + first = service._session_id + + service.reopen_after_drain() + assert [s.session_id for s in sessions()] == [service._session_id] != [first] + assert count(server, "DELETE", SESSION_ROUTE) == 1 + assert len(exit_hooks) == 1 and not service.lifetime.ended + service.close() + assert sessions() == [] and exit_hooks == [] + + +def test_the_save_of_the_returned_cache_is_not_interrupted() -> None: + service = make_service() + saved: list[dict[str, str]] = [] + + def save(cache: dict[str, str]) -> None: + signal.raise_signal(signal.SIGINT) + signal.raise_signal(signal.SIGINT) + saved.append(cache) + + service.lifetime.save_cache = save + service.client.send = lambda *a, **k: SimpleNamespace(ok=True, json=lambda: {"cache": {"token": "x"}}) # type: ignore + service.close() + assert saved == [{"token": "x"}] + + +def test_a_press_that_a_destructor_swallows_does_not_disable_the_next() -> None: + service = make_service() + + def send(*args: Any, **kwargs: Any) -> Any: + signal.raise_signal(signal.SIGINT) + with contextlib.suppress(KeyboardInterrupt): + signal.raise_signal(signal.SIGINT) + signal.raise_signal(signal.SIGINT) + pytest.fail("the third press did not stop the end") + + service.client.send = send # type: ignore[method-assign] + with pytest.raises(KeyboardInterrupt): + service.close() + + +def test_a_user_who_gave_up_waits_for_no_other_end(exit_hooks: list[Any]) -> None: + first, second = make_service(), make_service() + + def send(*args: Any, **kwargs: Any) -> Any: + signal.raise_signal(signal.SIGINT) + signal.raise_signal(signal.SIGINT) + + first.client.send = second.client.send = send # type: ignore[method-assign,assignment] + with pytest.raises(KeyboardInterrupt): + first.close() + second.client.send = pytest.fail # type: ignore[method-assign,assignment] + second.lifetime.end_at_exit() + assert second.lifetime.ended + + +def test_an_ignored_ctrl_c_stays_ignored(monkeypatch: pytest.MonkeyPatch) -> None: + """A process that nohup or a shell started with SIGINT ignored keeps that during the end.""" + service = make_service() + seen: list[Any] = [] + service.client.send = lambda *a, **k: seen.append(signal.getsignal(signal.SIGINT)) # type: ignore + before = signal.signal(signal.SIGINT, signal.SIG_IGN) + try: + service.close() + finally: + signal.signal(signal.SIGINT, before) + assert seen == [signal.SIG_IGN] + + +@pytest.mark.parametrize("fault", ["send", "body", "shape", "save"]) +def test_a_fault_of_one_delete_does_not_stop_the_rest(exit_hooks: list[Any], fault: str) -> None: + service = make_service() + service.lifetime.name() + sent: list[str] = [] + stopped: list[int] = [] + + def broken(*args: Any) -> Any: + raise {"save": SystemExit, "body": RecursionError}.get(fault, RuntimeError)("EXAMPLE fault") + + def send(method: str, endpoint: str, timeout: float, background: bool) -> Any: + sent.append(endpoint) + if fault == "send": + broken() + return SimpleNamespace(ok=True, json=broken if fault == "body" else lambda: [] if fault == "shape" else {}) + + service.client.send = send # type: ignore[method-assign] + service.client.tunnel = SimpleNamespace(stop=lambda: stopped.append(1), lost=False) # type: ignore[assignment] + if fault == "save": + service.lifetime.save_cache = broken + exit_hooks.append(service.lifetime.end_at_exit) + + service.close() + assert len(sent) == 2 and stopped == [1] and exit_hooks == [] + service.close() + assert len(sent) == 2 + + +@responses.activate +def test_the_error_of_a_failed_create_is_the_one_that_the_user_sees() -> None: + service = make_client(SERVER) + error = {"status": "error", "error_code": "AUTH_FAILED", "message": "EXAMPLE reason"} + responses.add(responses.POST, SERVER + SESSION_CREATE_ROUTE, json=error, status=422) + service.lifetime.save_cache = interrupt + with pytest.raises(RemoteError, match="EXAMPLE reason"): + service.authenticate() + + +def test_an_interrupted_channel_close_runs_again() -> None: + service = make_service() + closes = iter([interrupt, lambda: None]) + service.lifetime.channel = SimpleNamespace(close=lambda: next(closes)()) # type: ignore[assignment] + service.client.send = lambda *a, **k: SimpleNamespace(ok=False) # type: ignore + with pytest.raises(KeyboardInterrupt): + service.close() + service.close() + assert next(closes, None) is None and service.channel is None + + +def test_a_release_keeps_what_another_thread_opened_meanwhile() -> None: + service = make_service() + channel: Any = SimpleNamespace(close=lambda: None) + tunnel: Any = SimpleNamespace(stop=lambda: None, lost=False) + service.client.send = lambda *a, **k: SimpleNamespace(ok=False) # type: ignore + service.lifetime.channel = SimpleNamespace(close=lambda: setattr(service.lifetime, "channel", channel)) # type: ignore + service.client.tunnel = SimpleNamespace(stop=lambda: setattr(service.client, "tunnel", tunnel), lost=False) # type: ignore + + service.lifetime.release() + assert service.channel is channel and service.client.tunnel is tunnel + + +@pytest.mark.parametrize("at", ["hook", "create", "end"]) +def test_an_end_of_another_thread_stops_the_opening( + server: SimpleNamespace, # noqa: F811 + logins: list[Any], + exit_hooks: list[Any], + monkeypatch: pytest.MonkeyPatch, + at: str, +) -> None: + """Each test hook ends the owner from another thread at one point of the opening.""" + service = make_client(server.url) + + def end(*args: Any) -> Any: + assert in_thread(service.close)() is None + return {} + + if at == "hook": + monkeypatch.setattr(atexit, "register", lambda hook: end() and None or exit_hooks.append(hook)) + elif at == "create": + monkeypatch.setattr(remote_service, "launch_keys", end) + else: + drain = service.drain_server_logs + monkeypatch.setattr(service, "drain_server_logs", lambda: (drain(), end())) + monkeypatch.setattr(WebSocketChannel, "keep_alive", lambda self: None) + + with pytest.raises(RemoteError): + service.authenticate() + assert sessions() == [] and exit_hooks == [] + assert count(server, "POST", SESSION_CREATE_ROUTE) == (2 if at == "end" else 0) + + +def test_an_ended_owner_opens_no_tunnel(monkeypatch: pytest.MonkeyPatch) -> None: + service, _ = local_proxy_client(monkeypatch, lambda: pytest.fail("the ended owner opened a tunnel")) + service.close() + with pytest.raises(RemoteError): + service.authenticate() + + +@pytest.mark.parametrize("thread", ["tunnel", "channel"]) +def test_a_stop_before_the_thread_runs_keeps_it_from_connecting(monkeypatch: pytest.MonkeyPatch, thread: str) -> None: + connected: list[Any] = [] + + async def connect(self: Any) -> None: + connected.append(self) + + if thread == "tunnel": + tunnel = TunnelClient(SERVER, {}) + monkeypatch.setattr(TunnelClient, "connect", connect) + tunnel.stop() + tunnel.thread.run() + else: + service = make_service() + service.ctx = SimpleNamespace(obj=None) # type: ignore[assignment] + channel = WebSocketChannel(ServerMessages(service), PollingChannel(ServerMessages(service))) + monkeypatch.setattr(WebSocketChannel, "connect", connect) + channel.close() + channel.thread.run() + assert channel.attempted.is_set() + assert connected == [] + + +def test_the_end_does_not_wait_for_a_cdm_call(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(remote_channel, "CDM_CLOSE_TIMEOUT", 0.01) + service = make_service() + service.ctx = SimpleNamespace(obj=None) # type: ignore[assignment] + messages = ServerMessages(service) + with messages.cdm_lock: + assert in_thread(messages.close_cdm_sessions)() is None + + +def test_the_tunnel_test_stops_the_tunnel_it_was_interrupted_in(monkeypatch: pytest.MonkeyPatch) -> None: + from unshackle.commands import tunnel_test + + service, stopped = local_proxy_client(monkeypatch, interrupt) + monkeypatch.setattr(tunnel_test, "get_ip_info", lambda session=None: {"ip": "192.0.2.1"}) + monkeypatch.setattr(tunnel_test, "remote_client", lambda name: service.client) + with pytest.raises(KeyboardInterrupt): + tunnel_test.tunnel_test.callback(None, None) + assert len(stopped) == 1 + + +def test_a_press_after_the_end_does_not_leave_its_handler(monkeypatch: pytest.MonkeyPatch) -> None: + service = make_service() + service.client.send = lambda *a, **k: SimpleNamespace(ok=False) # type: ignore + before, set_handler = signal.getsignal(signal.SIGINT), signal.signal + + def press_first(signum: int, handler: Any) -> Any: + if handler is before: + signal.raise_signal(signal.SIGINT) + signal.raise_signal(signal.SIGINT) + return set_handler(signum, handler) + + monkeypatch.setattr(signal, "signal", press_first) + service.close() + assert signal.getsignal(signal.SIGINT) is before + + +def test_a_channel_of_an_ended_owner_stops_by_itself() -> None: + service = make_service() + service.ctx = SimpleNamespace(obj=None) # type: ignore[assignment] + channel = WebSocketChannel(ServerMessages(service), PollingChannel(ServerMessages(service))) + service.lifetime.ended = True + channel.thread.run() + assert channel.attempted.is_set() and not channel.connected.is_set() + + +def test_a_create_of_a_reopen_passes_through_the_old_channel() -> None: + """The client's in_flight hook stays the one of the closed channel until the new channel is open.""" + service = make_service() + channel = PollingChannel(ServerMessages(service)) + service.lifetime.session_id = None + with channel.in_flight(SESSION_CREATE_ROUTE): + assert channel.cdm_requests == 0 diff --git a/tests/remote/unit/test_session_log.py b/tests/remote/unit/test_session_log.py index 6c64e091..f7a6b282 100644 --- a/tests/remote/unit/test_session_log.py +++ b/tests/remote/unit/test_session_log.py @@ -4,6 +4,7 @@ import logging import pytest +from tests.remote.sessions import hold_session from unshackle.core.api.handlers import session_logs_handler from unshackle.core.api.session_log import SessionLogBuffer, SessionLogMirror, capture_service_logs from unshackle.core.api.session_store import get_session_store @@ -169,8 +170,8 @@ def test_drain_server_logs_survives_client_systemexit() -> None: from unshackle.core.remote_service import RemoteService svc = RemoteService.__new__(RemoteService) - svc._session_id = "abc" - svc.channel = PollingChannel(ServerMessages(svc)) + hold_session(svc) + svc.lifetime.channel = PollingChannel(ServerMessages(svc)) class ExitingClient: def get_optional(self, endpoint: str) -> dict: @@ -186,8 +187,8 @@ def test_drain_server_logs_reemits_and_advances_seq() -> None: from unshackle.core.remote_service import RemoteService svc = RemoteService.__new__(RemoteService) - svc._session_id = "abc" - svc.channel = PollingChannel(ServerMessages(svc)) + hold_session(svc) + svc.lifetime.channel = PollingChannel(ServerMessages(svc)) svc.log = logging.getLogger("test-drain-reemit") class StubClient: diff --git a/tests/remote/unit/test_session_reopen.py b/tests/remote/unit/test_session_reopen.py index c97833c7..f8def07d 100644 --- a/tests/remote/unit/test_session_reopen.py +++ b/tests/remote/unit/test_session_reopen.py @@ -13,6 +13,7 @@ import requests import responses from langcodes import Language +from tests.remote.sessions import hold_session from unshackle.core.remote_protocol import LicensingMode, Licensor from unshackle.core.remote_service import RemoteClient, RemoteError, RemoteService, quiet from unshackle.core.tracks import Audio @@ -43,7 +44,7 @@ def make_service() -> RemoteService: service.log = logging.getLogger("test") service.credential = None service.service_tag = service.title_id = "TEST" - service._session_id = "s1" + hold_session(service, "s1") service._reopen_lock = Lock() service._segment_filters = {} service._tracks_by_title = {} @@ -71,7 +72,7 @@ def test_a_lost_session_reopens_and_replays_the_call_under_the_new_ids(monkeypat service._tracks_by_title["ep3-aaaa"] = [held] def authenticate(credential=None): - service._session_id = "s2" + service.lifetime.session_id = "s2" monkeypatch.setattr(service, "authenticate", authenticate) monkeypatch.setattr(service, "get_tracks", lambda t: [audio("a-new")]) @@ -125,7 +126,7 @@ def rest_song(id_: str, album: str, position: Any = None, track: int = 1) -> dic def test_a_reopened_session_never_takes_another_song_for_a_playlist_song(monkeypatch, before, after, alias): service = make_service() service._titles = [build_title(info, "TEST", "x") for info in before] - monkeypatch.setattr(service, "authenticate", lambda credential=None: setattr(service, "_session_id", "s2")) + monkeypatch.setattr(service, "authenticate", lambda credential=None: hold_session(service, "s2")) responses.add(responses.GET, f"{SERVER}/api/health", json={"status": "ok", "draining": False}) responses.add(responses.GET, f"{SERVER}/api/session/s2/titles", json={"titles": after}) @@ -136,7 +137,7 @@ def test_a_reopened_session_never_takes_another_song_for_a_playlist_song(monkeyp @responses.activate def test_a_malformed_song_position_on_reopen_is_one_error_line(monkeypatch): service = make_service() - monkeypatch.setattr(service, "authenticate", lambda credential=None: setattr(service, "_session_id", "s2")) + monkeypatch.setattr(service, "authenticate", lambda credential=None: hold_session(service, "s2")) responses.add(responses.GET, f"{SERVER}/api/health", json={"status": "ok", "draining": False}) listing = {"titles": [rest_song("song-z", "Z", "x")]} responses.add(responses.GET, f"{SERVER}/api/session/s2/titles", json=listing) diff --git a/tests/test_client_session_auth.py b/tests/test_client_session_auth.py index 78d4d9ef..cdcf21ed 100644 --- a/tests/test_client_session_auth.py +++ b/tests/test_client_session_auth.py @@ -3,7 +3,7 @@ from types import SimpleNamespace import pytest import requests -from tests.remote.sessions import session_entry, stub_service_build +from tests.remote.sessions import hold_session, session_entry, stub_service_build from unshackle.core.api import server_keys from unshackle.core.api.errors import APIError from unshackle.core.api.handlers import client_session_auth, resolve_handler_proxy, scrub_track_data @@ -175,12 +175,12 @@ def test_remote_get_tracks_scopes_server_cookies(): _sample_decrypt_tracks=set(), _server_cdm_request=None, session=requests.Session(), - _session_id="s", service_tag="EXAMPLE", log=logging.getLogger("test"), client=SimpleNamespace(post=lambda path, body: {"session_cookie_jar": jar}, probe=lambda endpoint: {}), drain_server_logs=lambda: None, ) + hold_session(service) service.get_tracks(SimpleNamespace(id="t1")) cdn = service.session.prepare_request(requests.Request("GET", "https://cdn.other.net/seg.mp4")) assert "Cookie" not in cdn.headers diff --git a/unshackle/commands/tunnel_test.py b/unshackle/commands/tunnel_test.py index dc142eca..a9524025 100644 --- a/unshackle/commands/tunnel_test.py +++ b/unshackle/commands/tunnel_test.py @@ -38,12 +38,13 @@ def tunnel_test(server: str | None, proxy: str | None) -> None: log.info(f"Step 1: this machine exits at {local['ip']} ({str(local.get('country', '?')).upper()})") client = remote_client(server) - tunnel = start_tunnel(client, proxy) - log.info(f"Step 2: opened a tunnel to {safe_display_url(client.server_url)}") try: + tunnel = start_tunnel(client, proxy) + log.info(f"Step 2: opened a tunnel to {safe_display_url(client.server_url)}") remote = client.get(f"{CHECK_ROUTE}?id={tunnel.id}") finally: - tunnel.stop() + if client.tunnel: + client.tunnel.stop() country = str(remote.get("country", "?")).upper() # one exit can answer over IPv4 here and IPv6 there, so a matching country also passes diff --git a/unshackle/core/api/download_manager.py b/unshackle/core/api/download_manager.py index f3b0bd1e..2b69d885 100644 --- a/unshackle/core/api/download_manager.py +++ b/unshackle/core/api/download_manager.py @@ -906,11 +906,12 @@ async def shutdown_download_manager(_app: object) -> None: def busy_services() -> set[str]: - """Tags a hot reload must not swap: those with an unfinished job and those a live remote session uses.""" + """Tags a hot reload must not swap: those with an unfinished job and those a remote session or its create uses.""" from unshackle.core.api.session_store import get_session_store from unshackle.core.api.stats import stats - busy = {entry.service_tag for entry in get_session_store().list()} + store = get_session_store() + busy = {entry.service_tag for entry in store.list()} | store.pending_services if stats.mode != "remote_only": busy |= get_download_manager().busy_services() return busy diff --git a/unshackle/core/api/handlers.py b/unshackle/core/api/handlers.py index 2d37144a..ec481318 100644 --- a/unshackle/core/api/handlers.py +++ b/unshackle/core/api/handlers.py @@ -40,7 +40,7 @@ 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 SessionEntry, SessionStore +from unshackle.core.api.session_store import PendingCreate, SessionEntry, SessionStore, holds from unshackle.core.binaries import binary_version from unshackle.core.cacher import Cacher from unshackle.core.cdm.choice import choose_cdm, drm_system @@ -2766,6 +2766,17 @@ def client_device_cdm( ) +def new_session_id(data: dict[str, Any]) -> str: + """The id of the remote session to make: the one its client named, as a canonical UUID version 4, else a new one.""" + if "session_id" not in data: + return str(uuid.uuid4()) + named = data["session_id"] + with suppress(ValueError): + if isinstance(named, str) and str(uuid.UUID(named, version=4)) == named: + return named + raise APIError(APIErrorCode.INVALID_INPUT, "session_id must be the canonical text of a version 4 UUID") + + async def session_create_handler(data: dict[str, Any], request: web.Request | None = None) -> web.Response: """Answer the remote session creation: authenticate + get titles + get tracks + get chapters. @@ -2776,6 +2787,7 @@ async def session_create_handler(data: dict[str, Any], request: web.Request | No from unshackle.core.api.session_store import get_session_store, refuse_while_draining refuse_while_draining() + session_id = new_session_id(data) service_tag = data.get("service") title_id = data.get("title_id") profile = client_profile(data) @@ -2794,99 +2806,10 @@ async def session_create_handler(data: dict[str, Any], request: web.Request | No ) try: - proxy_param, proxy_providers = await asyncio.to_thread(resolve_handler_proxy, data, normalized_service, request) - - import uuid as uuid_mod - - session_id = str(uuid_mod.uuid4()) - api_key = caller_key(request) - policy = request_policy(request) - session_cache_dir = f"_sessions/{api_key_namespace(request)}/{session_id}/{normalized_service}" - - server_account = server_account_for(policy, normalized_service) - if server_account: - region = data.get("proxy_region") or data.get("client_region") - if region is not None and not (isinstance(region, str) and re.fullmatch(r"[A-Za-z]{2}", region)): - raise APIError(APIErrorCode.INVALID_INPUT, "proxy_region must be a two-letter country code.") - if region is None and data.get("no_proxy"): - region = await asyncio.to_thread(server_region) - profile = next_server_profile(normalized_service, region) - log.info(f"Using server account '{sanitize_log(profile or 'default')}' for {normalized_service}") - - licensing = session_licensing(policy, normalized_service, data) - bridge = InputBridge() - log_buffer = None if server_account else SessionLogBuffer() - service_class_name = getattr(Services.load(normalized_service), "__name__", normalized_service) - - purpose = SessionLaunch( - (proxy_param, proxy_providers), policy, server_account, licensing, bridge, session_cache_dir - ) - - def build_service() -> Launched: - with capture_service_logs(service_class_name, log_buffer): - return launch_served(purpose, data, normalized_service, title_id, profile, request) - - service_instance, cookies, credential, launched_licensing = await asyncio.to_thread(build_service) - licensing = launched_licensing or licensing - if log_buffer: - service_instance.log = SessionLogMirror(service_instance.log, log_buffer) - session_cache_tag = None if server_account else session_cache_dir - - cache_data = data.get("cache", {}) - client = data.get("client") - store = get_session_store() - try: - if cache_data and session_cache_tag: - await asyncio.to_thread(write_client_cache, cache_data, session_cache_tag) - session = await store.create( - normalized_service, - service_instance, - session_id=session_id, - owner_key=api_key, - creator_ip=request.remote if request else None, - server_account=(profile or "default") if server_account else None, - cache_tag=session_cache_tag, - policy=policy, - licensing=licensing, - client_auth=not server_account - and (cookies is not None or credential is not None or bool(cache_data and session_cache_tag)), - # Echoed to every dashboard viewer, so cap what an arbitrary client can push into it. - client=client if isinstance(client, dict) and len(json.dumps(client, default=str)) <= 4096 else {}, - input_bridge=bridge, - log_buffer=log_buffer, - ) - except BaseException: - if store.peek(session_id) is None: - SessionStore.cleanup_cache_dir(session_cache_tag) - raise - - async def run_auth() -> None: - try: - await asyncio.to_thread(service_instance.authenticate, cookies, credential) - if not server_account: - session.client_auth = True - bridge.login_status = AuthStatus.AUTHENTICATED - except (Exception, SystemExit) as e: - log.exception("Auth failed for session %s", session_id) - session.auth_error = redact_secrets(str(e)) - bridge.login_status = AuthStatus.FAILED - finally: - session.channel.send(status_message(session)) - if store.peek(session_id) is not session: - SessionStore.cleanup_cache_dir(session_cache_tag) - - store.track_login(asyncio.create_task(run_auth())) - - return web.json_response( - SessionCreated( - session_id=session.session_id, - service=normalized_service, - status=AuthStatus.AUTHENTICATING, - server_account=server_account, - **licensing.created_fields(), - ) - ) - + address = request.remote if request else None + pending = PendingCreate(session_id, normalized_service, caller_key(request), address) + async with get_session_store().creating(pending): + return await create_session(data, request, title_id, profile, pending) except APIError: raise except (Exception, SystemExit) as e: @@ -2899,6 +2822,114 @@ async def session_create_handler(data: dict[str, Any], request: web.Request | No ) +async def create_session( + data: dict[str, Any], + request: web.Request | None, + title_id: str, + profile: str | None, + pending: PendingCreate, +) -> web.Response: + """Build the service of a remote session, store the session and start its login, unless its client ends it first. + + The cache directory has a name of its own, as the create that replaces this one has the same session id. + """ + from unshackle.core.api.session_store import get_session_store + + normalized_service = pending.service_tag + proxy_param, proxy_providers = await asyncio.to_thread(resolve_handler_proxy, data, normalized_service, request) + + policy = request_policy(request) + session_id = pending.session_id + session_cache_dir = f"_sessions/{api_key_namespace(request)}/{uuid.uuid4()}/{normalized_service}" + + server_account = server_account_for(policy, normalized_service) + session_cache_tag = None if server_account else session_cache_dir + if server_account: + region = data.get("proxy_region") or data.get("client_region") + if region is not None and not (isinstance(region, str) and re.fullmatch(r"[A-Za-z]{2}", region)): + raise APIError(APIErrorCode.INVALID_INPUT, "proxy_region must be a two-letter country code.") + if region is None and data.get("no_proxy"): + region = await asyncio.to_thread(server_region) + profile = next_server_profile(normalized_service, region) + log.info(f"Using server account '{sanitize_log(profile or 'default')}' for {normalized_service}") + + licensing = session_licensing(policy, normalized_service, data) + bridge = InputBridge() + log_buffer = None if server_account else SessionLogBuffer() + service_class_name = getattr(Services.load(normalized_service), "__name__", normalized_service) + + purpose = SessionLaunch( + (proxy_param, proxy_providers), policy, server_account, licensing, bridge, session_cache_dir + ) + + def build_service() -> Launched: + with capture_service_logs(service_class_name, log_buffer): + return launch_served(purpose, data, normalized_service, title_id, profile, request) + + cache_data = data.get("cache", {}) + client = data.get("client") + store = get_session_store() + try: + pending.require_live() + service_instance, cookies, credential, launched_licensing = await asyncio.to_thread(build_service) + licensing = launched_licensing or licensing + if log_buffer: + service_instance.log = SessionLogMirror(service_instance.log, log_buffer) + if cache_data and session_cache_tag: + await asyncio.to_thread(write_client_cache, cache_data, session_cache_tag) + session = await store.create( + normalized_service, + service_instance, + owner_key=pending.owner_key, + creator_ip=pending.creator_ip, + server_account=(profile or "default") if server_account else None, + cache_tag=session_cache_tag, + policy=policy, + licensing=licensing, + client_auth=not server_account + and (cookies is not None or credential is not None or bool(cache_data and session_cache_tag)), + # Echoed to every dashboard viewer, so cap what an arbitrary client can push into it. + client=client if isinstance(client, dict) and len(json.dumps(client, default=str)) <= 4096 else {}, + input_bridge=bridge, + log_buffer=log_buffer, + pending=pending, + ) + if store.peek(session_id) is not session: + pending.refuse() + except BaseException: + entry = store.peek(session_id) + if entry is None or entry.cache_tag != session_cache_tag: + await SessionStore.remove_cache_dirs([session_cache_tag]) + raise + + async def run_auth() -> None: + try: + await asyncio.to_thread(service_instance.authenticate, cookies, credential) + if not server_account: + session.client_auth = True + bridge.login_status = AuthStatus.AUTHENTICATED + except (Exception, SystemExit) as e: + log.exception("Auth failed for session %s", session_id) + session.auth_error = redact_secrets(str(e)) + bridge.login_status = AuthStatus.FAILED + finally: + session.channel.send(status_message(session)) + if store.peek(session_id) is not session: + SessionStore.cleanup_cache_dir(session_cache_tag) + + store.track_login(asyncio.create_task(run_auth())) + + return web.json_response( + SessionCreated( + session_id=session.session_id, + service=normalized_service, + status=AuthStatus.AUTHENTICATING, + server_account=server_account, + **licensing.created_fields(), + ) + ) + + async def session_titles_handler(session_id: str, request: web.Request | None = None) -> web.Response: """Get titles for the authenticated remote session. @@ -3279,8 +3310,6 @@ async def get_validated_session(session_id: str, request: web.Request | None) -> behind a reverse proxy every caller shares the proxy's address, so the IP check (kept as defence in depth) cannot distinguish users on its own. """ - import hmac - from unshackle.core.api.session_store import get_session_store store = get_session_store() @@ -3291,17 +3320,8 @@ async def get_validated_session(session_id: str, request: web.Request | None) -> f"Session not found or expired: {session_id}", details={"session_id": session_id}, ) - if session.owner_key is not None and request is not None: - if not hmac.compare_digest(caller_key(request), session.owner_key): - raise APIError( - APIErrorCode.FORBIDDEN, - "Session access denied", - ) - if session.creator_ip and request and request.remote != session.creator_ip: - raise APIError( - APIErrorCode.FORBIDDEN, - "Session access denied", - ) + if request is not None and not holds(session, caller_key(request), request.remote): + raise APIError(APIErrorCode.FORBIDDEN, "Session access denied") return session @@ -3891,11 +3911,17 @@ async def session_info_handler(session_id: str, request: web.Request | None = No async def session_delete_handler(session_id: str, request: web.Request | None = None) -> web.Response: - """Delete a remote session, return updated cache files, and clean up server-side data.""" + """Delete a remote session, return updated cache files, and clean up server-side data. + + A create that the same API key still has in progress under the id ends with no remote session and no cache to return. + """ from unshackle.core.api.session_store import get_session_store - session = await get_validated_session(session_id, request) store = get_session_store() + ended = store.end_pending(session_id, caller_key(request), request.remote if request else None) + if ended and store.peek(session_id) is None: + return web.json_response(SessionClosed(status="ok")) + session = await get_validated_session(session_id, request) session.end() cache_tag = session.cache_tag diff --git a/unshackle/core/api/routes.py b/unshackle/core/api/routes.py index ced4ded3..f1ab6007 100644 --- a/unshackle/core/api/routes.py +++ b/unshackle/core/api/routes.py @@ -1980,6 +1980,14 @@ async def session_create(request: web.Request) -> web.Response: type: string title_id: type: string + session_id: + type: string + description: | + The ID that the client gives the remote session, so that it can delete the session before + this request answers. The canonical text of a version 4 UUID; the server answers any other value with + INVALID_INPUT. A create of the same API key and IP with the same ID replaces the remote session of + that ID. The server answers the ID of another API key or IP with FORBIDDEN. Without it the server + makes the ID. credentials: type: object additionalProperties: true @@ -2127,7 +2135,9 @@ async def session_create(request: web.Request) -> web.Response: '403': description: | SERVER_CDM_CAPPED when `quality` asks for more than the server CDM limit and the client - reported no local CDM + reported no local CDM; FORBIDDEN when another API key or IP has the `session_id` + '404': + description: SESSION_NOT_FOUND when a DELETE or a newer create ended the `session_id` first '401': description: Authentication failed """ @@ -2575,7 +2585,9 @@ async def session_delete(request: web.Request) -> web.Response: Delete a remote session. --- summary: Delete remote session - description: Clean up a remote session + description: >- + Clean up a remote session. A session that the same API key is still creating ends too, and its create request + then answers SESSION_NOT_FOUND. parameters: - name: session_id in: path diff --git a/unshackle/core/api/session_store.py b/unshackle/core/api/session_store.py index c7542b00..75399304 100644 --- a/unshackle/core/api/session_store.py +++ b/unshackle/core/api/session_store.py @@ -11,19 +11,22 @@ from __future__ import annotations import asyncio import builtins import contextlib +import hmac import logging import uuid from collections import Counter, deque +from collections.abc import AsyncIterator from dataclasses import dataclass, field from datetime import UTC, datetime -from typing import TYPE_CHECKING, Any +from typing import TYPE_CHECKING, Any, NoReturn +from unshackle.core.api.errors import APIError from unshackle.core.api.events import bus from unshackle.core.api.input_bridge import AUTH_INPUT_TIMEOUT, InputBridge from unshackle.core.api.sanitize import sanitize_log from unshackle.core.api.session_channel import SessionChannel, drain_message from unshackle.core.config import config -from unshackle.core.remote_protocol import AuthStatus, LicensingMode, Licensor +from unshackle.core.remote_protocol import APIErrorCode, AuthStatus, LicensingMode, Licensor from unshackle.core.tracks import Track, Tracks if TYPE_CHECKING: @@ -141,6 +144,36 @@ class SessionEntry: } +def holds(held: SessionEntry | PendingCreate, owner_key: str, creator_ip: str | None) -> bool: + """Whether a remote session or its create belongs to this API key and, when it knows one, this address.""" + if held.creator_ip and held.creator_ip != creator_ip: + return False + return held.owner_key is None or hmac.compare_digest(held.owner_key.encode(), owner_key.encode()) + + +@dataclass(eq=False) +class PendingCreate: + """A remote session creation that its handler still works on, under the id that the session will have.""" + + session_id: str + service_tag: str + owner_key: str = field(repr=False) + creator_ip: str | None + ended: bool = False + + def require_live(self) -> None: + """Raise when a DELETE or a newer create of the same id ended it.""" + if self.ended: + self.refuse() + + def refuse(self) -> NoReturn: + raise APIError( + APIErrorCode.SESSION_NOT_FOUND, + f"The client ended the remote session during its creation: {self.session_id}", + details={"session_id": self.session_id}, + ) + + def _schedule_pending_reload(service_tag: str) -> None: """Apply staged service reloads now that a remote session ended; the task runs after the store lock releases.""" from unshackle.core.api.download_manager import schedule_pending_reload @@ -165,6 +198,7 @@ class SessionStore: def __init__(self) -> None: self._sessions: dict[str, SessionEntry] = {} + self._pending: dict[str, PendingCreate] = {} self._lock = asyncio.Lock() self._cleanup_task: asyncio.Task | None = None self._logins: set[asyncio.Task[None]] = set() @@ -185,6 +219,43 @@ class SessionStore: limit = config.serve.get("max_sessions", 100) return limit if isinstance(limit, int) and limit > 0 else None + @contextlib.asynccontextmanager + async def creating(self, pending: PendingCreate) -> AsyncIterator[None]: + """Hold a remote session id for one client while its create handler works, so that a DELETE can end the create. + + This ends an earlier create of the same client under the id, and refuses the id of another API key or address. + """ + session_id = pending.session_id + async with self._lock: + earlier = self._pending.get(session_id) + for held in (earlier, self._sessions.get(session_id)): + if held is not None and not holds(held, pending.owner_key, pending.creator_ip): + raise APIError(APIErrorCode.FORBIDDEN, "Session access denied") + if earlier is not None: + earlier.require_live() + earlier.ended = True + self._pending[session_id] = pending + try: + yield + finally: + if self._pending.get(session_id) is pending: + del self._pending[session_id] + _schedule_pending_reload(pending.service_tag) + + @property + def pending_services(self) -> set[str]: + """The tags whose service a create handler builds now.""" + return {pending.service_tag for pending in self._pending.values()} + + def end_pending(self, session_id: str, owner_key: str, creator_ip: str | None) -> bool: + """End the create that this client has in progress under the id. False when it has none.""" + pending = self._pending.get(session_id) + if pending is None or not holds(pending, owner_key, creator_ip): + return False + pending.ended = True + log.info(f"Ended the creation of session {sanitize_log(session_id)}") + return True + async def create( self, service_tag: str, @@ -201,10 +272,19 @@ class SessionStore: client: dict[str, Any] | None = None, input_bridge: InputBridge | None = None, log_buffer: Any | None = None, + pending: PendingCreate | None = None, ) -> SessionEntry: - """Make a new remote session, complete with every field the dashboard shows, and announce it.""" - evicted_tag: str | None = None + """Make a new remote session, complete with every field the dashboard shows, and announce it. + + It replaces the remote session that the client has under the id of ``pending``, and raises when that has ended. + """ + ended_tags: list[str | None] = [] async with self._lock: + if pending is not None: + pending.require_live() + session_id = pending.session_id + if replaced := self._sessions.get(session_id): + ended_tags.append(self._retire(replaced, "closed")) max_sessions = self.max_sessions if max_sessions is not None and len(self._sessions) >= max_sessions: sessions = self._sessions @@ -214,7 +294,7 @@ class SessionStore: key=lambda k: (sessions[k].in_use, -held[sessions[k].owner_key], sessions[k].last_accessed), ) log.warning(f"Max sessions reached ({max_sessions}), evicting oldest of the busiest key: {oldest_id}") - evicted_tag = self._retire(sessions[oldest_id], "evicted") + ended_tags.append(self._retire(sessions[oldest_id], "evicted")) session_id = session_id or str(uuid.uuid4()) entry = SessionEntry( @@ -235,7 +315,7 @@ class SessionStore: self._sessions[session_id] = entry _publish("create", entry) log.info(f"Created session {sanitize_log(session_id)} for service {sanitize_log(service_tag)}") - await self.remove_cache_dirs([evicted_tag]) + await self.remove_cache_dirs(ended_tags) return entry async def get(self, session_id: str) -> SessionEntry | None: @@ -332,7 +412,7 @@ class SessionStore: """End every remote session at server shutdown, wait LOGIN_WAIT seconds for the running logins, stop the sweep. A login thread can still write the remote session cache after its bridge ends. The store has forgotten - the session by then, so the login task of session_create_handler removes that cache directory again. + the session by then, so the login task of create_session removes that cache directory again. """ async with self._lock: cache_tags = [self._retire(entry, None) for entry in list(self._sessions.values())] @@ -421,9 +501,6 @@ session_store: SessionStore | None = None def refuse_while_draining() -> None: """Raise SERVER_DRAINING for a new session or job once the operator has started a drain.""" - from unshackle.core.api.errors import APIError - from unshackle.core.remote_protocol import APIErrorCode - if get_session_store().draining: raise APIError( APIErrorCode.SERVER_DRAINING, diff --git a/unshackle/core/remote_channel.py b/unshackle/core/remote_channel.py index 97b5a89e..4e150607 100644 --- a/unshackle/core/remote_channel.py +++ b/unshackle/core/remote_channel.py @@ -57,6 +57,7 @@ CONNECT_TIMEOUT = 10.0 RECONNECT_DELAY = 1.0 GONE_STATUSES = (401, 403, 404) # the API key or the remote session is gone, so a reconnect cannot help SEND_TIMEOUT = 10.0 +CDM_CLOSE_TIMEOUT = 5.0 KEPT_ANSWERS = 64 LEVELS = logging.getLevelNamesMapping() @@ -78,7 +79,7 @@ class ServerMessages: self.cdm_sessions: dict[str, bytes] = {} def route(self, route: str) -> str: - return route.format(session_id=self.service._session_id) + return route.format(session_id=self.service.lifetime.require_session()) def show_logs(self, records: list[LogRecord]) -> None: """Log the service's server-side records here, each once: a record that the other path brought is skipped.""" @@ -133,13 +134,17 @@ class ServerMessages: show_notice(notice, self.service.auth_qr) def close_cdm_sessions(self) -> None: - """Close the local CDM sessions that the server's calls opened; best effort.""" + """Close the local CDM sessions that the server's calls opened; best effort, without a long wait on a running call.""" cdm = self.service.local_cdm - with self.cdm_lock: + if not self.cdm_lock.acquire(timeout=CDM_CLOSE_TIMEOUT): + return + try: for session_id in self.cdm_sessions.values(): with contextlib.suppress(Exception): cdm.close(session_id) self.cdm_sessions.clear() + finally: + self.cdm_lock.release() def login_done(self) -> None: self.close_cdm_sessions() @@ -230,6 +235,8 @@ class PollingChannel: def runs_service_code(self, endpoint: str) -> bool: """Whether a request to *endpoint* runs service code on the server, which can make CDM calls.""" + if self.service._session_id is None: + return False own = {self.messages.route(route) for route in (PROMPT_ROUTE, LOGS_ROUTE, SAMPLES_ROUTE)} return endpoint.startswith(self.messages.route(SESSION_ROUTE) + "/") and endpoint.partition("?")[0] not in own @@ -326,6 +333,7 @@ class WebSocketChannel: self.ws: aiohttp.ClientWebSocketResponse | None = None self.loop: asyncio.AbstractEventLoop | None = None self.task: asyncio.Task[None] | None = None + self.stopped = False self.thread = Thread(target=run_loop, args=(self.run,), name=f"{self.service.service_tag}-channel", daemon=True) def open(self, timeout: float = CONNECT_TIMEOUT) -> bool: @@ -340,8 +348,10 @@ class WebSocketChannel: async def run(self) -> None: self.loop, self.task = asyncio.get_running_loop(), asyncio.current_task() try: - await self.connect() - except asyncio.CancelledError: + if not self.stopped: + with quiet(): + await self.connect() + except (asyncio.CancelledError, RemoteError): pass finally: self.attempted.set() @@ -483,6 +493,7 @@ class WebSocketChannel: return self.draining_now if self.connected.is_set() else self.fallback.draining() def close(self) -> None: + self.stopped = True if self.loop and self.task and self.thread.is_alive(): with contextlib.suppress(RuntimeError): # the loop closes before its thread ends self.loop.call_soon_threadsafe(self.task.cancel) @@ -500,8 +511,9 @@ def open_channel(service: RemoteService) -> Channel: fallback = PollingChannel(messages) if service.client.no_channel: return fallback - channel = WebSocketChannel(messages, fallback) + channel = service.lifetime.channel = WebSocketChannel(messages, fallback) if channel.open(): return channel + service.lifetime.require_open() service.client.no_channel = True return fallback diff --git a/unshackle/core/remote_lifetime.py b/unshackle/core/remote_lifetime.py new file mode 100644 index 00000000..affa4d7d --- /dev/null +++ b/unshackle/core/remote_lifetime.py @@ -0,0 +1,180 @@ +"""The lifetime of a remote session on the client, from before its create request to after its DELETE.""" + +from __future__ import annotations + +import atexit +import contextlib +import logging +import signal +import uuid +from collections.abc import Callable, Iterator +from threading import RLock, current_thread, main_thread +from typing import TYPE_CHECKING + +from unshackle.core.remote_protocol import SESSION_ROUTE, APIErrorCode, SessionClosed +from unshackle.core.remote_service import RemoteClient, RemoteError, quiet + +if TYPE_CHECKING: + from unshackle.core.remote_channel import Channel + +log = logging.getLogger("remote_lifetime") + +END_TIMEOUT = 15.0 +GIVE_UP = 2 + + +class Presses: + """The Ctrl+C presses during the ends of this process. The first one is ignored, and at GIVE_UP no end waits.""" + + count = 0 + + +class RemoteSessionLifetime: + """The one owner of a remote session, its tunnel and its session channel. + + :meth:`release` gives up what is open, and the owner can open again, as a reopen does. :meth:`end` is final. + Both can run again after an interrupt and from any thread, and neither waits on a reopen of another thread. + It holds an id from before its create request until the server answers its DELETE or the DELETE fails. + """ + + def __init__(self, client: RemoteClient, save_cache: Callable[[dict[str, str]], None]) -> None: + self.client = client + self.save_cache = save_cache + self.session_id: str | None = None + self.channel: Channel | None = None + self.ended = False + self._held: set[str] = set() + self._lock = RLock() + self._saving = False + + def require_open(self) -> None: + """Raise when this owner has ended.""" + if self.ended: + raise RemoteError("The remote session has ended", APIErrorCode.SESSION_NOT_FOUND) + + def require_session(self) -> str: + """The id of the open remote session, or raise.""" + self.require_open() + if (session_id := self.session_id) is None: + raise RemoteError("No remote session is open", APIErrorCode.SESSION_NOT_FOUND) + return session_id + + @contextlib.contextmanager + def opening(self) -> Iterator[None]: + """Register the exit hook, then release all that the block opened when it raises or the owner has ended. + + An error of a call that another thread ended this owner under is no news to the user, so it stays out of the log. + """ + with quiet(lambda: self.ended): + try: + self.require_open() + atexit.unregister(self.end_at_exit) + atexit.register(self.end_at_exit) + yield + self.require_open() + except BaseException: + if self.ended: + self.end_at_exit() + else: + self.patiently(self.release) + raise + + def name(self) -> str: + """The id that the next create request asks for, so that a DELETE can name the remote session before the answer.""" + named = str(uuid.uuid4()) + with self._lock: + self.require_open() + self._held.add(named) + return named + + def adopt(self, named: str, session_id: str) -> None: + """Take the id of the create reply, which an older server picks itself.""" + with self._lock: + self._held = (self._held - {named}) | {session_id} + self.session_id = session_id + + def release(self, gone: bool = False) -> None: + """Give up the remote session, its channel and its tunnel; ``gone`` when the server said it has no such session.""" + with self._lock: + if gone: + self._held -= {self.session_id} + self.session_id = None + self.close_channel() + for session_id in list(self._held): + self._delete(session_id) + if tunnel := self.client.tunnel: + tunnel.stop() + if self.client.tunnel is tunnel: + self.client.tunnel = None + + def end(self) -> None: + """Release everything for good: no thread opens a remote session through this owner again. + + It raises KeyboardInterrupt when the user gave up on it, and the exit hook then stays. + """ + self.ended = True + if not self.patiently(self.release): + raise KeyboardInterrupt + # a long-lived serve opens many of these; the exit hook would keep every one alive + atexit.unregister(self.end_at_exit) + + def end_at_exit(self) -> None: + """:meth:`end` where no caller is left to stop.""" + with contextlib.suppress(KeyboardInterrupt): + self.end() + + def close_channel(self) -> None: + if channel := self.channel: + channel.close() + if self.channel is channel: + self.channel = None + + def _delete(self, session_id: str) -> None: + """Send one DELETE and save the cache it returns. An interrupt keeps the id, so a later release sends it again.""" + body: SessionClosed = {} + try: + endpoint = SESSION_ROUTE.format(session_id=session_id) + resp = self.client.send("delete", endpoint, min(END_TIMEOUT, self.client.timeout), background=True) + if resp.ok: + body = resp.json() + except Exception as e: + log.debug(f"The DELETE of the remote session failed: {type(e).__name__}") + self._saving = True + try: + self.save_cache(body.get("cache") or {}) + except (Exception, SystemExit) as e: + log.warning(f"Failed to save the cache of the remote session: {e}") + finally: + self._saving = False + with self._lock: + self._held.discard(session_id) + + def patiently(self, work: Callable[[], None]) -> bool: + """Run ``work``, ignore the first Ctrl+C and stop at the next one; False when the user gave up. + + Only the main thread can, so on another thread ``work`` runs with the signal handlers as they are. + """ + before = signal.getsignal(signal.SIGINT) + if current_thread() is not main_thread() or not callable(before): + work() + return True + if Presses.count >= GIVE_UP: + return False + armed = True + + def press(*_: object) -> None: + Presses.count += 1 + if Presses.count >= GIVE_UP and armed and not self._saving: + raise KeyboardInterrupt + + try: + try: + signal.signal(signal.SIGINT, press) + work() + finally: + armed = False + return True + except KeyboardInterrupt: + return False + finally: + signal.signal(signal.SIGINT, before) diff --git a/unshackle/core/remote_protocol.py b/unshackle/core/remote_protocol.py index b2534a33..de17349e 100644 --- a/unshackle/core/remote_protocol.py +++ b/unshackle/core/remote_protocol.py @@ -125,6 +125,7 @@ class SessionCreate(ClientLogin, total=False): service: str title_id: str + session_id: str profile: str service_params: dict[str, Any] season: Any diff --git a/unshackle/core/remote_service.py b/unshackle/core/remote_service.py index 6a1699f3..4a98ccc3 100644 --- a/unshackle/core/remote_service.py +++ b/unshackle/core/remote_service.py @@ -7,7 +7,6 @@ Everything else (track selection, download, decrypt, mux) runs locally. from __future__ import annotations -import atexit import base64 import contextlib import hashlib @@ -78,7 +77,6 @@ from unshackle.core.remote_protocol import ( SegmentFilterReply, SegmentFilterRequest, SegmentsRequest, - SessionClosed, SessionCreate, SessionCreated, TitlesReply, @@ -106,6 +104,7 @@ from unshackle.core.wire import apply_tracks_reply, build_chapters, build_music, if TYPE_CHECKING: from unshackle.core.remote_channel import Channel + from unshackle.core.remote_lifetime import RemoteSessionLifetime log = logging.getLogger("remote_service") @@ -135,7 +134,7 @@ class _Mute(local): """This thread's RemoteError log state: inside ``session_call`` (``recovering``) and under ``quiet()``.""" recovering = False - quiet = False + quiet: Callable[[], bool] = staticmethod(lambda: False) _mute = _Mute() @@ -163,10 +162,10 @@ def malformed_answer(what: str) -> Iterator[None]: @contextlib.contextmanager -def quiet() -> Iterator[None]: - """Log this thread's RemoteErrors at debug level, because the caller reports them.""" +def quiet(when: Callable[[], bool] = lambda: True) -> Iterator[None]: + """Log this thread's RemoteErrors at debug level, because the caller reports them; only while ``when`` is true.""" before = _mute.quiet - _mute.quiet = True + _mute.quiet = lambda: before() or when() try: yield finally: @@ -210,7 +209,7 @@ class RemoteError(SystemExit): super().__init__(1) self.message = sanitize_log(message) self.kind = kind - muted = _mute.quiet or (_mute.recovering and kind in RECOVERABLE) + muted = _mute.quiet() or (_mute.recovering and kind in RECOVERABLE) (log.debug if muted else log.error)(self.message) def __str__(self) -> str: @@ -411,9 +410,6 @@ class RemoteClient: """GET an endpoint that an older server may not have. Empty dict when the route is missing.""" return self.request("get", endpoint, optional=True) - def delete(self, endpoint: str) -> dict[str, Any]: - return self.request("delete", endpoint) - def sample_batches(samples: list[bytes]) -> Iterator[list[bytes]]: """Split samples into consecutive batches of at most cbcs.SAMPLE_BATCH_BYTES (a larger sample goes alone).""" @@ -672,7 +668,7 @@ def start_tunnel(client: RemoteClient, proxy: str | None = None) -> TunnelClient slot_deadline = time.monotonic() + RETRY_AFTER_MAX rate_waits = 0 while True: - tunnel = TunnelClient(client.server_url, headers, proxy) + tunnel = client.tunnel = TunnelClient(client.server_url, headers, proxy) try: tunnel.start() break @@ -684,7 +680,6 @@ def start_tunnel(client: RemoteClient, proxy: str | None = None) -> TunnelClient wait_retry_after(TUNNEL_SLOT_POLL, "Every tunnel of this API key is in use") else: raise click.ClickException(f"--local-proxy could not open a tunnel to the server: {e}") from None - client.tunnel = tunnel return tunnel @@ -810,7 +805,7 @@ class RemoteService(TitleSource): """ server_cdm_type: str = "widevine" - channel: Channel | None = None + lifetime: RemoteSessionLifetime licensing: LicensingMode | None = None """The server's answer to who licenses this remote session; an older server gives it in the tracks reply.""" _server_cdm_request: bool | None = None @@ -826,6 +821,8 @@ class RemoteService(TitleSource): services_config: dict, service_params: dict[str, Any] | None = None, ) -> None: + from unshackle.core.remote_lifetime import RemoteSessionLifetime + self.__class__.__name__ = service_tag console.print(Padding(Rule(f"[rule.text]Service: {service_tag} (Remote)"), (1, 2))) @@ -840,7 +837,7 @@ class RemoteService(TitleSource): self._titles: Titles_T | None = None self._tracks_by_title: dict[str, Tracks] = {} self._chapters_by_title: dict[str, list] = {} - self._session_id: str | None = None + self.lifetime = RemoteSessionLifetime(self.client, self.save_session_cache) self.client_licensed: set[str] = set() # track ids this machine's device licenses by challenge relay self.deferred_refusals: dict[str, str] = {} self.server_vault_keys: dict[UUID, str] = {} @@ -917,6 +914,14 @@ class RemoteService(TitleSource): def title(self) -> str: return self.title_id + @property + def _session_id(self) -> str | None: + return self.lifetime.session_id + + @property + def channel(self) -> Channel | None: + return self.lifetime.channel + def search(self) -> Iterator[SearchResult]: """Search on the server, which logs in to the service itself with the login material sent here.""" params = self.ctx.parent.params if self.ctx.parent else {} @@ -926,15 +931,15 @@ class RemoteService(TitleSource): data["profile"] = profile if not self._anonymous_search: data.update(self.client_login(profile)) - if params.get("no_proxy"): - data["no_proxy"] = True - elif params.get("local_proxy"): - data["proxy"] = self.tunnel() - elif params.get("proxy"): - providers = getattr(self.ctx.obj, "proxy_providers", None) - data["proxy"] = resolve_remote_proxy_arg(server_proxy_arg(params), providers) - self.require_reachable_proxy(data["proxy"]) try: + if params.get("no_proxy"): + data["no_proxy"] = True + elif params.get("local_proxy"): + data["proxy"] = self.tunnel() + elif params.get("proxy"): + providers = getattr(self.ctx.obj, "proxy_providers", None) + data["proxy"] = resolve_remote_proxy_arg(server_proxy_arg(params), providers) + self.require_reachable_proxy(data["proxy"]) response = self.client.post(SEARCH_ROUTE, data) finally: if self.client.tunnel: # a search is one request, so its tunnel ends with it @@ -983,6 +988,11 @@ class RemoteService(TitleSource): return f"tunnel:{tunnel.id}" def authenticate(self, cookies: CookieJar | None = None, credential: Credential | None = None) -> None: + with self.lifetime.opening(): + self.open_session(credential) + + def open_session(self, credential: Credential | None) -> None: + """Make the remote session and wait for its login; what it opens belongs to ``lifetime``.""" self.credential = credential profile = self.ctx.parent.params.get("profile") if self.ctx.parent else None proxy = self.ctx.parent.params.get("proxy") if self.ctx.parent else None @@ -1121,16 +1131,11 @@ class RemoteService(TitleSource): "argv": argv, } - try: - result = cast(SessionCreated, self.client.post(SESSION_CREATE_ROUTE, create_data)) - if not isinstance(result.get("session_id"), str): - raise RemoteError("The remote server sent malformed session: no session_id", ClientErrorKind.UNKNOWN) - except BaseException: - if local and self.client.tunnel: # no session, so close() never runs: free the tunnel now - self.client.tunnel.stop() - raise - self._session_id = result["session_id"] - atexit.register(self.close) + create_data["session_id"] = self.lifetime.name() + result = cast(SessionCreated, self.client.post(SESSION_CREATE_ROUTE, create_data)) + if not isinstance(result.get("session_id"), str): + raise RemoteError("The remote server sent malformed session: no session_id", ClientErrorKind.UNKNOWN) + self.lifetime.adopt(create_data["session_id"], result["session_id"]) # an older server omits the field, and the tracks response settles it if "server_cdm" in result: answer = LicensingMode.from_created(result) @@ -1151,13 +1156,13 @@ class RemoteService(TitleSource): from unshackle.core.remote_channel import open_channel - self.channel = open_channel(self) + channel = self.lifetime.channel = open_channel(self) if result.get("status", AuthStatus.AUTHENTICATED) == AuthStatus.AUTHENTICATING: - self.channel.wait_auth() + channel.wait_auth() if create_data.get("cdm_relay"): - self.client.in_flight = self.channel.in_flight + self.client.in_flight = channel.in_flight self.drain_server_logs() - self.channel.keep_alive() + channel.keep_alive() @property def local_cdm(self) -> Any: @@ -1223,7 +1228,7 @@ class RemoteService(TitleSource): raise lost = e if not self.recover(session_id, lost.kind): - if not _mute.quiet: + if not _mute.quiet(): log.error(lost.message) raise lost return call(self._session_id) @@ -1245,14 +1250,18 @@ class RemoteService(TitleSource): if alive: return kind == ClientErrorKind.CONNECT self.log.warning("The remote session was lost, opening a new one") + self.lifetime.release(gone=kind == APIErrorCode.SESSION_NOT_FOUND) return self.reopen() def wait_for_server(self, accepting: bool) -> bool: - """Wait until the server answers, and with ``accepting`` until it also takes new sessions. False on timeout.""" + """Wait until the server answers, and with ``accepting`` until it also takes new sessions. + + False on timeout, and when the owner of the remote session has ended. + """ deadline = time.monotonic() + REOPEN_WAIT delay = 1.0 warned = False - while True: + while not self.lifetime.ended: health = self.client.probe(HEALTH_ROUTE) if health.get("status") == "ok" and not (accepting and health.get("draining")): return True @@ -1264,6 +1273,7 @@ class RemoteService(TitleSource): # jittered, so the clients of a restarted server do not all log in again at the same moment time.sleep(random.uniform(delay / 2, delay)) # nosec B311 delay = min(delay * 2, 30.0) + return False def licence_path(self) -> object: """Where this remote session takes its keys from, which a reopened session must keep. @@ -1274,16 +1284,11 @@ class RemoteService(TitleSource): return (licensing.licensor, licensing.vault_first) if licensing else self._server_cdm_request def reopen(self) -> bool: - """Open a new remote session after the server lost this one, and load the current title's tracks on it again. + """Open a new remote session after the release of the last one, and load the current title's tracks on it again. A track the new remote session gives another id keeps its old one here, and calls translate it. """ grants = self.licence_path() - self.close_channel() - self._session_id = None - if self.client.tunnel: # the server forgot the tunnel too - self.client.tunnel.stop() - self.client.tunnel = None self._segment_filters.clear() if not self.wait_for_server(accepting=True): return False @@ -1322,10 +1327,10 @@ class RemoteService(TitleSource): return True def reopen_after_drain(self) -> None: - """Close the remote session before the server's announced restart, so its drain can end, then open a new one.""" + """Release the remote session before the server's announced restart, so its drain can end, then open a new one.""" with self._reopen_lock: self.log.info("The remote server restarts for an update, reopening the session after it") - self.close() + self.lifetime.release() self._current_title = None if not self.reopen(): raise RemoteError( @@ -1345,11 +1350,6 @@ class RemoteService(TitleSource): if self.channel: self.channel.drain_logs() - def close_channel(self) -> None: - channel, self.channel = self.channel, None - if channel: - channel.close() - def get_titles(self) -> Titles_T: if self._titles is not None: return self._titles @@ -1851,22 +1851,12 @@ class RemoteService(TitleSource): ) from None def close(self) -> None: - # a long-lived serve opens many of these; the atexit hook would keep every one alive - atexit.unregister(self.close) - self.close_channel() - session_id, self._session_id = self._session_id, None - if session_id: - try: - with quiet(): - result = cast(SessionClosed, self.client.delete(SESSION_ROUTE.format(session_id=session_id))) - profile = self.ctx.parent.params.get("profile") if self.ctx.parent else None - self.save_returned_cache(result.get("cache", {}), profile) - except SystemExit: - pass - except Exception as e: - self.log.warning(f"Failed to clean up remote session: {e}") - if self.client.tunnel: - self.client.tunnel.stop() + """End the remote session for good. dl, the job worker and the relay pool all end it here.""" + self.lifetime.end() + + def save_session_cache(self, cache_data: dict[str, str]) -> None: + """Save the cache files that the DELETE of the remote session returns.""" + self.save_returned_cache(cache_data, self.ctx.parent.params.get("profile") if self.ctx.parent else None) def save_returned_cache(self, cache_data: dict[str, str], profile: str | None = None) -> None: """Save cache files returned by the server to the local cache directory. diff --git a/unshackle/core/tunnel.py b/unshackle/core/tunnel.py index 55914240..813e49f2 100644 --- a/unshackle/core/tunnel.py +++ b/unshackle/core/tunnel.py @@ -549,6 +549,7 @@ class TunnelClient: self.thread = threading.Thread(target=run_loop, args=(self.run,), name="tunnel", daemon=True) self.loop: asyncio.AbstractEventLoop | None = None self.task: asyncio.Task[None] | None = None + self.stopped = False def start(self, timeout: float = 20) -> str: """Open the tunnel and return its id.""" @@ -560,6 +561,7 @@ class TunnelClient: def stop(self) -> None: """Close the tunnel and wait for its connections to end, so none is left pending at exit.""" + self.stopped = True if self.loop and self.task and self.thread.is_alive(): with contextlib.suppress(RuntimeError): # the loop closes before its thread ends self.loop.call_soon_threadsafe(self.task.cancel) @@ -567,6 +569,8 @@ class TunnelClient: async def run(self) -> None: self.loop, self.task = asyncio.get_running_loop(), asyncio.current_task() + if self.stopped: + return try: await self.connect() except asyncio.CancelledError: