fix(remote): measure the idle time of a remote session on a monotonic clock

This commit is contained in:
imSp4rky
2026-11-30 17:06:15 -07:00
parent 34a3820eb8
commit e813737506
6 changed files with 59 additions and 31 deletions
+7 -7
View File
@@ -7,7 +7,6 @@ import json
import logging
import threading
from collections.abc import Callable, Iterator
from datetime import UTC, datetime
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from threading import Event, Semaphore, Thread
@@ -160,6 +159,11 @@ def server(request: pytest.FixtureRequest, monkeypatch: pytest.MonkeyPatch, tmp_
app = web.Application(middlewares=[record, cors_middleware, no_5xx_middleware, api_key_authentication])
app["config"] = {"users": [KEY, OTHER_KEY]}
setup_routes(app, remote_only=True)
async def close_store(_: web.Application) -> None:
await session_store.get_session_store().close()
app.on_cleanup.append(close_store)
loop = asyncio.new_event_loop()
runner = web.AppRunner(app)
loop.run_until_complete(runner.setup())
@@ -220,10 +224,6 @@ def example_messages(caplog: pytest.LogCaptureFixture) -> list[str]:
return [r.getMessage() for r in caplog.records if r.name == "EXAMPLE"]
def idle_seconds(entry: Any) -> float:
return (datetime.now(UTC) - entry.last_accessed).total_seconds()
@pytest.mark.parametrize(
"server,channel",
[(True, "none"), (False, "refused"), (True, "failed")],
@@ -496,7 +496,7 @@ def test_an_open_channel_keeps_the_session_alive(server: SimpleNamespace, monkey
session_id = service._session_id
entry = store.peek(session_id)
assert wait_until(lambda: entry.channel.attached, 5)
assert wait_until(lambda: idle_seconds(entry) > 3 * ttl, 10)
assert wait_until(lambda: entry.idle_seconds > 3 * ttl, 10)
assert on_loop(server, store.cleanup_expired()) == 0
assert store.peek(session_id) is entry
assert count(server, "GET", SESSION_ROUTE, session_id) == 0
@@ -504,7 +504,7 @@ def test_an_open_channel_keeps_the_session_alive(server: SimpleNamespace, monkey
service.lifetime.close_channel()
assert wait_until(lambda: not entry.channel.attached, 5)
assert wait_until(lambda: idle_seconds(entry) > 2 * ttl, 10)
assert wait_until(lambda: entry.idle_seconds > 2 * ttl, 10)
assert on_loop(server, store.cleanup_expired()) == 1
assert store.peek(session_id) is None
assert count(server, "GET", SESSION_ROUTE, session_id) == 0
@@ -1,5 +1,6 @@
"""A per-key height cap on the server CDM hands licensing above it to the client's own device."""
import atexit
import json
import logging
from datetime import datetime
@@ -15,7 +16,7 @@ from tests.core.key_resolver import key_table, resolver
from tests.remote.key_source import CAPPED, PR_DEVICE, MemoryKeySource, one_title, remote_session
from tests.remote.sessions import launch_session, session_entry
from unshackle.commands.dl import dl
from unshackle.core import remote_channel
from unshackle.core import remote_channel, remote_lifetime
from unshackle.core.api import handlers, job_admission, key_policy, server_keys
from unshackle.core.api.errors import APIError
from unshackle.core.api.key_policy import KeyPolicy
@@ -636,7 +637,7 @@ def created(answer, monkeypatch):
svc.client = SimpleNamespace(post=lambda path, data: {"session_id": "sess", **answer})
channel = SimpleNamespace(keep_alive=lambda: None, drain_logs=lambda: None, in_flight=None)
monkeypatch.setattr(remote_channel, "open_channel", lambda service: channel)
monkeypatch.setattr("atexit.register", lambda hook: None)
monkeypatch.setattr(remote_lifetime, "atexit", SimpleNamespace(register=id, unregister=atexit.unregister))
svc.authenticate()
return svc
+9 -5
View File
@@ -3,7 +3,6 @@
from __future__ import annotations
import asyncio
import atexit
import contextlib
import signal
import subprocess
@@ -31,7 +30,7 @@ from tests.remote.unit.test_remote_loopback import (
from tests.remote.unit.test_remote_service_helpers import blob
from tests.remote.unit.test_session_reopen import SERVER, make_service
from tests.remote.unit.test_tunnel import wait_until
from unshackle.core import remote_channel, remote_service
from unshackle.core import remote_channel, remote_lifetime, remote_service
from unshackle.core.api import handlers, routes, session_store
from unshackle.core.api.download_manager import busy_services
from unshackle.core.api.session_store import SessionEntry
@@ -640,8 +639,13 @@ def test_the_end_does_not_wait_for_a_reopen(server: SimpleNamespace, logins: lis
@pytest.fixture
def exit_hooks(monkeypatch: pytest.MonkeyPatch) -> list[Any]:
hooks: list[Any] = []
monkeypatch.setattr(atexit, "register", hooks.append)
monkeypatch.setattr(atexit, "unregister", lambda hook: hooks.remove(hook) if hook in hooks else None)
def unregister(hook: Any) -> None:
if hook in hooks:
hooks.remove(hook)
fake = SimpleNamespace(register=hooks.append, unregister=unregister)
monkeypatch.setattr(remote_lifetime, "atexit", fake) # other modules register hooks of their own meanwhile
return hooks
@@ -994,7 +998,7 @@ def test_an_end_of_another_thread_stops_the_opening(
return {}
if at == "hook":
monkeypatch.setattr(atexit, "register", lambda hook: end() and None or exit_hooks.append(hook))
monkeypatch.setattr(remote_lifetime.atexit, "register", lambda hook: end() and None or exit_hooks.append(hook))
elif at == "create":
monkeypatch.setattr(remote_service, "launch_keys", end)
else:
+23 -6
View File
@@ -50,10 +50,12 @@ async def test_get_returns_none_for_missing(store: SessionStore) -> None:
async def test_get_touches_last_accessed(store: SessionStore) -> None:
entry = await store.create("DEMO", _FakeService())
before = entry.last_accessed
entry.idle_since -= 100
await asyncio.sleep(0.01)
fetched = await store.get(entry.session_id)
assert fetched is entry
assert fetched.last_accessed > before
assert fetched.idle_seconds < 100
async def test_delete_removes_and_cancels_bridge(store: SessionStore) -> None:
@@ -99,7 +101,7 @@ async def test_get_and_the_sweep_share_one_expiry_rule(
bridge = InputBridge()
bridge.login_status = status
entry = await store.create("EXAMPLE", _FakeService(), session_id="s", input_bridge=bridge)
entry.last_accessed = datetime.now(UTC) - timedelta(seconds=idle)
entry.idle_since = time.monotonic() - idle
if via == "get":
assert (await store.get("s") is None) is expires
@@ -108,10 +110,25 @@ async def test_get_and_the_sweep_share_one_expiry_rule(
assert store.session_count == int(not expires)
@pytest.mark.parametrize("step", [1, -1], ids=["forward", "back"])
@pytest.mark.parametrize("idle", [0, 1], ids=["active", "idle"])
async def test_a_step_of_the_wall_clock_changes_no_expiry(
store: SessionStore, monkeypatch: pytest.MonkeyPatch, step: int, idle: int
) -> None:
entry = await store.create("EXAMPLE", _FakeService(), session_id="s")
entry.idle_since -= idle * (store.ttl + 100)
stepped = datetime.now(UTC) + timedelta(seconds=step * 2 * (store.ttl + 100))
monkeypatch.setattr(session_store_module, "datetime", SimpleNamespace(now=lambda tz: stepped))
assert entry.summary()["idle_seconds"] // (store.ttl + 100) == idle
assert await store.cleanup_expired() == idle
assert await store.get("s") is (None if idle else entry)
async def test_session_with_work_in_progress_does_not_expire(store: SessionStore) -> None:
"""A request that holds the lock for longer than the TTL keeps its session and cache directory."""
entry = await store.create("EXAMPLE", _FakeService(), session_id="busy")
entry.last_accessed = datetime.now(UTC) - timedelta(seconds=store.ttl + 100)
entry.idle_since = time.monotonic() - store.ttl - 100
async with entry.lock:
assert await store.cleanup_expired() == 0
assert await store.get("busy") is entry
@@ -204,7 +221,7 @@ async def test_get_expiry_removes_cache_dir(store: SessionStore, monkeypatch: py
monkeypatch.setattr(SessionStore, "cleanup_cache_dir", staticmethod(removed.append))
entry = await store.create("EXAMPLE", _FakeService())
entry.cache_tag = "_sessions/k/s/EXAMPLE"
entry.last_accessed = datetime.now(UTC) - timedelta(seconds=store.ttl + 100)
entry.idle_since = time.monotonic() - store.ttl - 100
assert await store.get(entry.session_id) is None
assert removed == ["_sessions/k/s/EXAMPLE"]
@@ -285,7 +302,7 @@ async def test_inline_expiry_applies_staged_service_reload(
applied = _stage_reload(monkeypatch, {"EXAMPLE"})
entry = await store.create("EXAMPLE", _FakeService())
entry.last_accessed = datetime.now(UTC) - timedelta(seconds=store.ttl + 100)
entry.idle_since = time.monotonic() - store.ttl - 100
assert await store.get(entry.session_id) is None
await asyncio.sleep(0.05)
assert applied == [set()]
@@ -296,9 +313,9 @@ async def test_cleanup_expired_applies_staged_service_reload_once(
) -> None:
"""A cleanup sweep that drops several sessions on one tag schedules one reload for that tag."""
applied = _stage_reload(monkeypatch, {"EXAMPLE"})
stale = datetime.now(UTC) - timedelta(seconds=store.ttl + 100)
stale = time.monotonic() - store.ttl - 100
for sid in ("a", "b"):
(await store.create("EXAMPLE", _FakeService(), session_id=sid)).last_accessed = stale
(await store.create("EXAMPLE", _FakeService(), session_id=sid)).idle_since = stale
assert await store.cleanup_expired() == 2
await asyncio.sleep(0.05)