lab2 complete

This commit is contained in:
kuruoni
2026-11-14 04:50:02 +03:00
parent 65003b6119
commit 684d00c899
20 changed files with 796 additions and 16 deletions
+68
View File
@@ -0,0 +1,68 @@
import uuid
import base64
from typing import Optional
from fastapi import FastAPI, Request, status
from fastapi.exceptions import RequestValidationError
from starlette.exceptions import HTTPException as StarletteHTTPException
from contextlib import asynccontextmanager
from .exceptions import make_error_response, ApiException
from .db import get_pool, init_db, close_db
from .routes.router import api_v1_router
@asynccontextmanager
async def lifespan(app: FastAPI):
await init_db()
yield
await close_db()
app = FastAPI(title='MTUCI messanger', lifespan=lifespan)
@app.middleware("http")
async def request_id_middleware(request: Request, call_next):
req_id = request.headers.get("X-Request-Id")
if not req_id or not req_id.strip():
req_id = str(uuid.uuid4())
request.state.request_id = req_id
response = await call_next(request)
response.headers["X-Request-Id"] = req_id
return response
@app.exception_handler(ApiException)
async def api_exception_handler(request: Request, exc: ApiException):
req_id = getattr(request.state, "request_id", str(uuid.uuid4()))
return make_error_response(exc.status_code, exc.code, exc.message, req_id, exc.headers)
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError):
req_id = getattr(request.state, "request_id", str(uuid.uuid4()))
return make_error_response(400, "invalid_request", "Invalid request body", req_id)
@app.exception_handler(StarletteHTTPException)
async def http_exception_handler(request: Request, exc: StarletteHTTPException):
req_id = getattr(request.state, "request_id", str(uuid.uuid4()))
return make_error_response(exc.status_code, "invalid_request", str(exc.detail), req_id)
@app.exception_handler(Exception)
async def general_exception_handler(request: Request, exc: Exception):
req_id = getattr(request.state, "request_id", str(uuid.uuid4()))
return make_error_response(500, "internal_error", "Internal server error", req_id)
@app.get("/health/live")
async def health_live():
return {"status": "ok"}
@app.get("/health/ready")
async def health_ready():
return {"status": "ok"}
app.include_router(api_v1_router)
+25
View File
@@ -0,0 +1,25 @@
import os
import asyncpg
DATABASE_URL = os.getenv("DATABASE_URL", "postgresql://messenger:secret_password@postgres:5432/messenger_db")
pool: asyncpg.Pool = None
async def init_db():
global pool
pool = await asyncpg.create_pool(DATABASE_URL, min_size=2, max_size=10)
migration_path = os.path.join(os.path.dirname(__file__), "migrations", "001_init_db.sql")
if os.path.exists(migration_path):
with open(migration_path, "r", encoding="utf-8") as f:
sql = f.read()
async with pool.acquire() as conn:
await conn.execute(sql)
async def close_db():
global pool
if pool:
await pool.close()
def get_pool() -> asyncpg.Pool:
return pool
+18
View File
@@ -0,0 +1,18 @@
from fastapi.responses import JSONResponse
class ApiException(Exception):
def __init__(self, status_code: int, code: str, message: str, headers: dict = None):
self.status_code = status_code
self.code = code
self.message = message
self.headers = headers or {}
def make_error_response(status_code: int, code: str, message: str, request_id: str, headers: dict = None):
resp_headers = {"X-Request-Id": request_id}
if headers:
resp_headers.update(headers)
return JSONResponse(
status_code=status_code,
content={"error": {"code": code, "message": message, "request_id": request_id}},
headers=resp_headers
)
+36
View File
@@ -0,0 +1,36 @@
CREATE TABLE IF NOT EXISTS users (
id UUID PRIMARY KEY,
username VARCHAR(32) UNIQUE NOT NULL,
display_name VARCHAR(100) NOT NULL,
password_hash TEXT NOT NULL,
created_at TIMESTAMPTZ NOT NULL
);
CREATE TABLE IF NOT EXISTS sessions (
token TEXT PRIMARY KEY,
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
expires_at TIMESTAMPTZ NOT NULL,
revoked BOOLEAN NOT NULL DEFAULT FALSE
);
CREATE TABLE IF NOT EXISTS chats (
id UUID PRIMARY KEY,
title VARCHAR(128) NOT NULL,
created_at TIMESTAMPTZ NOT NULL
);
CREATE TABLE IF NOT EXISTS chat_members (
chat_id UUID NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
PRIMARY KEY (chat_id, user_id)
);
CREATE TABLE IF NOT EXISTS messages (
id UUID PRIMARY KEY,
chat_id UUID NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
sender_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
text TEXT NOT NULL,
created_at TIMESTAMPTZ NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_messages_chat_cursor ON messages (chat_id, created_at, id);
+23
View File
@@ -0,0 +1,23 @@
import uuid
from pydantic import BaseModel, ConfigDict, Field
from typing import List
class CreateUserRequest(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)
password: str = Field(min_length=12, max_length=128)
class CreateChatRequest(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)
class SendMessageRequest(BaseModel):
model_config = ConfigDict(extra="forbid")
text: str = Field(min_length=1, max_length=4000)
+69
View File
@@ -0,0 +1,69 @@
import bcrypt
import base64
import secrets
import os
from datetime import timedelta
from fastapi import APIRouter, Request, status
from ..exceptions import ApiException
from ..db import get_pool
from ..utils import get_utc_now, authenticate_user, format_iso
router = APIRouter(tags=["auth"])
SESSION_TTL_SECONDS = int(os.getenv("SESSION_TTL_SECONDS", "3600"))
@router.post("/auth/sessions", status_code=status.HTTP_201_CREATED)
async def create_session(request: Request):
auth = request.headers.get("Authorization")
auth_err_headers = {"WWW-Authenticate": 'Basic realm="messenger"'}
if not auth or not auth.startswith("Basic "):
raise ApiException(401, "unauthorized", "Missing Basic auth", headers=auth_err_headers)
try:
decoded = base64.b64decode(auth.split(" ", 1)[1]).decode("utf-8")
username, password = decoded.split(":", 1)
except Exception:
raise ApiException(401, "unauthorized", "Invalid Basic format", headers=auth_err_headers)
pool = get_pool()
user = await pool.fetchrow("SELECT id, username, display_name, password_hash, created_at FROM users WHERE username = $1", username)
if not user:
raise ApiException(401, "unauthorized", "Invalid credentials", headers=auth_err_headers)
if not bcrypt.checkpw(password.encode("utf-8"), user["password_hash"].encode("utf-8")):
raise ApiException(401, "unauthorized", "Invalid credentials", headers=auth_err_headers)
token = secrets.token_urlsafe(32)
now = get_utc_now()
expires_at = now + timedelta(seconds=SESSION_TTL_SECONDS)
await pool.execute(
"INSERT INTO sessions (token, user_id, expires_at, revoked) VALUES ($1, $2, $3, FALSE)",
token, user["id"], expires_at
)
return {
"token": token,
"token_type": "Bearer",
"expires_at": format_iso(expires_at),
"user": {
"id": str(user["id"]),
"username": user["username"],
"display_name": user["display_name"],
"created_at": format_iso(user["created_at"])
}
}
@router.delete("/auth/sessions/current", status_code=status.HTTP_204_NO_CONTENT)
async def delete_current_session(request: Request):
await authenticate_user(request)
token = request.state.current_token
pool = get_pool()
await pool.execute("UPDATE sessions SET revoked = TRUE WHERE token = $1", token)
return None
+111
View File
@@ -0,0 +1,111 @@
import uuid
from fastapi import APIRouter, Request, status
from ..models import CreateChatRequest
from ..utils import authenticate_user, validate_uuid, format_iso, get_utc_now
from ..exceptions import ApiException
from ..db import get_pool
router = APIRouter(tags=["chats"])
@router.post("/chats", status_code=status.HTTP_201_CREATED)
async def create_chat(body: CreateChatRequest, request: Request):
caller_id = await authenticate_user(request)
if not body.title.strip() or len(body.title) > 128:
raise ApiException(400, "invalid_request", "Invalid title")
if len(body.member_ids) != len(set(body.member_ids)):
raise ApiException(400, "invalid_request", "Duplicate member_ids")
if caller_id not in body.member_ids:
raise ApiException(400, "invalid_request", "Caller must be included in member_ids")
pool = get_pool()
member_uuids = []
for mid in body.member_ids:
validate_uuid(mid)
u = uuid.UUID(mid)
exists = await pool.fetchval("SELECT id FROM users WHERE id = $1", u)
if not exists:
raise ApiException(400, "invalid_request", f"Member {mid} not found")
member_uuids.append(u)
cid = uuid.uuid4()
now = get_utc_now()
async with pool.acquire() as conn:
async with conn.transaction():
await conn.execute("INSERT INTO chats (id, title, created_at) VALUES ($1, $2, $3)", cid, body.title, now)
for m in member_uuids:
await conn.execute("INSERT INTO chat_members (chat_id, user_id) VALUES ($1, $2)", cid, m)
return {
"id": str(cid),
"title": body.title,
"member_ids": body.member_ids,
"created_at": format_iso(now)
}
@router.get("/chats")
async def list_chats(request: Request, limit: int = 50):
caller_id = await authenticate_user(request)
if limit < 1 or limit > 100:
raise ApiException(400, "invalid_request", "Limit must be between 1 and 100")
pool = get_pool()
rows = await pool.fetch("""
SELECT c.id, c.title, c.created_at, array_agg(cm.user_id::text) as member_ids
FROM chats c
JOIN chat_members cm ON c.id = cm.chat_id
WHERE c.id IN (SELECT chat_id FROM chat_members WHERE user_id = $1)
GROUP BY c.id, c.title, c.created_at
ORDER BY c.created_at ASC, c.id ASC
LIMIT $2
""", uuid.UUID(caller_id), limit)
items = [
{
"id": str(r["id"]),
"title": r["title"],
"member_ids": list(r["member_ids"]),
"created_at": format_iso(r["created_at"])
}
for r in rows
]
result = {
"items": items,
"next_cursor": None
}
print("API RESPONSE:", result)
return result
@router.get("/chats/{chat_id}")
async def get_chat(chat_id: str, request: Request):
caller_id = await authenticate_user(request)
validate_uuid(chat_id)
pool = get_pool()
row = await pool.fetchrow("""
SELECT c.id, c.title, c.created_at, array_agg(cm.user_id::text) as member_ids
FROM chats c
JOIN chat_members cm ON c.id = cm.chat_id
WHERE c.id = $1
GROUP BY c.id, c.title, c.created_at
""", uuid.UUID(chat_id))
if not row or caller_id not in row["member_ids"]:
raise ApiException(404, "not_found", "Chat not found")
return {
"id": str(row["id"]),
"title": row["title"],
"member_ids": list(row["member_ids"]),
"created_at": format_iso(row["created_at"])
}
+149
View File
@@ -0,0 +1,149 @@
import uuid
import json
import base64
from datetime import timezone, datetime
from typing import Optional
from fastapi import APIRouter, status, Request
from ..utils import authenticate_user, validate_uuid, get_utc_now, format_iso
from ..exceptions import ApiException
from ..models import SendMessageRequest
from ..db import get_pool
router = APIRouter(tags=["messages"])
@router.post("/chats/{chat_id}/messages", status_code=status.HTTP_201_CREATED)
async def send_message(chat_id: str, body: SendMessageRequest, request: Request):
caller_id = await authenticate_user(request)
validate_uuid(chat_id)
pool = get_pool()
is_member = await pool.fetchval(
"SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2",
uuid.UUID(chat_id), uuid.UUID(caller_id)
)
if not is_member:
raise ApiException(404, "not_found", "Chat not found")
if not body.text.strip() or len(body.text) > 4000:
raise ApiException(400, "invalid_request", "Invalid text")
mid = uuid.uuid4()
now = get_utc_now()
await pool.execute(
"INSERT INTO messages (id, chat_id, sender_id, text, created_at) VALUES ($1, $2, $3, $4, $5)",
mid, uuid.UUID(chat_id), uuid.UUID(caller_id), body.text, now
)
return {
"id": str(mid),
"chat_id": chat_id,
"sender_id": caller_id,
"text": body.text,
"created_at": format_iso(now)
}
@router.get("/chats/{chat_id}/messages")
async def get_messages(
chat_id: str,
request: Request,
limit: int = 50,
cursor: Optional[str] = None
):
caller_id = await authenticate_user(request)
validate_uuid(chat_id)
pool = get_pool()
chat_uuid = uuid.UUID(chat_id)
is_member = await pool.fetchval(
"SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2",
chat_uuid,
uuid.UUID(caller_id)
)
if not is_member:
raise ApiException(404, "not_found", "Chat not found")
if limit < 1 or limit > 100:
raise ApiException(400, "invalid_request", "Invalid limit")
cursor_time = None
cursor_id = None
if cursor is not None:
try:
decoded = base64.urlsafe_b64decode(
cursor + "=" * (-len(cursor) % 4)
)
data = json.loads(decoded)
cursor_time = datetime.fromisoformat(
data["created_at"].replace("Z", "+00:00")
)
cursor_id = uuid.UUID(data["id"])
if cursor_time.tzinfo is None:
raise ValueError()
cursor_time = cursor_time.astimezone(timezone.utc)
except (ValueError, KeyError, TypeError, UnicodeDecodeError):
raise ApiException(
400, "invalid_request", "Invalid cursor"
)
rows = await pool.fetch(
"""
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
""",
chat_uuid,
cursor_time,
cursor_id,
limit + 1
)
has_more = len(rows) > limit
rows = rows[:limit]
items = [
{
"id": str(row["id"]),
"chat_id": str(row["chat_id"]),
"sender_id": str(row["sender_id"]),
"text": row["text"],
"created_at": format_iso(row["created_at"])
}
for row in rows
]
next_cursor = None
if has_more and rows:
last = rows[-1]
cursor_data = {
"created_at": format_iso(last["created_at"]),
"id": str(last["id"])
}
next_cursor = base64.urlsafe_b64encode(
json.dumps(cursor_data).encode("utf-8")
).decode("ascii").rstrip("=")
return {
"items": items,
"next_cursor": next_cursor
}
+10
View File
@@ -0,0 +1,10 @@
from fastapi import APIRouter
from . import auth, chats, users, messages
api_v1_router = APIRouter(prefix="/api/v1")
api_v1_router.include_router(auth.router)
api_v1_router.include_router(chats.router)
api_v1_router.include_router(users.router)
api_v1_router.include_router(messages.router)
+58
View File
@@ -0,0 +1,58 @@
import bcrypt
import uuid
from fastapi import APIRouter, status, Request
from ..utils import authenticate_user, get_utc_now, USERNAME_REGEX, format_iso
from ..db import get_pool
from ..exceptions import ApiException
from ..models import CreateUserRequest
router = APIRouter(tags=["users"])
@router.post("/users", status_code=status.HTTP_201_CREATED)
async def create_user(body: CreateUserRequest):
if not USERNAME_REGEX.match(body.username):
raise ApiException(400, "invalid_request", "Invalid username format")
if not body.password or len(body.password) < 4:
raise ApiException(400, "invalid_request", "Password too short")
display_name = body.display_name if body.display_name is not None else body.username
if len(display_name) < 1 or len(display_name) > 100 or not display_name.strip():
raise ApiException(400, "invalid_request", "Invalid display_name")
pool = get_pool()
existing = await pool.fetchval("SELECT id FROM users WHERE username = $1", body.username)
if existing:
raise ApiException(409, "conflict", "Username already taken")
salt = bcrypt.gensalt()
pw_hash = bcrypt.hashpw(body.password.encode("utf-8"), salt).decode("utf-8")
uid = uuid.uuid4()
now = get_utc_now()
await pool.execute(
"INSERT INTO users (id, username, display_name, password_hash, created_at) VALUES ($1, $2, $3, $4, $5)",
uid, body.username, display_name, pw_hash, now
)
return {
"id": str(uid),
"username": body.username,
"display_name": display_name,
"created_at": format_iso(now)
}
@router.get("/users/me")
async def get_me(request: Request):
caller_id = await authenticate_user(request)
pool = get_pool()
row = await pool.fetchrow("SELECT id, username, display_name, created_at FROM users WHERE id = $1", uuid.UUID(caller_id))
return {
"id": str(row["id"]),
"username": row["username"],
"display_name": row["display_name"],
"created_at": format_iso(row["created_at"])
}
+53
View File
@@ -0,0 +1,53 @@
import re
import uuid as _uuid_lib
from fastapi import Request
from datetime import timezone, datetime
from .exceptions import ApiException
from .db import get_pool
users_db = {}
usernames_set = set()
chats_db = {}
messages_db = {}
USERNAME_REGEX = re.compile(r"^[a-z0-9_]{3,32}$")
def get_utc_now() -> str:
return datetime.now(timezone.utc)
def format_iso(dt: datetime) -> str:
return dt.strftime("%Y-%m-%dT%H:%M:%S.%fZ")
async def authenticate_user(request: Request) -> str:
auth = request.headers.get("Authorization")
auth_err_headers = {"WWW-Authenticate": 'Bearer realm="messenger"'}
if not auth or not auth.startswith("Bearer "):
raise ApiException(401, "unauthorized", "Missing or invalid Bearer token", headers=auth_err_headers)
token = auth.split(" ", 1)[1].strip()
pool = get_pool()
row = await pool.fetchrow(
"SELECT user_id, expires_at, revoked FROM sessions WHERE token = $1",
token
)
if not row:
raise ApiException(401, "unauthorized", "Session not found", headers=auth_err_headers)
if row["revoked"] or row["expires_at"] <= get_utc_now():
raise ApiException(401, "unauthorized", "Session expired or revoked", headers=auth_err_headers)
request.state.current_token = token
return str(row["user_id"])
def validate_uuid(val: str):
try:
_uuid_lib.UUID(str(val))
except Exception as e:
print(f" РЕАЛЬНАЯ ОШИБКА В validate_uuid: {type(e).__name__} -> {e}")
raise ApiException(400, "invalid_request", f"Invalid UUID: {val}")