feat(remote): end a remote session when its client is gone

This commit is contained in:
imSp4rky
2026-11-30 17:23:35 -07:00
parent e813737506
commit ffe812f054
13 changed files with 747 additions and 53 deletions
+2 -2
View File
@@ -950,7 +950,7 @@ Report the install status of the external binaries unshackle depends on (the sam
!!! note "Developer feature"
The `/api/session/*` endpoints power unshackle's **remote download** mode. A thin local client authenticates once against a remote server, then fetches titles, tracks, and segments, and proxies DRM licensing back through it. The server mounts these endpoints in `--remote-only` mode, and they are what the built-in `RemoteService` client drives. Most end users never call them directly.
The server holds remote sessions in memory. They expire after `serve.session_ttl` (default 300s) without a request, except while the login runs, which can stay idle for the larger of `session_ttl` and 600s. A remote session binds to the IP that made it, so the server rejects a request from a different IP with `403 FORBIDDEN`.
The server holds remote sessions in memory. They expire after `serve.session_ttl` (default 300s) without a request, except while the login runs, which can stay idle for the larger of `session_ttl` and 600s. A remote session whose client is gone ends sooner: see [Client presence](remote-sessions.md#client-presence). A remote session binds to the IP that made it, so the server rejects a request from a different IP with `403 FORBIDDEN`.
### Remote session lifecycle overview
@@ -989,7 +989,7 @@ the newlines must go out at once.
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.
`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 remote session with your ID ends when you send no request for it and open no channel within 150s of the create. 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`.
+38 -10
View File
@@ -385,20 +385,22 @@ HTTP session headers and `track.data` lose their secret-looking keys, as for a s
## Remote session lifecycle and expiry
Remote sessions live in an **in-memory store on the server** and expire on a timer. You
Remote sessions live in an **in-memory store on the server**. They expire on a timer, or when their client is gone. You
generally never touch this directly, but it explains behaviour you might observe.
| Behavior | Value | Notes |
|---|---|---|
| Idle session TTL | **300s** (5 min) default | Refreshed on every request to the session and when a `titles` or `tracks` request ends. A remote session does not expire while a request works on it or while its remote session channel is open |
| Idle session TTL | **300s** (5 min) default | Refreshed on every request to the session and when a `titles` or `tracks` request ends. A remote session does not reach this limit while a request works on it or while its remote session channel is open |
| Client presence | **180s**, **150s** or **90s** | The time that a client can be silent after it lost its channel, after `create`, or after it closed its channel. See [Client presence](#client-presence) |
| Max concurrent sessions | **100** default | When full, the least recently used remote session of the API key that holds the most is evicted. A remote session that a request works on goes last |
| Auth/input timeout | **600s** (10 min) | A remote session that still logs in, a prompt included, can stay idle for the larger of the TTL and this value |
| Cleanup sweep | every 60s | Expired sessions are removed and their input prompts cancelled |
| Auth/input timeout | **600s** (10 min) | A remote session that still logs in, a prompt included, can stay idle for the larger of the TTL and this value, unless its client is gone |
| Cleanup sweep | every 5s | Expired sessions are removed and their input prompts cancelled |
!!! note "Auth is never rushed"
A remote session that is still `authenticating` or waiting on `pending_input` can stay
idle for the larger of `session_ttl` and 600s. This gives you time to enter an interactive
code without the remote session vanishing mid-prompt.
code without the remote session vanishing mid-prompt. The client must stay: it keeps its
channel open, or it polls.
The TTL and max-session limits are read from server config:
@@ -550,7 +552,7 @@ layer.
fails then, because no client is listening. A fetched call waits 60 seconds for its answer.
The call leaves the auth status as it was. An answer never marks the remote session as client-authenticated.
- `AUTH_INPUT_TIMEOUT = 600.0` seconds. An `AUTHENTICATING` remote session expires in the store after
the larger of `session_ttl` and this value. A remote session that waits on a prompt stays `AUTHENTICATING`.
the larger of `session_ttl` and this value, or when its client is gone. A remote session that waits on a prompt stays `AUTHENTICATING`.
`GET /api/session/{id}/prompt` returns one of:
@@ -621,15 +623,17 @@ Source: `unshackle/core/api/session_store.py`. A singleton you get from
key or IP has. **`end_pending()`** ends such a create for a `DELETE`, and then `create()` stores nothing.
- **`create()`** evicts the least-recently-accessed remote session of the API key that holds the most when at capacity,
then stores a complete `SessionEntry` from the fields of the `create` handler and publishes the `create` event.
- **Expiry.** `get()` and `cleanup_expired()` use one rule. A remote session that no request holds
expires when it is idle for longer than `ttl`. While its login runs (`AUTHENTICATING`), the limit is
- **Expiry.** `get()` and `cleanup_expired()` use one rule. A remote session expires when its client is gone
([Client presence](#client-presence)), also while a request holds it. A remote session that no request holds
also expires when it is idle for longer than `ttl`. While its login runs (`AUTHENTICATING`), the limit is
the larger of `ttl` and `AUTH_INPUT_TIMEOUT`.
- **`get()`** refreshes `last_accessed` and `idle_since` through `touch()`. It returns `None` and
deletes the entry when the remote session has expired.
- **`cleanup_expired()`** runs every 60s and removes each expired remote session.
- **`cleanup_expired()`** runs every 5s and removes each expired remote session.
- **Removal.** Eviction, expiry and `delete()` end the remote session the same way: they cancel its
`InputBridge`, close its channel, send the `delete` dashboard event, schedule a staged service reload
and delete its cache directory (pruning empty parent dirs up to, but not including, the cache root).
and delete its cache directory (pruning empty parent dirs up to, but not including, the cache root). A request
that waits for the remote session then answers `SESSION_NOT_FOUND` and starts no service code.
- **`track_login(task)`** keeps each login task of `session/create` until it ends.
- The server calls **`close()`** on shutdown. It ends each open remote session, which
unblocks any waiting auth threads, and deletes the cache directory of each one. It sends no dashboard event
@@ -649,9 +653,33 @@ Source: `unshackle/core/api/session_store.py`. A singleton you get from
| `cache_tag` | Per-session cache directory tag |
| `input_bridge` | `InputBridge` for interactive auth, if any |
| `auth_status` / `auth_error` | Current `AuthStatus`, read from `input_bridge` (`AUTHENTICATED` without one), and last error message |
| `presence` | `ClientPresence`: the state of the client and its last sign of life |
| `created_at` / `last_accessed` | Timestamps; `last_accessed` drives LRU eviction |
| `idle_since` | Monotonic time of the last access; it drives the TTL, so a step of the system clock expires no remote session |
### Client presence
Source: `unshackle/core/api/client_presence.py`. The server knows a client by its channel, its requests and its
`create`. Each state has a limit for the silence of the client. At the limit, the server ends the remote session.
| State | When | Limit |
|---|---|---|
| awaited | The client gave the remote session its ID in `create`, and has sent no request and opened no channel since | 150s |
| polling | The client has had no channel | The TTL rule only |
| present | The channel is open | None |
| away | The channel closed with any code except 1000, the connection broke, or the server closed the channel | 180s, or half of `session_ttl` when that is more |
| left | The client closed the channel with code 1000 | 90s |
- **Sign of life.** A request of the client for the remote session, or a new channel, starts the time again. The end
of a request does not. A request after the state left makes the state away.
- **Work in progress.** A request that still works for the client does not keep the remote session past the limit.
- **Login.** A client that is away or left does not get the 600s of a login. Its login ends with the remote session.
- **TTL.** The limit never makes a remote session stay for longer than the TTL rule lets it.
- **The `DELETE`.** The client closes its channel and then sends the `DELETE`, whose answer has the login cache.
Thus the close does not end the remote session at once.
- **A silent loss.** A client that the network cuts off sends no close. The server sends a ping after 20s without
data, and counts the client as away when no answer comes in 10s.
### Per-session cache namespacing
The `create` handler builds a `Cacher` namespaced as:
+1 -1
View File
@@ -163,7 +163,7 @@ is the [REST API](../../dev/rest-api/index.md) section. These are the config key
| `services` | list | *(unset)* | Global service allowlist. Omit to allow all. |
| `remote_only` | bool | `false` | Expose only the remote service session endpoints (health, services, search, session) and disable the rest of the REST API. |
| `dashboard` | dict | *(unset)* | Developer dashboard: `key` is the API key for the read-only `/api/dashboard/` endpoints (status, remote sessions, remote session logs, jobs, keys, services, health, logs, SSE events). Unset leaves those routes unregistered, and a reload that removes the key makes them answer `404`. See [dashboard endpoints](../../dev/rest-api/dashboard.md). |
| `session_ttl` | int (s) | `300` | Seconds a remote session can stay idle before it expires. A remote client sends keep-alive requests to its remote session during a download, so the remote session does not expire during a long download. A remote session that still logs in can stay idle for the larger of this value and 600 seconds. |
| `session_ttl` | int (s) | `300` | Seconds a remote session can stay idle before it expires. A remote client sends keep-alive requests to its remote session during a download, so the remote session does not expire during a long download. A remote session that still logs in can stay idle for the larger of this value and 600 seconds. A client that closes or loses its channel and does not come back loses its remote session sooner: see [Client presence](../../dev/rest-api/remote-sessions.md#client-presence). |
| `max_sessions` | int or null | `100` | Maximum concurrent remote sessions; at the cap the server evicts the oldest remote session of the API key that holds the most. Set it to `null` or `0` for no limit, which is also what `/api/dashboard/status` then reports, so a dashboard can tell "no cap" from a cap that happens to sit at the default. |
| `history_limit` | int | `100` | How many finished jobs to retain in history. |
| `compression_level` | int | `1` | gzip level for responses. |
+549
View File
@@ -0,0 +1,549 @@
"""How long a remote session stays without a sign of its client: the close of its channel, its requests, its create.
The clients are real ones, and the silence is a moved clock: the limits are the ones of the server.
"""
from __future__ import annotations
import asyncio
import contextlib
import math
import subprocess
import time
import uuid
from collections.abc import Callable, Iterator
from pathlib import Path
from threading import Event
from types import SimpleNamespace
from typing import Any
import aiohttp
import pytest
import requests
from aiohttp import web
from tests.remote.unit.test_remote_loopback import server # noqa: F401
from tests.remote.unit.test_remote_loopback import (
CODE,
KEY,
OTHER_KEY,
StubService,
gate_channel,
make_client,
on_loop,
)
from tests.remote.unit.test_session_lifetime import ( # noqa: F401
DEADLINE,
client,
create,
delete,
in_thread,
logins,
sessions,
wait_authenticated,
)
from tests.remote.unit.test_tunnel import wait_until
from unshackle.core.api import session_store
from unshackle.core.api.client_presence import (
AWAY_LIMIT,
FIRST_CONTACT_LIMIT,
LEFT_LIMIT,
ClientPresence,
ClientState,
)
from unshackle.core.api.input_bridge import AUTH_INPUT_TIMEOUT, InputBridge
from unshackle.core.api.session_store import SessionEntry, SessionStore
from unshackle.core.config import config
from unshackle.core.remote_channel import CDM_CLOSE_TIMEOUT
from unshackle.core.remote_lifetime import END_TIMEOUT
from unshackle.core.remote_protocol import (
CHANNEL_ROUTE,
CHANNEL_SESSION_GONE,
LOGS_ROUTE,
PROMPT_ROUTE,
SESSION_CREATE_ROUTE,
SESSION_ROUTE,
TITLES_ROUTE,
APIErrorCode,
AuthStatus,
)
from unshackle.core.remote_service import PROBE_TIMEOUT
from unshackle.core.tunnel import HEARTBEAT
pytestmark = pytest.mark.unit
TTL = 300
Start = Callable[..., subprocess.Popen[str]]
@pytest.fixture(autouse=True)
def ttl(server: SimpleNamespace, monkeypatch: pytest.MonkeyPatch) -> None: # noqa: F811
monkeypatch.setitem(config.serve, "session_ttl", TTL)
def silent_for(entry: SessionEntry, seconds: float) -> None:
entry.presence.seen_at = time.monotonic() - seconds
def sweep(server: SimpleNamespace) -> int: # noqa: F811
return on_loop(server, session_store.get_session_store().cleanup_expired())
def ends_after(server: SimpleNamespace, entry: SessionEntry, limit: float) -> bool: # noqa: F811
"""Whether the sweep keeps the remote session just before *limit* seconds of silence, and ends it just after."""
silent_for(entry, limit - 5)
kept = sweep(server) == 0 and sessions() == [entry]
silent_for(entry, limit + 1)
return kept and sweep(server) == 1 and sessions() == []
def stays(server: SimpleNamespace, entry: SessionEntry) -> bool: # noqa: F811
silent_for(entry, 10 * AUTH_INPUT_TIMEOUT)
return sweep(server) == 0
def logged_in(entry: SessionEntry) -> bool:
return wait_until(lambda: entry.auth_status is AuthStatus.AUTHENTICATED, DEADLINE)
def store_token(entry: SessionEntry) -> Path:
"""Write a login cache file on the server, and return its directory."""
stored = config.directories.cache / str(entry.cache_tag) / "token.json"
stored.parent.mkdir(parents=True)
stored.write_text('"EXAMPLE"', encoding="utf-8")
return stored.parent
def get(server: SimpleNamespace, route: str, entry: SessionEntry, key: str = KEY) -> requests.Response: # noqa: F811
url = server.url + route.format(session_id=entry.session_id)
return requests.get(url, headers={"X-Secret-Key": key}, timeout=DEADLINE)
def state_is(entry: SessionEntry, state: ClientState) -> bool:
return wait_until(lambda: entry.presence.state is state, DEADLINE)
@pytest.fixture
def killed(server: SimpleNamespace, client: Start) -> Callable[[], SessionEntry]: # noqa: F811
"""Start a real client and kill it when its channel is attached; the result is its remote session."""
def run(logs_in: bool = True, before: Callable[[SessionEntry], Any] = lambda entry: None) -> SessionEntry:
process = client(server.url)
if logs_in:
wait_authenticated(process)
assert wait_until(lambda: any(s.channel.attached for s in sessions()), DEADLINE)
(entry,) = sessions()
assert stays(server, entry)
before(entry)
process.kill()
assert state_is(entry, ClientState.AWAY)
return entry
return run
def test_the_sweep_ends_the_session_of_a_killed_client_at_the_away_limit(
server: SimpleNamespace, # noqa: F811
logins: list[Any], # noqa: F811
killed: Callable[..., SessionEntry],
monkeypatch: pytest.MonkeyPatch,
) -> None:
assert session_store.SWEEP_INTERVAL <= 5
monkeypatch.setattr(session_store, "SWEEP_INTERVAL", 0.02)
entry = killed()
directory = store_token(entry)
on_loop(server, session_store.get_session_store().start_cleanup_loop())
silent_for(entry, AWAY_LIMIT - 5)
assert not wait_until(lambda: sessions() == [], 0.5)
silent_for(entry, AWAY_LIMIT + 1)
assert wait_until(lambda: sessions() == [] and not directory.exists(), DEADLINE)
def test_the_login_of_a_killed_client_stops_at_the_away_limit(
server: SimpleNamespace, # noqa: F811
killed: Callable[..., SessionEntry],
monkeypatch: pytest.MonkeyPatch,
) -> None:
stopped = Event()
def wait_for_approval(stub: StubService, cookies: Any, credential: Any) -> None:
try:
while not stopped.wait(0.01):
stub._input_bridge.ensure_active()
finally:
stopped.set()
monkeypatch.setattr(StubService, "authenticate", wait_for_approval)
entry = killed(logs_in=False)
assert not stopped.is_set()
assert ends_after(server, entry, AWAY_LIMIT)
assert stopped.wait(DEADLINE)
assert wait_until(lambda: not session_store.get_session_store()._logins, DEADLINE)
def test_a_request_of_a_killed_client_does_not_keep_its_session(
server: SimpleNamespace, # noqa: F811
logins: list[Any], # noqa: F811
killed: Callable[..., SessionEntry],
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""The request holds the lock, and its end is no sign of the client that asked for it."""
release = Event()
monkeypatch.setitem(StubService.hooks, "titles", lambda stub: release.wait(DEADLINE))
events: list[str] = []
monkeypatch.setattr(session_store, "_publish", lambda action, *a, **k: events.append(action))
replies: list[Any] = []
def ask(entry: SessionEntry) -> None:
replies.append(in_thread(lambda: get(server, TITLES_ROUTE, entry)))
assert wait_until(entry.lock.locked, DEADLINE)
try:
entry = killed(before=ask)
assert entry.lock.locked()
assert ends_after(server, entry, AWAY_LIMIT)
with pytest.raises(RuntimeError, match="cancelled"):
entry.input_bridge.ensure_active() # type: ignore[union-attr]
finally:
release.set()
assert replies[0]().status_code == 200
assert entry.presence.silence > AWAY_LIMIT
assert events[-1] == "delete"
def test_a_request_that_waits_for_the_lock_does_not_start_after_the_end(
server: SimpleNamespace, # noqa: F811
logins: list[Any], # noqa: F811
) -> None:
release = Event()
started: list[StubService] = []
StubService.hooks["titles"] = lambda stub: (started.append(stub), release.wait(DEADLINE)) and None
session_id = str(uuid.uuid4())
assert create(server.url, session_id).status_code == 200
(entry,) = sessions()
assert logged_in(entry)
try:
first = in_thread(lambda: get(server, TITLES_ROUTE, entry))
assert wait_until(lambda: len(started) == 1, DEADLINE)
second = in_thread(lambda: get(server, TITLES_ROUTE, entry))
assert wait_until(lambda: bool(entry.lock._waiters), DEADLINE)
on_loop(server, session_store.get_session_store().delete(session_id))
finally:
release.set()
assert first().status_code == 200
assert second().json()["error_code"] == APIErrorCode.SESSION_NOT_FOUND
assert len(started) == 1
@pytest.mark.parametrize("route", [SESSION_ROUTE, PROMPT_ROUTE, LOGS_ROUTE])
def test_the_polls_of_a_client_without_its_channel_keep_its_session_during_a_long_request(
server: SimpleNamespace, # noqa: F811
logins: list[Any], # noqa: F811
monkeypatch: pytest.MonkeyPatch,
route: str,
) -> None:
refuse, release = gate_channel(monkeypatch), Event()
monkeypatch.setitem(StubService.hooks, "titles", lambda stub: release.wait(DEADLINE))
service = make_client(server.url)
try:
service.authenticate()
(entry,) = sessions()
assert state_is(entry, ClientState.PRESENT)
listing = in_thread(service.get_titles)
assert wait_until(entry.lock.locked, DEADLINE)
refuse.set()
on_loop(server, entry.channel.ws.close()) # type: ignore[union-attr]
assert state_is(entry, ClientState.AWAY), "a close that the server starts is not the client's"
for _ in range(3):
silent_for(entry, AWAY_LIMIT - 5)
assert get(server, route, entry).ok and entry.lock.locked()
assert entry.presence.silence < AWAY_LIMIT / 2 and entry.presence.state is ClientState.AWAY
assert sweep(server) == 0
release.set()
assert len(listing()) == 3
finally:
release.set()
service.close()
def test_a_delete_after_the_close_of_the_channel_returns_the_login_cache(
server: SimpleNamespace, # noqa: F811
logins: list[Any], # noqa: F811
) -> None:
service = make_client(server.url)
service.authenticate()
(entry,) = sessions()
assert state_is(entry, ClientState.PRESENT)
store_token(entry)
service.lifetime.close_channel()
assert state_is(entry, ClientState.LEFT)
silent_for(entry, LEFT_LIMIT - 5)
assert sweep(server) == 0
service.close()
assert sessions() == []
assert (config.directories.cache / "EXAMPLE" / "token.json").exists()
def test_a_session_ends_when_no_delete_follows_the_close_of_the_channel(
server: SimpleNamespace, # noqa: F811
logins: list[Any], # noqa: F811
) -> None:
service = make_client(server.url)
service.authenticate()
(entry,) = sessions()
assert state_is(entry, ClientState.PRESENT)
service.lifetime.close_channel()
assert state_is(entry, ClientState.LEFT)
assert ends_after(server, entry, LEFT_LIMIT)
service.close()
@contextlib.contextmanager
def half_open_gateway(server: SimpleNamespace) -> Iterator[str]: # noqa: F811
"""A gateway that passes the channel upgrade to the server, then drops it and answers the client 502."""
async def forward(request: web.Request) -> web.StreamResponse:
async with aiohttp.ClientSession(auto_decompress=False) as http:
headers = {k: v for k, v in request.headers.items() if k.startswith("X-") or k == "Content-Type"}
if request.path.endswith("/channel"):
async with http.ws_connect(server.url + request.path, headers=headers) as ws:
await ws.receive()
ws._response.connection.transport.abort() # type: ignore[union-attr]
return web.Response(status=502)
url, body = server.url + request.path_qs, await request.read()
async with http.request(request.method, url, headers=headers, data=body) as reply:
return web.Response(status=reply.status, body=await reply.read(), content_type="application/json")
async def start() -> web.AppRunner:
app = web.Application()
app.router.add_route("*", "/{path:.*}", forward)
runner = web.AppRunner(app)
await runner.setup()
await web.TCPSite(runner, "127.0.0.1", 0).start()
return runner
runner = on_loop(server, start())
try:
yield f"http://127.0.0.1:{runner.addresses[0][1]}"
finally:
on_loop(server, runner.cleanup())
def test_a_user_who_types_a_code_keeps_the_session_that_the_channel_failed_to_open(
server: SimpleNamespace, # noqa: F811
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""The server saw a channel and its loss, and the client polls: it must do so while its user types."""
typing, typed = Event(), Event()
with half_open_gateway(server) as url:
service = make_client(url)
def ask(prompt: str, qr: object = None) -> str:
typing.set()
assert typed.wait(DEADLINE)
return CODE
service._input_bridge = SimpleNamespace(request_input=ask)
monkeypatch.setitem(config.serve, "session_ttl", 3)
login = in_thread(service.authenticate)
try:
assert typing.wait(DEADLINE)
(entry,) = sessions()
assert entry.presence.state is ClientState.AWAY
silent_for(entry, AWAY_LIMIT - 5)
assert wait_until(lambda: entry.presence.silence < AWAY_LIMIT / 2, DEADLINE), "the client does not poll"
typed.set()
assert login() is None
finally:
typed.set()
service.close()
Socket = aiohttp.ClientWebSocketResponse
@pytest.fixture
def channel(server: SimpleNamespace, logins: list[Any]) -> Callable[..., None]: # noqa: F811
"""Run a check with real client sockets on the channel of one remote session, off the loop of the server."""
def run(check: Callable[[SessionEntry, Callable[[], Any]], Any]) -> None:
assert create(server.url, str(uuid.uuid4())).status_code == 200
(entry,) = sessions()
url = server.url + CHANNEL_ROUTE.format(session_id=entry.session_id)
async def main() -> None:
async with aiohttp.ClientSession(headers={"X-Secret-Key": KEY}) as http:
await check(entry, lambda: http.ws_connect(url))
asyncio.run(asyncio.wait_for(main(), DEADLINE))
return run
async def close_code(socket: Socket) -> Any:
"""Read until the server closes the socket; its close code."""
while (msg := await socket.receive()).type is aiohttp.WSMsgType.TEXT:
pass
return msg.data
async def a_state_is(entry: SessionEntry, state: ClientState) -> bool:
return await asyncio.to_thread(state_is, entry, state)
@pytest.mark.parametrize(
("close", "state"),
[
(lambda ws: ws.close(code=1000), ClientState.LEFT),
(lambda ws: ws.close(code=1001), ClientState.AWAY),
(lambda ws: ws.send_frame(b"", aiohttp.WSMsgType.CLOSE), ClientState.AWAY),
],
ids=["1000", "1001", "no-code"],
)
def test_only_a_close_with_1000_of_the_client_is_a_leave(
channel: Callable[..., None], close: Callable[[Socket], Any], state: ClientState
) -> None:
async def check(entry: SessionEntry, connect: Callable[[], Any]) -> None:
socket = await connect()
assert await a_state_is(entry, ClientState.PRESENT)
await close(socket)
assert await a_state_is(entry, state)
await socket.close()
channel(check)
def test_a_replaced_socket_does_not_mark_the_new_one_away(
server: SimpleNamespace, # noqa: F811
channel: Callable[..., None],
) -> None:
async def check(entry: SessionEntry, connect: Callable[[], Any]) -> None:
first = await connect()
assert await a_state_is(entry, ClientState.PRESENT)
old = entry.channel.ws
second = await connect()
assert await close_code(first) == 1000
await first.close()
assert await asyncio.to_thread(wait_until, lambda: old is not None and old.close_code is not None, DEADLINE)
assert entry.presence.state is ClientState.PRESENT
assert await asyncio.to_thread(stays, server, entry)
await second.close()
assert await a_state_is(entry, ClientState.LEFT)
channel(check)
def test_the_end_of_the_session_is_no_leave(server: SimpleNamespace, channel: Callable[..., None]) -> None: # noqa: F811
async def check(entry: SessionEntry, connect: Callable[[], Any]) -> None:
socket = await connect()
assert await a_state_is(entry, ClientState.PRESENT)
assert (await asyncio.to_thread(delete, server.url, entry.session_id)).ok
assert await close_code(socket) == CHANNEL_SESSION_GONE
assert await a_state_is(entry, ClientState.AWAY)
channel(check)
def test_a_new_channel_or_a_request_after_the_leave_is_a_client_that_still_works(
server: SimpleNamespace, # noqa: F811
channel: Callable[..., None],
) -> None:
"""A client that gives up on a slow channel closes it with 1000 and then polls."""
async def check(entry: SessionEntry, connect: Callable[[], Any]) -> None:
await (await connect()).close()
assert await a_state_is(entry, ClientState.LEFT)
socket = await connect()
assert await a_state_is(entry, ClientState.PRESENT)
await socket.close()
assert await a_state_is(entry, ClientState.LEFT)
assert (await asyncio.to_thread(get, server, SESSION_ROUTE, entry, OTHER_KEY)).status_code == 403
assert entry.presence.state is ClientState.LEFT
assert (await asyncio.to_thread(get, server, SESSION_ROUTE, entry)).ok
assert entry.presence.state is ClientState.AWAY
assert await asyncio.to_thread(ends_after, server, entry, AWAY_LIMIT)
channel(check)
def test_a_client_that_never_comes_back_for_its_session_loses_it(
server: SimpleNamespace, # noqa: F811
logins: list[Any], # noqa: F811
) -> None:
assert create(server.url, str(uuid.uuid4())).status_code == 200
(entry,) = sessions()
assert get(server, SESSION_ROUTE, entry, OTHER_KEY).status_code == 403
assert ends_after(server, entry, FIRST_CONTACT_LIMIT)
@pytest.mark.parametrize("client_kind", ["polls", "no-id"])
def test_a_client_without_a_channel_keeps_the_ttl(
server: SimpleNamespace, # noqa: F811
logins: list[Any], # noqa: F811
client_kind: str,
) -> None:
if client_kind == "polls":
assert create(server.url, str(uuid.uuid4())).status_code == 200
(entry,) = sessions()
assert get(server, PROMPT_ROUTE, entry).ok
else:
body = {"service": "EXAMPLE", "title_id": "example-1"}
headers = {"X-Secret-Key": KEY}
assert requests.post(server.url + SESSION_CREATE_ROUTE, json=body, headers=headers, timeout=DEADLINE).ok
(entry,) = sessions()
assert logged_in(entry) and stays(server, entry)
entry.idle_since = time.monotonic() - (TTL - 5)
assert sweep(server) == 0
entry.idle_since = time.monotonic() - (TTL + 1)
assert sweep(server) == 1
@pytest.mark.parametrize("busy", [False, True], ids=["idle", "busy"])
@pytest.mark.parametrize("ttl_seconds", [30, 100, 300, 1200, 3600])
async def test_no_session_stays_for_longer_than_its_ttl_lets_it(
monkeypatch: pytest.MonkeyPatch, ttl_seconds: int, busy: bool
) -> None:
"""Work for a client keeps its session past a short TTL, as before, until the client is gone."""
monkeypatch.setitem(config.serve, "session_ttl", ttl_seconds)
store = SessionStore()
entry = await store.create("EXAMPLE", None, input_bridge=InputBridge())
entry.input_bridge.login_status = AuthStatus.AUTHENTICATED # type: ignore[union-attr]
entry.presence.detached(left=False)
if busy:
await entry.lock.acquire()
limit = max(180, ttl_seconds / 2) if busy else min(ttl_seconds, max(180, ttl_seconds / 2))
for silence, count in ((limit - 5, 0), (limit + 1, 1)):
silent_for(entry, silence)
entry.idle_since = entry.presence.seen_at
assert await store.cleanup_expired() == count
def test_each_limit_is_longer_than_the_silence_of_a_client_that_still_works() -> None:
"""The numbers of the client: a ping is lost, the DELETE is late, or the create reply never arrives."""
detection = HEARTBEAT * 1.5
delete_arrives = 5 + CDM_CLOSE_TIMEOUT + 3 * END_TIMEOUT
reconnects = sum((1, 2, 4, 8, 16, 30))
assert 120 + END_TIMEOUT < FIRST_CONTACT_LIMIT <= 150
assert detection + PROBE_TIMEOUT + 100 < AWAY_LIMIT <= 180
assert max(delete_arrives, reconnects) < LEFT_LIMIT <= 90
presence = ClientPresence()
presence.detached(left=False)
for ttl_seconds in range(1, 7200):
assert presence.limit(ttl_seconds) > ttl_seconds / 3 + PROBE_TIMEOUT
def test_a_client_that_is_present_has_no_limit() -> None:
presence = ClientPresence(named=True)
presence.attached()
assert presence.limit(TTL) == math.inf
@pytest.mark.parametrize("left", [True, False])
def test_the_loss_of_the_channel_restarts_the_clock(left: bool) -> None:
presence = ClientPresence()
presence.attached()
presence.seen_at -= 10 * TTL
presence.detached(left)
assert presence.silence < 5 and not presence.gone(TTL)
+4 -1
View File
@@ -24,6 +24,7 @@ from tests.remote.sessions import stub_service_build
from tests.remote.unit.test_tunnel import wait_until
from unshackle.core import remote_channel, remote_service
from unshackle.core.api import handlers, routes, session_store
from unshackle.core.api.client_presence import LEFT_LIMIT
from unshackle.core.api.errors import APIError
from unshackle.core.api.handlers import api_key_authentication
from unshackle.core.api.routes import cors_middleware, no_5xx_middleware, setup_routes
@@ -502,9 +503,11 @@ def test_an_open_channel_keeps_the_session_alive(server: SimpleNamespace, monkey
assert count(server, "GET", SESSION_ROUTE, session_id) == 0
assert count(server, "GET", LOGS_ROUTE) == count(server, "GET", PROMPT_ROUTE) == 0
monkeypatch.setitem(config.serve, "session_ttl", 300)
service.lifetime.close_channel()
assert wait_until(lambda: not entry.channel.attached, 5)
assert wait_until(lambda: entry.idle_seconds > 2 * ttl, 10)
assert on_loop(server, store.cleanup_expired()) == 0
entry.presence.seen_at -= LEFT_LIMIT + 1
assert on_loop(server, store.cleanup_expired()) == 1
assert store.peek(session_id) is None
assert count(server, "GET", SESSION_ROUTE, session_id) == 0
+4 -5
View File
@@ -8,6 +8,8 @@ import threading
from typing import Any
import pytest
from aiohttp import WSMessage
from aiohttp.http_websocket import WS_CLOSED_MESSAGE
from tests.remote.unit.test_tunnel import wait_until
from unshackle.core.api.input_bridge import InputBridge
@@ -31,12 +33,9 @@ class FakeSocket:
self.closed.set()
return True
def __aiter__(self) -> FakeSocket:
return self
async def __anext__(self) -> Any:
async def receive(self) -> WSMessage:
await self.closed.wait()
raise StopAsyncIteration
return WS_CLOSED_MESSAGE
def entry_with_logs(count: int) -> SessionEntry:
+12
View File
@@ -216,6 +216,18 @@ async def test_max_sessions_evicts_the_oldest_session_of_the_key_that_holds_the_
assert set(store._sessions) == {"a-1", "b-2", "b-3"}
async def test_max_sessions_evicts_a_session_with_work_in_progress_last(
store: SessionStore, monkeypatch: pytest.MonkeyPatch
) -> None:
monkeypatch.setattr(type(store), "max_sessions", property(lambda _: 2))
busy = await store.create("EXAMPLE", _FakeService(), session_id="busy")
async with busy.lock:
await asyncio.sleep(0.01)
await store.create("EXAMPLE", _FakeService(), session_id="idle")
await store.create("EXAMPLE", _FakeService(), session_id="new")
assert set(store._sessions) == {"busy", "new"}
async def test_get_expiry_removes_cache_dir(store: SessionStore, monkeypatch: pytest.MonkeyPatch) -> None:
removed: list = []
monkeypatch.setattr(SessionStore, "cleanup_cache_dir", staticmethod(removed.append))
+78
View File
@@ -0,0 +1,78 @@
"""Whether the client of a remote session is still there, from what its channel, its requests and its create show.
The limits of the silence, each of which must be longer than the silence of a client that still works:
- ``FIRST_CONTACT_LIMIT``: a client whose create reply got lost sends the DELETE after its request timeout (120 s).
- ``AWAY_LIMIT``: a client that lost its channel polls at once and then in each third of the TTL. When the first poll
gets no answer, the next one arrives 160 s after the server saw the loss. It reconnects with a backoff of 30 s at most.
- ``LEFT_LIMIT``: the DELETE of a client that closed its channel arrives within 55 s, and its reply has the login cache.
A gateway can also close a working channel with 1000, and 61 s cover six tries to reconnect.
"""
from __future__ import annotations
import math
import time
from enum import Enum, auto
FIRST_CONTACT_LIMIT = 150.0
AWAY_LIMIT = 180.0
LEFT_LIMIT = 90.0
class ClientState(Enum):
"""AWAITED: the client named the id in its create and has sent nothing since. POLLING: it has had no channel."""
AWAITED = auto()
POLLING = auto()
PRESENT = auto()
AWAY = auto()
LEFT = auto()
class ClientPresence:
"""The state of the client of one remote session, and the time since its last sign of life.
Only the event loop calls it. A sign of life is a request of the client for its remote session, or a new channel.
"""
def __init__(self, named: bool = False) -> None:
self.state = ClientState.AWAITED if named else ClientState.POLLING
self.seen_at = time.monotonic()
@property
def silence(self) -> float:
"""Seconds since the last sign of life."""
return time.monotonic() - self.seen_at
def seen(self) -> None:
"""Take a request of the client. One that arrives after the client left shows that it only left its channel."""
self.seen_at = time.monotonic()
if self.state is ClientState.AWAITED:
self.state = ClientState.POLLING
elif self.state is ClientState.LEFT:
self.state = ClientState.AWAY
def attached(self) -> None:
self.state = ClientState.PRESENT
def detached(self, left: bool) -> None:
"""Take the loss of the channel; ``left`` when the client closed it with code 1000."""
self.seen_at = time.monotonic()
self.state = ClientState.LEFT if left else ClientState.AWAY
def limit(self, ttl: float) -> float:
"""Seconds of silence after which the client is gone."""
match self.state:
case ClientState.AWAITED:
return FIRST_CONTACT_LIMIT
case ClientState.AWAY:
return max(AWAY_LIMIT, ttl / 2)
case ClientState.LEFT:
return LEFT_LIMIT
case _:
return math.inf
def gone(self, ttl: float) -> bool:
"""Whether the client has been silent for longer than it may, also while work for it still runs."""
return self.silence > self.limit(ttl)
+17 -19
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_log import SessionLogBuffer, SessionLogMirror, capture_service_logs
from unshackle.core.api.session_store import PendingCreate, SessionEntry, SessionStore, holds
from unshackle.core.api.session_store import PendingCreate, SessionEntry, SessionStore, holds, session_not_found
from unshackle.core.binaries import binary_version
from unshackle.core.cacher import Cacher
from unshackle.core.cdm.choice import choose_cdm, drm_system
@@ -2807,7 +2807,8 @@ async def session_create_handler(data: dict[str, Any], request: web.Request | No
try:
address = request.remote if request else None
pending = PendingCreate(session_id, normalized_service, caller_key(request), address)
named = "session_id" in data
pending = PendingCreate(session_id, normalized_service, caller_key(request), address, named)
async with get_session_store().creating(pending):
return await create_session(data, request, title_id, profile, pending)
except APIError:
@@ -2942,7 +2943,7 @@ async def session_titles_handler(session_id: str, request: web.Request | None =
try:
service_instance = session.service_instance
async with session.lock:
async with session.work():
try:
titles = await asyncio.to_thread(service_instance.get_titles)
finally:
@@ -3069,7 +3070,7 @@ async def session_tracks_handler(
try:
service_instance = session.service_instance
async with session.lock:
async with session.work():
try:
tracks = await asyncio.to_thread(probed_tracks, service_instance, title)
finally:
@@ -3162,7 +3163,7 @@ async def session_segments_handler(
)
tracks[track_id] = track
async with session.lock:
async with session.work():
urls = await asyncio.to_thread(lambda: {track_id: served_url(t) for track_id, t in tracks.items()})
headers, cookies = client_session_auth(session)
@@ -3315,13 +3316,10 @@ async def get_validated_session(session_id: str, request: web.Request | None) ->
store = get_session_store()
session = await store.get(session_id)
if not session:
raise APIError(
APIErrorCode.SESSION_NOT_FOUND,
f"Session not found or expired: {session_id}",
details={"session_id": session_id},
)
raise session_not_found(session_id)
if request is not None and not holds(session, caller_key(request), request.remote):
raise APIError(APIErrorCode.FORBIDDEN, "Session access denied")
session.presence.seen()
return session
@@ -3578,13 +3576,13 @@ async def session_segment_filter_handler(
playlist = m3u8.loads(utf8_text(response), uri=str(track.url))
return [segment.absolute_uri for segment in playlist.segments if segment_filter(segment)]
try:
async with session.lock:
async with session.work():
try:
unwanted = await asyncio.to_thread(unwanted_segments)
except (Exception, SystemExit):
# `from None`: a debug-mode traceback would otherwise carry the service's exception chain
log.exception(f"Error running the segment filter for track {sanitize_log(str(track_id))}")
raise APIError(APIErrorCode.SERVICE_ERROR, "Could not run the segment filter for this track") from None
except (Exception, SystemExit):
# `from None`: a debug-mode traceback would otherwise carry the service's exception chain
log.exception(f"Error running the segment filter for track {sanitize_log(str(track_id))}")
raise APIError(APIErrorCode.SERVICE_ERROR, "Could not run the segment filter for this track") from None
return web.json_response(SegmentFilterReply(unwanted=unwanted))
@@ -3632,7 +3630,7 @@ async def session_samples_handler(
return web.Response(body=cbcs.pack_samples(decrypter(samples)), content_type="application/octet-stream")
try:
async with session.lock:
async with session.work():
return await asyncio.to_thread(run)
except APIError:
raise
@@ -3658,7 +3656,7 @@ async def session_license_handler(
session = await get_validated_session(session_id, request)
require_authenticated(session)
async with session.lock:
async with session.work():
return await asyncio.to_thread(license_response, data, session, session_id, request)
@@ -3881,7 +3879,7 @@ async def session_keys_handler(data: TrackKeys, session_id: str, request: web.Re
return vaults, new
try:
async with session.lock:
async with session.work():
named = await asyncio.to_thread(named_kids)
vaults, new = await asyncio.to_thread(store, named)
if new:
+2 -1
View File
@@ -1987,7 +1987,8 @@ async def session_create(request: web.Request) -> web.Response:
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.
makes the ID. A remote session with this ID ends when its client sends no request and opens no
channel within 150 seconds.
credentials:
type: object
additionalProperties: true
+8 -4
View File
@@ -12,7 +12,7 @@ import asyncio
import json
from typing import TYPE_CHECKING, Any, cast
from aiohttp import WSMsgType, web
from aiohttp import WSCloseCode, WSMsgType, web
from unshackle.core.api.sanitize import sanitize_log
from unshackle.core.remote_protocol import (
@@ -95,14 +95,16 @@ class SessionChannel:
The client first gets what it missed: the log records after *since*, a drain notice, the prompts and CDM
calls the polling routes did not serve, then the login state. A log record can come twice; its ``seq``
tells the client.
tells the client. A close frame comes to the read loop only when the client starts the close; the loop of
a socket that the server closes, or that the network loses, ends with another message.
"""
if self.ended:
await ws.close(code=CHANNEL_SESSION_GONE, message=b"session closed")
return
previous = self.ws
previous, left = self.ws, False
queue: asyncio.Queue[Any] = asyncio.Queue()
self.loop, self.ws, self.queue = asyncio.get_running_loop(), ws, queue
session.presence.attached()
backlog: list[Any] = []
if session.log_buffer is not None:
backlog += [log_message(r) for r in session.log_buffer.since(since)]
@@ -116,13 +118,15 @@ class SessionChannel:
try:
if previous is not None:
await previous.close()
async for msg in ws:
while (msg := await ws.receive()).type not in (WSMsgType.CLOSE, WSMsgType.CLOSING, WSMsgType.CLOSED):
if msg.type == WSMsgType.TEXT and bridge is not None:
receive(msg.data, bridge)
left = msg.type == WSMsgType.CLOSE and msg.data == WSCloseCode.OK
finally:
writer.cancel()
if self.ws is ws:
self.ws = self.queue = None
session.presence.detached(left)
if bridge is not None:
bridge.release_channel_asks()
session.touch()
+31 -9
View File
@@ -21,6 +21,7 @@ from dataclasses import dataclass, field
from datetime import UTC, datetime
from typing import TYPE_CHECKING, Any, NoReturn
from unshackle.core.api.client_presence import ClientPresence
from unshackle.core.api.errors import APIError
from unshackle.core.api.events import bus
from unshackle.core.api.input_bridge import AUTH_INPUT_TIMEOUT, InputBridge
@@ -37,10 +38,19 @@ log = logging.getLogger("api.session")
NO_DEVICE = LicensingMode(Licensor.NO_DEVICE)
LOGIN_WAIT = 5.0
SWEEP_INTERVAL = 5.0
DRAIN_WARNING = "This server restarts for an update after the open downloads finish; this download continues"
def session_not_found(session_id: str) -> APIError:
return APIError(
APIErrorCode.SESSION_NOT_FOUND,
f"Session not found or expired: {session_id}",
details={"session_id": session_id},
)
@dataclass
class SessionEntry:
"""A single authenticated remote session with a service."""
@@ -68,6 +78,7 @@ class SessionEntry:
input_bridge: InputBridge | None = None
log_buffer: Any | None = None # SessionLogBuffer mirroring the service's self.log
channel: SessionChannel = field(default_factory=SessionChannel, repr=False, compare=False)
presence: ClientPresence = field(default_factory=ClientPresence, repr=False, compare=False)
auth_error: str | None = None
client: dict[str, Any] = field(default_factory=dict) # version/argv/platform the client reported
actions: deque[dict[str, Any]] = field(default_factory=lambda: deque(maxlen=500))
@@ -92,6 +103,14 @@ class SessionEntry:
self.tracks.update(title_tracks)
self.tracks_by_title[title_id] = title_tracks
@contextlib.asynccontextmanager
async def work(self) -> AsyncIterator[None]:
"""Hold the lock for service work. A request that waited for it until the remote session ended is refused."""
async with self.lock:
if self.channel.ended:
raise session_not_found(self.session_id)
yield
def touch(self) -> None:
"""Update last_accessed timestamp and restart the idle time."""
self.last_accessed = datetime.now(UTC)
@@ -105,8 +124,8 @@ class SessionEntry:
def in_use(self) -> bool:
"""True while a request holds the lock for service work, or the client holds its remote session channel open.
The store does not expire such a remote session. A request can run for longer than the TTL, and expiry
would remove the cache directory that the worker thread still writes to.
Idle time does not expire such a remote session: a request can run for longer than the TTL, and the worker
thread still writes to the cache directory. Only a client that is gone ends it.
"""
return self.lock.locked() or self.channel.attached
@@ -166,6 +185,7 @@ class PendingCreate:
service_tag: str
owner_key: str = field(repr=False)
creator_ip: str | None
named: bool = False
ended: bool = False
def require_live(self) -> None:
@@ -318,6 +338,7 @@ class SessionStore:
client=client or {},
input_bridge=input_bridge,
log_buffer=log_buffer,
presence=ClientPresence(named=pending is not None and pending.named),
)
self._sessions[session_id] = entry
_publish("create", entry)
@@ -335,9 +356,7 @@ class SessionStore:
if not self._expired(entry):
entry.touch()
return entry
elapsed = entry.idle_seconds
limit = self._idle_limit(entry)
log.info(f"Session {sanitize_log(session_id)} expired (elapsed={elapsed:.0f}s, ttl={limit:.0f}s)")
log.info(f"Session {sanitize_log(session_id)} expired (elapsed={entry.idle_seconds:.0f}s)")
cache_tag = self._retire(entry, "expired")
await self.remove_cache_dirs([cache_tag])
return None
@@ -376,7 +395,9 @@ class SessionStore:
return max(self.ttl, AUTH_INPUT_TIMEOUT) if entry.auth_status == AuthStatus.AUTHENTICATING else self.ttl
def _expired(self, entry: SessionEntry) -> bool:
"""The one expiry rule: no request holds the remote session and it is idle past its limit."""
"""The one expiry rule: the client is gone, or no request holds the remote session and it is idle too long."""
if entry.presence.gone(self.ttl):
return True
return not entry.in_use and entry.idle_seconds > self._idle_limit(entry)
def _retire(self, entry: SessionEntry, reason: str | None) -> str | None:
@@ -404,7 +425,7 @@ class SessionStore:
async def loop() -> None:
while True:
await asyncio.sleep(60)
await asyncio.sleep(SWEEP_INTERVAL)
try:
await self.cleanup_expired()
except Exception:
@@ -462,8 +483,9 @@ class SessionStore:
@staticmethod
def publish_update(entry: SessionEntry) -> None:
"""Tell dashboard listeners that a session's summary changed (titles or tracks loaded, auth settled)."""
_publish("update", entry)
"""Tell dashboard listeners that the summary of an open remote session changed (titles or tracks loaded)."""
if not entry.channel.ended:
_publish("update", entry)
def record_action(self, session_id: str, action: dict[str, Any]) -> None:
"""Append one request to the session's action log and tell dashboard listeners."""
+1 -1
View File
@@ -1157,12 +1157,12 @@ class RemoteService(TitleSource):
from unshackle.core.remote_channel import open_channel
channel = self.lifetime.channel = open_channel(self)
channel.keep_alive()
if result.get("status", AuthStatus.AUTHENTICATED) == AuthStatus.AUTHENTICATING:
channel.wait_auth()
if create_data.get("cdm_relay"):
self.client.in_flight = channel.in_flight
self.drain_server_logs()
channel.keep_alive()
@property
def local_cdm(self) -> Any: