From c41d8ec3cfe32e7b99b169ea917b0a1520a38aba Mon Sep 17 00:00:00 2001 From: imSp4rky Date: Mon, 30 Nov 2026 19:21:21 -0700 Subject: [PATCH] fix(remote): end remote session work when the server stops, and leave no session cache behind --- docs/dev/rest-api/remote-sessions.md | 18 +- tests/remote/unit/test_serve_stop.py | 437 ++++++++++++++++++++++++++ unshackle/commands/serve.py | 19 +- unshackle/core/api/input_bridge.py | 26 +- unshackle/core/api/session_channel.py | 4 +- unshackle/core/api/session_store.py | 25 +- 6 files changed, 504 insertions(+), 25 deletions(-) create mode 100644 tests/remote/unit/test_serve_stop.py diff --git a/docs/dev/rest-api/remote-sessions.md b/docs/dev/rest-api/remote-sessions.md index c8755b7d..7283caca 100644 --- a/docs/dev/rest-api/remote-sessions.md +++ b/docs/dev/rest-api/remote-sessions.md @@ -633,12 +633,18 @@ Source: `unshackle/core/api/session_store.py`. A singleton you get from - **Removal.** Eviction, expiry and `delete()` end the remote session the same way: they cancel its `InputBridge`, close its channel, send the `delete` dashboard event, schedule a staged service reload and delete its cache directory (pruning empty parent dirs up to, but not including, the cache root). A request - that waits for the remote session then answers `SESSION_NOT_FOUND` and starts no service code. -- **`track_login(task)`** keeps each login task of `session/create` until it ends. -- The server calls **`close()`** on shutdown. It ends each open remote session, which - unblocks any waiting auth threads, and deletes the cache directory of each one. It sends no dashboard event - and schedules no reload. It then waits up to 5 seconds for each login that still runs, and stops the sweep. - A login that ends after the shutdown deletes its cache directory again. + that waits for the remote session then answers `SESSION_NOT_FOUND` and starts no service code. So does a request + whose service code waits on the client for a prompt or a CDM call, whatever that code does next. A service thread + that runs can still write to the cache directory, so a task deletes the directory again after the last request. +- **`track_login(task)`** keeps each login task of `session/create`, and each task that deletes a cache directory + again, until it ends. +- **Shutdown.** First, `close_channels()` cancels each `InputBridge` and closes each channel, so no request waits + for a client while the server waits for its requests. Then the server calls **`close()`**. It ends each open + remote session and deletes the cache directory of each one. It sends no dashboard event + and schedules no reload. It then waits up to 5 seconds for each tracked task that still runs, and stops the sweep. + Within that time, a login that ends deletes its cache directory again. +- **Signals.** The first `SIGTERM` starts the shutdown, and the server ignores each later one. A second Ctrl+C forces + the end. On Windows only Ctrl+C starts the shutdown. `SessionEntry` fields: diff --git a/tests/remote/unit/test_serve_stop.py b/tests/remote/unit/test_serve_stop.py new file mode 100644 index 00000000..5999d982 --- /dev/null +++ b/tests/remote/unit/test_serve_stop.py @@ -0,0 +1,437 @@ +"""What ends with a remote session: the work of a server that stops, and the cache that a service thread writes late. + +A stop is a signal to a real ``serve`` process. The sessions of the late writes end on a server in this process. +""" + +from __future__ import annotations + +import asyncio +import contextlib +import json +import signal +import time +import uuid +from collections.abc import Callable, Iterator +from itertools import count +from pathlib import Path +from threading import Event +from types import SimpleNamespace +from typing import Any + +import aiohttp +import pytest +from aiohttp import web + +from tests.remote.unit.test_client_presence import close_code, get, logged_in, silent_for, store_token, sweep +from tests.remote.unit.test_process_exit import BOUND, posix, run, settings # noqa: F401 +from tests.remote.unit.test_remote_loopback import KEY, StubService, on_loop, server # noqa: F401 +from tests.remote.unit.test_remote_service_helpers import blob +from tests.remote.unit.test_session_lifetime import ( # noqa: F401 + DEADLINE, + create, + delete, + error_code, + in_thread, + logins, + sessions, +) +from tests.remote.unit.test_tunnel import wait_until +from unshackle.core.api import session_store +from unshackle.core.api.client_presence import AWAY_LIMIT +from unshackle.core.api.events import bus +from unshackle.core.api.session_channel import close_channels +from unshackle.core.api.session_store import SessionEntry, SessionStore +from unshackle.core.config import config +from unshackle.core.remote_protocol import ( + CHANNEL_ROUTE, + CHANNEL_SESSION_GONE, + TITLES_ROUTE, + APIErrorCode, + AuthStatus, +) + +pytestmark = pytest.mark.unit + +SERVES = { + "api-only": ["--api-only", "--remote-only"], + "with-cdm": ["--no-widevine", "--no-playready"], +} + +SERVER = """ +import asyncio, json, os, sys, time +from threading import Semaphore +import pytest +from aiohttp import web +from unshackle.core.config import config +config.__init__(**json.loads(sys.argv[1])) +from tests.remote.sessions import stub_service_build +from tests.remote.unit.test_remote_loopback import StubService +from unshackle.commands.serve import serve +from unshackle.core import services +from unshackle.core.api import events, handlers, routes +work = sys.argv[2] + +def say(*line): + print(*line, flush=True) + +class Stub(StubService): + def ask(self, part): + if part != work: + return + try: + if part == "cdm": + self._input_bridge.request_cdm({"op": "x"}) + else: + self._input_bridge.request_input("Enter the EXAMPLE code") + except RuntimeError as e: + say("released", part, e) + raise + + def authenticate(self, cookies, credential): + self.ask("login") + + def get_titles(self): + self.ask("prompt") + self.ask("cdm") + return super().get_titles() + +start, publish = web.TCPSite.start, events.bus.publish + +async def started(site): + await start(site) + say("port", site._server.sockets[0].getsockname()[1]) + +def published(kind, data): + if kind == "session": + say("event", data["action"]) + publish(kind, data) + +async def hold(app): + say("stopping") + while work == "hold" and not (config.directories.temp / "release").exists(): + await asyncio.sleep(0.01) + +web.TCPSite.start = started +routes.close_event_streams = hold +events.bus.publish = published +patch = pytest.MonkeyPatch() +patch.setattr(services, "load_all", lambda: None) +patch.setattr(handlers, "validate_service", lambda service, request=None: service) +patch.setattr(handlers, "resolve_handler_proxy", lambda *args: (None, [])) +patch.setattr(handlers, "server_account_for", lambda *args: False) +patch.setattr(handlers.Services, "load", lambda service: Stub) +stub_service_build(patch, lambda: Stub(Semaphore(0))) + +class Leave: + def __del__(self, held=work == "leave", path=str(config.directories.temp / "release"), write=os.write, + access=os.access, sleep=time.sleep): + write(1, b"leaving\\n") + while held and not access(path, 0): + sleep(0.01) + +sys.leave = Leave() +serve(args=["-q", "-h", "127.0.0.1", "-p", "0", *sys.argv[3:]]) +""" + + +class Serve: + """A ``serve`` process whose output goes to a file.""" + + def __init__(self, run: Callable[..., Any], path: Path, work: str, options: list[str]) -> None: # noqa: F811 + path.mkdir() + self.sessions = path / "cache" / "_sessions" + self.log = path / "serve.log" + self.release = path / "temp" / "release" + data = {"serve": {"api_secret": KEY}, "update_checks": False, "directories": settings("", path)["directories"]} + with self.log.open("w", encoding="utf-8") as log: + self.process = run("-c", SERVER, json.dumps(data), work, *options, stdout=log) + assert wait_until(lambda: "port " in self.output or self.process.poll() is not None, DEADLINE) + assert self.process.poll() is None, self.output + self.url = f"http://127.0.0.1:{self.output.split('port ')[1].split()[0]}" + + @property + def output(self) -> str: + return self.log.read_text(encoding="utf-8", errors="replace") + + def send(self, *signals: signal.Signals) -> None: + for one in signals: + self.process.send_signal(one) + + def says(self, line: str) -> bool: + return wait_until(lambda: line in self.output, DEADLINE) + + def ended_well(self) -> None: + """The process ends at once with code 0, has removed each session cache, and logs no unhandled exception.""" + since = time.monotonic() + assert self.process.wait(DEADLINE) == 0, self.output + assert time.monotonic() - since < BOUND + assert not list(self.sessions.rglob("*")), self.output + for trace in ("nhandled exception", "InvalidStateError", "never retrieved", "was destroyed"): + assert trace not in self.output + + +@pytest.fixture +def serve(tmp_path: Path, run: Callable[..., Any]) -> Callable[..., Serve]: # noqa: F811 + paths = (tmp_path / str(n) for n in count()) + return lambda work="", options=SERVES["api-only"]: Serve(run, next(paths), work, options) + + +def session_id() -> str: + return str(uuid.uuid4()) + + +async def opened(http: aiohttp.ClientSession, running: Serve, until: str) -> tuple[str, Any]: + """A remote session with a login cache on the server, and its channel once a message of the type *until* came.""" + sid = session_id() + reply = await asyncio.to_thread(create, running.url, sid, cache={"token": blob('"EXAMPLE"')}) + assert reply.status_code == 200, reply.text + socket = await http.ws_connect(running.url + CHANNEL_ROUTE.format(session_id=sid)) + await read_until(socket, until) + return sid, socket + + +async def read_until(socket: Any, kind: str) -> None: + while (message := await socket.receive_json(timeout=DEADLINE)).get("type") != kind: + pass + if kind == "status": + while message["status"] != AuthStatus.AUTHENTICATED: + message = await socket.receive_json(timeout=DEADLINE) + + +@posix +@pytest.mark.parametrize("work", ["login", "prompt", "cdm"]) +async def test_a_stop_ends_the_work_that_waits_for_its_client(serve: Callable[..., Serve], work: str) -> None: + """The refusal of the open request, and the close code of the channel, make the client open a new session.""" + running = serve(work) + async with aiohttp.ClientSession(headers={"X-Secret-Key": KEY}) as http: + sid, socket = await opened(http, running, "prompt" if work == "login" else "status") + titles = None + if work != "login": + titles = asyncio.create_task(http.get(running.url + TITLES_ROUTE.format(session_id=sid))) + await read_until(socket, "cdm_call" if work == "cdm" else "prompt") + assert list(running.sessions.rglob("token.json")) + closed = asyncio.create_task(close_code(socket)) + running.send(signal.SIGTERM) + await asyncio.to_thread(running.ended_well) + assert await closed == CHANNEL_SESSION_GONE + if titles: + reply = await titles + assert (reply.status, (await reply.json())["error_code"]) == (404, APIErrorCode.SESSION_NOT_FOUND) + assert f"released {work} Session was cancelled" in running.output + assert "event delete" not in running.output + assert "Closed 1 remote session(s) at shutdown" in running.output + + +@posix +@pytest.mark.parametrize("options", SERVES.values(), ids=SERVES) +async def test_two_sigterms_at_once_do_not_cut_the_stop(serve: Callable[..., Serve], options: list[str]) -> None: + for _ in range(3): + running = serve(options=options) + async with aiohttp.ClientSession(headers={"X-Secret-Key": KEY}) as http: + sockets = [(await opened(http, running, "status"))[1] for _ in range(4)] + closed = [asyncio.create_task(close_code(socket)) for socket in sockets] + running.send(signal.SIGTERM, signal.SIGTERM) + await asyncio.to_thread(running.ended_well) + assert await asyncio.gather(*closed) == [CHANNEL_SESSION_GONE] * 4 + assert "Closed 4 remote session(s) at shutdown" in running.output + + +@posix +@pytest.mark.parametrize(("work", "line"), [("hold", "stopping"), ("leave", "leaving")], ids=["stop", "exit"]) +async def test_a_sigterm_after_the_first_does_not_cut_the_stop( + serve: Callable[..., Serve], work: str, line: str +) -> None: + running = serve(work) + async with aiohttp.ClientSession(headers={"X-Secret-Key": KEY}) as http: + await opened(http, running, "status") + running.send(signal.SIGTERM) + assert running.says(line) + running.send(signal.SIGTERM) + running.release.parent.mkdir(exist_ok=True) + running.release.touch() + await asyncio.to_thread(running.ended_well) + + +@posix +def test_a_second_ctrl_c_still_forces_the_stop(serve: Callable[..., Serve]) -> None: + running = serve("hold") + running.send(signal.SIGINT) + assert running.says("stopping") + running.send(signal.SIGINT) + assert running.process.wait(DEADLINE) == 1 + + +@pytest.fixture +def entry( + server: SimpleNamespace, # noqa: F811 + logins: list[Any], # noqa: F811 + monkeypatch: pytest.MonkeyPatch, +) -> SessionEntry: + """A remote session with a login cache.""" + monkeypatch.setitem(config.serve, "session_ttl", 300) + assert create(server.url, session_id(), cache={"token": blob('"EXAMPLE"')}).status_code == 200 + (entry,) = sessions() + assert logged_in(entry) + return entry + + +@pytest.fixture +def titles(server: SimpleNamespace, entry: SessionEntry) -> Iterator[SimpleNamespace]: # noqa: F811 + """A titles call that waits for ``release``, and then writes the login cache again.""" + held = SimpleNamespace(directory=config.directories.cache / str(entry.cache_tag), started=Event(), release=Event()) + + def write_late(stub: StubService) -> None: + held.started.set() + assert held.release.wait(DEADLINE), "the test did not release the titles" + store_token(entry) + + StubService.hooks["titles"] = write_late + held.reply = in_thread(lambda: get(server, TITLES_ROUTE, entry)) + assert held.started.wait(DEADLINE) + try: + yield held + finally: + held.release.set() + + +def end_by_delete(server: SimpleNamespace, entry: SessionEntry) -> None: # noqa: F811 + assert delete(server.url, entry.session_id).status_code == 200 + + +def end_by_eviction(server: SimpleNamespace, entry: SessionEntry) -> None: # noqa: F811 + config.serve["max_sessions"] = 1 + assert create(server.url, session_id()).status_code == 200 + + +def end_by_a_client_that_is_gone(server: SimpleNamespace, entry: SessionEntry) -> None: # noqa: F811 + entry.presence.detached(left=False) + silent_for(entry, AWAY_LIMIT + 1) + assert sweep(server) == 1 + + +def end_by_a_new_create_of_the_id(server: SimpleNamespace, entry: SessionEntry) -> None: # noqa: F811 + assert create(server.url, entry.session_id, cache={"token": blob('"EXAMPLE"')}).status_code == 200 + + +ENDS = [end_by_delete, end_by_eviction, end_by_a_client_that_is_gone, end_by_a_new_create_of_the_id] + + +@pytest.mark.parametrize("end", ENDS) +def test_a_late_write_of_a_service_thread_leaves_no_cache( + server: SimpleNamespace, # noqa: F811 + entry: SessionEntry, + titles: SimpleNamespace, + end: Callable[[SimpleNamespace, SessionEntry], None], +) -> None: + """The removal comes after the last request: one that waits behind the writer is refused and writes nothing.""" + waiting = in_thread(lambda: get(server, TITLES_ROUTE, entry)) + assert wait_until(lambda: len(entry.lock._waiters or ()) == 1, DEADLINE) + end(server, entry) + assert wait_until(lambda: not titles.directory.exists(), DEADLINE) + titles.release.set() + assert titles.reply().status_code == 200 + assert error_code(waiting()) == APIErrorCode.SESSION_NOT_FOUND + assert wait_until(lambda: not session_store.get_session_store()._logins, DEADLINE) + assert not titles.directory.exists() + if end is end_by_a_new_create_of_the_id: + (new,) = sessions() + assert (config.directories.cache / str(new.cache_tag) / "token.json").exists() + + +def test_the_dashboard_gets_one_delete_event_and_no_update_after_it( + server: SimpleNamespace, # noqa: F811 + entry: SessionEntry, + titles: SimpleNamespace, +) -> None: + """A stop ends the work before the store retires the session, so each end runs twice.""" + seq = bus.seq + on_loop(server, close_channels(web.Application())) + end_by_delete(server, entry) + titles.release.set() + assert titles.reply().status_code == 200 + actions = [e["data"]["action"] for e in bus.since(seq) if e["event"] == "session"] + assert actions.count("delete") == 1 and actions[-1] == "delete" + + +@pytest.mark.parametrize(("cache_tag", "busy"), [("_sessions/EXAMPLE", False), (None, True)], ids=["idle", "no-cache"]) +async def test_an_end_with_nothing_to_write_late_starts_no_task( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, cache_tag: str | None, busy: bool +) -> None: + monkeypatch.setattr(config.directories, "cache", tmp_path) + store = SessionStore() + entry = await store.create("EXAMPLE", None, cache_tag=cache_tag) + if busy: + await entry.lock.acquire() + assert await store.delete(entry.session_id) and not store._logins + + +async def test_the_close_waits_for_a_late_write(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(config.directories, "cache", tmp_path) + directory = tmp_path / "_sessions" / "EXAMPLE" + directory.mkdir(parents=True) + store = SessionStore() + entry = await store.create("EXAMPLE", None, cache_tag="_sessions/EXAMPLE") + await entry.lock.acquire() + closing = asyncio.create_task(store.close()) + assert await asyncio.to_thread(wait_until, lambda: not directory.exists(), DEADLINE) + directory.mkdir(parents=True) + entry.lock.release() + await asyncio.wait_for(closing, DEADLINE) + assert not directory.exists() + + +async def test_a_late_write_holds_the_close_no_longer_than_a_login( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setattr(config.directories, "cache", tmp_path) + monkeypatch.setattr(session_store, "LOGIN_WAIT", 0.05) + store = SessionStore() + entry = await store.create("EXAMPLE", None, cache_tag="_sessions/EXAMPLE") + await entry.lock.acquire() + await asyncio.wait_for(store.close(), DEADLINE) + (tmp_path / "_sessions" / "EXAMPLE").mkdir(parents=True) + entry.lock.release() + assert await asyncio.to_thread(wait_until, lambda: not (tmp_path / "_sessions").exists(), DEADLINE) + + +@pytest.mark.parametrize("error", [None, RuntimeError, SystemExit], ids=["answers", "fails", "exits"]) +@pytest.mark.parametrize(("call", "args"), [("request_input", ["code?"]), ("request_cdm", [{}]), ("ensure_active", [])]) +def test_a_request_that_the_end_cuts_is_refused( + server: SimpleNamespace, # noqa: F811 + entry: SessionEntry, + call: str, + args: list[Any], + error: type[BaseException] | None, +) -> None: + """Also when the service goes on without the answer of its client, or exits.""" + + def ask(stub: StubService) -> None: + on_loop(server, session_store.get_session_store().delete(entry.session_id)) + with contextlib.suppress(RuntimeError): + getattr(stub._input_bridge, call)(*args) + if error: + raise error(1) + + StubService.hooks["titles"] = ask + assert error_code(get(server, TITLES_ROUTE, entry)) == APIErrorCode.SESSION_NOT_FOUND + + +@pytest.mark.parametrize("ended", [True, False], ids=["ended", "open"]) +@pytest.mark.parametrize("error", [RuntimeError("EXAMPLE failed"), SystemExit(1)], ids=["error", "exit"]) +def test_an_error_of_the_service_stays_that_error( + server: SimpleNamespace, # noqa: F811 + entry: SessionEntry, + error: BaseException, + ended: bool, +) -> None: + def fail(stub: StubService) -> None: + if ended: + on_loop(server, session_store.get_session_store().delete(entry.session_id)) + raise error + + StubService.hooks["titles"] = fail + reply = get(server, TITLES_ROUTE, entry) + if isinstance(error, SystemExit): + assert error_code(reply) == APIErrorCode.SERVICE_ERROR + else: + assert error_code(reply) == APIErrorCode.INTERNAL_ERROR and "EXAMPLE failed" in reply.json()["message"] diff --git a/unshackle/commands/serve.py b/unshackle/commands/serve.py index a27f6e06..f68b476d 100644 --- a/unshackle/commands/serve.py +++ b/unshackle/commands/serve.py @@ -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) diff --git a/unshackle/core/api/input_bridge.py b/unshackle/core/api/input_bridge.py index 305d72f9..cc9486f9 100644 --- a/unshackle/core/api/input_bridge.py +++ b/unshackle/core/api/input_bridge.py @@ -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: diff --git a/unshackle/core/api/session_channel.py b/unshackle/core/api/session_channel.py index a90fe6da..930461ab 100644 --- a/unshackle/core/api/session_channel.py +++ b/unshackle/core/api/session_channel.py @@ -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() diff --git a/unshackle/core/api/session_store.py b/unshackle/core/api/session_store.py index b9939c00..946de46c 100644 --- a/unshackle/core/api/session_store.py +++ b/unshackle/core/api/session_store.py @@ -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.