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
+4 -3
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()})")
client = remote_client(server)
tunnel = start_tunnel(client, proxy)
log.info(f"Step 2: opened a tunnel to {safe_display_url(client.server_url)}")
try:
tunnel = start_tunnel(client, proxy)
log.info(f"Step 2: opened a tunnel to {safe_display_url(client.server_url)}")
remote = client.get(f"{CHECK_ROUTE}?id={tunnel.id}")
finally:
tunnel.stop()
if client.tunnel:
client.tunnel.stop()
country = str(remote.get("country", "?")).upper()
# one exit can answer over IPv4 here and IPv6 there, so a matching country also passes
+3 -2
View File
@@ -906,11 +906,12 @@ async def shutdown_download_manager(_app: object) -> None:
def busy_services() -> set[str]:
"""Tags a hot reload must not swap: those with an unfinished job and those a live remote session uses."""
"""Tags a hot reload must not swap: those with an unfinished job and those a remote session or its create uses."""
from unshackle.core.api.session_store import get_session_store
from unshackle.core.api.stats import stats
busy = {entry.service_tag for entry in get_session_store().list()}
store = get_session_store()
busy = {entry.service_tag for entry in store.list()} | store.pending_services
if stats.mode != "remote_only":
busy |= get_download_manager().busy_services()
return busy
+135 -109
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 SessionEntry, SessionStore
from unshackle.core.api.session_store import PendingCreate, SessionEntry, SessionStore, holds
from unshackle.core.binaries import binary_version
from unshackle.core.cacher import Cacher
from unshackle.core.cdm.choice import choose_cdm, drm_system
@@ -2766,6 +2766,17 @@ def client_device_cdm(
)
def new_session_id(data: dict[str, Any]) -> str:
"""The id of the remote session to make: the one its client named, as a canonical UUID version 4, else a new one."""
if "session_id" not in data:
return str(uuid.uuid4())
named = data["session_id"]
with suppress(ValueError):
if isinstance(named, str) and str(uuid.UUID(named, version=4)) == named:
return named
raise APIError(APIErrorCode.INVALID_INPUT, "session_id must be the canonical text of a version 4 UUID")
async def session_create_handler(data: dict[str, Any], request: web.Request | None = None) -> web.Response:
"""Answer the remote session creation: authenticate + get titles + get tracks + get chapters.
@@ -2776,6 +2787,7 @@ async def session_create_handler(data: dict[str, Any], request: web.Request | No
from unshackle.core.api.session_store import get_session_store, refuse_while_draining
refuse_while_draining()
session_id = new_session_id(data)
service_tag = data.get("service")
title_id = data.get("title_id")
profile = client_profile(data)
@@ -2794,99 +2806,10 @@ async def session_create_handler(data: dict[str, Any], request: web.Request | No
)
try:
proxy_param, proxy_providers = await asyncio.to_thread(resolve_handler_proxy, data, normalized_service, request)
import uuid as uuid_mod
session_id = str(uuid_mod.uuid4())
api_key = caller_key(request)
policy = request_policy(request)
session_cache_dir = f"_sessions/{api_key_namespace(request)}/{session_id}/{normalized_service}"
server_account = server_account_for(policy, normalized_service)
if server_account:
region = data.get("proxy_region") or data.get("client_region")
if region is not None and not (isinstance(region, str) and re.fullmatch(r"[A-Za-z]{2}", region)):
raise APIError(APIErrorCode.INVALID_INPUT, "proxy_region must be a two-letter country code.")
if region is None and data.get("no_proxy"):
region = await asyncio.to_thread(server_region)
profile = next_server_profile(normalized_service, region)
log.info(f"Using server account '{sanitize_log(profile or 'default')}' for {normalized_service}")
licensing = session_licensing(policy, normalized_service, data)
bridge = InputBridge()
log_buffer = None if server_account else SessionLogBuffer()
service_class_name = getattr(Services.load(normalized_service), "__name__", normalized_service)
purpose = SessionLaunch(
(proxy_param, proxy_providers), policy, server_account, licensing, bridge, session_cache_dir
)
def build_service() -> Launched:
with capture_service_logs(service_class_name, log_buffer):
return launch_served(purpose, data, normalized_service, title_id, profile, request)
service_instance, cookies, credential, launched_licensing = await asyncio.to_thread(build_service)
licensing = launched_licensing or licensing
if log_buffer:
service_instance.log = SessionLogMirror(service_instance.log, log_buffer)
session_cache_tag = None if server_account else session_cache_dir
cache_data = data.get("cache", {})
client = data.get("client")
store = get_session_store()
try:
if cache_data and session_cache_tag:
await asyncio.to_thread(write_client_cache, cache_data, session_cache_tag)
session = await store.create(
normalized_service,
service_instance,
session_id=session_id,
owner_key=api_key,
creator_ip=request.remote if request else None,
server_account=(profile or "default") if server_account else None,
cache_tag=session_cache_tag,
policy=policy,
licensing=licensing,
client_auth=not server_account
and (cookies is not None or credential is not None or bool(cache_data and session_cache_tag)),
# Echoed to every dashboard viewer, so cap what an arbitrary client can push into it.
client=client if isinstance(client, dict) and len(json.dumps(client, default=str)) <= 4096 else {},
input_bridge=bridge,
log_buffer=log_buffer,
)
except BaseException:
if store.peek(session_id) is None:
SessionStore.cleanup_cache_dir(session_cache_tag)
raise
async def run_auth() -> None:
try:
await asyncio.to_thread(service_instance.authenticate, cookies, credential)
if not server_account:
session.client_auth = True
bridge.login_status = AuthStatus.AUTHENTICATED
except (Exception, SystemExit) as e:
log.exception("Auth failed for session %s", session_id)
session.auth_error = redact_secrets(str(e))
bridge.login_status = AuthStatus.FAILED
finally:
session.channel.send(status_message(session))
if store.peek(session_id) is not session:
SessionStore.cleanup_cache_dir(session_cache_tag)
store.track_login(asyncio.create_task(run_auth()))
return web.json_response(
SessionCreated(
session_id=session.session_id,
service=normalized_service,
status=AuthStatus.AUTHENTICATING,
server_account=server_account,
**licensing.created_fields(),
)
)
address = request.remote if request else None
pending = PendingCreate(session_id, normalized_service, caller_key(request), address)
async with get_session_store().creating(pending):
return await create_session(data, request, title_id, profile, pending)
except APIError:
raise
except (Exception, SystemExit) as e:
@@ -2899,6 +2822,114 @@ async def session_create_handler(data: dict[str, Any], request: web.Request | No
)
async def create_session(
data: dict[str, Any],
request: web.Request | None,
title_id: str,
profile: str | None,
pending: PendingCreate,
) -> web.Response:
"""Build the service of a remote session, store the session and start its login, unless its client ends it first.
The cache directory has a name of its own, as the create that replaces this one has the same session id.
"""
from unshackle.core.api.session_store import get_session_store
normalized_service = pending.service_tag
proxy_param, proxy_providers = await asyncio.to_thread(resolve_handler_proxy, data, normalized_service, request)
policy = request_policy(request)
session_id = pending.session_id
session_cache_dir = f"_sessions/{api_key_namespace(request)}/{uuid.uuid4()}/{normalized_service}"
server_account = server_account_for(policy, normalized_service)
session_cache_tag = None if server_account else session_cache_dir
if server_account:
region = data.get("proxy_region") or data.get("client_region")
if region is not None and not (isinstance(region, str) and re.fullmatch(r"[A-Za-z]{2}", region)):
raise APIError(APIErrorCode.INVALID_INPUT, "proxy_region must be a two-letter country code.")
if region is None and data.get("no_proxy"):
region = await asyncio.to_thread(server_region)
profile = next_server_profile(normalized_service, region)
log.info(f"Using server account '{sanitize_log(profile or 'default')}' for {normalized_service}")
licensing = session_licensing(policy, normalized_service, data)
bridge = InputBridge()
log_buffer = None if server_account else SessionLogBuffer()
service_class_name = getattr(Services.load(normalized_service), "__name__", normalized_service)
purpose = SessionLaunch(
(proxy_param, proxy_providers), policy, server_account, licensing, bridge, session_cache_dir
)
def build_service() -> Launched:
with capture_service_logs(service_class_name, log_buffer):
return launch_served(purpose, data, normalized_service, title_id, profile, request)
cache_data = data.get("cache", {})
client = data.get("client")
store = get_session_store()
try:
pending.require_live()
service_instance, cookies, credential, launched_licensing = await asyncio.to_thread(build_service)
licensing = launched_licensing or licensing
if log_buffer:
service_instance.log = SessionLogMirror(service_instance.log, log_buffer)
if cache_data and session_cache_tag:
await asyncio.to_thread(write_client_cache, cache_data, session_cache_tag)
session = await store.create(
normalized_service,
service_instance,
owner_key=pending.owner_key,
creator_ip=pending.creator_ip,
server_account=(profile or "default") if server_account else None,
cache_tag=session_cache_tag,
policy=policy,
licensing=licensing,
client_auth=not server_account
and (cookies is not None or credential is not None or bool(cache_data and session_cache_tag)),
# Echoed to every dashboard viewer, so cap what an arbitrary client can push into it.
client=client if isinstance(client, dict) and len(json.dumps(client, default=str)) <= 4096 else {},
input_bridge=bridge,
log_buffer=log_buffer,
pending=pending,
)
if store.peek(session_id) is not session:
pending.refuse()
except BaseException:
entry = store.peek(session_id)
if entry is None or entry.cache_tag != session_cache_tag:
await SessionStore.remove_cache_dirs([session_cache_tag])
raise
async def run_auth() -> None:
try:
await asyncio.to_thread(service_instance.authenticate, cookies, credential)
if not server_account:
session.client_auth = True
bridge.login_status = AuthStatus.AUTHENTICATED
except (Exception, SystemExit) as e:
log.exception("Auth failed for session %s", session_id)
session.auth_error = redact_secrets(str(e))
bridge.login_status = AuthStatus.FAILED
finally:
session.channel.send(status_message(session))
if store.peek(session_id) is not session:
SessionStore.cleanup_cache_dir(session_cache_tag)
store.track_login(asyncio.create_task(run_auth()))
return web.json_response(
SessionCreated(
session_id=session.session_id,
service=normalized_service,
status=AuthStatus.AUTHENTICATING,
server_account=server_account,
**licensing.created_fields(),
)
)
async def session_titles_handler(session_id: str, request: web.Request | None = None) -> web.Response:
"""Get titles for the authenticated remote session.
@@ -3279,8 +3310,6 @@ async def get_validated_session(session_id: str, request: web.Request | None) ->
behind a reverse proxy every caller shares the proxy's address, so the IP check
(kept as defence in depth) cannot distinguish users on its own.
"""
import hmac
from unshackle.core.api.session_store import get_session_store
store = get_session_store()
@@ -3291,17 +3320,8 @@ async def get_validated_session(session_id: str, request: web.Request | None) ->
f"Session not found or expired: {session_id}",
details={"session_id": session_id},
)
if session.owner_key is not None and request is not None:
if not hmac.compare_digest(caller_key(request), session.owner_key):
raise APIError(
APIErrorCode.FORBIDDEN,
"Session access denied",
)
if session.creator_ip and request and request.remote != session.creator_ip:
raise APIError(
APIErrorCode.FORBIDDEN,
"Session access denied",
)
if request is not None and not holds(session, caller_key(request), request.remote):
raise APIError(APIErrorCode.FORBIDDEN, "Session access denied")
return session
@@ -3891,11 +3911,17 @@ async def session_info_handler(session_id: str, request: web.Request | None = No
async def session_delete_handler(session_id: str, request: web.Request | None = None) -> web.Response:
"""Delete a remote session, return updated cache files, and clean up server-side data."""
"""Delete a remote session, return updated cache files, and clean up server-side data.
A create that the same API key still has in progress under the id ends with no remote session and no cache to return.
"""
from unshackle.core.api.session_store import get_session_store
session = await get_validated_session(session_id, request)
store = get_session_store()
ended = store.end_pending(session_id, caller_key(request), request.remote if request else None)
if ended and store.peek(session_id) is None:
return web.json_response(SessionClosed(status="ok"))
session = await get_validated_session(session_id, request)
session.end()
cache_tag = session.cache_tag
+14 -2
View File
@@ -1980,6 +1980,14 @@ async def session_create(request: web.Request) -> web.Response:
type: string
title_id:
type: string
session_id:
type: string
description: |
The ID that the client gives the remote session, so that it can delete the session before
this request answers. The canonical text of a version 4 UUID; the server answers any other value with
INVALID_INPUT. A create of the same API key and IP with the same ID replaces the remote session of
that ID. The server answers the ID of another API key or IP with FORBIDDEN. Without it the server
makes the ID.
credentials:
type: object
additionalProperties: true
@@ -2127,7 +2135,9 @@ async def session_create(request: web.Request) -> web.Response:
'403':
description: |
SERVER_CDM_CAPPED when `quality` asks for more than the server CDM limit and the client
reported no local CDM
reported no local CDM; FORBIDDEN when another API key or IP has the `session_id`
'404':
description: SESSION_NOT_FOUND when a DELETE or a newer create ended the `session_id` first
'401':
description: Authentication failed
"""
@@ -2575,7 +2585,9 @@ async def session_delete(request: web.Request) -> web.Response:
Delete a remote session.
---
summary: Delete remote session
description: Clean up a remote session
description: >-
Clean up a remote session. A session that the same API key is still creating ends too, and its create request
then answers SESSION_NOT_FOUND.
parameters:
- name: session_id
in: path
+87 -10
View File
@@ -11,19 +11,22 @@ from __future__ import annotations
import asyncio
import builtins
import contextlib
import hmac
import logging
import uuid
from collections import Counter, deque
from collections.abc import AsyncIterator
from dataclasses import dataclass, field
from datetime import UTC, datetime
from typing import TYPE_CHECKING, Any
from typing import TYPE_CHECKING, Any, NoReturn
from unshackle.core.api.errors import APIError
from unshackle.core.api.events import bus
from unshackle.core.api.input_bridge import AUTH_INPUT_TIMEOUT, InputBridge
from unshackle.core.api.sanitize import sanitize_log
from unshackle.core.api.session_channel import SessionChannel, drain_message
from unshackle.core.config import config
from unshackle.core.remote_protocol import AuthStatus, LicensingMode, Licensor
from unshackle.core.remote_protocol import APIErrorCode, AuthStatus, LicensingMode, Licensor
from unshackle.core.tracks import Track, Tracks
if TYPE_CHECKING:
@@ -141,6 +144,36 @@ class SessionEntry:
}
def holds(held: SessionEntry | PendingCreate, owner_key: str, creator_ip: str | None) -> bool:
"""Whether a remote session or its create belongs to this API key and, when it knows one, this address."""
if held.creator_ip and held.creator_ip != creator_ip:
return False
return held.owner_key is None or hmac.compare_digest(held.owner_key.encode(), owner_key.encode())
@dataclass(eq=False)
class PendingCreate:
"""A remote session creation that its handler still works on, under the id that the session will have."""
session_id: str
service_tag: str
owner_key: str = field(repr=False)
creator_ip: str | None
ended: bool = False
def require_live(self) -> None:
"""Raise when a DELETE or a newer create of the same id ended it."""
if self.ended:
self.refuse()
def refuse(self) -> NoReturn:
raise APIError(
APIErrorCode.SESSION_NOT_FOUND,
f"The client ended the remote session during its creation: {self.session_id}",
details={"session_id": self.session_id},
)
def _schedule_pending_reload(service_tag: str) -> None:
"""Apply staged service reloads now that a remote session ended; the task runs after the store lock releases."""
from unshackle.core.api.download_manager import schedule_pending_reload
@@ -165,6 +198,7 @@ class SessionStore:
def __init__(self) -> None:
self._sessions: dict[str, SessionEntry] = {}
self._pending: dict[str, PendingCreate] = {}
self._lock = asyncio.Lock()
self._cleanup_task: asyncio.Task | None = None
self._logins: set[asyncio.Task[None]] = set()
@@ -185,6 +219,43 @@ class SessionStore:
limit = config.serve.get("max_sessions", 100)
return limit if isinstance(limit, int) and limit > 0 else None
@contextlib.asynccontextmanager
async def creating(self, pending: PendingCreate) -> AsyncIterator[None]:
"""Hold a remote session id for one client while its create handler works, so that a DELETE can end the create.
This ends an earlier create of the same client under the id, and refuses the id of another API key or address.
"""
session_id = pending.session_id
async with self._lock:
earlier = self._pending.get(session_id)
for held in (earlier, self._sessions.get(session_id)):
if held is not None and not holds(held, pending.owner_key, pending.creator_ip):
raise APIError(APIErrorCode.FORBIDDEN, "Session access denied")
if earlier is not None:
earlier.require_live()
earlier.ended = True
self._pending[session_id] = pending
try:
yield
finally:
if self._pending.get(session_id) is pending:
del self._pending[session_id]
_schedule_pending_reload(pending.service_tag)
@property
def pending_services(self) -> set[str]:
"""The tags whose service a create handler builds now."""
return {pending.service_tag for pending in self._pending.values()}
def end_pending(self, session_id: str, owner_key: str, creator_ip: str | None) -> bool:
"""End the create that this client has in progress under the id. False when it has none."""
pending = self._pending.get(session_id)
if pending is None or not holds(pending, owner_key, creator_ip):
return False
pending.ended = True
log.info(f"Ended the creation of session {sanitize_log(session_id)}")
return True
async def create(
self,
service_tag: str,
@@ -201,10 +272,19 @@ class SessionStore:
client: dict[str, Any] | None = None,
input_bridge: InputBridge | None = None,
log_buffer: Any | None = None,
pending: PendingCreate | None = None,
) -> SessionEntry:
"""Make a new remote session, complete with every field the dashboard shows, and announce it."""
evicted_tag: str | None = None
"""Make a new remote session, complete with every field the dashboard shows, and announce it.
It replaces the remote session that the client has under the id of ``pending``, and raises when that has ended.
"""
ended_tags: list[str | None] = []
async with self._lock:
if pending is not None:
pending.require_live()
session_id = pending.session_id
if replaced := self._sessions.get(session_id):
ended_tags.append(self._retire(replaced, "closed"))
max_sessions = self.max_sessions
if max_sessions is not None and len(self._sessions) >= max_sessions:
sessions = self._sessions
@@ -214,7 +294,7 @@ class SessionStore:
key=lambda k: (sessions[k].in_use, -held[sessions[k].owner_key], sessions[k].last_accessed),
)
log.warning(f"Max sessions reached ({max_sessions}), evicting oldest of the busiest key: {oldest_id}")
evicted_tag = self._retire(sessions[oldest_id], "evicted")
ended_tags.append(self._retire(sessions[oldest_id], "evicted"))
session_id = session_id or str(uuid.uuid4())
entry = SessionEntry(
@@ -235,7 +315,7 @@ class SessionStore:
self._sessions[session_id] = entry
_publish("create", entry)
log.info(f"Created session {sanitize_log(session_id)} for service {sanitize_log(service_tag)}")
await self.remove_cache_dirs([evicted_tag])
await self.remove_cache_dirs(ended_tags)
return entry
async def get(self, session_id: str) -> SessionEntry | None:
@@ -332,7 +412,7 @@ class SessionStore:
"""End every remote session at server shutdown, wait LOGIN_WAIT seconds for the running logins, stop the sweep.
A login thread can still write the remote session cache after its bridge ends. The store has forgotten
the session by then, so the login task of session_create_handler removes that cache directory again.
the session by then, so the login task of create_session removes that cache directory again.
"""
async with self._lock:
cache_tags = [self._retire(entry, None) for entry in list(self._sessions.values())]
@@ -421,9 +501,6 @@ session_store: SessionStore | None = None
def refuse_while_draining() -> None:
"""Raise SERVER_DRAINING for a new session or job once the operator has started a drain."""
from unshackle.core.api.errors import APIError
from unshackle.core.remote_protocol import APIErrorCode
if get_session_store().draining:
raise APIError(
APIErrorCode.SERVER_DRAINING,
+18 -6
View File
@@ -57,6 +57,7 @@ CONNECT_TIMEOUT = 10.0
RECONNECT_DELAY = 1.0
GONE_STATUSES = (401, 403, 404) # the API key or the remote session is gone, so a reconnect cannot help
SEND_TIMEOUT = 10.0
CDM_CLOSE_TIMEOUT = 5.0
KEPT_ANSWERS = 64
LEVELS = logging.getLevelNamesMapping()
@@ -78,7 +79,7 @@ class ServerMessages:
self.cdm_sessions: dict[str, bytes] = {}
def route(self, route: str) -> str:
return route.format(session_id=self.service._session_id)
return route.format(session_id=self.service.lifetime.require_session())
def show_logs(self, records: list[LogRecord]) -> None:
"""Log the service's server-side records here, each once: a record that the other path brought is skipped."""
@@ -133,13 +134,17 @@ class ServerMessages:
show_notice(notice, self.service.auth_qr)
def close_cdm_sessions(self) -> None:
"""Close the local CDM sessions that the server's calls opened; best effort."""
"""Close the local CDM sessions that the server's calls opened; best effort, without a long wait on a running call."""
cdm = self.service.local_cdm
with self.cdm_lock:
if not self.cdm_lock.acquire(timeout=CDM_CLOSE_TIMEOUT):
return
try:
for session_id in self.cdm_sessions.values():
with contextlib.suppress(Exception):
cdm.close(session_id)
self.cdm_sessions.clear()
finally:
self.cdm_lock.release()
def login_done(self) -> None:
self.close_cdm_sessions()
@@ -230,6 +235,8 @@ class PollingChannel:
def runs_service_code(self, endpoint: str) -> bool:
"""Whether a request to *endpoint* runs service code on the server, which can make CDM calls."""
if self.service._session_id is None:
return False
own = {self.messages.route(route) for route in (PROMPT_ROUTE, LOGS_ROUTE, SAMPLES_ROUTE)}
return endpoint.startswith(self.messages.route(SESSION_ROUTE) + "/") and endpoint.partition("?")[0] not in own
@@ -326,6 +333,7 @@ class WebSocketChannel:
self.ws: aiohttp.ClientWebSocketResponse | None = None
self.loop: asyncio.AbstractEventLoop | None = None
self.task: asyncio.Task[None] | None = None
self.stopped = False
self.thread = Thread(target=run_loop, args=(self.run,), name=f"{self.service.service_tag}-channel", daemon=True)
def open(self, timeout: float = CONNECT_TIMEOUT) -> bool:
@@ -340,8 +348,10 @@ class WebSocketChannel:
async def run(self) -> None:
self.loop, self.task = asyncio.get_running_loop(), asyncio.current_task()
try:
await self.connect()
except asyncio.CancelledError:
if not self.stopped:
with quiet():
await self.connect()
except (asyncio.CancelledError, RemoteError):
pass
finally:
self.attempted.set()
@@ -483,6 +493,7 @@ class WebSocketChannel:
return self.draining_now if self.connected.is_set() else self.fallback.draining()
def close(self) -> None:
self.stopped = True
if self.loop and self.task and self.thread.is_alive():
with contextlib.suppress(RuntimeError): # the loop closes before its thread ends
self.loop.call_soon_threadsafe(self.task.cancel)
@@ -500,8 +511,9 @@ def open_channel(service: RemoteService) -> Channel:
fallback = PollingChannel(messages)
if service.client.no_channel:
return fallback
channel = WebSocketChannel(messages, fallback)
channel = service.lifetime.channel = WebSocketChannel(messages, fallback)
if channel.open():
return channel
service.lifetime.require_open()
service.client.no_channel = True
return fallback
+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
title_id: str
session_id: str
profile: str
service_params: dict[str, Any]
season: Any
+58 -68
View File
@@ -7,7 +7,6 @@ Everything else (track selection, download, decrypt, mux) runs locally.
from __future__ import annotations
import atexit
import base64
import contextlib
import hashlib
@@ -78,7 +77,6 @@ from unshackle.core.remote_protocol import (
SegmentFilterReply,
SegmentFilterRequest,
SegmentsRequest,
SessionClosed,
SessionCreate,
SessionCreated,
TitlesReply,
@@ -106,6 +104,7 @@ from unshackle.core.wire import apply_tracks_reply, build_chapters, build_music,
if TYPE_CHECKING:
from unshackle.core.remote_channel import Channel
from unshackle.core.remote_lifetime import RemoteSessionLifetime
log = logging.getLogger("remote_service")
@@ -135,7 +134,7 @@ class _Mute(local):
"""This thread's RemoteError log state: inside ``session_call`` (``recovering``) and under ``quiet()``."""
recovering = False
quiet = False
quiet: Callable[[], bool] = staticmethod(lambda: False)
_mute = _Mute()
@@ -163,10 +162,10 @@ def malformed_answer(what: str) -> Iterator[None]:
@contextlib.contextmanager
def quiet() -> Iterator[None]:
"""Log this thread's RemoteErrors at debug level, because the caller reports them."""
def quiet(when: Callable[[], bool] = lambda: True) -> Iterator[None]:
"""Log this thread's RemoteErrors at debug level, because the caller reports them; only while ``when`` is true."""
before = _mute.quiet
_mute.quiet = True
_mute.quiet = lambda: before() or when()
try:
yield
finally:
@@ -210,7 +209,7 @@ class RemoteError(SystemExit):
super().__init__(1)
self.message = sanitize_log(message)
self.kind = kind
muted = _mute.quiet or (_mute.recovering and kind in RECOVERABLE)
muted = _mute.quiet() or (_mute.recovering and kind in RECOVERABLE)
(log.debug if muted else log.error)(self.message)
def __str__(self) -> str:
@@ -411,9 +410,6 @@ class RemoteClient:
"""GET an endpoint that an older server may not have. Empty dict when the route is missing."""
return self.request("get", endpoint, optional=True)
def delete(self, endpoint: str) -> dict[str, Any]:
return self.request("delete", endpoint)
def sample_batches(samples: list[bytes]) -> Iterator[list[bytes]]:
"""Split samples into consecutive batches of at most cbcs.SAMPLE_BATCH_BYTES (a larger sample goes alone)."""
@@ -672,7 +668,7 @@ def start_tunnel(client: RemoteClient, proxy: str | None = None) -> TunnelClient
slot_deadline = time.monotonic() + RETRY_AFTER_MAX
rate_waits = 0
while True:
tunnel = TunnelClient(client.server_url, headers, proxy)
tunnel = client.tunnel = TunnelClient(client.server_url, headers, proxy)
try:
tunnel.start()
break
@@ -684,7 +680,6 @@ def start_tunnel(client: RemoteClient, proxy: str | None = None) -> TunnelClient
wait_retry_after(TUNNEL_SLOT_POLL, "Every tunnel of this API key is in use")
else:
raise click.ClickException(f"--local-proxy could not open a tunnel to the server: {e}") from None
client.tunnel = tunnel
return tunnel
@@ -810,7 +805,7 @@ class RemoteService(TitleSource):
"""
server_cdm_type: str = "widevine"
channel: Channel | None = None
lifetime: RemoteSessionLifetime
licensing: LicensingMode | None = None
"""The server's answer to who licenses this remote session; an older server gives it in the tracks reply."""
_server_cdm_request: bool | None = None
@@ -826,6 +821,8 @@ class RemoteService(TitleSource):
services_config: dict,
service_params: dict[str, Any] | None = None,
) -> None:
from unshackle.core.remote_lifetime import RemoteSessionLifetime
self.__class__.__name__ = service_tag
console.print(Padding(Rule(f"[rule.text]Service: {service_tag} (Remote)"), (1, 2)))
@@ -840,7 +837,7 @@ class RemoteService(TitleSource):
self._titles: Titles_T | None = None
self._tracks_by_title: dict[str, Tracks] = {}
self._chapters_by_title: dict[str, list] = {}
self._session_id: str | None = None
self.lifetime = RemoteSessionLifetime(self.client, self.save_session_cache)
self.client_licensed: set[str] = set() # track ids this machine's device licenses by challenge relay
self.deferred_refusals: dict[str, str] = {}
self.server_vault_keys: dict[UUID, str] = {}
@@ -917,6 +914,14 @@ class RemoteService(TitleSource):
def title(self) -> str:
return self.title_id
@property
def _session_id(self) -> str | None:
return self.lifetime.session_id
@property
def channel(self) -> Channel | None:
return self.lifetime.channel
def search(self) -> Iterator[SearchResult]:
"""Search on the server, which logs in to the service itself with the login material sent here."""
params = self.ctx.parent.params if self.ctx.parent else {}
@@ -926,15 +931,15 @@ class RemoteService(TitleSource):
data["profile"] = profile
if not self._anonymous_search:
data.update(self.client_login(profile))
if params.get("no_proxy"):
data["no_proxy"] = True
elif params.get("local_proxy"):
data["proxy"] = self.tunnel()
elif params.get("proxy"):
providers = getattr(self.ctx.obj, "proxy_providers", None)
data["proxy"] = resolve_remote_proxy_arg(server_proxy_arg(params), providers)
self.require_reachable_proxy(data["proxy"])
try:
if params.get("no_proxy"):
data["no_proxy"] = True
elif params.get("local_proxy"):
data["proxy"] = self.tunnel()
elif params.get("proxy"):
providers = getattr(self.ctx.obj, "proxy_providers", None)
data["proxy"] = resolve_remote_proxy_arg(server_proxy_arg(params), providers)
self.require_reachable_proxy(data["proxy"])
response = self.client.post(SEARCH_ROUTE, data)
finally:
if self.client.tunnel: # a search is one request, so its tunnel ends with it
@@ -983,6 +988,11 @@ class RemoteService(TitleSource):
return f"tunnel:{tunnel.id}"
def authenticate(self, cookies: CookieJar | None = None, credential: Credential | None = None) -> None:
with self.lifetime.opening():
self.open_session(credential)
def open_session(self, credential: Credential | None) -> None:
"""Make the remote session and wait for its login; what it opens belongs to ``lifetime``."""
self.credential = credential
profile = self.ctx.parent.params.get("profile") if self.ctx.parent else None
proxy = self.ctx.parent.params.get("proxy") if self.ctx.parent else None
@@ -1121,16 +1131,11 @@ class RemoteService(TitleSource):
"argv": argv,
}
try:
result = cast(SessionCreated, self.client.post(SESSION_CREATE_ROUTE, create_data))
if not isinstance(result.get("session_id"), str):
raise RemoteError("The remote server sent malformed session: no session_id", ClientErrorKind.UNKNOWN)
except BaseException:
if local and self.client.tunnel: # no session, so close() never runs: free the tunnel now
self.client.tunnel.stop()
raise
self._session_id = result["session_id"]
atexit.register(self.close)
create_data["session_id"] = self.lifetime.name()
result = cast(SessionCreated, self.client.post(SESSION_CREATE_ROUTE, create_data))
if not isinstance(result.get("session_id"), str):
raise RemoteError("The remote server sent malformed session: no session_id", ClientErrorKind.UNKNOWN)
self.lifetime.adopt(create_data["session_id"], result["session_id"])
# an older server omits the field, and the tracks response settles it
if "server_cdm" in result:
answer = LicensingMode.from_created(result)
@@ -1151,13 +1156,13 @@ class RemoteService(TitleSource):
from unshackle.core.remote_channel import open_channel
self.channel = open_channel(self)
channel = self.lifetime.channel = open_channel(self)
if result.get("status", AuthStatus.AUTHENTICATED) == AuthStatus.AUTHENTICATING:
self.channel.wait_auth()
channel.wait_auth()
if create_data.get("cdm_relay"):
self.client.in_flight = self.channel.in_flight
self.client.in_flight = channel.in_flight
self.drain_server_logs()
self.channel.keep_alive()
channel.keep_alive()
@property
def local_cdm(self) -> Any:
@@ -1223,7 +1228,7 @@ class RemoteService(TitleSource):
raise
lost = e
if not self.recover(session_id, lost.kind):
if not _mute.quiet:
if not _mute.quiet():
log.error(lost.message)
raise lost
return call(self._session_id)
@@ -1245,14 +1250,18 @@ class RemoteService(TitleSource):
if alive:
return kind == ClientErrorKind.CONNECT
self.log.warning("The remote session was lost, opening a new one")
self.lifetime.release(gone=kind == APIErrorCode.SESSION_NOT_FOUND)
return self.reopen()
def wait_for_server(self, accepting: bool) -> bool:
"""Wait until the server answers, and with ``accepting`` until it also takes new sessions. False on timeout."""
"""Wait until the server answers, and with ``accepting`` until it also takes new sessions.
False on timeout, and when the owner of the remote session has ended.
"""
deadline = time.monotonic() + REOPEN_WAIT
delay = 1.0
warned = False
while True:
while not self.lifetime.ended:
health = self.client.probe(HEALTH_ROUTE)
if health.get("status") == "ok" and not (accepting and health.get("draining")):
return True
@@ -1264,6 +1273,7 @@ class RemoteService(TitleSource):
# jittered, so the clients of a restarted server do not all log in again at the same moment
time.sleep(random.uniform(delay / 2, delay)) # nosec B311
delay = min(delay * 2, 30.0)
return False
def licence_path(self) -> object:
"""Where this remote session takes its keys from, which a reopened session must keep.
@@ -1274,16 +1284,11 @@ class RemoteService(TitleSource):
return (licensing.licensor, licensing.vault_first) if licensing else self._server_cdm_request
def reopen(self) -> bool:
"""Open a new remote session after the server lost this one, and load the current title's tracks on it again.
"""Open a new remote session after the release of the last one, and load the current title's tracks on it again.
A track the new remote session gives another id keeps its old one here, and calls translate it.
"""
grants = self.licence_path()
self.close_channel()
self._session_id = None
if self.client.tunnel: # the server forgot the tunnel too
self.client.tunnel.stop()
self.client.tunnel = None
self._segment_filters.clear()
if not self.wait_for_server(accepting=True):
return False
@@ -1322,10 +1327,10 @@ class RemoteService(TitleSource):
return True
def reopen_after_drain(self) -> None:
"""Close the remote session before the server's announced restart, so its drain can end, then open a new one."""
"""Release the remote session before the server's announced restart, so its drain can end, then open a new one."""
with self._reopen_lock:
self.log.info("The remote server restarts for an update, reopening the session after it")
self.close()
self.lifetime.release()
self._current_title = None
if not self.reopen():
raise RemoteError(
@@ -1345,11 +1350,6 @@ class RemoteService(TitleSource):
if self.channel:
self.channel.drain_logs()
def close_channel(self) -> None:
channel, self.channel = self.channel, None
if channel:
channel.close()
def get_titles(self) -> Titles_T:
if self._titles is not None:
return self._titles
@@ -1851,22 +1851,12 @@ class RemoteService(TitleSource):
) from None
def close(self) -> None:
# a long-lived serve opens many of these; the atexit hook would keep every one alive
atexit.unregister(self.close)
self.close_channel()
session_id, self._session_id = self._session_id, None
if session_id:
try:
with quiet():
result = cast(SessionClosed, self.client.delete(SESSION_ROUTE.format(session_id=session_id)))
profile = self.ctx.parent.params.get("profile") if self.ctx.parent else None
self.save_returned_cache(result.get("cache", {}), profile)
except SystemExit:
pass
except Exception as e:
self.log.warning(f"Failed to clean up remote session: {e}")
if self.client.tunnel:
self.client.tunnel.stop()
"""End the remote session for good. dl, the job worker and the relay pool all end it here."""
self.lifetime.end()
def save_session_cache(self, cache_data: dict[str, str]) -> None:
"""Save the cache files that the DELETE of the remote session returns."""
self.save_returned_cache(cache_data, self.ctx.parent.params.get("profile") if self.ctx.parent else None)
def save_returned_cache(self, cache_data: dict[str, str], profile: str | None = None) -> None:
"""Save cache files returned by the server to the local cache directory.
+4
View File
@@ -549,6 +549,7 @@ class TunnelClient:
self.thread = threading.Thread(target=run_loop, args=(self.run,), name="tunnel", daemon=True)
self.loop: asyncio.AbstractEventLoop | None = None
self.task: asyncio.Task[None] | None = None
self.stopped = False
def start(self, timeout: float = 20) -> str:
"""Open the tunnel and return its id."""
@@ -560,6 +561,7 @@ class TunnelClient:
def stop(self) -> None:
"""Close the tunnel and wait for its connections to end, so none is left pending at exit."""
self.stopped = True
if self.loop and self.task and self.thread.is_alive():
with contextlib.suppress(RuntimeError): # the loop closes before its thread ends
self.loop.call_soon_threadsafe(self.task.cancel)
@@ -567,6 +569,8 @@ class TunnelClient:
async def run(self) -> None:
self.loop, self.task = asyncio.get_running_loop(), asyncio.current_task()
if self.stopped:
return
try:
await self.connect()
except asyncio.CancelledError: