ЛР 3 - БПИ2304 - Евпраксина - на 3 #158

Closed
evpraks wants to merge 1 commits from evpraks/mtusi2026lab3:solution/BPI2304-Evpraksina into main
23 changed files with 727 additions and 14 deletions
+24 -14
View File
@@ -1,18 +1,28 @@
## Лабораторная 3
Автор / группа: TODO
Целевая оценка (3/4/5): TODO
Трек 5, если заявлен: TODO
Автор / группа: Евпраксина Эльвира БПИ2304
Целевая оценка (3/4/5): 3
Трек 5, если заявлен: —
Что реализовано и что перенесено: TODO
Команды запуска из чистого clone: TODO
Результаты проверок и ссылка на REPORT.md: TODO
Ограничения / известные ошибки: TODO
Источники и использование ИИ: TODO
Что реализовано и что перенесено: перенесена lab2 (пользователи, сессии Basic→Bearer, чаты, сообщения, PostgreSQL, миграции, Argon2id). В lab3 добавлено: `X-Instance-Id` и `X-Request-Id` на всех ответах API; обязательный `Idempotency-Key` для `POST /api/v1/chats/{chat_id}/messages` с таблицей `idempotency_keys` и одной транзакцией (`INSERT ... ON CONFLICT DO NOTHING` + `SELECT ... FOR UPDATE`); отдельный одноразовый сервис `migrate`; две API-реплики `api-1`, `api-2` за nginx-LB (`max_fails=1 fail_timeout=2s`, `proxy_next_upstream`); порты API наружу не публикуются; `scripts/restart.sh` и `scripts/stop-one.sh` (плюс `.bat`-эквиваленты для локального прогона `tests/resilience.py` на Windows). Сессии и идемпотентность хранятся в общей PostgreSQL.
- [ ] Весь обязательный минимум текущей и предыдущих работ сохранён с объявленными переходами.
- [ ] Контракт и публичные тесты не ослаблены.
- [ ] make check и make test выполнены; приложен реальный вывод.
- [ ] Сценарии отказов/безопасности своего уровня воспроизведены.
- [ ] Все секреты и приватные ключи находятся вне Git; отчёт не содержит tokens.
- [ ] README задания сохранён, REPORT.md содержит инструкцию именно моего решения.
Команды запуска из чистого clone: см. `REPORT.md` → «Запуск из чистого clone». Кратко:
1. `mkdir -p secrets` и положить в `secrets/pg_password.txt` и `secrets/database_url.txt`; `cp .env.example .env`.
2. `docker compose --env-file .env up -d --build`.
3. Дождаться `curl -fsS http://localhost:8080/health/ready`.
4. `PYTHONUTF8=1 python tests/smoke.py --base-url http://localhost:8080`.
5. `PYTHONUTF8=1 python tests/resilience.py --mode persistence --action-script scripts/restart.sh --base-url http://localhost:8080`.
6. `PYTHONUTF8=1 python tests/resilience.py --mode failover --action-script scripts/stop-one.sh --base-url http://localhost:8080`.
Результаты проверок и ссылка на REPORT.md: публичный smoke — PASS; persistence — PASS; failover (две реплики) — PASS: `observed_instances_before: 2`, `successful_writes: 97`, `failed_attempts: 0`, `first_recovery_seconds: 1.734` и `successful_writes: 95`, `failed_attempts: 0`, `first_recovery_seconds: 1.5`. Через LB наблюдаются оба `X-Instance-Id` (`api-1`, `api-2`). Доказательства — в `evidence/` (`smoke.txt`, `instance-ids.txt`, `headers.txt`, `docker-compose-ps.txt`, `persistence.txt`, `failover-1.txt`, `failover-2.txt`); подробности — в `REPORT.md`.
Ограничения / известные ошибки: один Docker-host, PostgreSQL без реплики, nginx-LB без HA; асинхронная чистка `idempotency_keys` по `IDEMPOTENCY_TTL_SECONDS` не реализована (контракт ≥24 ч не нарушается, таблица растёт). `scripts/*.bat` нужны только для локального прогона на Windows; основной путь — `scripts/*.sh`.
Источники и использование ИИ: FastAPI 0.115, uvicorn 0.30, psycopg 3.2, argon2-cffi, pydantic 2.9, nginx 1.27, PostgreSQL 16.4, Docker Compose v2. ИИ использовался для консультаций по идемпотентности, настройке nginx upstream и разбору ошибок локального запуска.
- [x] Весь обязательный минимум текущей и предыдущих работ сохранён с объявленными переходами.
- [x] Контракт и публичные тесты не ослаблены.
- [x] make check и make test выполнены; приложен реальный вывод.
- [x] Сценарии отказов/безопасности своего уровня воспроизведены.
- [x] Все секреты и приватные ключи находятся вне Git; отчёт не содержит tokens.
- [x] README задания сохранён, REPORT.md содержит инструкцию именно моего решения.
+11
View File
@@ -0,0 +1,11 @@
FROM python:3.12-slim AS runtime
ENV PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY migrations ./migrations
COPY src ./src
RUN useradd -m app && chown -R app /app
USER app
EXPOSE 8080
CMD ["uvicorn", "src.main:app", "--host", "0.0.0.0", "--port", "8080"]
+79
View File
@@ -0,0 +1,79 @@
services:
postgres:
image: postgres:16.4
environment:
POSTGRES_USER: messenger
POSTGRES_PASSWORD_FILE: /run/secrets/pg_password
POSTGRES_DB: messenger
secrets: [pg_password]
volumes:
- pgdata:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U messenger -d messenger"]
interval: 3s
timeout: 3s
retries: 20
migrate:
build: .
depends_on:
postgres:
condition: service_healthy
environment:
DATABASE_URL_FILE: /run/secrets/database_url
secrets: [database_url]
command: ["python", "-c", "from src.db import run_migrations; run_migrations()"]
restart: "no"
api-1:
build: .
depends_on:
migrate:
condition: service_completed_successfully
environment:
SESSION_TTL_SECONDS: "3600"
DATABASE_URL_FILE: /run/secrets/database_url
INSTANCE_ID: api-1
secrets: [database_url]
healthcheck:
test: ["CMD", "python", "-c", "import urllib.request;urllib.request.urlopen('http://localhost:8080/health/ready',timeout=2)"]
interval: 3s
timeout: 3s
retries: 30
api-2:
build: .
depends_on:
migrate:
condition: service_completed_successfully
environment:
SESSION_TTL_SECONDS: "3600"
DATABASE_URL_FILE: /run/secrets/database_url
INSTANCE_ID: api-2
secrets: [database_url]
healthcheck:
test: ["CMD", "python", "-c", "import urllib.request;urllib.request.urlopen('http://localhost:8080/health/ready',timeout=2)"]
interval: 3s
timeout: 3s
retries: 30
lb:
image: nginx:1.27-alpine
ports:
- "8080:8080"
volumes:
- ./nginx/nginx.conf:/etc/nginx/nginx.conf:ro
depends_on:
api-1:
condition: service_healthy
api-2:
condition: service_healthy
secrets:
pg_password:
file: ./secrets/pg_password.txt
database_url:
file: ./secrets/database_url.txt
volumes:
pgdata:
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+40
View File
@@ -0,0 +1,40 @@
CREATE EXTENSION IF NOT EXISTS pgcrypto;
CREATE TABLE IF NOT EXISTS users (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
username text NOT NULL UNIQUE CHECK (username ~ '^[a-z0-9_]{3,32}$'),
display_name text NOT NULL CHECK (char_length(display_name) BETWEEN 1 AND 100),
password_hash text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE IF NOT EXISTS chats (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
title text NOT NULL CHECK (char_length(title) BETWEEN 1 AND 100),
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 DEFAULT gen_random_uuid(),
chat_id uuid NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
sender_id uuid NOT NULL REFERENCES users(id),
text text NOT NULL CHECK (char_length(text) BETWEEN 1 AND 4000),
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS messages_chat_created_idx ON messages (chat_id, created_at, id);
CREATE TABLE IF NOT EXISTS sessions (
token_hash text PRIMARY KEY,
user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,
expires_at timestamptz NOT NULL
);
CREATE INDEX IF NOT EXISTS sessions_user_idx ON sessions (user_id);
CREATE INDEX IF NOT EXISTS sessions_expires_idx ON sessions (expires_at);
+13
View File
@@ -0,0 +1,13 @@
CREATE TABLE IF NOT EXISTS idempotency_keys (
user_id uuid NOT NULL,
method text NOT NULL,
path text NOT NULL,
key text NOT NULL,
request_hash text NOT NULL,
status_code int,
response_body jsonb,
message_id uuid,
created_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (user_id, method, path, key)
);
CREATE INDEX IF NOT EXISTS idempotency_created_idx ON idempotency_keys (created_at);
+24
View File
@@ -0,0 +1,24 @@
worker_processes 1;
events { worker_connections 1024; }
http {
upstream api {
server api-1:8080 max_fails=1 fail_timeout=2s;
server api-2:8080 max_fails=1 fail_timeout=2s;
}
server {
listen 8080;
location / {
proxy_pass http://api;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_next_upstream error timeout http_502 http_503 http_504;
proxy_connect_timeout 1s;
proxy_read_timeout 5s;
}
}
}
+5
View File
@@ -0,0 +1,5 @@
fastapi==0.115.0
uvicorn[standard]==0.30.6
psycopg[binary,pool]==3.2.3
argon2-cffi==23.1.0
pydantic==2.9.2
+9
View File
@@ -0,0 +1,9 @@
@echo off
docker compose --env-file .env restart postgres api-1 api-2 lb
:wait
curl.exe -fsS http://localhost:8080/health/ready >nul 2>&1
if %errorlevel% neq 0 (
timeout /t 1 /nobreak >nul
goto wait
)
exit /b 0
+12
View File
@@ -0,0 +1,12 @@
#!/bin/sh
set -eu
docker compose --env-file .env restart postgres api-1 api-2 lb
i=0
while [ "$i" -lt 90 ]; do
if curl -fsS http://localhost:8080/health/ready >/dev/null 2>&1; then
exit 0
fi
i=$((i + 1))
sleep 1
done
exit 1
+7
View File
@@ -0,0 +1,7 @@
@echo off
if "%TARGET_INSTANCE_ID%"=="" (
echo TARGET_INSTANCE_ID is not set 1>&2
exit /b 2
)
docker compose --env-file .env stop %TARGET_INSTANCE_ID%
exit /b %errorlevel%
+4
View File
@@ -0,0 +1,4 @@
#!/bin/sh
set -eu
: "${TARGET_INSTANCE_ID:?test provides target API instance alias}"
exec docker compose --env-file .env stop "$TARGET_INSTANCE_ID"
View File
+71
View File
@@ -0,0 +1,71 @@
import hashlib
import os
import secrets
from datetime import datetime, timedelta, timezone
from argon2 import PasswordHasher
from argon2.exceptions import VerifyMismatchError
from .db import pool
TTL = int(os.environ.get("SESSION_TTL_SECONDS", "3600"))
hasher = PasswordHasher()
def hash_password(pw: str) -> str:
return hasher.hash(pw)
def verify_password(hash_: str, pw: str) -> bool:
try:
return hasher.verify(hash_, pw)
except VerifyMismatchError:
return False
def _hash_token(token: str) -> str:
return hashlib.sha256(token.encode()).hexdigest()
def create_session(user_id: str):
token = secrets.token_urlsafe(32)
expires = datetime.now(timezone.utc) + timedelta(seconds=TTL)
with pool.connection() as conn:
with conn.cursor() as cur:
cur.execute(
"INSERT INTO sessions (token_hash, user_id, expires_at) VALUES (%s,%s,%s)",
(_hash_token(token), user_id, expires),
)
conn.commit()
return token, expires
def resolve_session(token: str):
with pool.connection() as conn:
with conn.cursor() as cur:
cur.execute(
"SELECT user_id, expires_at FROM sessions WHERE token_hash=%s",
(_hash_token(token),),
)
row = cur.fetchone()
if not row:
return None
user_id, expires = row
if expires <= datetime.now(timezone.utc):
revoke_session(token)
return None
return user_id
def revoke_session(token: str) -> None:
with pool.connection() as conn:
with conn.cursor() as cur:
cur.execute("DELETE FROM sessions WHERE token_hash=%s", (_hash_token(token),))
conn.commit()
def purge_expired() -> None:
with pool.connection() as conn:
with conn.cursor() as cur:
cur.execute("DELETE FROM sessions WHERE expires_at < now()")
conn.commit()
+37
View File
@@ -0,0 +1,37 @@
import os
from contextlib import contextmanager
from pathlib import Path
from psycopg_pool import ConnectionPool
def _read_secret(env_var: str, file_env_var: str) -> str:
if os.environ.get(env_var):
return os.environ[env_var]
path = os.environ.get(file_env_var)
if path and Path(path).is_file():
# Используем utf-8-sig, чтобы игнорировать BOM (невидимый маркер),
# который Windows иногда добавляет в начало файла.
return Path(path).read_text(encoding="utf-8-sig").strip()
raise RuntimeError(f"Neither {env_var} nor {file_env_var} is set")
DATABASE_URL = _read_secret("DATABASE_URL", "DATABASE_URL_FILE")
pool = ConnectionPool(conninfo=DATABASE_URL, min_size=1, max_size=10, open=True)
def run_migrations() -> None:
migrations_dir = Path("migrations")
for f in sorted(migrations_dir.glob("*.sql")):
sql = f.read_text(encoding="utf-8-sig")
with pool.connection() as conn:
with conn.cursor() as cur:
cur.execute(sql)
conn.commit()
@contextmanager
def tx():
with pool.connection() as conn:
with conn.transaction():
yield conn
+40
View File
@@ -0,0 +1,40 @@
import uuid
from fastapi import Request
from fastapi.responses import JSONResponse
from fastapi.exceptions import RequestValidationError
class ApiError(Exception):
def __init__(self, status: int, code: str, message: str, headers=None):
self.status = status
self.code = code
self.message = message
self.headers = headers or {}
def request_id_of(request: Request) -> str:
# Берем ID из состояния запроса, если он там есть
if hasattr(request.state, "request_id"):
return request.state.request_id
# Иначе смотрим в заголовках или генерируем новый
return request.headers.get("X-Request-Id") or uuid.uuid4().hex
async def api_error_handler(request: Request, exc: ApiError):
rid = request_id_of(request)
body = {"error": {"code": exc.code, "message": exc.message, "request_id": rid}}
headers = {"X-Request-Id": rid, **exc.headers}
return JSONResponse(body, status_code=exc.status, headers=headers)
async def unhandled_handler(request: Request, exc: Exception):
rid = request_id_of(request)
body = {"error": {"code": "internal_error", "message": "internal error", "request_id": rid}}
return JSONResponse(body, status_code=500, headers={"X-Request-Id": rid})
async def validation_exception_handler(request: Request, exc: RequestValidationError):
rid = request_id_of(request)
body = {"error": {"code": "invalid_request", "message": "Ошибка валидации данных", "request_id": rid}}
return JSONResponse(body, status_code=400, headers={"X-Request-Id": rid})
+351
View File
@@ -0,0 +1,351 @@
import base64
import hashlib
import json
import os
import re
import secrets
import uuid
from contextlib import asynccontextmanager
from datetime import timezone
from typing import Optional
from fastapi import FastAPI, Header, Request, Response
from fastapi.exceptions import RequestValidationError
from pydantic import BaseModel, Field, field_validator
from .auth import (create_session, hash_password, purge_expired,
resolve_session, revoke_session, verify_password)
from .db import pool, run_migrations, tx
from .errors import (ApiError, api_error_handler, request_id_of,
unhandled_handler, validation_exception_handler)
@asynccontextmanager
async def lifespan(app: FastAPI):
run_migrations()
purge_expired()
yield
app = FastAPI(lifespan=lifespan)
app.add_exception_handler(ApiError, api_error_handler)
app.add_exception_handler(RequestValidationError, validation_exception_handler)
app.add_exception_handler(Exception, unhandled_handler)
INSTANCE_ID = os.environ.get("INSTANCE_ID") or secrets.token_hex(6)
@app.middleware("http")
async def _rid_middleware(request: Request, call_next):
rid = request_id_of(request)
request.state.request_id = rid
response = await call_next(request)
response.headers["X-Request-Id"] = rid
response.headers["X-Instance-Id"] = INSTANCE_ID
return response
USERNAME_RE = r"^[a-z0-9_]{3,32}$"
IDEMPOTENCY_RE = re.compile(r"^[A-Za-z0-9._:-]{1,128}$")
class CreateUser(BaseModel):
username: str = Field(pattern=USERNAME_RE)
display_name: str = Field(min_length=1, max_length=100)
password: str = Field(min_length=12, max_length=128)
class CreateChat(BaseModel):
title: str = Field(min_length=1, max_length=100)
member_ids: list[uuid.UUID] = Field(min_length=1, max_length=100)
@field_validator("member_ids")
@classmethod
def unique_members(cls, v):
if len(set(v)) != len(v):
raise ValueError("duplicate member_ids")
return v
class CreateMessage(BaseModel):
text: str = Field(min_length=1, max_length=4000)
def _iso(dt) -> str:
return dt.astimezone(timezone.utc).isoformat().replace("+00:00", "Z")
def _row_to_user(row) -> dict:
return {"id": str(row[0]), "username": row[1],
"display_name": row[2], "created_at": _iso(row[3])}
def _require_bearer(authorization: Optional[str]) -> str:
if not authorization or not authorization.startswith("Bearer "):
raise ApiError(401, "unauthorized", "Требуется Bearer-токен",
{"WWW-Authenticate": 'Bearer realm="messenger"'})
token = authorization[len("Bearer "):]
user_id = resolve_session(token)
if not user_id:
raise ApiError(401, "unauthorized", "Сессия недействительна",
{"WWW-Authenticate": 'Bearer realm="messenger"'})
return str(user_id)
def _is_member(conn, chat_id: str, user_id: str) -> bool:
with conn.cursor() as cur:
cur.execute("SELECT 1 FROM chat_members WHERE chat_id=%s AND user_id=%s",
(chat_id, user_id))
return cur.fetchone() is not None
@app.get("/health/live")
def live():
return {"status": "ok"}
@app.get("/health/ready")
def ready():
try:
with pool.connection() as conn:
with conn.cursor() as cur:
cur.execute("SELECT 1")
return {"status": "ok"}
except Exception:
raise ApiError(503, "unavailable", "База недоступна")
@app.post("/api/v1/users", status_code=201)
def register(body: CreateUser):
with tx() as conn:
with conn.cursor() as cur:
cur.execute("SELECT 1 FROM users WHERE username=%s", (body.username,))
if cur.fetchone():
raise ApiError(409, "conflict", "Username занят")
cur.execute(
"INSERT INTO users (username, display_name, password_hash) "
"VALUES (%s,%s,%s) RETURNING id, username, display_name, created_at",
(body.username, body.display_name, hash_password(body.password)),
)
row = cur.fetchone()
return _row_to_user(row)
@app.get("/api/v1/users/me")
def me(authorization: Optional[str] = Header(default=None)):
uid = _require_bearer(authorization)
with pool.connection() as conn:
with conn.cursor() as cur:
cur.execute("SELECT id, username, display_name, created_at FROM users WHERE id=%s",
(uid,))
row = cur.fetchone()
if not row:
raise ApiError(401, "unauthorized", "Пользователь не найден",
{"WWW-Authenticate": 'Bearer realm="messenger"'})
return _row_to_user(row)
@app.post("/api/v1/auth/sessions", status_code=201)
def login(authorization: Optional[str] = Header(default=None)):
if not authorization or not authorization.startswith("Basic "):
raise ApiError(401, "unauthorized", "Требуется Basic",
{"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'})
try:
raw = base64.b64decode(authorization[len("Basic "):], validate=True).decode("utf-8")
username, password = raw.split(":", 1)
except Exception:
raise ApiError(400, "invalid_request", "Некорректный Basic")
with pool.connection() as conn:
with conn.cursor() as cur:
cur.execute("SELECT id, password_hash FROM users WHERE username=%s", (username,))
row = cur.fetchone()
if not row or not verify_password(row[1], password):
raise ApiError(401, "unauthorized", "Неверные учётные данные",
{"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'})
token, expires = create_session(str(row[0]))
with pool.connection() as conn:
with conn.cursor() as cur:
cur.execute("SELECT id, username, display_name, created_at FROM users WHERE id=%s",
(row[0],))
u = cur.fetchone()
return {"token": token, "token_type": "Bearer",
"expires_at": _iso(expires), "user": _row_to_user(u)}
@app.delete("/api/v1/auth/sessions/current", status_code=204)
def logout(authorization: Optional[str] = Header(default=None)):
if not authorization or not authorization.startswith("Bearer "):
raise ApiError(401, "unauthorized", "Требуется Bearer",
{"WWW-Authenticate": 'Bearer realm="messenger"'})
token = authorization[len("Bearer "):]
if not resolve_session(token):
raise ApiError(401, "unauthorized", "Сессия недействительна",
{"WWW-Authenticate": 'Bearer realm="messenger"'})
revoke_session(token)
return Response(status_code=204)
def _row_to_chat(row, members) -> dict:
return {"id": str(row[0]), "title": row[1],
"member_ids": [str(m) for m in members], "created_at": _iso(row[2])}
@app.post("/api/v1/chats", status_code=201)
def create_chat(body: CreateChat, authorization: Optional[str] = Header(default=None)):
uid = _require_bearer(authorization)
if uuid.UUID(uid) not in body.member_ids:
raise ApiError(400, "invalid_request", "Вызывающий должен быть в member_ids")
with tx() as conn:
with conn.cursor() as cur:
cur.execute("SELECT id FROM users WHERE id = ANY(%s)",
([str(m) for m in body.member_ids],))
found = {str(r[0]) for r in cur.fetchall()}
if found != {str(m) for m in body.member_ids}:
raise ApiError(400, "invalid_request", "Неизвестный участник")
cur.execute("INSERT INTO chats (title) VALUES (%s) "
"RETURNING id, title, created_at", (body.title,))
row = cur.fetchone()
chat_id = row[0]
cur.executemany("INSERT INTO chat_members (chat_id, user_id) VALUES (%s,%s)",
[(chat_id, str(m)) for m in body.member_ids])
return _row_to_chat(row, body.member_ids)
@app.get("/api/v1/chats")
def list_chats(limit: int = 50, cursor: Optional[str] = None,
authorization: Optional[str] = Header(default=None)):
uid = _require_bearer(authorization)
if not (1 <= limit <= 100):
raise ApiError(400, "invalid_request", "limit 1..100")
with pool.connection() as conn:
with conn.cursor() as cur:
cur.execute(
"SELECT c.id, c.title, c.created_at FROM chats c "
"JOIN chat_members m ON m.chat_id = c.id "
"WHERE m.user_id = %s ORDER BY c.created_at, c.id LIMIT %s",
(uid, limit),
)
rows = cur.fetchall()
items = []
for r in rows:
cur.execute("SELECT user_id FROM chat_members WHERE chat_id=%s", (r[0],))
members = [x[0] for x in cur.fetchall()]
items.append(_row_to_chat(r, members))
return {"items": items, "next_cursor": None}
@app.get("/api/v1/chats/{chat_id}")
def get_chat(chat_id: uuid.UUID, authorization: Optional[str] = Header(default=None)):
uid = _require_bearer(authorization)
with pool.connection() as conn:
if not _is_member(conn, str(chat_id), uid):
raise ApiError(404, "not_found", "Чат не найден")
with conn.cursor() as cur:
cur.execute("SELECT id, title, created_at FROM chats WHERE id=%s", (str(chat_id),))
row = cur.fetchone()
cur.execute("SELECT user_id FROM chat_members WHERE chat_id=%s", (str(chat_id),))
members = [x[0] for x in cur.fetchall()]
return _row_to_chat(row, members)
@app.post("/api/v1/chats/{chat_id}/messages", status_code=201)
def send_message(chat_id: uuid.UUID, body: CreateMessage,
authorization: Optional[str] = Header(default=None),
idempotency_key: Optional[str] = Header(default=None,
alias="Idempotency-Key")):
uid = _require_bearer(authorization)
if not body.text.strip():
raise ApiError(400, "invalid_request", "Пустой текст")
if not idempotency_key or not IDEMPOTENCY_RE.fullmatch(idempotency_key):
raise ApiError(400, "invalid_request", "Неверный Idempotency-Key")
path = f"/api/v1/chats/{chat_id}/messages"
canonical = json.dumps({"text": body.text}, sort_keys=True, ensure_ascii=False)
request_hash = hashlib.sha256(canonical.encode("utf-8")).hexdigest()
with tx() as conn:
if not _is_member(conn, str(chat_id), uid):
raise ApiError(404, "not_found", "Чат не найден")
with conn.cursor() as cur:
cur.execute(
"INSERT INTO idempotency_keys (user_id, method, path, key, request_hash) "
"VALUES (%s, 'POST', %s, %s, %s) ON CONFLICT DO NOTHING",
(uid, path, idempotency_key, request_hash),
)
inserted = cur.rowcount
if inserted == 0:
cur.execute(
"SELECT request_hash, status_code, response_body "
"FROM idempotency_keys "
"WHERE user_id=%s AND method='POST' AND path=%s AND key=%s "
"FOR UPDATE",
(uid, path, idempotency_key),
)
rh, sc, rb = cur.fetchone()
if rh != request_hash:
raise ApiError(409, "conflict",
"Idempotency-Key переиспользован с другим body")
if rb is not None:
return rb
raise ApiError(409, "conflict", "Запрос ещё выполняется")
cur.execute(
"INSERT INTO messages (chat_id, sender_id, text) VALUES (%s,%s,%s) "
"RETURNING id, chat_id, sender_id, text, created_at",
(str(chat_id), uid, body.text),
)
row = cur.fetchone()
result = {"id": str(row[0]), "chat_id": str(row[1]), "sender_id": str(row[2]),
"text": row[3], "created_at": _iso(row[4])}
cur.execute(
"UPDATE idempotency_keys "
"SET status_code=201, response_body=%s, message_id=%s "
"WHERE user_id=%s AND method='POST' AND path=%s AND key=%s",
(json.dumps(result), row[0], uid, path, idempotency_key),
)
return result
@app.get("/api/v1/chats/{chat_id}/messages")
def list_messages(chat_id: uuid.UUID, limit: int = 50, cursor: Optional[str] = None,
authorization: Optional[str] = Header(default=None)):
uid = _require_bearer(authorization)
if not (1 <= limit <= 100):
raise ApiError(400, "invalid_request", "limit 1..100")
with pool.connection() as conn:
if not _is_member(conn, str(chat_id), uid):
raise ApiError(404, "not_found", "Чат не найден")
params = [str(chat_id)]
where = "chat_id=%s"
if cursor:
try:
ts, mid = cursor.split("|")
params += [ts, mid]
where += " AND (created_at, id) > (%s::timestamptz, %s::uuid)"
except Exception:
raise ApiError(400, "invalid_request", "Неверный cursor")
params.append(limit + 1)
with conn.cursor() as cur:
cur.execute(
f"SELECT id, chat_id, sender_id, text, created_at FROM messages "
f"WHERE {where} ORDER BY created_at, id LIMIT %s", params)
rows = cur.fetchall()
has_more = len(rows) > limit
if has_more:
rows = rows[:limit]
items = [{"id": str(r[0]), "chat_id": str(r[1]), "sender_id": str(r[2]),
"text": r[3], "created_at": _iso(r[4])} for r in rows]
next_cursor = None
if has_more and rows:
last = rows[-1]
next_cursor = f"{last[4].isoformat()}|{last[0]}"
return {"items": items, "next_cursor": next_cursor}