Lab2: перенос исходников app/ и собственных тестов из lab1

This commit is contained in:
2026-09-30 23:09:16 +03:00
parent 65003b6119
commit d17eb22925
6 changed files with 518 additions and 0 deletions
View File
+182
View File
@@ -0,0 +1,182 @@
import os
import uuid
from contextvars import ContextVar
from typing import Optional
from fastapi import Depends, FastAPI, Header, HTTPException, Query, Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from starlette.middleware.base import BaseHTTPMiddleware
from .models import CreateChat, CreateMessage, CreateUser
from .storage import storage
request_id_var: ContextVar[str] = ContextVar("request_id", default="")
def err(status_code: int, code: str, message: str) -> JSONResponse:
return JSONResponse(
status_code=status_code,
content={
"error": {
"code": code,
"message": message,
"request_id": request_id_var.get(),
}
},
)
class RequestIdMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request: Request, call_next):
rid = request.headers.get("X-Request-Id") or uuid.uuid4().hex
request_id_var.set(rid)
response = await call_next(request)
response.headers["X-Request-Id"] = rid
return response
app = FastAPI(title="MTUSI Messenger — lab1")
app.add_middleware(RequestIdMiddleware)
# ---------- exception handlers ----------
_HTTP_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",
}
@app.exception_handler(RequestValidationError)
async def _validation_handler(request: Request, exc: RequestValidationError):
# пустое сообщение, limit=0, чужой json и т.п.
return err(400, "invalid_request", "Validation error")
@app.exception_handler(HTTPException)
async def _http_handler(request: Request, exc: HTTPException):
code = _HTTP_CODES.get(exc.status_code, "internal_error")
message = exc.detail if isinstance(exc.detail, str) and exc.detail else "Error"
return err(exc.status_code, code, message)
@app.exception_handler(Exception)
async def _generic_handler(request: Request, exc: Exception):
# ноль деталей -> ошибка
return err(500, "internal_error", "Internal server error")
# dependency
def get_actor(x_user_id: Optional[str] = Header(None, alias="X-User-Id")) -> dict:
if not x_user_id:
raise HTTPException(401, "Unauthorized")
user = storage.get_user(x_user_id)
if user is None:
raise HTTPException(401, "Unauthorized")
return user
# health
@app.get("/health/live")
def health_live():
return {"status": "ok"}
@app.get("/health/ready")
def health_ready():
return {"status": "ok"}
# users
@app.post("/api/v1/users", status_code=201)
def create_user(body: CreateUser):
user = storage.create_user(body.username, body.display_name)
if user is None:
raise HTTPException(409, "Username already exists")
return user
@app.get("/api/v1/users/me")
def current_user(actor: dict = Depends(get_actor)):
return actor
# chats
@app.post("/api/v1/chats", status_code=201)
def create_chat(body: CreateChat, actor: dict = Depends(get_actor)):
if actor["id"] not in body.member_ids:
raise HTTPException(400, "Caller must be in member_ids")
chat, error = storage.create_chat(body.title, body.member_ids, actor["id"])
if error == "member_not_found":
raise HTTPException(404, "Member not found")
if error:
raise HTTPException(400, error)
return chat
@app.get("/api/v1/chats")
def list_chats(
actor: dict = Depends(get_actor),
limit: int = Query(50, ge=1, le=100),
cursor: Optional[str] = Query(None, min_length=1),
):
items, next_cursor = storage.list_chats(actor["id"], limit, cursor)
return {"items": items, "next_cursor": next_cursor}
@app.get("/api/v1/chats/{chat_id}")
def get_chat(chat_id: str, actor: dict = Depends(get_actor)):
chat = storage.get_chat(chat_id, actor["id"])
if chat is None:
raise HTTPException(404, "Chat not found")
return chat
# messages
@app.post("/api/v1/chats/{chat_id}/messages", status_code=201)
def post_message(
chat_id: str,
body: CreateMessage,
actor: dict = Depends(get_actor),
):
msg, error = storage.post_message(chat_id, actor["id"], body.text)
if error == "chat_not_found":
raise HTTPException(404, "Chat not found")
if error:
raise HTTPException(400, error)
return msg
@app.get("/api/v1/chats/{chat_id}/messages")
def list_messages(
chat_id: str,
actor: dict = Depends(get_actor),
limit: int = Query(50, ge=1, le=100),
cursor: Optional[str] = Query(None, min_length=1),
):
items, next_cursor, error = storage.list_messages(
chat_id, actor["id"], limit, cursor
)
if error == "chat_not_found":
raise HTTPException(404, "Chat not found")
return {"items": items, "next_cursor": next_cursor}
if __name__ == "__main__":
import uvicorn
port = int(os.getenv("PORT", "8080"))
uvicorn.run(app, host="0.0.0.0", port=port, log_level="info")
+30
View File
@@ -0,0 +1,30 @@
from uuid import UUID
from pydantic import BaseModel, ConfigDict, Field, field_validator
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 CreateChat(BaseModel):
model_config = ConfigDict(extra="forbid")
title: str = Field(min_length=1, max_length=100)
member_ids: list[str] = Field(min_length=1, max_length=100)
@field_validator("member_ids")
@classmethod
def _validate_members(cls, value: list[str]) -> list[str]:
seen: set[str] = set()
for raw in value:
UUID(raw) # бросит ValueError -> RequestValidationError -> 400
if raw in seen:
raise ValueError("duplicate member_ids")
seen.add(raw)
return value
class CreateMessage(BaseModel):
model_config = ConfigDict(extra="forbid")
text: str = Field(min_length=1, max_length=4000)
+134
View File
@@ -0,0 +1,134 @@
import threading
import uuid
from datetime import datetime, timezone
def new_id() -> str:
return str(uuid.uuid4())
def now_iso() -> str:
return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
def _key_message(m: dict):
return (m["created_at"], uuid.UUID(m["id"]).int)
class Storage:
def __init__(self) -> None:
self._lock = threading.RLock()
self.users: dict[str, dict] = {}
self.chats: dict[str, dict] = {}
self.messages: dict[str, list[dict]] = {}
# users
def create_user(self, username: str, display_name: str) -> dict | None:
with self._lock:
for u in self.users.values():
if u["username"] == username:
return None
uid = new_id()
user = {
"id": uid,
"username": username,
"display_name": display_name,
"created_at": now_iso(),
}
self.users[uid] = user
return dict(user)
def get_user(self, uid: str) -> dict | None:
with self._lock:
u = self.users.get(uid)
return dict(u) if u else None
# chats
def create_chat(self, title: str, member_ids: list[str], creator_id: str):
with self._lock:
for mid in member_ids:
if mid not in self.users:
return None, "member_not_found"
if creator_id not in member_ids:
return None, "creator_not_member"
cid = new_id()
chat = {
"id": cid,
"title": title,
"member_ids": list(member_ids),
"created_at": now_iso(),
}
self.chats[cid] = chat
self.messages[cid] = []
return self._chat_public(chat), None
def get_chat(self, chat_id: str, requester_id: str) -> dict | None:
with self._lock:
chat = self.chats.get(chat_id)
if chat is None or requester_id not in chat["member_ids"]:
return None
return self._chat_public(chat)
def list_chats(self, requester_id: str, limit: int, cursor: str | None):
with self._lock:
items = [c for c in self.chats.values() if requester_id in c["member_ids"]]
items.sort(key=lambda c: (c["created_at"], uuid.UUID(c["id"]).int))
start = 0
if cursor:
for i, c in enumerate(items):
if c["id"] == cursor:
start = i + 1
break
page = items[start:start + limit]
next_cursor = None
if len(page) == limit and start + limit < len(items):
next_cursor = page[-1]["id"]
return [self._chat_public(c) for c in page], next_cursor
# messages
def post_message(self, chat_id: str, sender_id: str, text: str):
with self._lock:
chat = self.chats.get(chat_id)
if chat is None or sender_id not in chat["member_ids"]:
return None, "chat_not_found"
msg = {
"id": new_id(),
"chat_id": chat_id,
"sender_id": sender_id,
"text": text,
"created_at": now_iso(),
}
self.messages[chat_id].append(msg)
return dict(msg), None
def list_messages(self, chat_id: str, requester_id: str,
limit: int, cursor: str | None):
with self._lock:
chat = self.chats.get(chat_id)
if chat is None or requester_id not in chat["member_ids"]:
return None, None, "chat_not_found"
items = self.messages[chat_id] # здесь было узкое место items = sorted(self.messages[chat_id], key=_key_message)
start = 0
if cursor:
for i, m in enumerate(items):
if m["id"] == cursor:
start = i + 1
break
page = items[start:start + limit]
next_cursor = None
if len(page) == limit and start + limit < len(items):
next_cursor = page[-1]["id"]
return [dict(m) for m in page], next_cursor, None
@staticmethod
def _chat_public(chat: dict) -> dict:
return {
"id": chat["id"],
"title": chat["title"],
"member_ids": list(chat["member_ids"]),
"created_at": chat["created_at"],
}
storage = Storage()