forked from mtusi2026/mtusi2026lab3
162 lines
5.7 KiB
Python
162 lines
5.7 KiB
Python
import asyncio
|
|
from datetime import UTC, datetime, timedelta
|
|
from typing import cast
|
|
from unittest.mock import AsyncMock
|
|
from uuid import uuid4
|
|
|
|
import pytest
|
|
from redis.asyncio import Redis
|
|
from redis.exceptions import ConnectionError as CacheConnectionError
|
|
|
|
from fakes import NullLogger
|
|
from messenger.identity.domain.models import Session
|
|
from messenger.identity.infrastructure.valkey import (
|
|
FILL,
|
|
REVOKE,
|
|
REVOKED,
|
|
CachedSessionDirectory,
|
|
key_of,
|
|
milliseconds,
|
|
)
|
|
|
|
NOW = datetime(2030, 1, 1, tzinfo=UTC)
|
|
|
|
|
|
class CacheModel:
|
|
def __init__(self) -> None:
|
|
self.values: dict[str, str] = {}
|
|
self.expires: dict[str, int] = {}
|
|
|
|
async def get(self, key: str) -> str | None:
|
|
return self.values.get(key)
|
|
|
|
async def set(self, key: str, value: str, *, pxat: int, nx: bool = False) -> bool:
|
|
if nx and key in self.values:
|
|
return False
|
|
self.values[key], self.expires[key] = value, pxat
|
|
return True
|
|
|
|
async def delete(self, key: str) -> None:
|
|
self.values.pop(key, None)
|
|
self.expires.pop(key, None)
|
|
|
|
async def eval(self, script: str, count: int, key: str, marker: str, *args: str | int) -> bool:
|
|
assert count == 2
|
|
if script == REVOKE:
|
|
value, until = args
|
|
assert isinstance(value, str) and isinstance(until, int)
|
|
await self.set(key, value, pxat=until)
|
|
await self.delete(marker)
|
|
return True
|
|
assert script == FILL
|
|
nonce, value, until = args
|
|
assert isinstance(value, str) and isinstance(until, int)
|
|
if await self.get(marker) != nonce:
|
|
return False
|
|
await self.delete(marker)
|
|
return bool(value) and await self.set(key, value, pxat=until, nx=True)
|
|
|
|
|
|
def directory(origin: AsyncMock, cache: CacheModel, ttl: int = 300) -> CachedSessionDirectory:
|
|
return CachedSessionDirectory(
|
|
origin, cast(Redis, cache), NullLogger(), limit=timedelta(seconds=ttl), cooldown=1
|
|
)
|
|
|
|
|
|
@pytest.fixture
|
|
def session() -> Session:
|
|
return Session.issue(user_id=uuid4(), issued_at=NOW, ttl=timedelta(seconds=30))[1]
|
|
|
|
|
|
@pytest.mark.parametrize("ttl", [10, 300])
|
|
async def test_cache_hit_keeps_absolute_ttl_without_reading_origin(
|
|
session: Session, ttl: int
|
|
) -> None:
|
|
origin, cache = AsyncMock(), CacheModel()
|
|
origin.find.return_value = session
|
|
cached = directory(origin, cache, ttl)
|
|
assert await cached.find(session.token_hash, NOW) == session
|
|
assert await directory(origin, cache, ttl).find(session.token_hash, NOW) == session
|
|
origin.find.assert_awaited_once()
|
|
assert cache.expires == {
|
|
key_of(session.token_hash): milliseconds(
|
|
min(session.expires_at, NOW + timedelta(seconds=ttl))
|
|
)
|
|
}
|
|
|
|
|
|
@pytest.mark.parametrize("loss", ["none", "flushall", "evict", "replacement"])
|
|
async def test_delayed_fill_cannot_revive_logged_out_session(session: Session, loss: str) -> None:
|
|
origin, cache = AsyncMock(), CacheModel()
|
|
origin.find.return_value = session
|
|
entered, released = asyncio.Event(), asyncio.Event()
|
|
|
|
async def stale_find(token_hash: bytes, now: datetime) -> Session:
|
|
entered.set()
|
|
await released.wait()
|
|
return session
|
|
|
|
slow = AsyncMock()
|
|
slow.find.side_effect = stale_find
|
|
async with asyncio.TaskGroup() as group:
|
|
reader = group.create_task(directory(slow, cache).find(session.token_hash, NOW))
|
|
await asyncio.wait_for(entered.wait(), 1)
|
|
try:
|
|
await directory(origin, cache).revoke(session)
|
|
origin.find.return_value = None
|
|
key = key_of(session.token_hash)
|
|
if loss == "flushall":
|
|
cache.values.clear()
|
|
elif loss in {"evict", "replacement"}:
|
|
await cache.delete(key)
|
|
if loss == "replacement":
|
|
await cache.set(f"{key}:fill", uuid4().hex, pxat=milliseconds(session.expires_at))
|
|
finally:
|
|
released.set()
|
|
assert reader.result() == session
|
|
assert await directory(origin, cache).find(session.token_hash, NOW) is None
|
|
assert await cache.get(key) in {None, REVOKED}
|
|
|
|
|
|
async def test_failed_reservation_never_fills_from_stale_database_result(session: Session) -> None:
|
|
cache = CacheModel()
|
|
origin = AsyncMock()
|
|
key = key_of(session.token_hash)
|
|
await cache.set(f"{key}:fill", "another-reader", pxat=milliseconds(session.expires_at))
|
|
|
|
async def find(token_hash: bytes, now: datetime) -> Session:
|
|
cache.values.clear()
|
|
return session
|
|
|
|
origin.find.side_effect = find
|
|
assert await directory(origin, cache).find(session.token_hash, NOW) == session
|
|
assert await cache.get(key) is None
|
|
|
|
|
|
async def test_missing_session_releases_only_its_own_reservation(session: Session) -> None:
|
|
origin, cache = AsyncMock(), CacheModel()
|
|
origin.find.return_value = None
|
|
assert await directory(origin, cache).find(session.token_hash, NOW) is None
|
|
assert cache.values == {}
|
|
|
|
|
|
@pytest.mark.parametrize("failed_operation", ["get", "set"])
|
|
async def test_cache_recovery_during_database_read_does_not_allow_unreserved_fill(
|
|
session: Session, failed_operation: str
|
|
) -> None:
|
|
origin, cache = AsyncMock(), AsyncMock()
|
|
cache.get.return_value = None
|
|
getattr(cache, failed_operation).side_effect = CacheConnectionError("offline")
|
|
cached = CachedSessionDirectory(
|
|
origin, cache, NullLogger(), limit=timedelta(seconds=300), cooldown=1
|
|
)
|
|
|
|
async def find(token_hash: bytes, now: datetime) -> Session:
|
|
cached._resume_at = 0.0
|
|
return session
|
|
|
|
origin.find.side_effect = find
|
|
assert await cached.find(session.token_hash, NOW) == session
|
|
assert cache.set.await_count == (failed_operation == "set")
|
|
cache.eval.assert_not_awaited()
|