Implement lab3 load balancing and idempotent messaging

This commit is contained in:
ferraronp
2026-11-06 18:57:11 +03:00
parent 0ab3a341aa
commit 303c60e2e1
27 changed files with 1133 additions and 33 deletions
+1
View File
@@ -0,0 +1 @@
"""Lab 3 messenger API."""
+4
View File
@@ -0,0 +1,4 @@
import os
import uvicorn
if __name__ == "__main__":
uvicorn.run("app.main:app", host="0.0.0.0", port=int(os.getenv("APP_PORT", "8080")), workers=1, timeout_graceful_shutdown=8)
+182
View File
@@ -0,0 +1,182 @@
"""Messenger HTTP handlers; state lives only in PostgreSQL/Redis."""
import hashlib
import json
import re
import uuid
import psycopg
from argon2 import PasswordHasher
from fastapi import APIRouter, Request
from .auth import current_user, hasher, login, logout, public_user
from .core import APIError, invalid, iso, make_cursor, parse_limit, parse_uuid, read_cursor
from .models import CreateChat, CreateMessage, CreateUser
from .storage import db
router = APIRouter()
KEY_RE = re.compile(r"^[A-Za-z0-9._:-]{1,128}$", re.ASCII)
def actor(req: Request) -> dict:
return getattr(req.state, "actor", None) or current_user(req)
def chat_detail(conn, chat: dict) -> dict:
members = conn.execute("SELECT user_id FROM chat_members WHERE chat_id=%s ORDER BY position", (chat["id"],)).fetchall()
return {"id": str(chat["id"]), "title": bytes(chat["title"]).decode("utf-8"), "created_at": iso(chat["created_at"]), "member_ids": [str(x["user_id"]) for x in members]}
def message_detail(row: dict) -> dict:
return {"id": str(row["id"]), "chat_id": str(row["chat_id"]), "sender_id": str(row["sender_id"]), "text": bytes(row["text"]).decode("utf-8"), "created_at": iso(row["created_at"])}
def require_chat(conn, chat_id: str, actor_id: str) -> dict:
row = conn.execute("SELECT c.* FROM chats c JOIN chat_members cm ON cm.chat_id=c.id WHERE c.id=%s AND cm.user_id=%s", (chat_id, actor_id)).fetchone()
if row is None:
raise APIError(404, "not_found", "Object not found")
return row
@router.get("/health/live")
def live():
return {"status": "ok"}
@router.get("/health/ready")
def ready():
from .storage import ready as storage_ready
if not storage_ready():
raise APIError(503, "unavailable", "Service not ready")
return {"status": "ok"}
@router.post("/api/v1/users", status_code=201)
def register(body: CreateUser):
hashed = hasher.hash(body.password)
ident = str(uuid.uuid4())
try:
with db() as conn:
row = conn.execute("INSERT INTO users(id,username,display_name,password_hash) VALUES (%s,%s,%s,%s) RETURNING *", (ident, body.username, body.display_name.encode("utf-8"), hashed)).fetchone()
return public_user(row)
except psycopg.errors.UniqueViolation:
raise APIError(409, "conflict", "Username already exists") from None
@router.post("/api/v1/auth/sessions", status_code=201)
def sessions(req: Request):
return login(req)
@router.delete("/api/v1/auth/sessions/current", status_code=204)
def sessions_delete(req: Request):
logout(req)
return None
@router.get("/api/v1/users/me")
def users_me(req: Request):
return actor(req)
@router.post("/api/v1/chats", status_code=201)
def chats_create(req: Request, body: CreateChat):
ident = actor(req)["id"]
if ident not in body.member_ids:
raise invalid("Current user must belong to the chat")
chat_id = str(uuid.uuid4())
try:
with db() as conn:
with conn.transaction():
# Validate all members; FK constraints are the final authority for races.
found = conn.execute("SELECT id FROM users WHERE id = ANY(%s::uuid[])", (body.member_ids,)).fetchall()
if len(found) != len(body.member_ids):
raise invalid("Unknown member")
row = conn.execute("INSERT INTO chats(id,title) VALUES (%s,%s) RETURNING *", (chat_id, body.title.encode("utf-8"))).fetchone()
for pos, member in enumerate(body.member_ids):
conn.execute("INSERT INTO chat_members(chat_id,user_id,position) VALUES (%s,%s,%s)", (chat_id, member, pos))
result = chat_detail(conn, row)
return result
except psycopg.errors.ForeignKeyViolation:
raise invalid("Unknown member") from None
@router.get("/api/v1/chats")
def chats_list(req: Request, limit: str | None = None, cursor: str | None = None):
who = actor(req)["id"]
n = parse_limit(limit)
mark = read_cursor(cursor, "chats", who)
with db() as conn:
if mark:
existing = conn.execute("SELECT 1 FROM chats c JOIN chat_members cm ON c.id=cm.chat_id WHERE c.id=%s AND c.created_at=%s AND cm.user_id=%s", (mark[1], mark[0], who)).fetchone()
if not existing:
raise invalid("Invalid cursor")
rows = conn.execute("""
SELECT c.* FROM chats c JOIN chat_members cm ON cm.chat_id=c.id
WHERE cm.user_id=%s AND (%s::timestamptz IS NULL OR (c.created_at,c.id)>(%s::timestamptz,%s::uuid))
ORDER BY c.created_at,c.id LIMIT %s
""", (who, mark[0] if mark else None, mark[0] if mark else None, mark[1] if mark else None, n+1)).fetchall()
items = [chat_detail(conn, row) for row in rows[:n]]
more = len(rows) > n
last = rows[n-1] if more else None
return {"items": items, "next_cursor": make_cursor("chats", who, last["created_at"], str(last["id"])) if last else None}
@router.get("/api/v1/chats/{chat_id}")
def chats_get(req: Request, chat_id: str):
who = actor(req)["id"]
ident = parse_uuid(chat_id)
with db() as conn:
row = require_chat(conn, ident, who)
return chat_detail(conn, row)
@router.post("/api/v1/chats/{chat_id}/messages", status_code=201)
def messages_create(req: Request, chat_id: str, body: CreateMessage):
who = actor(req)["id"]
ident = parse_uuid(chat_id)
key = req.headers.get("Idempotency-Key")
if not key or not KEY_RE.fullmatch(key):
raise invalid("Invalid Idempotency-Key")
# Lab3 has only text; canonical JSON avoids unstable formatting/field ordering.
fingerprint = hashlib.sha256(json.dumps({"text": body.text}, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode("utf-8")).hexdigest()
lock_scope = f"{who}:POST:/api/v1/chats/{ident}/messages:{key}"
with db() as conn:
with conn.transaction():
require_chat(conn, ident, who)
# Transaction-scoped advisory lock is GLOBAL across API replicas.
conn.execute("SELECT pg_advisory_xact_lock(hashtextextended(%s, 0))", (lock_scope,))
previous = conn.execute("""
SELECT idem.body_sha256, m.* FROM message_idempotency idem
JOIN messages m ON m.id=idem.message_id
WHERE idem.actor_id=%s AND idem.chat_id=%s AND idem.method='POST' AND idem.idem_key=%s
""", (who, ident, key)).fetchone()
if previous:
if previous["body_sha256"] != fingerprint:
raise APIError(409, "conflict", "Idempotency key used with another body")
return message_detail(previous)
message_id = str(uuid.uuid4())
row = conn.execute("INSERT INTO messages(id,chat_id,sender_id,text) VALUES (%s,%s,%s,%s) RETURNING *", (message_id, ident, who, body.text.encode("utf-8"))).fetchone()
conn.execute("INSERT INTO message_idempotency(actor_id,chat_id,method,idem_key,body_sha256,message_id) VALUES (%s,%s,'POST',%s,%s,%s)", (who, ident, key, fingerprint, message_id))
return message_detail(row)
@router.get("/api/v1/chats/{chat_id}/messages")
def messages_list(req: Request, chat_id: str, limit: str | None = None, cursor: str | None = None):
who = actor(req)["id"]
ident = parse_uuid(chat_id)
n = parse_limit(limit)
mark = read_cursor(cursor, "messages", ident)
with db() as conn:
require_chat(conn, ident, who)
if mark:
existing = conn.execute("SELECT 1 FROM messages WHERE id=%s AND chat_id=%s AND created_at=%s", (mark[1], ident, mark[0])).fetchone()
if not existing:
raise invalid("Invalid cursor")
rows = conn.execute("""
SELECT * FROM messages WHERE chat_id=%s
AND (%s::timestamptz IS NULL OR (created_at,id)>(%s::timestamptz,%s::uuid))
ORDER BY created_at,id LIMIT %s
""", (ident, mark[0] if mark else None, mark[0] if mark else None, mark[1] if mark else None, n+1)).fetchall()
items = [message_detail(row) for row in rows[:n]]
last = rows[n-1] if len(rows)>n else None
return {"items": items, "next_cursor": make_cursor("messages", ident, last["created_at"], str(last["id"])) if last else None}
+104
View File
@@ -0,0 +1,104 @@
"""HTTP Basic only on login; bearer sessions shared by all API replicas."""
import base64
import binascii
import hashlib
import re
import secrets
import uuid
from datetime import datetime, timedelta, timezone
from argon2 import PasswordHasher
from argon2.exceptions import VerifyMismatchError, VerificationError
from fastapi import Request
from redis.exceptions import RedisError
from .core import APIError, SESSION_TTL, iso
from .storage import cache, db
hasher = PasswordHasher(time_cost=2, memory_cost=19456, parallelism=1)
PASSWORD_RE = re.compile(r"^[a-z0-9_]{3,32}$")
def public_user(row: dict):
return {"id": str(row["id"]), "username": row["username"], "display_name": bytes(row["display_name"]).decode("utf-8"), "created_at": iso(row["created_at"])}
def unauthorized() -> APIError:
return APIError(401, "unauthorized", "Unauthorized")
def challenge(req: Request) -> str:
return 'Basic realm="messenger", charset="UTF-8"' if req.url.path == "/api/v1/auth/sessions" else 'Bearer realm="messenger"'
def bearer_token(req: Request) -> str:
value = req.headers.get("Authorization", "")
if not value.startswith("Bearer ") or len(value) <= 7 or " " in value[7:] or len(value) > 512:
raise unauthorized()
try:
value[7:].encode("ascii")
except UnicodeEncodeError:
raise unauthorized() from None
return value[7:]
def session_key(token: str) -> str:
return "session:" + hashlib.sha256(token.encode("ascii")).hexdigest()
def current_user(req: Request) -> dict:
token = bearer_token(req)
try:
raw = cache().get(session_key(token))
except (RedisError, UnicodeError) as exc:
raise APIError(503, "unavailable", "Session store unavailable") from exc
if not raw:
raise unauthorized()
try:
ident = str(uuid.UUID(raw))
except (ValueError, TypeError):
try:
cache().delete(session_key(token))
except RedisError as exc:
raise APIError(503, "unavailable", "Session store unavailable") from exc
raise unauthorized() from None
with db() as conn:
row = conn.execute("SELECT * FROM users WHERE id = %s", (ident,)).fetchone()
if row is None:
raise unauthorized()
return public_user(row)
def login(req: Request):
auth = req.headers.get("Authorization", "")
if not auth.startswith("Basic "):
raise unauthorized()
try:
decoded = base64.b64decode(auth[6:].encode("ascii"), validate=True).decode("utf-8")
username, password = decoded.split(":", 1)
if not PASSWORD_RE.fullmatch(username):
raise ValueError()
except (ValueError, UnicodeError, binascii.Error):
raise unauthorized() from None
with db() as conn:
row = conn.execute("SELECT * FROM users WHERE username=%s", (username,)).fetchone()
if not row:
raise unauthorized()
try:
hasher.verify(row["password_hash"], password)
except (VerifyMismatchError, VerificationError):
raise unauthorized() from None
token = secrets.token_urlsafe(32)
try:
cache().set(session_key(token), str(row["id"]), ex=SESSION_TTL)
except RedisError as exc:
raise APIError(503, "unavailable", "Session store unavailable") from exc
return {"token": token, "token_type": "Bearer", "expires_at": iso(datetime.now(timezone.utc) + timedelta(seconds=SESSION_TTL)), "user": public_user(row)}
def logout(req: Request):
current_user(req)
try:
cache().delete(session_key(bearer_token(req)))
except RedisError as exc:
raise APIError(503, "unavailable", "Session store unavailable") from exc
+79
View File
@@ -0,0 +1,79 @@
"""Configuration, HTTP errors and shared representation helpers."""
import base64
import json
import os
import uuid
from datetime import datetime, timezone
from fastapi import Request
INSTANCE_ID = os.getenv("API_INSTANCE_ID", uuid.uuid4().hex[:12])
SESSION_TTL = int(os.getenv("SESSION_TTL_SECONDS", "3600"))
IDEMPOTENCY_TTL = max(86400, int(os.getenv("IDEMPOTENCY_TTL_SECONDS", "86400")))
class APIError(Exception):
def __init__(self, status: int, code: str, message: str):
super().__init__(message)
self.status = status
self.code = code
self.message = message
def iso(value: datetime) -> str:
return value.astimezone(timezone.utc).isoformat(timespec="microseconds").replace("+00:00", "Z")
def invalid(message: str = "Invalid request") -> APIError:
return APIError(400, "invalid_request", message)
def parse_uuid(value: str) -> str:
try:
return str(uuid.UUID(value))
except (ValueError, TypeError, AttributeError):
raise invalid("Invalid UUID") from None
def parse_limit(raw: str | None) -> int:
if raw is None:
return 50
try:
if not raw.isascii() or not raw.isdecimal():
raise ValueError()
value = int(raw)
except (ValueError, AttributeError):
raise invalid("Invalid limit") from None
if not 1 <= value <= 100:
raise invalid("Invalid limit")
return value
def make_cursor(kind: str, scope: str, created: datetime, ident: str) -> str:
b = json.dumps({"kind": kind, "scope": scope, "created_at": iso(created), "id": ident}, separators=(",", ":")).encode()
return base64.urlsafe_b64encode(b).decode().rstrip("=")
def read_cursor(raw: str | None, kind: str, scope: str):
if raw is None:
return None
try:
if not raw or len(raw) > 2048 or any(ch not in "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_" for ch in raw):
raise ValueError()
data = json.loads(base64.b64decode(raw + "=" * (-len(raw) % 4), altchars=b"-_", validate=True))
if not isinstance(data, dict) or data.get("kind") != kind or data.get("scope") != scope:
raise ValueError()
created = datetime.fromisoformat(data["created_at"].replace("Z", "+00:00"))
if created.tzinfo is None:
raise ValueError()
ident = str(uuid.UUID(data["id"]))
return created, ident
except (ValueError, TypeError, KeyError, UnicodeError, json.JSONDecodeError):
raise invalid("Invalid cursor") from None
def request_id(req: Request) -> str:
return getattr(req.state, "request_id", uuid.uuid4().hex)
def error_body(req: Request, code: str, message: str):
return {"error": {"code": code, "message": message, "request_id": request_id(req)}}
+82
View File
@@ -0,0 +1,82 @@
"""FastAPI process: one stateless replica. No auto-migration on startup."""
import logging
import uuid
from contextlib import asynccontextmanager
import psycopg
from fastapi import FastAPI, Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from starlette.concurrency import run_in_threadpool
from redis.exceptions import RedisError
from .api import router
from .auth import challenge, current_user
from .core import APIError, INSTANCE_ID, error_body, invalid, request_id
from .storage import start, stop
logging.basicConfig(level="INFO")
logger = logging.getLogger("lab3")
@asynccontextmanager
async def lifespan(app: FastAPI):
start()
try:
yield
finally:
stop()
app = FastAPI(title="MTUCI Messenger Lab 3", docs_url=None, redoc_url=None, openapi_url=None, lifespan=lifespan)
app.include_router(router)
PROTECTED = ("/api/v1/chats", "/api/v1/users/me", "/api/v1/auth/sessions/current")
JSON_POST = ("/api/v1/users", "/api/v1/chats")
@app.middleware("http")
async def request_context(req: Request, call_next):
req.state.request_id = uuid.uuid4().hex
try:
path = req.url.path
# Authenticate before parsing the request body or resource-specific fields.
if any(path == p or path.startswith(p + "/") for p in PROTECTED):
req.state.actor = await run_in_threadpool(current_user, req)
if req.method == "POST" and (path in JSON_POST or (path.startswith("/api/v1/chats/") and path.endswith("/messages"))):
if req.headers.get("content-type", "").split(";", 1)[0].strip().lower() != "application/json":
raise APIError(415, "unsupported_media_type", "Content-Type must be application/json")
if req.method == "POST" and path == "/api/v1/auth/sessions" and await req.body():
raise invalid("Login body is not allowed")
response = await call_next(req)
except APIError as exc:
response = api_error(req, exc)
except (RedisError, psycopg.OperationalError, psycopg.InterfaceError):
response = api_error(req, APIError(503, "unavailable", "Dependency unavailable"))
except Exception:
logger.exception("unexpected request failure id=%s", request_id(req))
response = api_error(req, APIError(500, "internal_error", "Internal server error"))
response.headers["X-Request-Id"] = request_id(req)
response.headers["X-Instance-Id"] = INSTANCE_ID
return response
def api_error(req: Request, exc: APIError) -> JSONResponse:
headers = {"WWW-Authenticate": challenge(req)} if exc.status == 401 else {}
return JSONResponse(status_code=exc.status, content=error_body(req, exc.code, exc.message), headers=headers)
@app.exception_handler(APIError)
async def api_error_handler(req: Request, exc: APIError):
return api_error(req, exc)
@app.exception_handler(RequestValidationError)
async def validation_error_handler(req: Request, exc: RequestValidationError):
return api_error(req, invalid())
@app.exception_handler(Exception)
async def unexpected_error_handler(req: Request, exc: Exception):
logger.exception("handler failure id=%s", request_id(req))
if isinstance(exc, (psycopg.OperationalError, psycopg.InterfaceError, RedisError)):
return api_error(req, APIError(503, "unavailable", "Dependency unavailable"))
return api_error(req, APIError(500, "internal_error", "Internal server error"))
+23
View File
@@ -0,0 +1,23 @@
"""Run once before API instances; transactional and advisory-lock coordinated migrations."""
import os
from pathlib import Path
import psycopg
MIGRATIONS = Path(__file__).resolve().parents[1] / "db" / "migrations"
def main():
with psycopg.connect(os.environ["DATABASE_URL"], autocommit=False) as conn:
with conn.transaction():
conn.execute("SELECT pg_advisory_xact_lock(62132103)")
conn.execute("CREATE TABLE IF NOT EXISTS schema_migrations(version TEXT PRIMARY KEY, applied_at TIMESTAMPTZ NOT NULL DEFAULT now())")
for path in sorted(MIGRATIONS.glob("[0-9]*.sql")):
applied = conn.execute("SELECT 1 FROM schema_migrations WHERE version=%s", (path.name,)).fetchone()
if applied:
continue
conn.execute(path.read_text(encoding="utf-8"))
conn.execute("INSERT INTO schema_migrations(version) VALUES (%s)", (path.name,))
print("Applied", path.name, flush=True)
print("Migrations up to date", flush=True)
if __name__ == "__main__":
main()
+62
View File
@@ -0,0 +1,62 @@
"""HTTP request models; all strings use Unicode code point limits."""
import re
import uuid
from pydantic import BaseModel, ConfigDict, Field, field_validator
USERNAME_RE = re.compile(r"^[a-z0-9_]{3,32}$")
class StrictModel(BaseModel):
model_config = ConfigDict(extra="forbid", strict=True)
class CreateUser(StrictModel):
username: str
display_name: str = Field(min_length=1, max_length=100)
password: str = Field(min_length=12, max_length=128)
@field_validator("username")
@classmethod
def username_valid(cls, value: str) -> str:
if not USERNAME_RE.fullmatch(value):
raise ValueError("Invalid username")
return value
@field_validator("display_name", "password")
@classmethod
def non_blank(cls, value: str) -> str:
if not value.strip():
raise ValueError("Blank value")
value.encode("utf-8", errors="strict")
return value
class CreateChat(StrictModel):
title: str = Field(min_length=1, max_length=100)
member_ids: list[str] = Field(min_length=1, max_length=100)
@field_validator("title")
@classmethod
def non_blank(cls, value: str) -> str:
if not value.strip():
raise ValueError("Blank title")
value.encode("utf-8", errors="strict")
return value
@field_validator("member_ids")
@classmethod
def uuid_members(cls, value: list[str]) -> list[str]:
for member in value:
if not isinstance(member, str) or str(uuid.UUID(member)) != member:
raise ValueError("Invalid member UUID")
if len(value) != len(set(value)):
raise ValueError("Duplicate member")
return value
class CreateMessage(StrictModel):
text: str = Field(min_length=1, max_length=4000)
@field_validator("text")
@classmethod
def non_blank(cls, value: str) -> str:
if not value.strip():
raise ValueError("Blank text")
value.encode("utf-8", errors="strict")
return value
+61
View File
@@ -0,0 +1,61 @@
"""Shared external state: psycopg connection pool and Redis session store."""
import os
from contextlib import contextmanager
import psycopg
from psycopg.rows import dict_row
from psycopg_pool import ConnectionPool, PoolTimeout
from redis import Redis
from redis.exceptions import RedisError
from .core import APIError
pool: ConnectionPool | None = None
redis_client: Redis | None = None
def start() -> None:
global pool, redis_client
url = os.environ["DATABASE_URL"]
size = int(os.getenv("DB_POOL_MAX", "8"))
pool = ConnectionPool(conninfo=url, min_size=1, max_size=size, timeout=3, kwargs={"row_factory": dict_row, "connect_timeout": 5, "options": "-c statement_timeout=5000"}, open=False)
pool.open(wait=True, timeout=30)
redis_client = Redis.from_url(os.environ.get("REDIS_URL", "redis://redis:6379/0"), socket_connect_timeout=2, socket_timeout=2, decode_responses=True)
redis_client.ping()
def stop() -> None:
global pool, redis_client
if pool is not None:
pool.close()
pool = None
if redis_client is not None:
redis_client.close()
redis_client = None
@contextmanager
def db():
if pool is None:
raise APIError(503, "unavailable", "Database unavailable")
try:
with pool.connection() as conn:
yield conn
except (psycopg.OperationalError, psycopg.InterfaceError, PoolTimeout) as exc:
raise APIError(503, "unavailable", "Database unavailable") from exc
def cache() -> Redis:
if redis_client is None:
raise APIError(503, "unavailable", "Session store unavailable")
return redis_client
def ready() -> bool:
try:
with db() as conn:
conn.execute("SELECT 1").fetchone()
cache().ping()
return True
except (APIError, RedisError, psycopg.Error):
return False