forked from kenzuya/unshackle
refactor(api): end every remote session through SessionStore._retire and close the store at shutdown
This commit is contained in:
@@ -1034,14 +1034,6 @@ def session_licensing(policy: KeyPolicy, service: str, data: dict[str, Any]) ->
|
||||
|
||||
|
||||
_account_counters: dict[str, int] = {}
|
||||
# the event loop holds only weak references to tasks, so a running login task needs a strong one
|
||||
_auth_tasks: set["asyncio.Task[None]"] = set()
|
||||
|
||||
|
||||
async def wait_for_logins(timeout: float) -> None:
|
||||
"""Wait up to ``timeout`` seconds for the remote session logins that still run, at serve shutdown."""
|
||||
if _auth_tasks:
|
||||
await asyncio.wait(set(_auth_tasks), timeout=timeout)
|
||||
|
||||
|
||||
def validate_server_accounts() -> dict[str, Any]:
|
||||
@@ -2882,9 +2874,7 @@ async def session_create_handler(data: dict[str, Any], request: web.Request | No
|
||||
if store.peek(session_id) is not session:
|
||||
SessionStore.cleanup_cache_dir(session_cache_tag)
|
||||
|
||||
auth_task = asyncio.create_task(run_auth())
|
||||
_auth_tasks.add(auth_task)
|
||||
auth_task.add_done_callback(_auth_tasks.discard)
|
||||
store.track_login(asyncio.create_task(run_auth()))
|
||||
|
||||
return web.json_response(
|
||||
SessionCreated(
|
||||
|
||||
@@ -19,8 +19,7 @@ from unshackle.core.remote_protocol import APIErrorCode, AuthStatus, coded
|
||||
if TYPE_CHECKING:
|
||||
from unshackle.core.api.session_channel import SessionChannel
|
||||
|
||||
# Seconds the server waits for a remote client to answer an input prompt before
|
||||
# giving up; also the TTL SessionStore grants AUTHENTICATING sessions.
|
||||
# Seconds the server waits for a remote client to answer an input prompt before giving up.
|
||||
AUTH_INPUT_TIMEOUT = 600.0
|
||||
CDM_CALL_TIMEOUT = 60.0
|
||||
# A listening client polls every few seconds, so a CDM call nobody fetches in this time has no client behind it.
|
||||
|
||||
@@ -10,6 +10,7 @@ from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import builtins
|
||||
import contextlib
|
||||
import logging
|
||||
import uuid
|
||||
from collections import Counter, deque
|
||||
@@ -31,6 +32,8 @@ if TYPE_CHECKING:
|
||||
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"
|
||||
|
||||
|
||||
@@ -164,6 +167,7 @@ class SessionStore:
|
||||
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
|
||||
@@ -210,11 +214,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 = self._sessions.pop(oldest_id)
|
||||
evicted.end()
|
||||
evicted_tag = evicted.cache_tag
|
||||
_publish("delete", evicted, "evicted")
|
||||
_schedule_pending_reload(evicted.service_tag)
|
||||
evicted_tag = self._retire(sessions[oldest_id], "evicted")
|
||||
|
||||
session_id = session_id or str(uuid.uuid4())
|
||||
entry = SessionEntry(
|
||||
@@ -245,19 +245,15 @@ class SessionStore:
|
||||
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:
|
||||
now = datetime.now(UTC)
|
||||
if not self._expired(entry, now):
|
||||
entry.touch()
|
||||
return entry
|
||||
await self.remove_cache_dirs([entry.cache_tag])
|
||||
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:
|
||||
@@ -271,45 +267,51 @@ class SessionStore:
|
||||
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)
|
||||
entry = self._sessions.get(session_id)
|
||||
if not entry:
|
||||
return False
|
||||
entry.end()
|
||||
_publish("delete", entry, "closed")
|
||||
cache_tag = self._retire(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])
|
||||
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 = []
|
||||
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)
|
||||
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:
|
||||
@@ -326,25 +328,24 @@ class SessionStore:
|
||||
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 close(self) -> None:
|
||||
"""End every remote session at server shutdown, wait LOGIN_WAIT seconds for the running logins, stop the sweep.
|
||||
|
||||
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.
|
||||
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:
|
||||
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])
|
||||
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:
|
||||
|
||||
Reference in New Issue
Block a user