forked from mtusi2026/mtusi2026lab3
Реализовать стенд лабораторной 3: две API-реплики и балансировка
FastAPI + PostgreSQL как единый источник истины: пользователи, Basic/Bearer-сессии, чаты, сообщения. Сессии и идемпотентные ключи хранятся в БД, поэтому реплики взаимозаменяемы. Общая идемпотентность POST сообщения по Idempotency-Key, включая конкурентный повтор через разные реплики. compose.yaml: postgres, one-shot migrate, api1, api2 и nginx как единственная публичная точка входа. Добавлены scripts/stop-one.sh и scripts/restart.sh, student-tests, evidence и заполненный REPORT.md.
This commit is contained in:
@@ -0,0 +1,19 @@
|
||||
"""Domain errors mapped to the contract error envelope."""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Mapping
|
||||
|
||||
|
||||
class ApiError(Exception):
|
||||
def __init__(
|
||||
self,
|
||||
status_code: int,
|
||||
code: str,
|
||||
message: str,
|
||||
headers: Mapping[str, str] | None = None,
|
||||
) -> None:
|
||||
super().__init__(message)
|
||||
self.status_code = status_code
|
||||
self.code = code
|
||||
self.message = message
|
||||
self.headers = dict(headers or {})
|
||||
+599
@@ -0,0 +1,599 @@
|
||||
"""HTTP API for laboratory 3: shared state, two interchangeable replicas."""
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
import uuid
|
||||
from contextlib import asynccontextmanager
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
|
||||
from fastapi import FastAPI, Request, Response
|
||||
from fastapi.responses import JSONResponse
|
||||
from psycopg import errors as pg_errors
|
||||
from psycopg.rows import dict_row
|
||||
from psycopg.types.json import Jsonb
|
||||
from psycopg_pool import AsyncConnectionPool
|
||||
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||
|
||||
from .errors import ApiError
|
||||
from .security import hash_password, new_session_token, token_digest, verify_password
|
||||
from .settings import load_settings
|
||||
from .validation import (
|
||||
invalid,
|
||||
parse_limit,
|
||||
parse_uuid,
|
||||
reject_unknown_fields,
|
||||
require_string,
|
||||
validate_display_name,
|
||||
validate_idempotency_key,
|
||||
validate_member_ids,
|
||||
validate_message_text,
|
||||
validate_password,
|
||||
validate_title,
|
||||
validate_username,
|
||||
)
|
||||
|
||||
logger = logging.getLogger("messenger.api")
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s %(message)s")
|
||||
|
||||
settings = load_settings()
|
||||
|
||||
BASIC_CHALLENGE = {"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'}
|
||||
BEARER_CHALLENGE = {"WWW-Authenticate": 'Bearer realm="messenger"'}
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
pool = AsyncConnectionPool(
|
||||
settings.database_url,
|
||||
min_size=1,
|
||||
max_size=10,
|
||||
timeout=5,
|
||||
open=False,
|
||||
kwargs={"application_name": settings.instance_id},
|
||||
)
|
||||
await pool.open(wait=False)
|
||||
app.state.pool = pool
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
await pool.close()
|
||||
|
||||
|
||||
app = FastAPI(title="MTUSI Messenger lab3", lifespan=lifespan, docs_url=None, redoc_url=None)
|
||||
|
||||
|
||||
def error_response(
|
||||
request: Request,
|
||||
status_code: int,
|
||||
code: str,
|
||||
message: str,
|
||||
headers: dict[str, str] | None = None,
|
||||
) -> JSONResponse:
|
||||
request_id = getattr(request.state, "request_id", None) or str(uuid.uuid4())
|
||||
response = JSONResponse(
|
||||
status_code=status_code,
|
||||
content={"error": {"code": code, "message": message, "request_id": request_id}},
|
||||
)
|
||||
for name, value in (headers or {}).items():
|
||||
response.headers[name] = value
|
||||
return response
|
||||
|
||||
|
||||
@app.middleware("http")
|
||||
async def add_instance_and_request_headers(request: Request, call_next):
|
||||
request_id = str(uuid.uuid4())
|
||||
request.state.request_id = request_id
|
||||
try:
|
||||
response = await call_next(request)
|
||||
except ApiError as exc: # defensive: handlers normally convert this first
|
||||
response = error_response(request, exc.status_code, exc.code, exc.message, exc.headers)
|
||||
except Exception:
|
||||
logger.exception("unhandled error while serving request")
|
||||
response = error_response(request, 500, "internal_error", "Internal server error")
|
||||
response.headers["X-Request-Id"] = request_id
|
||||
response.headers["X-Instance-Id"] = settings.instance_id
|
||||
return response
|
||||
|
||||
|
||||
@app.exception_handler(ApiError)
|
||||
async def api_error_handler(request: Request, exc: ApiError) -> JSONResponse:
|
||||
return error_response(request, exc.status_code, exc.code, exc.message, exc.headers)
|
||||
|
||||
|
||||
@app.exception_handler(StarletteHTTPException)
|
||||
async def http_error_handler(request: Request, exc: StarletteHTTPException) -> JSONResponse:
|
||||
code = "not_found" if exc.status_code == 404 else "invalid_request"
|
||||
return error_response(request, exc.status_code, code, "Request could not be processed")
|
||||
|
||||
|
||||
@app.exception_handler(Exception)
|
||||
async def unhandled_error_handler(request: Request, exc: Exception) -> JSONResponse:
|
||||
logger.exception("unhandled error: %s", type(exc).__name__)
|
||||
return error_response(request, 500, "internal_error", "Internal server error")
|
||||
|
||||
|
||||
def iso_utc(value: datetime) -> str:
|
||||
if value.tzinfo is None:
|
||||
value = value.replace(tzinfo=timezone.utc)
|
||||
return value.astimezone(timezone.utc).isoformat().replace("+00:00", "Z")
|
||||
|
||||
|
||||
def user_json(row: dict[str, Any]) -> dict[str, Any]:
|
||||
return {
|
||||
"id": str(row["id"]),
|
||||
"username": row["username"],
|
||||
"display_name": row["display_name"],
|
||||
"created_at": iso_utc(row["created_at"]),
|
||||
}
|
||||
|
||||
|
||||
def message_json(row: dict[str, Any]) -> dict[str, Any]:
|
||||
return {
|
||||
"id": str(row["id"]),
|
||||
"chat_id": str(row["chat_id"]),
|
||||
"sender_id": str(row["sender_id"]),
|
||||
"text": row["text"],
|
||||
"created_at": iso_utc(row["created_at"]),
|
||||
}
|
||||
|
||||
|
||||
def chat_json(row: dict[str, Any], member_ids: list[str]) -> dict[str, Any]:
|
||||
return {
|
||||
"id": str(row["id"]),
|
||||
"title": row["title"],
|
||||
"member_ids": member_ids,
|
||||
"created_at": iso_utc(row["created_at"]),
|
||||
}
|
||||
|
||||
|
||||
async def read_json_object(request: Request) -> dict[str, Any]:
|
||||
raw = await request.body()
|
||||
try:
|
||||
value = json.loads(raw)
|
||||
except (ValueError, UnicodeDecodeError) as exc:
|
||||
raise invalid("Request body must be valid JSON") from exc
|
||||
if not isinstance(value, dict):
|
||||
raise invalid("Request body must be a JSON object")
|
||||
return value
|
||||
|
||||
|
||||
async def authenticate(request: Request) -> dict[str, Any]:
|
||||
header = request.headers.get("authorization", "")
|
||||
scheme, _, token = header.partition(" ")
|
||||
token = token.strip()
|
||||
if scheme.lower() != "bearer" or not token:
|
||||
raise ApiError(401, "unauthorized", "Bearer token required", BEARER_CHALLENGE)
|
||||
|
||||
digest = token_digest(token)
|
||||
async with request.app.state.pool.connection() as conn:
|
||||
async with conn.cursor(row_factory=dict_row) as cur:
|
||||
await cur.execute(
|
||||
"""
|
||||
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_hash = %s AND s.expires_at > now()
|
||||
""",
|
||||
(digest,),
|
||||
)
|
||||
row = await cur.fetchone()
|
||||
if row is None:
|
||||
raise ApiError(401, "unauthorized", "Session is not valid", BEARER_CHALLENGE)
|
||||
request.state.token_hash = digest
|
||||
return row
|
||||
|
||||
|
||||
async def require_member(pool: AsyncConnectionPool, chat_id: uuid.UUID, user_id: uuid.UUID) -> None:
|
||||
async with pool.connection() as conn:
|
||||
async with conn.cursor() as cur:
|
||||
await cur.execute(
|
||||
"SELECT 1 FROM chat_members WHERE chat_id = %s AND user_id = %s",
|
||||
(chat_id, user_id),
|
||||
)
|
||||
if await cur.fetchone() is None:
|
||||
raise ApiError(404, "not_found", "Chat not found")
|
||||
|
||||
|
||||
async def chat_members(pool: AsyncConnectionPool, chat_ids: list[uuid.UUID]) -> dict[uuid.UUID, list[str]]:
|
||||
result: dict[uuid.UUID, list[str]] = {chat_id: [] for chat_id in chat_ids}
|
||||
if not chat_ids:
|
||||
return result
|
||||
async with pool.connection() as conn:
|
||||
async with conn.cursor() as cur:
|
||||
await cur.execute(
|
||||
"""
|
||||
SELECT chat_id, user_id
|
||||
FROM chat_members
|
||||
WHERE chat_id = ANY(%s::uuid[])
|
||||
ORDER BY chat_id, user_id
|
||||
""",
|
||||
(chat_ids,),
|
||||
)
|
||||
for chat_id, user_id in await cur.fetchall():
|
||||
result[chat_id].append(str(user_id))
|
||||
return result
|
||||
|
||||
|
||||
def encode_cursor(scope: str, created_at: datetime, item_id: uuid.UUID) -> str:
|
||||
payload = {"v": 1, "s": scope, "t": iso_utc(created_at), "i": str(item_id)}
|
||||
raw = json.dumps(payload, separators=(",", ":"), ensure_ascii=False).encode("utf-8")
|
||||
return base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=")
|
||||
|
||||
|
||||
def decode_cursor(raw: str) -> tuple[str, datetime, uuid.UUID]:
|
||||
try:
|
||||
padded = raw + "=" * (-len(raw) % 4)
|
||||
payload = json.loads(base64.urlsafe_b64decode(padded.encode("ascii")))
|
||||
if not isinstance(payload, dict) or payload.get("v") != 1:
|
||||
raise ValueError
|
||||
scope = payload["s"]
|
||||
created_at = datetime.fromisoformat(str(payload["t"]).replace("Z", "+00:00"))
|
||||
item_id = uuid.UUID(str(payload["i"]))
|
||||
if not isinstance(scope, str):
|
||||
raise ValueError
|
||||
except (ValueError, KeyError, TypeError, UnicodeDecodeError) as exc:
|
||||
raise invalid("cursor is invalid") from exc
|
||||
if created_at.tzinfo is None:
|
||||
created_at = created_at.replace(tzinfo=timezone.utc)
|
||||
return scope, created_at, item_id
|
||||
|
||||
|
||||
@app.get("/health/live")
|
||||
async def health_live() -> dict[str, str]:
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@app.get("/health/ready")
|
||||
async def health_ready(request: Request) -> dict[str, str]:
|
||||
try:
|
||||
async with request.app.state.pool.connection(timeout=2) as conn:
|
||||
async with conn.cursor() as cur:
|
||||
await cur.execute("SELECT 1")
|
||||
await cur.fetchone()
|
||||
except Exception as exc:
|
||||
logger.warning("readiness check failed: %s", type(exc).__name__)
|
||||
raise ApiError(503, "unavailable", "Database is not available") from exc
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@app.post("/api/v1/users")
|
||||
async def register_user(request: Request) -> JSONResponse:
|
||||
data = await read_json_object(request)
|
||||
reject_unknown_fields(data, {"username", "display_name", "password"})
|
||||
username = validate_username(require_string(data, "username"))
|
||||
display_name = validate_display_name(require_string(data, "display_name"))
|
||||
password = validate_password(require_string(data, "password"))
|
||||
|
||||
password_hash = hash_password(password)
|
||||
try:
|
||||
async with request.app.state.pool.connection() as conn:
|
||||
async with conn.cursor(row_factory=dict_row) as cur:
|
||||
await cur.execute(
|
||||
"""
|
||||
INSERT INTO users (id, username, display_name, password_hash)
|
||||
VALUES (%s, %s, %s, %s)
|
||||
RETURNING id, username, display_name, created_at
|
||||
""",
|
||||
(uuid.uuid4(), username, display_name, password_hash),
|
||||
)
|
||||
row = await cur.fetchone()
|
||||
await conn.commit()
|
||||
except pg_errors.UniqueViolation as exc:
|
||||
raise ApiError(409, "conflict", "username is already taken") from exc
|
||||
return JSONResponse(status_code=201, content=user_json(row))
|
||||
|
||||
|
||||
@app.post("/api/v1/auth/sessions")
|
||||
async def create_session(request: Request) -> JSONResponse:
|
||||
header = request.headers.get("authorization", "")
|
||||
scheme, _, credential = header.partition(" ")
|
||||
if scheme.lower() != "basic" or not credential.strip():
|
||||
raise ApiError(401, "unauthorized", "Basic credentials required", BASIC_CHALLENGE)
|
||||
|
||||
try:
|
||||
decoded = base64.b64decode(credential.strip(), validate=True).decode("utf-8")
|
||||
username, password = decoded.split(":", 1)
|
||||
except (ValueError, UnicodeDecodeError) as exc:
|
||||
raise ApiError(401, "unauthorized", "Invalid credentials", BASIC_CHALLENGE) from exc
|
||||
if not username or not password:
|
||||
raise ApiError(401, "unauthorized", "Invalid credentials", BASIC_CHALLENGE)
|
||||
|
||||
async with request.app.state.pool.connection() as conn:
|
||||
async with conn.cursor(row_factory=dict_row) as cur:
|
||||
await cur.execute(
|
||||
"SELECT id, username, display_name, password_hash, created_at FROM users WHERE username = %s",
|
||||
(username,),
|
||||
)
|
||||
row = await cur.fetchone()
|
||||
if row is None or not verify_password(password, row["password_hash"]):
|
||||
raise ApiError(401, "unauthorized", "Invalid credentials", BASIC_CHALLENGE)
|
||||
|
||||
token = new_session_token()
|
||||
await cur.execute(
|
||||
"""
|
||||
INSERT INTO sessions (token_hash, user_id, expires_at)
|
||||
VALUES (%s, %s, now() + make_interval(secs => %s))
|
||||
RETURNING expires_at
|
||||
""",
|
||||
(token_digest(token), row["id"], settings.session_ttl_seconds),
|
||||
)
|
||||
expires_at = (await cur.fetchone())["expires_at"]
|
||||
await conn.commit()
|
||||
|
||||
return JSONResponse(
|
||||
status_code=201,
|
||||
content={
|
||||
"token": token,
|
||||
"token_type": "Bearer",
|
||||
"expires_at": iso_utc(expires_at),
|
||||
"user": user_json(row),
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@app.delete("/api/v1/auth/sessions/current")
|
||||
async def delete_current_session(request: Request) -> Response:
|
||||
await authenticate(request)
|
||||
async with request.app.state.pool.connection() as conn:
|
||||
async with conn.cursor() as cur:
|
||||
await cur.execute("DELETE FROM sessions WHERE token_hash = %s", (request.state.token_hash,))
|
||||
await conn.commit()
|
||||
return Response(status_code=204)
|
||||
|
||||
|
||||
@app.get("/api/v1/users/me")
|
||||
async def current_user(request: Request) -> dict[str, Any]:
|
||||
user = await authenticate(request)
|
||||
return user_json(user)
|
||||
|
||||
|
||||
@app.post("/api/v1/chats")
|
||||
async def create_chat(request: Request) -> JSONResponse:
|
||||
user = await authenticate(request)
|
||||
data = await read_json_object(request)
|
||||
reject_unknown_fields(data, {"title", "member_ids"})
|
||||
title = validate_title(require_string(data, "title"))
|
||||
member_ids = validate_member_ids(data.get("member_ids"))
|
||||
user_id = user["id"]
|
||||
if user_id not in member_ids:
|
||||
raise invalid("Caller must be a member of the new chat")
|
||||
|
||||
chat_id = uuid.uuid4()
|
||||
async with request.app.state.pool.connection() as conn:
|
||||
async with conn.transaction():
|
||||
async with conn.cursor(row_factory=dict_row) as cur:
|
||||
await cur.execute("SELECT id FROM users WHERE id = ANY(%s::uuid[])", (member_ids,))
|
||||
known = {row["id"] for row in await cur.fetchall()}
|
||||
if known != set(member_ids):
|
||||
raise invalid("member_ids contains unknown users")
|
||||
await cur.execute(
|
||||
"INSERT INTO chats (id, title) VALUES (%s, %s) RETURNING id, title, created_at",
|
||||
(chat_id, title),
|
||||
)
|
||||
chat = await cur.fetchone()
|
||||
await cur.executemany(
|
||||
"INSERT INTO chat_members (chat_id, user_id) VALUES (%s, %s)",
|
||||
[(chat_id, member_id) for member_id in member_ids],
|
||||
)
|
||||
return JSONResponse(
|
||||
status_code=201,
|
||||
content=chat_json(chat, sorted(str(member_id) for member_id in member_ids)),
|
||||
)
|
||||
|
||||
|
||||
@app.get("/api/v1/chats")
|
||||
async def list_chats(request: Request) -> dict[str, Any]:
|
||||
user = await authenticate(request)
|
||||
limit = parse_limit(request)
|
||||
cursor_raw = request.query_params.get("cursor")
|
||||
|
||||
conditions = ["m.user_id = %s"]
|
||||
params: list[Any] = [user["id"]]
|
||||
if cursor_raw:
|
||||
scope, created_at, item_id = decode_cursor(cursor_raw)
|
||||
if scope != "chats":
|
||||
raise invalid("cursor does not belong to this collection")
|
||||
conditions.append("(c.created_at, c.id) > (%s::timestamptz, %s::uuid)")
|
||||
params.extend([created_at, item_id])
|
||||
params.append(limit + 1)
|
||||
|
||||
async with request.app.state.pool.connection() as conn:
|
||||
async with conn.cursor(row_factory=dict_row) as cur:
|
||||
await cur.execute(
|
||||
"""
|
||||
SELECT c.id, c.title, c.created_at
|
||||
FROM chats c
|
||||
JOIN chat_members m ON m.chat_id = c.id
|
||||
WHERE """
|
||||
+ " AND ".join(conditions)
|
||||
+ " ORDER BY c.created_at ASC, c.id ASC LIMIT %s",
|
||||
params,
|
||||
)
|
||||
rows = await cur.fetchall()
|
||||
|
||||
has_more = len(rows) > limit
|
||||
rows = rows[:limit]
|
||||
members = await chat_members(request.app.state.pool, [row["id"] for row in rows])
|
||||
next_cursor = (
|
||||
encode_cursor("chats", rows[-1]["created_at"], rows[-1]["id"]) if has_more and rows else None
|
||||
)
|
||||
return {
|
||||
"items": [chat_json(row, members[row["id"]]) for row in rows],
|
||||
"next_cursor": next_cursor,
|
||||
}
|
||||
|
||||
|
||||
@app.get("/api/v1/chats/{chat_id}")
|
||||
async def get_chat(chat_id: str, request: Request) -> dict[str, Any]:
|
||||
user = await authenticate(request)
|
||||
parsed_chat_id = parse_uuid(chat_id, "chat_id")
|
||||
await require_member(request.app.state.pool, parsed_chat_id, user["id"])
|
||||
|
||||
async with request.app.state.pool.connection() as conn:
|
||||
async with conn.cursor(row_factory=dict_row) as cur:
|
||||
await cur.execute(
|
||||
"SELECT id, title, created_at FROM chats WHERE id = %s",
|
||||
(parsed_chat_id,),
|
||||
)
|
||||
row = await cur.fetchone()
|
||||
if row is None:
|
||||
raise ApiError(404, "not_found", "Chat not found")
|
||||
members = await chat_members(request.app.state.pool, [parsed_chat_id])
|
||||
return chat_json(row, members[parsed_chat_id])
|
||||
|
||||
|
||||
def canonical_request_hash(payload: dict[str, Any]) -> str:
|
||||
canonical = json.dumps(payload, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
|
||||
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
async def create_message_idempotent(
|
||||
pool: AsyncConnectionPool,
|
||||
user_id: uuid.UUID,
|
||||
chat_id: uuid.UUID,
|
||||
idempotency_key: str,
|
||||
text: str,
|
||||
) -> tuple[int, dict[str, Any]]:
|
||||
path = f"/api/v1/chats/{chat_id}/messages"
|
||||
request_hash = canonical_request_hash({"text": text})
|
||||
|
||||
for _ in range(5):
|
||||
async with pool.connection() as conn:
|
||||
async with conn.transaction():
|
||||
async with conn.cursor(row_factory=dict_row) as cur:
|
||||
await cur.execute(
|
||||
"SELECT 1 FROM chat_members WHERE chat_id = %s AND user_id = %s",
|
||||
(chat_id, user_id),
|
||||
)
|
||||
if await cur.fetchone() is None:
|
||||
raise ApiError(404, "not_found", "Chat not found")
|
||||
|
||||
await cur.execute(
|
||||
"""
|
||||
INSERT INTO idempotency_keys
|
||||
(user_id, method, path, key, request_hash, expires_at)
|
||||
VALUES (%s, 'POST', %s, %s, %s, now() + make_interval(secs => %s))
|
||||
ON CONFLICT DO NOTHING
|
||||
RETURNING user_id
|
||||
""",
|
||||
(
|
||||
user_id,
|
||||
path,
|
||||
idempotency_key,
|
||||
request_hash,
|
||||
settings.idempotency_ttl_seconds,
|
||||
),
|
||||
)
|
||||
if await cur.fetchone() is not None:
|
||||
await cur.execute(
|
||||
"""
|
||||
INSERT INTO messages (id, chat_id, sender_id, text)
|
||||
VALUES (%s, %s, %s, %s)
|
||||
RETURNING id, chat_id, sender_id, text, created_at
|
||||
""",
|
||||
(uuid.uuid4(), chat_id, user_id, text),
|
||||
)
|
||||
message = message_json(await cur.fetchone())
|
||||
await cur.execute(
|
||||
"""
|
||||
UPDATE idempotency_keys
|
||||
SET status_code = 201, response_body = %s
|
||||
WHERE user_id = %s AND method = 'POST' AND path = %s AND key = %s
|
||||
""",
|
||||
(Jsonb(message), user_id, path, idempotency_key),
|
||||
)
|
||||
return 201, message
|
||||
|
||||
await cur.execute(
|
||||
"""
|
||||
SELECT request_hash, status_code, response_body, expires_at, now() AS now_ts
|
||||
FROM idempotency_keys
|
||||
WHERE user_id = %s AND method = 'POST' AND path = %s AND key = %s
|
||||
""",
|
||||
(user_id, path, idempotency_key),
|
||||
)
|
||||
existing = await cur.fetchone()
|
||||
if existing is None:
|
||||
continue
|
||||
if existing["expires_at"] <= existing["now_ts"]:
|
||||
await cur.execute(
|
||||
"""
|
||||
DELETE FROM idempotency_keys
|
||||
WHERE user_id = %s AND method = 'POST' AND path = %s AND key = %s
|
||||
""",
|
||||
(user_id, path, idempotency_key),
|
||||
)
|
||||
continue
|
||||
if existing["request_hash"] != request_hash:
|
||||
raise ApiError(
|
||||
409,
|
||||
"conflict",
|
||||
"Idempotency-Key was reused with a different request body",
|
||||
)
|
||||
if existing["status_code"] is None or existing["response_body"] is None:
|
||||
continue
|
||||
return existing["status_code"], existing["response_body"]
|
||||
|
||||
raise ApiError(503, "unavailable", "Concurrent idempotent request did not complete")
|
||||
|
||||
|
||||
@app.post("/api/v1/chats/{chat_id}/messages")
|
||||
async def create_message(chat_id: str, request: Request) -> JSONResponse:
|
||||
user = await authenticate(request)
|
||||
parsed_chat_id = parse_uuid(chat_id, "chat_id")
|
||||
await require_member(request.app.state.pool, parsed_chat_id, user["id"])
|
||||
|
||||
idempotency_key = validate_idempotency_key(request)
|
||||
data = await read_json_object(request)
|
||||
reject_unknown_fields(data, {"text"})
|
||||
text = validate_message_text(require_string(data, "text"))
|
||||
|
||||
status_code, message = await create_message_idempotent(
|
||||
request.app.state.pool, user["id"], parsed_chat_id, idempotency_key, text
|
||||
)
|
||||
return JSONResponse(status_code=status_code, content=message)
|
||||
|
||||
|
||||
@app.get("/api/v1/chats/{chat_id}/messages")
|
||||
async def list_messages(chat_id: str, request: Request) -> dict[str, Any]:
|
||||
user = await authenticate(request)
|
||||
parsed_chat_id = parse_uuid(chat_id, "chat_id")
|
||||
await require_member(request.app.state.pool, parsed_chat_id, user["id"])
|
||||
|
||||
limit = parse_limit(request)
|
||||
cursor_raw = request.query_params.get("cursor")
|
||||
conditions = ["chat_id = %s"]
|
||||
params: list[Any] = [parsed_chat_id]
|
||||
if cursor_raw:
|
||||
scope, created_at, item_id = decode_cursor(cursor_raw)
|
||||
if scope != str(parsed_chat_id):
|
||||
raise invalid("cursor does not belong to this chat")
|
||||
conditions.append("(created_at, id) > (%s::timestamptz, %s::uuid)")
|
||||
params.extend([created_at, item_id])
|
||||
params.append(limit + 1)
|
||||
|
||||
async with request.app.state.pool.connection() as conn:
|
||||
async with conn.cursor(row_factory=dict_row) as cur:
|
||||
await cur.execute(
|
||||
"""
|
||||
SELECT id, chat_id, sender_id, text, created_at
|
||||
FROM messages
|
||||
WHERE """
|
||||
+ " AND ".join(conditions)
|
||||
+ " ORDER BY created_at ASC, id ASC LIMIT %s",
|
||||
params,
|
||||
)
|
||||
rows = await cur.fetchall()
|
||||
|
||||
has_more = len(rows) > limit
|
||||
rows = rows[:limit]
|
||||
next_cursor = (
|
||||
encode_cursor(str(parsed_chat_id), rows[-1]["created_at"], rows[-1]["id"])
|
||||
if has_more and rows
|
||||
else None
|
||||
)
|
||||
return {"items": [message_json(row) for row in rows], "next_cursor": next_cursor}
|
||||
@@ -0,0 +1,60 @@
|
||||
"""One-shot, idempotent schema migration runner.
|
||||
|
||||
The compose stack starts this module as a separate service before any API
|
||||
replica, so replicas never race on DDL.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import psycopg
|
||||
|
||||
from .settings import load_settings
|
||||
|
||||
MIGRATION_FILE = Path(__file__).resolve().parents[1] / "migrations" / "001_init.sql"
|
||||
MIGRATION_VERSION = "001_init"
|
||||
ADVISORY_LOCK_ID = 727_001_003
|
||||
|
||||
|
||||
def statements(sql: str) -> list[str]:
|
||||
return [part.strip() for part in sql.split(";") if part.strip()]
|
||||
|
||||
|
||||
async def wait_for_database(database_url: str, attempts: int = 60) -> psycopg.AsyncConnection:
|
||||
last_error: Exception | None = None
|
||||
for _ in range(attempts):
|
||||
try:
|
||||
return await psycopg.AsyncConnection.connect(database_url)
|
||||
except psycopg.OperationalError as exc:
|
||||
last_error = exc
|
||||
await asyncio.sleep(1)
|
||||
raise SystemExit(f"database is not reachable: {type(last_error).__name__}")
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
settings = load_settings()
|
||||
sql = MIGRATION_FILE.read_text(encoding="utf-8")
|
||||
conn = await wait_for_database(settings.database_url)
|
||||
async with conn:
|
||||
async with conn.cursor() as cur:
|
||||
await cur.execute("SELECT pg_advisory_lock(%s)", (ADVISORY_LOCK_ID,))
|
||||
try:
|
||||
for statement in statements(sql):
|
||||
await cur.execute(statement)
|
||||
await cur.execute(
|
||||
"INSERT INTO schema_migrations (version) VALUES (%s) ON CONFLICT DO NOTHING",
|
||||
(MIGRATION_VERSION,),
|
||||
)
|
||||
finally:
|
||||
await cur.execute("SELECT pg_advisory_unlock(%s)", (ADVISORY_LOCK_ID,))
|
||||
await conn.commit()
|
||||
print(f"migrations applied: {MIGRATION_VERSION}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
asyncio.run(main())
|
||||
except KeyboardInterrupt:
|
||||
sys.exit(130)
|
||||
@@ -0,0 +1,63 @@
|
||||
"""Password hashing (scrypt) and opaque session tokens."""
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import os
|
||||
import secrets
|
||||
|
||||
_SCRYPT_N = 2**14
|
||||
_SCRYPT_R = 8
|
||||
_SCRYPT_P = 1
|
||||
_SCRYPT_DKLEN = 32
|
||||
_SCRYPT_MAXMEM = 64 * 1024 * 1024
|
||||
|
||||
|
||||
def hash_password(password: str) -> str:
|
||||
salt = os.urandom(16)
|
||||
digest = hashlib.scrypt(
|
||||
password.encode("utf-8"),
|
||||
salt=salt,
|
||||
n=_SCRYPT_N,
|
||||
r=_SCRYPT_R,
|
||||
p=_SCRYPT_P,
|
||||
dklen=_SCRYPT_DKLEN,
|
||||
maxmem=_SCRYPT_MAXMEM,
|
||||
)
|
||||
return "scrypt${}${}${}${}${}".format(
|
||||
_SCRYPT_N,
|
||||
_SCRYPT_R,
|
||||
_SCRYPT_P,
|
||||
base64.b64encode(salt).decode("ascii"),
|
||||
base64.b64encode(digest).decode("ascii"),
|
||||
)
|
||||
|
||||
|
||||
def verify_password(password: str, encoded: str) -> bool:
|
||||
try:
|
||||
scheme, n_raw, r_raw, p_raw, salt_raw, digest_raw = encoded.split("$")
|
||||
if scheme != "scrypt":
|
||||
return False
|
||||
expected = base64.b64decode(digest_raw, validate=True)
|
||||
actual = hashlib.scrypt(
|
||||
password.encode("utf-8"),
|
||||
salt=base64.b64decode(salt_raw, validate=True),
|
||||
n=int(n_raw),
|
||||
r=int(r_raw),
|
||||
p=int(p_raw),
|
||||
dklen=len(expected),
|
||||
maxmem=_SCRYPT_MAXMEM,
|
||||
)
|
||||
except (ValueError, TypeError, MemoryError):
|
||||
return False
|
||||
return hmac.compare_digest(actual, expected)
|
||||
|
||||
|
||||
def new_session_token() -> str:
|
||||
# 48 random bytes -> 384 bits of entropy, encoded as an opaque URL-safe string.
|
||||
return secrets.token_urlsafe(48)
|
||||
|
||||
|
||||
def token_digest(token: str) -> str:
|
||||
return hashlib.sha256(token.encode("utf-8")).hexdigest()
|
||||
@@ -0,0 +1,42 @@
|
||||
"""Runtime configuration loaded from environment variables."""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Settings:
|
||||
database_url: str
|
||||
session_ttl_seconds: int
|
||||
idempotency_ttl_seconds: int
|
||||
instance_id: str
|
||||
|
||||
|
||||
def _positive_int(name: str, default: int) -> int:
|
||||
raw = os.environ.get(name, str(default))
|
||||
try:
|
||||
value = int(raw)
|
||||
except ValueError as exc:
|
||||
raise RuntimeError(f"{name} must be an integer") from exc
|
||||
if value < 1:
|
||||
raise RuntimeError(f"{name} must be positive")
|
||||
return value
|
||||
|
||||
|
||||
def load_settings() -> Settings:
|
||||
database_url = os.environ.get("DATABASE_URL", "").strip()
|
||||
if not database_url:
|
||||
secret_path = os.environ.get("DATABASE_URL_FILE", "").strip()
|
||||
if secret_path and Path(secret_path).is_file():
|
||||
database_url = Path(secret_path).read_text(encoding="utf-8").strip()
|
||||
if not database_url:
|
||||
raise RuntimeError("DATABASE_URL or DATABASE_URL_FILE must be set")
|
||||
|
||||
return Settings(
|
||||
database_url=database_url,
|
||||
session_ttl_seconds=_positive_int("SESSION_TTL_SECONDS", 3600),
|
||||
idempotency_ttl_seconds=_positive_int("IDEMPOTENCY_TTL_SECONDS", 86400),
|
||||
instance_id=os.environ.get("INSTANCE_ID") or os.environ.get("HOSTNAME") or "api",
|
||||
)
|
||||
@@ -0,0 +1,99 @@
|
||||
"""Strict request validation matching contracts/README.md."""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import uuid
|
||||
from typing import Any, Iterable
|
||||
|
||||
from fastapi import Request
|
||||
|
||||
from .errors import ApiError
|
||||
|
||||
USERNAME_RE = re.compile(r"[a-z0-9_]{3,32}")
|
||||
IDEMPOTENCY_KEY_RE = re.compile(r"[A-Za-z0-9._:-]{1,128}")
|
||||
|
||||
|
||||
def invalid(message: str) -> ApiError:
|
||||
return ApiError(400, "invalid_request", message)
|
||||
|
||||
|
||||
def reject_unknown_fields(data: dict[str, Any], allowed: Iterable[str]) -> None:
|
||||
unknown = set(data) - set(allowed)
|
||||
if unknown:
|
||||
raise invalid("Request contains unknown fields")
|
||||
|
||||
|
||||
def require_string(data: dict[str, Any], field: str) -> str:
|
||||
value = data.get(field)
|
||||
if not isinstance(value, str):
|
||||
raise invalid(f"Field '{field}' must be a string")
|
||||
return value
|
||||
|
||||
|
||||
def validate_username(value: str) -> str:
|
||||
if USERNAME_RE.fullmatch(value) is None:
|
||||
raise invalid("username must match [a-z0-9_]{3,32}")
|
||||
return value
|
||||
|
||||
|
||||
def validate_display_name(value: str) -> str:
|
||||
if not 1 <= len(value) <= 100 or not value.strip():
|
||||
raise invalid("display_name must contain 1..100 non-blank characters")
|
||||
return value
|
||||
|
||||
|
||||
def validate_password(value: str) -> str:
|
||||
if not 12 <= len(value) <= 128 or not value.strip():
|
||||
raise invalid("password must contain 12..128 non-blank characters")
|
||||
return value
|
||||
|
||||
|
||||
def validate_title(value: str) -> str:
|
||||
if not 1 <= len(value) <= 100 or not value.strip():
|
||||
raise invalid("title must contain 1..100 non-blank characters")
|
||||
return value
|
||||
|
||||
|
||||
def validate_message_text(value: str) -> str:
|
||||
if not 1 <= len(value) <= 4000 or not value.strip():
|
||||
raise invalid("text must contain 1..4000 non-blank characters")
|
||||
return value
|
||||
|
||||
|
||||
def parse_uuid(value: str, field: str = "id") -> uuid.UUID:
|
||||
try:
|
||||
return uuid.UUID(value)
|
||||
except (ValueError, AttributeError, TypeError) as exc:
|
||||
raise invalid(f"'{field}' must be a UUID") from exc
|
||||
|
||||
|
||||
def validate_member_ids(value: Any) -> list[uuid.UUID]:
|
||||
if not isinstance(value, list) or not 1 <= len(value) <= 100:
|
||||
raise invalid("member_ids must contain 1..100 UUIDs")
|
||||
members: list[uuid.UUID] = []
|
||||
for item in value:
|
||||
if not isinstance(item, str):
|
||||
raise invalid("member_ids must contain UUID strings")
|
||||
members.append(parse_uuid(item, "member_ids"))
|
||||
if len(set(members)) != len(members):
|
||||
raise invalid("member_ids must not contain duplicates")
|
||||
return members
|
||||
|
||||
|
||||
def validate_idempotency_key(request: Request) -> str:
|
||||
key = request.headers.get("Idempotency-Key")
|
||||
if key is None or IDEMPOTENCY_KEY_RE.fullmatch(key) is None:
|
||||
raise invalid("Idempotency-Key is required and must match [A-Za-z0-9._:-]{1,128}")
|
||||
return key
|
||||
|
||||
|
||||
def parse_limit(request: Request) -> int:
|
||||
raw = request.query_params.get("limit")
|
||||
if raw is None:
|
||||
return 50
|
||||
if re.fullmatch(r"[0-9]{1,3}", raw) is None:
|
||||
raise invalid("limit must be an integer between 1 and 100")
|
||||
value = int(raw)
|
||||
if not 1 <= value <= 100:
|
||||
raise invalid("limit must be an integer between 1 and 100")
|
||||
return value
|
||||
Reference in New Issue
Block a user