fix(remote): end remote session work when the server stops, and leave no session cache behind

This commit is contained in:
imSp4rky
2026-11-30 19:21:21 -07:00
parent bafce963d3
commit c41d8ec3cf
6 changed files with 504 additions and 25 deletions
+18 -1
View File
@@ -58,16 +58,33 @@ class _MaskAccessKey(logging.Filter):
def _install_session_store(app: web.Application) -> None:
"""Start the remote session store's idle sweep with the app and close the store on cleanup."""
"""Start the remote session store's idle sweep with the app and close the store on cleanup.
aiohttp raises on each SIGTERM, and a second one would end the cleanup before it closes the store. After its cleanup
it restores the default action, and so does the exit of Python for each Python handler: one more SIGTERM would then
kill a server that has ended well. A loop on Windows takes no handler.
"""
from unshackle.core.api.session_store import get_session_store
session_store = get_session_store()
stopping = False
def stop_once() -> None:
nonlocal stopping
if not stopping:
stopping = True
raise web.GracefulExit
async def start(_app: web.Application) -> None:
with suppress(NotImplementedError):
asyncio.get_running_loop().add_signal_handler(signal.SIGTERM, stop_once)
await session_store.start_cleanup_loop()
async def stop(_app: web.Application) -> None:
await session_store.close()
if stopping:
asyncio.get_running_loop().remove_signal_handler(signal.SIGTERM)
signal.signal(signal.SIGTERM, signal.SIG_IGN)
app.on_startup.append(start)
app.on_cleanup.append(stop)
+14 -12
View File
@@ -53,7 +53,8 @@ class InputBridge:
"""Thread-safe bridge between the service threads and the async HTTP layer.
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.
answers through the remote session channel or the prompt routes. ``cut`` is True once a call failed because of
:meth:`cancel`: the service can go on after the error.
"""
channel: SessionChannel | None = field(default=None, init=False, repr=False)
@@ -61,11 +62,17 @@ class InputBridge:
_status: AuthStatus = field(default=AuthStatus.AUTHENTICATING, init=False)
_cancelled: bool = field(default=False, init=False, repr=False)
_lock: threading.Lock = field(default_factory=threading.Lock, init=False, repr=False)
cut: bool = field(default=False, init=False, repr=False)
def _require_active(self) -> None:
"""Raise once the server cancelled the bridge; call it with the lock held."""
if self._cancelled:
self.cut = True
raise RuntimeError("Session was cancelled")
def _open(self, prompt: str, cdm_call: dict[str, Any] | None = None, qr: str | None = 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")
self._require_active()
ask = Ask(uuid.uuid4().hex, prompt, cdm_call, qr)
if self.channel is not None and self.channel.offer(ask):
ask.owner = CHANNEL
@@ -85,8 +92,7 @@ class InputBridge:
"""
with self._lock:
if self._status == AuthStatus.AUTHENTICATED and not (self.channel and self.channel.attached):
if self._cancelled:
raise RuntimeError("Session was cancelled")
self._require_active()
raise RuntimeError(f"Remote mode cannot relay a prompt after authentication: {prompt}")
ask = self._open(prompt, qr=qr)
try:
@@ -94,8 +100,7 @@ class InputBridge:
if not ask.answered.wait(timeout=timeout):
raise coded(TimeoutError(f"No client response for prompt within {timeout}s"), APIErrorCode.AUTH_FAILED)
with self._lock:
if self._cancelled:
raise RuntimeError("Session was cancelled")
self._require_active()
if ask.error is not None:
raise RuntimeError(f"The client could not answer the prompt: {ask.error}")
return ask.response or ""
@@ -118,13 +123,11 @@ class InputBridge:
picked_up = ask.picked_up.wait(timeout=pickup)
answered = picked_up and ask.answered.wait(timeout=timeout)
with self._lock:
self._require_active()
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:
raise TimeoutError(f"No client fetched the CDM call within {pickup:.0f}s, so none is listening")
if not answered:
@@ -232,8 +235,7 @@ class InputBridge:
def ensure_active(self) -> None:
"""Raise RuntimeError once the server cancelled the bridge, so a login loop stops."""
with self._lock:
if self._cancelled:
raise RuntimeError("Session was cancelled")
self._require_active()
@property
def status(self) -> AuthStatus:
+2 -2
View File
@@ -180,8 +180,8 @@ def receive(text: str, bridge: Any) -> None:
async def close_channels(_: web.Application) -> None:
"""End every attached channel at server shutdown, so no WebSocket holds the shutdown open."""
"""End the work of every remote session at server shutdown, so no WebSocket or service thread holds it open."""
from unshackle.core.api.session_store import get_session_store
for entry in get_session_store().list():
entry.channel.end()
entry.end()
+21 -4
View File
@@ -105,11 +105,21 @@ class SessionEntry:
@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."""
"""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)
yield
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."""
@@ -408,13 +418,20 @@ class SessionStore:
"""
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 login task until it ends, so that close() can wait for it."""
"""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)
@@ -435,7 +452,7 @@ class SessionStore:
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.
"""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.