chore: port lab 6 solution into the lab 7 skeleton

Source: mtusi2026lab6-safronov, solution/bvt2301-safronov, 6c6a065.
Files follow AGENTS.md, "Переход в следующую лабу". Contracts, public
tests, README, REPORT and evidence of lab 6 are not carried over; infra
and scripts of the lab 7 skeleton stay as they are.
Makefile is the lab 6 one with the lab 7 skeleton part restored
(HTTPS BASE_URL on 8443, test-security); .gitignore and .dockerignore
are taken from lab 6 because both skeletons have the same files;
.env.example is the lab 6 one without changes.
The compose project, image and CI prefix are renamed to lab7, and
references to the previous lab now name lab6.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-16 03:59:04 +03:00
co-authored by Claude Opus 5.5
parent 20afc2c790
commit 089d78609d
687 changed files with 178271 additions and 40 deletions
+6
View File
@@ -0,0 +1,6 @@
from src.infra.cache.client import Cache, create_cache
__all__ = [
"Cache",
"create_cache",
]
+163
View File
@@ -0,0 +1,163 @@
"""Клиент Valkey со сроком на команду и обходом при отказе.
redis-py по умолчанию повторяет команду с backoff: замороженный Valkey
задерживал запрос на 6 с вместо таймаута клиента (design change
`membership-cache`, Context). Здесь повтор один и только на обрыв
соединения (`ConnectionError`): старое соединение пула после рестарта
Valkey переоткрывается сразу, а таймаут не повторяется. Вся команда —
ожидание пула, соединение, повтор и ответ — ограничена
`[cache] timeout_seconds`. После отказа кэш пропускается на
`[cache] retry_after_seconds`: запросы идут сразу в PostgreSQL, не
дожидаясь таймаута каждый раз.
"""
import asyncio
import time
from types import MappingProxyType
from opentelemetry.trace import Span
from redis.asyncio import BlockingConnectionPool, Redis
from redis.asyncio.retry import Retry
from redis.backoff import NoBackoff
from redis.exceptions import ConnectionError as RedisConnectionError
from redis.exceptions import RedisError
from src.config.settings import Cache as CacheSettings
from src.infra import telemetry
from src.infra.logger import AbstractLogger, get_logger
from src.utils.constants import ATTR_CACHE_RESULT
logger: AbstractLogger = get_logger().bind(module="cache")
# исход команды в span (`messenger.cache.result`)
CACHE_HIT = "hit"
CACHE_MISS = "miss"
CACHE_STORED = "stored"
CACHE_ERROR = "error"
# окно пропуска после отказа: команды не было
CACHE_SKIPPED = "skipped"
_SPAN_ATTRIBUTES = MappingProxyType({"db.system.name": "valkey"})
def _result(
span: Span | None,
result: str,
*,
error: BaseException | None = None,
) -> None:
if span is None:
return
span.set_attribute(ATTR_CACHE_RESULT, result)
if error is not None:
telemetry.mark_error(span, error)
class Cache:
"""Кэш поверх клиента Valkey: отказ — промах, а не исключение.
`namespace` — имя базы PostgreSQL, из которой читаются значения: на
одном Valkey ключи разных баз не пересекаются.
"""
def __init__(
self,
client: Redis,
*,
namespace: str,
timeout_seconds: float,
retry_after_seconds: float,
) -> None:
self.namespace = namespace
self._client = client
self._timeout_seconds = timeout_seconds
self._retry_after_seconds = retry_after_seconds
# monotonic-время конца пропуска; None — кэш работает
self._skip_until: float | None = None
async def get(self, key: str) -> str | None:
"""Значение ключа; `None` — промах, в том числе из-за отказа."""
# span без ключа: в нём chat_id (design change otel-telemetry,
# решение 12); исход — атрибут, отказ — ещё и статус ошибки
with telemetry.child_span("GET", attributes=_SPAN_ATTRIBUTES) as span:
if self._skipping():
_result(span, CACHE_SKIPPED)
return None
try:
async with asyncio.timeout(self._timeout_seconds):
value = await self._client.get(key)
except (RedisError, OSError) as e:
self._failed(e)
_result(span, CACHE_ERROR, error=e)
return None
self._succeeded()
_result(span, CACHE_MISS if value is None else CACHE_HIT)
return value
async def set(self, key: str, value: str, *, ttl_seconds: int) -> bool:
"""Записать со сроком; `False` — не записано из-за отказа."""
with telemetry.child_span("SET", attributes=_SPAN_ATTRIBUTES) as span:
if self._skipping():
_result(span, CACHE_SKIPPED)
return False
try:
async with asyncio.timeout(self._timeout_seconds):
await self._client.set(key, value, ex=ttl_seconds)
except (RedisError, OSError) as e:
self._failed(e)
_result(span, CACHE_ERROR, error=e)
return False
self._succeeded()
_result(span, CACHE_STORED)
return True
async def aclose(self) -> None:
await self._client.aclose()
def _skipping(self) -> bool:
return (
self._skip_until is not None
and time.monotonic() < self._skip_until
)
def _failed(self, error: Exception) -> None:
# warning — один на отказ: неудачные пробы после пропуска молчат.
# TimeoutError от asyncio.timeout без текста — тогда repr
if self._skip_until is None:
logger.warning(
"Cache is unavailable",
error=str(error) or repr(error),
error_type=type(error).__name__,
retry_after_seconds=self._retry_after_seconds,
)
self._skip_until = time.monotonic() + self._retry_after_seconds
def _succeeded(self) -> None:
if self._skip_until is not None:
self._skip_until = None
logger.info("Cache is available again")
def create_cache(cache: CacheSettings, *, namespace: str) -> Cache:
"""Кэш с пулом и таймаутами из `[cache]`; соединения — лениво."""
# BlockingConnectionPool: при всплеске запросов ждёт свободное
# соединение, а обычный пул сразу бросал бы MaxConnectionsError, и
# здоровый Valkey пропускался бы как отказавший.
# Retry — из redis.asyncio: синхронный класс асинхронное соединение
# вызывает через await, и повтор молча не выполняется
pool = BlockingConnectionPool(
host=cache.host,
port=cache.port,
password=cache.password.get_secret_value() or None,
max_connections=cache.max_connections,
timeout=cache.timeout_seconds,
socket_timeout=cache.timeout_seconds,
socket_connect_timeout=cache.timeout_seconds,
retry=Retry(NoBackoff(), 1, supported_errors=(RedisConnectionError,)),
decode_responses=True,
)
return Cache(
Redis.from_pool(pool),
namespace=namespace,
timeout_seconds=cache.timeout_seconds,
retry_after_seconds=cache.retry_after_seconds,
)
+13
View File
@@ -0,0 +1,13 @@
"""Кэш процесса API (Valkey).
Создаётся при импорте по `settings.cache`, соединения пул открывает
лениво. Импортируют модуль только `src/main.py` (закрытие в lifespan) и
`src/api/dependencies.py`, как `src/infra/db/session.py`. Ключи — по
имени базы из `settings.database`: `make test_isolated` с базой
`test_<db>` не видит карточек рабочей.
"""
from src.config import settings
from src.infra.cache.client import create_cache
cache = create_cache(settings.cache, namespace=settings.database.name)