feat(remote): add a session channel for the messages the server starts

This commit is contained in:
imSp4rky
2026-11-24 17:50:10 -07:00
parent 5da940a5d3
commit ed090affc3
22 changed files with 1606 additions and 400 deletions
+17
View File
@@ -28,6 +28,7 @@ from unshackle.core.api.errors import APIError, categorize_exception, handle_api
from unshackle.core.api.input_bridge import InputBridge, NoUserBridge
from unshackle.core.api.progress import track_log_label
from unshackle.core.api.sanitize import MAX_SESSION_CACHE_KEYS, safe_cache_key, safe_cache_payload, sanitize_log
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 SessionStore
from unshackle.core.binaries import binary_version
@@ -535,6 +536,7 @@ def setup_remote_service(
raise
finally:
_remote_logins.pop(login.id, None)
service_instance._input_bridge = NoUserBridge() # nobody can answer a prompt once the login is gone
return service_instance
@@ -3657,6 +3659,9 @@ async def session_create_handler(data: Dict[str, Any], request: Optional[web.Req
session.input_bridge = bridge
session.log_buffer = log_buffer
session.auth_status = AuthStatus.AUTHENTICATING
bridge.channel = session.channel
if log_buffer:
log_buffer.listener = session.channel.log
async def run_auth() -> None:
try:
@@ -3671,6 +3676,7 @@ async def session_create_handler(data: Dict[str, Any], request: Optional[web.Req
session.auth_error = redact_secrets(str(e))
bridge.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)
@@ -5454,6 +5460,17 @@ async def session_delete_handler(session_id: str, request: Optional[web.Request]
return web.json_response(response)
async def session_channel_handler(session_id: str, request: web.Request) -> web.StreamResponse:
"""Attach the caller's session channel, which carries the messages the server starts for the remote session."""
from unshackle.core.api.session_store import get_session_store
session = await get_validated_session(session_id, request)
ws = web.WebSocketResponse(heartbeat=HEARTBEAT)
await ws.prepare(request) # a request that is not a WebSocket upgrade fails here
await session.channel.serve(ws, session, _since(request), get_session_store().draining)
return ws
def shared_key_client(request: web.Request) -> Optional[str]:
"""The person behind a ``shared: true`` API key, from the ``X-Client-Id`` its gateway sets; None for other keys.
+142 -86
View File
@@ -1,21 +1,24 @@
"""Thread-safe bridge for interactive input during remote authentication.
"""Thread-safe bridge for the prompts and CDM calls that service code on the server sends to the remote client.
When a service calls ``request_input()`` during ``authenticate()`` on the
server, the InputBridge pauses the auth thread and exposes the prompt to
the HTTP layer so a remote client can poll for it, collect the user's
response, and submit it back. The auth thread then resumes with the
response value.
When a service calls ``request_input()`` or its client-device CDM makes a call, the InputBridge blocks the
service thread on an *ask* until the remote client answers it. The remote session channel carries an ask when one is
attached; otherwise the prompt routes serve it, one at a time. Each ask belongs to the path that carried it
first, and only that path can answer it.
"""
from __future__ import annotations
import json
import threading
import uuid
from dataclasses import dataclass, field
from typing import Any, Optional
from typing import TYPE_CHECKING, Any, Optional
from unshackle.core.remote_protocol import AuthStatus
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/PENDING_INPUT sessions.
AUTH_INPUT_TIMEOUT = 600.0
@@ -27,63 +30,81 @@ CDM_CALL_FALLBACK_PROMPT = (
"This service needs your local CDM during login, and your unshackle cannot answer it. Update unshackle"
)
CHANNEL = "channel"
POLL = "poll"
@dataclass(eq=False)
class Ask:
"""One prompt or CDM call that service code waits on."""
id: str
prompt: str
cdm_call: Optional[dict[str, Any]] = None
owner: Optional[str] = None # CHANNEL or POLL: the path that carried the ask, and the only one that answers it
response: Optional[str] = None
error: Optional[str] = None # the client could not answer, and says why
picked_up: threading.Event = field(default_factory=threading.Event)
answered: threading.Event = field(default_factory=threading.Event)
@dataclass
class InputBridge:
"""Thread-safe bridge between a sync auth thread and the async HTTP layer.
"""Thread-safe bridge between the service threads and the async HTTP layer.
The auth thread calls :meth:`request_input` which blocks until the
remote client submits a response through the HTTP prompt endpoints.
A service thread calls :meth:`request_input` or :meth:`request_cdm`, which block until the remote client
answers through the remote session channel or the prompt routes.
"""
_prompt: Optional[str] = field(default=None, init=False, repr=False)
_response: Optional[str] = field(default=None, init=False, repr=False)
channel: Optional[SessionChannel] = field(default=None, init=False, repr=False)
_asks: dict[str, Ask] = field(default_factory=dict, init=False, repr=False)
_status: AuthStatus = field(default=AuthStatus.AUTHENTICATING, init=False)
_cancelled: bool = field(default=False, init=False, repr=False)
_cdm_call: Optional[dict[str, Any]] = field(default=None, init=False, repr=False)
_response_ready: threading.Event = field(default_factory=threading.Event, init=False, repr=False)
_picked_up: threading.Event = field(default_factory=threading.Event, init=False, repr=False)
_lock: threading.Lock = field(default_factory=threading.Lock, init=False, repr=False)
def _open(self, prompt: str, cdm_call: Optional[dict[str, Any]] = None) -> Ask:
"""Register an ask and offer it to the attached channel; call it with the lock held."""
if self._cancelled:
raise RuntimeError("Session was cancelled")
ask = Ask(uuid.uuid4().hex, prompt, cdm_call)
if self.channel is not None and self.channel.offer(ask):
ask.owner = CHANNEL
ask.picked_up.set()
self._asks[ask.id] = ask
return ask
def request_input(self, prompt: str, timeout: float = AUTH_INPUT_TIMEOUT) -> str:
"""Block until the remote client submits a response for *prompt*.
Args:
prompt: The message to display to the remote user.
timeout: Maximum seconds to wait for a response.
Returns:
The string response from the remote client.
After authentication only an attached session channel can carry a prompt, as a polling client stops
asking for prompts once it is logged in.
Raises:
TimeoutError: If the bridge gets no response within *timeout*.
RuntimeError: If the server cancelled the bridge, or authentication is complete.
RuntimeError: If the server cancelled the bridge, or authentication is complete and no channel is attached.
"""
with self._lock:
if self._cancelled:
raise RuntimeError("Session was cancelled")
if self._status == AuthStatus.AUTHENTICATED:
if self._status == AuthStatus.AUTHENTICATED and not (self.channel and self.channel.attached):
if self._cancelled:
raise RuntimeError("Session was cancelled")
raise RuntimeError(f"Remote mode cannot relay a prompt after authentication: {prompt}")
self._prompt = prompt
self._response = None
self._status = AuthStatus.PENDING_INPUT
self._response_ready.clear()
# cancel() and submit_response() both .set() the event, so a single wait
# returns on signal-or-cancel; no poll loop needed.
if not self._response_ready.wait(timeout=timeout):
ask = self._open(prompt)
try:
# cancel() and an answer both set the event, so a single wait returns on signal-or-cancel
if not ask.answered.wait(timeout=timeout):
with self._lock:
if self._status != AuthStatus.AUTHENTICATED:
self._status = AuthStatus.FAILED
raise TimeoutError(f"No client response for prompt within {timeout}s")
with self._lock:
self._status = AuthStatus.FAILED
raise TimeoutError(f"No client response for prompt within {timeout}s")
with self._lock:
if self._cancelled:
raise RuntimeError("Session was cancelled")
response = self._response or ""
self._prompt = None
self._response = None
self._status = AuthStatus.AUTHENTICATING
return response
if self._cancelled:
raise RuntimeError("Session was cancelled")
if ask.error is not None:
raise RuntimeError(f"The client could not answer the prompt: {ask.error}")
return ask.response or ""
finally:
with self._lock:
self._asks.pop(ask.id, None)
def request_cdm(
self, call: dict[str, Any], timeout: float = CDM_CALL_TIMEOUT, pickup: float = CDM_PICKUP_TIMEOUT
@@ -95,25 +116,16 @@ class InputBridge:
service thread for seconds, not for the full ``timeout``.
"""
with self._lock:
if self._cancelled:
raise RuntimeError("Session was cancelled")
previous = self._status
self._prompt = CDM_CALL_FALLBACK_PROMPT
self._cdm_call = call
self._response = None
self._status = AuthStatus.PENDING_INPUT
self._response_ready.clear()
self._picked_up.clear()
picked_up = self._picked_up.wait(timeout=pickup)
answered = picked_up and self._response_ready.wait(timeout=timeout)
with self._lock:
answer = self._response
self._prompt = self._response = self._cdm_call = None
cancelled = self._cancelled
if not cancelled:
self._status = previous
ask = self._open(CDM_CALL_FALLBACK_PROMPT, call)
try:
picked_up = ask.picked_up.wait(timeout=pickup)
answered = picked_up and ask.answered.wait(timeout=timeout)
with self._lock:
answer = ask.response
cancelled = self._cancelled
finally:
with self._lock:
self._asks.pop(ask.id, None)
if cancelled:
raise RuntimeError("Session was cancelled")
if not picked_up:
@@ -130,51 +142,92 @@ class InputBridge:
raise RuntimeError(f"The client's CDM refused the call: {result['error']}")
return result
def _pollable(self) -> list[Ask]:
"""The asks the prompt routes can serve: unanswered, and not carried by the channel; call it under the lock.
An answered ask stops being pending at once, before the waiting thread wakes, so a client that polls again
straight away never sees it twice.
"""
return [a for a in self._asks.values() if not a.answered.is_set() and a.owner != CHANNEL]
def get_pending_cdm_call(self) -> Optional[dict[str, Any]]:
"""Return the CDM call that service code waits on, if any, and mark it as fetched by a client."""
with self._lock:
if self._awaiting_answer() and self._cdm_call is not None:
self._picked_up.set()
return self._cdm_call
return None
ask = next((a for a in self._pollable() if a.cdm_call is not None), None)
if ask is None:
return None
ask.owner = POLL
ask.picked_up.set()
return ask.cdm_call
def get_pending_prompt(self) -> Optional[str]:
"""Return the current prompt when the auth thread waits for input."""
"""Return the prompt of the first ask the prompt routes can serve, and keep that ask on them."""
with self._lock:
if self._awaiting_answer():
return self._prompt
return None
ask = next(iter(self._pollable()), None)
if ask is None:
return None
ask.owner = POLL
return ask.prompt
def submit_response(self, response: str) -> bool:
"""Deliver the client's response and unblock the auth thread.
"""Answer the oldest ask that the prompt routes served, else the oldest one they can serve.
Returns:
``True`` if a prompt was pending and the bridge accepted the response,
``False`` otherwise.
``True`` if an ask was pending and the bridge accepted the response, ``False`` otherwise.
"""
with self._lock:
if not self._awaiting_answer():
pending = self._pollable()
ask = next((a for a in pending if a.owner == POLL), pending[0] if pending else None)
if ask is None:
return False
self._response = response
self._picked_up.set()
self._response_ready.set()
self._answer(ask, response)
return True
def _awaiting_answer(self) -> bool:
"""True while a prompt or CDM call waits and no answer has arrived; call it under the lock.
def answer(self, ask_id: str, response: str, error: Optional[str] = None) -> bool:
"""Answer the ask with this id that the remote session channel carried; False when no such ask waits."""
with self._lock:
ask = self._asks.get(ask_id)
if ask is None or ask.owner != CHANNEL or ask.answered.is_set():
return False
ask.error = error
self._answer(ask, response)
return True
An answered call stops being pending at once, before the waiting thread wakes, so a client
that polls again straight away never sees it twice.
@staticmethod
def _answer(ask: Ask, response: str) -> None:
ask.response = response
ask.picked_up.set()
ask.answered.set()
def claim_for_channel(self) -> list[Ask]:
"""Give every unanswered ask that the prompt routes did not serve to a newly attached session channel."""
with self._lock:
asks = [a for a in self._asks.values() if not a.answered.is_set() and a.owner != POLL]
for ask in asks:
ask.owner = CHANNEL
ask.picked_up.set()
return asks
def release_channel_asks(self) -> None:
"""Hand the unanswered asks of a detached channel back to the prompt routes, so none waits on a dead socket.
A prompt after login stays with the channel, as a polling client asks for prompts only while it logs in.
"""
return self._status == AuthStatus.PENDING_INPUT and not self._response_ready.is_set()
with self._lock:
for ask in self._asks.values():
pollable = ask.cdm_call is not None or self._status != AuthStatus.AUTHENTICATED
if ask.owner == CHANNEL and pollable and not ask.answered.is_set():
ask.owner = None
def cancel(self) -> None:
"""Cancel the bridge, unblocking any waiting auth thread."""
"""Cancel the bridge, unblocking any waiting service thread."""
with self._lock:
self._cancelled = True
self._status = AuthStatus.FAILED
self._picked_up.set()
self._response_ready.set()
asks = list(self._asks.values())
for ask in asks:
ask.picked_up.set()
ask.answered.set()
def ensure_active(self) -> None:
"""Raise RuntimeError once the server cancelled the bridge, so a login loop stops."""
@@ -184,7 +237,10 @@ class InputBridge:
@property
def status(self) -> AuthStatus:
"""``pending_input`` while an ask waits for its answer, else the login state."""
with self._lock:
if self._status != AuthStatus.FAILED and any(not a.answered.is_set() for a in self._asks.values()):
return AuthStatus.PENDING_INPUT
return self._status
@status.setter
+42
View File
@@ -59,6 +59,7 @@ from unshackle.core.api.handlers import (
server_accounts_allowed,
server_config_handler,
session_bad_key_handler,
session_channel_handler,
session_create_handler,
session_delete_handler,
session_info_handler,
@@ -75,9 +76,11 @@ from unshackle.core.api.handlers import (
tunnel_handler,
)
from unshackle.core.api.sanitize import sanitize_log
from unshackle.core.api.session_channel import close_channels
from unshackle.core.drm import cbcs
from unshackle.core.remote_protocol import (
BAD_KEY_ROUTE,
CHANNEL_ROUTE,
HEALTH_ROUTE,
LICENSE_ROUTE,
LOGS_ROUTE,
@@ -2537,6 +2540,43 @@ async def session_delete(request: web.Request) -> web.Response:
return await session_delete_handler(session_id, request)
@api_handler
async def session_channel(request: web.Request) -> web.StreamResponse:
"""
Open the remote session channel.
---
summary: Open session channel
description: >-
A WebSocket that a --remote client holds open for its remote session. The server sends each message it
starts as a JSON text frame with a type field - prompt and cdm_call (each with an id), log, status, and drain
(with draining true or false).
The client answers a prompt or a CDM call with {"type": "answer", "id": <id>, "response": <text>}.
On attach the server first sends the log records after since, the drain state, the waiting prompts and
CDM calls, then the login state. The remote session does not expire while the channel is open. When the
server removes the remote session, it closes the channel with code 4404.
parameters:
- name: session_id
in: path
required: true
schema:
type: string
- name: since
in: query
required: false
description: Send the log records after this sequence number first (default - 0)
schema:
type: integer
responses:
'101':
description: WebSocket open
'403':
description: The remote session belongs to another API key
'404':
description: Remote session not found
"""
return await session_channel_handler(request.match_info["session_id"], request)
@api_handler
async def session_prompt_get(request: web.Request) -> web.Response:
"""
@@ -3450,6 +3490,7 @@ ROUTES: list[tuple[str, str, Handler, bool]] = [
("GET", LOGS_ROUTE, session_logs, True),
("GET", PROMPT_ROUTE, session_prompt_get, True),
("POST", PROMPT_ROUTE, session_prompt_submit, True),
("GET", CHANNEL_ROUTE, session_channel, True),
("GET", SESSION_ROUTE, session_info, True),
("DELETE", SESSION_ROUTE, session_delete, True),
]
@@ -3494,6 +3535,7 @@ def setup_routes(
add[method](path, handler)
app.on_response_prepare.append(generic_server_header)
app.on_shutdown.append(close_tunnels)
app.on_shutdown.append(close_channels)
async def generic_server_header(request: web.Request, response: web.StreamResponse) -> None:
+180
View File
@@ -0,0 +1,180 @@
"""The messages a remote session's server starts, and the session channel that carries them to the client.
Service threads (prompts and CDM calls in the input bridge, the session log mirror), the drain and the session
store hand each message to the remote session's :class:`SessionChannel`. While the client holds the channel's
WebSocket open, the channel sends the message at once. Otherwise the message waits where the polling routes read
it (the input bridge, the log buffer of the remote session, the drain flag), as for a client without the channel.
"""
from __future__ import annotations
import asyncio
import json
from typing import TYPE_CHECKING, Any, Optional, Union, cast
from aiohttp import WSMsgType, web
from unshackle.core.api.sanitize import sanitize_log
from unshackle.core.remote_protocol import (
CHANNEL_SESSION_GONE,
ChannelAnswer,
ChannelCdmCall,
ChannelDrain,
ChannelLog,
ChannelMessage,
ChannelPrompt,
ChannelStatus,
LogRecord,
)
from unshackle.core.tunnel import HEARTBEAT
if TYPE_CHECKING:
from unshackle.core.api.input_bridge import Ask
from unshackle.core.api.session_store import SessionEntry
Message = Union[ChannelPrompt, ChannelCdmCall, ChannelLog, ChannelStatus, ChannelDrain]
GONE = object()
def drain_message(draining: bool) -> ChannelDrain:
return ChannelDrain(type=ChannelMessage.DRAIN, draining=draining)
def status_message(session: SessionEntry) -> ChannelStatus:
"""The login state of the remote session, with the same redacted error that the prompt route gives."""
message = ChannelStatus(type=ChannelMessage.STATUS, status=session.auth_status.value)
if session.auth_error:
message["error"] = session.auth_error
return message
class SessionChannel:
"""The WebSocket of one remote session, while the client holds it open.
Any thread can hand a message to :meth:`send`: it goes to the event loop through ``call_soon_threadsafe``,
and one writer task sends the messages in order. Nothing here takes a lock or waits on a worker.
"""
def __init__(self) -> None:
self.ws: Optional[web.WebSocketResponse] = None
self.queue: Optional[asyncio.Queue[Any]] = None
self.loop: Optional[asyncio.AbstractEventLoop] = None
self.ended = False
@property
def attached(self) -> bool:
return self.ws is not None
def send(self, message: Any) -> bool:
"""Queue *message* for the attached WebSocket, from any thread; False when no WebSocket is attached."""
loop, queue = self.loop, self.queue
if loop is None or queue is None:
return False
try:
loop.call_soon_threadsafe(queue.put_nowait, message)
except RuntimeError: # the loop closed at server shutdown
return False
return True
def offer(self, ask: Ask) -> bool:
"""Send a prompt or CDM call that service code waits on; False when the polling routes must serve it."""
return self.send(ask_message(ask))
def log(self, record: LogRecord) -> None:
"""Send one record of the service log mirror; the buffer keeps it for the logs route too."""
if self.queue is not None:
self.send(log_message(record))
def end(self) -> None:
"""Close the channel for good, with the close code that tells the client the remote session is gone."""
self.ended = True
self.send(GONE)
async def serve(self, ws: web.WebSocketResponse, session: SessionEntry, since: int, draining: bool) -> None:
"""Attach *ws* until the client or the server closes it.
The client first gets what it missed: the log records after *since*, a drain notice, the prompts and CDM
calls the polling routes did not serve, then the login state. A log record can come twice; its ``seq``
tells the client.
"""
if self.ended:
await ws.close(code=CHANNEL_SESSION_GONE, message=b"session closed")
return
previous = self.ws
queue: asyncio.Queue[Any] = asyncio.Queue()
self.loop, self.ws, self.queue = asyncio.get_running_loop(), ws, queue
backlog: list[Any] = []
if session.log_buffer is not None:
backlog += [log_message(r) for r in session.log_buffer.since(since)]
backlog.append(drain_message(draining))
bridge = session.input_bridge
backlog += [ask_message(ask) for ask in (bridge.claim_for_channel() if bridge else [])]
backlog.append(status_message(session))
for message in backlog:
queue.put_nowait(message)
writer = asyncio.create_task(self.write(ws, queue, session))
try:
if previous is not None:
await previous.close()
async for msg in ws:
if msg.type == WSMsgType.TEXT and bridge is not None:
receive(msg.data, bridge)
finally:
writer.cancel()
if self.ws is ws:
self.ws = self.queue = None
if bridge is not None:
bridge.release_channel_asks()
session.touch()
@staticmethod
async def write(ws: web.WebSocketResponse, queue: asyncio.Queue[Any], session: SessionEntry) -> None:
"""Send the queued messages in order; the idle timer moves while the channel is open, for the dashboard."""
try:
while True:
try:
message = await asyncio.wait_for(queue.get(), HEARTBEAT)
except asyncio.TimeoutError:
session.touch()
continue
if message is GONE:
await ws.close(code=CHANNEL_SESSION_GONE, message=b"session closed")
return
await ws.send_json(message)
session.touch()
except Exception: # a writer that cannot send closes the socket, so the session does not stay attached
await ws.close()
def log_message(record: LogRecord) -> ChannelLog:
return cast(ChannelLog, {"type": ChannelMessage.LOG, **record})
def ask_message(ask: Ask) -> Union[ChannelPrompt, ChannelCdmCall]:
if ask.cdm_call is not None:
return ChannelCdmCall(type=ChannelMessage.CDM_CALL, id=ask.id, call=ask.cdm_call)
return ChannelPrompt(type=ChannelMessage.PROMPT, id=ask.id, prompt=ask.prompt)
def receive(text: str, bridge: Any) -> None:
"""Hand the client's answer to the ask it names; any other message is ignored."""
try:
data: ChannelAnswer = json.loads(text)
except ValueError:
return
if (
isinstance(data, dict)
and data.get("type") == ChannelMessage.ANSWER
and isinstance(data.get("id"), str)
and isinstance(data.get("response"), str)
):
error = data.get("error")
bridge.answer(data["id"], data["response"], sanitize_log(error)[:500] if isinstance(error, str) else None)
async def close_channels(_: web.Application) -> None:
"""End every attached channel at server shutdown, so no WebSocket holds the shutdown open."""
from unshackle.core.api.session_store import get_session_store
for entry in get_session_store().list():
entry.channel.end()
+14 -9
View File
@@ -18,7 +18,7 @@ import threading
import time
import traceback
from collections import deque
from typing import Any, Deque, List, MutableMapping, Optional, Tuple
from typing import Any, Callable, Deque, List, MutableMapping, Optional, Tuple
from unshackle.core.api.sanitize import sanitize_log
from unshackle.core.remote_protocol import LogRecord
@@ -28,24 +28,29 @@ MAX_MESSAGE_LEN = 2000
class SessionLogBuffer:
"""Thread-safe bounded buffer of log records with a monotonic sequence."""
"""Thread-safe bounded buffer of log records with a monotonic sequence.
``listener`` gets each new record under the lock, so records reach it in sequence order; it must not block.
"""
def __init__(self, maxlen: int = MAX_RECORDS) -> None:
self._records: Deque[LogRecord] = deque(maxlen=maxlen)
self._seq = 0
self._lock = threading.Lock()
self.listener: Optional[Callable[[LogRecord], None]] = None
def append(self, level: int, message: str) -> None:
with self._lock:
self._seq += 1
self._records.append(
LogRecord(
seq=self._seq,
level=logging.getLevelName(level),
message=sanitize_log(message)[:MAX_MESSAGE_LEN],
ts=time.time(),
)
record = LogRecord(
seq=self._seq,
level=logging.getLevelName(level),
message=sanitize_log(message)[:MAX_MESSAGE_LEN],
ts=time.time(),
)
self._records.append(record)
if self.listener is not None:
self.listener(record)
def since(self, seq: int) -> List[LogRecord]:
"""Records with a sequence number greater than *seq*, oldest first."""
+21 -13
View File
@@ -19,6 +19,7 @@ from typing import Any, Deque, Dict, List, Optional
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
@@ -57,6 +58,7 @@ class SessionEntry:
user_config: Optional[Dict[str, Any]] = None # the serve.users entry the session was created with
input_bridge: Optional[InputBridge] = None
log_buffer: Optional[Any] = None # SessionLogBuffer mirroring the service's self.log
channel: SessionChannel = field(default_factory=SessionChannel, repr=False, compare=False)
auth_status: AuthStatus = AuthStatus.AUTHENTICATED
auth_error: Optional[str] = None
client: Dict[str, Any] = field(default_factory=dict) # version/argv/platform the client reported
@@ -70,12 +72,18 @@ class SessionEntry:
@property
def in_use(self) -> bool:
"""True while a request holds the lock for service work; the store does not expire such a remote session.
"""True while a request holds the lock for service work, or the client holds its remote session channel open.
A request can run for longer than the TTL, and expiry would remove the cache directory
that the worker thread still writes to.
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()
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."""
@@ -177,8 +185,7 @@ class SessionStore:
)
log.warning(f"Max sessions reached ({max_sessions}), evicting oldest of the busiest key: {oldest_id}")
evicted = self._sessions.pop(oldest_id)
if evicted.input_bridge:
evicted.input_bridge.cancel()
evicted.end()
evicted_tag = evicted.cache_tag
_publish("delete", evicted, "evicted")
_schedule_pending_reload(evicted.service_tag)
@@ -211,6 +218,7 @@ class SessionStore:
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:
@@ -233,8 +241,7 @@ class SessionStore:
entry = self._sessions.pop(session_id, None)
if not entry:
return False
if entry.input_bridge:
entry.input_bridge.cancel()
entry.end()
_publish("delete", entry, "closed")
log.info(f"Deleted session {sanitize_log(session_id)}")
_schedule_pending_reload(entry.service_tag)
@@ -259,8 +266,7 @@ class SessionStore:
cache_tags: list[Optional[str]] = []
for sid in expired:
entry = self._sessions.pop(sid)
if entry.input_bridge:
entry.input_bridge.cancel()
entry.end()
cache_tags.append(entry.cache_tag)
_publish("delete", entry, "expired")
ended_tags.add(entry.service_tag)
@@ -294,11 +300,10 @@ class SessionStore:
self._cleanup_task = None
async def cancel_all_bridges(self) -> None:
"""Cancel all active input bridges (called on server shutdown)."""
"""Cancel all active input bridges and close every remote session channel (called on server shutdown)."""
async with self._lock:
for entry in self._sessions.values():
if entry.input_bridge:
entry.input_bridge.cancel()
entry.end()
count = len(self._sessions)
if count:
log.info(f"Cancelled bridges for {count} active session(s)")
@@ -357,11 +362,14 @@ class SessionStore:
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: