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

441 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 contextlib
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, 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
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
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)
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.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((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._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
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,
) -> 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_tag = 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 {},
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
now = datetime.now(UTC)
if not self._expired(entry, now):
entry.touch()
return entry
elapsed = (now - entry.last_accessed).total_seconds()
limit = self._idle_limit(entry)
log.info(f"Session {sanitize_log(session_id)} expired (elapsed={elapsed:.0f}s, ttl={limit:.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:
now = datetime.now(UTC)
expired = [entry for entry in self._sessions.values() if self._expired(entry, now)]
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, now: datetime) -> bool:
"""The one expiry rule: no request holds the remote session and it is idle past its limit."""
return not entry.in_use and (now - entry.last_accessed).total_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 reason is not None:
_publish("delete", entry, reason)
_schedule_pending_reload(entry.service_tag)
return entry.cache_tag
def track_login(self, task: asyncio.Task[None]) -> None:
"""Hold a strong reference to a login task until it ends, 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(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 close(self) -> None:
"""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.
"""
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 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