Bring the system changes of lab 3 from 61c0c28..72a1e57 onto the lab 4 code, resolving each conflict by meaning and keeping everything lab 4 added: - a message is posted with one SQL statement under the chat row lock, and the attachment links go into the same statement; a foreign key violation on the attachment link still answers 404 and leaves nothing behind. Text and the attachment list are checked before the write, an outsider gets 404 for both, as before the carry over; - the request pipeline counts the body bytes actually received against the limit of the route, so a chunked body over 1 MiB gets 413 and the upload route keeps its MAX_UPLOAD_BYTES limit; - a request cancelled at shutdown gets 503 unavailable in the contract format, the worker waits a second less than the rest of the shutdown budget, SHUTDOWN_TIMEOUT_SECONDS becomes 6 s and the stop hooks 7 s; - readiness sits behind a Readiness port with the draining flag in shared infrastructure, and the drain window is logged through Logger; - logout revokes through SessionRevocations and withdraws the mark when PostgreSQL rejects the delete; an empty cursor is 400; - EventBus.project is gone, the sweep test subscribes and waits on a queue; domain tests check attachment_list instead of Chat.post; - make up waits for every replica in the balancer, BASE_URL follows the lb port, the image is tagged by the compose project, retry-check and faults-evidence are added, detection runs three times, failover-each and rolling-update record the stand usage, CI checks numeric uids. down also takes the tools and reconcile profiles of lab 4. Track 1 tooling of lab 3 (scaling.py, its samplers, tools/ and the CPU pinning of api, lb, valkey and k6) stays out; stand-usage.sh queries the database size itself instead of the track 1 sampler. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01V1d3RLHNBBMA6UqBLLJv27
114 lines
3.6 KiB
Python
114 lines
3.6 KiB
Python
import time
|
|
from collections.abc import Awaitable
|
|
from datetime import datetime, timedelta
|
|
from uuid import UUID
|
|
|
|
from redis.asyncio import Redis
|
|
from redis.exceptions import RedisError
|
|
|
|
from messenger.identity.application.ports import SessionDirectory
|
|
from messenger.identity.domain.models import Session
|
|
from messenger.shared.application.errors import Unavailable
|
|
from messenger.shared.application.ports import Logger
|
|
|
|
REVOKED = "-"
|
|
FAILURES = (RedisError, OSError)
|
|
|
|
|
|
def key_of(token_hash: bytes) -> str:
|
|
return f"session:{token_hash.hex()}"
|
|
|
|
|
|
def milliseconds(moment: datetime) -> int:
|
|
return int(moment.timestamp() * 1000)
|
|
|
|
|
|
def encode(session: Session) -> str:
|
|
return f"{session.user_id} {session.created_at.isoformat()} {session.expires_at.isoformat()}"
|
|
|
|
|
|
def decode(token_hash: bytes, value: str) -> Session:
|
|
user_id, created_at, expires_at = value.split(" ")
|
|
return Session(
|
|
token_hash=token_hash,
|
|
user_id=UUID(user_id),
|
|
created_at=datetime.fromisoformat(created_at),
|
|
expires_at=datetime.fromisoformat(expires_at),
|
|
)
|
|
|
|
|
|
class NoRevocations:
|
|
async def revoke(self, session: Session) -> None:
|
|
return None
|
|
|
|
async def restore(self, session: Session) -> None:
|
|
return None
|
|
|
|
|
|
class CachedSessionDirectory:
|
|
__slots__ = ("_client", "_cooldown", "_limit", "_logger", "_origin", "_resume_at")
|
|
|
|
def __init__(
|
|
self,
|
|
origin: SessionDirectory,
|
|
client: Redis,
|
|
logger: Logger,
|
|
*,
|
|
limit: timedelta,
|
|
cooldown: float,
|
|
) -> None:
|
|
self._origin = origin
|
|
self._client = client
|
|
self._logger = logger
|
|
self._limit = limit
|
|
self._cooldown = cooldown
|
|
self._resume_at = 0.0
|
|
|
|
async def find(self, token_hash: bytes, now: datetime) -> Session | None:
|
|
key = key_of(token_hash)
|
|
cached = await self._read(key)
|
|
if cached == REVOKED:
|
|
return None
|
|
if cached is not None:
|
|
session = decode(token_hash, cached)
|
|
return session if session.expires_at > now else None
|
|
session = await self._origin.find(token_hash, now)
|
|
if session is not None and self._closed():
|
|
until = milliseconds(min(session.expires_at, now + self._limit))
|
|
await self._quietly(self._client.set(key, encode(session), pxat=until, nx=True))
|
|
return session
|
|
|
|
async def revoke(self, session: Session) -> None:
|
|
if not self._closed():
|
|
raise Unavailable("кэш сессий недоступен")
|
|
try:
|
|
await self._client.set(
|
|
key_of(session.token_hash), REVOKED, pxat=milliseconds(session.expires_at)
|
|
)
|
|
except FAILURES as error:
|
|
self._trip(error)
|
|
raise Unavailable("кэш сессий недоступен") from error
|
|
|
|
async def restore(self, session: Session) -> None:
|
|
await self._quietly(self._client.delete(key_of(session.token_hash)))
|
|
|
|
async def _read(self, key: str) -> str | None:
|
|
if not self._closed():
|
|
return None
|
|
value = await self._quietly(self._client.get(key))
|
|
return value.decode() if isinstance(value, bytes) else value
|
|
|
|
async def _quietly[ResultT](self, call: Awaitable[ResultT]) -> ResultT | None:
|
|
try:
|
|
return await call
|
|
except FAILURES as error:
|
|
self._trip(error)
|
|
return None
|
|
|
|
def _closed(self) -> bool:
|
|
return time.monotonic() >= self._resume_at
|
|
|
|
def _trip(self, error: Exception) -> None:
|
|
self._resume_at = time.monotonic() + self._cooldown
|
|
self._logger.warning("cache.bypassed", error=type(error).__name__, limit=self._cooldown)
|