ЛР 3: балансировка, 2 реплики API и общая идемпотентность (оценка 3)
This commit is contained in:
@@ -0,0 +1 @@
|
||||
"""Messenger lab2: PostgreSQL-backed API."""
|
||||
@@ -0,0 +1,13 @@
|
||||
"""Local entry point: python -m app"""
|
||||
import os
|
||||
|
||||
import uvicorn
|
||||
|
||||
if __name__ == "__main__":
|
||||
uvicorn.run(
|
||||
"app.main:app",
|
||||
host=os.environ.get("APP_HOST", "0.0.0.0"),
|
||||
port=int(os.environ.get("APP_PORT", "8080")),
|
||||
workers=1, # in-process ordering/cursors; PostgreSQL is the shared source of truth
|
||||
log_level=os.environ.get("LOG_LEVEL", "info"),
|
||||
)
|
||||
@@ -0,0 +1,150 @@
|
||||
"""PostgreSQL access: small bounded connection pool, versioned migrations, row helpers."""
|
||||
import logging
|
||||
import os
|
||||
import queue
|
||||
from contextlib import contextmanager
|
||||
from datetime import timezone
|
||||
from pathlib import Path
|
||||
|
||||
import psycopg
|
||||
from psycopg.rows import dict_row
|
||||
|
||||
log = logging.getLogger("messenger.db")
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
MIGRATIONS = ROOT / "migrations"
|
||||
|
||||
|
||||
def _read_secret(path):
|
||||
if not path:
|
||||
return None
|
||||
value = Path(path).read_text(encoding="utf-8").strip()
|
||||
if not value:
|
||||
raise RuntimeError("secret file is empty: " + path)
|
||||
return value
|
||||
|
||||
|
||||
def database_url():
|
||||
"""Prefer a mounted secret file; fall back to an environment variable for local runs."""
|
||||
url = _read_secret(os.environ.get("DATABASE_URL_FILE"))
|
||||
if url:
|
||||
return url
|
||||
url = os.environ.get("DATABASE_URL")
|
||||
if not url:
|
||||
raise RuntimeError("DATABASE_URL or DATABASE_URL_FILE is required")
|
||||
return url
|
||||
|
||||
|
||||
class Database:
|
||||
"""A tiny FIFO pool. Each request borrows one connection and returns it."""
|
||||
|
||||
def __init__(self):
|
||||
self._pool = None
|
||||
self.dsn = None
|
||||
|
||||
def start(self):
|
||||
self.dsn = database_url()
|
||||
size = int(os.environ.get("DB_POOL_MAX", "8"))
|
||||
self._pool = queue.Queue(maxsize=size)
|
||||
for _ in range(size):
|
||||
self._pool.put(self._connect())
|
||||
self.migrate()
|
||||
|
||||
def _connect(self):
|
||||
return psycopg.connect(self.dsn, connect_timeout=3, row_factory=dict_row, autocommit=True)
|
||||
|
||||
def stop(self):
|
||||
if self._pool is None:
|
||||
return
|
||||
while not self._pool.empty():
|
||||
try:
|
||||
self._pool.get_nowait().close()
|
||||
except queue.Empty:
|
||||
break
|
||||
self._pool = None
|
||||
|
||||
@contextmanager
|
||||
def connection(self):
|
||||
conn = self._pool.get(timeout=5)
|
||||
try:
|
||||
yield conn
|
||||
finally:
|
||||
self._pool.put(conn)
|
||||
|
||||
@contextmanager
|
||||
def transaction(self):
|
||||
with self.connection() as conn:
|
||||
# Explicit BEGIN/COMMIT; rollback on any exception.
|
||||
conn.execute("BEGIN")
|
||||
try:
|
||||
yield conn
|
||||
except BaseException:
|
||||
conn.execute("ROLLBACK")
|
||||
raise
|
||||
else:
|
||||
conn.execute("COMMIT")
|
||||
|
||||
def ready(self):
|
||||
try:
|
||||
with self.connection() as conn:
|
||||
conn.execute("SELECT 1").fetchone()
|
||||
return True
|
||||
except Exception:
|
||||
log.exception("readiness check failed")
|
||||
return False
|
||||
|
||||
def migrate(self):
|
||||
"""Apply *.sql in name order, at most once each; restart-safe with the same volume."""
|
||||
with self.transaction() as conn:
|
||||
# All API replicas start against the same database. A transaction-scoped
|
||||
# advisory lock makes the migration step strictly single-runner:
|
||||
# the second replica waits, then sees schema_migrations already filled.
|
||||
conn.execute("SELECT pg_advisory_xact_lock(20261116)")
|
||||
conn.execute(
|
||||
"CREATE TABLE IF NOT EXISTS schema_migrations ("
|
||||
"name TEXT PRIMARY KEY, applied_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp())"
|
||||
)
|
||||
applied = {r["name"] for r in conn.execute("SELECT name FROM schema_migrations").fetchall()}
|
||||
for path in sorted(MIGRATIONS.glob("*.sql")):
|
||||
if path.name in applied:
|
||||
continue
|
||||
conn.execute(path.read_text(encoding="utf-8"))
|
||||
conn.execute("INSERT INTO schema_migrations(name) VALUES (%s)", (path.name,))
|
||||
log.info("applied migration %s", path.name)
|
||||
|
||||
|
||||
db = Database()
|
||||
|
||||
|
||||
def utc_text(value):
|
||||
"""RFC 3339 UTC with an explicit Z and microsecond precision."""
|
||||
value = value.astimezone(timezone.utc)
|
||||
return value.strftime("%Y-%m-%dT%H:%M:%S.%fZ")
|
||||
|
||||
|
||||
def user_public(row):
|
||||
return {
|
||||
"id": str(row["id"]),
|
||||
"username": row["username"],
|
||||
"display_name": row["display_name"],
|
||||
"created_at": utc_text(row["created_at"]),
|
||||
}
|
||||
|
||||
|
||||
def chat_public(row):
|
||||
return {
|
||||
"id": str(row["id"]),
|
||||
"title": row["title"],
|
||||
"member_ids": [str(x) for x in (row["member_ids"] or [])],
|
||||
"created_at": utc_text(row["created_at"]),
|
||||
}
|
||||
|
||||
|
||||
def message_public(row):
|
||||
return {
|
||||
"id": str(row["id"]),
|
||||
"chat_id": str(row["chat_id"]),
|
||||
"sender_id": str(row["sender_id"]),
|
||||
"text": row["text"],
|
||||
"created_at": utc_text(row["created_at"]),
|
||||
}
|
||||
+475
@@ -0,0 +1,475 @@
|
||||
"""Lab2 messenger HTTP layer. Contract: contracts/openapi.json.
|
||||
|
||||
State lives in PostgreSQL: users, chats, memberships, messages and sessions.
|
||||
Basic is accepted only on POST /auth/sessions; every other protected route needs Bearer.
|
||||
"""
|
||||
import base64
|
||||
import binascii
|
||||
import datetime as dt
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import uuid
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
import psycopg
|
||||
from fastapi import FastAPI, Request
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.responses import JSONResponse, Response
|
||||
from starlette.datastructures import MutableHeaders
|
||||
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||
|
||||
from .db import chat_public, db, message_public, user_public, utc_text
|
||||
from .security import bearer_token, hash_password, parse_basic, token_hash, verify_password
|
||||
|
||||
log = logging.getLogger("messenger")
|
||||
|
||||
MAX_BODY_BYTES = 1 << 20
|
||||
DEFAULT_LIMIT, MAX_LIMIT = 50, 100
|
||||
USERNAME_RE = re.compile(r"[a-z0-9_]{3,32}\Z")
|
||||
UUID_RE = re.compile(r"[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\Z")
|
||||
IDEMPOTENCY_KEY_RE = re.compile(r"[A-Za-z0-9._:-]{1,128}\Z")
|
||||
BASIC_CHALLENGE = 'Basic realm="messenger", charset="UTF-8"'
|
||||
BEARER_CHALLENGE = 'Bearer realm="messenger"'
|
||||
INSTANCE_ID = os.environ.get("INSTANCE_ALIAS") or uuid.uuid4().hex[:12]
|
||||
|
||||
UTC = dt.timezone.utc
|
||||
|
||||
|
||||
class ApiError(Exception):
|
||||
def __init__(self, status, code, message, headers=None):
|
||||
self.status, self.code, self.message, self.headers = status, code, message, headers
|
||||
|
||||
|
||||
def bad_request(message):
|
||||
return ApiError(400, "invalid_request", message)
|
||||
|
||||
|
||||
def unauthorized(challenge, message="Требуется действительная аутентификация"):
|
||||
return ApiError(401, "unauthorized", message, {"WWW-Authenticate": challenge})
|
||||
|
||||
|
||||
def not_found():
|
||||
return ApiError(404, "not_found", "Объект не найден")
|
||||
|
||||
|
||||
def error_response(status, code, message, request_id, headers=None):
|
||||
body = {"error": {"code": code, "message": message, "request_id": request_id}}
|
||||
return JSONResponse(body, status_code=status, headers=headers)
|
||||
|
||||
|
||||
class RequestContextMiddleware:
|
||||
"""Add X-Request-Id (and X-Instance-Id) to every response, including errors and health."""
|
||||
|
||||
def __init__(self, app):
|
||||
self.app = app
|
||||
|
||||
async def __call__(self, scope, receive, send):
|
||||
if scope["type"] != "http":
|
||||
await self.app(scope, receive, send)
|
||||
return
|
||||
request_id = str(uuid.uuid4())
|
||||
scope.setdefault("state", {})["request_id"] = request_id
|
||||
started = False
|
||||
|
||||
async def send_with_id(message):
|
||||
nonlocal started
|
||||
if message["type"] == "http.response.start":
|
||||
started = True
|
||||
headers = MutableHeaders(scope=message)
|
||||
headers["X-Request-Id"] = request_id
|
||||
headers["X-Instance-Id"] = INSTANCE_ID
|
||||
await send(message)
|
||||
|
||||
try:
|
||||
await self.app(scope, receive, send_with_id)
|
||||
except Exception:
|
||||
log.exception("unhandled error request_id=%s", request_id)
|
||||
if not started:
|
||||
response = error_response(500, "internal_error", "Внутренняя ошибка сервера", request_id)
|
||||
await response(scope, receive, send_with_id)
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app):
|
||||
db.start()
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
db.stop()
|
||||
|
||||
|
||||
app = FastAPI(title="Messenger lab2", docs_url=None, redoc_url=None, openapi_url=None, lifespan=lifespan)
|
||||
app.add_middleware(RequestContextMiddleware)
|
||||
|
||||
|
||||
@app.exception_handler(ApiError)
|
||||
async def handle_api_error(request: Request, exc: ApiError):
|
||||
return error_response(exc.status, exc.code, exc.message, request.state.request_id, exc.headers)
|
||||
|
||||
|
||||
@app.exception_handler(StarletteHTTPException)
|
||||
async def handle_http_exception(request: Request, exc: StarletteHTTPException):
|
||||
if exc.status_code == 404:
|
||||
code, message = "not_found", "Объект не найден"
|
||||
elif exc.status_code < 500:
|
||||
code, message = "invalid_request", "Некорректный запрос"
|
||||
else:
|
||||
code, message = "internal_error", "Внутренняя ошибка сервера"
|
||||
return error_response(exc.status_code, code, message, request.state.request_id, exc.headers)
|
||||
|
||||
|
||||
@app.exception_handler(RequestValidationError)
|
||||
async def handle_validation_error(request: Request, exc: RequestValidationError):
|
||||
return error_response(400, "invalid_request", "Некорректный запрос", request.state.request_id)
|
||||
|
||||
|
||||
# ---------- validation helpers ----------
|
||||
|
||||
def clean_string(data, field, max_len):
|
||||
value = data.get(field)
|
||||
if not isinstance(value, str):
|
||||
raise bad_request("Поле %s должно быть строкой" % field)
|
||||
if not value.strip() or len(value) > max_len:
|
||||
raise bad_request("Поле %s должно содержать от 1 до %d символов" % (field, max_len))
|
||||
return value
|
||||
|
||||
|
||||
def idempotency_key(request):
|
||||
value = request.headers.get("idempotency-key")
|
||||
if not value or not IDEMPOTENCY_KEY_RE.fullmatch(value):
|
||||
raise bad_request("Idempotency-Key обязателен и должен соответствовать [A-Za-z0-9._:-]{1,128}")
|
||||
return value
|
||||
|
||||
|
||||
def parse_uuid(value, what):
|
||||
if not isinstance(value, str) or not UUID_RE.fullmatch(value):
|
||||
raise bad_request("Некорректный UUID: %s" % what)
|
||||
return value.lower()
|
||||
|
||||
|
||||
async def read_json_object(request, allowed):
|
||||
declared = request.headers.get("content-length", "")
|
||||
if declared.isdigit() and int(declared) > MAX_BODY_BYTES:
|
||||
raise ApiError(413, "payload_too_large", "Тело запроса слишком большое")
|
||||
content_type = request.headers.get("content-type", "").split(";")[0].strip().lower()
|
||||
if content_type and content_type != "application/json":
|
||||
raise ApiError(415, "unsupported_media_type", "Ожидается application/json")
|
||||
body = bytearray()
|
||||
async for chunk in request.stream():
|
||||
body += chunk
|
||||
if len(body) > MAX_BODY_BYTES:
|
||||
raise ApiError(413, "payload_too_large", "Тело запроса слишком большое")
|
||||
try:
|
||||
data = json.loads(bytes(body).decode("utf-8"))
|
||||
except (UnicodeDecodeError, ValueError):
|
||||
raise bad_request("Тело запроса не является корректным JSON") from None
|
||||
if not isinstance(data, dict):
|
||||
raise bad_request("Тело запроса должно быть JSON-объектом")
|
||||
if set(data) != set(allowed):
|
||||
raise bad_request("Ожидаемые поля: " + ", ".join(sorted(allowed)))
|
||||
return data
|
||||
|
||||
|
||||
def page_params(request):
|
||||
query = request.query_params
|
||||
raw_limit = query.getlist("limit")
|
||||
if len(raw_limit) > 1 or len(query.getlist("cursor")) > 1:
|
||||
raise bad_request("Параметры limit и cursor можно указать только один раз")
|
||||
limit = DEFAULT_LIMIT
|
||||
if raw_limit:
|
||||
text = raw_limit[0]
|
||||
if not (text.isascii() and text.isdigit()) or not 1 <= int(text) <= MAX_LIMIT:
|
||||
raise bad_request("limit должен быть целым числом от 1 до %d" % MAX_LIMIT)
|
||||
limit = int(text)
|
||||
return limit, query.get("cursor") or None
|
||||
|
||||
|
||||
def encode_cursor(kind, scope, created_at, item_id):
|
||||
raw = json.dumps(
|
||||
{"k": kind, "s": scope,
|
||||
"t": int(created_at.timestamp() * 1_000_000),
|
||||
"i": uuid.UUID(str(item_id)).int},
|
||||
separators=(",", ":"),
|
||||
)
|
||||
return base64.urlsafe_b64encode(raw.encode()).decode().rstrip("=")
|
||||
|
||||
|
||||
def decode_cursor(text, kind, scope):
|
||||
try:
|
||||
data = json.loads(base64.urlsafe_b64decode(text + "=" * (-len(text) % 4)))
|
||||
t, i = data["t"], data["i"]
|
||||
valid = (data["k"] == kind and data["s"] == scope
|
||||
and type(t) is int and type(i) is int and t >= 0 and i >= 0)
|
||||
if not valid:
|
||||
raise ValueError
|
||||
return dt.datetime.fromtimestamp(t / 1_000_000, tz=UTC), uuid.UUID(int=i)
|
||||
except (ValueError, KeyError, TypeError, binascii.Error, OverflowError):
|
||||
raise bad_request("Некорректный cursor") from None
|
||||
|
||||
|
||||
def page_response(items, limit, kind, scope, rows):
|
||||
"""items are public JSON dicts; rows are the raw DB rows used for the opaque cursor."""
|
||||
more = len(items) > limit
|
||||
window = items[:limit]
|
||||
last = rows[limit - 1] if more and len(rows) >= limit else None
|
||||
cursor = (encode_cursor(kind, scope, last["created_at"], last["id"])
|
||||
if last is not None else None)
|
||||
return JSONResponse({"items": window, "next_cursor": cursor})
|
||||
|
||||
|
||||
# ---------- authentication and resource access ----------
|
||||
|
||||
def current_user(request):
|
||||
"""Lab2: only an opaque Bearer session identifies the caller; X-User-Id is ignored."""
|
||||
token = bearer_token(request.headers.get("authorization"))
|
||||
if not token:
|
||||
raise unauthorized(BEARER_CHALLENGE)
|
||||
with db.connection() as conn:
|
||||
row = conn.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 > clock_timestamp()",
|
||||
(token_hash(token),),
|
||||
).fetchone()
|
||||
if row is None:
|
||||
raise unauthorized(BEARER_CHALLENGE)
|
||||
return user_public(row)
|
||||
|
||||
|
||||
def authenticated_chat(request, chat_id):
|
||||
user = current_user(request)
|
||||
chat_uuid = parse_uuid(chat_id, "chat_id")
|
||||
with db.connection() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT c.id, c.title, c.created_at, "
|
||||
"array_agg(m.user_id ORDER BY m.user_id) AS member_ids "
|
||||
"FROM chats c JOIN chat_members m ON m.chat_id = c.id "
|
||||
"WHERE c.id = %s AND m.user_id = %s GROUP BY c.id",
|
||||
(chat_uuid, uuid.UUID(user["id"])),
|
||||
).fetchone()
|
||||
if row is None:
|
||||
raise not_found() # unknown and foreign chats look identical
|
||||
return user, chat_public(row)
|
||||
|
||||
|
||||
# ---------- health ----------
|
||||
|
||||
@app.get("/health/live")
|
||||
async def live():
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@app.get("/health/ready")
|
||||
async def ready():
|
||||
if not db.ready():
|
||||
raise ApiError(503, "unavailable", "Хранилище данных недоступно")
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
# ---------- users and sessions ----------
|
||||
|
||||
@app.post("/api/v1/users")
|
||||
async def register_user(request: Request):
|
||||
data = await read_json_object(request, ("username", "display_name", "password"))
|
||||
username = data["username"]
|
||||
if not isinstance(username, str) or not USERNAME_RE.fullmatch(username):
|
||||
raise bad_request("username должен соответствовать [a-z0-9_]{3,32}")
|
||||
display_name = clean_string(data, "display_name", 100)
|
||||
password = data["password"]
|
||||
if not isinstance(password, str) or not 12 <= len(password) <= 128:
|
||||
raise bad_request("password должен содержать от 12 до 128 символов")
|
||||
user_id = uuid.uuid4()
|
||||
try:
|
||||
with db.transaction() as conn:
|
||||
conn.execute(
|
||||
"INSERT INTO users(id, username, display_name, password_hash) VALUES (%s,%s,%s,%s)",
|
||||
(user_id, username, display_name, hash_password(password)),
|
||||
)
|
||||
row = conn.execute("SELECT * FROM users WHERE id = %s", (user_id,)).fetchone()
|
||||
except psycopg.errors.UniqueViolation:
|
||||
raise ApiError(409, "conflict", "Имя пользователя уже занято") from None
|
||||
return JSONResponse(user_public(row), status_code=201)
|
||||
|
||||
|
||||
@app.post("/api/v1/auth/sessions")
|
||||
async def create_session(request: Request):
|
||||
credential = parse_basic(request.headers.get("authorization"))
|
||||
if credential is None:
|
||||
raise unauthorized(BASIC_CHALLENGE, "Неверные учетные данные")
|
||||
username, password = credential
|
||||
with db.connection() as conn:
|
||||
row = conn.execute("SELECT * FROM users WHERE username = %s", (username,)).fetchone()
|
||||
if row is None or not verify_password(password, row["password_hash"]):
|
||||
raise unauthorized(BASIC_CHALLENGE, "Неверные учетные данные")
|
||||
token = base64.urlsafe_b64encode(os.urandom(32)).decode().rstrip("=")
|
||||
ttl = int(os.environ.get("SESSION_TTL_SECONDS", "3600"))
|
||||
expires_at = dt.datetime.now(UTC) + dt.timedelta(seconds=ttl)
|
||||
with db.transaction() as conn:
|
||||
conn.execute(
|
||||
"INSERT INTO sessions(token_hash, user_id, expires_at) VALUES (%s,%s,%s)",
|
||||
(token_hash(token), row["id"], expires_at),
|
||||
)
|
||||
return JSONResponse({
|
||||
"token": token,
|
||||
"token_type": "Bearer",
|
||||
"expires_at": utc_text(expires_at),
|
||||
"user": user_public(row),
|
||||
}, status_code=201)
|
||||
|
||||
|
||||
@app.delete("/api/v1/auth/sessions/current")
|
||||
async def revoke_session(request: Request):
|
||||
token = bearer_token(request.headers.get("authorization"))
|
||||
if not token:
|
||||
raise unauthorized(BEARER_CHALLENGE)
|
||||
with db.transaction() as conn:
|
||||
result = conn.execute(
|
||||
"DELETE FROM sessions WHERE token_hash = %s AND expires_at > clock_timestamp()",
|
||||
(token_hash(token),),
|
||||
)
|
||||
if result.rowcount == 0:
|
||||
raise unauthorized(BEARER_CHALLENGE)
|
||||
return Response(status_code=204)
|
||||
|
||||
|
||||
@app.get("/api/v1/users/me")
|
||||
async def get_me(request: Request):
|
||||
return current_user(request)
|
||||
|
||||
|
||||
# ---------- chats ----------
|
||||
|
||||
@app.post("/api/v1/chats")
|
||||
async def create_chat(request: Request):
|
||||
user = current_user(request)
|
||||
data = await read_json_object(request, ("title", "member_ids"))
|
||||
title = clean_string(data, "title", 100)
|
||||
raw_members = data["member_ids"]
|
||||
if not isinstance(raw_members, list) or not 1 <= len(raw_members) <= 100:
|
||||
raise bad_request("member_ids должен быть списком из 1–100 UUID")
|
||||
members = [parse_uuid(m, "member_ids") for m in raw_members]
|
||||
if len(set(members)) != len(members):
|
||||
raise bad_request("member_ids содержит дубликаты")
|
||||
if user["id"] not in members:
|
||||
raise bad_request("member_ids должен содержать вызывающего пользователя")
|
||||
chat_id = uuid.uuid4()
|
||||
member_uuids = [uuid.UUID(x) for x in members]
|
||||
try:
|
||||
with db.transaction() as conn:
|
||||
found = conn.execute(
|
||||
"SELECT id FROM users WHERE id = ANY(%s::uuid[])", (member_uuids,)
|
||||
).fetchall()
|
||||
if len(found) != len(member_uuids):
|
||||
raise bad_request("member_ids содержит неизвестного пользователя")
|
||||
conn.execute("INSERT INTO chats(id, title) VALUES (%s,%s)", (chat_id, title))
|
||||
for member in member_uuids:
|
||||
conn.execute(
|
||||
"INSERT INTO chat_members(chat_id, user_id) VALUES (%s,%s)",
|
||||
(chat_id, member),
|
||||
)
|
||||
row = conn.execute(
|
||||
"SELECT c.id, c.title, c.created_at, array_agg(m.user_id ORDER BY m.user_id) AS member_ids "
|
||||
"FROM chats c JOIN chat_members m ON m.chat_id = c.id WHERE c.id = %s GROUP BY c.id",
|
||||
(chat_id,),
|
||||
).fetchone()
|
||||
except psycopg.errors.ForeignKeyViolation:
|
||||
raise bad_request("member_ids содержит неизвестного пользователя") from None
|
||||
return JSONResponse(chat_public(row), status_code=201)
|
||||
|
||||
|
||||
@app.get("/api/v1/chats")
|
||||
async def list_chats(request: Request):
|
||||
user = current_user(request)
|
||||
limit, cursor = page_params(request)
|
||||
after = decode_cursor(cursor, "chats", user["id"]) if cursor else None
|
||||
sql = (
|
||||
"SELECT c.id, c.title, c.created_at, array_agg(m.user_id ORDER BY m.user_id) AS member_ids "
|
||||
"FROM chats c JOIN chat_members m ON m.chat_id = c.id WHERE m.user_id = %s"
|
||||
)
|
||||
params = [uuid.UUID(user["id"])]
|
||||
if after:
|
||||
sql += " AND (c.created_at, c.id) > (%s, %s::uuid)"
|
||||
params.extend([after[0], after[1]])
|
||||
sql += " GROUP BY c.id ORDER BY c.created_at, c.id LIMIT %s"
|
||||
params.append(limit + 1)
|
||||
with db.connection() as conn:
|
||||
rows = conn.execute(sql, params).fetchall()
|
||||
items = [chat_public(r) for r in rows]
|
||||
return page_response(items, limit, "chats", user["id"], rows)
|
||||
|
||||
|
||||
@app.get("/api/v1/chats/{chat_id}")
|
||||
async def get_chat(chat_id: str, request: Request):
|
||||
_, chat = authenticated_chat(request, chat_id)
|
||||
return chat
|
||||
|
||||
|
||||
# ---------- messages ----------
|
||||
|
||||
@app.post("/api/v1/chats/{chat_id}/messages")
|
||||
async def create_message(chat_id: str, request: Request):
|
||||
"""Idempotent POST: the ledger row and the message are committed atomically."""
|
||||
user, chat = authenticated_chat(request, chat_id) # replay re-checks session and access
|
||||
data = await read_json_object(request, ("text",))
|
||||
text = clean_string(data, "text", 4000)
|
||||
key = idempotency_key(request)
|
||||
# Canonical body hash: key order does not matter; omitted attachment_ids == [].
|
||||
canonical = json.dumps({"text": text}, sort_keys=True, separators=(",", ":"))
|
||||
request_hash = hashlib.sha256(canonical.encode("utf-8")).hexdigest()
|
||||
scope_path = request.url.path
|
||||
actor_id = uuid.UUID(user["id"])
|
||||
|
||||
for _attempt in range(5):
|
||||
try:
|
||||
with db.transaction() as conn:
|
||||
previous = conn.execute(
|
||||
"SELECT request_hash, status_code, response_body FROM idempotency_records "
|
||||
"WHERE user_id=%s AND method=%s AND path=%s AND key=%s FOR UPDATE",
|
||||
(actor_id, "POST", scope_path, key),
|
||||
).fetchone()
|
||||
if previous is not None:
|
||||
if previous["request_hash"] != request_hash:
|
||||
raise ApiError(409, "conflict", "Тот же Idempotency-Key использован с другим телом")
|
||||
return JSONResponse(previous["response_body"], status_code=previous["status_code"])
|
||||
|
||||
message_id = uuid.uuid4()
|
||||
conn.execute(
|
||||
"INSERT INTO messages(id, chat_id, sender_id, text) VALUES (%s,%s,%s,%s)",
|
||||
(message_id, uuid.UUID(chat["id"]), actor_id, text),
|
||||
)
|
||||
row = conn.execute("SELECT * FROM messages WHERE id = %s", (message_id,)).fetchone()
|
||||
body = message_public(row)
|
||||
conn.execute(
|
||||
"INSERT INTO idempotency_records"
|
||||
"(user_id, method, path, key, request_hash, status_code, response_body) "
|
||||
"VALUES (%s,%s,%s,%s,%s,%s,%s::jsonb)",
|
||||
(actor_id, "POST", scope_path, key, request_hash, 201,
|
||||
json.dumps(body, ensure_ascii=False)),
|
||||
)
|
||||
return JSONResponse(body, status_code=201)
|
||||
except psycopg.errors.UniqueViolation:
|
||||
# Another replica won the race for this key. Roll back and read its
|
||||
# committed response on the next attempt instead of creating a duplicate.
|
||||
continue
|
||||
raise ApiError(409, "conflict", "Не удалось зафиксировать Idempotency-Key")
|
||||
|
||||
|
||||
@app.get("/api/v1/chats/{chat_id}/messages")
|
||||
async def list_messages(chat_id: str, request: Request):
|
||||
_, chat = authenticated_chat(request, chat_id)
|
||||
limit, cursor = page_params(request)
|
||||
after = decode_cursor(cursor, "messages", chat["id"]) if cursor else None
|
||||
sql = "SELECT * FROM messages WHERE chat_id = %s"
|
||||
params = [uuid.UUID(chat["id"])]
|
||||
if after:
|
||||
sql += " AND (created_at, id) > (%s, %s::uuid)"
|
||||
params.extend([after[0], after[1]])
|
||||
sql += " ORDER BY created_at, id LIMIT %s"
|
||||
params.append(limit + 1)
|
||||
with db.connection() as conn:
|
||||
rows = conn.execute(sql, params).fetchall()
|
||||
items = [message_public(r) for r in rows]
|
||||
return page_response(items, limit, "messages", chat["id"], rows)
|
||||
@@ -0,0 +1,66 @@
|
||||
"""Password KDF and HTTP credential parsing (Basic / opaque Bearer)."""
|
||||
import base64
|
||||
import binascii
|
||||
import hashlib
|
||||
import hmac
|
||||
import os
|
||||
import re
|
||||
|
||||
USERNAME_RE = re.compile(r"[a-z0-9_]{3,32}\Z")
|
||||
SCRYPT_N = 2 ** 14
|
||||
SCRYPT_R = 8
|
||||
SCRYPT_P = 1
|
||||
SCRYPT_LEN = 32
|
||||
|
||||
|
||||
def hash_password(password):
|
||||
salt = os.urandom(16)
|
||||
derived = hashlib.scrypt(
|
||||
password.encode("utf-8"), salt=salt, n=SCRYPT_N, r=SCRYPT_R, p=SCRYPT_P, dklen=SCRYPT_LEN
|
||||
)
|
||||
return "scrypt$%d$%d$%d$%s$%s" % (
|
||||
SCRYPT_N, SCRYPT_R, SCRYPT_P, salt.hex(), derived.hex()
|
||||
)
|
||||
|
||||
|
||||
def verify_password(password, stored):
|
||||
try:
|
||||
scheme, n, r, p, salt_hex, digest_hex = stored.split("$")
|
||||
if scheme != "scrypt":
|
||||
return False
|
||||
derived = hashlib.scrypt(
|
||||
password.encode("utf-8"),
|
||||
salt=bytes.fromhex(salt_hex),
|
||||
n=int(n), r=int(r), p=int(p), dklen=len(bytes.fromhex(digest_hex)),
|
||||
)
|
||||
return hmac.compare_digest(derived, bytes.fromhex(digest_hex))
|
||||
except (ValueError, TypeError):
|
||||
return False
|
||||
|
||||
|
||||
def token_hash(token):
|
||||
return hashlib.sha256(token.encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def parse_basic(header):
|
||||
"""Return (username, password) or None. Colon inside the password is allowed."""
|
||||
if not header or not header.lower().startswith("basic "):
|
||||
return None
|
||||
encoded = header[6:].strip()
|
||||
try:
|
||||
raw = base64.b64decode(encoded, validate=True).decode("utf-8")
|
||||
except (ValueError, UnicodeDecodeError, binascii.Error):
|
||||
return None
|
||||
if ":" not in raw:
|
||||
return None
|
||||
username, password = raw.split(":", 1)
|
||||
if not USERNAME_RE.fullmatch(username) or not 12 <= len(password) <= 128:
|
||||
return None
|
||||
return username, password
|
||||
|
||||
|
||||
def bearer_token(header):
|
||||
if not header or not header.lower().startswith("bearer "):
|
||||
return None
|
||||
token = header[7:].strip()
|
||||
return token or None
|
||||
Reference in New Issue
Block a user