feat(remote): end a remote session when its client is gone

This commit is contained in:
imSp4rky
2026-11-30 17:23:35 -07:00
parent e813737506
commit ffe812f054
13 changed files with 747 additions and 53 deletions
+549
View File
@@ -0,0 +1,549 @@
"""How long a remote session stays without a sign of its client: the close of its channel, its requests, its create.
The clients are real ones, and the silence is a moved clock: the limits are the ones of the server.
"""
from __future__ import annotations
import asyncio
import contextlib
import math
import subprocess
import time
import uuid
from collections.abc import Callable, Iterator
from pathlib import Path
from threading import Event
from types import SimpleNamespace
from typing import Any
import aiohttp
import pytest
import requests
from aiohttp import web
from tests.remote.unit.test_remote_loopback import server # noqa: F401
from tests.remote.unit.test_remote_loopback import (
CODE,
KEY,
OTHER_KEY,
StubService,
gate_channel,
make_client,
on_loop,
)
from tests.remote.unit.test_session_lifetime import ( # noqa: F401
DEADLINE,
client,
create,
delete,
in_thread,
logins,
sessions,
wait_authenticated,
)
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,
FIRST_CONTACT_LIMIT,
LEFT_LIMIT,
ClientPresence,
ClientState,
)
from unshackle.core.api.input_bridge import AUTH_INPUT_TIMEOUT, InputBridge
from unshackle.core.api.session_store import SessionEntry, SessionStore
from unshackle.core.config import config
from unshackle.core.remote_channel import CDM_CLOSE_TIMEOUT
from unshackle.core.remote_lifetime import END_TIMEOUT
from unshackle.core.remote_protocol import (
CHANNEL_ROUTE,
CHANNEL_SESSION_GONE,
LOGS_ROUTE,
PROMPT_ROUTE,
SESSION_CREATE_ROUTE,
SESSION_ROUTE,
TITLES_ROUTE,
APIErrorCode,
AuthStatus,
)
from unshackle.core.remote_service import PROBE_TIMEOUT
from unshackle.core.tunnel import HEARTBEAT
pytestmark = pytest.mark.unit
TTL = 300
Start = Callable[..., subprocess.Popen[str]]
@pytest.fixture(autouse=True)
def ttl(server: SimpleNamespace, monkeypatch: pytest.MonkeyPatch) -> None: # noqa: F811
monkeypatch.setitem(config.serve, "session_ttl", TTL)
def silent_for(entry: SessionEntry, seconds: float) -> None:
entry.presence.seen_at = time.monotonic() - seconds
def sweep(server: SimpleNamespace) -> int: # noqa: F811
return on_loop(server, session_store.get_session_store().cleanup_expired())
def ends_after(server: SimpleNamespace, entry: SessionEntry, limit: float) -> bool: # noqa: F811
"""Whether the sweep keeps the remote session just before *limit* seconds of silence, and ends it just after."""
silent_for(entry, limit - 5)
kept = sweep(server) == 0 and sessions() == [entry]
silent_for(entry, limit + 1)
return kept and sweep(server) == 1 and sessions() == []
def stays(server: SimpleNamespace, entry: SessionEntry) -> bool: # noqa: F811
silent_for(entry, 10 * AUTH_INPUT_TIMEOUT)
return sweep(server) == 0
def logged_in(entry: SessionEntry) -> bool:
return wait_until(lambda: entry.auth_status is AuthStatus.AUTHENTICATED, DEADLINE)
def store_token(entry: SessionEntry) -> Path:
"""Write a login cache file on the server, and return its directory."""
stored = config.directories.cache / str(entry.cache_tag) / "token.json"
stored.parent.mkdir(parents=True)
stored.write_text('"EXAMPLE"', encoding="utf-8")
return stored.parent
def get(server: SimpleNamespace, route: str, entry: SessionEntry, key: str = KEY) -> requests.Response: # noqa: F811
url = server.url + route.format(session_id=entry.session_id)
return requests.get(url, headers={"X-Secret-Key": key}, timeout=DEADLINE)
def state_is(entry: SessionEntry, state: ClientState) -> bool:
return wait_until(lambda: entry.presence.state is state, DEADLINE)
@pytest.fixture
def killed(server: SimpleNamespace, client: Start) -> Callable[[], SessionEntry]: # noqa: F811
"""Start a real client and kill it when its channel is attached; the result is its remote session."""
def run(logs_in: bool = True, before: Callable[[SessionEntry], Any] = lambda entry: None) -> SessionEntry:
process = client(server.url)
if logs_in:
wait_authenticated(process)
assert wait_until(lambda: any(s.channel.attached for s in sessions()), DEADLINE)
(entry,) = sessions()
assert stays(server, entry)
before(entry)
process.kill()
assert state_is(entry, ClientState.AWAY)
return entry
return run
def test_the_sweep_ends_the_session_of_a_killed_client_at_the_away_limit(
server: SimpleNamespace, # noqa: F811
logins: list[Any], # noqa: F811
killed: Callable[..., SessionEntry],
monkeypatch: pytest.MonkeyPatch,
) -> None:
assert session_store.SWEEP_INTERVAL <= 5
monkeypatch.setattr(session_store, "SWEEP_INTERVAL", 0.02)
entry = killed()
directory = store_token(entry)
on_loop(server, session_store.get_session_store().start_cleanup_loop())
silent_for(entry, AWAY_LIMIT - 5)
assert not wait_until(lambda: sessions() == [], 0.5)
silent_for(entry, AWAY_LIMIT + 1)
assert wait_until(lambda: sessions() == [] and not directory.exists(), DEADLINE)
def test_the_login_of_a_killed_client_stops_at_the_away_limit(
server: SimpleNamespace, # noqa: F811
killed: Callable[..., SessionEntry],
monkeypatch: pytest.MonkeyPatch,
) -> None:
stopped = Event()
def wait_for_approval(stub: StubService, cookies: Any, credential: Any) -> None:
try:
while not stopped.wait(0.01):
stub._input_bridge.ensure_active()
finally:
stopped.set()
monkeypatch.setattr(StubService, "authenticate", wait_for_approval)
entry = killed(logs_in=False)
assert not stopped.is_set()
assert ends_after(server, entry, AWAY_LIMIT)
assert stopped.wait(DEADLINE)
assert wait_until(lambda: not session_store.get_session_store()._logins, DEADLINE)
def test_a_request_of_a_killed_client_does_not_keep_its_session(
server: SimpleNamespace, # noqa: F811
logins: list[Any], # noqa: F811
killed: Callable[..., SessionEntry],
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""The request holds the lock, and its end is no sign of the client that asked for it."""
release = Event()
monkeypatch.setitem(StubService.hooks, "titles", lambda stub: release.wait(DEADLINE))
events: list[str] = []
monkeypatch.setattr(session_store, "_publish", lambda action, *a, **k: events.append(action))
replies: list[Any] = []
def ask(entry: SessionEntry) -> None:
replies.append(in_thread(lambda: get(server, TITLES_ROUTE, entry)))
assert wait_until(entry.lock.locked, DEADLINE)
try:
entry = killed(before=ask)
assert entry.lock.locked()
assert ends_after(server, entry, AWAY_LIMIT)
with pytest.raises(RuntimeError, match="cancelled"):
entry.input_bridge.ensure_active() # type: ignore[union-attr]
finally:
release.set()
assert replies[0]().status_code == 200
assert entry.presence.silence > AWAY_LIMIT
assert events[-1] == "delete"
def test_a_request_that_waits_for_the_lock_does_not_start_after_the_end(
server: SimpleNamespace, # noqa: F811
logins: list[Any], # noqa: F811
) -> None:
release = Event()
started: list[StubService] = []
StubService.hooks["titles"] = lambda stub: (started.append(stub), release.wait(DEADLINE)) and None
session_id = str(uuid.uuid4())
assert create(server.url, session_id).status_code == 200
(entry,) = sessions()
assert logged_in(entry)
try:
first = in_thread(lambda: get(server, TITLES_ROUTE, entry))
assert wait_until(lambda: len(started) == 1, DEADLINE)
second = in_thread(lambda: get(server, TITLES_ROUTE, entry))
assert wait_until(lambda: bool(entry.lock._waiters), DEADLINE)
on_loop(server, session_store.get_session_store().delete(session_id))
finally:
release.set()
assert first().status_code == 200
assert second().json()["error_code"] == APIErrorCode.SESSION_NOT_FOUND
assert len(started) == 1
@pytest.mark.parametrize("route", [SESSION_ROUTE, PROMPT_ROUTE, LOGS_ROUTE])
def test_the_polls_of_a_client_without_its_channel_keep_its_session_during_a_long_request(
server: SimpleNamespace, # noqa: F811
logins: list[Any], # noqa: F811
monkeypatch: pytest.MonkeyPatch,
route: str,
) -> None:
refuse, release = gate_channel(monkeypatch), Event()
monkeypatch.setitem(StubService.hooks, "titles", lambda stub: release.wait(DEADLINE))
service = make_client(server.url)
try:
service.authenticate()
(entry,) = sessions()
assert state_is(entry, ClientState.PRESENT)
listing = in_thread(service.get_titles)
assert wait_until(entry.lock.locked, DEADLINE)
refuse.set()
on_loop(server, entry.channel.ws.close()) # type: ignore[union-attr]
assert state_is(entry, ClientState.AWAY), "a close that the server starts is not the client's"
for _ in range(3):
silent_for(entry, AWAY_LIMIT - 5)
assert get(server, route, entry).ok and entry.lock.locked()
assert entry.presence.silence < AWAY_LIMIT / 2 and entry.presence.state is ClientState.AWAY
assert sweep(server) == 0
release.set()
assert len(listing()) == 3
finally:
release.set()
service.close()
def test_a_delete_after_the_close_of_the_channel_returns_the_login_cache(
server: SimpleNamespace, # noqa: F811
logins: list[Any], # noqa: F811
) -> None:
service = make_client(server.url)
service.authenticate()
(entry,) = sessions()
assert state_is(entry, ClientState.PRESENT)
store_token(entry)
service.lifetime.close_channel()
assert state_is(entry, ClientState.LEFT)
silent_for(entry, LEFT_LIMIT - 5)
assert sweep(server) == 0
service.close()
assert sessions() == []
assert (config.directories.cache / "EXAMPLE" / "token.json").exists()
def test_a_session_ends_when_no_delete_follows_the_close_of_the_channel(
server: SimpleNamespace, # noqa: F811
logins: list[Any], # noqa: F811
) -> None:
service = make_client(server.url)
service.authenticate()
(entry,) = sessions()
assert state_is(entry, ClientState.PRESENT)
service.lifetime.close_channel()
assert state_is(entry, ClientState.LEFT)
assert ends_after(server, entry, LEFT_LIMIT)
service.close()
@contextlib.contextmanager
def half_open_gateway(server: SimpleNamespace) -> Iterator[str]: # noqa: F811
"""A gateway that passes the channel upgrade to the server, then drops it and answers the client 502."""
async def forward(request: web.Request) -> web.StreamResponse:
async with aiohttp.ClientSession(auto_decompress=False) as http:
headers = {k: v for k, v in request.headers.items() if k.startswith("X-") or k == "Content-Type"}
if request.path.endswith("/channel"):
async with http.ws_connect(server.url + request.path, headers=headers) as ws:
await ws.receive()
ws._response.connection.transport.abort() # type: ignore[union-attr]
return web.Response(status=502)
url, body = server.url + request.path_qs, await request.read()
async with http.request(request.method, url, headers=headers, data=body) as reply:
return web.Response(status=reply.status, body=await reply.read(), content_type="application/json")
async def start() -> web.AppRunner:
app = web.Application()
app.router.add_route("*", "/{path:.*}", forward)
runner = web.AppRunner(app)
await runner.setup()
await web.TCPSite(runner, "127.0.0.1", 0).start()
return runner
runner = on_loop(server, start())
try:
yield f"http://127.0.0.1:{runner.addresses[0][1]}"
finally:
on_loop(server, runner.cleanup())
def test_a_user_who_types_a_code_keeps_the_session_that_the_channel_failed_to_open(
server: SimpleNamespace, # noqa: F811
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""The server saw a channel and its loss, and the client polls: it must do so while its user types."""
typing, typed = Event(), Event()
with half_open_gateway(server) as url:
service = make_client(url)
def ask(prompt: str, qr: object = None) -> str:
typing.set()
assert typed.wait(DEADLINE)
return CODE
service._input_bridge = SimpleNamespace(request_input=ask)
monkeypatch.setitem(config.serve, "session_ttl", 3)
login = in_thread(service.authenticate)
try:
assert typing.wait(DEADLINE)
(entry,) = sessions()
assert entry.presence.state is ClientState.AWAY
silent_for(entry, AWAY_LIMIT - 5)
assert wait_until(lambda: entry.presence.silence < AWAY_LIMIT / 2, DEADLINE), "the client does not poll"
typed.set()
assert login() is None
finally:
typed.set()
service.close()
Socket = aiohttp.ClientWebSocketResponse
@pytest.fixture
def channel(server: SimpleNamespace, logins: list[Any]) -> Callable[..., None]: # noqa: F811
"""Run a check with real client sockets on the channel of one remote session, off the loop of the server."""
def run(check: Callable[[SessionEntry, Callable[[], Any]], Any]) -> None:
assert create(server.url, str(uuid.uuid4())).status_code == 200
(entry,) = sessions()
url = server.url + CHANNEL_ROUTE.format(session_id=entry.session_id)
async def main() -> None:
async with aiohttp.ClientSession(headers={"X-Secret-Key": KEY}) as http:
await check(entry, lambda: http.ws_connect(url))
asyncio.run(asyncio.wait_for(main(), DEADLINE))
return run
async def close_code(socket: Socket) -> Any:
"""Read until the server closes the socket; its close code."""
while (msg := await socket.receive()).type is aiohttp.WSMsgType.TEXT:
pass
return msg.data
async def a_state_is(entry: SessionEntry, state: ClientState) -> bool:
return await asyncio.to_thread(state_is, entry, state)
@pytest.mark.parametrize(
("close", "state"),
[
(lambda ws: ws.close(code=1000), ClientState.LEFT),
(lambda ws: ws.close(code=1001), ClientState.AWAY),
(lambda ws: ws.send_frame(b"", aiohttp.WSMsgType.CLOSE), ClientState.AWAY),
],
ids=["1000", "1001", "no-code"],
)
def test_only_a_close_with_1000_of_the_client_is_a_leave(
channel: Callable[..., None], close: Callable[[Socket], Any], state: ClientState
) -> None:
async def check(entry: SessionEntry, connect: Callable[[], Any]) -> None:
socket = await connect()
assert await a_state_is(entry, ClientState.PRESENT)
await close(socket)
assert await a_state_is(entry, state)
await socket.close()
channel(check)
def test_a_replaced_socket_does_not_mark_the_new_one_away(
server: SimpleNamespace, # noqa: F811
channel: Callable[..., None],
) -> None:
async def check(entry: SessionEntry, connect: Callable[[], Any]) -> None:
first = await connect()
assert await a_state_is(entry, ClientState.PRESENT)
old = entry.channel.ws
second = await connect()
assert await close_code(first) == 1000
await first.close()
assert await asyncio.to_thread(wait_until, lambda: old is not None and old.close_code is not None, DEADLINE)
assert entry.presence.state is ClientState.PRESENT
assert await asyncio.to_thread(stays, server, entry)
await second.close()
assert await a_state_is(entry, ClientState.LEFT)
channel(check)
def test_the_end_of_the_session_is_no_leave(server: SimpleNamespace, channel: Callable[..., None]) -> None: # noqa: F811
async def check(entry: SessionEntry, connect: Callable[[], Any]) -> None:
socket = await connect()
assert await a_state_is(entry, ClientState.PRESENT)
assert (await asyncio.to_thread(delete, server.url, entry.session_id)).ok
assert await close_code(socket) == CHANNEL_SESSION_GONE
assert await a_state_is(entry, ClientState.AWAY)
channel(check)
def test_a_new_channel_or_a_request_after_the_leave_is_a_client_that_still_works(
server: SimpleNamespace, # noqa: F811
channel: Callable[..., None],
) -> None:
"""A client that gives up on a slow channel closes it with 1000 and then polls."""
async def check(entry: SessionEntry, connect: Callable[[], Any]) -> None:
await (await connect()).close()
assert await a_state_is(entry, ClientState.LEFT)
socket = await connect()
assert await a_state_is(entry, ClientState.PRESENT)
await socket.close()
assert await a_state_is(entry, ClientState.LEFT)
assert (await asyncio.to_thread(get, server, SESSION_ROUTE, entry, OTHER_KEY)).status_code == 403
assert entry.presence.state is ClientState.LEFT
assert (await asyncio.to_thread(get, server, SESSION_ROUTE, entry)).ok
assert entry.presence.state is ClientState.AWAY
assert await asyncio.to_thread(ends_after, server, entry, AWAY_LIMIT)
channel(check)
def test_a_client_that_never_comes_back_for_its_session_loses_it(
server: SimpleNamespace, # noqa: F811
logins: list[Any], # noqa: F811
) -> None:
assert create(server.url, str(uuid.uuid4())).status_code == 200
(entry,) = sessions()
assert get(server, SESSION_ROUTE, entry, OTHER_KEY).status_code == 403
assert ends_after(server, entry, FIRST_CONTACT_LIMIT)
@pytest.mark.parametrize("client_kind", ["polls", "no-id"])
def test_a_client_without_a_channel_keeps_the_ttl(
server: SimpleNamespace, # noqa: F811
logins: list[Any], # noqa: F811
client_kind: str,
) -> None:
if client_kind == "polls":
assert create(server.url, str(uuid.uuid4())).status_code == 200
(entry,) = sessions()
assert get(server, PROMPT_ROUTE, entry).ok
else:
body = {"service": "EXAMPLE", "title_id": "example-1"}
headers = {"X-Secret-Key": KEY}
assert requests.post(server.url + SESSION_CREATE_ROUTE, json=body, headers=headers, timeout=DEADLINE).ok
(entry,) = sessions()
assert logged_in(entry) and stays(server, entry)
entry.idle_since = time.monotonic() - (TTL - 5)
assert sweep(server) == 0
entry.idle_since = time.monotonic() - (TTL + 1)
assert sweep(server) == 1
@pytest.mark.parametrize("busy", [False, True], ids=["idle", "busy"])
@pytest.mark.parametrize("ttl_seconds", [30, 100, 300, 1200, 3600])
async def test_no_session_stays_for_longer_than_its_ttl_lets_it(
monkeypatch: pytest.MonkeyPatch, ttl_seconds: int, busy: bool
) -> None:
"""Work for a client keeps its session past a short TTL, as before, until the client is gone."""
monkeypatch.setitem(config.serve, "session_ttl", ttl_seconds)
store = SessionStore()
entry = await store.create("EXAMPLE", None, input_bridge=InputBridge())
entry.input_bridge.login_status = AuthStatus.AUTHENTICATED # type: ignore[union-attr]
entry.presence.detached(left=False)
if busy:
await entry.lock.acquire()
limit = max(180, ttl_seconds / 2) if busy else min(ttl_seconds, max(180, ttl_seconds / 2))
for silence, count in ((limit - 5, 0), (limit + 1, 1)):
silent_for(entry, silence)
entry.idle_since = entry.presence.seen_at
assert await store.cleanup_expired() == count
def test_each_limit_is_longer_than_the_silence_of_a_client_that_still_works() -> None:
"""The numbers of the client: a ping is lost, the DELETE is late, or the create reply never arrives."""
detection = HEARTBEAT * 1.5
delete_arrives = 5 + CDM_CLOSE_TIMEOUT + 3 * END_TIMEOUT
reconnects = sum((1, 2, 4, 8, 16, 30))
assert 120 + END_TIMEOUT < FIRST_CONTACT_LIMIT <= 150
assert detection + PROBE_TIMEOUT + 100 < AWAY_LIMIT <= 180
assert max(delete_arrives, reconnects) < LEFT_LIMIT <= 90
presence = ClientPresence()
presence.detached(left=False)
for ttl_seconds in range(1, 7200):
assert presence.limit(ttl_seconds) > ttl_seconds / 3 + PROBE_TIMEOUT
def test_a_client_that_is_present_has_no_limit() -> None:
presence = ClientPresence(named=True)
presence.attached()
assert presence.limit(TTL) == math.inf
@pytest.mark.parametrize("left", [True, False])
def test_the_loss_of_the_channel_restarts_the_clock(left: bool) -> None:
presence = ClientPresence()
presence.attached()
presence.seen_at -= 10 * TTL
presence.detached(left)
assert presence.silence < 5 and not presence.gone(TTL)