Files
mtusi2026lab3/app/main.py

412 lines
14 KiB
Python

"""MTUSI Messenger Lab 3 — FastAPI application.
Shared PostgreSQL is the single source of truth (users, chats, sessions,
messages, idempotency keys). Every replica exposes the same API behind a
load balancer; every response carries X-Request-Id and X-Instance-Id.
"""
import base64
import hashlib
import json
import os
import re
import secrets
import uuid
from contextlib import asynccontextmanager
from datetime import datetime, timedelta, timezone
from fastapi import Depends, FastAPI, Request, status
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse, Response
from pydantic import BaseModel, ConfigDict, Field, field_validator
from .config import IDEM_TTL_SECONDS, INSTANCE_ID, SESSION_TTL_SECONDS
from .db import Database, hash_password, verify_password
from .errors import APIError
db: Database | None = None
def _get_db() -> Database:
if db is None:
raise RuntimeError("Database not initialised")
return db
# ---------------------------------------------------------------------------
# Middleware — X-Request-Id and X-Instance-Id on every response
# ---------------------------------------------------------------------------
from starlette.middleware.base import BaseHTTPMiddleware # noqa: E402
class InstanceHeaderMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request: Request, call_next):
request_id = request.headers.get("x-request-id") or str(uuid.uuid4())
request.state.request_id = request_id
response = await call_next(request)
response.headers["X-Request-Id"] = request_id
response.headers["X-Instance-Id"] = INSTANCE_ID
return response
# ---------------------------------------------------------------------------
# Application lifecycle
# ---------------------------------------------------------------------------
@asynccontextmanager
async def lifespan(_app: FastAPI):
global db
dsn = os.getenv("DATABASE_URL")
if not dsn:
raise RuntimeError("DATABASE_URL environment variable is required")
database = Database(dsn)
await database.connect()
await database.cleanup_idempotency(IDEM_TTL_SECONDS)
db = database
yield
await database.close()
app = FastAPI(title="MTUSI Messenger Lab 3", version="1.3.0", lifespan=lifespan)
app.add_middleware(InstanceHeaderMiddleware)
# ---------------------------------------------------------------------------
# Error rendering — uniform {"error": {...}} body
# ---------------------------------------------------------------------------
@app.exception_handler(APIError)
async def api_error_handler(request: Request, exc: APIError):
body = {
"error": {
"code": exc.code,
"message": exc.message,
"request_id": getattr(request.state, "request_id", ""),
}
}
return JSONResponse(status_code=exc.status_code, content=body, headers=exc.headers)
@app.exception_handler(RequestValidationError)
async def validation_handler(request: Request, exc: RequestValidationError):
body = {
"error": {
"code": "invalid_request",
"message": "Invalid request",
"request_id": getattr(request.state, "request_id", ""),
}
}
return JSONResponse(status_code=400, content=body)
@app.exception_handler(Exception)
async def unhandled_handler(request: Request, exc: Exception):
body = {
"error": {
"code": "internal_error",
"message": "Unexpected error",
"request_id": getattr(request.state, "request_id", ""),
}
}
return JSONResponse(status_code=500, content=body)
# ---------------------------------------------------------------------------
# Authentication helpers
# ---------------------------------------------------------------------------
async def current_user(request: Request):
auth = request.headers.get("Authorization", "")
if not auth.startswith("Bearer "):
raise APIError(
401, "unauthorized", "Authentication required",
headers={"WWW-Authenticate": 'Bearer realm="messenger"'},
)
token = auth[7:].strip()
if not token:
raise APIError(
401, "unauthorized", "Authentication required",
headers={"WWW-Authenticate": 'Bearer realm="messenger"'},
)
user = await _get_db().get_session_user(token)
if not user:
raise APIError(
401, "unauthorized", "Invalid session",
headers={"WWW-Authenticate": 'Bearer realm="messenger"'},
)
return user
def _iso(dt) -> str:
if isinstance(dt, str):
return dt
if dt.tzinfo is None:
dt = dt.replace(tzinfo=timezone.utc)
return dt.astimezone(timezone.utc).isoformat().replace("+00:00", "Z")
def _user_out(user) -> dict:
return {
"id": str(user["id"]),
"username": user["username"],
"display_name": user["display_name"],
"created_at": _iso(user["created_at"]),
}
def _chat_out(chat) -> dict:
return {
"id": str(chat["id"]),
"title": chat["title"],
"member_ids": [str(m) for m in (chat["member_ids"] or [])],
"created_at": _iso(chat["created_at"]),
}
def _message_out(msg) -> dict:
return {
"id": str(msg["id"]),
"chat_id": str(msg["chat_id"]),
"sender_id": str(msg["sender_id"]),
"text": msg["text"],
"created_at": _iso(msg["created_at"]),
}
# ---------------------------------------------------------------------------
# Request/response models
# ---------------------------------------------------------------------------
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)
password: str = Field(min_length=12, max_length=128)
@field_validator("display_name")
@classmethod
def _display_not_blank(cls, v: str) -> str:
if not v.strip():
raise ValueError("display_name must not be blank")
return v
@field_validator("password")
@classmethod
def _password_not_blank(cls, v: str) -> str:
if not v.strip():
raise ValueError("password must not be blank")
return v
class CreateChat(BaseModel):
model_config = ConfigDict(extra="forbid")
title: str = Field(min_length=1, max_length=100)
member_ids: list[uuid.UUID] = Field(min_length=1, max_length=100)
@field_validator("title")
@classmethod
def _title_not_blank(cls, v: str) -> str:
if not v.strip():
raise ValueError("title must not be blank")
return v
class CreateMessage(BaseModel):
model_config = ConfigDict(extra="forbid")
text: str = Field(min_length=1, max_length=4000)
@field_validator("text")
@classmethod
def _text_not_blank(cls, v: str) -> str:
if not v.strip():
raise ValueError("message text must not be blank")
return v
# ---------------------------------------------------------------------------
# Auth routes
# ---------------------------------------------------------------------------
@app.post("/api/v1/auth/sessions", status_code=201)
async def create_session(request: Request):
auth = request.headers.get("Authorization", "")
if not auth.startswith("Basic "):
raise APIError(
401, "unauthorized", "Use Basic authentication",
headers={"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'},
)
try:
credentials = base64.b64decode(auth[6:]).decode("utf-8")
except Exception:
raise APIError(
401, "unauthorized", "Invalid base64 credentials",
headers={"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'},
)
parts = credentials.split(":", 1)
if len(parts) != 2:
raise APIError(
401, "unauthorized", "Invalid credentials format",
headers={"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'},
)
username, password = parts
user = await _get_db().get_user_by_username(username)
if not user or not verify_password(password, user["password_hash"]):
raise APIError(
401, "unauthorized", "Invalid credentials",
headers={"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'},
)
token = secrets.token_urlsafe(32)
expires_at = datetime.now(timezone.utc) + timedelta(seconds=SESSION_TTL_SECONDS)
await _get_db().create_session(token, user["id"], expires_at)
return {
"token": token,
"token_type": "Bearer",
"expires_at": _iso(expires_at),
"user": _user_out(user),
}
@app.delete("/api/v1/auth/sessions/current", status_code=204)
async def revoke_current_session(request: Request, user=Depends(current_user)):
auth = request.headers.get("Authorization", "")
token = auth[7:].strip()
await _get_db().revoke_session(token)
return Response(status_code=204)
# ---------------------------------------------------------------------------
# User routes
# ---------------------------------------------------------------------------
@app.post("/api/v1/users", status_code=201)
async def register_user(body: CreateUser):
user_id = uuid.uuid4()
created_at = datetime.now(timezone.utc)
pw_hash = hash_password(body.password)
user = await _get_db().create_user(user_id, body.username, body.display_name, pw_hash, created_at)
return _user_out(user)
@app.get("/api/v1/users/me")
async def current_user_endpoint(user=Depends(current_user)):
return _user_out(user)
# ---------------------------------------------------------------------------
# Chat routes
# ---------------------------------------------------------------------------
@app.post("/api/v1/chats", status_code=201)
async def create_chat(body: CreateChat, user=Depends(current_user)):
member_ids = list(body.member_ids)
if user["id"] not in member_ids:
raise APIError(400, "invalid_request", "Caller must be one of member_ids")
if len(set(member_ids)) != len(member_ids):
raise APIError(400, "invalid_request", "Duplicate member in list")
if not await _get_db().users_exist(member_ids):
raise APIError(400, "invalid_request", "One or more members do not exist")
chat_id = uuid.uuid4()
created_at = datetime.now(timezone.utc)
chat = await _get_db().create_chat(chat_id, body.title, member_ids, created_at)
members = await _get_db().get_chat_members(chat_id)
return {
"id": str(chat["id"]),
"title": chat["title"],
"member_ids": [str(m) for m in members],
"created_at": _iso(chat["created_at"]),
}
@app.get("/api/v1/chats")
async def list_chats(limit: int = 50, cursor: str | None = None, user=Depends(current_user)):
if limit < 1 or limit > 100:
raise APIError(400, "invalid_request", "Invalid limit")
items, next_cursor = await _get_db().list_chats(user["id"], limit, cursor)
return {"items": [_chat_out(c) for c in items], "next_cursor": next_cursor}
@app.get("/api/v1/chats/{chat_id}")
async def get_chat(chat_id: str, user=Depends(current_user)):
try:
cid = uuid.UUID(chat_id)
except ValueError:
raise APIError(400, "invalid_request", "Invalid chat id")
chat = await _get_db().get_chat(cid)
if not chat:
raise APIError(404, "not_found", "Chat not found")
members = await _get_db().get_chat_members(cid)
if user["id"] not in members:
raise APIError(404, "not_found", "Chat not found")
return _chat_out(chat)
# ---------------------------------------------------------------------------
# Message routes
# ---------------------------------------------------------------------------
@app.post("/api/v1/chats/{chat_id}/messages", status_code=201)
async def create_message(chat_id: str, body: CreateMessage, request: Request, user=Depends(current_user)):
idem_key = request.headers.get("Idempotency-Key")
if not idem_key or not re.fullmatch(r"[A-Za-z0-9._:-]{1,128}", idem_key):
raise APIError(
400, "invalid_request", "Idempotency-Key header required",
)
try:
cid = uuid.UUID(chat_id)
except ValueError:
raise APIError(400, "invalid_request", "Invalid chat id")
chat = await _get_db().get_chat(cid)
if not chat:
raise APIError(404, "not_found", "Chat not found")
members = await _get_db().get_chat_members(cid)
if user["id"] not in members:
raise APIError(404, "not_found", "Chat not found")
text = body.text
if not text or not text.strip():
raise APIError(400, "invalid_request", "Message text must not be empty")
body_hash = hashlib.sha256(
json.dumps({"text": text}, sort_keys=True, ensure_ascii=False).encode("utf-8")
).hexdigest()
response, status_code = await _get_db().create_message(
user["id"], cid, text, idem_key, body_hash,
)
return JSONResponse(status_code=status_code, content=response)
@app.get("/api/v1/chats/{chat_id}/messages")
async def list_messages(chat_id: str, limit: int = 50, cursor: str | None = None, user=Depends(current_user)):
try:
cid = uuid.UUID(chat_id)
except ValueError:
raise APIError(400, "invalid_request", "Invalid chat id")
chat = await _get_db().get_chat(cid)
if not chat:
raise APIError(404, "not_found", "Chat not found")
members = await _get_db().get_chat_members(cid)
if user["id"] not in members:
raise APIError(404, "not_found", "Chat not found")
if limit < 1 or limit > 100:
raise APIError(400, "invalid_request", "Invalid limit")
items, next_cursor = await _get_db().list_messages(cid, limit, cursor)
return {"items": [_message_out(m) for m in items], "next_cursor": next_cursor}
# ---------------------------------------------------------------------------
# Health routes
# ---------------------------------------------------------------------------
@app.get("/health/live")
async def live():
return {"status": "ok"}
@app.get("/health/ready")
async def ready():
ok = await _get_db().health()
if ok:
return {"status": "ok"}
raise APIError(503, "unavailable", "Service not ready")