chore: carry lab 3 over
- carry the lab 3 solution over from mtusi2026lab3-safronov (solution/bvt2301-safronov, ce89eba): src, migrations, student-tests, bench, openspec, .claude, infra/haproxy and infra/valkey, own scripts, Dockerfile, compose, pyproject and uv lock - merge Makefile, .gitignore and .dockerignore (the lab 3 versions only add lines to the skeleton, which is the same in lab 4) and .env.example (lab 4 skeleton names listed in the header) - rename the compose project to mtusi-lab4 and the image to :lab4 so the stand does not reuse the lab 3 containers and volumes - update AGENTS.md for lab 4: current lab, origin commit, contract and test files of the new skeleton Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,223 @@
|
||||
"""Зависимости ручек: сессия БД, сервисы, вход и текущая сессия, страница.
|
||||
|
||||
Сервисы получают сессию БД, а чаты и сообщения — ещё и кэш процесса
|
||||
(`src/infra/cache/instance.py`).
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import base64
|
||||
import binascii
|
||||
import re
|
||||
from collections.abc import AsyncIterator
|
||||
from dataclasses import dataclass
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import Depends, Query, Security
|
||||
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
||||
from fastapi.security.http import HTTPBase
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from src.config import settings
|
||||
from src.core import exceptions
|
||||
from src.core.services import (
|
||||
ChatService,
|
||||
MessageService,
|
||||
SessionService,
|
||||
UserService,
|
||||
)
|
||||
from src.infra.cache.instance import cache
|
||||
from src.infra.db import is_db_unavailable, ping
|
||||
from src.infra.db.session import engine, session_factory
|
||||
from src.infra.logger import AbstractLogger, current_user_id, get_logger
|
||||
from src.schemas import dataclasses
|
||||
from src.utils.constants import (
|
||||
PAGE_LIMIT_DEFAULT,
|
||||
PAGE_LIMIT_MAX,
|
||||
PAGE_LIMIT_MIN,
|
||||
PASSWORD_MAX_LENGTH,
|
||||
PASSWORD_MIN_LENGTH,
|
||||
READINESS_DB_TIMEOUT_SECONDS,
|
||||
USERNAME_PATTERN,
|
||||
)
|
||||
|
||||
logger: AbstractLogger = get_logger().bind(module="api_dependencies")
|
||||
|
||||
|
||||
async def get_db_session() -> AsyncIterator[AsyncSession]:
|
||||
"""Одна сессия БД на запрос; commit делает сервис.
|
||||
|
||||
Незакоммиченное при выходе откатывается. Вся работа запроса с БД
|
||||
ограничена `[database] request_timeout_seconds`: зависший Postgres не
|
||||
держит запрос бесконечно. Недоступность БД (`is_db_unavailable`) —
|
||||
503 `unavailable`, а соединение не возвращается в пул: его состояние
|
||||
неизвестно, а откат на зависшем сервере повис бы.
|
||||
"""
|
||||
async with session_factory() as db_session:
|
||||
try:
|
||||
async with asyncio.timeout(
|
||||
settings.database.request_timeout_seconds,
|
||||
):
|
||||
yield db_session
|
||||
except Exception as e:
|
||||
if not is_db_unavailable(e):
|
||||
raise
|
||||
await db_session.invalidate()
|
||||
logger.warning(
|
||||
"Database is unavailable",
|
||||
error_type=type(e).__name__,
|
||||
error=str(e),
|
||||
)
|
||||
raise exceptions.ServiceUnavailable from e
|
||||
|
||||
|
||||
DbSessionDep = Annotated[AsyncSession, Depends(get_db_session)]
|
||||
|
||||
|
||||
async def require_database() -> None:
|
||||
"""Readiness: Postgres отвечает на `SELECT 1` за отведённое время.
|
||||
|
||||
Любая ошибка — 503: готовность не должна отвечать 500. Не логирует:
|
||||
healthcheck спрашивает каждые несколько секунд.
|
||||
"""
|
||||
try:
|
||||
await ping(engine, timeout=READINESS_DB_TIMEOUT_SECONDS)
|
||||
except Exception as e:
|
||||
raise exceptions.ServiceUnavailable from e
|
||||
|
||||
|
||||
async def get_user_service(db_session: DbSessionDep) -> UserService:
|
||||
return UserService(db_session=db_session)
|
||||
|
||||
|
||||
async def get_chat_service(db_session: DbSessionDep) -> ChatService:
|
||||
return ChatService(db_session=db_session, cache=cache)
|
||||
|
||||
|
||||
async def get_message_service(db_session: DbSessionDep) -> MessageService:
|
||||
return MessageService(db_session=db_session, cache=cache)
|
||||
|
||||
|
||||
async def get_session_service(db_session: DbSessionDep) -> SessionService:
|
||||
return SessionService(db_session=db_session)
|
||||
|
||||
|
||||
UserServiceDep = Annotated[UserService, Depends(get_user_service)]
|
||||
ChatServiceDep = Annotated[ChatService, Depends(get_chat_service)]
|
||||
MessageServiceDep = Annotated[MessageService, Depends(get_message_service)]
|
||||
SessionServiceDep = Annotated[SessionService, Depends(get_session_service)]
|
||||
|
||||
|
||||
# схемы basicAuth и bearerAuth из contracts/openapi.json: объявлены в
|
||||
# /openapi.json и дают кнопку Authorize в /docs. auto_error=False — нет
|
||||
# заголовка или схема чужая даёт None, а 401 в формате контракта бросает
|
||||
# сервис. HTTPBase отдаёт credentials как есть: HTTPBasic FastAPI
|
||||
# декодирует ASCII и на пароле не из ASCII сам ответил бы 401
|
||||
basic_scheme = HTTPBase(
|
||||
scheme="basic",
|
||||
scheme_name="basicAuth",
|
||||
auto_error=False,
|
||||
)
|
||||
bearer_scheme = HTTPBearer(
|
||||
scheme_name="bearerAuth",
|
||||
bearerFormat="opaque session token",
|
||||
auto_error=False,
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class BasicCredentials:
|
||||
username: str
|
||||
password: str
|
||||
|
||||
|
||||
def parse_basic(
|
||||
credentials: HTTPAuthorizationCredentials | None,
|
||||
) -> BasicCredentials | None:
|
||||
"""username и пароль из `Authorization: Basic`; None — разбор не удался.
|
||||
|
||||
base64 строго, UTF-8, разделитель — первое двоеточие: в username его
|
||||
не бывает, в пароле оно допустимо. Значения, которые не могут быть
|
||||
верными (формат username и длина пароля публичны), отсекаются здесь:
|
||||
до БД и KDF не доходит ни мусор, ни пароль в мегабайт.
|
||||
"""
|
||||
if credentials is None or credentials.scheme.lower() != "basic":
|
||||
return None
|
||||
try:
|
||||
decoded = base64.b64decode(credentials.credentials, validate=True)
|
||||
username, separator, password = decoded.decode().partition(":")
|
||||
except (binascii.Error, UnicodeDecodeError):
|
||||
return None
|
||||
if not separator or not re.fullmatch(USERNAME_PATTERN, username):
|
||||
return None
|
||||
if not PASSWORD_MIN_LENGTH <= len(password) <= PASSWORD_MAX_LENGTH:
|
||||
return None
|
||||
return BasicCredentials(username=username, password=password)
|
||||
|
||||
|
||||
async def get_basic_credentials(
|
||||
credentials: Annotated[
|
||||
HTTPAuthorizationCredentials | None,
|
||||
Security(basic_scheme),
|
||||
],
|
||||
) -> BasicCredentials:
|
||||
"""Учётные данные входа; любой сбой разбора — тот же 401, что и
|
||||
неверный пароль."""
|
||||
parsed = parse_basic(credentials)
|
||||
if parsed is None:
|
||||
raise exceptions.InvalidCredentials
|
||||
return parsed
|
||||
|
||||
|
||||
BasicCredentialsDep = Annotated[
|
||||
BasicCredentials,
|
||||
Depends(get_basic_credentials),
|
||||
]
|
||||
|
||||
|
||||
async def get_current_session(
|
||||
credentials: Annotated[
|
||||
HTTPAuthorizationCredentials | None,
|
||||
Security(bearer_scheme),
|
||||
],
|
||||
sessions: SessionServiceDep,
|
||||
) -> dataclasses.CurrentSessionDTO:
|
||||
"""Действующая сессия по Bearer-токену; иначе 401."""
|
||||
current = await sessions.authenticate(
|
||||
token=credentials.credentials if credentials else None,
|
||||
)
|
||||
current_user_id.set(str(current.user.id))
|
||||
return current
|
||||
|
||||
|
||||
CurrentSession = Annotated[
|
||||
dataclasses.CurrentSessionDTO,
|
||||
Depends(get_current_session),
|
||||
]
|
||||
|
||||
|
||||
async def get_current_user(
|
||||
current: CurrentSession,
|
||||
) -> dataclasses.UserFullDTO:
|
||||
return current.user
|
||||
|
||||
|
||||
CurrentUser = Annotated[dataclasses.UserFullDTO, Depends(get_current_user)]
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class PageQuery:
|
||||
limit: int
|
||||
cursor: str | None
|
||||
|
||||
|
||||
async def get_page_query(
|
||||
limit: Annotated[
|
||||
int,
|
||||
Query(ge=PAGE_LIMIT_MIN, le=PAGE_LIMIT_MAX),
|
||||
] = PAGE_LIMIT_DEFAULT,
|
||||
cursor: Annotated[str | None, Query(min_length=1)] = None,
|
||||
) -> PageQuery:
|
||||
return PageQuery(limit=limit, cursor=cursor)
|
||||
|
||||
|
||||
PageQueryDep = Annotated[PageQuery, Depends(get_page_query)]
|
||||
Reference in New Issue
Block a user