+ скопировала все файлы проекта из л.р. 1
This commit is contained in:
@@ -0,0 +1,91 @@
|
||||
import base64
|
||||
import json
|
||||
from uuid import UUID
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, Security
|
||||
from ..models.schemas import Chat, ChatPage, CreateChat
|
||||
from ..storage.memory import storage
|
||||
from .security import dev_user
|
||||
|
||||
|
||||
router = APIRouter(prefix="/api/v1/chats", tags=["chats"])
|
||||
|
||||
|
||||
def _current_user_id(x_user_id: str | None = Security(dev_user)) -> UUID:
|
||||
if not x_user_id:
|
||||
raise HTTPException(status_code=401, detail="unauthorized")
|
||||
try:
|
||||
return UUID(x_user_id)
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=401, detail="unauthorized")
|
||||
|
||||
|
||||
def _encode_cursor(user_id: UUID, chat: Chat) -> str:
|
||||
"""Простой курсор: user_id + id + created_at, base64."""
|
||||
data = {"user_id": str(user_id), "id": str(chat.id), "created_at": chat.created_at.isoformat()}
|
||||
return base64.urlsafe_b64encode(json.dumps(data).encode()).decode()
|
||||
|
||||
|
||||
def _decode_cursor(user_id: UUID, cursor: str) -> tuple:
|
||||
try:
|
||||
data = json.loads(base64.urlsafe_b64decode(cursor.encode()).decode())
|
||||
if data.get("user_id") != str(user_id):
|
||||
raise ValueError("cursor_user_mismatch")
|
||||
return UUID(data["id"]), data["created_at"]
|
||||
except Exception:
|
||||
raise HTTPException(status_code=400, detail="invalid_request")
|
||||
|
||||
|
||||
@router.post(
|
||||
path="",
|
||||
summary="Создать чат",
|
||||
response_model=Chat,
|
||||
status_code=201,
|
||||
)
|
||||
def create_chat(
|
||||
payload: CreateChat,
|
||||
user_id: UUID = Depends(_current_user_id),
|
||||
) -> Chat:
|
||||
"""Вызывающий должен входить в member_ids"""
|
||||
|
||||
if user_id not in payload.member_ids:
|
||||
raise HTTPException(status_code=400, detail="invalid_request")
|
||||
if len(set(payload.member_ids)) != len(payload.member_ids):
|
||||
raise HTTPException(status_code=400, detail="invalid_request")
|
||||
try:
|
||||
return storage.create_chat(payload.title, list(payload.member_ids))
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=400, detail="invalid_request")
|
||||
|
||||
|
||||
@router.get(
|
||||
path="",
|
||||
summary="Получить список чатов текущего пользователя",
|
||||
response_model=ChatPage,
|
||||
)
|
||||
def list_chats(
|
||||
user_id: UUID = Depends(_current_user_id),
|
||||
limit: int = Query(50, ge=1, le=100),
|
||||
cursor: str | None = None,
|
||||
) -> ChatPage:
|
||||
chats = storage.list_chats_for_user(user_id)
|
||||
if cursor:
|
||||
cid, ccreated = _decode_cursor(user_id, cursor)
|
||||
chats = [c for c in chats if (c.created_at.isoformat(), str(c.id)) > (ccreated, str(cid))]
|
||||
page = chats[:limit]
|
||||
next_cursor = _encode_cursor(user_id, page[-1]) if len(chats) > limit else None
|
||||
return ChatPage(items=page, next_cursor=next_cursor)
|
||||
|
||||
|
||||
@router.get(
|
||||
path="/{chat_id}",
|
||||
summary="Получить доступный чат по идентификатору",
|
||||
response_model=Chat,
|
||||
)
|
||||
def get_chat(
|
||||
chat_id: UUID,
|
||||
user_id: UUID = Depends(_current_user_id),
|
||||
) -> Chat:
|
||||
chat = storage.get_chat(chat_id)
|
||||
if chat is None or user_id not in chat.member_ids:
|
||||
raise HTTPException(status_code=404, detail="not_found")
|
||||
return chat
|
||||
@@ -0,0 +1,25 @@
|
||||
from fastapi import APIRouter
|
||||
from ..models.schemas import Health
|
||||
|
||||
|
||||
router = APIRouter(tags=["health"])
|
||||
|
||||
|
||||
@router.get(
|
||||
path="/health/live",
|
||||
summary="Проверка жизнеспособности процесса",
|
||||
response_model=Health,
|
||||
)
|
||||
def liveness() -> Health:
|
||||
"""Процесс жив"""
|
||||
return Health(status="ok")
|
||||
|
||||
|
||||
@router.get(
|
||||
path="/health/ready",
|
||||
summary="Проверка готовности принимать трафик",
|
||||
response_model=Health,
|
||||
)
|
||||
def readiness() -> Health:
|
||||
"""Готов принимать трафик. В lab1 критичных зависимостей нет."""
|
||||
return Health(status="ok")
|
||||
@@ -0,0 +1,81 @@
|
||||
import base64
|
||||
import json
|
||||
from uuid import UUID
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, Security
|
||||
from ..models.schemas import CreateMessage, Message, MessagePage
|
||||
from ..storage.memory import storage
|
||||
from .security import dev_user
|
||||
|
||||
|
||||
router = APIRouter(prefix="/api/v1/chats", tags=["messages"])
|
||||
|
||||
|
||||
def _current_user_id(x_user_id: str | None = Security(dev_user)) -> UUID:
|
||||
if not x_user_id:
|
||||
raise HTTPException(status_code=401, detail="unauthorized")
|
||||
try:
|
||||
return UUID(x_user_id)
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=401, detail="unauthorized")
|
||||
|
||||
|
||||
def _require_member(chat_id: UUID, user_id: UUID):
|
||||
chat = storage.get_chat(chat_id)
|
||||
if chat is None or user_id not in chat.member_ids:
|
||||
raise HTTPException(status_code=404, detail="not_found")
|
||||
return chat
|
||||
|
||||
|
||||
def _encode_cursor(chat_id: UUID, message: Message) -> str:
|
||||
data = {"chat_id": str(chat_id), "id": str(message.id), "created_at": message.created_at.isoformat()}
|
||||
return base64.urlsafe_b64encode(json.dumps(data).encode()).decode()
|
||||
|
||||
|
||||
def _decode_cursor(chat_id: UUID, cursor: str) -> tuple:
|
||||
try:
|
||||
data = json.loads(base64.urlsafe_b64decode(cursor.encode()).decode())
|
||||
if data.get("chat_id") != str(chat_id):
|
||||
raise ValueError("cursor_chat_mismatch")
|
||||
return UUID(data["id"]), data["created_at"]
|
||||
except Exception:
|
||||
raise HTTPException(status_code=400, detail="invalid_request")
|
||||
|
||||
|
||||
@router.post(
|
||||
path="/{chat_id}/messages",
|
||||
summary="Отправить сообщение в чат",
|
||||
response_model=Message,
|
||||
status_code=201,
|
||||
)
|
||||
def create_message(
|
||||
chat_id: UUID,
|
||||
payload: CreateMessage,
|
||||
user_id: UUID = Depends(_current_user_id),
|
||||
) -> Message:
|
||||
_require_member(chat_id, user_id)
|
||||
if not payload.text.strip():
|
||||
raise HTTPException(status_code=400, detail="invalid_request")
|
||||
return storage.add_message(chat_id, user_id, payload.text)
|
||||
|
||||
|
||||
@router.get(
|
||||
path="/{chat_id}/messages",
|
||||
summary="Получить историю сообщений чата",
|
||||
response_model=MessagePage,
|
||||
)
|
||||
def list_messages(
|
||||
chat_id: UUID,
|
||||
user_id: UUID = Depends(_current_user_id),
|
||||
limit: int = Query(50, ge=1, le=100),
|
||||
cursor: str | None = None,
|
||||
) -> MessagePage:
|
||||
"""Реализована курсорная пагинация"""
|
||||
|
||||
_require_member(chat_id, user_id)
|
||||
messages = storage.list_messages(chat_id)
|
||||
if cursor:
|
||||
mid, mcreated = _decode_cursor(chat_id, cursor)
|
||||
messages = [m for m in messages if (m.created_at.isoformat(), str(m.id)) > (mcreated, str(mid))]
|
||||
page = messages[:limit]
|
||||
next_cursor = _encode_cursor(chat_id, page[-1]) if len(messages) > limit else None
|
||||
return MessagePage(items=page, next_cursor=next_cursor)
|
||||
@@ -0,0 +1,3 @@
|
||||
from fastapi.security import APIKeyHeader
|
||||
|
||||
dev_user = APIKeyHeader(name="X-User-Id", auto_error=False, scheme_name="devUser")
|
||||
@@ -0,0 +1,45 @@
|
||||
from uuid import UUID
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from ..models.schemas import CreateUser, User
|
||||
from ..storage.memory import storage
|
||||
from .security import dev_user
|
||||
from fastapi import Security
|
||||
|
||||
router = APIRouter(prefix="/api/v1", tags=["users"])
|
||||
|
||||
|
||||
def _current_user_id(x_user_id: str | None = Security(dev_user)) -> UUID:
|
||||
"""Достаёт X-User-Id из заголовков и валидирует."""
|
||||
if not x_user_id:
|
||||
raise HTTPException(status_code=401, detail="unauthorized")
|
||||
try:
|
||||
return UUID(x_user_id)
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=401, detail="unauthorized")
|
||||
|
||||
|
||||
@router.post(
|
||||
path="/users",
|
||||
summary="Создать пользователя",
|
||||
response_model=User,
|
||||
status_code=201,
|
||||
)
|
||||
def register_user(payload: CreateUser) -> User:
|
||||
"""Публичная регистрация."""
|
||||
try:
|
||||
return storage.create_user(payload.username, payload.display_name)
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=409, detail="conflict")
|
||||
|
||||
|
||||
@router.get(
|
||||
path="/users/me",
|
||||
summary="Получить текущего пользователя",
|
||||
response_model=User,
|
||||
)
|
||||
def current_user(user_id: UUID = Depends(_current_user_id)) -> User:
|
||||
"""Текущий пользователь по X-User-Id."""
|
||||
user = storage.get_user(user_id)
|
||||
if user is None:
|
||||
raise HTTPException(status_code=401, detail="unauthorized")
|
||||
return user
|
||||
+148
@@ -0,0 +1,148 @@
|
||||
import logging
|
||||
import os
|
||||
import signal
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
from contextlib import asynccontextmanager
|
||||
from fastapi import FastAPI, Request
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.openapi.utils import get_openapi
|
||||
from fastapi.responses import JSONResponse
|
||||
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||
import uvicorn
|
||||
from .api import chats, health, messages, users
|
||||
|
||||
|
||||
# --- Логирование: структурированный stdout, без содержимого сообщений ---
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(asctime)s %(levelname)s %(name)s %(message)s",
|
||||
stream=sys.stdout,
|
||||
)
|
||||
logger = logging.getLogger("app")
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
logger.info("event=startup app_env=%s", os.environ.get("APP_ENV", "lab"))
|
||||
yield
|
||||
logger.info("event=shutdown_complete")
|
||||
|
||||
|
||||
app = FastAPI(
|
||||
title="MTUCI Messenger — lab1",
|
||||
version="1.2.2",
|
||||
lifespan=lifespan,
|
||||
swagger_ui_parameters={"persistAuthorization": True},
|
||||
)
|
||||
|
||||
|
||||
def custom_openapi():
|
||||
if app.openapi_schema:
|
||||
return app.openapi_schema
|
||||
schema = get_openapi(title=app.title, version=app.version, routes=app.routes)
|
||||
schema.setdefault("components", {}).setdefault("securitySchemes", {})["devUser"] = {
|
||||
"type": "apiKey",
|
||||
"in": "header",
|
||||
"name": "X-User-Id",
|
||||
"description": "Только учебная lab1: существующий UUID. Не является аутентификацией.",
|
||||
}
|
||||
app.openapi_schema = schema
|
||||
return schema
|
||||
|
||||
|
||||
app.openapi = custom_openapi
|
||||
|
||||
|
||||
@app.middleware("http")
|
||||
async def observability_middleware(request: Request, call_next):
|
||||
"""X-Request-Id во всех ответах + структурный лог без тела сообщений."""
|
||||
request_id = request.headers.get("X-Request-Id") or uuid.uuid4().hex
|
||||
request.state.request_id = request_id
|
||||
started = time.monotonic()
|
||||
response = await call_next(request)
|
||||
response.headers["X-Request-Id"] = request_id
|
||||
duration_ms = round((time.monotonic() - started) * 1000, 2)
|
||||
# Логируем только метаданные: метод, путь без query, статус, длительность, request_id
|
||||
path = request.url.path
|
||||
logger.info(
|
||||
"event=http method=%s path=%s status=%s duration_ms=%s request_id=%s",
|
||||
request.method,
|
||||
path,
|
||||
response.status_code,
|
||||
duration_ms,
|
||||
request_id,
|
||||
)
|
||||
return response
|
||||
|
||||
|
||||
# Словарь HTTP-кодов → кодов ошибок из контракта
|
||||
_ERROR_CODES = {
|
||||
400: "invalid_request",
|
||||
401: "unauthorized",
|
||||
404: "not_found",
|
||||
409: "conflict",
|
||||
413: "payload_too_large",
|
||||
415: "unsupported_media_type",
|
||||
429: "rate_limited",
|
||||
503: "unavailable",
|
||||
500: "internal_error",
|
||||
}
|
||||
|
||||
|
||||
def _error_response(status_code: int, message: str, request_id: str) -> JSONResponse:
|
||||
code = _ERROR_CODES.get(status_code, "internal_error")
|
||||
return JSONResponse(
|
||||
status_code=status_code,
|
||||
content={"error": {"code": code, "message": message, "request_id": request_id}},
|
||||
)
|
||||
|
||||
|
||||
@app.exception_handler(StarletteHTTPException)
|
||||
async def http_exception_handler(request: Request, exc: StarletteHTTPException):
|
||||
request_id = getattr(request.state, "request_id", uuid.uuid4().hex)
|
||||
message = exc.detail if isinstance(exc.detail, str) else "Ошибка"
|
||||
return _error_response(exc.status_code, message, request_id)
|
||||
|
||||
|
||||
@app.exception_handler(RequestValidationError)
|
||||
async def validation_exception_handler(request: Request, exc: RequestValidationError):
|
||||
request_id = getattr(request.state, "request_id", uuid.uuid4().hex)
|
||||
return _error_response(400, "Неверный запрос", request_id)
|
||||
|
||||
|
||||
@app.exception_handler(Exception)
|
||||
async def unhandled_exception_handler(request: Request, exc: Exception):
|
||||
request_id = getattr(request.state, "request_id", uuid.uuid4().hex)
|
||||
# Внутренние детали не раскрываем; пишем в лог без секретов
|
||||
logger.error("event=unhandled_exception type=%s request_id=%s", type(exc).__name__, request_id)
|
||||
return _error_response(500, "Внутренняя ошибка", request_id)
|
||||
|
||||
|
||||
app.include_router(health.router)
|
||||
app.include_router(users.router)
|
||||
app.include_router(chats.router)
|
||||
app.include_router(messages.router)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
config = uvicorn.Config(
|
||||
"app.main:app",
|
||||
host="0.0.0.0",
|
||||
port=8080,
|
||||
log_level="info",
|
||||
)
|
||||
server = uvicorn.Server(config)
|
||||
|
||||
def _handle_sigterm(signum, frame):
|
||||
"""SIGTERM: логируем и инициируем graceful shutdown uvicorn.
|
||||
|
||||
server.should_exit=True заставляет uvicorn закрыть слушающий сокет
|
||||
(healthcheck перестаёт отвечать) и корректно завершить процесс.
|
||||
"""
|
||||
logger.info("event=sigterm_received signal=%s", signum)
|
||||
server.should_exit = True
|
||||
|
||||
signal.signal(signal.SIGTERM, _handle_sigterm)
|
||||
server.run()
|
||||
@@ -0,0 +1,74 @@
|
||||
from datetime import datetime
|
||||
from typing import List, Optional
|
||||
from uuid import UUID
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
|
||||
class Health(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
status: str
|
||||
|
||||
|
||||
class CreateUser(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
username: str = Field(pattern=r"^[a-z0-9_]{3,32}$")
|
||||
display_name: str = Field(min_length=1, max_length=100)
|
||||
|
||||
|
||||
class User(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
id: UUID
|
||||
username: str
|
||||
display_name: str
|
||||
created_at: datetime
|
||||
|
||||
|
||||
class CreateChat(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
title: str = Field(min_length=1, max_length=100)
|
||||
member_ids: List[UUID] = Field(min_length=1, max_length=100)
|
||||
|
||||
|
||||
class Chat(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
id: UUID
|
||||
title: str
|
||||
member_ids: List[UUID]
|
||||
created_at: datetime
|
||||
|
||||
|
||||
class CreateMessage(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
text: str = Field(min_length=1, max_length=4000)
|
||||
|
||||
|
||||
class Message(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
id: UUID
|
||||
chat_id: UUID
|
||||
sender_id: UUID
|
||||
text: str
|
||||
created_at: datetime
|
||||
|
||||
|
||||
class ChatPage(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
items: List[Chat]
|
||||
next_cursor: Optional[str] = None
|
||||
|
||||
|
||||
class MessagePage(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
items: List[Message]
|
||||
next_cursor: Optional[str] = None
|
||||
|
||||
|
||||
class ErrorBody(BaseModel):
|
||||
code: str
|
||||
message: str
|
||||
request_id: str
|
||||
|
||||
|
||||
class ErrorResponse(BaseModel):
|
||||
error: ErrorBody
|
||||
@@ -0,0 +1,98 @@
|
||||
import threading
|
||||
from datetime import datetime, timezone
|
||||
from typing import Dict, List, Optional
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
from ..models.schemas import Chat, Message, User
|
||||
|
||||
|
||||
def now_utc() -> datetime:
|
||||
"""Время сервера в UTC с суффиксом Z на выходе."""
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
class MemoryStorage:
|
||||
"""Потокобезопасное In-memory хранилище пользователей, чатов и сообщений. Все данные исчезают при перезапуске процесса"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._lock = threading.RLock()
|
||||
self._users: Dict[UUID, User] = {}
|
||||
self._usernames: Dict[str, UUID] = {}
|
||||
self._chats: Dict[UUID, Chat] = {}
|
||||
self._messages: Dict[UUID, List[Message]] = {}
|
||||
|
||||
# ---------- Пользователи ----------
|
||||
def create_user(self, username: str, display_name: str) -> User:
|
||||
with self._lock:
|
||||
if username in self._usernames:
|
||||
raise ValueError("username_taken")
|
||||
user = User(
|
||||
id=uuid4(),
|
||||
username=username,
|
||||
display_name=display_name,
|
||||
created_at=now_utc(),
|
||||
)
|
||||
self._users[user.id] = user
|
||||
self._usernames[username] = user.id
|
||||
return user
|
||||
|
||||
def get_user(self, user_id: UUID) -> Optional[User]:
|
||||
with self._lock:
|
||||
return self._users.get(user_id)
|
||||
|
||||
def get_user_by_username(self, username: str) -> Optional[User]:
|
||||
with self._lock:
|
||||
uid = self._usernames.get(username)
|
||||
return self._users.get(uid) if uid else None
|
||||
|
||||
# ---------- Чаты ----------
|
||||
def create_chat(self, title: str, member_ids: List[UUID]) -> Chat:
|
||||
with self._lock:
|
||||
for uid in member_ids:
|
||||
if uid not in self._users:
|
||||
raise ValueError("unknown_member")
|
||||
chat = Chat(
|
||||
id=uuid4(),
|
||||
title=title,
|
||||
member_ids=list(member_ids),
|
||||
created_at=now_utc(),
|
||||
)
|
||||
self._chats[chat.id] = chat
|
||||
self._messages[chat.id] = []
|
||||
return chat
|
||||
|
||||
def get_chat(self, chat_id: UUID) -> Optional[Chat]:
|
||||
with self._lock:
|
||||
return self._chats.get(chat_id)
|
||||
|
||||
def list_chats_for_user(self, user_id: UUID) -> List[Chat]:
|
||||
with self._lock:
|
||||
chats = [c for c in self._chats.values() if user_id in c.member_ids]
|
||||
chats.sort(key=lambda c: (c.created_at, str(c.id)))
|
||||
return chats
|
||||
|
||||
# ---------- Сообщения ----------
|
||||
def add_message(self, chat_id: UUID, sender_id: UUID, text: str) -> Message:
|
||||
"""Улучшение Трека 1: список сообщений хранится уже отсортированным.
|
||||
created_at монотонен в пределах одного процесса, поэтому append
|
||||
сохраняет порядок (created_at, id) по возрастанию — сортировка на
|
||||
чтении не нужна. При конкурентных вставках под RLock порядок
|
||||
сохраняется, но монотонность часов не гарантируется контрактом."""
|
||||
with self._lock:
|
||||
message = Message(
|
||||
id=uuid4(),
|
||||
chat_id=chat_id,
|
||||
sender_id=sender_id,
|
||||
text=text,
|
||||
created_at=now_utc(),
|
||||
)
|
||||
self._messages.setdefault(chat_id, []).append(message)
|
||||
return message
|
||||
|
||||
def list_messages(self, chat_id: UUID) -> List[Message]:
|
||||
with self._lock:
|
||||
# Без пересортировки: список уже в порядке (created_at, id).
|
||||
return list(self._messages.get(chat_id, []))
|
||||
|
||||
|
||||
storage = MemoryStorage() # единственный экземпляр хранилища на процесс
|
||||
Reference in New Issue
Block a user