forked from mtusi2026/mtusi2026lab2
feat: ЛР2 - PostgreSQL, Redis сессии и keyset-пагинация
This commit is contained in:
+27
@@ -0,0 +1,27 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import secrets
|
||||
from argon2 import PasswordHasher
|
||||
from argon2.exceptions import VerifyMismatchError
|
||||
|
||||
_hasher = PasswordHasher()
|
||||
|
||||
|
||||
def hash_password(password: str) -> str:
|
||||
"""Хэширует пароль с использованием Argon2id."""
|
||||
return _hasher.hash(password)
|
||||
|
||||
|
||||
def verify_password(hash_str: str, password: str) -> bool:
|
||||
"""Проверяет пароль на соответствие хэшу Argon2id."""
|
||||
try:
|
||||
return _hasher.verify(hash_str, password)
|
||||
except VerifyMismatchError:
|
||||
return False
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def generate_session_token() -> str:
|
||||
"""Генерирует криптографически стойкий непрозрачный токен сессии (256 бит энтропии)."""
|
||||
return secrets.token_urlsafe(32)
|
||||
+32
-5
@@ -1,6 +1,33 @@
|
||||
import os
|
||||
from __future__ import annotations
|
||||
|
||||
APP_HOST = os.getenv("APP_HOST", "0.0.0.0")
|
||||
APP_PORT = int(os.getenv("APP_PORT", "8080"))
|
||||
APP_ENV = os.getenv("APP_ENV", "lab")
|
||||
LOG_LEVEL = os.getenv("LOG_LEVEL", "INFO")
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def _get_val(env_name: str, file_env_name: str | None = None, default: str = "") -> str:
|
||||
if file_env_name and file_env_name in os.environ:
|
||||
file_path = Path(os.environ[file_env_name])
|
||||
if file_path.is_file():
|
||||
return file_path.read_text(encoding="utf-8").strip()
|
||||
return os.getenv(env_name, default)
|
||||
|
||||
|
||||
APP_HOST: str = os.getenv("APP_HOST", "0.0.0.0")
|
||||
APP_PORT: int = int(os.getenv("APP_PORT", "8080"))
|
||||
APP_ENV: str = os.getenv("APP_ENV", "lab")
|
||||
LOG_LEVEL: str = os.getenv("LOG_LEVEL", "INFO")
|
||||
|
||||
SESSION_TTL_SECONDS: int = int(os.getenv("SESSION_TTL_SECONDS", "3600"))
|
||||
SESSION_STORE: str = os.getenv("SESSION_STORE", "redis").lower()
|
||||
|
||||
DATABASE_URL: str = _get_val(
|
||||
"DATABASE_URL",
|
||||
"DATABASE_URL_FILE",
|
||||
"postgresql://postgres:postgres@postgres:5432/messenger",
|
||||
)
|
||||
|
||||
CACHE_URL: str = _get_val(
|
||||
"CACHE_URL",
|
||||
"CACHE_URL_FILE",
|
||||
"redis://redis:6379/0",
|
||||
)
|
||||
|
||||
+21
-17
@@ -1,26 +1,30 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from uuid import UUID
|
||||
|
||||
from fastapi import Header, Request
|
||||
from fastapi import Depends, Header, Request
|
||||
|
||||
from app.errors import UnauthorizedError
|
||||
from app.schemas import UserResponse
|
||||
from app.storage import UnauthorizedError, storage
|
||||
from app.storage import storage
|
||||
|
||||
|
||||
async def get_current_user(
|
||||
request: Request,
|
||||
x_user_id: str | None = Header(default=None, alias="X-User-Id"),
|
||||
) -> UserResponse:
|
||||
if not x_user_id or not x_user_id.strip():
|
||||
raise UnauthorizedError("Отсутствует заголовок X-User-Id")
|
||||
async def get_current_token(
|
||||
authorization: str | None = Header(default=None, alias="Authorization"),
|
||||
) -> str:
|
||||
if not authorization or not authorization.strip():
|
||||
raise UnauthorizedError("Отсутствует заголовок Authorization")
|
||||
|
||||
# валидация формата UUID
|
||||
try:
|
||||
UUID(x_user_id)
|
||||
except ValueError:
|
||||
raise UnauthorizedError("Неверный формат заголовка X-User-Id")
|
||||
parts = authorization.strip().split(maxsplit=1)
|
||||
if len(parts) != 2 or parts[0].lower() != "bearer":
|
||||
raise UnauthorizedError("Неверная схема авторизации (ожидается Bearer)")
|
||||
|
||||
# проверка существования пользователя
|
||||
user = await storage.get_user_by_id(x_user_id)
|
||||
token = parts[1].strip()
|
||||
if not token:
|
||||
raise UnauthorizedError("Пустой Bearer токен")
|
||||
return token
|
||||
|
||||
|
||||
async def get_current_user(token: str = Depends(get_current_token)) -> UserResponse:
|
||||
user = await storage.get_session_user(token)
|
||||
if not user:
|
||||
raise UnauthorizedError("Недействительная или истекшая сессия")
|
||||
return user
|
||||
|
||||
+50
-11
@@ -9,12 +9,27 @@ from fastapi.responses import JSONResponse
|
||||
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||
|
||||
from app.schemas import ErrorCode, ErrorDetail, ErrorResponse
|
||||
from app.storage import (
|
||||
ConflictError,
|
||||
InvalidRequestError,
|
||||
NotFoundError,
|
||||
UnauthorizedError,
|
||||
)
|
||||
|
||||
|
||||
class StorageError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class InvalidRequestError(StorageError):
|
||||
pass
|
||||
|
||||
|
||||
class NotFoundError(StorageError):
|
||||
pass
|
||||
|
||||
|
||||
class ConflictError(StorageError):
|
||||
pass
|
||||
|
||||
|
||||
class UnauthorizedError(StorageError):
|
||||
pass
|
||||
|
||||
|
||||
logger = logging.getLogger("app.errors")
|
||||
|
||||
@@ -27,15 +42,22 @@ def get_request_id(request: Request) -> str:
|
||||
|
||||
|
||||
def make_error_response(
|
||||
status_code: int, code: ErrorCode, message: str, request_id: str
|
||||
status_code: int,
|
||||
code: ErrorCode,
|
||||
message: str,
|
||||
request_id: str,
|
||||
headers: dict[str, str] | None = None,
|
||||
) -> JSONResponse:
|
||||
payload = ErrorResponse(
|
||||
error=ErrorDetail(code=code, message=message, request_id=request_id)
|
||||
).model_dump()
|
||||
resp_headers = {"X-Request-Id": request_id, "Content-Type": "application/json"}
|
||||
if headers:
|
||||
resp_headers.update(headers)
|
||||
return JSONResponse(
|
||||
status_code=status_code,
|
||||
content=payload,
|
||||
headers={"X-Request-Id": request_id, "Content-Type": "application/json"},
|
||||
headers=resp_headers,
|
||||
)
|
||||
|
||||
|
||||
@@ -54,8 +76,17 @@ def register_error_handlers(app: FastAPI) -> None:
|
||||
request: Request, exc: UnauthorizedError
|
||||
) -> JSONResponse:
|
||||
req_id = get_request_id(request)
|
||||
scheme = (
|
||||
'Basic realm="messenger", charset="UTF-8"'
|
||||
if request.url.path == "/api/v1/auth/sessions"
|
||||
else 'Bearer realm="messenger"'
|
||||
)
|
||||
return make_error_response(
|
||||
status.HTTP_401_UNAUTHORIZED, ErrorCode.UNAUTHORIZED, str(exc), req_id
|
||||
status.HTTP_401_UNAUTHORIZED,
|
||||
ErrorCode.UNAUTHORIZED,
|
||||
str(exc),
|
||||
req_id,
|
||||
headers={"WWW-Authenticate": scheme},
|
||||
)
|
||||
|
||||
@app.exception_handler(NotFoundError)
|
||||
@@ -77,7 +108,6 @@ def register_error_handlers(app: FastAPI) -> None:
|
||||
request: Request, exc: RequestValidationError
|
||||
) -> JSONResponse:
|
||||
req_id = get_request_id(request)
|
||||
# Ошибки валидации входного JSON маппятся на 400
|
||||
errors = exc.errors()
|
||||
messages = []
|
||||
for err in errors:
|
||||
@@ -95,10 +125,17 @@ def register_error_handlers(app: FastAPI) -> None:
|
||||
) -> JSONResponse:
|
||||
req_id = get_request_id(request)
|
||||
code = ErrorCode.INTERNAL_ERROR
|
||||
extra_headers: dict[str, str] = {}
|
||||
if exc.status_code == 400:
|
||||
code = ErrorCode.INVALID_REQUEST
|
||||
elif exc.status_code == 401:
|
||||
code = ErrorCode.UNAUTHORIZED
|
||||
scheme = (
|
||||
'Basic realm="messenger", charset="UTF-8"'
|
||||
if request.url.path == "/api/v1/auth/sessions"
|
||||
else 'Bearer realm="messenger"'
|
||||
)
|
||||
extra_headers["WWW-Authenticate"] = scheme
|
||||
elif exc.status_code == 404:
|
||||
code = ErrorCode.NOT_FOUND
|
||||
elif exc.status_code == 409:
|
||||
@@ -113,7 +150,9 @@ def register_error_handlers(app: FastAPI) -> None:
|
||||
code = ErrorCode.UNAVAILABLE
|
||||
|
||||
msg = exc.detail if isinstance(exc.detail, str) else "HTTP ошибка"
|
||||
return make_error_response(exc.status_code, code, msg, req_id)
|
||||
return make_error_response(
|
||||
exc.status_code, code, msg, req_id, headers=extra_headers
|
||||
)
|
||||
|
||||
@app.exception_handler(Exception)
|
||||
async def unhandled_exception_handler(
|
||||
|
||||
+7
-2
@@ -9,10 +9,12 @@ from fastapi import FastAPI
|
||||
from app.config import APP_HOST, APP_PORT, LOG_LEVEL
|
||||
from app.errors import register_error_handlers
|
||||
from app.middleware import RequestIdAndLoggingMiddleware
|
||||
from app.routes.auth import router as auth_router
|
||||
from app.routes.chats import router as chats_router
|
||||
from app.routes.health import router as health_router
|
||||
from app.routes.messages import router as messages_router
|
||||
from app.routes.users import router as users_router
|
||||
from app.storage import storage
|
||||
|
||||
logger = logging.getLogger("app.lifecycle")
|
||||
|
||||
@@ -22,13 +24,15 @@ async def lifespan(app: FastAPI):
|
||||
logger.info(
|
||||
"Starting messenger server on %s:%d (env: %s)", APP_HOST, APP_PORT, LOG_LEVEL
|
||||
)
|
||||
await storage.connect()
|
||||
yield
|
||||
logger.info("Graceful shutdown: closing connections and cleaning up...")
|
||||
logger.info("Graceful shutdown: closing connections...")
|
||||
await storage.disconnect()
|
||||
|
||||
|
||||
app = FastAPI(
|
||||
title="highload-messenger",
|
||||
version="1.1.0",
|
||||
version="1.2.0",
|
||||
docs_url="/docs",
|
||||
redoc_url=None,
|
||||
lifespan=lifespan,
|
||||
@@ -39,6 +43,7 @@ app.add_middleware(RequestIdAndLoggingMiddleware)
|
||||
register_error_handlers(app)
|
||||
|
||||
app.include_router(health_router)
|
||||
app.include_router(auth_router)
|
||||
app.include_router(users_router)
|
||||
app.include_router(chats_router)
|
||||
app.include_router(messages_router)
|
||||
|
||||
@@ -29,6 +29,21 @@ class RequestIdAndLoggingMiddleware(BaseHTTPMiddleware):
|
||||
request.state.request_id = request_id
|
||||
start_time = time.monotonic()
|
||||
|
||||
if request.method in ("POST", "PUT", "PATCH") and request.url.path != "/api/v1/auth/sessions":
|
||||
ct = request.headers.get("content-type")
|
||||
if ct:
|
||||
ct_clean = ct.split(";")[0].strip().lower()
|
||||
if ct_clean != "application/json":
|
||||
from fastapi import status
|
||||
from app.errors import make_error_response
|
||||
from app.schemas import ErrorCode
|
||||
return make_error_response(
|
||||
status.HTTP_415_UNSUPPORTED_MEDIA_TYPE,
|
||||
ErrorCode.UNSUPPORTED_MEDIA_TYPE,
|
||||
f"Неподдерживаемый тип содержимого '{ct}'. Ожидается application/json",
|
||||
request_id,
|
||||
)
|
||||
|
||||
try:
|
||||
response = await call_next(request)
|
||||
except Exception:
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
from fastapi import APIRouter, Depends, Header, Request, Response, status
|
||||
|
||||
from app.dependencies import get_current_token
|
||||
from app.errors import InvalidRequestError, UnauthorizedError
|
||||
from app.schemas import SessionResponse
|
||||
from app.storage import storage
|
||||
|
||||
router = APIRouter(prefix="/api/v1/auth/sessions", tags=["auth"])
|
||||
|
||||
|
||||
@router.post("", response_model=SessionResponse, status_code=status.HTTP_201_CREATED)
|
||||
async def create_session(
|
||||
request: Request,
|
||||
authorization: str | None = Header(default=None, alias="Authorization"),
|
||||
) -> SessionResponse:
|
||||
"""Аутентификация пользователя через Basic Auth и создание новой сессии."""
|
||||
body = await request.body()
|
||||
if body and body.strip():
|
||||
raise InvalidRequestError("Тело запроса для создания сессии должно быть пустым")
|
||||
|
||||
if not authorization or not authorization.strip():
|
||||
raise UnauthorizedError("Отсутствует заголовок Authorization")
|
||||
|
||||
parts = authorization.strip().split(maxsplit=1)
|
||||
if len(parts) != 2 or parts[0].lower() != "basic":
|
||||
raise UnauthorizedError("Неверная схема авторизации (ожидается Basic)")
|
||||
|
||||
try:
|
||||
raw_bytes = base64.b64decode(parts[1].strip())
|
||||
raw_str = raw_bytes.decode("utf-8")
|
||||
if ":" not in raw_str:
|
||||
raise UnauthorizedError("Некорректный формат Basic credentials")
|
||||
username, password = raw_str.split(":", 1)
|
||||
except Exception:
|
||||
raise UnauthorizedError("Некорректный заголовок Basic авторизации")
|
||||
|
||||
user = await storage.authenticate_user(username, password)
|
||||
if not user:
|
||||
raise UnauthorizedError("Неверное имя пользователя или пароль")
|
||||
|
||||
session = await storage.create_session(user)
|
||||
return session
|
||||
|
||||
|
||||
@router.delete("/current", status_code=status.HTTP_204_NO_CONTENT)
|
||||
async def delete_current_session(
|
||||
request: Request,
|
||||
token: str = Depends(get_current_token),
|
||||
) -> Response:
|
||||
"""Отзыв текущей сессии."""
|
||||
body = await request.body()
|
||||
if body and body.strip():
|
||||
raise InvalidRequestError("Тело запроса для отзыва сессии должно быть пустым")
|
||||
|
||||
user = await storage.get_session_user(token)
|
||||
if not user:
|
||||
raise UnauthorizedError("Недействительная или уже отозванная сессия")
|
||||
|
||||
await storage.delete_session(token)
|
||||
return Response(status_code=status.HTTP_204_NO_CONTENT)
|
||||
@@ -1,8 +1,10 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, status
|
||||
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||
|
||||
from app.schemas import HealthResponse
|
||||
from app.storage import storage
|
||||
|
||||
router = APIRouter(tags=["health"])
|
||||
|
||||
@@ -11,6 +13,7 @@ router = APIRouter(tags=["health"])
|
||||
"/health/live", response_model=HealthResponse, status_code=status.HTTP_200_OK
|
||||
)
|
||||
async def health_live() -> HealthResponse:
|
||||
"""Проверка жизни процесса (Liveness)."""
|
||||
return HealthResponse(status="ok")
|
||||
|
||||
|
||||
@@ -18,4 +21,11 @@ async def health_live() -> HealthResponse:
|
||||
"/health/ready", response_model=HealthResponse, status_code=status.HTTP_200_OK
|
||||
)
|
||||
async def health_ready() -> HealthResponse:
|
||||
"""Проверка готовности сервиса и его зависимостей (Readiness)."""
|
||||
is_ready = await storage.check_health()
|
||||
if not is_ready:
|
||||
raise StarletteHTTPException(
|
||||
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
||||
detail="Сервис или его хранилища недоступны",
|
||||
)
|
||||
return HealthResponse(status="ok")
|
||||
|
||||
@@ -36,7 +36,7 @@ async def create_message(
|
||||
) -> MessageResponse:
|
||||
"""Отправка сообщения в чат."""
|
||||
valid_id = validate_uuid(chat_id, "chat_id")
|
||||
msg = await storage.create_message(
|
||||
msg = await storage.send_message(
|
||||
caller_id=current_user.id,
|
||||
chat_id=valid_id,
|
||||
text=body.text,
|
||||
|
||||
+3
-1
@@ -13,7 +13,9 @@ router = APIRouter(prefix="/api/v1/users", tags=["users"])
|
||||
async def create_user(body: CreateUserRequest) -> UserResponse:
|
||||
"""Регистрация нового пользователя."""
|
||||
user = await storage.create_user(
|
||||
username=body.username, display_name=body.display_name
|
||||
username=body.username,
|
||||
display_name=body.display_name,
|
||||
password=body.password,
|
||||
)
|
||||
return user
|
||||
|
||||
|
||||
+25
-7
@@ -50,6 +50,7 @@ class CreateUserRequest(BaseModel):
|
||||
|
||||
username: str = Field(min_length=3, max_length=32)
|
||||
display_name: str = Field(min_length=1, max_length=100)
|
||||
password: str = Field(min_length=12, max_length=128)
|
||||
|
||||
@field_validator("username")
|
||||
@classmethod
|
||||
@@ -61,8 +62,16 @@ class CreateUserRequest(BaseModel):
|
||||
@field_validator("display_name")
|
||||
@classmethod
|
||||
def validate_display_name(cls, v: str) -> str:
|
||||
if not v.strip():
|
||||
clean = v.replace("\x00", "")
|
||||
if not clean.strip():
|
||||
raise ValueError("Отображаемое имя не может состоять только из пробелов")
|
||||
return clean
|
||||
|
||||
@field_validator("password")
|
||||
@classmethod
|
||||
def validate_password(cls, v: str) -> str:
|
||||
if not v.strip():
|
||||
raise ValueError("Пароль не может состоять только из пробелов")
|
||||
return v
|
||||
|
||||
|
||||
@@ -75,6 +84,15 @@ class UserResponse(BaseModel):
|
||||
created_at: str
|
||||
|
||||
|
||||
class SessionResponse(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
token: str = Field(min_length=32)
|
||||
token_type: str = Field(default="Bearer")
|
||||
expires_at: str
|
||||
user: UserResponse
|
||||
|
||||
|
||||
class CreateChatRequest(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
@@ -84,17 +102,16 @@ class CreateChatRequest(BaseModel):
|
||||
@field_validator("title")
|
||||
@classmethod
|
||||
def validate_title(cls, v: str) -> str:
|
||||
if not v.strip():
|
||||
clean = v.replace("\x00", "")
|
||||
if not clean.strip():
|
||||
raise ValueError("Название не может состоять только из пробелов")
|
||||
return v
|
||||
return clean
|
||||
|
||||
@field_validator("member_ids")
|
||||
@classmethod
|
||||
def validate_member_ids(cls, v: list[str]) -> list[str]:
|
||||
# Проверка уникальности
|
||||
if len(v) != len(set(v)):
|
||||
raise ValueError("Идентификаторы участников должны быть уникальными")
|
||||
# Проверка формата каждого UUID
|
||||
for member_id in v:
|
||||
try:
|
||||
UUID(member_id)
|
||||
@@ -127,9 +144,10 @@ class CreateMessageRequest(BaseModel):
|
||||
@field_validator("text")
|
||||
@classmethod
|
||||
def validate_text(cls, v: str) -> str:
|
||||
if not v.strip():
|
||||
clean = v.replace("\x00", "")
|
||||
if not clean.strip():
|
||||
raise ValueError("Текст сообщения не может состоять только из пробелов")
|
||||
return v
|
||||
return clean
|
||||
|
||||
|
||||
class MessageResponse(BaseModel):
|
||||
|
||||
+444
-155
@@ -1,36 +1,36 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import base64
|
||||
import datetime as dt
|
||||
import json
|
||||
import logging
|
||||
import uuid
|
||||
from typing import Any
|
||||
|
||||
import asyncpg
|
||||
import redis.asyncio as redis
|
||||
|
||||
from app.auth import generate_session_token, hash_password, verify_password
|
||||
from app.config import (
|
||||
CACHE_URL,
|
||||
DATABASE_URL,
|
||||
SESSION_TTL_SECONDS,
|
||||
)
|
||||
from app.errors import (
|
||||
ConflictError,
|
||||
InvalidRequestError,
|
||||
NotFoundError,
|
||||
UnauthorizedError,
|
||||
)
|
||||
from app.schemas import (
|
||||
ChatResponse,
|
||||
MessageResponse,
|
||||
SessionResponse,
|
||||
UserResponse,
|
||||
now_utc_iso,
|
||||
)
|
||||
|
||||
|
||||
class StorageError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class InvalidRequestError(StorageError):
|
||||
pass
|
||||
|
||||
|
||||
class NotFoundError(StorageError):
|
||||
pass
|
||||
|
||||
|
||||
class ConflictError(StorageError):
|
||||
pass
|
||||
|
||||
|
||||
class UnauthorizedError(StorageError):
|
||||
pass
|
||||
logger = logging.getLogger("app.storage")
|
||||
|
||||
|
||||
def encode_cursor(data: dict) -> str:
|
||||
@@ -54,188 +54,477 @@ def decode_cursor(cursor_str: str) -> dict:
|
||||
raise InvalidRequestError("Некорректный курсор") from exc
|
||||
|
||||
|
||||
class InMemoryStorage:
|
||||
def _format_dt(d: dt.datetime) -> str:
|
||||
if d.tzinfo is None:
|
||||
d = d.replace(tzinfo=dt.timezone.utc)
|
||||
return d.astimezone(dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%fZ")
|
||||
|
||||
|
||||
class PostgresStorage:
|
||||
def __init__(self) -> None:
|
||||
self._lock = asyncio.Lock()
|
||||
self._users_by_id: dict[str, UserResponse] = {}
|
||||
self._users_by_username: dict[str, UserResponse] = {}
|
||||
self._chats_by_id: dict[str, ChatResponse] = {}
|
||||
self._messages_by_chat: dict[str, list[MessageResponse]] = {}
|
||||
self.pg_pool: asyncpg.Pool | None = None
|
||||
self.redis_client: redis.Redis | None = None
|
||||
|
||||
async def create_user(self, username: str, display_name: str) -> UserResponse:
|
||||
async with self._lock:
|
||||
if username in self._users_by_username:
|
||||
raise ConflictError("Имя пользователя уже занято")
|
||||
async def connect(self) -> None:
|
||||
logger.info("Подключение к PostgreSQL: %s", DATABASE_URL.split("@")[-1])
|
||||
self.pg_pool = await asyncpg.create_pool(
|
||||
DATABASE_URL,
|
||||
min_size=2,
|
||||
max_size=20,
|
||||
command_timeout=5.0,
|
||||
timeout=5.0,
|
||||
)
|
||||
|
||||
user_id = str(uuid.uuid4())
|
||||
created_at = now_utc_iso()
|
||||
user = UserResponse(
|
||||
id=user_id,
|
||||
username=username,
|
||||
display_name=display_name,
|
||||
created_at=created_at,
|
||||
logger.info("Подключение к Redis: %s", CACHE_URL.split("@")[-1])
|
||||
self.redis_client = redis.from_url(
|
||||
CACHE_URL,
|
||||
decode_responses=True,
|
||||
socket_connect_timeout=3.0,
|
||||
socket_timeout=3.0,
|
||||
)
|
||||
|
||||
async def disconnect(self) -> None:
|
||||
if self.pg_pool:
|
||||
await self.pg_pool.close()
|
||||
self.pg_pool = None
|
||||
if self.redis_client:
|
||||
await self.redis_client.close()
|
||||
self.redis_client = None
|
||||
|
||||
async def check_health(self) -> bool:
|
||||
if not self.pg_pool or not self.redis_client:
|
||||
return False
|
||||
try:
|
||||
async with self.pg_pool.acquire() as conn:
|
||||
await conn.fetchval("SELECT 1")
|
||||
await self.redis_client.ping()
|
||||
return True
|
||||
except Exception as exc:
|
||||
logger.warning("Ошибка проверки health: %s", exc)
|
||||
return False
|
||||
|
||||
# ------------------ Пользователи и аутентификация ------------------
|
||||
|
||||
async def create_user(
|
||||
self, username: str, display_name: str, password: str
|
||||
) -> UserResponse:
|
||||
user_id = uuid.uuid4()
|
||||
now = dt.datetime.now(dt.timezone.utc)
|
||||
pwd_hash = hash_password(password)
|
||||
display_name = display_name.replace("\x00", "")
|
||||
|
||||
assert self.pg_pool is not None
|
||||
try:
|
||||
async with self.pg_pool.acquire() as conn:
|
||||
await conn.execute(
|
||||
"""
|
||||
INSERT INTO users (id, username, display_name, password_hash, created_at)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
""",
|
||||
user_id,
|
||||
username,
|
||||
display_name,
|
||||
pwd_hash,
|
||||
now,
|
||||
)
|
||||
except asyncpg.UniqueViolationError:
|
||||
raise ConflictError("Имя пользователя уже занято")
|
||||
|
||||
return UserResponse(
|
||||
id=str(user_id),
|
||||
username=username,
|
||||
display_name=display_name,
|
||||
created_at=_format_dt(now),
|
||||
)
|
||||
|
||||
async def authenticate_user(
|
||||
self, username: str, password: str
|
||||
) -> UserResponse | None:
|
||||
assert self.pg_pool is not None
|
||||
async with self.pg_pool.acquire() as conn:
|
||||
row = await conn.fetchrow(
|
||||
"""
|
||||
SELECT id, username, display_name, password_hash, created_at
|
||||
FROM users
|
||||
WHERE username = $1
|
||||
""",
|
||||
username,
|
||||
)
|
||||
self._users_by_id[user_id] = user
|
||||
self._users_by_username[username] = user
|
||||
return user
|
||||
|
||||
async def get_user_by_id(self, user_id: str) -> UserResponse:
|
||||
async with self._lock:
|
||||
user = self._users_by_id.get(user_id)
|
||||
if not user:
|
||||
raise UnauthorizedError("Пользователь не найден или не авторизован")
|
||||
return user
|
||||
if not row:
|
||||
return None
|
||||
|
||||
if not verify_password(row["password_hash"], password):
|
||||
return None
|
||||
|
||||
return UserResponse(
|
||||
id=str(row["id"]),
|
||||
username=row["username"],
|
||||
display_name=row["display_name"],
|
||||
created_at=_format_dt(row["created_at"]),
|
||||
)
|
||||
|
||||
async def get_user_by_id(self, user_id: str) -> UserResponse | None:
|
||||
try:
|
||||
uid = uuid.UUID(user_id)
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
assert self.pg_pool is not None
|
||||
async with self.pg_pool.acquire() as conn:
|
||||
row = await conn.fetchrow(
|
||||
"""
|
||||
SELECT id, username, display_name, created_at
|
||||
FROM users
|
||||
WHERE id = $1
|
||||
""",
|
||||
uid,
|
||||
)
|
||||
|
||||
if not row:
|
||||
return None
|
||||
|
||||
return UserResponse(
|
||||
id=str(row["id"]),
|
||||
username=row["username"],
|
||||
display_name=row["display_name"],
|
||||
created_at=_format_dt(row["created_at"]),
|
||||
)
|
||||
|
||||
# ------------------ Сессии (Redis) ------------------
|
||||
|
||||
async def create_session(self, user: UserResponse) -> SessionResponse:
|
||||
assert self.redis_client is not None
|
||||
token = generate_session_token()
|
||||
now = dt.datetime.now(dt.timezone.utc)
|
||||
expires_at = now + dt.timedelta(seconds=SESSION_TTL_SECONDS)
|
||||
expires_at_str = _format_dt(expires_at)
|
||||
|
||||
session_data = json.dumps(
|
||||
{
|
||||
"user_id": user.id,
|
||||
"expires_at": expires_at_str,
|
||||
}
|
||||
)
|
||||
|
||||
key = f"session:{token}"
|
||||
await self.redis_client.set(key, session_data, ex=SESSION_TTL_SECONDS)
|
||||
|
||||
return SessionResponse(
|
||||
token=token,
|
||||
token_type="Bearer",
|
||||
expires_at=expires_at_str,
|
||||
user=user,
|
||||
)
|
||||
|
||||
async def get_session_user(self, token: str) -> UserResponse | None:
|
||||
if not token or not self.redis_client:
|
||||
return None
|
||||
|
||||
key = f"session:{token}"
|
||||
raw = await self.redis_client.get(key)
|
||||
if not raw:
|
||||
return None
|
||||
|
||||
try:
|
||||
data = json.loads(raw)
|
||||
user_id = data.get("user_id")
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
if not user_id:
|
||||
return None
|
||||
|
||||
return await self.get_user_by_id(user_id)
|
||||
|
||||
async def delete_session(self, token: str) -> bool:
|
||||
if not token or not self.redis_client:
|
||||
return False
|
||||
key = f"session:{token}"
|
||||
res = await self.redis_client.delete(key)
|
||||
return res > 0
|
||||
|
||||
# ------------------ Чаты ------------------
|
||||
|
||||
async def create_chat(
|
||||
self, caller_id: str, title: str, member_ids: list[str]
|
||||
) -> ChatResponse:
|
||||
async with self._lock:
|
||||
# Вызывающий обязан быть в списке участников
|
||||
if caller_id not in member_ids:
|
||||
raise InvalidRequestError("Создатель чата должен быть в списке участников member_ids")
|
||||
if caller_id not in member_ids:
|
||||
raise InvalidRequestError("Создатель чата должен быть в списке участников")
|
||||
|
||||
# Все участники обязаны существовать
|
||||
for mid in member_ids:
|
||||
if mid not in self._users_by_id:
|
||||
raise InvalidRequestError(f"Пользователь {mid} не существует")
|
||||
chat_id = uuid.uuid4()
|
||||
now = dt.datetime.now(dt.timezone.utc)
|
||||
title = title.replace("\x00", "")
|
||||
|
||||
chat_id = str(uuid.uuid4())
|
||||
created_at = now_utc_iso()
|
||||
chat = ChatResponse(
|
||||
id=chat_id,
|
||||
title=title,
|
||||
member_ids=list(member_ids),
|
||||
created_at=created_at,
|
||||
member_uuids = [uuid.UUID(m) for m in member_ids]
|
||||
|
||||
assert self.pg_pool is not None
|
||||
async with self.pg_pool.acquire() as conn:
|
||||
# Проверяем существование всех участников
|
||||
found = await conn.fetch(
|
||||
"SELECT id FROM users WHERE id = ANY($1::uuid[])", member_uuids
|
||||
)
|
||||
self._chats_by_id[chat_id] = chat
|
||||
self._messages_by_chat[chat_id] = []
|
||||
return chat
|
||||
if len(found) != len(member_uuids):
|
||||
raise InvalidRequestError(
|
||||
"Один или несколько участников чата не найдены"
|
||||
)
|
||||
|
||||
async with conn.transaction():
|
||||
await conn.execute(
|
||||
"INSERT INTO chats (id, title, created_at) VALUES ($1, $2, $3)",
|
||||
chat_id,
|
||||
title,
|
||||
now,
|
||||
)
|
||||
member_records = [(chat_id, m) for m in member_uuids]
|
||||
await conn.executemany(
|
||||
"INSERT INTO chat_members (chat_id, user_id) VALUES ($1, $2)",
|
||||
member_records,
|
||||
)
|
||||
|
||||
return ChatResponse(
|
||||
id=str(chat_id),
|
||||
title=title,
|
||||
member_ids=member_ids,
|
||||
created_at=_format_dt(now),
|
||||
)
|
||||
|
||||
async def get_chat(self, caller_id: str, chat_id: str) -> ChatResponse:
|
||||
async with self._lock:
|
||||
chat = self._chats_by_id.get(chat_id)
|
||||
# Если чата нет или вызывающий не участник — строго 404
|
||||
if not chat or caller_id not in chat.member_ids:
|
||||
try:
|
||||
cid = uuid.UUID(chat_id)
|
||||
c_caller = uuid.UUID(caller_id)
|
||||
except ValueError:
|
||||
raise NotFoundError("Чат не найден")
|
||||
|
||||
assert self.pg_pool is not None
|
||||
async with self.pg_pool.acquire() as conn:
|
||||
# Проверяем членство вызывающего
|
||||
is_member = await conn.fetchval(
|
||||
"SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2",
|
||||
cid,
|
||||
c_caller,
|
||||
)
|
||||
if not is_member:
|
||||
raise NotFoundError("Чат не найден")
|
||||
return chat
|
||||
|
||||
chat_row = await conn.fetchrow(
|
||||
"SELECT id, title, created_at FROM chats WHERE id = $1", cid
|
||||
)
|
||||
if not chat_row:
|
||||
raise NotFoundError("Чат не найден")
|
||||
|
||||
members_rows = await conn.fetch(
|
||||
"SELECT user_id FROM chat_members WHERE chat_id = $1", cid
|
||||
)
|
||||
member_ids = [str(r["user_id"]) for r in members_rows]
|
||||
|
||||
return ChatResponse(
|
||||
id=str(chat_row["id"]),
|
||||
title=chat_row["title"],
|
||||
member_ids=member_ids,
|
||||
created_at=_format_dt(chat_row["created_at"]),
|
||||
)
|
||||
|
||||
async def list_chats(
|
||||
self, caller_id: str, limit: int = 50, cursor: str | None = None
|
||||
) -> tuple[list[ChatResponse], str | None]:
|
||||
async with self._lock:
|
||||
# Фильтруем только чаты, где пользователь — участник
|
||||
user_chats = [
|
||||
chat
|
||||
for chat in self._chats_by_id.values()
|
||||
if caller_id in chat.member_ids
|
||||
]
|
||||
# Сортировка по (created_at, id) по возрастанию
|
||||
user_chats.sort(key=lambda x: (x.created_at, x.id))
|
||||
try:
|
||||
c_caller = uuid.UUID(caller_id)
|
||||
except ValueError:
|
||||
return [], None
|
||||
|
||||
start_idx = 0
|
||||
if cursor is not None:
|
||||
c_data = decode_cursor(cursor)
|
||||
if c_data.get("type") != "chats":
|
||||
raise InvalidRequestError("Курсор недействителен для списка чатов")
|
||||
c_created = c_data.get("created_at")
|
||||
c_id = c_data.get("id")
|
||||
if (
|
||||
not isinstance(c_created, str)
|
||||
or not isinstance(c_id, str)
|
||||
or not c_created.strip()
|
||||
or not c_id.strip()
|
||||
):
|
||||
raise InvalidRequestError("Поврежденный курсор")
|
||||
c_created: dt.datetime | None = None
|
||||
c_id: uuid.UUID | None = None
|
||||
|
||||
# Ищем первый элемент, строго больший курсора
|
||||
start_idx = len(user_chats)
|
||||
for idx, chat in enumerate(user_chats):
|
||||
if (chat.created_at, chat.id) > (c_created, c_id):
|
||||
start_idx = idx
|
||||
break
|
||||
|
||||
items = user_chats[start_idx : start_idx + limit]
|
||||
has_next = (start_idx + limit) < len(user_chats)
|
||||
next_cursor = None
|
||||
if has_next and items:
|
||||
last = items[-1]
|
||||
next_cursor = encode_cursor(
|
||||
{"type": "chats", "created_at": last.created_at, "id": last.id}
|
||||
if cursor is not None:
|
||||
c_data = decode_cursor(cursor)
|
||||
if c_data.get("type") != "chats":
|
||||
raise InvalidRequestError("Недействительный тип курсора")
|
||||
c_created_str = c_data.get("created_at")
|
||||
c_id_str = c_data.get("id")
|
||||
if (
|
||||
not isinstance(c_created_str, str)
|
||||
or not isinstance(c_id_str, str)
|
||||
or not c_created_str.strip()
|
||||
or not c_id_str.strip()
|
||||
):
|
||||
raise InvalidRequestError("Поврежденный курсор")
|
||||
try:
|
||||
c_created = dt.datetime.fromisoformat(
|
||||
c_created_str.replace("Z", "+00:00")
|
||||
)
|
||||
c_id = uuid.UUID(c_id_str)
|
||||
except Exception:
|
||||
raise InvalidRequestError("Некорректные параметры курсора")
|
||||
|
||||
return items, next_cursor
|
||||
assert self.pg_pool is not None
|
||||
async with self.pg_pool.acquire() as conn:
|
||||
query = """
|
||||
SELECT c.id, c.title, c.created_at, array_agg(cm.user_id::text) as member_ids
|
||||
FROM chats c
|
||||
JOIN chat_members my_m ON c.id = my_m.chat_id AND my_m.user_id = $1
|
||||
JOIN chat_members cm ON c.id = cm.chat_id
|
||||
WHERE ($2::timestamptz IS NULL OR (c.created_at, c.id) > ($2::timestamptz, $3::uuid))
|
||||
GROUP BY c.id, c.title, c.created_at
|
||||
ORDER BY c.created_at ASC, c.id ASC
|
||||
LIMIT $4
|
||||
"""
|
||||
rows = await conn.fetch(query, c_caller, c_created, c_id, limit + 1)
|
||||
|
||||
async def create_message(
|
||||
has_next = len(rows) > limit
|
||||
items_rows = rows[:limit]
|
||||
|
||||
items = [
|
||||
ChatResponse(
|
||||
id=str(r["id"]),
|
||||
title=r["title"],
|
||||
member_ids=list(r["member_ids"]),
|
||||
created_at=_format_dt(r["created_at"]),
|
||||
)
|
||||
for r in items_rows
|
||||
]
|
||||
|
||||
next_cursor = None
|
||||
if has_next and items:
|
||||
last = items[-1]
|
||||
next_cursor = encode_cursor(
|
||||
{
|
||||
"type": "chats",
|
||||
"created_at": last.created_at,
|
||||
"id": last.id,
|
||||
}
|
||||
)
|
||||
|
||||
return items, next_cursor
|
||||
|
||||
# ------------------ Сообщения ------------------
|
||||
|
||||
async def send_message(
|
||||
self, caller_id: str, chat_id: str, text: str
|
||||
) -> MessageResponse:
|
||||
async with self._lock:
|
||||
chat = self._chats_by_id.get(chat_id)
|
||||
if not chat or caller_id not in chat.member_ids:
|
||||
try:
|
||||
cid = uuid.UUID(chat_id)
|
||||
c_caller = uuid.UUID(caller_id)
|
||||
except ValueError:
|
||||
raise NotFoundError("Чат не найден")
|
||||
|
||||
msg_id = uuid.uuid4()
|
||||
now = dt.datetime.now(dt.timezone.utc)
|
||||
text = text.replace("\x00", "")
|
||||
|
||||
assert self.pg_pool is not None
|
||||
async with self.pg_pool.acquire() as conn:
|
||||
is_member = await conn.fetchval(
|
||||
"SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2",
|
||||
cid,
|
||||
c_caller,
|
||||
)
|
||||
if not is_member:
|
||||
raise NotFoundError("Чат не найден")
|
||||
|
||||
message_id = str(uuid.uuid4())
|
||||
created_at = now_utc_iso()
|
||||
msg = MessageResponse(
|
||||
id=message_id,
|
||||
chat_id=chat_id,
|
||||
sender_id=caller_id,
|
||||
text=text,
|
||||
created_at=created_at,
|
||||
await conn.execute(
|
||||
"""
|
||||
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
""",
|
||||
msg_id,
|
||||
cid,
|
||||
c_caller,
|
||||
text,
|
||||
now,
|
||||
)
|
||||
self._messages_by_chat[chat_id].append(msg)
|
||||
return msg
|
||||
|
||||
return MessageResponse(
|
||||
id=str(msg_id),
|
||||
chat_id=chat_id,
|
||||
sender_id=caller_id,
|
||||
text=text,
|
||||
created_at=_format_dt(now),
|
||||
)
|
||||
|
||||
async def list_messages(
|
||||
self, caller_id: str, chat_id: str, limit: int = 50, cursor: str | None = None
|
||||
) -> tuple[list[MessageResponse], str | None]:
|
||||
async with self._lock:
|
||||
chat = self._chats_by_id.get(chat_id)
|
||||
if not chat or caller_id not in chat.member_ids:
|
||||
try:
|
||||
cid = uuid.UUID(chat_id)
|
||||
c_caller = uuid.UUID(caller_id)
|
||||
except ValueError:
|
||||
raise NotFoundError("Чат не найден")
|
||||
|
||||
assert self.pg_pool is not None
|
||||
async with self.pg_pool.acquire() as conn:
|
||||
is_member = await conn.fetchval(
|
||||
"SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2",
|
||||
cid,
|
||||
c_caller,
|
||||
)
|
||||
if not is_member:
|
||||
raise NotFoundError("Чат не найден")
|
||||
|
||||
all_msgs = self._messages_by_chat.get(chat_id, [])
|
||||
# Сортировка по (created_at, id) по возрастанию
|
||||
sorted_msgs = sorted(all_msgs, key=lambda x: (x.created_at, x.id))
|
||||
c_created: dt.datetime | None = None
|
||||
c_id: uuid.UUID | None = None
|
||||
|
||||
start_idx = 0
|
||||
if cursor is not None:
|
||||
c_data = decode_cursor(cursor)
|
||||
if c_data.get("type") != "messages" or c_data.get("chat_id") != chat_id:
|
||||
raise InvalidRequestError(
|
||||
"Курсор принадлежит другому чату или недействителен"
|
||||
)
|
||||
c_created = c_data.get("created_at")
|
||||
c_id = c_data.get("id")
|
||||
c_created_str = c_data.get("created_at")
|
||||
c_id_str = c_data.get("id")
|
||||
if (
|
||||
not isinstance(c_created, str)
|
||||
or not isinstance(c_id, str)
|
||||
or not c_created.strip()
|
||||
or not c_id.strip()
|
||||
not isinstance(c_created_str, str)
|
||||
or not isinstance(c_id_str, str)
|
||||
or not c_created_str.strip()
|
||||
or not c_id_str.strip()
|
||||
):
|
||||
raise InvalidRequestError("Поврежденный курсор")
|
||||
try:
|
||||
c_created = dt.datetime.fromisoformat(
|
||||
c_created_str.replace("Z", "+00:00")
|
||||
)
|
||||
c_id = uuid.UUID(c_id_str)
|
||||
except Exception:
|
||||
raise InvalidRequestError("Некорректные параметры курсора")
|
||||
|
||||
start_idx = len(sorted_msgs)
|
||||
for idx, msg in enumerate(sorted_msgs):
|
||||
if (msg.created_at, msg.id) > (c_created, c_id):
|
||||
start_idx = idx
|
||||
break
|
||||
query = """
|
||||
SELECT id, chat_id, sender_id, text, created_at
|
||||
FROM messages
|
||||
WHERE chat_id = $1
|
||||
AND ($2::timestamptz IS NULL OR (created_at, id) > ($2::timestamptz, $3::uuid))
|
||||
ORDER BY created_at ASC, id ASC
|
||||
LIMIT $4
|
||||
"""
|
||||
rows = await conn.fetch(query, cid, c_created, c_id, limit + 1)
|
||||
|
||||
items = sorted_msgs[start_idx : start_idx + limit]
|
||||
has_next = (start_idx + limit) < len(sorted_msgs)
|
||||
next_cursor = None
|
||||
if has_next and items:
|
||||
last = items[-1]
|
||||
next_cursor = encode_cursor(
|
||||
{
|
||||
"type": "messages",
|
||||
"chat_id": chat_id,
|
||||
"created_at": last.created_at,
|
||||
"id": last.id,
|
||||
}
|
||||
)
|
||||
has_next = len(rows) > limit
|
||||
items_rows = rows[:limit]
|
||||
|
||||
return items, next_cursor
|
||||
items = [
|
||||
MessageResponse(
|
||||
id=str(r["id"]),
|
||||
chat_id=str(r["chat_id"]),
|
||||
sender_id=str(r["sender_id"]),
|
||||
text=r["text"],
|
||||
created_at=_format_dt(r["created_at"]),
|
||||
)
|
||||
for r in items_rows
|
||||
]
|
||||
|
||||
next_cursor = None
|
||||
if has_next and items:
|
||||
last = items[-1]
|
||||
next_cursor = encode_cursor(
|
||||
{
|
||||
"type": "messages",
|
||||
"chat_id": chat_id,
|
||||
"created_at": last.created_at,
|
||||
"id": last.id,
|
||||
}
|
||||
)
|
||||
|
||||
return items, next_cursor
|
||||
|
||||
|
||||
# Глобальный экземпляр хранилища для процесса
|
||||
storage = InMemoryStorage()
|
||||
# Глобальный экземпляр хранилища
|
||||
storage = PostgresStorage()
|
||||
|
||||
Reference in New Issue
Block a user