forked from mtusi2026/mtusi2026lab3
Лабораторная 3: реализован стенд с балансировщиком и идемпотентностью
This commit is contained in:
@@ -0,0 +1,2 @@
|
||||
"""MTUSI Messenger Lab 3 — FastAPI application."""
|
||||
__version__ = "1.3.0"
|
||||
@@ -0,0 +1,19 @@
|
||||
"""Application configuration loaded from environment variables."""
|
||||
|
||||
import os
|
||||
import uuid
|
||||
|
||||
INSTANCE_ID = os.getenv("INSTANCE_ID", str(uuid.uuid4()))
|
||||
|
||||
APP_HOST = os.getenv("APP_HOST", "0.0.0.0")
|
||||
APP_PORT = int(os.getenv("APP_PORT", "8080"))
|
||||
|
||||
SESSION_TTL_SECONDS = int(os.getenv("SESSION_TTL_SECONDS", "3600"))
|
||||
IDEM_TTL_SECONDS = int(os.getenv("IDEM_TTL_SECONDS", "86400"))
|
||||
|
||||
RATE_LIMIT_REQUESTS = int(os.getenv("RATE_LIMIT_REQUESTS", "0")) # 0 = disabled
|
||||
|
||||
# Security: bcrypt salt rounds; 12 is minimum for bcrypt, scrypt uses n=2**14 etc.
|
||||
SCRYPT_N = int(os.getenv("SCRYPT_N", "16384")) # 2**14
|
||||
SCRYPT_R = int(os.getenv("SCRYPT_R", "8"))
|
||||
SCRYPT_P = int(os.getenv("SCRYPT_P", "1"))
|
||||
@@ -0,0 +1,302 @@
|
||||
"""PostgreSQL-backed storage for users, chats, sessions, messages and idempotency keys.
|
||||
|
||||
All state lives in one shared PostgreSQL instance so every API replica sees the
|
||||
same truth. Sessions and idempotency records are durable, which is what makes
|
||||
the service horizontally scalable and safe to restart.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import secrets
|
||||
import uuid
|
||||
from datetime import datetime, timezone
|
||||
|
||||
import asyncpg
|
||||
|
||||
from .config import IDEM_TTL_SECONDS, SCRYPT_N, SCRYPT_P, SCRYPT_R
|
||||
from .errors import APIError
|
||||
|
||||
|
||||
def utc_now() -> datetime:
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
def iso_z(dt: datetime) -> str:
|
||||
"""RFC 3339 UTC with trailing Z, as required by the contract."""
|
||||
if dt.tzinfo is None:
|
||||
dt = dt.replace(tzinfo=timezone.utc)
|
||||
return dt.astimezone(timezone.utc).isoformat().replace("+00:00", "Z")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Password hashing (library KDF: scrypt via OpenSSL)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def hash_password(password: str) -> str:
|
||||
salt = os.urandom(16)
|
||||
derived = hashlib.scrypt(
|
||||
password.encode("utf-8"), salt=salt, n=SCRYPT_N, r=SCRYPT_R, p=SCRYPT_P, dklen=32
|
||||
)
|
||||
return "scrypt$%d$%d$%d$%s$%s" % (SCRYPT_N, SCRYPT_R, SCRYPT_P, salt.hex(), derived.hex())
|
||||
|
||||
|
||||
def verify_password(password: str, stored: str) -> bool:
|
||||
try:
|
||||
parts = stored.split("$")
|
||||
if len(parts) != 6 or parts[0] != "scrypt":
|
||||
return False
|
||||
n, r, p = int(parts[1]), int(parts[2]), int(parts[3])
|
||||
salt = bytes.fromhex(parts[4])
|
||||
expected = bytes.fromhex(parts[5])
|
||||
derived = hashlib.scrypt(
|
||||
password.encode("utf-8"), salt=salt, n=n, r=r, p=p, dklen=len(expected)
|
||||
)
|
||||
return secrets.compare_digest(derived, expected)
|
||||
except (ValueError, TypeError):
|
||||
return False
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Opaque keyset cursors
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def encode_cursor(chat_id, created_at: datetime, item_id) -> str:
|
||||
payload = json.dumps(
|
||||
{"c": str(chat_id), "t": iso_z(created_at), "i": str(item_id)}, separators=(",", ":")
|
||||
)
|
||||
return base64.urlsafe_b64encode(payload.encode()).decode().rstrip("=")
|
||||
|
||||
|
||||
def decode_cursor(cursor: str, expected_chat_id):
|
||||
try:
|
||||
raw = base64.urlsafe_b64decode(cursor + "=" * (-len(cursor) % 4))
|
||||
data = json.loads(raw)
|
||||
chat = uuid.UUID(str(data["c"]))
|
||||
when = datetime.fromisoformat(str(data["t"]).replace("Z", "+00:00"))
|
||||
item = uuid.UUID(str(data["i"]))
|
||||
except Exception:
|
||||
raise APIError(400, "invalid_request", "Invalid cursor") from None
|
||||
if expected_chat_id is not None and chat != expected_chat_id:
|
||||
raise APIError(400, "invalid_request", "Cursor belongs to a different resource")
|
||||
return when, item
|
||||
|
||||
|
||||
class Database:
|
||||
def __init__(self, dsn: str):
|
||||
self.dsn = dsn
|
||||
self._pool: asyncpg.Pool | None = None
|
||||
|
||||
async def connect(self, retries: int = 30, delay: float = 1.0) -> None:
|
||||
last_err = None
|
||||
for _ in range(retries):
|
||||
try:
|
||||
self._pool = await asyncpg.create_pool(self.dsn, min_size=1, max_size=10)
|
||||
return
|
||||
except Exception as exc: # pragma: no cover - startup retry loop
|
||||
last_err = exc
|
||||
await asyncio.sleep(delay)
|
||||
raise RuntimeError(f"Could not connect to PostgreSQL: {last_err}")
|
||||
|
||||
async def close(self) -> None:
|
||||
if self._pool is not None:
|
||||
await self._pool.close()
|
||||
self._pool = None
|
||||
|
||||
async def health(self) -> bool:
|
||||
if self._pool is None:
|
||||
return False
|
||||
try:
|
||||
async with self._pool.acquire() as conn:
|
||||
await conn.execute("SELECT 1")
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
# -- users ----------------------------------------------------------------
|
||||
|
||||
async def create_user(self, user_id, username: str, display_name: str, password_hash: str, created_at):
|
||||
async with self._pool.acquire() as conn:
|
||||
try:
|
||||
return await conn.fetchrow(
|
||||
"INSERT INTO users (id, username, display_name, password_hash, created_at) "
|
||||
"VALUES ($1, $2, $3, $4, $5) RETURNING id, username, display_name, created_at",
|
||||
user_id, username, display_name, password_hash, created_at,
|
||||
)
|
||||
except asyncpg.UniqueViolationError:
|
||||
raise APIError(409, "conflict", "Username already taken") from None
|
||||
|
||||
async def get_user_by_username(self, username: str):
|
||||
async with self._pool.acquire() as conn:
|
||||
return await conn.fetchrow("SELECT * FROM users WHERE username = $1", username)
|
||||
|
||||
async def get_user_by_id(self, user_id):
|
||||
async with self._pool.acquire() as conn:
|
||||
return await conn.fetchrow("SELECT * FROM users WHERE id = $1", user_id)
|
||||
|
||||
# -- sessions -------------------------------------------------------------
|
||||
|
||||
async def create_session(self, token: str, user_id, expires_at) -> None:
|
||||
async with self._pool.acquire() as conn:
|
||||
await conn.execute(
|
||||
"INSERT INTO sessions (token, user_id, expires_at) VALUES ($1, $2, $3)",
|
||||
token, user_id, expires_at,
|
||||
)
|
||||
|
||||
async def get_session_user(self, token: str):
|
||||
async with self._pool.acquire() as conn:
|
||||
return await conn.fetchrow(
|
||||
"SELECT u.id, u.username, u.display_name, u.created_at "
|
||||
"FROM sessions s JOIN users u ON u.id = s.user_id "
|
||||
"WHERE s.token = $1 AND s.expires_at > now()",
|
||||
token,
|
||||
)
|
||||
|
||||
async def revoke_session(self, token: str) -> None:
|
||||
async with self._pool.acquire() as conn:
|
||||
await conn.execute("DELETE FROM sessions WHERE token = $1", token)
|
||||
|
||||
|
||||
# -- chats ----------------------------------------------------------------
|
||||
|
||||
async def create_chat(self, chat_id, title: str, member_ids, created_at):
|
||||
async with self._pool.acquire() as conn:
|
||||
async with conn.transaction():
|
||||
await conn.execute(
|
||||
"INSERT INTO chats (id, title, created_at) VALUES ($1, $2, $3)",
|
||||
chat_id, title, created_at,
|
||||
)
|
||||
for uid in member_ids:
|
||||
await conn.execute(
|
||||
"INSERT INTO chat_members (chat_id, user_id) VALUES ($1, $2)",
|
||||
chat_id, uid,
|
||||
)
|
||||
return await conn.fetchrow("SELECT * FROM chats WHERE id = $1", chat_id)
|
||||
|
||||
async def get_chat(self, chat_id):
|
||||
async with self._pool.acquire() as conn:
|
||||
return await conn.fetchrow("SELECT * FROM chats WHERE id = $1", chat_id)
|
||||
|
||||
async def get_chat_members(self, chat_id):
|
||||
async with self._pool.acquire() as conn:
|
||||
rows = await conn.fetch(
|
||||
"SELECT user_id FROM chat_members WHERE chat_id = $1 ORDER BY user_id", chat_id
|
||||
)
|
||||
return [row["user_id"] for row in rows]
|
||||
|
||||
async def users_exist(self, user_ids) -> bool:
|
||||
if not user_ids:
|
||||
return True
|
||||
async with self._pool.acquire() as conn:
|
||||
row = await conn.fetchrow(
|
||||
"SELECT COUNT(DISTINCT id) AS n FROM users WHERE id = ANY($1)", list(user_ids)
|
||||
)
|
||||
return row["n"] == len(set(user_ids))
|
||||
|
||||
async def list_chats(self, user_id, limit: int, cursor: str | None):
|
||||
after_t, after_id = None, None
|
||||
if cursor is not None:
|
||||
after_t, after_id = decode_cursor(cursor, None)
|
||||
async with self._pool.acquire() as conn:
|
||||
rows = await conn.fetch(
|
||||
"""
|
||||
SELECT c.id, c.title, c.created_at,
|
||||
ARRAY(SELECT cm2.user_id FROM chat_members cm2
|
||||
WHERE cm2.chat_id = c.id ORDER BY cm2.user_id) AS member_ids
|
||||
FROM chats c
|
||||
JOIN chat_members cm ON cm.chat_id = c.id AND cm.user_id = $1
|
||||
WHERE $2::timestamptz IS NULL OR (c.created_at, c.id) > ($2, $3)
|
||||
ORDER BY c.created_at ASC, c.id ASC
|
||||
LIMIT $4
|
||||
""",
|
||||
user_id, after_t, after_id, limit + 1,
|
||||
)
|
||||
has_more = len(rows) > limit
|
||||
items = rows[:limit]
|
||||
next_cursor = None
|
||||
if has_more and items:
|
||||
last = items[-1]
|
||||
next_cursor = encode_cursor(last["id"], last["created_at"], last["id"])
|
||||
return items, next_cursor
|
||||
|
||||
|
||||
# -- messages -------------------------------------------------------------
|
||||
|
||||
async def list_messages(self, chat_id, limit: int, cursor: str | None):
|
||||
after_t, after_id = None, None
|
||||
if cursor is not None:
|
||||
after_t, after_id = decode_cursor(cursor, chat_id)
|
||||
async with self._pool.acquire() as conn:
|
||||
rows = await conn.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, $3))
|
||||
ORDER BY created_at ASC, id ASC
|
||||
LIMIT $4
|
||||
""",
|
||||
chat_id, after_t, after_id, limit + 1,
|
||||
)
|
||||
has_more = len(rows) > limit
|
||||
items = rows[:limit]
|
||||
next_cursor = None
|
||||
if has_more and items:
|
||||
last = items[-1]
|
||||
next_cursor = encode_cursor(chat_id, last["created_at"], last["id"])
|
||||
return items, next_cursor
|
||||
|
||||
async def create_message(self, user_id, chat_id, text: str, idem_key: str, body_hash: str):
|
||||
msg_id = uuid.uuid4()
|
||||
created_at = utc_now()
|
||||
response = {
|
||||
"id": str(msg_id),
|
||||
"chat_id": str(chat_id),
|
||||
"sender_id": str(user_id),
|
||||
"text": text,
|
||||
"created_at": iso_z(created_at),
|
||||
}
|
||||
path = f"/api/v1/chats/{chat_id}/messages"
|
||||
async with self._pool.acquire() as conn:
|
||||
async with conn.transaction():
|
||||
inserted = await conn.fetchval(
|
||||
"""
|
||||
INSERT INTO idempotency_keys
|
||||
(user_id, method, path, idem_key, request_hash, response_json, status_code)
|
||||
VALUES ($1, 'POST', $2, $3, $4, $5, 201)
|
||||
ON CONFLICT (user_id, method, path, idem_key) DO NOTHING
|
||||
RETURNING 1
|
||||
""",
|
||||
user_id, path, idem_key, body_hash, json.dumps(response),
|
||||
)
|
||||
if inserted:
|
||||
await conn.execute(
|
||||
"INSERT INTO messages (id, chat_id, sender_id, text, created_at) "
|
||||
"VALUES ($1, $2, $3, $4, $5)",
|
||||
msg_id, chat_id, user_id, text, created_at,
|
||||
)
|
||||
return response, 201
|
||||
row = await conn.fetchrow(
|
||||
"SELECT request_hash, response_json, status_code FROM idempotency_keys "
|
||||
"WHERE user_id = $1 AND method = 'POST' AND path = $2 AND idem_key = $3",
|
||||
user_id, path, idem_key,
|
||||
)
|
||||
if row is None:
|
||||
raise APIError(500, "internal_error", "Internal error")
|
||||
if row["request_hash"] != body_hash:
|
||||
raise APIError(409, "conflict", "Idempotency key reused with a different body")
|
||||
return json.loads(row["response_json"]), row["status_code"]
|
||||
|
||||
# -- idempotency maintenance --------------------------------------------
|
||||
|
||||
async def cleanup_idempotency(self, ttl_seconds: int) -> None:
|
||||
if self._pool is None:
|
||||
return
|
||||
async with self._pool.acquire() as conn:
|
||||
await conn.execute(
|
||||
"DELETE FROM idempotency_keys WHERE created_at < now() - make_interval(secs => $1)",
|
||||
ttl_seconds,
|
||||
)
|
||||
@@ -0,0 +1,29 @@
|
||||
"""Error model shared by the messenger API layers."""
|
||||
|
||||
|
||||
class APIError(Exception):
|
||||
"""Structured application error; rendered as ``{"error": {...}}``."""
|
||||
|
||||
def __init__(self, status_code: int, code: str, message: str, headers: dict | None = None):
|
||||
self.status_code = status_code
|
||||
self.code = code
|
||||
self.message = message
|
||||
self.headers = dict(headers or {})
|
||||
super().__init__(message)
|
||||
|
||||
|
||||
_ERROR_STATUS: dict[str, int] = {
|
||||
"invalid_request": 400,
|
||||
"unauthorized": 401,
|
||||
"not_found": 404,
|
||||
"conflict": 409,
|
||||
"payload_too_large": 413,
|
||||
"unsupported_media_type": 415,
|
||||
"rate_limited": 429,
|
||||
"unavailable": 503,
|
||||
"internal_error": 500,
|
||||
}
|
||||
|
||||
|
||||
def status_for_code(code: str) -> int:
|
||||
return _ERROR_STATUS.get(code, 500)
|
||||
+411
@@ -0,0 +1,411 @@
|
||||
"""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")
|
||||
@@ -0,0 +1,67 @@
|
||||
"""One-shot migration runner: applies app/migrations/*.sql exactly once.
|
||||
|
||||
Run as a dedicated compose service (or `python -m app.migrate`) before the API
|
||||
replicas start, so schema changes are never raced between replicas.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
import pathlib
|
||||
import sys
|
||||
|
||||
import asyncpg
|
||||
|
||||
MIGRATIONS_DIR = pathlib.Path(__file__).resolve().parent / "migrations"
|
||||
ADVISORY_LOCK_KEY = 424242
|
||||
|
||||
|
||||
async def run() -> int:
|
||||
dsn = os.environ.get("DATABASE_URL")
|
||||
if not dsn:
|
||||
print("DATABASE_URL environment variable is required", file=sys.stderr)
|
||||
return 2
|
||||
|
||||
conn = await asyncpg.connect(dsn)
|
||||
try:
|
||||
await conn.execute(
|
||||
"CREATE TABLE IF NOT EXISTS schema_migrations ("
|
||||
"version TEXT PRIMARY KEY, applied_at TIMESTAMPTZ NOT NULL DEFAULT now())"
|
||||
)
|
||||
await conn.execute("SELECT pg_advisory_lock($1)", ADVISORY_LOCK_KEY)
|
||||
try:
|
||||
applied = 0
|
||||
for path in sorted(MIGRATIONS_DIR.glob("*.sql")):
|
||||
version = path.stem
|
||||
already = await conn.fetchval(
|
||||
"SELECT 1 FROM schema_migrations WHERE version = $1", version
|
||||
)
|
||||
if already:
|
||||
print(f"migration {version}: already applied")
|
||||
continue
|
||||
sql = path.read_text(encoding="utf-8")
|
||||
# Strip `--` line comments before splitting on ';' so a semicolon
|
||||
# inside a comment cannot produce a bogus statement fragment.
|
||||
cleaned_lines = []
|
||||
for line in sql.splitlines():
|
||||
idx = line.find("--")
|
||||
cleaned_lines.append(line if idx < 0 else line[:idx])
|
||||
cleaned = "\n".join(cleaned_lines)
|
||||
statements = [chunk.strip() for chunk in cleaned.split(";") if chunk.strip()]
|
||||
async with conn.transaction():
|
||||
for statement in statements:
|
||||
await conn.execute(statement)
|
||||
await conn.execute(
|
||||
"INSERT INTO schema_migrations (version) VALUES ($1)", version
|
||||
)
|
||||
print(f"migration {version}: applied ({len(statements)} statement(s))")
|
||||
applied += 1
|
||||
print(f"migrations complete: {applied} newly applied")
|
||||
return 0
|
||||
finally:
|
||||
await conn.execute("SELECT pg_advisory_unlock($1)", ADVISORY_LOCK_KEY)
|
||||
finally:
|
||||
await conn.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(asyncio.run(run()))
|
||||
@@ -0,0 +1,58 @@
|
||||
-- 001_init.sql — initial schema for MTUSI Messenger Lab 3
|
||||
-- All tables use UUID primary keys; all timestamps are TIMESTAMPTZ (UTC).
|
||||
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id UUID PRIMARY KEY,
|
||||
username TEXT NOT NULL UNIQUE,
|
||||
display_name TEXT NOT NULL,
|
||||
password_hash TEXT NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS sessions (
|
||||
token TEXT PRIMARY KEY,
|
||||
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
expires_at TIMESTAMPTZ NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS chats (
|
||||
id UUID PRIMARY KEY,
|
||||
title TEXT NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
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 DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_messages_chat_created ON messages (chat_id, created_at, id);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS idempotency_keys (
|
||||
user_id UUID NOT NULL,
|
||||
method TEXT NOT NULL,
|
||||
path TEXT NOT NULL,
|
||||
idem_key TEXT NOT NULL,
|
||||
request_hash TEXT NOT NULL,
|
||||
response_json TEXT NOT NULL,
|
||||
status_code INTEGER NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (user_id, method, path, idem_key)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_idempotency_created_at ON idempotency_keys (created_at);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||
version TEXT PRIMARY KEY,
|
||||
applied_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
Reference in New Issue
Block a user