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
+3 -2
View File
@@ -624,7 +624,7 @@ Source: `unshackle/core/api/session_store.py`. A singleton you get from
- **Expiry.** `get()` and `cleanup_expired()` use one rule. A remote session that no request holds - **Expiry.** `get()` and `cleanup_expired()` use one rule. A remote session that no request holds
expires when it is idle for longer than `ttl`. While its login runs (`AUTHENTICATING`), the limit is expires when it is idle for longer than `ttl`. While its login runs (`AUTHENTICATING`), the limit is
the larger of `ttl` and `AUTH_INPUT_TIMEOUT`. the larger of `ttl` and `AUTH_INPUT_TIMEOUT`.
- **`get()`** refreshes `last_accessed` through `touch()`. It returns `None` and - **`get()`** refreshes `last_accessed` and `idle_since` through `touch()`. It returns `None` and
deletes the entry when the remote session has expired. deletes the entry when the remote session has expired.
- **`cleanup_expired()`** runs every 60s and removes each expired remote session. - **`cleanup_expired()`** runs every 60s and removes each expired remote session.
- **Removal.** Eviction, expiry and `delete()` end the remote session the same way: they cancel its - **Removal.** Eviction, expiry and `delete()` end the remote session the same way: they cancel its
@@ -649,7 +649,8 @@ Source: `unshackle/core/api/session_store.py`. A singleton you get from
| `cache_tag` | Per-session cache directory tag | | `cache_tag` | Per-session cache directory tag |
| `input_bridge` | `InputBridge` for interactive auth, if any | | `input_bridge` | `InputBridge` for interactive auth, if any |
| `auth_status` / `auth_error` | Current `AuthStatus`, read from `input_bridge` (`AUTHENTICATED` without one), and last error message | | `auth_status` / `auth_error` | Current `AuthStatus`, read from `input_bridge` (`AUTHENTICATED` without one), and last error message |
| `created_at` / `last_accessed` | Timestamps; `last_accessed` drives TTL and LRU eviction | | `created_at` / `last_accessed` | Timestamps; `last_accessed` drives LRU eviction |
| `idle_since` | Monotonic time of the last access; it drives the TTL, so a step of the system clock expires no remote session |
### Per-session cache namespacing ### Per-session cache namespacing
+7 -7
View File
@@ -7,7 +7,6 @@ import json
import logging import logging
import threading import threading
from collections.abc import Callable, Iterator from collections.abc import Callable, Iterator
from datetime import UTC, datetime
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path from pathlib import Path
from threading import Event, Semaphore, Thread 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 = web.Application(middlewares=[record, cors_middleware, no_5xx_middleware, api_key_authentication])
app["config"] = {"users": [KEY, OTHER_KEY]} app["config"] = {"users": [KEY, OTHER_KEY]}
setup_routes(app, remote_only=True) 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() loop = asyncio.new_event_loop()
runner = web.AppRunner(app) runner = web.AppRunner(app)
loop.run_until_complete(runner.setup()) 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"] 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( @pytest.mark.parametrize(
"server,channel", "server,channel",
[(True, "none"), (False, "refused"), (True, "failed")], [(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 session_id = service._session_id
entry = store.peek(session_id) entry = store.peek(session_id)
assert wait_until(lambda: entry.channel.attached, 5) 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 on_loop(server, store.cleanup_expired()) == 0
assert store.peek(session_id) is entry assert store.peek(session_id) is entry
assert count(server, "GET", SESSION_ROUTE, session_id) == 0 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() service.lifetime.close_channel()
assert wait_until(lambda: not entry.channel.attached, 5) 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 on_loop(server, store.cleanup_expired()) == 1
assert store.peek(session_id) is None assert store.peek(session_id) is None
assert count(server, "GET", SESSION_ROUTE, session_id) == 0 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.""" """A per-key height cap on the server CDM hands licensing above it to the client's own device."""
import atexit
import json import json
import logging import logging
from datetime import datetime 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.key_source import CAPPED, PR_DEVICE, MemoryKeySource, one_title, remote_session
from tests.remote.sessions import launch_session, session_entry from tests.remote.sessions import launch_session, session_entry
from unshackle.commands.dl import dl 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 import handlers, job_admission, key_policy, server_keys
from unshackle.core.api.errors import APIError from unshackle.core.api.errors import APIError
from unshackle.core.api.key_policy import KeyPolicy 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}) svc.client = SimpleNamespace(post=lambda path, data: {"session_id": "sess", **answer})
channel = SimpleNamespace(keep_alive=lambda: None, drain_logs=lambda: None, in_flight=None) channel = SimpleNamespace(keep_alive=lambda: None, drain_logs=lambda: None, in_flight=None)
monkeypatch.setattr(remote_channel, "open_channel", lambda service: channel) 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() svc.authenticate()
return svc return svc
+9 -5
View File
@@ -3,7 +3,6 @@
from __future__ import annotations from __future__ import annotations
import asyncio import asyncio
import atexit
import contextlib import contextlib
import signal import signal
import subprocess 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_remote_service_helpers import blob
from tests.remote.unit.test_session_reopen import SERVER, make_service from tests.remote.unit.test_session_reopen import SERVER, make_service
from tests.remote.unit.test_tunnel import wait_until 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 import handlers, routes, session_store
from unshackle.core.api.download_manager import busy_services from unshackle.core.api.download_manager import busy_services
from unshackle.core.api.session_store import SessionEntry 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 @pytest.fixture
def exit_hooks(monkeypatch: pytest.MonkeyPatch) -> list[Any]: def exit_hooks(monkeypatch: pytest.MonkeyPatch) -> list[Any]:
hooks: 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 return hooks
@@ -994,7 +998,7 @@ def test_an_end_of_another_thread_stops_the_opening(
return {} return {}
if at == "hook": 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": elif at == "create":
monkeypatch.setattr(remote_service, "launch_keys", end) monkeypatch.setattr(remote_service, "launch_keys", end)
else: 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: async def test_get_touches_last_accessed(store: SessionStore) -> None:
entry = await store.create("DEMO", _FakeService()) entry = await store.create("DEMO", _FakeService())
before = entry.last_accessed before = entry.last_accessed
entry.idle_since -= 100
await asyncio.sleep(0.01) await asyncio.sleep(0.01)
fetched = await store.get(entry.session_id) fetched = await store.get(entry.session_id)
assert fetched is entry assert fetched is entry
assert fetched.last_accessed > before assert fetched.last_accessed > before
assert fetched.idle_seconds < 100
async def test_delete_removes_and_cancels_bridge(store: SessionStore) -> None: 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 = InputBridge()
bridge.login_status = status bridge.login_status = status
entry = await store.create("EXAMPLE", _FakeService(), session_id="s", input_bridge=bridge) 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": if via == "get":
assert (await store.get("s") is None) is expires 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) 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: 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.""" """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 = 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: async with entry.lock:
assert await store.cleanup_expired() == 0 assert await store.cleanup_expired() == 0
assert await store.get("busy") is entry 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)) monkeypatch.setattr(SessionStore, "cleanup_cache_dir", staticmethod(removed.append))
entry = await store.create("EXAMPLE", _FakeService()) entry = await store.create("EXAMPLE", _FakeService())
entry.cache_tag = "_sessions/k/s/EXAMPLE" 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 await store.get(entry.session_id) is None
assert removed == ["_sessions/k/s/EXAMPLE"] assert removed == ["_sessions/k/s/EXAMPLE"]
@@ -285,7 +302,7 @@ async def test_inline_expiry_applies_staged_service_reload(
applied = _stage_reload(monkeypatch, {"EXAMPLE"}) applied = _stage_reload(monkeypatch, {"EXAMPLE"})
entry = await store.create("EXAMPLE", _FakeService()) 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 assert await store.get(entry.session_id) is None
await asyncio.sleep(0.05) await asyncio.sleep(0.05)
assert applied == [set()] assert applied == [set()]
@@ -296,9 +313,9 @@ async def test_cleanup_expired_applies_staged_service_reload_once(
) -> None: ) -> None:
"""A cleanup sweep that drops several sessions on one tag schedules one reload for that tag.""" """A cleanup sweep that drops several sessions on one tag schedules one reload for that tag."""
applied = _stage_reload(monkeypatch, {"EXAMPLE"}) 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"): 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 assert await store.cleanup_expired() == 2
await asyncio.sleep(0.05) await asyncio.sleep(0.05)
+14 -9
View File
@@ -13,6 +13,7 @@ import builtins
import contextlib import contextlib
import hmac import hmac
import logging import logging
import time
import uuid import uuid
from collections import Counter, deque from collections import Counter, deque
from collections.abc import AsyncIterator from collections.abc import AsyncIterator
@@ -72,6 +73,7 @@ class SessionEntry:
actions: deque[dict[str, Any]] = field(default_factory=lambda: deque(maxlen=500)) actions: deque[dict[str, Any]] = field(default_factory=lambda: deque(maxlen=500))
created_at: datetime = field(default_factory=lambda: datetime.now(UTC)) created_at: datetime = field(default_factory=lambda: datetime.now(UTC))
last_accessed: datetime = field(default_factory=lambda: datetime.now(UTC)) last_accessed: datetime = field(default_factory=lambda: datetime.now(UTC))
idle_since: float = field(default_factory=time.monotonic) # expiry reads no wall clock, which can step
def __post_init__(self) -> None: def __post_init__(self) -> None:
if self.input_bridge is not None: if self.input_bridge is not None:
@@ -91,8 +93,13 @@ class SessionEntry:
self.tracks_by_title[title_id] = title_tracks self.tracks_by_title[title_id] = title_tracks
def touch(self) -> None: def touch(self) -> None:
"""Update last_accessed timestamp.""" """Update last_accessed timestamp and restart the idle time."""
self.last_accessed = datetime.now(UTC) self.last_accessed = datetime.now(UTC)
self.idle_since = time.monotonic()
@property
def idle_seconds(self) -> float:
return time.monotonic() - self.idle_since
@property @property
def in_use(self) -> bool: def in_use(self) -> bool:
@@ -140,7 +147,7 @@ class SessionEntry:
"created_ts": self.created_at.timestamp(), "created_ts": self.created_at.timestamp(),
"last_accessed_ts": self.last_accessed.timestamp(), "last_accessed_ts": self.last_accessed.timestamp(),
"age_seconds": int((now - self.created_at).total_seconds()), "age_seconds": int((now - self.created_at).total_seconds()),
"idle_seconds": int((now - self.last_accessed).total_seconds()), "idle_seconds": int(self.idle_seconds),
} }
@@ -325,11 +332,10 @@ class SessionStore:
if entry is None: if entry is None:
return None return None
now = datetime.now(UTC) if not self._expired(entry):
if not self._expired(entry, now):
entry.touch() entry.touch()
return entry return entry
elapsed = (now - entry.last_accessed).total_seconds() elapsed = entry.idle_seconds
limit = self._idle_limit(entry) limit = self._idle_limit(entry)
log.info(f"Session {sanitize_log(session_id)} expired (elapsed={elapsed:.0f}s, ttl={limit:.0f}s)") log.info(f"Session {sanitize_log(session_id)} expired (elapsed={elapsed:.0f}s, ttl={limit:.0f}s)")
cache_tag = self._retire(entry, "expired") cache_tag = self._retire(entry, "expired")
@@ -358,8 +364,7 @@ class SessionStore:
async def cleanup_expired(self) -> int: async def cleanup_expired(self) -> int:
"""Remove all expired sessions. Returns count of removed sessions.""" """Remove all expired sessions. Returns count of removed sessions."""
async with self._lock: async with self._lock:
now = datetime.now(UTC) expired = [entry for entry in self._sessions.values() if self._expired(entry)]
expired = [entry for entry in self._sessions.values() if self._expired(entry, now)]
cache_tags = [self._retire(entry, "expired") for entry in expired] cache_tags = [self._retire(entry, "expired") for entry in expired]
if expired: if expired:
log.info(f"Cleaned up {len(expired)} expired sessions") log.info(f"Cleaned up {len(expired)} expired sessions")
@@ -370,9 +375,9 @@ class SessionStore:
"""The idle limit of a remote session: the TTL, or max(TTL, AUTH_INPUT_TIMEOUT) while its login runs.""" """The idle limit of a remote session: the TTL, or max(TTL, AUTH_INPUT_TIMEOUT) while its login runs."""
return max(self.ttl, AUTH_INPUT_TIMEOUT) if entry.auth_status == AuthStatus.AUTHENTICATING else self.ttl return max(self.ttl, AUTH_INPUT_TIMEOUT) if entry.auth_status == AuthStatus.AUTHENTICATING else self.ttl
def _expired(self, entry: SessionEntry, now: datetime) -> bool: def _expired(self, entry: SessionEntry) -> bool:
"""The one expiry rule: no request holds the remote session and it is idle past its limit.""" """The one expiry rule: no request holds the remote session and it is idle past its limit."""
return not entry.in_use and (now - entry.last_accessed).total_seconds() > self._idle_limit(entry) return not entry.in_use and entry.idle_seconds > self._idle_limit(entry)
def _retire(self, entry: SessionEntry, reason: str | None) -> str | None: def _retire(self, entry: SessionEntry, reason: str | None) -> str | None:
"""End a remote session under the store lock and return its cache tag, for removal outside the lock. """End a remote session under the store lock and return its cache tag, for removal outside the lock.