Files
mtusi2026lab3/src/main.py
T

351 lines
14 KiB
Python

import base64
import hashlib
import json
import os
import re
import secrets
import uuid
from contextlib import asynccontextmanager
from datetime import timezone
from typing import Optional
from fastapi import FastAPI, Header, Request, Response
from fastapi.exceptions import RequestValidationError
from pydantic import BaseModel, Field, field_validator
from .auth import (create_session, hash_password, purge_expired,
resolve_session, revoke_session, verify_password)
from .db import pool, run_migrations, tx
from .errors import (ApiError, api_error_handler, request_id_of,
unhandled_handler, validation_exception_handler)
@asynccontextmanager
async def lifespan(app: FastAPI):
run_migrations()
purge_expired()
yield
app = FastAPI(lifespan=lifespan)
app.add_exception_handler(ApiError, api_error_handler)
app.add_exception_handler(RequestValidationError, validation_exception_handler)
app.add_exception_handler(Exception, unhandled_handler)
INSTANCE_ID = os.environ.get("INSTANCE_ID") or secrets.token_hex(6)
@app.middleware("http")
async def _rid_middleware(request: Request, call_next):
rid = request_id_of(request)
request.state.request_id = rid
response = await call_next(request)
response.headers["X-Request-Id"] = rid
response.headers["X-Instance-Id"] = INSTANCE_ID
return response
USERNAME_RE = r"^[a-z0-9_]{3,32}$"
IDEMPOTENCY_RE = re.compile(r"^[A-Za-z0-9._:-]{1,128}$")
class CreateUser(BaseModel):
username: str = Field(pattern=USERNAME_RE)
display_name: str = Field(min_length=1, max_length=100)
password: str = Field(min_length=12, max_length=128)
class CreateChat(BaseModel):
title: str = Field(min_length=1, max_length=100)
member_ids: list[uuid.UUID] = Field(min_length=1, max_length=100)
@field_validator("member_ids")
@classmethod
def unique_members(cls, v):
if len(set(v)) != len(v):
raise ValueError("duplicate member_ids")
return v
class CreateMessage(BaseModel):
text: str = Field(min_length=1, max_length=4000)
def _iso(dt) -> str:
return dt.astimezone(timezone.utc).isoformat().replace("+00:00", "Z")
def _row_to_user(row) -> dict:
return {"id": str(row[0]), "username": row[1],
"display_name": row[2], "created_at": _iso(row[3])}
def _require_bearer(authorization: Optional[str]) -> str:
if not authorization or not authorization.startswith("Bearer "):
raise ApiError(401, "unauthorized", "Требуется Bearer-токен",
{"WWW-Authenticate": 'Bearer realm="messenger"'})
token = authorization[len("Bearer "):]
user_id = resolve_session(token)
if not user_id:
raise ApiError(401, "unauthorized", "Сессия недействительна",
{"WWW-Authenticate": 'Bearer realm="messenger"'})
return str(user_id)
def _is_member(conn, chat_id: str, user_id: str) -> bool:
with conn.cursor() as cur:
cur.execute("SELECT 1 FROM chat_members WHERE chat_id=%s AND user_id=%s",
(chat_id, user_id))
return cur.fetchone() is not None
@app.get("/health/live")
def live():
return {"status": "ok"}
@app.get("/health/ready")
def ready():
try:
with pool.connection() as conn:
with conn.cursor() as cur:
cur.execute("SELECT 1")
return {"status": "ok"}
except Exception:
raise ApiError(503, "unavailable", "База недоступна")
@app.post("/api/v1/users", status_code=201)
def register(body: CreateUser):
with tx() as conn:
with conn.cursor() as cur:
cur.execute("SELECT 1 FROM users WHERE username=%s", (body.username,))
if cur.fetchone():
raise ApiError(409, "conflict", "Username занят")
cur.execute(
"INSERT INTO users (username, display_name, password_hash) "
"VALUES (%s,%s,%s) RETURNING id, username, display_name, created_at",
(body.username, body.display_name, hash_password(body.password)),
)
row = cur.fetchone()
return _row_to_user(row)
@app.get("/api/v1/users/me")
def me(authorization: Optional[str] = Header(default=None)):
uid = _require_bearer(authorization)
with pool.connection() as conn:
with conn.cursor() as cur:
cur.execute("SELECT id, username, display_name, created_at FROM users WHERE id=%s",
(uid,))
row = cur.fetchone()
if not row:
raise ApiError(401, "unauthorized", "Пользователь не найден",
{"WWW-Authenticate": 'Bearer realm="messenger"'})
return _row_to_user(row)
@app.post("/api/v1/auth/sessions", status_code=201)
def login(authorization: Optional[str] = Header(default=None)):
if not authorization or not authorization.startswith("Basic "):
raise ApiError(401, "unauthorized", "Требуется Basic",
{"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'})
try:
raw = base64.b64decode(authorization[len("Basic "):], validate=True).decode("utf-8")
username, password = raw.split(":", 1)
except Exception:
raise ApiError(400, "invalid_request", "Некорректный Basic")
with pool.connection() as conn:
with conn.cursor() as cur:
cur.execute("SELECT id, password_hash FROM users WHERE username=%s", (username,))
row = cur.fetchone()
if not row or not verify_password(row[1], password):
raise ApiError(401, "unauthorized", "Неверные учётные данные",
{"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'})
token, expires = create_session(str(row[0]))
with pool.connection() as conn:
with conn.cursor() as cur:
cur.execute("SELECT id, username, display_name, created_at FROM users WHERE id=%s",
(row[0],))
u = cur.fetchone()
return {"token": token, "token_type": "Bearer",
"expires_at": _iso(expires), "user": _row_to_user(u)}
@app.delete("/api/v1/auth/sessions/current", status_code=204)
def logout(authorization: Optional[str] = Header(default=None)):
if not authorization or not authorization.startswith("Bearer "):
raise ApiError(401, "unauthorized", "Требуется Bearer",
{"WWW-Authenticate": 'Bearer realm="messenger"'})
token = authorization[len("Bearer "):]
if not resolve_session(token):
raise ApiError(401, "unauthorized", "Сессия недействительна",
{"WWW-Authenticate": 'Bearer realm="messenger"'})
revoke_session(token)
return Response(status_code=204)
def _row_to_chat(row, members) -> dict:
return {"id": str(row[0]), "title": row[1],
"member_ids": [str(m) for m in members], "created_at": _iso(row[2])}
@app.post("/api/v1/chats", status_code=201)
def create_chat(body: CreateChat, authorization: Optional[str] = Header(default=None)):
uid = _require_bearer(authorization)
if uuid.UUID(uid) not in body.member_ids:
raise ApiError(400, "invalid_request", "Вызывающий должен быть в member_ids")
with tx() as conn:
with conn.cursor() as cur:
cur.execute("SELECT id FROM users WHERE id = ANY(%s)",
([str(m) for m in body.member_ids],))
found = {str(r[0]) for r in cur.fetchall()}
if found != {str(m) for m in body.member_ids}:
raise ApiError(400, "invalid_request", "Неизвестный участник")
cur.execute("INSERT INTO chats (title) VALUES (%s) "
"RETURNING id, title, created_at", (body.title,))
row = cur.fetchone()
chat_id = row[0]
cur.executemany("INSERT INTO chat_members (chat_id, user_id) VALUES (%s,%s)",
[(chat_id, str(m)) for m in body.member_ids])
return _row_to_chat(row, body.member_ids)
@app.get("/api/v1/chats")
def list_chats(limit: int = 50, cursor: Optional[str] = None,
authorization: Optional[str] = Header(default=None)):
uid = _require_bearer(authorization)
if not (1 <= limit <= 100):
raise ApiError(400, "invalid_request", "limit 1..100")
with pool.connection() as conn:
with conn.cursor() as cur:
cur.execute(
"SELECT c.id, c.title, c.created_at FROM chats c "
"JOIN chat_members m ON m.chat_id = c.id "
"WHERE m.user_id = %s ORDER BY c.created_at, c.id LIMIT %s",
(uid, limit),
)
rows = cur.fetchall()
items = []
for r in rows:
cur.execute("SELECT user_id FROM chat_members WHERE chat_id=%s", (r[0],))
members = [x[0] for x in cur.fetchall()]
items.append(_row_to_chat(r, members))
return {"items": items, "next_cursor": None}
@app.get("/api/v1/chats/{chat_id}")
def get_chat(chat_id: uuid.UUID, authorization: Optional[str] = Header(default=None)):
uid = _require_bearer(authorization)
with pool.connection() as conn:
if not _is_member(conn, str(chat_id), uid):
raise ApiError(404, "not_found", "Чат не найден")
with conn.cursor() as cur:
cur.execute("SELECT id, title, created_at FROM chats WHERE id=%s", (str(chat_id),))
row = cur.fetchone()
cur.execute("SELECT user_id FROM chat_members WHERE chat_id=%s", (str(chat_id),))
members = [x[0] for x in cur.fetchall()]
return _row_to_chat(row, members)
@app.post("/api/v1/chats/{chat_id}/messages", status_code=201)
def send_message(chat_id: uuid.UUID, body: CreateMessage,
authorization: Optional[str] = Header(default=None),
idempotency_key: Optional[str] = Header(default=None,
alias="Idempotency-Key")):
uid = _require_bearer(authorization)
if not body.text.strip():
raise ApiError(400, "invalid_request", "Пустой текст")
if not idempotency_key or not IDEMPOTENCY_RE.fullmatch(idempotency_key):
raise ApiError(400, "invalid_request", "Неверный Idempotency-Key")
path = f"/api/v1/chats/{chat_id}/messages"
canonical = json.dumps({"text": body.text}, sort_keys=True, ensure_ascii=False)
request_hash = hashlib.sha256(canonical.encode("utf-8")).hexdigest()
with tx() as conn:
if not _is_member(conn, str(chat_id), uid):
raise ApiError(404, "not_found", "Чат не найден")
with conn.cursor() as cur:
cur.execute(
"INSERT INTO idempotency_keys (user_id, method, path, key, request_hash) "
"VALUES (%s, 'POST', %s, %s, %s) ON CONFLICT DO NOTHING",
(uid, path, idempotency_key, request_hash),
)
inserted = cur.rowcount
if inserted == 0:
cur.execute(
"SELECT request_hash, status_code, response_body "
"FROM idempotency_keys "
"WHERE user_id=%s AND method='POST' AND path=%s AND key=%s "
"FOR UPDATE",
(uid, path, idempotency_key),
)
rh, sc, rb = cur.fetchone()
if rh != request_hash:
raise ApiError(409, "conflict",
"Idempotency-Key переиспользован с другим body")
if rb is not None:
return rb
raise ApiError(409, "conflict", "Запрос ещё выполняется")
cur.execute(
"INSERT INTO messages (chat_id, sender_id, text) VALUES (%s,%s,%s) "
"RETURNING id, chat_id, sender_id, text, created_at",
(str(chat_id), uid, body.text),
)
row = cur.fetchone()
result = {"id": str(row[0]), "chat_id": str(row[1]), "sender_id": str(row[2]),
"text": row[3], "created_at": _iso(row[4])}
cur.execute(
"UPDATE idempotency_keys "
"SET status_code=201, response_body=%s, message_id=%s "
"WHERE user_id=%s AND method='POST' AND path=%s AND key=%s",
(json.dumps(result), row[0], uid, path, idempotency_key),
)
return result
@app.get("/api/v1/chats/{chat_id}/messages")
def list_messages(chat_id: uuid.UUID, limit: int = 50, cursor: Optional[str] = None,
authorization: Optional[str] = Header(default=None)):
uid = _require_bearer(authorization)
if not (1 <= limit <= 100):
raise ApiError(400, "invalid_request", "limit 1..100")
with pool.connection() as conn:
if not _is_member(conn, str(chat_id), uid):
raise ApiError(404, "not_found", "Чат не найден")
params = [str(chat_id)]
where = "chat_id=%s"
if cursor:
try:
ts, mid = cursor.split("|")
params += [ts, mid]
where += " AND (created_at, id) > (%s::timestamptz, %s::uuid)"
except Exception:
raise ApiError(400, "invalid_request", "Неверный cursor")
params.append(limit + 1)
with conn.cursor() as cur:
cur.execute(
f"SELECT id, chat_id, sender_id, text, created_at FROM messages "
f"WHERE {where} ORDER BY created_at, id LIMIT %s", params)
rows = cur.fetchall()
has_more = len(rows) > limit
if has_more:
rows = rows[:limit]
items = [{"id": str(r[0]), "chat_id": str(r[1]), "sender_id": str(r[2]),
"text": r[3], "created_at": _iso(r[4])} for r in rows]
next_cursor = None
if has_more and rows:
last = rows[-1]
next_cursor = f"{last[4].isoformat()}|{last[0]}"
return {"items": items, "next_cursor": next_cursor}