fix(remote): end a remote session from before its create to after its DELETE

This commit is contained in:
imSp4rky
2026-11-30 13:56:59 -07:00
parent 3634fc5686
commit 34a3820eb8
34 changed files with 1719 additions and 276 deletions
+7 -3
View File
@@ -987,7 +987,9 @@ the newlines must go out at once.
### `POST /api/session/create` ### `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/<sha1>` 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/<sha1>` 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`. `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 | | Status | Error code | Meaning |
| --- | --- | --- | | --- | --- | --- |
| `200` | - | Session created; authentication in progress. | | `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. | | `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. | | `400` | `INVALID_SERVICE` | Unknown or disallowed service. |
### `GET /api/session/{session_id}/channel` ### `GET /api/session/{session_id}/channel`
@@ -1307,7 +1311,7 @@ Return remote session metadata and validity.
### `DELETE /api/session/{session_id}` ### `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`" === "Response `200`"
+42 -6
View File
@@ -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, [remote session channel](#the-remote-session-channel) keeps the remote session alive,
so a long download does not let the remote session expire. On 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 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 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 client saves them locally, so the **next** remote session can skip interactive
authentication. The login belongs to the client when it succeeds and the 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 ### 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`, `credentials`, `cookies` (base64 of zlib-compressed Netscape cookie file), `proxy`,
`no_proxy`, `profile`, `cache` (a map of `filename → base64(zlib(bytes))`), `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 `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 - **Config-driven limits.** `serve.session_ttl` (default `300`) and
`serve.max_sessions` (default `100`) are read as properties, so config changes `serve.max_sessions` (default `100`) are read as properties, so config changes
take effect without recreating the store. 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, - **`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. 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 - **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 | | 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_tag` | Normalized service tag |
| `service_instance` | The authenticated service object kept alive between calls | | `service_instance` | The authenticated service object kept alive between calls |
| `titles` / `title_map` | Result of `get_titles()` and a `title_id → Title` map | | `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: The `create` handler builds a `Cacher` namespaced as:
```text ```text
_sessions/<pbkdf2_hmac(sha256, X-Secret-Key, "unshackle-session-ns", 100000)[:12]>/<session_id>/<service> _sessions/<pbkdf2_hmac(sha256, X-Secret-Key, "unshackle-session-ns", 100000)[:12]>/<uuid4>/<service>
``` ```
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. 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 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 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`) → (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 get the licence in proxy mode or `server_cdm` mode → `close()` (`DELETE`, saving any returned
`cache`). `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 - **Server restarts.** The server keeps remote sessions in memory only, so a restart
loses them all. The client recovers in two ways: loses them all. The client recovers in two ways:
- A drain announced through `draining`: the client finishes the current title, then - 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`, It waits until `/api/health` reports the restarted server without `draining`,
opens a new remote session, and continues with the next title. 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 - 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 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. 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 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 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 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. 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 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. 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 ## Troubleshooting
@@ -22,8 +22,3 @@ def test_remote_client_get_services(remote_client) -> None:
def test_remote_client_get_404_raises_systemexit(remote_client) -> None: def test_remote_client_get_404_raises_systemexit(remote_client) -> None:
with pytest.raises(SystemExit): with pytest.raises(SystemExit):
remote_client.get("/api/session/this-does-not-exist") 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")
+2 -1
View File
@@ -4,6 +4,7 @@ from types import SimpleNamespace
from typing import Any from typing import Any
from uuid import UUID from uuid import UUID
from tests.remote.sessions import hold_session
from unshackle.core.remote_protocol import LicensingMode, Licensor from unshackle.core.remote_protocol import LicensingMode, Licensor
from unshackle.core.remote_service import RemoteService, ServerVault from unshackle.core.remote_service import RemoteService, ServerVault
from unshackle.core.title_source import KeyArrival 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 = remote_keys(server_cdm_type="playready", local_cdm=local_cdm)
svc._track_alias = {} svc._track_alias = {}
svc._title_alias = {} svc._title_alias = {}
svc._session_id = "sess" hold_session(svc, "sess")
svc.log = logging.getLogger("test-remote-session") svc.log = logging.getLogger("test-remote-session")
posts: list = [] posts: list = []
svc.client = SimpleNamespace(post=lambda endpoint, payload, expect=(): posts.append(payload) or answer) svc.client = SimpleNamespace(post=lambda endpoint, payload, expect=(): posts.append(payload) or answer)
+18 -1
View File
@@ -2,16 +2,19 @@
from collections.abc import Callable from collections.abc import Callable
from types import SimpleNamespace from types import SimpleNamespace
from typing import Any from typing import Any, NoReturn
import pytest import pytest
import requests
from unshackle.core.api import handlers, key_policy from unshackle.core.api import handlers, key_policy
from unshackle.core.api.handlers import Launched, SessionLaunch from unshackle.core.api.handlers import Launched, SessionLaunch
from unshackle.core.api.input_bridge import InputBridge from unshackle.core.api.input_bridge import InputBridge
from unshackle.core.api.key_policy import KeyPolicy from unshackle.core.api.key_policy import KeyPolicy
from unshackle.core.api.session_store import SessionEntry 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_protocol import LicensingMode, Licensor
from unshackle.core.remote_service import RemoteClient
def session_entry(**fields: Any) -> SessionEntry: 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(key_policy, "load_service_config", lambda tag: {})
monkeypatch.setattr(handlers, "load_full_cdm", lambda *a: None) monkeypatch.setattr(handlers, "load_full_cdm", lambda *a: None)
monkeypatch.setattr(handlers, "instantiate_service", lambda *a, **k: build()) 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)
+3 -7
View File
@@ -14,7 +14,7 @@ import pytest
from pywidevine import DeviceTypes from pywidevine import DeviceTypes
from pywidevine.pssh import PSSH 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 import handlers, key_policy, server_keys
from unshackle.core.api.errors import APIError from unshackle.core.api.errors import APIError
from unshackle.core.api.input_bridge import InputBridge 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: async def validated(session_id: str, request: Any) -> Any:
return session return session
class Store:
async def delete(self, session_id: str) -> bool:
return True
monkeypatch.setattr(handlers, "get_validated_session", validated) 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"}) monkeypatch.setattr(handlers, "collect_cache_files", lambda tag, withhold=(): {"MSL/server-esn": "tokens"})
response = asyncio.run(handlers.session_delete_handler("sid", None)) 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 = object.__new__(RemoteService)
svc.log = logging.getLogger("test") svc.log = logging.getLogger("test")
svc._session_id = "sid" hold_session(svc, "sid")
svc.licensing = LicensingMode(Licensor.LENT_DEVICE) svc.licensing = LicensingMode(Licensor.LENT_DEVICE)
svc.client_licensed = set() svc.client_licensed = set()
svc.deferred_refusals = {} svc.deferred_refusals = {}
+2 -1
View File
@@ -5,6 +5,7 @@ from types import SimpleNamespace
import pytest import pytest
from tests.remote.sessions import hold_session
from unshackle.core.api import handlers from unshackle.core.api import handlers
from unshackle.core.api.key_policy import KeyPolicy from unshackle.core.api.key_policy import KeyPolicy
from unshackle.core.remote_protocol import LicensingMode, Licensor 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={}, _chapters_by_title={},
_title_alias={}, _title_alias={},
_sample_decrypt_tracks=set(), _sample_decrypt_tracks=set(),
_session_id="s",
service_tag="EXAMPLE", service_tag="EXAMPLE",
ctx=SimpleNamespace(obj=None), ctx=SimpleNamespace(obj=None),
log=logging.getLogger("test"), 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, drain_server_logs=lambda: None,
) )
service.session = SimpleNamespace(headers={}) service.session = SimpleNamespace(headers={})
hold_session(service)
with caplog.at_level(logging.INFO): with caplog.at_level(logging.INFO):
service.get_tracks(SimpleNamespace(id="t1")) service.get_tracks(SimpleNamespace(id="t1"))
assert service.licensing == mode assert service.licensing == mode
+2 -1
View File
@@ -16,6 +16,7 @@ import requests
from aiohttp import WSMsgType, web from aiohttp import WSMsgType, web
from click.testing import CliRunner from click.testing import CliRunner
from tests.remote.sessions import hold_session
from tests.remote.unit.test_session_reopen import make_service from tests.remote.unit.test_session_reopen import make_service
from unshackle.core import remote_service from unshackle.core import remote_service
from unshackle.core.api import handlers 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: def test_relayed_server_logs_lose_their_control_characters(monkeypatch: pytest.MonkeyPatch) -> None:
service = RemoteService.__new__(RemoteService) service = RemoteService.__new__(RemoteService)
service._session_id = "sid" hold_session(service, "sid")
seen: list[str] = [] seen: list[str] = []
service.log = SimpleNamespace(log=lambda level, message: seen.append(message)) # type: ignore[assignment] service.log = SimpleNamespace(log=lambda level, message: seen.append(message)) # type: ignore[assignment]
service.client = SimpleNamespace( service.client = SimpleNamespace(
-11
View File
@@ -69,17 +69,6 @@ def test_post_sends_json_body(client: RemoteClient) -> None:
assert captured["body"] == {"service": "EXAMPLE"} 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 @responses.activate
def test_4xx_raises_systemexit_with_logged_error(client: RemoteClient, caplog: pytest.LogCaptureFixture) -> None: def test_4xx_raises_systemexit_with_logged_error(client: RemoteClient, caplog: pytest.LogCaptureFixture) -> None:
responses.add( responses.add(
+3 -2
View File
@@ -44,6 +44,7 @@ from unshackle.core.utilities import close_debug_logger, init_debug_logger
pytestmark = pytest.mark.unit pytestmark = pytest.mark.unit
KEY = "loopback-key" KEY = "loopback-key"
OTHER_KEY = "other-key"
CODE = "1234" CODE = "1234"
@@ -157,7 +158,7 @@ def server(request: pytest.FixtureRequest, monkeypatch: pytest.MonkeyPatch, tmp_
stub_service_build(monkeypatch, lambda: StubService(beats)) stub_service_build(monkeypatch, lambda: StubService(beats))
app = web.Application(middlewares=[record, cors_middleware, no_5xx_middleware, api_key_authentication]) 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) setup_routes(app, remote_only=True)
loop = asyncio.new_event_loop() loop = asyncio.new_event_loop()
runner = web.AppRunner(app) 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", SESSION_ROUTE, session_id) == 0
assert count(server, "GET", LOGS_ROUTE) == count(server, "GET", PROMPT_ROUTE) == 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: not entry.channel.attached, 5)
assert wait_until(lambda: idle_seconds(entry) > 2 * ttl, 10) assert wait_until(lambda: idle_seconds(entry) > 2 * ttl, 10)
assert on_loop(server, store.cleanup_expired()) == 1 assert on_loop(server, store.cleanup_expired()) == 1
@@ -12,7 +12,7 @@ import pytest
import responses import responses
from tests.core.test_music_renderer import OWN_FACTS, OWN_ROWS, header, mixed 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 tests.remote.unit.test_session_reopen import SERVER, make_service
from unshackle.core.api import handlers from unshackle.core.api import handlers
from unshackle.core.remote_service import RemoteError, RemoteService 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: def test_a_reopened_session_keeps_the_facts(monkeypatch: pytest.MonkeyPatch) -> None:
client = client_of(titles_reply(monkeypatch, served(mixed(**FACTS)))) client = client_of(titles_reply(monkeypatch, served(mixed(**FACTS))))
client.get_titles() 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, f"{SERVER}/api/health", json={"status": "ok", "draining": False})
responses.add( responses.add(
responses.GET, responses.GET,
+1 -1
View File
@@ -64,7 +64,7 @@ def test_recover_moves_to_the_next_auth_header() -> None:
@responses.activate @responses.activate
def test_server_draining_moves_to_the_next_auth_header() -> None: def test_server_draining_moves_to_the_next_auth_header() -> None:
service = make_service() 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})) responses.add_callback(responses.GET, f"{SERVER}/api/session/s1", callback=second_header_only({"draining": True}))
assert service.server_draining() assert service.server_draining()
+7 -4
View File
@@ -10,7 +10,7 @@ from typing import Any
import pytest import pytest
import yaml 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_protocol as protocol
from unshackle.core import remote_service from unshackle.core import remote_service
from unshackle.core.api import routes from unshackle.core.api import routes
@@ -23,7 +23,6 @@ CLIENT_METHODS = {
"probe": "GET", "probe": "GET",
"post": "POST", "post": "POST",
"post_optional": "POST", "post_optional": "POST",
"delete": "DELETE",
"ws_connect": "GET", "ws_connect": "GET",
} }
SERVED = {(method, path): handler for method, path, handler, _ in routes.ROUTES} 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 @functools.cache
def client_tree() -> ast.Module: def client_tree() -> ast.Module:
"""The client modules as one tree: the remote service and the session channel adapters.""" """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)] 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=[]) 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 == { assert SESSION_TRANSPORT_KEYS == {
"service", "service",
"title_id", "title_id",
"session_id",
"profile", "profile",
"service_params", "service_params",
"season", "season",
+4 -2
View File
@@ -5,6 +5,7 @@ from types import SimpleNamespace
import pytest import pytest
from tests.remote.sessions import hold_session
from unshackle.core import remote_service from unshackle.core import remote_service
from unshackle.core.api import handlers from unshackle.core.api import handlers
from unshackle.core.api.errors import APIError 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): def test_quiet_mutes_a_remote_error_the_caller_reports(caplog):
with caplog.at_level("DEBUG", logger="remote_service"), remote_service.quiet(): 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("Server error [SERVICE_ERROR]: refused", "SERVICE_ERROR")
remote_service.RemoteError("Remote auth failed: bad key", "AUTH") remote_service.RemoteError("Remote auth failed: bad key", "AUTH")
remote_service.RemoteError("Server error [NOT_FOUND]: outside", "NOT_FOUND") 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 = object.__new__(remote_service.RemoteService)
remote.seq = 0 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") remote.log = logging.getLogger("test")
monkeypatch.setattr(remote_service.RemoteService, "local_cdm", None) monkeypatch.setattr(remote_service.RemoteService, "local_cdm", None)
@@ -8,7 +8,7 @@ from enum import Enum
import pytest 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.manifests.snapshot import match_track
from unshackle.core.remote_service import RemoteService from unshackle.core.remote_service import RemoteService
from unshackle.core.titles.episode import Episode 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): async def fake_validated(session_id, request):
return session return session
class FakeStore:
async def delete(self, session_id):
return True
monkeypatch.setattr(handlers, "get_validated_session", fake_validated) 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) response = await handlers.session_delete_handler("sid", None)
body = json.loads(response.body) 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 types import SimpleNamespace
from unshackle.core.api import handlers from unshackle.core.api import handlers
from unshackle.core.api.session_store import SessionStore
class Stop(Exception): class Stop(Exception):
pass 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"))) stub_service_build(monkeypatch, lambda: SimpleNamespace(log=logging.getLogger("Svc")))
monkeypatch.setattr("unshackle.core.api.session_store.refuse_while_draining", lambda: None) monkeypatch.setattr("unshackle.core.api.session_store.refuse_while_draining", lambda: None)
class RefusingStore: class RefusingStore(SessionStore):
async def create(self, *args, **kwargs): async def create(self, *args, **kwargs):
if stop_at == "after_insert":
await super().create(*args, **kwargs)
raise Stop() raise Stop()
def peek(self, session_id): store = RefusingStore()
return object() if stop_at == "after_insert" else None monkeypatch.setattr("unshackle.core.api.session_store.get_session_store", lambda: store)
monkeypatch.setattr("unshackle.core.api.session_store.get_session_store", RefusingStore)
data = {"service": "TESTSVC", "title_id": "t", "cache": {"token": blob('"t"')}} data = {"service": "TESTSVC", "title_id": "t", "cache": {"token": blob('"t"')}}
response = asyncio.run(handlers.session_create_handler(data)) 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.session = requests.Session()
svc.log = logging.getLogger("test") svc.log = logging.getLogger("test")
svc.client = SimpleNamespace(post=post, server_url="https://server.example") svc.client = SimpleNamespace(post=post, server_url="https://server.example")
hold_session(svc, None)
return svc return svc
@@ -14,6 +14,7 @@ import pytest
from tests.core.key_resolver import key_table, resolver from tests.core.key_resolver import key_table, resolver
from tests.remote.key_source import remote_keys 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.api.errors import categorize_exception
from unshackle.core.remote_protocol import APIErrorCode, LicensingMode, Licensor 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 = remote_keys(server_cdm_type=server_type)
svc._track_alias = {} svc._track_alias = {}
svc._title_alias = {} svc._title_alias = {}
svc._session_id = "sess" hold_session(svc, "sess")
svc.log = logging.getLogger("test-remote-license") svc.log = logging.getLogger("test-remote-license")
svc.client = _Client(answer) svc.client = _Client(answer)
return svc return svc
+2 -2
View File
@@ -9,7 +9,7 @@ import click
import pytest import pytest
import responses 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.api import handlers
from unshackle.core.remote_service import RemoteClient, RemoteService from unshackle.core.remote_service import RemoteClient, RemoteService
@@ -64,7 +64,7 @@ def make_service(unwanted, status=200, error=None):
service._track_alias = {} service._track_alias = {}
service._title_alias = {} service._title_alias = {}
service.client = RemoteClient(server_url="http://srv:8786", api_key="k") service.client = RemoteClient(server_url="http://srv:8786", api_key="k")
service._session_id = "s1" hold_session(service, "s1")
service._segment_filters = {} service._segment_filters = {}
responses.add( responses.add(
responses.POST, responses.POST,
@@ -15,7 +15,7 @@ import pytest
from tests.core.key_resolver import vaults_of from tests.core.key_resolver import vaults_of
from tests.remote.key_source import one_title, remote_keys 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 import handlers, server_keys
from unshackle.core.api.errors import APIError from unshackle.core.api.errors import APIError
from unshackle.core.drm import BlowfishStripe, ClearKeyCTR from unshackle.core.drm import BlowfishStripe, ClearKeyCTR
@@ -34,7 +34,7 @@ def remote_service() -> RemoteService:
svc = remote_keys(server_cdm=None) svc = remote_keys(server_cdm=None)
svc._track_alias = {} svc._track_alias = {}
svc._title_alias = {} svc._title_alias = {}
svc._session_id = "sess" hold_session(svc, "sess")
svc.log = SimpleNamespace(warning=lambda *a, **k: None) svc.log = SimpleNamespace(warning=lambda *a, **k: None)
return svc return svc
@@ -634,9 +634,9 @@ def created(answer, monkeypatch):
svc, _ = sent_create(None, cdm_entry=True, cdm_map={"EXAMPLE1": "my_device"}) svc, _ = sent_create(None, cdm_entry=True, cdm_map={"EXAMPLE1": "my_device"})
svc._server_cdm_request = None svc._server_cdm_request = None
svc.client = SimpleNamespace(post=lambda path, data: {"session_id": "sess", **answer}) 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) channel = SimpleNamespace(keep_alive=lambda: None, drain_logs=lambda: None, in_flight=None)
monkeypatch.setattr(remote_channel, "open_channel", lambda service: channel) monkeypatch.setattr(remote_channel, "open_channel", lambda service: channel)
monkeypatch.setattr("atexit.register", lambda hook: None)
svc.authenticate() svc.authenticate()
return svc return svc
+2 -2
View File
@@ -18,7 +18,7 @@ from pywidevine.pssh import PSSH
from tests.core.key_resolver import key_table, resolver from tests.core.key_resolver import key_table, resolver
from tests.remote.key_source import remote_keys 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 import remote_channel
from unshackle.core.api import handlers, server_keys from unshackle.core.api import handlers, server_keys
from unshackle.core.cdm.detect import cdm_type_stub from unshackle.core.cdm.detect import cdm_type_stub
@@ -51,7 +51,7 @@ class Remote(SQLite):
def client(posts: list) -> RemoteService: def client(posts: list) -> RemoteService:
svc = remote_keys(server_cdm=False) svc = remote_keys(server_cdm=False)
svc._session_id = "sess" hold_session(svc, "sess")
svc._track_alias = {"v1": "v9"} svc._track_alias = {"v1": "v9"}
svc.client = SimpleNamespace( svc.client = SimpleNamespace(
send=lambda method, endpoint, timeout, background, json: posts.append((method, endpoint, background, json)) send=lambda method, endpoint, timeout, background, json: posts.append((method, endpoint, background, json))
File diff suppressed because it is too large Load Diff
+5 -4
View File
@@ -4,6 +4,7 @@ import logging
import pytest import pytest
from tests.remote.sessions import hold_session
from unshackle.core.api.handlers import session_logs_handler 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_log import SessionLogBuffer, SessionLogMirror, capture_service_logs
from unshackle.core.api.session_store import get_session_store 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 from unshackle.core.remote_service import RemoteService
svc = RemoteService.__new__(RemoteService) svc = RemoteService.__new__(RemoteService)
svc._session_id = "abc" hold_session(svc)
svc.channel = PollingChannel(ServerMessages(svc)) svc.lifetime.channel = PollingChannel(ServerMessages(svc))
class ExitingClient: class ExitingClient:
def get_optional(self, endpoint: str) -> dict: 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 from unshackle.core.remote_service import RemoteService
svc = RemoteService.__new__(RemoteService) svc = RemoteService.__new__(RemoteService)
svc._session_id = "abc" hold_session(svc)
svc.channel = PollingChannel(ServerMessages(svc)) svc.lifetime.channel = PollingChannel(ServerMessages(svc))
svc.log = logging.getLogger("test-drain-reemit") svc.log = logging.getLogger("test-drain-reemit")
class StubClient: class StubClient:
+5 -4
View File
@@ -13,6 +13,7 @@ import requests
import responses import responses
from langcodes import Language from langcodes import Language
from tests.remote.sessions import hold_session
from unshackle.core.remote_protocol import LicensingMode, Licensor from unshackle.core.remote_protocol import LicensingMode, Licensor
from unshackle.core.remote_service import RemoteClient, RemoteError, RemoteService, quiet from unshackle.core.remote_service import RemoteClient, RemoteError, RemoteService, quiet
from unshackle.core.tracks import Audio from unshackle.core.tracks import Audio
@@ -43,7 +44,7 @@ def make_service() -> RemoteService:
service.log = logging.getLogger("test") service.log = logging.getLogger("test")
service.credential = None service.credential = None
service.service_tag = service.title_id = "TEST" service.service_tag = service.title_id = "TEST"
service._session_id = "s1" hold_session(service, "s1")
service._reopen_lock = Lock() service._reopen_lock = Lock()
service._segment_filters = {} service._segment_filters = {}
service._tracks_by_title = {} 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] service._tracks_by_title["ep3-aaaa"] = [held]
def authenticate(credential=None): def authenticate(credential=None):
service._session_id = "s2" service.lifetime.session_id = "s2"
monkeypatch.setattr(service, "authenticate", authenticate) monkeypatch.setattr(service, "authenticate", authenticate)
monkeypatch.setattr(service, "get_tracks", lambda t: [audio("a-new")]) 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): def test_a_reopened_session_never_takes_another_song_for_a_playlist_song(monkeypatch, before, after, alias):
service = make_service() service = make_service()
service._titles = [build_title(info, "TEST", "x") for info in before] 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/health", json={"status": "ok", "draining": False})
responses.add(responses.GET, f"{SERVER}/api/session/s2/titles", json={"titles": after}) 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 @responses.activate
def test_a_malformed_song_position_on_reopen_is_one_error_line(monkeypatch): def test_a_malformed_song_position_on_reopen_is_one_error_line(monkeypatch):
service = make_service() 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}) responses.add(responses.GET, f"{SERVER}/api/health", json={"status": "ok", "draining": False})
listing = {"titles": [rest_song("song-z", "Z", "x")]} listing = {"titles": [rest_song("song-z", "Z", "x")]}
responses.add(responses.GET, f"{SERVER}/api/session/s2/titles", json=listing) responses.add(responses.GET, f"{SERVER}/api/session/s2/titles", json=listing)
+2 -2
View File
@@ -3,7 +3,7 @@ from types import SimpleNamespace
import pytest import pytest
import requests 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 import server_keys
from unshackle.core.api.errors import APIError from unshackle.core.api.errors import APIError
from unshackle.core.api.handlers import client_session_auth, resolve_handler_proxy, scrub_track_data 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(), _sample_decrypt_tracks=set(),
_server_cdm_request=None, _server_cdm_request=None,
session=requests.Session(), session=requests.Session(),
_session_id="s",
service_tag="EXAMPLE", service_tag="EXAMPLE",
log=logging.getLogger("test"), log=logging.getLogger("test"),
client=SimpleNamespace(post=lambda path, body: {"session_cookie_jar": jar}, probe=lambda endpoint: {}), client=SimpleNamespace(post=lambda path, body: {"session_cookie_jar": jar}, probe=lambda endpoint: {}),
drain_server_logs=lambda: None, drain_server_logs=lambda: None,
) )
hold_session(service)
service.get_tracks(SimpleNamespace(id="t1")) service.get_tracks(SimpleNamespace(id="t1"))
cdn = service.session.prepare_request(requests.Request("GET", "https://cdn.other.net/seg.mp4")) cdn = service.session.prepare_request(requests.Request("GET", "https://cdn.other.net/seg.mp4"))
assert "Cookie" not in cdn.headers assert "Cookie" not in cdn.headers
+3 -2
View File
@@ -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()})") log.info(f"Step 1: this machine exits at {local['ip']} ({str(local.get('country', '?')).upper()})")
client = remote_client(server) client = remote_client(server)
try:
tunnel = start_tunnel(client, proxy) tunnel = start_tunnel(client, proxy)
log.info(f"Step 2: opened a tunnel to {safe_display_url(client.server_url)}") log.info(f"Step 2: opened a tunnel to {safe_display_url(client.server_url)}")
try:
remote = client.get(f"{CHECK_ROUTE}?id={tunnel.id}") remote = client.get(f"{CHECK_ROUTE}?id={tunnel.id}")
finally: finally:
tunnel.stop() if client.tunnel:
client.tunnel.stop()
country = str(remote.get("country", "?")).upper() country = str(remote.get("country", "?")).upper()
# one exit can answer over IPv4 here and IPv6 there, so a matching country also passes # one exit can answer over IPv4 here and IPv6 there, so a matching country also passes
+3 -2
View File
@@ -906,11 +906,12 @@ async def shutdown_download_manager(_app: object) -> None:
def busy_services() -> set[str]: 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.session_store import get_session_store
from unshackle.core.api.stats import stats 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": if stats.mode != "remote_only":
busy |= get_download_manager().busy_services() busy |= get_download_manager().busy_services()
return busy return busy
+69 -43
View File
@@ -40,7 +40,7 @@ from unshackle.core.api.sanitize import (
) )
from unshackle.core.api.session_channel import status_message 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_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.binaries import binary_version
from unshackle.core.cacher import Cacher from unshackle.core.cacher import Cacher
from unshackle.core.cdm.choice import choose_cdm, drm_system 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: 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. """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 from unshackle.core.api.session_store import get_session_store, refuse_while_draining
refuse_while_draining() refuse_while_draining()
session_id = new_session_id(data)
service_tag = data.get("service") service_tag = data.get("service")
title_id = data.get("title_id") title_id = data.get("title_id")
profile = client_profile(data) profile = client_profile(data)
@@ -2794,16 +2806,44 @@ async def session_create_handler(data: dict[str, Any], request: web.Request | No
) )
try: try:
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:
log.exception("Error creating session")
debug_mode = request.app.get("debug_api", False) if request else False
return handle_api_exception(
e,
context={"operation": "session_create", "service": service_tag, "title_id": title_id},
debug_mode=debug_mode,
)
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) 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) policy = request_policy(request)
session_cache_dir = f"_sessions/{api_key_namespace(request)}/{session_id}/{normalized_service}" 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) server_account = server_account_for(policy, normalized_service)
session_cache_tag = None if server_account else session_cache_dir
if server_account: if server_account:
region = data.get("proxy_region") or data.get("client_region") 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)): if region is not None and not (isinstance(region, str) and re.fullmatch(r"[A-Za-z]{2}", region)):
@@ -2826,24 +2866,22 @@ async def session_create_handler(data: dict[str, Any], request: web.Request | No
with capture_service_logs(service_class_name, log_buffer): with capture_service_logs(service_class_name, log_buffer):
return launch_served(purpose, data, normalized_service, title_id, profile, request) 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", {}) cache_data = data.get("cache", {})
client = data.get("client") client = data.get("client")
store = get_session_store() store = get_session_store()
try: 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: if cache_data and session_cache_tag:
await asyncio.to_thread(write_client_cache, cache_data, session_cache_tag) await asyncio.to_thread(write_client_cache, cache_data, session_cache_tag)
session = await store.create( session = await store.create(
normalized_service, normalized_service,
service_instance, service_instance,
session_id=session_id, owner_key=pending.owner_key,
owner_key=api_key, creator_ip=pending.creator_ip,
creator_ip=request.remote if request else None,
server_account=(profile or "default") if server_account else None, server_account=(profile or "default") if server_account else None,
cache_tag=session_cache_tag, cache_tag=session_cache_tag,
policy=policy, policy=policy,
@@ -2854,10 +2892,14 @@ async def session_create_handler(data: dict[str, Any], request: web.Request | No
client=client if isinstance(client, dict) and len(json.dumps(client, default=str)) <= 4096 else {}, client=client if isinstance(client, dict) and len(json.dumps(client, default=str)) <= 4096 else {},
input_bridge=bridge, input_bridge=bridge,
log_buffer=log_buffer, log_buffer=log_buffer,
pending=pending,
) )
if store.peek(session_id) is not session:
pending.refuse()
except BaseException: except BaseException:
if store.peek(session_id) is None: entry = store.peek(session_id)
SessionStore.cleanup_cache_dir(session_cache_tag) if entry is None or entry.cache_tag != session_cache_tag:
await SessionStore.remove_cache_dirs([session_cache_tag])
raise raise
async def run_auth() -> None: async def run_auth() -> None:
@@ -2887,17 +2929,6 @@ async def session_create_handler(data: dict[str, Any], request: web.Request | No
) )
) )
except APIError:
raise
except (Exception, SystemExit) as e:
log.exception("Error creating session")
debug_mode = request.app.get("debug_api", False) if request else False
return handle_api_exception(
e,
context={"operation": "session_create", "service": service_tag, "title_id": title_id},
debug_mode=debug_mode,
)
async def session_titles_handler(session_id: str, request: web.Request | None = None) -> web.Response: async def session_titles_handler(session_id: str, request: web.Request | None = None) -> web.Response:
"""Get titles for the authenticated remote session. """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 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. (kept as defence in depth) cannot distinguish users on its own.
""" """
import hmac
from unshackle.core.api.session_store import get_session_store from unshackle.core.api.session_store import get_session_store
store = 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}", f"Session not found or expired: {session_id}",
details={"session_id": session_id}, details={"session_id": session_id},
) )
if session.owner_key is not None and request is not None: if request is not None and not holds(session, caller_key(request), request.remote):
if not hmac.compare_digest(caller_key(request), session.owner_key): raise APIError(APIErrorCode.FORBIDDEN, "Session access denied")
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",
)
return session 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: 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 from unshackle.core.api.session_store import get_session_store
session = await get_validated_session(session_id, request)
store = get_session_store() 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() session.end()
cache_tag = session.cache_tag cache_tag = session.cache_tag
+14 -2
View File
@@ -1980,6 +1980,14 @@ async def session_create(request: web.Request) -> web.Response:
type: string type: string
title_id: title_id:
type: string 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: credentials:
type: object type: object
additionalProperties: true additionalProperties: true
@@ -2127,7 +2135,9 @@ async def session_create(request: web.Request) -> web.Response:
'403': '403':
description: | description: |
SERVER_CDM_CAPPED when `quality` asks for more than the server CDM limit and the client 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': '401':
description: Authentication failed description: Authentication failed
""" """
@@ -2575,7 +2585,9 @@ async def session_delete(request: web.Request) -> web.Response:
Delete a remote session. Delete a remote session.
--- ---
summary: Delete 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: parameters:
- name: session_id - name: session_id
in: path in: path
+87 -10
View File
@@ -11,19 +11,22 @@ from __future__ import annotations
import asyncio import asyncio
import builtins import builtins
import contextlib import contextlib
import hmac
import logging import logging
import uuid import uuid
from collections import Counter, deque from collections import Counter, deque
from collections.abc import AsyncIterator
from dataclasses import dataclass, field from dataclasses import dataclass, field
from datetime import UTC, datetime 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.events import bus
from unshackle.core.api.input_bridge import AUTH_INPUT_TIMEOUT, InputBridge from unshackle.core.api.input_bridge import AUTH_INPUT_TIMEOUT, InputBridge
from unshackle.core.api.sanitize import sanitize_log from unshackle.core.api.sanitize import sanitize_log
from unshackle.core.api.session_channel import SessionChannel, drain_message from unshackle.core.api.session_channel import SessionChannel, drain_message
from unshackle.core.config import config 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 from unshackle.core.tracks import Track, Tracks
if TYPE_CHECKING: 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: 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.""" """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 from unshackle.core.api.download_manager import schedule_pending_reload
@@ -165,6 +198,7 @@ class SessionStore:
def __init__(self) -> None: def __init__(self) -> None:
self._sessions: dict[str, SessionEntry] = {} self._sessions: dict[str, SessionEntry] = {}
self._pending: dict[str, PendingCreate] = {}
self._lock = asyncio.Lock() self._lock = asyncio.Lock()
self._cleanup_task: asyncio.Task | None = None self._cleanup_task: asyncio.Task | None = None
self._logins: set[asyncio.Task[None]] = set() self._logins: set[asyncio.Task[None]] = set()
@@ -185,6 +219,43 @@ class SessionStore:
limit = config.serve.get("max_sessions", 100) limit = config.serve.get("max_sessions", 100)
return limit if isinstance(limit, int) and limit > 0 else None 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( async def create(
self, self,
service_tag: str, service_tag: str,
@@ -201,10 +272,19 @@ class SessionStore:
client: dict[str, Any] | None = None, client: dict[str, Any] | None = None,
input_bridge: InputBridge | None = None, input_bridge: InputBridge | None = None,
log_buffer: Any | None = None, log_buffer: Any | None = None,
pending: PendingCreate | None = None,
) -> SessionEntry: ) -> SessionEntry:
"""Make a new remote session, complete with every field the dashboard shows, and announce it.""" """Make a new remote session, complete with every field the dashboard shows, and announce it.
evicted_tag: str | None = None
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: 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 max_sessions = self.max_sessions
if max_sessions is not None and len(self._sessions) >= max_sessions: if max_sessions is not None and len(self._sessions) >= max_sessions:
sessions = self._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), 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}") 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()) session_id = session_id or str(uuid.uuid4())
entry = SessionEntry( entry = SessionEntry(
@@ -235,7 +315,7 @@ class SessionStore:
self._sessions[session_id] = entry self._sessions[session_id] = entry
_publish("create", entry) _publish("create", entry)
log.info(f"Created session {sanitize_log(session_id)} for service {sanitize_log(service_tag)}") 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 return entry
async def get(self, session_id: str) -> SessionEntry | None: 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. """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 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: async with self._lock:
cache_tags = [self._retire(entry, None) for entry in list(self._sessions.values())] 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: def refuse_while_draining() -> None:
"""Raise SERVER_DRAINING for a new session or job once the operator has started a drain.""" """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: if get_session_store().draining:
raise APIError( raise APIError(
APIErrorCode.SERVER_DRAINING, APIErrorCode.SERVER_DRAINING,
+17 -5
View File
@@ -57,6 +57,7 @@ CONNECT_TIMEOUT = 10.0
RECONNECT_DELAY = 1.0 RECONNECT_DELAY = 1.0
GONE_STATUSES = (401, 403, 404) # the API key or the remote session is gone, so a reconnect cannot help GONE_STATUSES = (401, 403, 404) # the API key or the remote session is gone, so a reconnect cannot help
SEND_TIMEOUT = 10.0 SEND_TIMEOUT = 10.0
CDM_CLOSE_TIMEOUT = 5.0
KEPT_ANSWERS = 64 KEPT_ANSWERS = 64
LEVELS = logging.getLevelNamesMapping() LEVELS = logging.getLevelNamesMapping()
@@ -78,7 +79,7 @@ class ServerMessages:
self.cdm_sessions: dict[str, bytes] = {} self.cdm_sessions: dict[str, bytes] = {}
def route(self, route: str) -> str: 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: 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.""" """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) show_notice(notice, self.service.auth_qr)
def close_cdm_sessions(self) -> None: 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 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(): for session_id in self.cdm_sessions.values():
with contextlib.suppress(Exception): with contextlib.suppress(Exception):
cdm.close(session_id) cdm.close(session_id)
self.cdm_sessions.clear() self.cdm_sessions.clear()
finally:
self.cdm_lock.release()
def login_done(self) -> None: def login_done(self) -> None:
self.close_cdm_sessions() self.close_cdm_sessions()
@@ -230,6 +235,8 @@ class PollingChannel:
def runs_service_code(self, endpoint: str) -> bool: def runs_service_code(self, endpoint: str) -> bool:
"""Whether a request to *endpoint* runs service code on the server, which can make CDM calls.""" """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)} 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 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.ws: aiohttp.ClientWebSocketResponse | None = None
self.loop: asyncio.AbstractEventLoop | None = None self.loop: asyncio.AbstractEventLoop | None = None
self.task: asyncio.Task[None] | 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) 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: def open(self, timeout: float = CONNECT_TIMEOUT) -> bool:
@@ -340,8 +348,10 @@ class WebSocketChannel:
async def run(self) -> None: async def run(self) -> None:
self.loop, self.task = asyncio.get_running_loop(), asyncio.current_task() self.loop, self.task = asyncio.get_running_loop(), asyncio.current_task()
try: try:
if not self.stopped:
with quiet():
await self.connect() await self.connect()
except asyncio.CancelledError: except (asyncio.CancelledError, RemoteError):
pass pass
finally: finally:
self.attempted.set() self.attempted.set()
@@ -483,6 +493,7 @@ class WebSocketChannel:
return self.draining_now if self.connected.is_set() else self.fallback.draining() return self.draining_now if self.connected.is_set() else self.fallback.draining()
def close(self) -> None: def close(self) -> None:
self.stopped = True
if self.loop and self.task and self.thread.is_alive(): if self.loop and self.task and self.thread.is_alive():
with contextlib.suppress(RuntimeError): # the loop closes before its thread ends with contextlib.suppress(RuntimeError): # the loop closes before its thread ends
self.loop.call_soon_threadsafe(self.task.cancel) self.loop.call_soon_threadsafe(self.task.cancel)
@@ -500,8 +511,9 @@ def open_channel(service: RemoteService) -> Channel:
fallback = PollingChannel(messages) fallback = PollingChannel(messages)
if service.client.no_channel: if service.client.no_channel:
return fallback return fallback
channel = WebSocketChannel(messages, fallback) channel = service.lifetime.channel = WebSocketChannel(messages, fallback)
if channel.open(): if channel.open():
return channel return channel
service.lifetime.require_open()
service.client.no_channel = True service.client.no_channel = True
return fallback return fallback
+180
View File
@@ -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)
+1
View File
@@ -125,6 +125,7 @@ class SessionCreate(ClientLogin, total=False):
service: str service: str
title_id: str title_id: str
session_id: str
profile: str profile: str
service_params: dict[str, Any] service_params: dict[str, Any]
season: Any season: Any
+48 -58
View File
@@ -7,7 +7,6 @@ Everything else (track selection, download, decrypt, mux) runs locally.
from __future__ import annotations from __future__ import annotations
import atexit
import base64 import base64
import contextlib import contextlib
import hashlib import hashlib
@@ -78,7 +77,6 @@ from unshackle.core.remote_protocol import (
SegmentFilterReply, SegmentFilterReply,
SegmentFilterRequest, SegmentFilterRequest,
SegmentsRequest, SegmentsRequest,
SessionClosed,
SessionCreate, SessionCreate,
SessionCreated, SessionCreated,
TitlesReply, TitlesReply,
@@ -106,6 +104,7 @@ from unshackle.core.wire import apply_tracks_reply, build_chapters, build_music,
if TYPE_CHECKING: if TYPE_CHECKING:
from unshackle.core.remote_channel import Channel from unshackle.core.remote_channel import Channel
from unshackle.core.remote_lifetime import RemoteSessionLifetime
log = logging.getLogger("remote_service") 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()``.""" """This thread's RemoteError log state: inside ``session_call`` (``recovering``) and under ``quiet()``."""
recovering = False recovering = False
quiet = False quiet: Callable[[], bool] = staticmethod(lambda: False)
_mute = _Mute() _mute = _Mute()
@@ -163,10 +162,10 @@ def malformed_answer(what: str) -> Iterator[None]:
@contextlib.contextmanager @contextlib.contextmanager
def quiet() -> Iterator[None]: def quiet(when: Callable[[], bool] = lambda: True) -> Iterator[None]:
"""Log this thread's RemoteErrors at debug level, because the caller reports them.""" """Log this thread's RemoteErrors at debug level, because the caller reports them; only while ``when`` is true."""
before = _mute.quiet before = _mute.quiet
_mute.quiet = True _mute.quiet = lambda: before() or when()
try: try:
yield yield
finally: finally:
@@ -210,7 +209,7 @@ class RemoteError(SystemExit):
super().__init__(1) super().__init__(1)
self.message = sanitize_log(message) self.message = sanitize_log(message)
self.kind = kind 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) (log.debug if muted else log.error)(self.message)
def __str__(self) -> str: 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.""" """GET an endpoint that an older server may not have. Empty dict when the route is missing."""
return self.request("get", endpoint, optional=True) 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]]: 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).""" """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 slot_deadline = time.monotonic() + RETRY_AFTER_MAX
rate_waits = 0 rate_waits = 0
while True: while True:
tunnel = TunnelClient(client.server_url, headers, proxy) tunnel = client.tunnel = TunnelClient(client.server_url, headers, proxy)
try: try:
tunnel.start() tunnel.start()
break 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") wait_retry_after(TUNNEL_SLOT_POLL, "Every tunnel of this API key is in use")
else: else:
raise click.ClickException(f"--local-proxy could not open a tunnel to the server: {e}") from None raise click.ClickException(f"--local-proxy could not open a tunnel to the server: {e}") from None
client.tunnel = tunnel
return tunnel return tunnel
@@ -810,7 +805,7 @@ class RemoteService(TitleSource):
""" """
server_cdm_type: str = "widevine" server_cdm_type: str = "widevine"
channel: Channel | None = None lifetime: RemoteSessionLifetime
licensing: LicensingMode | None = None licensing: LicensingMode | None = None
"""The server's answer to who licenses this remote session; an older server gives it in the tracks reply.""" """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 _server_cdm_request: bool | None = None
@@ -826,6 +821,8 @@ class RemoteService(TitleSource):
services_config: dict, services_config: dict,
service_params: dict[str, Any] | None = None, service_params: dict[str, Any] | None = None,
) -> None: ) -> None:
from unshackle.core.remote_lifetime import RemoteSessionLifetime
self.__class__.__name__ = service_tag self.__class__.__name__ = service_tag
console.print(Padding(Rule(f"[rule.text]Service: {service_tag} (Remote)"), (1, 2))) 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._titles: Titles_T | None = None
self._tracks_by_title: dict[str, Tracks] = {} self._tracks_by_title: dict[str, Tracks] = {}
self._chapters_by_title: dict[str, list] = {} 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.client_licensed: set[str] = set() # track ids this machine's device licenses by challenge relay
self.deferred_refusals: dict[str, str] = {} self.deferred_refusals: dict[str, str] = {}
self.server_vault_keys: dict[UUID, str] = {} self.server_vault_keys: dict[UUID, str] = {}
@@ -917,6 +914,14 @@ class RemoteService(TitleSource):
def title(self) -> str: def title(self) -> str:
return self.title_id 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]: def search(self) -> Iterator[SearchResult]:
"""Search on the server, which logs in to the service itself with the login material sent here.""" """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 {} params = self.ctx.parent.params if self.ctx.parent else {}
@@ -926,6 +931,7 @@ class RemoteService(TitleSource):
data["profile"] = profile data["profile"] = profile
if not self._anonymous_search: if not self._anonymous_search:
data.update(self.client_login(profile)) data.update(self.client_login(profile))
try:
if params.get("no_proxy"): if params.get("no_proxy"):
data["no_proxy"] = True data["no_proxy"] = True
elif params.get("local_proxy"): elif params.get("local_proxy"):
@@ -934,7 +940,6 @@ class RemoteService(TitleSource):
providers = getattr(self.ctx.obj, "proxy_providers", None) providers = getattr(self.ctx.obj, "proxy_providers", None)
data["proxy"] = resolve_remote_proxy_arg(server_proxy_arg(params), providers) data["proxy"] = resolve_remote_proxy_arg(server_proxy_arg(params), providers)
self.require_reachable_proxy(data["proxy"]) self.require_reachable_proxy(data["proxy"])
try:
response = self.client.post(SEARCH_ROUTE, data) response = self.client.post(SEARCH_ROUTE, data)
finally: finally:
if self.client.tunnel: # a search is one request, so its tunnel ends with it 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}" return f"tunnel:{tunnel.id}"
def authenticate(self, cookies: CookieJar | None = None, credential: Credential | None = None) -> None: 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 self.credential = credential
profile = self.ctx.parent.params.get("profile") if self.ctx.parent else None 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 proxy = self.ctx.parent.params.get("proxy") if self.ctx.parent else None
@@ -1121,16 +1131,11 @@ class RemoteService(TitleSource):
"argv": argv, "argv": argv,
} }
try: create_data["session_id"] = self.lifetime.name()
result = cast(SessionCreated, self.client.post(SESSION_CREATE_ROUTE, create_data)) result = cast(SessionCreated, self.client.post(SESSION_CREATE_ROUTE, create_data))
if not isinstance(result.get("session_id"), str): if not isinstance(result.get("session_id"), str):
raise RemoteError("The remote server sent malformed session: no session_id", ClientErrorKind.UNKNOWN) raise RemoteError("The remote server sent malformed session: no session_id", ClientErrorKind.UNKNOWN)
except BaseException: self.lifetime.adopt(create_data["session_id"], result["session_id"])
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)
# an older server omits the field, and the tracks response settles it # an older server omits the field, and the tracks response settles it
if "server_cdm" in result: if "server_cdm" in result:
answer = LicensingMode.from_created(result) answer = LicensingMode.from_created(result)
@@ -1151,13 +1156,13 @@ class RemoteService(TitleSource):
from unshackle.core.remote_channel import open_channel 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: if result.get("status", AuthStatus.AUTHENTICATED) == AuthStatus.AUTHENTICATING:
self.channel.wait_auth() channel.wait_auth()
if create_data.get("cdm_relay"): 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.drain_server_logs()
self.channel.keep_alive() channel.keep_alive()
@property @property
def local_cdm(self) -> Any: def local_cdm(self) -> Any:
@@ -1223,7 +1228,7 @@ class RemoteService(TitleSource):
raise raise
lost = e lost = e
if not self.recover(session_id, lost.kind): if not self.recover(session_id, lost.kind):
if not _mute.quiet: if not _mute.quiet():
log.error(lost.message) log.error(lost.message)
raise lost raise lost
return call(self._session_id) return call(self._session_id)
@@ -1245,14 +1250,18 @@ class RemoteService(TitleSource):
if alive: if alive:
return kind == ClientErrorKind.CONNECT return kind == ClientErrorKind.CONNECT
self.log.warning("The remote session was lost, opening a new one") self.log.warning("The remote session was lost, opening a new one")
self.lifetime.release(gone=kind == APIErrorCode.SESSION_NOT_FOUND)
return self.reopen() return self.reopen()
def wait_for_server(self, accepting: bool) -> bool: 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 deadline = time.monotonic() + REOPEN_WAIT
delay = 1.0 delay = 1.0
warned = False warned = False
while True: while not self.lifetime.ended:
health = self.client.probe(HEALTH_ROUTE) health = self.client.probe(HEALTH_ROUTE)
if health.get("status") == "ok" and not (accepting and health.get("draining")): if health.get("status") == "ok" and not (accepting and health.get("draining")):
return True 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 # 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 time.sleep(random.uniform(delay / 2, delay)) # nosec B311
delay = min(delay * 2, 30.0) delay = min(delay * 2, 30.0)
return False
def licence_path(self) -> object: def licence_path(self) -> object:
"""Where this remote session takes its keys from, which a reopened session must keep. """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 return (licensing.licensor, licensing.vault_first) if licensing else self._server_cdm_request
def reopen(self) -> bool: 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. A track the new remote session gives another id keeps its old one here, and calls translate it.
""" """
grants = self.licence_path() 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() self._segment_filters.clear()
if not self.wait_for_server(accepting=True): if not self.wait_for_server(accepting=True):
return False return False
@@ -1322,10 +1327,10 @@ class RemoteService(TitleSource):
return True return True
def reopen_after_drain(self) -> None: 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: with self._reopen_lock:
self.log.info("The remote server restarts for an update, reopening the session after it") self.log.info("The remote server restarts for an update, reopening the session after it")
self.close() self.lifetime.release()
self._current_title = None self._current_title = None
if not self.reopen(): if not self.reopen():
raise RemoteError( raise RemoteError(
@@ -1345,11 +1350,6 @@ class RemoteService(TitleSource):
if self.channel: if self.channel:
self.channel.drain_logs() 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: def get_titles(self) -> Titles_T:
if self._titles is not None: if self._titles is not None:
return self._titles return self._titles
@@ -1851,22 +1851,12 @@ class RemoteService(TitleSource):
) from None ) from None
def close(self) -> None: def close(self) -> None:
# a long-lived serve opens many of these; the atexit hook would keep every one alive """End the remote session for good. dl, the job worker and the relay pool all end it here."""
atexit.unregister(self.close) self.lifetime.end()
self.close_channel()
session_id, self._session_id = self._session_id, None def save_session_cache(self, cache_data: dict[str, str]) -> None:
if session_id: """Save the cache files that the DELETE of the remote session returns."""
try: self.save_returned_cache(cache_data, self.ctx.parent.params.get("profile") if self.ctx.parent else None)
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()
def save_returned_cache(self, cache_data: dict[str, str], profile: str | None = None) -> 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. """Save cache files returned by the server to the local cache directory.
+4
View File
@@ -549,6 +549,7 @@ class TunnelClient:
self.thread = threading.Thread(target=run_loop, args=(self.run,), name="tunnel", daemon=True) self.thread = threading.Thread(target=run_loop, args=(self.run,), name="tunnel", daemon=True)
self.loop: asyncio.AbstractEventLoop | None = None self.loop: asyncio.AbstractEventLoop | None = None
self.task: asyncio.Task[None] | None = None self.task: asyncio.Task[None] | None = None
self.stopped = False
def start(self, timeout: float = 20) -> str: def start(self, timeout: float = 20) -> str:
"""Open the tunnel and return its id.""" """Open the tunnel and return its id."""
@@ -560,6 +561,7 @@ class TunnelClient:
def stop(self) -> None: def stop(self) -> None:
"""Close the tunnel and wait for its connections to end, so none is left pending at exit.""" """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(): if self.loop and self.task and self.thread.is_alive():
with contextlib.suppress(RuntimeError): # the loop closes before its thread ends with contextlib.suppress(RuntimeError): # the loop closes before its thread ends
self.loop.call_soon_threadsafe(self.task.cancel) self.loop.call_soon_threadsafe(self.task.cancel)
@@ -567,6 +569,8 @@ class TunnelClient:
async def run(self) -> None: async def run(self) -> None:
self.loop, self.task = asyncio.get_running_loop(), asyncio.current_task() self.loop, self.task = asyncio.get_running_loop(), asyncio.current_task()
if self.stopped:
return
try: try:
await self.connect() await self.connect()
except asyncio.CancelledError: except asyncio.CancelledError: