Релизованный минимум на 3, подготовка к написанию REPORT.md
This commit is contained in:
@@ -1,15 +1,12 @@
|
|||||||
FROM python:3.11-slim
|
FROM python:3.11-slim
|
||||||
|
|
||||||
# Устанавливаем curl для healthcheck
|
|
||||||
RUN apt-get update && apt-get install -y curl && rm -rf /var/lib/apt/lists/*
|
RUN apt-get update && apt-get install -y curl && rm -rf /var/lib/apt/lists/*
|
||||||
|
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|
||||||
# Копируем зависимости
|
|
||||||
COPY requirements.txt .
|
COPY requirements.txt .
|
||||||
RUN pip install --no-cache-dir -r requirements.txt
|
RUN pip install --no-cache-dir -r requirements.txt
|
||||||
|
|
||||||
# Копируем исходный код
|
|
||||||
COPY src/ ./src/
|
COPY src/ ./src/
|
||||||
|
|
||||||
ENV HOST=0.0.0.0
|
ENV HOST=0.0.0.0
|
||||||
|
|||||||
+53
-25
@@ -1,35 +1,63 @@
|
|||||||
services:
|
services:
|
||||||
api:
|
postgres:
|
||||||
build: .
|
image: postgres:16.4-alpine
|
||||||
ports:
|
|
||||||
- "8080:8080"
|
|
||||||
environment:
|
environment:
|
||||||
- DATABASE_URL=postgresql://messenger:messenger_pass@postgres:5432/messenger
|
POSTGRES_USER: messenger
|
||||||
- SESSION_TTL_SECONDS=3600
|
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-messenger_pass}
|
||||||
|
POSTGRES_DB: messenger
|
||||||
|
volumes:
|
||||||
|
- pgdata:/var/lib/postgresql/data
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD-SHELL", "pg_isready -U messenger"]
|
||||||
|
interval: 3s
|
||||||
|
timeout: 3s
|
||||||
|
retries: 20
|
||||||
|
networks: [backend]
|
||||||
|
|
||||||
|
api-1:
|
||||||
|
build: .
|
||||||
|
environment:
|
||||||
|
DATABASE_URL: postgresql://messenger:${POSTGRES_PASSWORD:-messenger_pass}@postgres:5432/messenger
|
||||||
|
INSTANCE_ID: api-1
|
||||||
|
SESSION_TTL_SECONDS: "3600"
|
||||||
depends_on:
|
depends_on:
|
||||||
postgres:
|
postgres:
|
||||||
condition: service_healthy
|
condition: service_healthy
|
||||||
healthcheck:
|
stop_grace_period: 15s
|
||||||
test: ["CMD", "curl", "-f", "http://localhost:8080/health/ready"]
|
deploy:
|
||||||
interval: 5s
|
resources:
|
||||||
timeout: 3s
|
limits: { cpus: "0.5", memory: 256M }
|
||||||
retries: 5
|
networks: [backend]
|
||||||
restart: unless-stopped
|
# порты наружу НЕ публикуем
|
||||||
|
|
||||||
postgres:
|
api-2:
|
||||||
image: postgres:16.1
|
build: .
|
||||||
environment:
|
environment:
|
||||||
- POSTGRES_DB=messenger
|
DATABASE_URL: postgresql://messenger:${POSTGRES_PASSWORD:-messenger_pass}@postgres:5432/messenger
|
||||||
- POSTGRES_USER=messenger
|
INSTANCE_ID: api-2
|
||||||
- POSTGRES_PASSWORD=messenger_pass
|
SESSION_TTL_SECONDS: "3600"
|
||||||
|
depends_on:
|
||||||
|
postgres:
|
||||||
|
condition: service_healthy
|
||||||
|
stop_grace_period: 15s
|
||||||
|
deploy:
|
||||||
|
resources:
|
||||||
|
limits: { cpus: "0.5", memory: 256M }
|
||||||
|
networks: [backend]
|
||||||
|
|
||||||
|
lb:
|
||||||
|
image: nginx:1.27-alpine
|
||||||
|
ports:
|
||||||
|
- "8080:8080"
|
||||||
volumes:
|
volumes:
|
||||||
- postgres_data:/var/lib/postgresql/data
|
- ./nginx/lb.conf:/etc/nginx/nginx.conf:ro
|
||||||
healthcheck:
|
depends_on:
|
||||||
test: ["CMD-SHELL", "pg_isready -U messenger"]
|
- api-1
|
||||||
interval: 5s
|
- api-2
|
||||||
timeout: 3s
|
networks: [backend]
|
||||||
retries: 5
|
|
||||||
restart: unless-stopped
|
|
||||||
|
|
||||||
volumes:
|
volumes:
|
||||||
postgres_data:
|
pgdata:
|
||||||
|
|
||||||
|
networks:
|
||||||
|
backend:
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
worker_processes 1;
|
||||||
|
|
||||||
|
events { worker_connections 1024; }
|
||||||
|
|
||||||
|
http {
|
||||||
|
upstream api_backend {
|
||||||
|
server api-1:8080 max_fails=2 fail_timeout=5s;
|
||||||
|
server api-2:8080 max_fails=2 fail_timeout=5s;
|
||||||
|
}
|
||||||
|
|
||||||
|
server {
|
||||||
|
listen 8080;
|
||||||
|
server_name _;
|
||||||
|
|
||||||
|
location / {
|
||||||
|
proxy_pass http://api_backend;
|
||||||
|
proxy_http_version 1.1;
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header Connection "";
|
||||||
|
proxy_connect_timeout 2s;
|
||||||
|
proxy_send_timeout 30s;
|
||||||
|
proxy_read_timeout 30s;
|
||||||
|
proxy_next_upstream error timeout http_502 http_503 http_504;
|
||||||
|
proxy_next_upstream_tries 2;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+3
-13
@@ -1,15 +1,5 @@
|
|||||||
@echo off
|
@echo off
|
||||||
cd /d %~dp0\..
|
cd /d %~dp0\..
|
||||||
docker compose restart api postgres
|
echo Restarting API and Database...
|
||||||
|
docker compose restart api-1 api-2 postgres
|
||||||
set /a count=0
|
exit /b 0
|
||||||
:check_loop
|
|
||||||
timeout /t 2 /nobreak >nul
|
|
||||||
curl -s -f http://localhost:8080/health/ready >nul 2>&1
|
|
||||||
if %errorlevel% equ 0 exit /b 0
|
|
||||||
|
|
||||||
set /a count+=1
|
|
||||||
if %count% lss 15 goto check_loop
|
|
||||||
|
|
||||||
echo API failed to become ready
|
|
||||||
exit /b 1
|
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
@echo off
|
||||||
|
setlocal
|
||||||
|
cd /d %~dp0\..
|
||||||
|
if "%TARGET_INSTANCE_ID%"=="" (
|
||||||
|
echo TARGET_INSTANCE_ID is not set 1>&2
|
||||||
|
exit /b 2
|
||||||
|
)
|
||||||
|
if "%TARGET_INSTANCE_ID%"=="api-1" (set svc=api-1) else if "%TARGET_INSTANCE_ID%"=="api-2" (set svc=api-2) else (
|
||||||
|
echo unknown TARGET_INSTANCE_ID: %TARGET_INSTANCE_ID% 1>&2
|
||||||
|
exit /b 2
|
||||||
|
)
|
||||||
|
docker compose stop %svc%
|
||||||
|
exit /b %errorlevel%
|
||||||
+209
-223
@@ -1,4 +1,6 @@
|
|||||||
import os
|
import os
|
||||||
|
import glob
|
||||||
|
import json
|
||||||
import psycopg2
|
import psycopg2
|
||||||
from psycopg2.extras import RealDictCursor
|
from psycopg2.extras import RealDictCursor
|
||||||
from typing import Optional, List, Dict, Any, Tuple
|
from typing import Optional, List, Dict, Any, Tuple
|
||||||
@@ -7,17 +9,19 @@ from uuid import uuid4
|
|||||||
from datetime import datetime, timezone
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
|
|
||||||
DATABASE_URL = os.getenv("DATABASE_URL", "postgresql://messenger:messenger_pass@localhost:5432/messenger")
|
DATABASE_URL = os.getenv(
|
||||||
|
"DATABASE_URL",
|
||||||
|
"postgresql://messenger:messenger_pass@localhost:5432/messenger"
|
||||||
|
)
|
||||||
|
MIGRATIONS_DIR = os.path.join(os.path.dirname(__file__), "migrations")
|
||||||
|
|
||||||
|
|
||||||
def get_db_connection():
|
def get_db_connection():
|
||||||
"""Создать подключение к PostgreSQL"""
|
|
||||||
return psycopg2.connect(DATABASE_URL, cursor_factory=RealDictCursor)
|
return psycopg2.connect(DATABASE_URL, cursor_factory=RealDictCursor)
|
||||||
|
|
||||||
|
|
||||||
@contextmanager
|
@contextmanager
|
||||||
def get_db():
|
def get_db():
|
||||||
"""Контекстный менеджер для работы с БД"""
|
|
||||||
conn = get_db_connection()
|
conn = get_db_connection()
|
||||||
try:
|
try:
|
||||||
yield conn
|
yield conn
|
||||||
@@ -30,266 +34,248 @@ def get_db():
|
|||||||
|
|
||||||
|
|
||||||
def init_db():
|
def init_db():
|
||||||
"""Инициализировать БД (запустить миграции idempotently)"""
|
"""Прогнать все миграции по порядку (idempotent)."""
|
||||||
migration_path = os.path.join(os.path.dirname(__file__), "migrations", "001_initial.sql")
|
files = sorted(glob.glob(os.path.join(MIGRATIONS_DIR, "*.sql")))
|
||||||
with open(migration_path, "r") as f:
|
if not files:
|
||||||
migration_sql = f.read()
|
raise RuntimeError(f"No migrations found in {MIGRATIONS_DIR}")
|
||||||
|
|
||||||
with get_db() as conn:
|
with get_db() as conn:
|
||||||
with conn.cursor() as cur:
|
with conn.cursor() as cur:
|
||||||
cur.execute(migration_sql)
|
for path in files:
|
||||||
|
with open(path, "r") as f:
|
||||||
|
cur.execute(f.read())
|
||||||
|
print(f"[init_db] applied {len(files)} migration(s): "
|
||||||
|
f"{[os.path.basename(p) for p in files]}")
|
||||||
|
|
||||||
|
|
||||||
class PostgresStore:
|
class PostgresStore:
|
||||||
"""Store layer для PostgreSQL — заменяет InMemoryStore из Lab 1"""
|
|
||||||
|
|
||||||
|
# ---------- users ----------
|
||||||
def create_user(self, username: str, display_name: str, password_hash: str) -> dict:
|
def create_user(self, username: str, display_name: str, password_hash: str) -> dict:
|
||||||
with get_db() as conn:
|
with get_db() as conn:
|
||||||
with conn.cursor() as cur:
|
with conn.cursor() as cur:
|
||||||
# Проверяем уникальность username
|
|
||||||
cur.execute("SELECT id FROM users WHERE username = %s", (username,))
|
cur.execute("SELECT id FROM users WHERE username = %s", (username,))
|
||||||
if cur.fetchone():
|
if cur.fetchone():
|
||||||
raise ValueError("username_already_exists")
|
raise ValueError("username_already_exists")
|
||||||
|
|
||||||
user_id = str(uuid4())
|
user_id = str(uuid4())
|
||||||
now = datetime.now(timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ')
|
now = datetime.now(timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ')
|
||||||
|
|
||||||
cur.execute(
|
cur.execute(
|
||||||
"INSERT INTO users (id, username, display_name, password_hash, created_at) "
|
"INSERT INTO users (id, username, display_name, password_hash, created_at) "
|
||||||
"VALUES (%s, %s, %s, %s, %s)",
|
"VALUES (%s, %s, %s, %s, %s)",
|
||||||
(user_id, username, display_name, password_hash, now)
|
(user_id, username, display_name, password_hash, now)
|
||||||
)
|
)
|
||||||
|
return {"id": user_id, "username": username,
|
||||||
return {
|
"display_name": display_name, "created_at": now}
|
||||||
"id": user_id,
|
|
||||||
"username": username,
|
|
||||||
"display_name": display_name,
|
|
||||||
"created_at": now
|
|
||||||
}
|
|
||||||
|
|
||||||
def get_user(self, user_id: str) -> Optional[dict]:
|
def get_user(self, user_id: str) -> Optional[dict]:
|
||||||
with get_db() as conn:
|
with get_db() as conn, conn.cursor() as cur:
|
||||||
with conn.cursor() as cur:
|
cur.execute(
|
||||||
cur.execute(
|
"SELECT id, username, display_name, created_at FROM users WHERE id = %s",
|
||||||
"SELECT id, username, display_name, created_at FROM users WHERE id = %s",
|
(user_id,))
|
||||||
(user_id,)
|
row = cur.fetchone()
|
||||||
)
|
if row:
|
||||||
row = cur.fetchone()
|
row["created_at"] = row["created_at"].strftime('%Y-%m-%dT%H:%M:%SZ')
|
||||||
if row:
|
return row
|
||||||
# Преобразуем datetime в строку ISO8601
|
|
||||||
row["created_at"] = row["created_at"].strftime('%Y-%m-%dT%H:%M:%SZ')
|
|
||||||
return row
|
|
||||||
|
|
||||||
def get_user_by_username(self, username: str) -> Optional[dict]:
|
def get_user_by_username(self, username: str) -> Optional[dict]:
|
||||||
with get_db() as conn:
|
with get_db() as conn, conn.cursor() as cur:
|
||||||
with conn.cursor() as cur:
|
cur.execute(
|
||||||
cur.execute(
|
"SELECT id, username, display_name, password_hash, created_at "
|
||||||
"SELECT id, username, display_name, password_hash, created_at FROM users WHERE username = %s",
|
"FROM users WHERE username = %s", (username,))
|
||||||
(username,)
|
row = cur.fetchone()
|
||||||
)
|
if row:
|
||||||
row = cur.fetchone()
|
row["created_at"] = row["created_at"].strftime('%Y-%m-%dT%H:%M:%SZ')
|
||||||
if row:
|
return row
|
||||||
# Преобразуем datetime в строку ISO8601
|
|
||||||
row["created_at"] = row["created_at"].strftime('%Y-%m-%dT%H:%M:%SZ')
|
|
||||||
return row
|
|
||||||
|
|
||||||
|
# ---------- chats ----------
|
||||||
def create_chat(self, title: str, member_ids: List[str], creator_id: str) -> dict:
|
def create_chat(self, title: str, member_ids: List[str], creator_id: str) -> dict:
|
||||||
with get_db() as conn:
|
with get_db() as conn, conn.cursor() as cur:
|
||||||
with conn.cursor() as cur:
|
for member_id in member_ids:
|
||||||
# Проверяем, что все участники существуют
|
cur.execute("SELECT id FROM users WHERE id = %s", (member_id,))
|
||||||
for member_id in member_ids:
|
if not cur.fetchone():
|
||||||
cur.execute("SELECT id FROM users WHERE id = %s", (member_id,))
|
raise ValueError("user_not_found")
|
||||||
if not cur.fetchone():
|
if creator_id not in member_ids:
|
||||||
raise ValueError("user_not_found")
|
raise ValueError("creator_not_in_members")
|
||||||
|
if len(member_ids) != len(set(member_ids)):
|
||||||
# Проверяем, что создатель входит в список участников
|
raise ValueError("duplicate_members")
|
||||||
if creator_id not in member_ids:
|
chat_id = str(uuid4())
|
||||||
raise ValueError("creator_not_in_members")
|
now = datetime.now(timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ')
|
||||||
|
cur.execute(
|
||||||
# Проверяем уникальность member_ids
|
"INSERT INTO chats (id, title, created_at) VALUES (%s, %s, %s)",
|
||||||
if len(member_ids) != len(set(member_ids)):
|
(chat_id, title, now))
|
||||||
raise ValueError("duplicate_members")
|
for member_id in member_ids:
|
||||||
|
|
||||||
chat_id = str(uuid4())
|
|
||||||
now = datetime.now(timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ')
|
|
||||||
|
|
||||||
# Атомарно: создаём чат и всех участников в одной транзакции
|
|
||||||
cur.execute(
|
cur.execute(
|
||||||
"INSERT INTO chats (id, title, created_at) VALUES (%s, %s, %s)",
|
"INSERT INTO chat_members (chat_id, user_id) VALUES (%s, %s)",
|
||||||
(chat_id, title, now)
|
(chat_id, member_id))
|
||||||
)
|
return {"id": chat_id, "title": title,
|
||||||
|
"member_ids": member_ids, "created_at": now}
|
||||||
for member_id in member_ids:
|
|
||||||
cur.execute(
|
|
||||||
"INSERT INTO chat_members (chat_id, user_id) VALUES (%s, %s)",
|
|
||||||
(chat_id, member_id)
|
|
||||||
)
|
|
||||||
|
|
||||||
return {
|
|
||||||
"id": chat_id,
|
|
||||||
"title": title,
|
|
||||||
"member_ids": member_ids,
|
|
||||||
"created_at": now
|
|
||||||
}
|
|
||||||
|
|
||||||
def get_chat(self, chat_id: str, user_id: str) -> Optional[dict]:
|
def get_chat(self, chat_id: str, user_id: str) -> Optional[dict]:
|
||||||
with get_db() as conn:
|
with get_db() as conn, conn.cursor() as cur:
|
||||||
with conn.cursor() as cur:
|
cur.execute(
|
||||||
cur.execute(
|
"SELECT c.id, c.title, c.created_at FROM chats c "
|
||||||
"SELECT c.id, c.title, c.created_at "
|
"JOIN chat_members cm ON c.id = cm.chat_id "
|
||||||
"FROM chats c "
|
"WHERE c.id = %s AND cm.user_id = %s",
|
||||||
"JOIN chat_members cm ON c.id = cm.chat_id "
|
(chat_id, user_id))
|
||||||
"WHERE c.id = %s AND cm.user_id = %s",
|
chat = cur.fetchone()
|
||||||
(chat_id, user_id)
|
if not chat:
|
||||||
)
|
return None
|
||||||
chat = cur.fetchone()
|
cur.execute(
|
||||||
if not chat:
|
"SELECT user_id FROM chat_members WHERE chat_id = %s ORDER BY user_id",
|
||||||
return None
|
(chat_id,))
|
||||||
|
members = [row["user_id"] for row in cur.fetchall()]
|
||||||
|
return {"id": chat["id"], "title": chat["title"],
|
||||||
|
"member_ids": members,
|
||||||
|
"created_at": chat["created_at"].strftime('%Y-%m-%dT%H:%M:%SZ')}
|
||||||
|
|
||||||
# Получаем список участников
|
def list_chats(self, user_id: str, limit: int = 50,
|
||||||
|
cursor: Optional[str] = None) -> Tuple[List[dict], Optional[str]]:
|
||||||
|
with get_db() as conn, conn.cursor() as cur:
|
||||||
|
query = ("SELECT c.id, c.title, c.created_at FROM chats c "
|
||||||
|
"JOIN chat_members cm ON c.id = cm.chat_id "
|
||||||
|
"WHERE cm.user_id = %s")
|
||||||
|
params: List[Any] = [user_id]
|
||||||
|
if cursor:
|
||||||
|
parts = cursor.split(",", 1)
|
||||||
|
if len(parts) == 2:
|
||||||
|
query += " AND (c.created_at, c.id) > (%s::timestamptz, %s::uuid)"
|
||||||
|
params.extend(parts)
|
||||||
|
query += " ORDER BY c.created_at, c.id LIMIT %s"
|
||||||
|
params.append(limit + 1)
|
||||||
|
cur.execute(query, params)
|
||||||
|
rows = cur.fetchall()
|
||||||
|
has_more = len(rows) > limit
|
||||||
|
page = rows[:limit]
|
||||||
|
chats = []
|
||||||
|
for row in page:
|
||||||
cur.execute(
|
cur.execute(
|
||||||
"SELECT user_id FROM chat_members WHERE chat_id = %s ORDER BY user_id",
|
"SELECT user_id FROM chat_members WHERE chat_id = %s ORDER BY user_id",
|
||||||
(chat_id,)
|
(row["id"],))
|
||||||
)
|
chats.append({
|
||||||
members = [row["user_id"] for row in cur.fetchall()]
|
"id": row["id"], "title": row["title"],
|
||||||
|
"member_ids": [m["user_id"] for m in cur.fetchall()],
|
||||||
|
"created_at": row["created_at"].strftime('%Y-%m-%dT%H:%M:%SZ')})
|
||||||
|
next_cursor = None
|
||||||
|
if has_more and page:
|
||||||
|
last = page[-1]
|
||||||
|
next_cursor = (f"{last['created_at'].strftime('%Y-%m-%dT%H:%M:%SZ')},"
|
||||||
|
f"{last['id']}")
|
||||||
|
return chats, next_cursor
|
||||||
|
|
||||||
return {
|
# ---------- messages ----------
|
||||||
"id": chat["id"],
|
def list_messages(self, chat_id: str, user_id: str, limit: int = 50,
|
||||||
"title": chat["title"],
|
cursor: Optional[str] = None) -> Tuple[List[dict], Optional[str]]:
|
||||||
"member_ids": members,
|
with get_db() as conn, conn.cursor() as cur:
|
||||||
"created_at": chat["created_at"].strftime('%Y-%m-%dT%H:%M:%SZ')
|
cur.execute(
|
||||||
}
|
"SELECT 1 FROM chat_members WHERE chat_id = %s AND user_id = %s",
|
||||||
|
(chat_id, user_id))
|
||||||
|
if not cur.fetchone():
|
||||||
|
cur.execute("SELECT id FROM chats WHERE id = %s", (chat_id,))
|
||||||
|
if cur.fetchone():
|
||||||
|
raise ValueError("user_not_in_chat")
|
||||||
|
raise ValueError("chat_not_found")
|
||||||
|
query = ("SELECT id, chat_id, sender_id, text, created_at "
|
||||||
|
"FROM messages WHERE chat_id = %s")
|
||||||
|
params: List[Any] = [chat_id]
|
||||||
|
if cursor:
|
||||||
|
parts = cursor.split(",", 1)
|
||||||
|
if len(parts) == 2:
|
||||||
|
query += " AND (created_at, id) > (%s::timestamptz, %s::uuid)"
|
||||||
|
params.extend(parts)
|
||||||
|
query += " ORDER BY created_at, id LIMIT %s"
|
||||||
|
params.append(limit + 1)
|
||||||
|
cur.execute(query, params)
|
||||||
|
rows = cur.fetchall()
|
||||||
|
has_more = len(rows) > limit
|
||||||
|
page = rows[:limit]
|
||||||
|
messages = [{
|
||||||
|
"id": r["id"], "chat_id": r["chat_id"], "sender_id": r["sender_id"],
|
||||||
|
"text": r["text"],
|
||||||
|
"created_at": r["created_at"].strftime('%Y-%m-%dT%H:%M:%SZ')
|
||||||
|
} for r in page]
|
||||||
|
next_cursor = None
|
||||||
|
if has_more and page:
|
||||||
|
last = page[-1]
|
||||||
|
next_cursor = (f"{last['created_at'].strftime('%Y-%m-%dT%H:%M:%SZ')},"
|
||||||
|
f"{last['id']}")
|
||||||
|
return messages, next_cursor
|
||||||
|
|
||||||
def list_chats(self, user_id: str, limit: int = 50, cursor: Optional[str] = None) -> Tuple[List[dict], Optional[str]]:
|
# ---------- messages + idempotency (lab3) ----------
|
||||||
with get_db() as conn:
|
def get_idempotent_result(self, user_id: str, method: str, path: str,
|
||||||
with conn.cursor() as cur:
|
key: str) -> Optional[dict]:
|
||||||
query = """
|
with get_db() as conn, conn.cursor() as cur:
|
||||||
SELECT c.id, c.title, c.created_at
|
cur.execute(
|
||||||
FROM chats c
|
"SELECT request_hash, status_code, response_body "
|
||||||
JOIN chat_members cm ON c.id = cm.chat_id
|
"FROM idempotency_keys "
|
||||||
WHERE cm.user_id = %s
|
"WHERE user_id=%s AND method=%s AND path=%s AND key=%s",
|
||||||
"""
|
(user_id, method, path, key))
|
||||||
params = [user_id]
|
return cur.fetchone()
|
||||||
|
|
||||||
if cursor:
|
def create_message_idempotent(self, chat_id: str, sender_id: str, text: str,
|
||||||
cursor_parts = cursor.split(",", 1)
|
idem_key: str, path: str, request_hash: str) -> dict:
|
||||||
if len(cursor_parts) == 2:
|
"""
|
||||||
cursor_time, cursor_id = cursor_parts
|
Атомарно: проверка членства + вставка сообщения + запись ключа идемпотентности.
|
||||||
query += " AND (c.created_at, c.id) > (%s::timestamptz, %s::uuid)"
|
На гонку уникальности ключа возвращает сохранённый ранее ответ.
|
||||||
params.extend([cursor_time, cursor_id])
|
На конфликт хэша (другой payload с тем же ключом) — ValueError('idempotency_conflict').
|
||||||
|
"""
|
||||||
|
with get_db() as conn, conn.cursor() as cur:
|
||||||
|
# 1. Проверить, не записан ли уже ключ
|
||||||
|
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",
|
||||||
|
(sender_id, path, idem_key))
|
||||||
|
existing = cur.fetchone()
|
||||||
|
if existing:
|
||||||
|
if existing["request_hash"] != request_hash:
|
||||||
|
raise ValueError("idempotency_conflict")
|
||||||
|
return existing["response_body"]
|
||||||
|
|
||||||
query += " ORDER BY c.created_at, c.id LIMIT %s"
|
# 2. Проверить членство в чате
|
||||||
params.append(limit + 1) # Берём на 1 больше для определения has_more
|
cur.execute(
|
||||||
|
"SELECT 1 FROM chat_members WHERE chat_id = %s AND user_id = %s",
|
||||||
|
(chat_id, sender_id))
|
||||||
|
if not cur.fetchone():
|
||||||
|
cur.execute("SELECT id FROM chats WHERE id = %s", (chat_id,))
|
||||||
|
if cur.fetchone():
|
||||||
|
raise ValueError("sender_not_in_chat")
|
||||||
|
raise ValueError("chat_not_found")
|
||||||
|
|
||||||
cur.execute(query, params)
|
# 3. Вставить сообщение
|
||||||
rows = cur.fetchall()
|
message_id = str(uuid4())
|
||||||
|
now = datetime.now(timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ')
|
||||||
|
cur.execute(
|
||||||
|
"INSERT INTO messages (id, chat_id, sender_id, text, created_at) "
|
||||||
|
"VALUES (%s, %s, %s, %s, %s)",
|
||||||
|
(message_id, chat_id, sender_id, text, now))
|
||||||
|
message = {
|
||||||
|
"id": message_id, "chat_id": chat_id, "sender_id": sender_id,
|
||||||
|
"text": text, "created_at": now
|
||||||
|
}
|
||||||
|
|
||||||
has_more = len(rows) > limit
|
# 4. Записать ключ идемпотентности (гонку закроет PK)
|
||||||
page_rows = rows[:limit]
|
try:
|
||||||
|
|
||||||
chats = []
|
|
||||||
for row in page_rows:
|
|
||||||
cur.execute(
|
|
||||||
"SELECT user_id FROM chat_members WHERE chat_id = %s ORDER BY user_id",
|
|
||||||
(row["id"],)
|
|
||||||
)
|
|
||||||
members = [m["user_id"] for m in cur.fetchall()]
|
|
||||||
chats.append({
|
|
||||||
"id": row["id"],
|
|
||||||
"title": row["title"],
|
|
||||||
"member_ids": members,
|
|
||||||
"created_at": row["created_at"].strftime('%Y-%m-%dT%H:%M:%SZ')
|
|
||||||
})
|
|
||||||
|
|
||||||
next_cursor = None
|
|
||||||
if has_more and chats:
|
|
||||||
last = page_rows[-1]
|
|
||||||
next_cursor = f"{last['created_at'].strftime('%Y-%m-%dT%H:%M:%SZ')},{last['id']}"
|
|
||||||
|
|
||||||
return chats, next_cursor
|
|
||||||
|
|
||||||
def create_message(self, chat_id: str, sender_id: str, text: str) -> dict:
|
|
||||||
with get_db() as conn:
|
|
||||||
with conn.cursor() as cur:
|
|
||||||
# Проверяем, что чат существует и отправитель является участником
|
|
||||||
cur.execute(
|
cur.execute(
|
||||||
"SELECT 1 FROM chat_members WHERE chat_id = %s AND user_id = %s",
|
"INSERT INTO idempotency_keys "
|
||||||
(chat_id, sender_id)
|
"(user_id, method, path, key, request_hash, status_code, response_body) "
|
||||||
)
|
"VALUES (%s, 'POST', %s, %s, %s, 201, %s)",
|
||||||
if not cur.fetchone():
|
(sender_id, path, idem_key, request_hash,
|
||||||
cur.execute("SELECT id FROM chats WHERE id = %s", (chat_id,))
|
json.dumps(message)))
|
||||||
if cur.fetchone():
|
except psycopg2.errors.UniqueViolation:
|
||||||
raise ValueError("sender_not_in_chat")
|
# Параллельный запрос успел первым — откатываем свою вставку сообщения
|
||||||
raise ValueError("chat_not_found")
|
conn.rollback()
|
||||||
|
|
||||||
message_id = str(uuid4())
|
|
||||||
now = datetime.now(timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ')
|
|
||||||
|
|
||||||
cur.execute(
|
cur.execute(
|
||||||
"INSERT INTO messages (id, chat_id, sender_id, text, created_at) "
|
"SELECT request_hash, status_code, response_body "
|
||||||
"VALUES (%s, %s, %s, %s, %s)",
|
"FROM idempotency_keys "
|
||||||
(message_id, chat_id, sender_id, text, now)
|
"WHERE user_id=%s AND method='POST' AND path=%s AND key=%s",
|
||||||
)
|
(sender_id, path, idem_key))
|
||||||
|
row = cur.fetchone()
|
||||||
|
if not row:
|
||||||
|
raise
|
||||||
|
if row["request_hash"] != request_hash:
|
||||||
|
raise ValueError("idempotency_conflict")
|
||||||
|
return row["response_body"]
|
||||||
|
|
||||||
return {
|
return message
|
||||||
"id": message_id,
|
|
||||||
"chat_id": chat_id,
|
|
||||||
"sender_id": sender_id,
|
|
||||||
"text": text,
|
|
||||||
"created_at": now
|
|
||||||
}
|
|
||||||
|
|
||||||
def list_messages(self, chat_id: str, user_id: str, limit: int = 50, cursor: Optional[str] = None) -> Tuple[List[dict], Optional[str]]:
|
|
||||||
with get_db() as conn:
|
|
||||||
with conn.cursor() as cur:
|
|
||||||
# Проверяем, что пользователь является участником чата
|
|
||||||
cur.execute(
|
|
||||||
"SELECT 1 FROM chat_members WHERE chat_id = %s AND user_id = %s",
|
|
||||||
(chat_id, user_id)
|
|
||||||
)
|
|
||||||
if not cur.fetchone():
|
|
||||||
cur.execute("SELECT id FROM chats WHERE id = %s", (chat_id,))
|
|
||||||
if cur.fetchone():
|
|
||||||
raise ValueError("user_not_in_chat")
|
|
||||||
raise ValueError("chat_not_found")
|
|
||||||
|
|
||||||
query = """
|
|
||||||
SELECT id, chat_id, sender_id, text, created_at
|
|
||||||
FROM messages
|
|
||||||
WHERE chat_id = %s
|
|
||||||
"""
|
|
||||||
params = [chat_id]
|
|
||||||
|
|
||||||
if cursor:
|
|
||||||
cursor_parts = cursor.split(",", 1)
|
|
||||||
if len(cursor_parts) == 2:
|
|
||||||
cursor_time, cursor_id = cursor_parts
|
|
||||||
query += " AND (created_at, id) > (%s::timestamptz, %s::uuid)"
|
|
||||||
params.extend([cursor_time, cursor_id])
|
|
||||||
|
|
||||||
query += " ORDER BY created_at, id LIMIT %s"
|
|
||||||
params.append(limit + 1)
|
|
||||||
|
|
||||||
cur.execute(query, params)
|
|
||||||
rows = cur.fetchall()
|
|
||||||
|
|
||||||
has_more = len(rows) > limit
|
|
||||||
page_rows = rows[:limit]
|
|
||||||
|
|
||||||
messages = [{
|
|
||||||
"id": row["id"],
|
|
||||||
"chat_id": row["chat_id"],
|
|
||||||
"sender_id": row["sender_id"],
|
|
||||||
"text": row["text"],
|
|
||||||
"created_at": row["created_at"].strftime('%Y-%m-%dT%H:%M:%SZ')
|
|
||||||
} for row in page_rows]
|
|
||||||
|
|
||||||
next_cursor = None
|
|
||||||
if has_more and messages:
|
|
||||||
last = page_rows[-1]
|
|
||||||
next_cursor = f"{last['created_at'].strftime('%Y-%m-%dT%H:%M:%SZ')},{last['id']}"
|
|
||||||
|
|
||||||
return messages, next_cursor
|
|
||||||
|
|
||||||
|
|
||||||
store = PostgresStore()
|
store = PostgresStore()
|
||||||
+96
-140
@@ -1,9 +1,15 @@
|
|||||||
import base64
|
import base64
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
from uuid import uuid4
|
||||||
|
|
||||||
from fastapi import FastAPI, Request, HTTPException, Query
|
from fastapi import FastAPI, Request, HTTPException, Query
|
||||||
from fastapi.responses import JSONResponse, Response
|
from fastapi.responses import JSONResponse, Response
|
||||||
from fastapi.exceptions import RequestValidationError
|
from fastapi.exceptions import RequestValidationError
|
||||||
from typing import Optional
|
from typing import Optional
|
||||||
from uuid import uuid4
|
|
||||||
from .models import (
|
from .models import (
|
||||||
CreateUserRequest, CreateChatRequest, CreateMessageRequest,
|
CreateUserRequest, CreateChatRequest, CreateMessageRequest,
|
||||||
UserResponse, ChatResponse, MessageResponse, ChatPage, MessagePage,
|
UserResponse, ChatResponse, MessageResponse, ChatPage, MessagePage,
|
||||||
@@ -12,53 +18,50 @@ from .models import (
|
|||||||
from .database import store, init_db, get_db_connection
|
from .database import store, init_db, get_db_connection
|
||||||
from .auth import hash_password, verify_password, create_session, get_session, delete_session
|
from .auth import hash_password, verify_password, create_session, get_session, delete_session
|
||||||
|
|
||||||
|
# Идентификатор реплики — стабилен в пределах жизни процесса.
|
||||||
|
# Задаётся через env INSTANCE_ID, иначе генерируется.
|
||||||
|
INSTANCE_ID = os.getenv("INSTANCE_ID") or str(uuid4())
|
||||||
|
|
||||||
app = FastAPI()
|
app = FastAPI()
|
||||||
|
|
||||||
# Инициализация БД при старте
|
|
||||||
@app.on_event("startup")
|
@app.on_event("startup")
|
||||||
async def startup_event():
|
async def startup_event():
|
||||||
init_db()
|
init_db()
|
||||||
|
print(f"[startup] INSTANCE_ID={INSTANCE_ID}")
|
||||||
|
|
||||||
|
|
||||||
# Middleware для генерации X-Request-Id
|
|
||||||
@app.middleware("http")
|
@app.middleware("http")
|
||||||
async def add_request_id(request: Request, call_next):
|
async def add_headers(request: Request, call_next):
|
||||||
request_id = str(uuid4())
|
request_id = str(uuid4())
|
||||||
request.state.request_id = request_id
|
request.state.request_id = request_id
|
||||||
response = await call_next(request)
|
response = await call_next(request)
|
||||||
response.headers["X-Request-Id"] = request_id
|
response.headers["X-Request-Id"] = request_id
|
||||||
|
response.headers["X-Instance-Id"] = INSTANCE_ID
|
||||||
return response
|
return response
|
||||||
|
|
||||||
|
|
||||||
# Обработчик ошибок валидации Pydantic (422 → 400)
|
|
||||||
@app.exception_handler(RequestValidationError)
|
@app.exception_handler(RequestValidationError)
|
||||||
async def validation_exception_handler(request: Request, exc: RequestValidationError):
|
async def validation_exception_handler(request: Request, exc: RequestValidationError):
|
||||||
request_id = getattr(request.state, "request_id", str(uuid4()))
|
request_id = getattr(request.state, "request_id", str(uuid4()))
|
||||||
content = {
|
return JSONResponse(status_code=400, content={
|
||||||
"error": {
|
"error": {
|
||||||
"code": "invalid_request",
|
"code": "invalid_request",
|
||||||
"message": "Неверный формат запроса, неверные типы данных или лишние поля",
|
"message": "Неверный формат запроса, неверные типы данных или лишние поля",
|
||||||
"request_id": request_id
|
"request_id": request_id,
|
||||||
}
|
}
|
||||||
}
|
})
|
||||||
return JSONResponse(status_code=400, content=content)
|
|
||||||
|
|
||||||
|
|
||||||
# Глобальный обработчик HTTP ошибок
|
|
||||||
@app.exception_handler(HTTPException)
|
@app.exception_handler(HTTPException)
|
||||||
async def http_exception_handler(request: Request, exc: HTTPException):
|
async def http_exception_handler(request: Request, exc: HTTPException):
|
||||||
request_id = getattr(request.state, "request_id", str(uuid4()))
|
request_id = getattr(request.state, "request_id", str(uuid4()))
|
||||||
|
|
||||||
# Копируем headers из HTTPException, если они есть
|
|
||||||
headers = dict(exc.headers) if exc.headers else {}
|
headers = dict(exc.headers) if exc.headers else {}
|
||||||
|
|
||||||
# Если нет WWW-Authenticate, добавляем по умолчанию для 401
|
|
||||||
if exc.status_code == 401 and "WWW-Authenticate" not in headers:
|
if exc.status_code == 401 and "WWW-Authenticate" not in headers:
|
||||||
if "/auth/sessions" in str(request.url.path):
|
if "/auth/sessions" in str(request.url.path):
|
||||||
headers["WWW-Authenticate"] = 'Basic realm="messenger", charset="UTF-8"'
|
headers["WWW-Authenticate"] = 'Basic realm="messenger", charset="UTF-8"'
|
||||||
else:
|
else:
|
||||||
headers["WWW-Authenticate"] = 'Bearer realm="messenger"'
|
headers["WWW-Authenticate"] = 'Bearer realm="messenger"'
|
||||||
|
|
||||||
if isinstance(exc.detail, dict) and "error" in exc.detail:
|
if isinstance(exc.detail, dict) and "error" in exc.detail:
|
||||||
content = exc.detail
|
content = exc.detail
|
||||||
content["error"]["request_id"] = request_id
|
content["error"]["request_id"] = request_id
|
||||||
@@ -66,55 +69,38 @@ async def http_exception_handler(request: Request, exc: HTTPException):
|
|||||||
code_map = {
|
code_map = {
|
||||||
400: "invalid_request", 401: "unauthorized", 404: "not_found",
|
400: "invalid_request", 401: "unauthorized", 404: "not_found",
|
||||||
409: "conflict", 413: "payload_too_large", 415: "unsupported_media_type",
|
409: "conflict", 413: "payload_too_large", 415: "unsupported_media_type",
|
||||||
429: "rate_limited", 500: "internal_error", 503: "unavailable"
|
429: "rate_limited", 500: "internal_error", 503: "unavailable",
|
||||||
}
|
}
|
||||||
code = code_map.get(exc.status_code, "invalid_request")
|
content = {"error": {
|
||||||
content = {
|
"code": code_map.get(exc.status_code, "invalid_request"),
|
||||||
"error": {
|
"message": str(exc.detail),
|
||||||
"code": code,
|
"request_id": request_id,
|
||||||
"message": str(exc.detail),
|
}}
|
||||||
"request_id": request_id
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return JSONResponse(status_code=exc.status_code, content=content, headers=headers)
|
return JSONResponse(status_code=exc.status_code, content=content, headers=headers)
|
||||||
|
|
||||||
|
|
||||||
# Вспомогательная функция для получения текущего пользователя из Bearer токена
|
|
||||||
async def get_current_user_from_request(request: Request) -> dict:
|
async def get_current_user_from_request(request: Request) -> dict:
|
||||||
auth_header = request.headers.get("Authorization")
|
auth_header = request.headers.get("Authorization")
|
||||||
if not auth_header or not auth_header.startswith("Bearer "):
|
if not auth_header or not auth_header.startswith("Bearer "):
|
||||||
raise HTTPException(
|
raise HTTPException(401, detail="Missing or invalid Authorization header",
|
||||||
status_code=401,
|
headers={"WWW-Authenticate": 'Bearer realm="messenger"'})
|
||||||
detail="Missing or invalid Authorization header",
|
token = auth_header[7:]
|
||||||
headers={"WWW-Authenticate": 'Bearer realm="messenger"'}
|
|
||||||
)
|
|
||||||
|
|
||||||
token = auth_header[7:] # Убираем "Bearer "
|
|
||||||
|
|
||||||
conn = get_db_connection()
|
conn = get_db_connection()
|
||||||
try:
|
try:
|
||||||
session = get_session(conn, token)
|
session = get_session(conn, token)
|
||||||
if not session:
|
if not session:
|
||||||
raise HTTPException(
|
raise HTTPException(401, detail="Invalid or expired session",
|
||||||
status_code=401,
|
headers={"WWW-Authenticate": 'Bearer realm="messenger"'})
|
||||||
detail="Invalid or expired session",
|
|
||||||
headers={"WWW-Authenticate": 'Bearer realm="messenger"'}
|
|
||||||
)
|
|
||||||
|
|
||||||
user = store.get_user(session["user_id"])
|
user = store.get_user(session["user_id"])
|
||||||
if not user:
|
if not user:
|
||||||
raise HTTPException(
|
raise HTTPException(401, detail="User not found",
|
||||||
status_code=401,
|
headers={"WWW-Authenticate": 'Bearer realm="messenger"'})
|
||||||
detail="User not found",
|
|
||||||
headers={"WWW-Authenticate": 'Bearer realm="messenger"'}
|
|
||||||
)
|
|
||||||
|
|
||||||
return user
|
return user
|
||||||
finally:
|
finally:
|
||||||
conn.close()
|
conn.close()
|
||||||
|
|
||||||
# --- Health endpoints ---
|
|
||||||
|
# ---------- health ----------
|
||||||
@app.get("/health/live", response_model=HealthResponse)
|
@app.get("/health/live", response_model=HealthResponse)
|
||||||
async def health_live():
|
async def health_live():
|
||||||
return {"status": "ok"}
|
return {"status": "ok"}
|
||||||
@@ -127,62 +113,38 @@ async def health_ready():
|
|||||||
conn.close()
|
conn.close()
|
||||||
return {"status": "ok"}
|
return {"status": "ok"}
|
||||||
except Exception:
|
except Exception:
|
||||||
raise HTTPException(status_code=503, detail="Database unavailable")
|
raise HTTPException(503, detail="Database unavailable")
|
||||||
|
|
||||||
|
|
||||||
# --- Auth endpoints ---
|
# ---------- auth ----------
|
||||||
@app.post("/api/v1/auth/sessions", response_model=SessionResponse, status_code=201)
|
@app.post("/api/v1/auth/sessions", response_model=SessionResponse, status_code=201)
|
||||||
async def create_session_endpoint(request: Request):
|
async def create_session_endpoint(request: Request):
|
||||||
# Проверяем Basic auth
|
|
||||||
auth_header = request.headers.get("Authorization")
|
auth_header = request.headers.get("Authorization")
|
||||||
if not auth_header or not auth_header.startswith("Basic "):
|
if not auth_header or not auth_header.startswith("Basic "):
|
||||||
raise HTTPException(
|
raise HTTPException(401, detail="Missing Basic authentication",
|
||||||
status_code=401,
|
headers={"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'})
|
||||||
detail="Missing Basic authentication",
|
|
||||||
headers={"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'}
|
|
||||||
)
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# Декодируем base64(username:password)
|
|
||||||
decoded = base64.b64decode(auth_header[6:]).decode('utf-8')
|
decoded = base64.b64decode(auth_header[6:]).decode('utf-8')
|
||||||
# Пароль может содержать двоеточие, поэтому split только по первому
|
|
||||||
username, password = decoded.split(":", 1)
|
username, password = decoded.split(":", 1)
|
||||||
except Exception:
|
except Exception:
|
||||||
raise HTTPException(status_code=400, detail="Invalid Basic authentication format")
|
raise HTTPException(400, detail="Invalid Basic authentication format")
|
||||||
|
|
||||||
# Валидация username (ASCII [a-z0-9_]{3,32})
|
|
||||||
import re
|
|
||||||
if not re.match(r'^[a-z0-9_]{3,32}$', username):
|
if not re.match(r'^[a-z0-9_]{3,32}$', username):
|
||||||
raise HTTPException(status_code=400, detail="Invalid username format")
|
raise HTTPException(400, detail="Invalid username format")
|
||||||
|
|
||||||
# Валидация пароля (12-128 code points)
|
|
||||||
if len(password) < 12 or len(password) > 128:
|
if len(password) < 12 or len(password) > 128:
|
||||||
raise HTTPException(status_code=400, detail="Password must be 12-128 characters")
|
raise HTTPException(400, detail="Password must be 12-128 characters")
|
||||||
|
|
||||||
# Ищем пользователя
|
|
||||||
user = store.get_user_by_username(username)
|
user = store.get_user_by_username(username)
|
||||||
if not user:
|
if not user or not verify_password(password, user["password_hash"]):
|
||||||
raise HTTPException(status_code=401, detail="Invalid credentials")
|
raise HTTPException(401, detail="Invalid credentials")
|
||||||
|
|
||||||
# Проверяем пароль
|
|
||||||
if not verify_password(password, user["password_hash"]):
|
|
||||||
raise HTTPException(status_code=401, detail="Invalid credentials")
|
|
||||||
|
|
||||||
# Создаём сессию
|
|
||||||
conn = get_db_connection()
|
conn = get_db_connection()
|
||||||
try:
|
try:
|
||||||
session_data = create_session(conn, user["id"])
|
session_data = create_session(conn, user["id"])
|
||||||
|
|
||||||
return {
|
return {
|
||||||
"token": session_data["token"],
|
"token": session_data["token"],
|
||||||
"token_type": "Bearer",
|
"token_type": "Bearer",
|
||||||
"expires_at": session_data["expires_at"],
|
"expires_at": session_data["expires_at"],
|
||||||
"user": {
|
"user": {"id": user["id"], "username": user["username"],
|
||||||
"id": user["id"],
|
"display_name": user["display_name"],
|
||||||
"username": user["username"],
|
"created_at": user["created_at"]},
|
||||||
"display_name": user["display_name"],
|
|
||||||
"created_at": user["created_at"]
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
finally:
|
finally:
|
||||||
conn.close()
|
conn.close()
|
||||||
@@ -190,67 +152,53 @@ async def create_session_endpoint(request: Request):
|
|||||||
|
|
||||||
@app.delete("/api/v1/auth/sessions/current", status_code=204)
|
@app.delete("/api/v1/auth/sessions/current", status_code=204)
|
||||||
async def revoke_session(request: Request):
|
async def revoke_session(request: Request):
|
||||||
user = await get_current_user_from_request(request)
|
await get_current_user_from_request(request)
|
||||||
|
token = request.headers["Authorization"][7:]
|
||||||
auth_header = request.headers.get("Authorization")
|
|
||||||
token = auth_header[7:] # Убираем "Bearer "
|
|
||||||
|
|
||||||
conn = get_db_connection()
|
conn = get_db_connection()
|
||||||
try:
|
try:
|
||||||
delete_session(conn, token)
|
delete_session(conn, token)
|
||||||
finally:
|
finally:
|
||||||
conn.close()
|
conn.close()
|
||||||
|
|
||||||
return Response(status_code=204)
|
return Response(status_code=204)
|
||||||
|
|
||||||
|
|
||||||
# --- Users endpoints ---
|
# ---------- users ----------
|
||||||
@app.post("/api/v1/users", response_model=UserResponse, status_code=201)
|
@app.post("/api/v1/users", response_model=UserResponse, status_code=201)
|
||||||
async def create_user(request_body: CreateUserRequest):
|
async def create_user(body: CreateUserRequest):
|
||||||
try:
|
try:
|
||||||
password_hash = hash_password(request_body.password)
|
user = store.create_user(body.username, body.display_name,
|
||||||
user = store.create_user(
|
hash_password(body.password))
|
||||||
request_body.username,
|
|
||||||
request_body.display_name,
|
|
||||||
password_hash
|
|
||||||
)
|
|
||||||
return user
|
return user
|
||||||
except ValueError as e:
|
except ValueError as e:
|
||||||
if str(e) == "username_already_exists":
|
if str(e) == "username_already_exists":
|
||||||
raise HTTPException(status_code=409, detail="Username already exists")
|
raise HTTPException(409, detail="Username already exists")
|
||||||
raise HTTPException(status_code=400, detail=str(e))
|
raise HTTPException(400, detail=str(e))
|
||||||
|
|
||||||
|
|
||||||
@app.get("/api/v1/users/me", response_model=UserResponse)
|
@app.get("/api/v1/users/me", response_model=UserResponse)
|
||||||
async def get_current_user(request: Request):
|
async def get_current_user(request: Request):
|
||||||
user = await get_current_user_from_request(request)
|
return await get_current_user_from_request(request)
|
||||||
return user
|
|
||||||
|
|
||||||
|
|
||||||
# --- Chats endpoints ---
|
# ---------- chats ----------
|
||||||
@app.post("/api/v1/chats", response_model=ChatResponse, status_code=201)
|
@app.post("/api/v1/chats", response_model=ChatResponse, status_code=201)
|
||||||
async def create_chat(request_body: CreateChatRequest, request: Request):
|
async def create_chat(body: CreateChatRequest, request: Request):
|
||||||
user = await get_current_user_from_request(request)
|
user = await get_current_user_from_request(request)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
chat = store.create_chat(request_body.title, request_body.member_ids, user["id"])
|
return store.create_chat(body.title, body.member_ids, user["id"])
|
||||||
return chat
|
|
||||||
except ValueError as e:
|
except ValueError as e:
|
||||||
if str(e) == "user_not_found":
|
mapping = {
|
||||||
raise HTTPException(status_code=400, detail="One or more members not found")
|
"user_not_found": "One or more members not found",
|
||||||
if str(e) == "creator_not_in_members":
|
"creator_not_in_members": "Creator must be in member list",
|
||||||
raise HTTPException(status_code=400, detail="Creator must be in member list")
|
"duplicate_members": "Duplicate member IDs",
|
||||||
if str(e) == "duplicate_members":
|
}
|
||||||
raise HTTPException(status_code=400, detail="Duplicate member IDs")
|
raise HTTPException(400, detail=mapping.get(str(e), str(e)))
|
||||||
raise HTTPException(status_code=400, detail=str(e))
|
|
||||||
|
|
||||||
|
|
||||||
@app.get("/api/v1/chats", response_model=ChatPage)
|
@app.get("/api/v1/chats", response_model=ChatPage)
|
||||||
async def list_chats(
|
async def list_chats(request: Request,
|
||||||
request: Request,
|
limit: int = Query(default=50, ge=1, le=100),
|
||||||
limit: int = Query(default=50, ge=1, le=100),
|
cursor: Optional[str] = Query(default=None, min_length=1)):
|
||||||
cursor: Optional[str] = Query(default=None, min_length=1)
|
|
||||||
):
|
|
||||||
user = await get_current_user_from_request(request)
|
user = await get_current_user_from_request(request)
|
||||||
chats, next_cursor = store.list_chats(user["id"], limit, cursor)
|
chats, next_cursor = store.list_chats(user["id"], limit, cursor)
|
||||||
return {"items": chats, "next_cursor": next_cursor}
|
return {"items": chats, "next_cursor": next_cursor}
|
||||||
@@ -261,45 +209,53 @@ async def get_chat(chat_id: str, request: Request):
|
|||||||
user = await get_current_user_from_request(request)
|
user = await get_current_user_from_request(request)
|
||||||
chat = store.get_chat(chat_id, user["id"])
|
chat = store.get_chat(chat_id, user["id"])
|
||||||
if not chat:
|
if not chat:
|
||||||
raise HTTPException(status_code=404, detail="Chat not found")
|
raise HTTPException(404, detail="Chat not found")
|
||||||
return chat
|
return chat
|
||||||
|
|
||||||
|
|
||||||
# --- Messages endpoints ---
|
# ---------- messages ----------
|
||||||
@app.post("/api/v1/chats/{chat_id}/messages", response_model=MessageResponse, status_code=201)
|
@app.post("/api/v1/chats/{chat_id}/messages",
|
||||||
async def create_message(
|
response_model=MessageResponse, status_code=201)
|
||||||
chat_id: str,
|
async def create_message(chat_id: str, body: CreateMessageRequest, request: Request):
|
||||||
request_body: CreateMessageRequest,
|
|
||||||
request: Request
|
|
||||||
):
|
|
||||||
user = await get_current_user_from_request(request)
|
user = await get_current_user_from_request(request)
|
||||||
|
|
||||||
|
idem_key = request.headers.get("Idempotency-Key")
|
||||||
|
if not idem_key:
|
||||||
|
raise HTTPException(400, detail="Idempotency-Key header is required")
|
||||||
|
if len(idem_key) > 128 or not re.match(r'^[A-Za-z0-9._:-]+$', idem_key):
|
||||||
|
raise HTTPException(400, detail="Idempotency-Key must match ^[A-Za-z0-9._:-]{1,128}$")
|
||||||
|
|
||||||
|
path = f"/api/v1/chats/{chat_id}/messages"
|
||||||
|
request_hash = hashlib.sha256(
|
||||||
|
json.dumps({"chat_id": chat_id, "text": body.text}, sort_keys=True).encode()
|
||||||
|
).hexdigest()
|
||||||
|
|
||||||
try:
|
try:
|
||||||
message = store.create_message(chat_id, user["id"], request_body.text)
|
message = store.create_message_idempotent(
|
||||||
|
chat_id, user["id"], body.text,
|
||||||
|
idem_key=idem_key, path=path, request_hash=request_hash)
|
||||||
return message
|
return message
|
||||||
except ValueError as e:
|
except ValueError as e:
|
||||||
|
if str(e) == "idempotency_conflict":
|
||||||
|
raise HTTPException(409, detail="Idempotency-Key reused with different payload")
|
||||||
if str(e) == "chat_not_found":
|
if str(e) == "chat_not_found":
|
||||||
raise HTTPException(status_code=404, detail="Chat not found")
|
raise HTTPException(404, detail="Chat not found")
|
||||||
if str(e) == "sender_not_in_chat":
|
if str(e) == "sender_not_in_chat":
|
||||||
raise HTTPException(status_code=404, detail="User not in chat")
|
raise HTTPException(404, detail="User not in chat")
|
||||||
raise HTTPException(status_code=400, detail=str(e))
|
raise HTTPException(400, detail=str(e))
|
||||||
|
|
||||||
|
|
||||||
@app.get("/api/v1/chats/{chat_id}/messages", response_model=MessagePage)
|
@app.get("/api/v1/chats/{chat_id}/messages", response_model=MessagePage)
|
||||||
async def list_messages(
|
async def list_messages(chat_id: str, request: Request,
|
||||||
chat_id: str,
|
limit: int = Query(default=50, ge=1, le=100),
|
||||||
request: Request,
|
cursor: Optional[str] = Query(default=None, min_length=1)):
|
||||||
limit: int = Query(default=50, ge=1, le=100),
|
|
||||||
cursor: Optional[str] = Query(default=None, min_length=1)
|
|
||||||
):
|
|
||||||
user = await get_current_user_from_request(request)
|
user = await get_current_user_from_request(request)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
messages, next_cursor = store.list_messages(chat_id, user["id"], limit, cursor)
|
messages, next_cursor = store.list_messages(chat_id, user["id"], limit, cursor)
|
||||||
return {"items": messages, "next_cursor": next_cursor}
|
return {"items": messages, "next_cursor": next_cursor}
|
||||||
except ValueError as e:
|
except ValueError as e:
|
||||||
if str(e) == "chat_not_found":
|
if str(e) == "chat_not_found":
|
||||||
raise HTTPException(status_code=404, detail="Chat not found")
|
raise HTTPException(404, detail="Chat not found")
|
||||||
if str(e) == "user_not_in_chat":
|
if str(e) == "user_not_in_chat":
|
||||||
raise HTTPException(status_code=404, detail="User not in chat")
|
raise HTTPException(404, detail="User not in chat")
|
||||||
raise HTTPException(status_code=400, detail=str(e))
|
raise HTTPException(400, detail=str(e))
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
CREATE TABLE IF NOT EXISTS idempotency_keys (
|
||||||
|
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||||
|
method TEXT NOT NULL,
|
||||||
|
path TEXT NOT NULL,
|
||||||
|
key TEXT NOT NULL,
|
||||||
|
request_hash TEXT NOT NULL,
|
||||||
|
status_code INTEGER NOT NULL,
|
||||||
|
response_body JSONB NOT NULL,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
PRIMARY KEY (user_id, method, path, key)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_idempotency_created
|
||||||
|
ON idempotency_keys(created_at);
|
||||||
Reference in New Issue
Block a user