Lab2: starting
This commit is contained in:
+204
@@ -0,0 +1,204 @@
|
||||
"""
|
||||
Lab1: In-memory API мессенджера.
|
||||
Реализует 7 обязательных эндпоинтов по contracts/openapi.json:
|
||||
GET /health/live
|
||||
GET /health/ready
|
||||
POST /api/v1/users
|
||||
GET /api/v1/users/me
|
||||
POST /api/v1/chats
|
||||
GET /api/v1/chats
|
||||
GET /api/v1/chats/{chat_id}
|
||||
POST /api/v1/chats/{chat_id}/messages
|
||||
GET /api/v1/chats/{chat_id}/messages
|
||||
|
||||
Конфигурация (host/port/log-level) приходит из окружения — см. app/config.py.
|
||||
|
||||
Запуск через Docker (см. Dockerfile):
|
||||
uvicorn app.main:app --host ${APP_HOST} --port ${APP_PORT}
|
||||
|
||||
Запуск напрямую (для локальной отладки без контейнера):
|
||||
python -m app.main
|
||||
"""
|
||||
import uuid
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import Depends, FastAPI, Request
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||
|
||||
from app import config
|
||||
from app.deps import pagination_params, require_user
|
||||
from app.errors import (
|
||||
ApiError,
|
||||
api_error_handler,
|
||||
http_error_handler,
|
||||
unhandled_error_handler,
|
||||
validation_error_handler,
|
||||
)
|
||||
from app.models import (
|
||||
Chat,
|
||||
ChatPage,
|
||||
CreateChat,
|
||||
CreateMessage,
|
||||
CreateUser,
|
||||
Health,
|
||||
Message,
|
||||
MessagePage,
|
||||
User,
|
||||
)
|
||||
from app.storage import storage
|
||||
from pathlib import Path
|
||||
|
||||
app = FastAPI(title="MTUSI Messenger Lab1", version="1.0.0")
|
||||
app.add_exception_handler(ApiError, api_error_handler)
|
||||
app.add_exception_handler(RequestValidationError, validation_error_handler)
|
||||
app.add_exception_handler(StarletteHTTPException, http_error_handler)
|
||||
app.add_exception_handler(Exception, unhandled_error_handler)
|
||||
|
||||
|
||||
@app.middleware("http")
|
||||
async def add_request_id(request: Request, call_next):
|
||||
request.state.request_id = str(uuid.uuid4())
|
||||
response = await call_next(request)
|
||||
response.headers["X-Request-Id"] = request.state.request_id
|
||||
return response
|
||||
|
||||
# ---------- Health ----------
|
||||
|
||||
@app.get("/health/live", response_model=Health)
|
||||
async def liveness():
|
||||
return Health(status="ok")
|
||||
|
||||
|
||||
@app.get("/health/ready", response_model=Health)
|
||||
async def readiness():
|
||||
# В Lab1 нет внешних зависимостей (БД появится в Lab2), поэтому
|
||||
# процесс всегда готов, если он успешно поднялся.
|
||||
return Health(status="ok")
|
||||
|
||||
@app.get("/internal/metrics")
|
||||
async def internal_metrics():
|
||||
return {
|
||||
"rss_bytes": process_rss_bytes(),
|
||||
**storage.counts(),
|
||||
}
|
||||
|
||||
def process_rss_bytes() -> int:
|
||||
try:
|
||||
for line in Path("/proc/self/status").read_text(encoding="utf-8").splitlines():
|
||||
if line.startswith("VmRSS:"):
|
||||
return int(line.split()[1]) * 1024
|
||||
except OSError:
|
||||
pass
|
||||
return 0
|
||||
|
||||
# ---------- Пользователи ----------
|
||||
|
||||
@app.post("/api/v1/users", response_model=User, status_code=201)
|
||||
async def register_user(payload: CreateUser):
|
||||
user = storage.create_user(payload.username, payload.display_name)
|
||||
if user is None:
|
||||
raise ApiError(409, "Username is already taken.")
|
||||
return user
|
||||
|
||||
|
||||
@app.get("/api/v1/users/me", response_model=User)
|
||||
async def current_user(user: dict = Depends(require_user)):
|
||||
return user
|
||||
|
||||
|
||||
# ---------- Чаты ----------
|
||||
|
||||
@app.post("/api/v1/chats", response_model=Chat, status_code=201)
|
||||
async def create_chat(payload: CreateChat, user: dict = Depends(require_user)):
|
||||
member_ids = [str(m) for m in payload.member_ids]
|
||||
|
||||
if user["id"] not in member_ids:
|
||||
raise ApiError(400, "Caller must be included in member_ids.")
|
||||
|
||||
for member_id in member_ids:
|
||||
if storage.get_user(member_id) is None:
|
||||
raise ApiError(400, f"Unknown member_id: {member_id}")
|
||||
|
||||
chat = storage.create_chat(payload.title, member_ids)
|
||||
return chat
|
||||
|
||||
|
||||
@app.get("/api/v1/chats", response_model=ChatPage)
|
||||
async def list_chats(
|
||||
user: dict = Depends(require_user),
|
||||
pagination: tuple[int, Optional[str]] = Depends(pagination_params),
|
||||
):
|
||||
limit, cursor = pagination
|
||||
try:
|
||||
items, next_cursor = storage.list_chats_for_user(user["id"], limit, cursor)
|
||||
except ValueError:
|
||||
raise ApiError(400, "Invalid cursor.")
|
||||
return ChatPage(items=items, next_cursor=next_cursor)
|
||||
|
||||
|
||||
@app.get("/api/v1/chats/{chat_id}", response_model=Chat)
|
||||
async def get_chat(chat_id: str, user: dict = Depends(require_user)):
|
||||
try:
|
||||
uuid.UUID(chat_id)
|
||||
except ValueError:
|
||||
raise ApiError(400, "chat_id must be a valid UUID.")
|
||||
|
||||
chat = storage.get_chat(chat_id)
|
||||
if chat is None or user["id"] not in chat["member_ids"]:
|
||||
raise ApiError(404, "Chat not found.")
|
||||
return chat
|
||||
|
||||
|
||||
# ---------- Сообщения ----------
|
||||
|
||||
@app.post("/api/v1/chats/{chat_id}/messages", response_model=Message, status_code=201)
|
||||
async def create_message(chat_id: str, payload: CreateMessage, user: dict = Depends(require_user)):
|
||||
try:
|
||||
uuid.UUID(chat_id)
|
||||
except ValueError:
|
||||
raise ApiError(400, "chat_id must be a valid UUID.")
|
||||
|
||||
chat = storage.get_chat(chat_id)
|
||||
if chat is None or user["id"] not in chat["member_ids"]:
|
||||
raise ApiError(404, "Chat not found.")
|
||||
|
||||
message = storage.create_message(chat_id, user["id"], payload.text)
|
||||
return message
|
||||
|
||||
|
||||
@app.get("/api/v1/chats/{chat_id}/messages", response_model=MessagePage)
|
||||
async def list_messages(
|
||||
chat_id: str,
|
||||
user: dict = Depends(require_user),
|
||||
pagination: tuple[int, Optional[str]] = Depends(pagination_params),
|
||||
):
|
||||
try:
|
||||
uuid.UUID(chat_id)
|
||||
except ValueError:
|
||||
raise ApiError(400, "chat_id must be a valid UUID.")
|
||||
|
||||
chat = storage.get_chat(chat_id)
|
||||
if chat is None or user["id"] not in chat["member_ids"]:
|
||||
raise ApiError(404, "Chat not found.")
|
||||
|
||||
limit, cursor = pagination
|
||||
try:
|
||||
items, next_cursor = storage.list_messages(chat_id, limit, cursor)
|
||||
except ValueError:
|
||||
raise ApiError(400, "Invalid cursor.")
|
||||
return MessagePage(items=items, next_cursor=next_cursor)
|
||||
|
||||
def process_rss_bytes() -> int:
|
||||
try:
|
||||
for line in Path("/proc/self/status").read_text(encoding="utf-8").splitlines():
|
||||
if line.startswith("VmRSS:"):
|
||||
return int(line.split()[1]) * 1024
|
||||
except OSError:
|
||||
pass
|
||||
return 0
|
||||
|
||||
if __name__ == "__main__":
|
||||
import uvicorn
|
||||
|
||||
uvicorn.run(app, host=config.HOST, port=config.PORT, log_level=config.LOG_LEVEL)
|
||||
Reference in New Issue
Block a user