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

448 lines
19 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 logging
import uuid
from collections import Counter, deque
from dataclasses import dataclass, field
from datetime import UTC, datetime
from typing import TYPE_CHECKING, Any
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
from unshackle.core.tracks import Track, Tracks
if TYPE_CHECKING:
from unshackle.core.api.key_policy import KeyPolicy
log = logging.getLogger("api.session")
DRAIN_WARNING = "This server restarts for an update after the open downloads finish; this download continues"
@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
server_cdm: bool = False # False: the client's own device licenses this session
server_cdm_max_height: int | None = None
server_vault: bool = False # a session the client's device licenses may still take keys from the server vault
server_device: bool = False # its service runs on the server's lent device, so keys come only from a vault
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)
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))
created_at: datetime = field(default_factory=lambda: datetime.now(UTC))
last_accessed: datetime = field(default_factory=lambda: datetime.now(UTC))
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
def touch(self) -> None:
"""Update last_accessed timestamp."""
self.last_accessed = datetime.now(UTC)
@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.
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.
"""
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.server_cdm,
"server_cdm_max_height": self.server_cdm_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((now - self.last_accessed).total_seconds()),
}
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._lock = asyncio.Lock()
self._cleanup_task: asyncio.Task | None = None
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
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,
server_cdm: bool = False,
server_cdm_max_height: int | None = None,
server_vault: bool = False,
server_device: bool = False,
client_auth: bool = False,
client: dict[str, Any] | None = None,
input_bridge: InputBridge | None = None,
log_buffer: Any | None = None,
) -> SessionEntry:
"""Make a new remote session, complete with every field the dashboard shows, and announce it."""
evicted_tag: str | None = None
async with self._lock:
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}")
evicted = self._sessions.pop(oldest_id)
evicted.end()
evicted_tag = evicted.cache_tag
_publish("delete", evicted, "evicted")
_schedule_pending_reload(evicted.service_tag)
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,
server_cdm=server_cdm,
server_cdm_max_height=server_cdm_max_height,
server_vault=server_vault,
server_device=server_device,
client_auth=client_auth,
client=client or {},
input_bridge=input_bridge,
log_buffer=log_buffer,
)
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])
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
expired = False
if not entry.in_use and entry.auth_status != AuthStatus.AUTHENTICATING:
elapsed = (datetime.now(UTC) - entry.last_accessed).total_seconds()
if elapsed > self.ttl:
log.info(f"Session {sanitize_log(session_id)} expired (elapsed={elapsed:.0f}s, ttl={self.ttl}s)")
_publish("delete", self._sessions.pop(session_id), "expired")
entry.end()
_schedule_pending_reload(entry.service_tag)
expired = True
if not expired:
entry.touch()
return entry
await self.remove_cache_dirs([entry.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.pop(session_id, None)
if not entry:
return False
entry.end()
_publish("delete", entry, "closed")
log.info(f"Deleted session {sanitize_log(session_id)}")
_schedule_pending_reload(entry.service_tag)
await self.remove_cache_dirs([entry.cache_tag])
return True
async def cleanup_expired(self) -> int:
"""Remove all expired sessions. Returns count of removed sessions."""
async with self._lock:
now = datetime.now(UTC)
expired = []
for sid, entry in self._sessions.items():
if entry.in_use:
continue
elapsed = (now - entry.last_accessed).total_seconds()
if entry.auth_status == AuthStatus.AUTHENTICATING:
if elapsed > AUTH_INPUT_TIMEOUT:
expired.append(sid)
elif elapsed > self.ttl:
expired.append(sid)
ended_tags: set[str] = set()
cache_tags: list[str | None] = []
for sid in expired:
entry = self._sessions.pop(sid)
entry.end()
cache_tags.append(entry.cache_tag)
_publish("delete", entry, "expired")
ended_tags.add(entry.service_tag)
for tag in ended_tags:
_schedule_pending_reload(tag)
if expired:
log.info(f"Cleaned up {len(expired)} expired sessions")
await self.remove_cache_dirs(cache_tags)
return len(expired)
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(60)
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 stop_cleanup_loop(self) -> None:
"""Stop the periodic cleanup task."""
if self._cleanup_task is not None:
self._cleanup_task.cancel()
self._cleanup_task = None
async def cancel_all_bridges(self) -> None:
"""End every remote session and remove its cache directory (called on server shutdown).
The store forgets the sessions too, so a login task that ends after this removes the directory again.
"""
async with self._lock:
entries = list(self._sessions.values())
self._sessions.clear()
for entry in entries:
entry.end()
if entries:
log.info(f"Cancelled bridges for {len(entries)} active session(s)")
await self.remove_cache_dirs([entry.cache_tag for entry in entries])
@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 a session's summary changed (titles or tracks loaded, auth settled)."""
_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."""
from unshackle.core.api.errors import APIError
from unshackle.core.remote_protocol import APIErrorCode
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