forked from mtusi2026/mtusi2026lab2
Подгрузка lab1 для начала работы
This commit is contained in:
+20
@@ -0,0 +1,20 @@
|
||||
FROM python:3.11-slim
|
||||
|
||||
# Рабочая директория внутри контейнера
|
||||
WORKDIR /app
|
||||
|
||||
# Сначала копируем зависимости, чтобы Docker кэшировал этот слой
|
||||
COPY requirements.txt .
|
||||
RUN pip install --no-cache-dir -r requirements.txt
|
||||
|
||||
# Копируем исходный код приложения
|
||||
COPY src/ ./src/
|
||||
|
||||
# Переменные окружения по умолчанию
|
||||
ENV HOST=0.0.0.0
|
||||
ENV PORT=8080
|
||||
|
||||
EXPOSE 8080
|
||||
|
||||
# Запуск сервера как главного процесса контейнера
|
||||
CMD ["uvicorn", "src.main:app", "--host", "0.0.0.0", "--port", "8080"]
|
||||
@@ -0,0 +1,28 @@
|
||||
annotated-doc==0.0.5
|
||||
annotated-types==0.8.0
|
||||
anyio==4.16.0
|
||||
certifi==2026.10.23
|
||||
click==8.5.1
|
||||
colorama==0.4.6
|
||||
fastapi==0.162.2
|
||||
h11==0.16.0
|
||||
httpcore==1.0.9
|
||||
httptools==0.9.0
|
||||
httpx==0.28.1
|
||||
idna==3.20
|
||||
iniconfig==2.3.1
|
||||
opentelemetry-api==1.45.2
|
||||
packaging==26.3
|
||||
pluggy==1.7.0
|
||||
pydantic==2.14.3
|
||||
pydantic_core==2.50.4
|
||||
Pygments==2.21.0
|
||||
pytest==9.2.0
|
||||
python-dotenv==1.2.4
|
||||
PyYAML==6.0.3
|
||||
starlette==1.10.0
|
||||
typing-inspection==0.4.5
|
||||
typing_extensions==4.16.0
|
||||
uvicorn==0.54.0
|
||||
watchfiles==1.3.0
|
||||
websockets==17.4
|
||||
+174
@@ -0,0 +1,174 @@
|
||||
from fastapi import FastAPI, Request, HTTPException, Header, Query
|
||||
from fastapi.responses import JSONResponse
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from typing import Optional
|
||||
from uuid import uuid4
|
||||
from .models import (
|
||||
store, CreateUserRequest, CreateChatRequest, CreateMessageRequest,
|
||||
UserResponse, ChatResponse, MessageResponse, ChatPage, MessagePage,
|
||||
HealthResponse
|
||||
)
|
||||
|
||||
app = FastAPI()
|
||||
|
||||
# Middleware для генерации и проброса X-Request-Id
|
||||
@app.middleware("http")
|
||||
async def add_request_id(request: Request, call_next):
|
||||
request_id = str(uuid4())
|
||||
request.state.request_id = request_id
|
||||
response = await call_next(request)
|
||||
response.headers["X-Request-Id"] = request_id
|
||||
return response
|
||||
|
||||
# Обработчик ошибок валидации Pydantic (меняет стандартный 422 на 400 по контракту)
|
||||
@app.exception_handler(RequestValidationError)
|
||||
async def validation_exception_handler(request: Request, exc: RequestValidationError):
|
||||
request_id = getattr(request.state, "request_id", str(uuid4()))
|
||||
content = {
|
||||
"error": {
|
||||
"code": "invalid_request",
|
||||
"message": "Неверный формат запроса, неверные типы данных или лишние поля",
|
||||
"request_id": request_id
|
||||
}
|
||||
}
|
||||
return JSONResponse(status_code=400, content=content)
|
||||
|
||||
# Глобальный обработчик HTTP ошибок
|
||||
@app.exception_handler(HTTPException)
|
||||
async def http_exception_handler(request: Request, exc: HTTPException):
|
||||
request_id = getattr(request.state, "request_id", str(uuid4()))
|
||||
|
||||
if isinstance(exc.detail, dict) and "error" in exc.detail:
|
||||
content = exc.detail
|
||||
content["error"]["request_id"] = request_id
|
||||
else:
|
||||
code_map = {
|
||||
400: "invalid_request", 401: "unauthorized", 404: "not_found",
|
||||
409: "conflict", 413: "payload_too_large", 415: "unsupported_media_type",
|
||||
429: "rate_limited", 500: "internal_error", 503: "unavailable"
|
||||
}
|
||||
code = code_map.get(exc.status_code, "invalid_request")
|
||||
content = {
|
||||
"error": {
|
||||
"code": code,
|
||||
"message": str(exc.detail),
|
||||
"request_id": request_id
|
||||
}
|
||||
}
|
||||
return JSONResponse(status_code=exc.status_code, content=content)
|
||||
|
||||
# --- Health endpoints ---
|
||||
@app.get("/health/live", response_model=HealthResponse)
|
||||
async def health_live():
|
||||
return {"status": "ok"}
|
||||
|
||||
@app.get("/health/ready", response_model=HealthResponse)
|
||||
async def health_ready():
|
||||
return {"status": "ok"}
|
||||
|
||||
# --- Users ---
|
||||
@app.post("/api/v1/users", response_model=UserResponse, status_code=201)
|
||||
async def create_user(request: CreateUserRequest):
|
||||
try:
|
||||
user = await store.create_user(request.username, request.display_name)
|
||||
return user
|
||||
except ValueError as e:
|
||||
if str(e) == "username_already_exists":
|
||||
raise HTTPException(status_code=409, detail="Username already exists")
|
||||
raise HTTPException(status_code=400, detail=str(e))
|
||||
|
||||
@app.get("/api/v1/users/me", response_model=UserResponse)
|
||||
async def get_current_user(x_user_id: str = Header(None, alias="X-User-Id")):
|
||||
if not x_user_id:
|
||||
raise HTTPException(status_code=401, detail="Missing X-User-Id header")
|
||||
user = await store.get_user(x_user_id)
|
||||
if not user:
|
||||
raise HTTPException(status_code=401, detail="User not found")
|
||||
return user
|
||||
|
||||
# --- Chats ---
|
||||
@app.post("/api/v1/chats", response_model=ChatResponse, status_code=201)
|
||||
async def create_chat(request: CreateChatRequest, x_user_id: str = Header(None, alias="X-User-Id")):
|
||||
if not x_user_id:
|
||||
raise HTTPException(status_code=401, detail="Missing X-User-Id header")
|
||||
if not await store.get_user(x_user_id):
|
||||
raise HTTPException(status_code=401, detail="User not found")
|
||||
|
||||
try:
|
||||
chat = await store.create_chat(request.title, request.member_ids, x_user_id)
|
||||
return chat
|
||||
except ValueError as e:
|
||||
if str(e) == "user_not_found":
|
||||
raise HTTPException(status_code=400, detail="One or more members not found")
|
||||
if str(e) == "creator_not_in_members":
|
||||
raise HTTPException(status_code=400, detail="Creator must be in member list")
|
||||
if str(e) == "duplicate_members":
|
||||
raise HTTPException(status_code=400, detail="Duplicate member IDs")
|
||||
raise HTTPException(status_code=400, detail=str(e))
|
||||
|
||||
@app.get("/api/v1/chats", response_model=ChatPage)
|
||||
async def list_chats(
|
||||
x_user_id: str = Header(None, alias="X-User-Id"),
|
||||
limit: int = Query(default=50, ge=1, le=100), # Строгая валидация!
|
||||
cursor: Optional[str] = Query(default=None, min_length=1)
|
||||
):
|
||||
if not x_user_id:
|
||||
raise HTTPException(status_code=401, detail="Missing X-User-Id header")
|
||||
if not await store.get_user(x_user_id):
|
||||
raise HTTPException(status_code=401, detail="User not found")
|
||||
|
||||
chats, next_cursor = await store.list_chats(x_user_id, limit, cursor)
|
||||
return {"items": chats, "next_cursor": next_cursor}
|
||||
|
||||
@app.get("/api/v1/chats/{chat_id}", response_model=ChatResponse)
|
||||
async def get_chat(chat_id: str, x_user_id: str = Header(None, alias="X-User-Id")):
|
||||
if not x_user_id:
|
||||
raise HTTPException(status_code=401, detail="Missing X-User-Id header")
|
||||
chat = await store.get_chat(chat_id, x_user_id)
|
||||
if not chat:
|
||||
raise HTTPException(status_code=404, detail="Chat not found")
|
||||
return chat
|
||||
|
||||
# --- Messages ---
|
||||
@app.post("/api/v1/chats/{chat_id}/messages", response_model=MessageResponse, status_code=201)
|
||||
async def create_message(
|
||||
chat_id: str,
|
||||
request: CreateMessageRequest,
|
||||
x_user_id: str = Header(None, alias="X-User-Id")
|
||||
):
|
||||
if not x_user_id:
|
||||
raise HTTPException(status_code=401, detail="Missing X-User-Id header")
|
||||
if not await store.get_user(x_user_id):
|
||||
raise HTTPException(status_code=401, detail="User not found")
|
||||
|
||||
try:
|
||||
message = await store.create_message(chat_id, x_user_id, request.text)
|
||||
return message
|
||||
except ValueError as e:
|
||||
if str(e) == "chat_not_found":
|
||||
raise HTTPException(status_code=404, detail="Chat not found")
|
||||
if str(e) == "sender_not_in_chat":
|
||||
raise HTTPException(status_code=404, detail="User not in chat") # 404 вместо 403 по контракту
|
||||
raise HTTPException(status_code=400, detail=str(e))
|
||||
|
||||
@app.get("/api/v1/chats/{chat_id}/messages", response_model=MessagePage)
|
||||
async def list_messages(
|
||||
chat_id: str,
|
||||
x_user_id: str = Header(None, alias="X-User-Id"),
|
||||
limit: int = Query(default=50, ge=1, le=100), # Строгая валидация!
|
||||
cursor: Optional[str] = Query(default=None, min_length=1)
|
||||
):
|
||||
if not x_user_id:
|
||||
raise HTTPException(status_code=401, detail="Missing X-User-Id header")
|
||||
if not await store.get_user(x_user_id):
|
||||
raise HTTPException(status_code=401, detail="User not found")
|
||||
|
||||
try:
|
||||
messages, next_cursor = await store.list_messages(chat_id, x_user_id, limit, cursor)
|
||||
return {"items": messages, "next_cursor": next_cursor}
|
||||
except ValueError as e:
|
||||
if str(e) == "chat_not_found":
|
||||
raise HTTPException(status_code=404, detail="Chat not found")
|
||||
if str(e) == "user_not_in_chat":
|
||||
raise HTTPException(status_code=404, detail="User not in chat")
|
||||
raise HTTPException(status_code=400, detail=str(e))
|
||||
+264
@@ -0,0 +1,264 @@
|
||||
from datetime import datetime, timezone
|
||||
from typing import Optional, Dict, List
|
||||
from uuid import uuid4
|
||||
import asyncio
|
||||
from pydantic import BaseModel, Field, field_validator
|
||||
import re
|
||||
|
||||
|
||||
class CreateUserRequest(BaseModel):
|
||||
username: str = Field(..., min_length=3, max_length=32)
|
||||
display_name: str = Field(..., min_length=1, max_length=100)
|
||||
|
||||
@field_validator('username')
|
||||
@classmethod
|
||||
def validate_username(cls, v):
|
||||
if not re.match(r'^[a-z0-9_]{3,32}$', v):
|
||||
raise ValueError('username должен содержать только a-z, 0-9, _ (3-32 символа)')
|
||||
return v
|
||||
|
||||
@field_validator('display_name')
|
||||
@classmethod
|
||||
def validate_display_name(cls, v):
|
||||
if not v.strip():
|
||||
raise ValueError('display_name не может состоять только из пробелов')
|
||||
return v
|
||||
|
||||
class CreateChatRequest(BaseModel):
|
||||
title: str = Field(..., min_length=1, max_length=100)
|
||||
member_ids: List[str] = Field(..., min_length=1, max_length=100)
|
||||
|
||||
@field_validator('title')
|
||||
@classmethod
|
||||
def validate_title(cls, v):
|
||||
if not v.strip():
|
||||
raise ValueError('title не может состоять только из пробелов')
|
||||
return v
|
||||
|
||||
class CreateMessageRequest(BaseModel):
|
||||
text: str = Field(..., min_length=1, max_length=4000)
|
||||
|
||||
@field_validator('text')
|
||||
@classmethod
|
||||
def validate_text(cls, v):
|
||||
if not v.strip():
|
||||
raise ValueError('text не может состоять только из пробелов')
|
||||
return v
|
||||
|
||||
|
||||
class UserResponse(BaseModel):
|
||||
id: str
|
||||
username: str
|
||||
display_name: str
|
||||
created_at: str
|
||||
|
||||
class ChatResponse(BaseModel):
|
||||
id: str
|
||||
title: str
|
||||
member_ids: List[str]
|
||||
created_at: str
|
||||
|
||||
class MessageResponse(BaseModel):
|
||||
id: str
|
||||
chat_id: str
|
||||
sender_id: str
|
||||
text: str
|
||||
created_at: str
|
||||
|
||||
class ChatPage(BaseModel):
|
||||
items: List[ChatResponse]
|
||||
next_cursor: Optional[str] = None
|
||||
|
||||
class MessagePage(BaseModel):
|
||||
items: List[MessageResponse]
|
||||
next_cursor: Optional[str] = None
|
||||
|
||||
class HealthResponse(BaseModel):
|
||||
status: str = "ok"
|
||||
|
||||
class ErrorResponse(BaseModel):
|
||||
error: dict
|
||||
|
||||
|
||||
class InMemoryStore:
|
||||
def __init__(self):
|
||||
self._lock = asyncio.Lock()
|
||||
self.users: Dict[str, dict] = {} # id -> user
|
||||
self.chats: Dict[str, dict] = {} # id -> chat
|
||||
self.messages: Dict[str, List[dict]] = {} # chat_id -> [messages]
|
||||
self.usernames: Dict[str, str] = {} # username -> user_id (для проверки уникальности)
|
||||
|
||||
|
||||
async def create_user(self, username: str, display_name: str) -> dict:
|
||||
async with self._lock:
|
||||
if username in self.usernames:
|
||||
raise ValueError("username_already_exists")
|
||||
|
||||
user_id = str(uuid4())
|
||||
now = datetime.now(timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ')
|
||||
|
||||
user = {
|
||||
"id": user_id,
|
||||
"username": username,
|
||||
"display_name": display_name,
|
||||
"created_at": now
|
||||
}
|
||||
|
||||
self.users[user_id] = user
|
||||
self.usernames[username] = user_id
|
||||
|
||||
return user
|
||||
|
||||
async def get_user(self, user_id: str) -> Optional[dict]:
|
||||
async with self._lock:
|
||||
return self.users.get(user_id)
|
||||
|
||||
async def get_user_by_username(self, username: str) -> Optional[dict]:
|
||||
async with self._lock:
|
||||
user_id = self.usernames.get(username)
|
||||
if user_id:
|
||||
return self.users.get(user_id)
|
||||
return None
|
||||
|
||||
|
||||
async def create_chat(self, title: str, member_ids: List[str], creator_id: str) -> dict:
|
||||
async with self._lock:
|
||||
# Проверяем, что все участники существуют
|
||||
for member_id in member_ids:
|
||||
if member_id not in self.users:
|
||||
raise ValueError("user_not_found")
|
||||
|
||||
# Проверяем, что создатель входит в список участников
|
||||
if creator_id not in member_ids:
|
||||
raise ValueError("creator_not_in_members")
|
||||
|
||||
# Проверяем уникальность member_ids
|
||||
if len(member_ids) != len(set(member_ids)):
|
||||
raise ValueError("duplicate_members")
|
||||
|
||||
chat_id = str(uuid4())
|
||||
now = datetime.now(timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ')
|
||||
|
||||
chat = {
|
||||
"id": chat_id,
|
||||
"title": title,
|
||||
"member_ids": member_ids,
|
||||
"created_at": now
|
||||
}
|
||||
|
||||
self.chats[chat_id] = chat
|
||||
self.messages[chat_id] = []
|
||||
|
||||
return chat
|
||||
|
||||
async def get_chat(self, chat_id: str, user_id: str) -> Optional[dict]:
|
||||
async with self._lock:
|
||||
chat = self.chats.get(chat_id)
|
||||
if not chat:
|
||||
return None
|
||||
|
||||
# Проверяем, что пользователь является участником
|
||||
if user_id not in chat["member_ids"]:
|
||||
return None
|
||||
|
||||
return chat
|
||||
|
||||
async def list_chats(self, user_id: str, limit: int = 50, cursor: Optional[str] = None) -> tuple:
|
||||
async with self._lock:
|
||||
# Получаем все чаты пользователя
|
||||
user_chats = [
|
||||
chat for chat in self.chats.values()
|
||||
if user_id in chat["member_ids"]
|
||||
]
|
||||
|
||||
# Сортируем по (created_at, id)
|
||||
user_chats.sort(key=lambda c: (c["created_at"], c["id"]))
|
||||
|
||||
# Применяем cursor
|
||||
if cursor:
|
||||
# cursor — это "created_at,id" последнего элемента предыдущей страницы
|
||||
cursor_parts = cursor.split(",", 1)
|
||||
if len(cursor_parts) == 2:
|
||||
cursor_time, cursor_id = cursor_parts
|
||||
user_chats = [
|
||||
c for c in user_chats
|
||||
if (c["created_at"], c["id"]) > (cursor_time, cursor_id)
|
||||
]
|
||||
|
||||
# Ограничиваем количество
|
||||
has_more = len(user_chats) > limit
|
||||
page = user_chats[:limit]
|
||||
|
||||
# Формируем next_cursor
|
||||
next_cursor = None
|
||||
if has_more and page:
|
||||
last_item = page[-1]
|
||||
next_cursor = f"{last_item['created_at']},{last_item['id']}"
|
||||
|
||||
return page, next_cursor
|
||||
|
||||
|
||||
async def create_message(self, chat_id: str, sender_id: str, text: str) -> dict:
|
||||
async with self._lock:
|
||||
# Проверяем, что чат существует
|
||||
if chat_id not in self.chats:
|
||||
raise ValueError("chat_not_found")
|
||||
|
||||
# Проверяем, что отправитель является участником чата
|
||||
chat = self.chats[chat_id]
|
||||
if sender_id not in chat["member_ids"]:
|
||||
raise ValueError("sender_not_in_chat")
|
||||
|
||||
message_id = str(uuid4())
|
||||
now = datetime.now(timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ')
|
||||
|
||||
message = {
|
||||
"id": message_id,
|
||||
"chat_id": chat_id,
|
||||
"sender_id": sender_id,
|
||||
"text": text,
|
||||
"created_at": now
|
||||
}
|
||||
|
||||
self.messages[chat_id].append(message)
|
||||
|
||||
return message
|
||||
|
||||
async def list_messages(self, chat_id: str, user_id: str, limit: int = 50, cursor: Optional[str] = None) -> tuple:
|
||||
async with self._lock:
|
||||
# Проверяем, что чат существует и пользователь является участником
|
||||
chat = self.chats.get(chat_id)
|
||||
if not chat:
|
||||
raise ValueError("chat_not_found")
|
||||
|
||||
if user_id not in chat["member_ids"]:
|
||||
raise ValueError("user_not_in_chat")
|
||||
|
||||
messages = self.messages.get(chat_id, [])
|
||||
|
||||
# Сортируем по (created_at, id)
|
||||
messages.sort(key=lambda m: (m["created_at"], m["id"]))
|
||||
|
||||
# Применяем cursor
|
||||
if cursor:
|
||||
cursor_parts = cursor.split(",", 1)
|
||||
if len(cursor_parts) == 2:
|
||||
cursor_time, cursor_id = cursor_parts
|
||||
messages = [
|
||||
m for m in messages
|
||||
if (m["created_at"], m["id"]) > (cursor_time, cursor_id)
|
||||
]
|
||||
|
||||
# Ограничиваем количество
|
||||
has_more = len(messages) > limit
|
||||
page = messages[:limit]
|
||||
|
||||
# Формируем next_cursor
|
||||
next_cursor = None
|
||||
if has_more and page:
|
||||
last_item = page[-1]
|
||||
next_cursor = f"{last_item['created_at']},{last_item['id']}"
|
||||
|
||||
return page, next_cursor
|
||||
|
||||
store = InMemoryStore()
|
||||
Reference in New Issue
Block a user