refactor(api): end every remote session through SessionStore._retire and close the store at shutdown

This commit is contained in:
imSp4rky
2026-11-29 14:46:51 -07:00
parent ccc327e2c3
commit 977cbe4aa8
8 changed files with 158 additions and 160 deletions
+1 -1
View File
@@ -953,7 +953,7 @@ Report the install status of the external binaries unshackle depends on (the sam
!!! note "Developer feature"
The `/api/session/*` endpoints power unshackle's **remote download** mode. A thin local client authenticates once against a remote server, then fetches titles, tracks, and segments, and proxies DRM licensing back through it. The server mounts these endpoints in `--remote-only` mode, and they are what the built-in `RemoteService` client drives. Most end users never call them directly.
The server holds remote sessions in memory. They expire after `serve.session_ttl` (default 300s) without a request, except while awaiting interactive authentication input, which uses a 600s window. A remote session binds to the IP that made it, so the server rejects a request from a different IP with `403 FORBIDDEN`.
The server holds remote sessions in memory. They expire after `serve.session_ttl` (default 300s) without a request, except while the login runs, which can stay idle for the larger of `session_ttl` and 600s. A remote session binds to the IP that made it, so the server rejects a request from a different IP with `403 FORBIDDEN`.
### Remote session lifecycle overview
+20 -17
View File
@@ -384,14 +384,13 @@ generally never touch this directly, but it explains behaviour you might observe
|---|---|---|
| Idle session TTL | **300s** (5 min) default | Refreshed on every request to the session and when a `titles` or `tracks` request ends. A remote session does not expire while a request works on it or while its remote session channel is open |
| Max concurrent sessions | **100** default | When full, the least recently used remote session of the API key that holds the most is evicted. A remote session that a request works on goes last |
| Auth/input timeout | **600s** (10 min) | Sessions still authenticating or awaiting a prompt use this longer window instead of the TTL |
| Auth/input timeout | **600s** (10 min) | A remote session that still logs in, a prompt included, can stay idle for the larger of the TTL and this value |
| Cleanup sweep | every 60s | Expired sessions are removed and their input prompts cancelled |
!!! note "Auth is never rushed"
A remote session that is still `authenticating` or waiting on `pending_input` is
**not** subject to the short 300s TTL. It gets the full 600s auth window. This gives
you time to enter an interactive code without the remote session vanishing
mid-prompt.
A remote session that is still `authenticating` or waiting on `pending_input` can stay
idle for the larger of `session_ttl` and 600s. This gives you time to enter an interactive
code without the remote session vanishing mid-prompt.
The TTL and max-session limits are read from server config:
@@ -540,8 +539,8 @@ layer.
channel carries it, or the client polls while its own requests run. A call that no client fetches within 10 seconds
fails then, because no client is listening. A fetched call waits 60 seconds for its answer.
The call leaves the auth status as it was. An answer never marks the remote session as client-authenticated.
- `AUTH_INPUT_TIMEOUT = 600.0` seconds. This is also the TTL granted to
`AUTHENTICATING` sessions in the store. A remote session that waits on a prompt stays `AUTHENTICATING`.
- `AUTH_INPUT_TIMEOUT = 600.0` seconds. An `AUTHENTICATING` remote session expires in the store after
the larger of `session_ttl` and this value. A remote session that waits on a prompt stays `AUTHENTICATING`.
`GET /api/session/{id}/prompt` returns one of:
@@ -610,16 +609,20 @@ Source: `unshackle/core/api/session_store.py`. A singleton you get from
take effect without recreating the store.
- **`create()`** evicts the least-recently-accessed remote session of the API key that holds the most when at capacity,
then stores a complete `SessionEntry` from the fields of the `create` handler and publishes the `create` event.
- **`get()`** refreshes `last_accessed` through `touch()`. It returns `None` (and
deletes the entry) if an authenticated remote session has been idle longer than the
TTL. Remote sessions in `AUTHENTICATING` are exempt from TTL expiry.
- **`cleanup_expired()`** runs every 60s: authenticated remote sessions expire at
`ttl`, in-flight-auth remote sessions expire at `AUTH_INPUT_TIMEOUT`. The removal of
a remote session cancels its `InputBridge` and deletes its cache directory (pruning
empty parent dirs up to, but not including, the cache root).
- The server calls **`cancel_all_bridges()`** on shutdown. It ends each open remote session, which
unblocks any waiting auth threads, and deletes the cache directory of each one. The server then waits up
to 5 seconds for each login that still runs, and deletes its cache directory again when it ends.
- **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
the larger of `ttl` and `AUTH_INPUT_TIMEOUT`.
- **`get()`** refreshes `last_accessed` through `touch()`. It returns `None` and
deletes the entry when the remote session has expired.
- **`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
`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).
- **`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.
`SessionEntry` fields:
+1 -1
View File
@@ -163,7 +163,7 @@ is the [REST API](../../dev/rest-api/index.md) section. These are the config key
| `services` | list | *(unset)* | Global service allowlist. Omit to allow all. |
| `remote_only` | bool | `false` | Expose only the remote service session endpoints (health, services, search, session) and disable the rest of the REST API. |
| `dashboard` | dict | *(unset)* | Developer dashboard: `key` is the API key for the read-only `/api/dashboard/` endpoints (status, remote sessions, remote session logs, jobs, keys, services, health, logs, SSE events). Unset leaves those routes unregistered, and a reload that removes the key makes them answer `404`. See [dashboard endpoints](../../dev/rest-api/dashboard.md). |
| `session_ttl` | int (s) | `300` | Seconds a remote session can stay idle before it expires. A remote client sends keep-alive requests to its remote session during a download, so the remote session does not expire during a long download. |
| `session_ttl` | int (s) | `300` | Seconds a remote session can stay idle before it expires. A remote client sends keep-alive requests to its remote session during a download, so the remote session does not expire during a long download. A remote session that still logs in can stay idle for the larger of this value and 600 seconds. |
| `max_sessions` | int or null | `100` | Maximum concurrent remote sessions; at the cap the server evicts the oldest remote session of the API key that holds the most. Set it to `null` or `0` for no limit, which is also what `/api/dashboard/status` then reports, so a dashboard can tell "no cap" from a cap that happens to sit at the default. |
| `history_limit` | int | `100` | How many finished jobs to retain in history. |
| `compression_level` | int | `1` | gzip level for responses. |
+74 -62
View File
@@ -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)
+2 -9
View File
@@ -58,12 +58,7 @@ class _MaskAccessKey(logging.Filter):
def _install_session_store(app: web.Application) -> None:
"""Start the remote session store's idle sweep with the app and stop it, bridges included, on cleanup.
A login thread can still write the remote session cache after its bridge ends, so cleanup waits for the
logins, and each login that ends removes that cache directory again.
"""
from unshackle.core.api.handlers import wait_for_logins
"""Start the remote session store's idle sweep with the app and close the store on cleanup."""
from unshackle.core.api.session_store import get_session_store
session_store = get_session_store()
@@ -72,9 +67,7 @@ def _install_session_store(app: web.Application) -> None:
await session_store.start_cleanup_loop()
async def stop(_app: web.Application) -> None:
await session_store.cancel_all_bridges()
await wait_for_logins(5)
await session_store.stop_cleanup_loop()
await session_store.close()
app.on_startup.append(start)
app.on_cleanup.append(stop)
+1 -11
View File
@@ -1034,14 +1034,6 @@ def session_licensing(policy: KeyPolicy, service: str, data: dict[str, Any]) ->
_account_counters: dict[str, int] = {}
# the event loop holds only weak references to tasks, so a running login task needs a strong one
_auth_tasks: set["asyncio.Task[None]"] = set()
async def wait_for_logins(timeout: float) -> None:
"""Wait up to ``timeout`` seconds for the remote session logins that still run, at serve shutdown."""
if _auth_tasks:
await asyncio.wait(set(_auth_tasks), timeout=timeout)
def validate_server_accounts() -> dict[str, Any]:
@@ -2882,9 +2874,7 @@ async def session_create_handler(data: dict[str, Any], request: web.Request | No
if store.peek(session_id) is not session:
SessionStore.cleanup_cache_dir(session_cache_tag)
auth_task = asyncio.create_task(run_auth())
_auth_tasks.add(auth_task)
auth_task.add_done_callback(_auth_tasks.discard)
store.track_login(asyncio.create_task(run_auth()))
return web.json_response(
SessionCreated(
+1 -2
View File
@@ -19,8 +19,7 @@ from unshackle.core.remote_protocol import APIErrorCode, AuthStatus, coded
if TYPE_CHECKING:
from unshackle.core.api.session_channel import SessionChannel
# Seconds the server waits for a remote client to answer an input prompt before
# giving up; also the TTL SessionStore grants AUTHENTICATING sessions.
# Seconds the server waits for a remote client to answer an input prompt before giving up.
AUTH_INPUT_TIMEOUT = 600.0
CDM_CALL_TIMEOUT = 60.0
# A listening client polls every few seconds, so a CDM call nobody fetches in this time has no client behind it.
+58 -57
View File
@@ -10,6 +10,7 @@ from __future__ import annotations
import asyncio
import builtins
import contextlib
import logging
import uuid
from collections import Counter, deque
@@ -31,6 +32,8 @@ if TYPE_CHECKING:
log = logging.getLogger("api.session")
NO_DEVICE = LicensingMode(Licensor.NO_DEVICE)
LOGIN_WAIT = 5.0
DRAIN_WARNING = "This server restarts for an update after the open downloads finish; this download continues"
@@ -164,6 +167,7 @@ class SessionStore:
self._sessions: dict[str, SessionEntry] = {}
self._lock = asyncio.Lock()
self._cleanup_task: asyncio.Task | None = None
self._logins: set[asyncio.Task[None]] = set()
self.draining = False
@property
@@ -210,11 +214,7 @@ class SessionStore:
key=lambda k: (sessions[k].in_use, -held[sessions[k].owner_key], sessions[k].last_accessed),
)
log.warning(f"Max sessions reached ({max_sessions}), evicting oldest of the busiest key: {oldest_id}")
evicted = self._sessions.pop(oldest_id)
evicted.end()
evicted_tag = evicted.cache_tag
_publish("delete", evicted, "evicted")
_schedule_pending_reload(evicted.service_tag)
evicted_tag = self._retire(sessions[oldest_id], "evicted")
session_id = session_id or str(uuid.uuid4())
entry = SessionEntry(
@@ -245,19 +245,15 @@ class SessionStore:
if entry is None:
return None
expired = False
if not entry.in_use and entry.auth_status != AuthStatus.AUTHENTICATING:
elapsed = (datetime.now(UTC) - entry.last_accessed).total_seconds()
if elapsed > self.ttl:
log.info(f"Session {sanitize_log(session_id)} expired (elapsed={elapsed:.0f}s, ttl={self.ttl}s)")
_publish("delete", self._sessions.pop(session_id), "expired")
entry.end()
_schedule_pending_reload(entry.service_tag)
expired = True
if not expired:
now = datetime.now(UTC)
if not self._expired(entry, now):
entry.touch()
return entry
await self.remove_cache_dirs([entry.cache_tag])
elapsed = (now - entry.last_accessed).total_seconds()
limit = self._idle_limit(entry)
log.info(f"Session {sanitize_log(session_id)} expired (elapsed={elapsed:.0f}s, ttl={limit:.0f}s)")
cache_tag = self._retire(entry, "expired")
await self.remove_cache_dirs([cache_tag])
return None
def peek(self, session_id: str) -> SessionEntry | None:
@@ -271,45 +267,51 @@ class SessionStore:
async def delete(self, session_id: str) -> bool:
"""Delete a remote session. Returns True if it existed."""
async with self._lock:
entry = self._sessions.pop(session_id, None)
entry = self._sessions.get(session_id)
if not entry:
return False
entry.end()
_publish("delete", entry, "closed")
cache_tag = self._retire(entry, "closed")
log.info(f"Deleted session {sanitize_log(session_id)}")
_schedule_pending_reload(entry.service_tag)
await self.remove_cache_dirs([entry.cache_tag])
await self.remove_cache_dirs([cache_tag])
return True
async def cleanup_expired(self) -> int:
"""Remove all expired sessions. Returns count of removed sessions."""
async with self._lock:
now = datetime.now(UTC)
expired = []
for sid, entry in self._sessions.items():
if entry.in_use:
continue
elapsed = (now - entry.last_accessed).total_seconds()
if entry.auth_status == AuthStatus.AUTHENTICATING:
if elapsed > AUTH_INPUT_TIMEOUT:
expired.append(sid)
elif elapsed > self.ttl:
expired.append(sid)
ended_tags: set[str] = set()
cache_tags: list[str | None] = []
for sid in expired:
entry = self._sessions.pop(sid)
entry.end()
cache_tags.append(entry.cache_tag)
_publish("delete", entry, "expired")
ended_tags.add(entry.service_tag)
for tag in ended_tags:
_schedule_pending_reload(tag)
expired = [entry for entry in self._sessions.values() if self._expired(entry, now)]
cache_tags = [self._retire(entry, "expired") for entry in expired]
if expired:
log.info(f"Cleaned up {len(expired)} expired sessions")
await self.remove_cache_dirs(cache_tags)
return len(expired)
def _idle_limit(self, entry: SessionEntry) -> float:
"""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
def _expired(self, entry: SessionEntry, now: datetime) -> bool:
"""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)
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.
A reason goes to the dashboard delete event and schedules a staged service reload; the shutdown
retire passes None and does neither.
"""
del self._sessions[entry.session_id]
entry.end()
if reason is not None:
_publish("delete", entry, reason)
_schedule_pending_reload(entry.service_tag)
return 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."""
self._logins.add(task)
task.add_done_callback(self._logins.discard)
async def start_cleanup_loop(self) -> None:
"""Start periodic cleanup of expired sessions."""
if self._cleanup_task is not None:
@@ -326,25 +328,24 @@ class SessionStore:
self._cleanup_task = asyncio.create_task(loop())
log.info("Session cleanup loop started")
async def stop_cleanup_loop(self) -> None:
"""Stop the periodic cleanup task."""
if self._cleanup_task is not None:
self._cleanup_task.cancel()
self._cleanup_task = None
async def close(self) -> None:
"""End every remote session at server shutdown, wait LOGIN_WAIT seconds for the running logins, stop the sweep.
async def cancel_all_bridges(self) -> None:
"""End every remote session and remove its cache directory (called on server shutdown).
The store forgets the sessions too, so a login task that ends after this removes the directory again.
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 session_create_handler removes that cache directory again.
"""
async with self._lock:
entries = list(self._sessions.values())
self._sessions.clear()
for entry in entries:
entry.end()
if entries:
log.info(f"Cancelled bridges for {len(entries)} active session(s)")
await self.remove_cache_dirs([entry.cache_tag for entry in entries])
cache_tags = [self._retire(entry, None) for entry in list(self._sessions.values())]
if cache_tags:
log.info(f"Closed {len(cache_tags)} remote session(s) at shutdown")
await self.remove_cache_dirs(cache_tags)
if self._logins:
await asyncio.wait(set(self._logins), timeout=LOGIN_WAIT)
if self._cleanup_task is not None:
self._cleanup_task.cancel()
with contextlib.suppress(asyncio.CancelledError):
await self._cleanup_task
self._cleanup_task = None
@classmethod
async def remove_cache_dirs(cls, cache_tags: builtins.list[str | None]) -> None: