Files
unshackle/unshackle/core/api/session_store.py
T

565 lines
24 KiB
Python

"""Server-side remote session store for the remote-dl client-server architecture.
Maintains authenticated service instances between API calls so that
a client can authenticate once and then make several requests (get the tracks,
get the segment URLs, get the licence in proxy mode) with the same
remote session.
"""
from __future__ import annotations
import asyncio
import builtins
import contextlib
import hmac
import logging
import time
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, 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
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 APIErrorCode, AuthStatus, ClientPlugin, LicensingMode, Licensor
from unshackle.core.tracks import Track, Tracks
if TYPE_CHECKING:
from unshackle.core.api.key_policy import KeyPolicy
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."""
session_id: str
service_tag: str
service_instance: Any
titles: Any = None # Titles_T from get_titles()
title_map: dict[str, Any] = field(default_factory=dict)
current_title_id: str | None = None # title the client last asked tracks for
tracks: dict[str, Track] = field(default_factory=dict)
served_keys: dict[str, tuple[str, str]] = field(
default_factory=dict
) # KID -> (KEY, serving vault name or "cdm") from server_cdm
tracks_by_title: dict[str, dict[str, Track]] = field(default_factory=dict)
chapters_by_title: dict[str, list[Any]] = field(default_factory=dict)
lock: asyncio.Lock = field(default_factory=asyncio.Lock, repr=False, compare=False)
creator_ip: str | None = None
owner_key: str | None = None # X-Secret-Key that owns this session
cache_tag: str | None = None
server_account: str | None = None # profile name when the server lent its own account
licensing: LicensingMode = NO_DEVICE
client_auth: bool = False # the login is the client's: it succeeded without a server account
policy: KeyPolicy | None = field(default=None, repr=False) # the API key policy the session was created with
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
client_plugins: dict[str, ClientPlugin] | None = None # None: a client too old to list its DRM plugins
actions: deque[dict[str, Any]] = field(default_factory=lambda: deque(maxlen=500))
created_at: datetime = field(default_factory=lambda: datetime.now(UTC))
last_accessed: datetime = field(default_factory=lambda: datetime.now(UTC))
idle_since: float = field(default_factory=time.monotonic) # expiry reads no wall clock, which can step
def __post_init__(self) -> None:
if self.input_bridge is not None:
self.input_bridge.channel = self.channel
if self.log_buffer is not None:
self.log_buffer.listener = self.channel.log
@property
def auth_status(self) -> AuthStatus:
"""The login state, which the input bridge holds; a remote session with no bridge has no login to wait on."""
return self.input_bridge.login_status if self.input_bridge else AuthStatus.AUTHENTICATED
def add_tracks(self, title_id: str, tracks: Tracks) -> None:
"""Register the video, audio and subtitle tracks of a title, so the later routes find each one by its id."""
title_tracks: dict[str, Track] = {str(t.id): t for t in [*tracks.videos, *tracks.audio, *tracks.subtitles]}
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.
So is one that waited on the client until then, even when the service has an answer without the client's:
the refusal makes a client that is still there open a new remote session.
"""
async with self.lock:
if self.channel.ended:
raise session_not_found(self.session_id)
try:
yield
except (Exception, SystemExit):
if not (self.input_bridge and self.input_bridge.cut):
raise
if self.input_bridge and self.input_bridge.cut:
raise session_not_found(self.session_id) from None
def touch(self) -> None:
"""Update last_accessed timestamp and restart the idle time."""
self.last_accessed = datetime.now(UTC)
self.idle_since = time.monotonic()
@property
def idle_seconds(self) -> float:
return time.monotonic() - self.idle_since
@property
def in_use(self) -> bool:
"""True while a request holds the lock for service work, or the client holds its remote session channel open.
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
def end(self) -> None:
"""Unblock the service threads that wait on the client, and close the remote session channel."""
if self.input_bridge:
self.input_bridge.cancel()
self.channel.end()
def summary(self, include_actions: bool = True) -> dict[str, Any]:
"""Dashboard view of the session: no service instance, no raw owner key."""
from unshackle.core.api.stats import mask_key
now = datetime.now(UTC)
title_id = (
self.current_title_id if self.current_title_id in self.title_map else next(iter(self.title_map), None)
)
title = self.title_map.get(title_id) if title_id else None
return {
"id": self.session_id,
"owner": mask_key(self.owner_key),
"creator_ip": self.creator_ip,
"service": self.service_tag,
"title_id": title_id,
"title": str(title) if title else None,
"titles": len(self.title_map),
"tracks": len(self.tracks),
"auth_status": self.auth_status.value,
"auth_error": self.auth_error,
"server_account": self.server_account,
"server_cdm": self.licensing.server_cdm,
"server_cdm_max_height": self.licensing.max_height,
"log_seq": self.log_buffer.last_seq if self.log_buffer else 0,
"client": self.client,
**({"actions": list(self.actions)} if include_actions else {}),
"created_at": self.created_at.isoformat(),
"last_accessed": self.last_accessed.isoformat(),
"created_ts": self.created_at.timestamp(),
"last_accessed_ts": self.last_accessed.timestamp(),
"age_seconds": int((now - self.created_at).total_seconds()),
"idle_seconds": int(self.idle_seconds),
}
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
named: bool = False
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
schedule_pending_reload(service_tag)
def _publish(
action: str, entry: SessionEntry, reason: str | None = None, action_entry: dict[str, Any] | None = None
) -> None:
"""Tell dashboard listeners about a remote session; ``action_entry`` replaces the action log with that one action."""
data = {"action": action, **entry.summary(include_actions=action_entry is None)}
if reason:
data["reason"] = reason
if action_entry is not None:
data["action_entry"] = action_entry
bus.publish("session", data)
class SessionStore:
"""Thread-safe remote session store with TTL-based expiration."""
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()
self.draining = False
@property
def ttl(self) -> int:
"""Remote session TTL in seconds from config."""
return config.serve.get("session_ttl", 300)
@property
def max_sessions(self) -> int | None:
"""Max concurrent sessions from config; None when the operator set no limit.
``max_sessions: null`` or ``0`` means unlimited, so a dashboard can tell "no cap" from
a cap that happens to sit at the default.
"""
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,
service_instance: Any,
session_id: str | None = None,
*,
owner_key: str | None = None,
creator_ip: str | None = None,
server_account: str | None = None,
cache_tag: str | None = None,
policy: KeyPolicy | None = None,
licensing: LicensingMode = NO_DEVICE,
client_auth: bool = False,
client: dict[str, Any] | None = None,
input_bridge: InputBridge | None = None,
log_buffer: Any | None = None,
pending: PendingCreate | None = None,
client_plugins: dict[str, ClientPlugin] | None = None,
) -> SessionEntry:
"""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
held = Counter(s.owner_key for s in sessions.values())
oldest_id = min(
sessions,
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}")
ended_tags.append(self._retire(sessions[oldest_id], "evicted"))
session_id = session_id or str(uuid.uuid4())
entry = SessionEntry(
session_id=session_id,
service_tag=service_tag,
service_instance=service_instance,
owner_key=owner_key,
creator_ip=creator_ip,
server_account=server_account,
cache_tag=cache_tag,
policy=policy,
licensing=licensing,
client_auth=client_auth,
client=client or {},
client_plugins=client_plugins,
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)
log.info(f"Created session {sanitize_log(session_id)} for service {sanitize_log(service_tag)}")
await self.remove_cache_dirs(ended_tags)
return entry
async def get(self, session_id: str) -> SessionEntry | None:
"""Get a remote session by ID, returns None if not found or expired."""
async with self._lock:
entry = self._sessions.get(session_id)
if entry is None:
return None
if not self._expired(entry):
entry.touch()
return entry
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
def peek(self, session_id: str) -> SessionEntry | None:
"""A remote session entry without touching it, for read-only observers.
``get`` refreshes ``last_accessed`` and expires stale entries, so an observer polling
through it would keep an idle remote session alive and always report it as active.
"""
return self._sessions.get(session_id)
async def delete(self, session_id: str) -> bool:
"""Delete a remote session. Returns True if it existed."""
async with self._lock:
entry = self._sessions.get(session_id)
if not entry:
return False
cache_tag = self._retire(entry, "closed")
log.info(f"Deleted session {sanitize_log(session_id)}")
await self.remove_cache_dirs([cache_tag])
return True
async def cleanup_expired(self) -> int:
"""Remove all expired sessions. Returns count of removed sessions."""
async with self._lock:
expired = [entry for entry in self._sessions.values() if self._expired(entry)]
cache_tags = [self._retire(entry, "expired") for entry in expired]
if expired:
log.info(f"Cleaned up {len(expired)} expired sessions")
await self.remove_cache_dirs(cache_tags)
return len(expired)
def _idle_limit(self, entry: SessionEntry) -> float:
"""The idle limit of a remote session: the TTL, or max(TTL, AUTH_INPUT_TIMEOUT) while its login runs."""
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: 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:
"""End a remote session under the store lock and return its cache tag, for removal outside the lock.
A reason goes to the dashboard delete event and schedules a staged service reload; the shutdown
retire passes None and does neither.
"""
del self._sessions[entry.session_id]
entry.end()
if entry.cache_tag and entry.lock.locked():
self.track_login(asyncio.create_task(self._remove_cache_after_work(entry)))
if reason is not None:
_publish("delete", entry, reason)
_schedule_pending_reload(entry.service_tag)
return entry.cache_tag
async def _remove_cache_after_work(self, entry: SessionEntry) -> None:
"""Remove the cache directory again after the service thread of a running request, which can still write it."""
async with entry.lock:
await self.remove_cache_dirs([entry.cache_tag])
def track_login(self, task: asyncio.Task[None]) -> None:
"""Hold a strong reference to a task that can outlive its remote session, so that close() can wait for it."""
self._logins.add(task)
task.add_done_callback(self._logins.discard)
async def start_cleanup_loop(self) -> None:
"""Start periodic cleanup of expired sessions."""
if self._cleanup_task is not None:
return
async def loop() -> None:
while True:
await asyncio.sleep(SWEEP_INTERVAL)
try:
await self.cleanup_expired()
except Exception:
log.exception("Error during session cleanup")
self._cleanup_task = asyncio.create_task(loop())
log.info("Session cleanup loop started")
async def close(self) -> None:
"""End every remote session at server shutdown, wait LOGIN_WAIT seconds for the running work, 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 create_session removes that cache directory again.
"""
async with self._lock:
cache_tags = [self._retire(entry, None) for entry in list(self._sessions.values())]
if cache_tags:
log.info(f"Closed {len(cache_tags)} remote session(s) at shutdown")
await self.remove_cache_dirs(cache_tags)
if self._logins:
await asyncio.wait(set(self._logins), timeout=LOGIN_WAIT)
if self._cleanup_task is not None:
self._cleanup_task.cancel()
with contextlib.suppress(asyncio.CancelledError):
await self._cleanup_task
self._cleanup_task = None
@classmethod
async def remove_cache_dirs(cls, cache_tags: builtins.list[str | None]) -> None:
"""Remove the cache directories of ended remote sessions on a worker thread, outside the store lock."""
if any(cache_tags):
await asyncio.to_thread(lambda: [cls.cleanup_cache_dir(tag) for tag in cache_tags])
@staticmethod
def cleanup_cache_dir(cache_tag: str | None) -> None:
"""Remove the remote session cache directory and empty parents."""
if not cache_tag:
return
import shutil
cache_dir = config.directories.cache / cache_tag
if cache_dir.is_dir():
try:
shutil.rmtree(cache_dir)
except Exception as e:
log.warning(f"Failed to remove session cache {cache_dir}: {e}")
for parent in cache_dir.parents:
if parent == config.directories.cache:
break
try:
if parent.is_dir() and not any(parent.iterdir()):
parent.rmdir()
except OSError:
break
@staticmethod
def publish_update(entry: SessionEntry) -> None:
"""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."""
entry = self._sessions.get(session_id)
if entry is None:
return
entry.actions.append(action)
_publish("update", entry, action_entry=action)
def list(self) -> builtins.list[SessionEntry]:
"""Snapshot of every live session."""
return list(self._sessions.values())
def start_drain(self) -> None:
"""Refuse new sessions and jobs until the restart, and warn each open session through its service log."""
if self.draining:
return
self.draining = True
log.warning(f"Draining: new sessions and jobs are refused, {len(self._sessions)} session(s) open")
for entry in self._sessions.values():
if entry.log_buffer is not None:
entry.log_buffer.append(logging.WARNING, DRAIN_WARNING)
entry.channel.send(drain_message(True))
def stop_drain(self) -> None:
if self.draining:
self.draining = False
log.warning("Drain cancelled: new sessions and jobs are accepted again")
for entry in self._sessions.values():
entry.channel.send(drain_message(False))
@property
def session_count(self) -> int:
"""Number of active sessions."""
return len(self._sessions)
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."""
if get_session_store().draining:
raise APIError(
APIErrorCode.SERVER_DRAINING,
"This server restarts for an update and starts no new sessions or downloads",
retryable=True,
)
def get_session_store() -> SessionStore:
"""Get or make the global remote session store singleton."""
global session_store
if session_store is None:
session_store = SessionStore()
return session_store