forked from kenzuya/unshackle
refactor(api): end every remote session through SessionStore._retire and close the store at shutdown
This commit is contained in:
@@ -5,12 +5,13 @@ from __future__ import annotations
|
||||
import asyncio
|
||||
import threading
|
||||
import time
|
||||
from datetime import UTC
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from unshackle.core.api.input_bridge import InputBridge
|
||||
from unshackle.core.api import session_store as session_store_module
|
||||
from unshackle.core.api.input_bridge import AUTH_INPUT_TIMEOUT, InputBridge
|
||||
from unshackle.core.api.session_store import SessionEntry, SessionStore, get_session_store
|
||||
from unshackle.core.remote_protocol import AuthStatus
|
||||
|
||||
@@ -71,20 +72,44 @@ async def test_delete_returns_false_when_missing(store: SessionStore) -> None:
|
||||
assert await store.delete("missing") is False
|
||||
|
||||
|
||||
async def test_cleanup_expired_drops_old_authenticated(store: SessionStore, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
from datetime import datetime, timedelta
|
||||
@pytest.mark.parametrize("via", ["get", "sweep"])
|
||||
@pytest.mark.parametrize(
|
||||
("ttl", "status", "idle", "expires"),
|
||||
[
|
||||
(300, AuthStatus.AUTHENTICATING, 301, False),
|
||||
(300, AuthStatus.AUTHENTICATING, AUTH_INPUT_TIMEOUT + 1, True),
|
||||
(300, AuthStatus.AUTHENTICATED, 301, True),
|
||||
(900, AuthStatus.AUTHENTICATING, AUTH_INPUT_TIMEOUT + 1, False),
|
||||
(900, AuthStatus.AUTHENTICATING, 901, True),
|
||||
(900, AuthStatus.AUTHENTICATED, AUTH_INPUT_TIMEOUT + 1, False),
|
||||
(900, AuthStatus.AUTHENTICATED, 901, True),
|
||||
],
|
||||
)
|
||||
async def test_get_and_the_sweep_share_one_expiry_rule(
|
||||
store: SessionStore,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
via: str,
|
||||
ttl: int,
|
||||
status: AuthStatus,
|
||||
idle: float,
|
||||
expires: bool,
|
||||
) -> None:
|
||||
"""A login that still runs gets max(ttl, AUTH_INPUT_TIMEOUT), never less than an idle authenticated session."""
|
||||
monkeypatch.setattr(type(store), "ttl", property(lambda _: ttl))
|
||||
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 = await store.create("EXAMPLE", _FakeService())
|
||||
entry.last_accessed = datetime.now(UTC) - timedelta(seconds=store.ttl + 100)
|
||||
removed = await store.cleanup_expired()
|
||||
assert removed == 1
|
||||
assert store.session_count == 0
|
||||
if via == "get":
|
||||
assert (await store.get("s") is None) is expires
|
||||
else:
|
||||
assert await store.cleanup_expired() == int(expires)
|
||||
assert store.session_count == int(not expires)
|
||||
|
||||
|
||||
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."""
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
entry = await store.create("EXAMPLE", _FakeService(), session_id="busy")
|
||||
entry.last_accessed = datetime.now(UTC) - timedelta(seconds=store.ttl + 100)
|
||||
async with entry.lock:
|
||||
@@ -92,59 +117,53 @@ async def test_session_with_work_in_progress_does_not_expire(store: SessionStore
|
||||
assert await store.get("busy") is entry
|
||||
|
||||
|
||||
async def test_cleanup_expired_keeps_a_login_under_grace(store: SessionStore) -> None:
|
||||
"""A session that still logs in, a prompt included, gets a longer grace period (10 min) than authenticated TTL."""
|
||||
from datetime import datetime, timedelta
|
||||
async def test_close_ends_every_session_and_removes_its_cache_dir(
|
||||
store: SessionStore, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
"""A shutdown ends each session without a delete event or a staged service reload."""
|
||||
removed: list = []
|
||||
published: list = []
|
||||
monkeypatch.setattr(SessionStore, "cleanup_cache_dir", staticmethod(removed.append))
|
||||
monkeypatch.setattr(session_store_module, "_publish", lambda *a, **k: published.append(a))
|
||||
monkeypatch.setattr(session_store_module, "_schedule_pending_reload", lambda tag: published.append(tag))
|
||||
a = await store.create("EXAMPLE", _FakeService(), input_bridge=InputBridge(), cache_tag="_sessions/k/s/EXAMPLE")
|
||||
b = await store.create("OTHER", _FakeService(), input_bridge=InputBridge())
|
||||
published.clear()
|
||||
|
||||
entry = await store.create("EXAMPLE", _FakeService(), input_bridge=InputBridge())
|
||||
entry.last_accessed = datetime.now(UTC) - timedelta(seconds=store.ttl + 1)
|
||||
removed = await store.cleanup_expired()
|
||||
assert removed == 0
|
||||
assert store.session_count == 1
|
||||
|
||||
|
||||
async def test_get_keeps_a_login_past_the_ttl(store: SessionStore) -> None:
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
entry = await store.create("EXAMPLE", _FakeService(), input_bridge=InputBridge())
|
||||
entry.last_accessed = datetime.now(UTC) - timedelta(seconds=store.ttl + 1)
|
||||
assert await store.get(entry.session_id) is entry
|
||||
|
||||
|
||||
async def test_cleanup_expired_drops_a_login_past_grace(store: SessionStore) -> None:
|
||||
"""The auth-state grace is the single AUTH_INPUT_TIMEOUT rule, not a separate magic number."""
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from unshackle.core.api.input_bridge import AUTH_INPUT_TIMEOUT
|
||||
|
||||
entry = await store.create("EXAMPLE", _FakeService(), input_bridge=InputBridge())
|
||||
entry.last_accessed = datetime.now(UTC) - timedelta(seconds=AUTH_INPUT_TIMEOUT + 1)
|
||||
removed = await store.cleanup_expired()
|
||||
assert removed == 1
|
||||
assert store.session_count == 0
|
||||
|
||||
|
||||
async def test_cancel_all_bridges(store: SessionStore) -> None:
|
||||
a = await store.create("EXAMPLE", _FakeService(), input_bridge=InputBridge())
|
||||
b = await store.create("DEMO", _FakeService(), input_bridge=InputBridge())
|
||||
|
||||
await store.cancel_all_bridges()
|
||||
await store.close()
|
||||
for entry in (a, b):
|
||||
with pytest.raises(RuntimeError, match="cancelled"):
|
||||
entry.input_bridge.ensure_active()
|
||||
assert entry.channel.ended
|
||||
assert removed == [a.cache_tag, None]
|
||||
assert store.session_count == 0
|
||||
assert published == []
|
||||
|
||||
|
||||
async def test_cancel_all_bridges_removes_the_session_cache_dirs(
|
||||
async def test_close_waits_for_a_login_and_stops_the_sweep(store: SessionStore) -> None:
|
||||
login = asyncio.create_task(asyncio.sleep(0.05))
|
||||
store.track_login(login)
|
||||
await store.start_cleanup_loop()
|
||||
sweep = store._cleanup_task
|
||||
|
||||
await store.close()
|
||||
assert login.done()
|
||||
assert store._logins == set()
|
||||
assert sweep is not None and sweep.cancelled()
|
||||
|
||||
|
||||
async def test_close_gives_up_on_a_login_that_does_not_end(
|
||||
store: SessionStore, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
removed: list = []
|
||||
monkeypatch.setattr(SessionStore, "cleanup_cache_dir", staticmethod(removed.append))
|
||||
entry = await store.create("EXAMPLE", _FakeService(), cache_tag="_sessions/k/s/EXAMPLE")
|
||||
await store.create("OTHER", _FakeService())
|
||||
monkeypatch.setattr(session_store_module, "LOGIN_WAIT", 0.01)
|
||||
login = asyncio.create_task(asyncio.Event().wait())
|
||||
store.track_login(login)
|
||||
await store.start_cleanup_loop()
|
||||
|
||||
await store.cancel_all_bridges()
|
||||
assert removed == [entry.cache_tag, None]
|
||||
assert store.session_count == 0
|
||||
await asyncio.wait_for(store.close(), 5)
|
||||
assert not login.done()
|
||||
assert store._cleanup_task is None
|
||||
login.cancel()
|
||||
|
||||
|
||||
async def test_get_session_store_returns_singleton() -> None:
|
||||
@@ -181,8 +200,6 @@ async def test_max_sessions_evicts_the_oldest_session_of_the_key_that_holds_the_
|
||||
|
||||
|
||||
async def test_get_expiry_removes_cache_dir(store: SessionStore, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
removed: list = []
|
||||
monkeypatch.setattr(SessionStore, "cleanup_cache_dir", staticmethod(removed.append))
|
||||
entry = await store.create("EXAMPLE", _FakeService())
|
||||
@@ -265,8 +282,6 @@ async def test_eviction_applies_staged_service_reload(store: SessionStore, monke
|
||||
async def test_inline_expiry_applies_staged_service_reload(
|
||||
store: SessionStore, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
applied = _stage_reload(monkeypatch, {"EXAMPLE"})
|
||||
|
||||
entry = await store.create("EXAMPLE", _FakeService())
|
||||
@@ -280,8 +295,6 @@ async def test_cleanup_expired_applies_staged_service_reload_once(
|
||||
store: SessionStore, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
"""A cleanup sweep that drops several sessions on one tag schedules one reload for that tag."""
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
applied = _stage_reload(monkeypatch, {"EXAMPLE"})
|
||||
stale = datetime.now(UTC) - timedelta(seconds=store.ttl + 100)
|
||||
for sid in ("a", "b"):
|
||||
@@ -295,7 +308,6 @@ async def test_cleanup_expired_applies_staged_service_reload_once(
|
||||
async def test_live_session_on_same_tag_keeps_it_busy(store: SessionStore, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
"""Ending one of two sessions on a staged tag reports the tag busy; ending the last one frees it."""
|
||||
from unshackle.core.api import download_manager
|
||||
from unshackle.core.api import session_store as session_store_module
|
||||
|
||||
applied = _stage_reload(monkeypatch, {"EXAMPLE"})
|
||||
monkeypatch.setattr(session_store_module, "session_store", store)
|
||||
|
||||
Reference in New Issue
Block a user