Реализация с PostgreSQL и session-based auth
This commit is contained in:
+5
-5
@@ -1,20 +1,20 @@
|
|||||||
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/*
|
||||||
|
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|
||||||
# Сначала копируем зависимости, чтобы Docker кэшировал этот слой
|
# Копируем зависимости
|
||||||
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
|
||||||
ENV PORT=8080
|
ENV PORT=8080
|
||||||
|
|
||||||
EXPOSE 8080
|
EXPOSE 8080
|
||||||
|
|
||||||
# Запуск сервера как главного процесса контейнера
|
|
||||||
CMD ["uvicorn", "src.main:app", "--host", "0.0.0.0", "--port", "8080"]
|
CMD ["uvicorn", "src.main:app", "--host", "0.0.0.0", "--port", "8080"]
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
services:
|
||||||
|
api:
|
||||||
|
build: .
|
||||||
|
ports:
|
||||||
|
- "8080:8080"
|
||||||
|
environment:
|
||||||
|
- DATABASE_URL=postgresql://messenger:messenger_pass@postgres:5432/messenger
|
||||||
|
- SESSION_TTL_SECONDS=3600
|
||||||
|
depends_on:
|
||||||
|
postgres:
|
||||||
|
condition: service_healthy
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD", "curl", "-f", "http://localhost:8080/health/ready"]
|
||||||
|
interval: 5s
|
||||||
|
timeout: 3s
|
||||||
|
retries: 5
|
||||||
|
restart: unless-stopped
|
||||||
|
|
||||||
|
postgres:
|
||||||
|
image: postgres:16.1
|
||||||
|
environment:
|
||||||
|
- POSTGRES_DB=messenger
|
||||||
|
- POSTGRES_USER=messenger
|
||||||
|
- POSTGRES_PASSWORD=messenger_pass
|
||||||
|
volumes:
|
||||||
|
- postgres_data:/var/lib/postgresql/data
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD-SHELL", "pg_isready -U messenger"]
|
||||||
|
interval: 5s
|
||||||
|
timeout: 3s
|
||||||
|
retries: 5
|
||||||
|
restart: unless-stopped
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
postgres_data:
|
||||||
+6
-28
@@ -1,28 +1,6 @@
|
|||||||
annotated-doc==0.0.5
|
fastapi==0.104.1
|
||||||
annotated-types==0.8.0
|
uvicorn==0.24.0
|
||||||
anyio==4.16.0
|
psycopg2-binary==2.9.9
|
||||||
certifi==2026.10.23
|
bcrypt==4.1.2
|
||||||
click==8.5.1
|
python-multipart==0.0.6
|
||||||
colorama==0.4.6
|
pydantic==2.5.0
|
||||||
fastapi==0.162.2
|
|
||||||
h11==0.16.0
|
|
||||||
httpcore==1.0.9
|
|
||||||
httptools==0.9.0
|
|
||||||
httpx==0.28.1
|
|
||||||
idna==3.20
|
|
||||||
iniconfig==2.3.1
|
|
||||||
opentelemetry-api==1.45.2
|
|
||||||
packaging==26.3
|
|
||||||
pluggy==1.7.0
|
|
||||||
pydantic==2.14.3
|
|
||||||
pydantic_core==2.50.4
|
|
||||||
Pygments==2.21.0
|
|
||||||
pytest==9.2.0
|
|
||||||
python-dotenv==1.2.4
|
|
||||||
PyYAML==6.0.3
|
|
||||||
starlette==1.10.0
|
|
||||||
typing-inspection==0.4.5
|
|
||||||
typing_extensions==4.16.0
|
|
||||||
uvicorn==0.54.0
|
|
||||||
watchfiles==1.3.0
|
|
||||||
websockets==17.4
|
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
@echo off
|
||||||
|
cd /d %~dp0\..
|
||||||
|
docker compose restart api postgres
|
||||||
|
|
||||||
|
set /a count=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
|
||||||
+61
@@ -0,0 +1,61 @@
|
|||||||
|
import os
|
||||||
|
import hashlib
|
||||||
|
import bcrypt
|
||||||
|
import secrets
|
||||||
|
from datetime import datetime, timezone, timedelta
|
||||||
|
from typing import Optional, Dict, Any
|
||||||
|
|
||||||
|
|
||||||
|
SESSION_TTL_SECONDS = int(os.getenv("SESSION_TTL_SECONDS", "3600"))
|
||||||
|
|
||||||
|
|
||||||
|
def hash_password(password: str) -> str:
|
||||||
|
"""Хешировать пароль: SHA-256 пре-хеширование + bcrypt (обход лимита 72 байт)"""
|
||||||
|
pre_hash = hashlib.sha256(password.encode('utf-8')).digest()
|
||||||
|
return bcrypt.hashpw(pre_hash, bcrypt.gensalt()).decode('utf-8')
|
||||||
|
|
||||||
|
|
||||||
|
def verify_password(password: str, password_hash: str) -> bool:
|
||||||
|
"""Проверить пароль"""
|
||||||
|
pre_hash = hashlib.sha256(password.encode('utf-8')).digest()
|
||||||
|
return bcrypt.checkpw(pre_hash, password_hash.encode('utf-8'))
|
||||||
|
|
||||||
|
|
||||||
|
def generate_token() -> str:
|
||||||
|
"""Сгенерировать случайный токен сессии (256 бит энтропии)"""
|
||||||
|
return secrets.token_hex(32) # 64 символа = 256 бит
|
||||||
|
|
||||||
|
|
||||||
|
def create_session(db_conn, user_id: str) -> Dict[str, Any]:
|
||||||
|
"""Создать новую сессию в БД"""
|
||||||
|
token = generate_token()
|
||||||
|
expires_at = datetime.now(timezone.utc) + timedelta(seconds=SESSION_TTL_SECONDS)
|
||||||
|
|
||||||
|
with db_conn.cursor() as cur:
|
||||||
|
cur.execute(
|
||||||
|
"INSERT INTO sessions (token, user_id, expires_at) VALUES (%s, %s, %s)",
|
||||||
|
(token, user_id, expires_at)
|
||||||
|
)
|
||||||
|
db_conn.commit()
|
||||||
|
|
||||||
|
return {
|
||||||
|
"token": token,
|
||||||
|
"expires_at": expires_at.strftime('%Y-%m-%dT%H:%M:%SZ')
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def get_session(db_conn, token: str) -> Optional[Dict[str, Any]]:
|
||||||
|
"""Получить действительную сессию по токену"""
|
||||||
|
with db_conn.cursor() as cur:
|
||||||
|
cur.execute(
|
||||||
|
"SELECT token, user_id, expires_at FROM sessions WHERE token = %s AND expires_at > NOW()",
|
||||||
|
(token,)
|
||||||
|
)
|
||||||
|
return cur.fetchone()
|
||||||
|
|
||||||
|
|
||||||
|
def delete_session(db_conn, token: str):
|
||||||
|
"""Удалить сессию (logout)"""
|
||||||
|
with db_conn.cursor() as cur:
|
||||||
|
cur.execute("DELETE FROM sessions WHERE token = %s", (token,))
|
||||||
|
db_conn.commit()
|
||||||
+295
@@ -0,0 +1,295 @@
|
|||||||
|
import os
|
||||||
|
import psycopg2
|
||||||
|
from psycopg2.extras import RealDictCursor
|
||||||
|
from typing import Optional, List, Dict, Any, Tuple
|
||||||
|
from contextlib import contextmanager
|
||||||
|
from uuid import uuid4
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
|
|
||||||
|
DATABASE_URL = os.getenv("DATABASE_URL", "postgresql://messenger:messenger_pass@localhost:5432/messenger")
|
||||||
|
|
||||||
|
|
||||||
|
def get_db_connection():
|
||||||
|
"""Создать подключение к PostgreSQL"""
|
||||||
|
return psycopg2.connect(DATABASE_URL, cursor_factory=RealDictCursor)
|
||||||
|
|
||||||
|
|
||||||
|
@contextmanager
|
||||||
|
def get_db():
|
||||||
|
"""Контекстный менеджер для работы с БД"""
|
||||||
|
conn = get_db_connection()
|
||||||
|
try:
|
||||||
|
yield conn
|
||||||
|
conn.commit()
|
||||||
|
except Exception:
|
||||||
|
conn.rollback()
|
||||||
|
raise
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
def init_db():
|
||||||
|
"""Инициализировать БД (запустить миграции idempotently)"""
|
||||||
|
migration_path = os.path.join(os.path.dirname(__file__), "migrations", "001_initial.sql")
|
||||||
|
with open(migration_path, "r") as f:
|
||||||
|
migration_sql = f.read()
|
||||||
|
|
||||||
|
with get_db() as conn:
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
cur.execute(migration_sql)
|
||||||
|
|
||||||
|
|
||||||
|
class PostgresStore:
|
||||||
|
"""Store layer для PostgreSQL — заменяет InMemoryStore из Lab 1"""
|
||||||
|
|
||||||
|
def create_user(self, username: str, display_name: str, password_hash: str) -> dict:
|
||||||
|
with get_db() as conn:
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
# Проверяем уникальность username
|
||||||
|
cur.execute("SELECT id FROM users WHERE username = %s", (username,))
|
||||||
|
if cur.fetchone():
|
||||||
|
raise ValueError("username_already_exists")
|
||||||
|
|
||||||
|
user_id = str(uuid4())
|
||||||
|
now = datetime.now(timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ')
|
||||||
|
|
||||||
|
cur.execute(
|
||||||
|
"INSERT INTO users (id, username, display_name, password_hash, created_at) "
|
||||||
|
"VALUES (%s, %s, %s, %s, %s)",
|
||||||
|
(user_id, username, display_name, password_hash, now)
|
||||||
|
)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"id": user_id,
|
||||||
|
"username": username,
|
||||||
|
"display_name": display_name,
|
||||||
|
"created_at": now
|
||||||
|
}
|
||||||
|
|
||||||
|
def get_user(self, user_id: str) -> Optional[dict]:
|
||||||
|
with get_db() as conn:
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
cur.execute(
|
||||||
|
"SELECT id, username, display_name, created_at FROM users WHERE id = %s",
|
||||||
|
(user_id,)
|
||||||
|
)
|
||||||
|
row = cur.fetchone()
|
||||||
|
if 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]:
|
||||||
|
with get_db() as conn:
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
cur.execute(
|
||||||
|
"SELECT id, username, display_name, password_hash, created_at FROM users WHERE username = %s",
|
||||||
|
(username,)
|
||||||
|
)
|
||||||
|
row = cur.fetchone()
|
||||||
|
if row:
|
||||||
|
# Преобразуем datetime в строку ISO8601
|
||||||
|
row["created_at"] = row["created_at"].strftime('%Y-%m-%dT%H:%M:%SZ')
|
||||||
|
return row
|
||||||
|
|
||||||
|
def create_chat(self, title: str, member_ids: List[str], creator_id: str) -> dict:
|
||||||
|
with get_db() as conn:
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
# Проверяем, что все участники существуют
|
||||||
|
for member_id in member_ids:
|
||||||
|
cur.execute("SELECT id FROM users WHERE id = %s", (member_id,))
|
||||||
|
if not cur.fetchone():
|
||||||
|
raise ValueError("user_not_found")
|
||||||
|
|
||||||
|
# Проверяем, что создатель входит в список участников
|
||||||
|
if creator_id not in member_ids:
|
||||||
|
raise ValueError("creator_not_in_members")
|
||||||
|
|
||||||
|
# Проверяем уникальность member_ids
|
||||||
|
if len(member_ids) != len(set(member_ids)):
|
||||||
|
raise ValueError("duplicate_members")
|
||||||
|
|
||||||
|
chat_id = str(uuid4())
|
||||||
|
now = datetime.now(timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ')
|
||||||
|
|
||||||
|
# Атомарно: создаём чат и всех участников в одной транзакции
|
||||||
|
cur.execute(
|
||||||
|
"INSERT INTO chats (id, title, created_at) VALUES (%s, %s, %s)",
|
||||||
|
(chat_id, title, 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]:
|
||||||
|
with get_db() as conn:
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
cur.execute(
|
||||||
|
"SELECT c.id, c.title, c.created_at "
|
||||||
|
"FROM chats c "
|
||||||
|
"JOIN chat_members cm ON c.id = cm.chat_id "
|
||||||
|
"WHERE c.id = %s AND cm.user_id = %s",
|
||||||
|
(chat_id, user_id)
|
||||||
|
)
|
||||||
|
chat = cur.fetchone()
|
||||||
|
if not chat:
|
||||||
|
return None
|
||||||
|
|
||||||
|
# Получаем список участников
|
||||||
|
cur.execute(
|
||||||
|
"SELECT user_id FROM chat_members WHERE chat_id = %s ORDER BY user_id",
|
||||||
|
(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:
|
||||||
|
with 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 = [user_id]
|
||||||
|
|
||||||
|
if cursor:
|
||||||
|
cursor_parts = cursor.split(",", 1)
|
||||||
|
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])
|
||||||
|
|
||||||
|
query += " ORDER BY c.created_at, c.id LIMIT %s"
|
||||||
|
params.append(limit + 1) # Берём на 1 больше для определения has_more
|
||||||
|
|
||||||
|
cur.execute(query, params)
|
||||||
|
rows = cur.fetchall()
|
||||||
|
|
||||||
|
has_more = len(rows) > limit
|
||||||
|
page_rows = rows[:limit]
|
||||||
|
|
||||||
|
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(
|
||||||
|
"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")
|
||||||
|
|
||||||
|
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)
|
||||||
|
)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"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()
|
||||||
+185
-54
@@ -1,17 +1,26 @@
|
|||||||
from fastapi import FastAPI, Request, HTTPException, Header, Query
|
import base64
|
||||||
from fastapi.responses import JSONResponse
|
from fastapi import FastAPI, Request, HTTPException, Query
|
||||||
|
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 uuid import uuid4
|
||||||
from .models import (
|
from .models import (
|
||||||
store, CreateUserRequest, CreateChatRequest, CreateMessageRequest,
|
CreateUserRequest, CreateChatRequest, CreateMessageRequest,
|
||||||
UserResponse, ChatResponse, MessageResponse, ChatPage, MessagePage,
|
UserResponse, ChatResponse, MessageResponse, ChatPage, MessagePage,
|
||||||
HealthResponse
|
SessionResponse, HealthResponse
|
||||||
)
|
)
|
||||||
|
from .database import store, init_db, get_db_connection
|
||||||
|
from .auth import hash_password, verify_password, create_session, get_session, delete_session
|
||||||
|
|
||||||
app = FastAPI()
|
app = FastAPI()
|
||||||
|
|
||||||
# Middleware для генерации и проброса X-Request-Id
|
# Инициализация БД при старте
|
||||||
|
@app.on_event("startup")
|
||||||
|
async def startup_event():
|
||||||
|
init_db()
|
||||||
|
|
||||||
|
|
||||||
|
# Middleware для генерации X-Request-Id
|
||||||
@app.middleware("http")
|
@app.middleware("http")
|
||||||
async def add_request_id(request: Request, call_next):
|
async def add_request_id(request: Request, call_next):
|
||||||
request_id = str(uuid4())
|
request_id = str(uuid4())
|
||||||
@@ -20,7 +29,8 @@ async def add_request_id(request: Request, call_next):
|
|||||||
response.headers["X-Request-Id"] = request_id
|
response.headers["X-Request-Id"] = request_id
|
||||||
return response
|
return response
|
||||||
|
|
||||||
# Обработчик ошибок валидации Pydantic (меняет стандартный 422 на 400 по контракту)
|
|
||||||
|
# Обработчик ошибок валидации 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()))
|
||||||
@@ -33,11 +43,22 @@ async def validation_exception_handler(request: Request, exc: RequestValidationE
|
|||||||
}
|
}
|
||||||
return JSONResponse(status_code=400, content=content)
|
return JSONResponse(status_code=400, content=content)
|
||||||
|
|
||||||
|
|
||||||
# Глобальный обработчик HTTP ошибок
|
# Глобальный обработчик 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 {}
|
||||||
|
|
||||||
|
# Если нет WWW-Authenticate, добавляем по умолчанию для 401
|
||||||
|
if exc.status_code == 401 and "WWW-Authenticate" not in headers:
|
||||||
|
if "/auth/sessions" in str(request.url.path):
|
||||||
|
headers["WWW-Authenticate"] = 'Basic realm="messenger", charset="UTF-8"'
|
||||||
|
else:
|
||||||
|
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
|
||||||
@@ -55,47 +76,164 @@ async def http_exception_handler(request: Request, exc: HTTPException):
|
|||||||
"request_id": request_id
|
"request_id": request_id
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return JSONResponse(status_code=exc.status_code, content=content)
|
|
||||||
|
return JSONResponse(status_code=exc.status_code, content=content, headers=headers)
|
||||||
|
|
||||||
|
|
||||||
|
# Вспомогательная функция для получения текущего пользователя из Bearer токена
|
||||||
|
async def get_current_user_from_request(request: Request) -> dict:
|
||||||
|
auth_header = request.headers.get("Authorization")
|
||||||
|
if not auth_header or not auth_header.startswith("Bearer "):
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=401,
|
||||||
|
detail="Missing or invalid Authorization header",
|
||||||
|
headers={"WWW-Authenticate": 'Bearer realm="messenger"'}
|
||||||
|
)
|
||||||
|
|
||||||
|
token = auth_header[7:] # Убираем "Bearer "
|
||||||
|
|
||||||
|
conn = get_db_connection()
|
||||||
|
try:
|
||||||
|
session = get_session(conn, token)
|
||||||
|
if not session:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=401,
|
||||||
|
detail="Invalid or expired session",
|
||||||
|
headers={"WWW-Authenticate": 'Bearer realm="messenger"'}
|
||||||
|
)
|
||||||
|
|
||||||
|
user = store.get_user(session["user_id"])
|
||||||
|
if not user:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=401,
|
||||||
|
detail="User not found",
|
||||||
|
headers={"WWW-Authenticate": 'Bearer realm="messenger"'}
|
||||||
|
)
|
||||||
|
|
||||||
|
return user
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
# --- Health endpoints ---
|
# --- Health endpoints ---
|
||||||
@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"}
|
||||||
|
|
||||||
|
|
||||||
@app.get("/health/ready", response_model=HealthResponse)
|
@app.get("/health/ready", response_model=HealthResponse)
|
||||||
async def health_ready():
|
async def health_ready():
|
||||||
return {"status": "ok"}
|
|
||||||
|
|
||||||
# --- Users ---
|
|
||||||
@app.post("/api/v1/users", response_model=UserResponse, status_code=201)
|
|
||||||
async def create_user(request: CreateUserRequest):
|
|
||||||
try:
|
try:
|
||||||
user = await store.create_user(request.username, request.display_name)
|
conn = get_db_connection()
|
||||||
|
conn.close()
|
||||||
|
return {"status": "ok"}
|
||||||
|
except Exception:
|
||||||
|
raise HTTPException(status_code=503, detail="Database unavailable")
|
||||||
|
|
||||||
|
|
||||||
|
# --- Auth endpoints ---
|
||||||
|
@app.post("/api/v1/auth/sessions", response_model=SessionResponse, status_code=201)
|
||||||
|
async def create_session_endpoint(request: Request):
|
||||||
|
# Проверяем Basic auth
|
||||||
|
auth_header = request.headers.get("Authorization")
|
||||||
|
if not auth_header or not auth_header.startswith("Basic "):
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=401,
|
||||||
|
detail="Missing Basic authentication",
|
||||||
|
headers={"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'}
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
# Декодируем base64(username:password)
|
||||||
|
decoded = base64.b64decode(auth_header[6:]).decode('utf-8')
|
||||||
|
# Пароль может содержать двоеточие, поэтому split только по первому
|
||||||
|
username, password = decoded.split(":", 1)
|
||||||
|
except Exception:
|
||||||
|
raise HTTPException(status_code=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):
|
||||||
|
raise HTTPException(status_code=400, detail="Invalid username format")
|
||||||
|
|
||||||
|
# Валидация пароля (12-128 code points)
|
||||||
|
if len(password) < 12 or len(password) > 128:
|
||||||
|
raise HTTPException(status_code=400, detail="Password must be 12-128 characters")
|
||||||
|
|
||||||
|
# Ищем пользователя
|
||||||
|
user = store.get_user_by_username(username)
|
||||||
|
if not user:
|
||||||
|
raise HTTPException(status_code=401, detail="Invalid credentials")
|
||||||
|
|
||||||
|
# Проверяем пароль
|
||||||
|
if not verify_password(password, user["password_hash"]):
|
||||||
|
raise HTTPException(status_code=401, detail="Invalid credentials")
|
||||||
|
|
||||||
|
# Создаём сессию
|
||||||
|
conn = get_db_connection()
|
||||||
|
try:
|
||||||
|
session_data = create_session(conn, user["id"])
|
||||||
|
|
||||||
|
return {
|
||||||
|
"token": session_data["token"],
|
||||||
|
"token_type": "Bearer",
|
||||||
|
"expires_at": session_data["expires_at"],
|
||||||
|
"user": {
|
||||||
|
"id": user["id"],
|
||||||
|
"username": user["username"],
|
||||||
|
"display_name": user["display_name"],
|
||||||
|
"created_at": user["created_at"]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
@app.delete("/api/v1/auth/sessions/current", status_code=204)
|
||||||
|
async def revoke_session(request: Request):
|
||||||
|
user = await get_current_user_from_request(request)
|
||||||
|
|
||||||
|
auth_header = request.headers.get("Authorization")
|
||||||
|
token = auth_header[7:] # Убираем "Bearer "
|
||||||
|
|
||||||
|
conn = get_db_connection()
|
||||||
|
try:
|
||||||
|
delete_session(conn, token)
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
return Response(status_code=204)
|
||||||
|
|
||||||
|
|
||||||
|
# --- Users endpoints ---
|
||||||
|
@app.post("/api/v1/users", response_model=UserResponse, status_code=201)
|
||||||
|
async def create_user(request_body: CreateUserRequest):
|
||||||
|
try:
|
||||||
|
password_hash = hash_password(request_body.password)
|
||||||
|
user = store.create_user(
|
||||||
|
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(status_code=409, detail="Username already exists")
|
||||||
raise HTTPException(status_code=400, detail=str(e))
|
raise HTTPException(status_code=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(x_user_id: str = Header(None, alias="X-User-Id")):
|
async def get_current_user(request: Request):
|
||||||
if not x_user_id:
|
user = await get_current_user_from_request(request)
|
||||||
raise HTTPException(status_code=401, detail="Missing X-User-Id header")
|
|
||||||
user = await store.get_user(x_user_id)
|
|
||||||
if not user:
|
|
||||||
raise HTTPException(status_code=401, detail="User not found")
|
|
||||||
return user
|
return user
|
||||||
|
|
||||||
# --- Chats ---
|
|
||||||
|
# --- Chats endpoints ---
|
||||||
@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: CreateChatRequest, x_user_id: str = Header(None, alias="X-User-Id")):
|
async def create_chat(request_body: CreateChatRequest, request: Request):
|
||||||
if not x_user_id:
|
user = await get_current_user_from_request(request)
|
||||||
raise HTTPException(status_code=401, detail="Missing X-User-Id header")
|
|
||||||
if not await store.get_user(x_user_id):
|
|
||||||
raise HTTPException(status_code=401, detail="User not found")
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
chat = await store.create_chat(request.title, request.member_ids, x_user_id)
|
chat = store.create_chat(request_body.title, request_body.member_ids, user["id"])
|
||||||
return chat
|
return chat
|
||||||
except ValueError as e:
|
except ValueError as e:
|
||||||
if str(e) == "user_not_found":
|
if str(e) == "user_not_found":
|
||||||
@@ -106,65 +244,58 @@ async def create_chat(request: CreateChatRequest, x_user_id: str = Header(None,
|
|||||||
raise HTTPException(status_code=400, detail="Duplicate member IDs")
|
raise HTTPException(status_code=400, detail="Duplicate member IDs")
|
||||||
raise HTTPException(status_code=400, detail=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(
|
||||||
x_user_id: str = Header(None, alias="X-User-Id"),
|
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)
|
||||||
):
|
):
|
||||||
if not x_user_id:
|
user = await get_current_user_from_request(request)
|
||||||
raise HTTPException(status_code=401, detail="Missing X-User-Id header")
|
chats, next_cursor = store.list_chats(user["id"], limit, cursor)
|
||||||
if not await store.get_user(x_user_id):
|
|
||||||
raise HTTPException(status_code=401, detail="User not found")
|
|
||||||
|
|
||||||
chats, next_cursor = await store.list_chats(x_user_id, limit, cursor)
|
|
||||||
return {"items": chats, "next_cursor": next_cursor}
|
return {"items": chats, "next_cursor": next_cursor}
|
||||||
|
|
||||||
|
|
||||||
@app.get("/api/v1/chats/{chat_id}", response_model=ChatResponse)
|
@app.get("/api/v1/chats/{chat_id}", response_model=ChatResponse)
|
||||||
async def get_chat(chat_id: str, x_user_id: str = Header(None, alias="X-User-Id")):
|
async def get_chat(chat_id: str, request: Request):
|
||||||
if not x_user_id:
|
user = await get_current_user_from_request(request)
|
||||||
raise HTTPException(status_code=401, detail="Missing X-User-Id header")
|
chat = store.get_chat(chat_id, user["id"])
|
||||||
chat = await store.get_chat(chat_id, x_user_id)
|
|
||||||
if not chat:
|
if not chat:
|
||||||
raise HTTPException(status_code=404, detail="Chat not found")
|
raise HTTPException(status_code=404, detail="Chat not found")
|
||||||
return chat
|
return chat
|
||||||
|
|
||||||
# --- Messages ---
|
|
||||||
|
# --- Messages endpoints ---
|
||||||
@app.post("/api/v1/chats/{chat_id}/messages", response_model=MessageResponse, status_code=201)
|
@app.post("/api/v1/chats/{chat_id}/messages", response_model=MessageResponse, status_code=201)
|
||||||
async def create_message(
|
async def create_message(
|
||||||
chat_id: str,
|
chat_id: str,
|
||||||
request: CreateMessageRequest,
|
request_body: CreateMessageRequest,
|
||||||
x_user_id: str = Header(None, alias="X-User-Id")
|
request: Request
|
||||||
):
|
):
|
||||||
if not x_user_id:
|
user = await get_current_user_from_request(request)
|
||||||
raise HTTPException(status_code=401, detail="Missing X-User-Id header")
|
|
||||||
if not await store.get_user(x_user_id):
|
|
||||||
raise HTTPException(status_code=401, detail="User not found")
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
message = await store.create_message(chat_id, x_user_id, request.text)
|
message = store.create_message(chat_id, user["id"], request_body.text)
|
||||||
return message
|
return message
|
||||||
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(status_code=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") # 404 вместо 403 по контракту
|
raise HTTPException(status_code=404, detail="User not in chat")
|
||||||
raise HTTPException(status_code=400, detail=str(e))
|
raise HTTPException(status_code=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,
|
chat_id: str,
|
||||||
x_user_id: str = Header(None, alias="X-User-Id"),
|
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)
|
||||||
):
|
):
|
||||||
if not x_user_id:
|
user = await get_current_user_from_request(request)
|
||||||
raise HTTPException(status_code=401, detail="Missing X-User-Id header")
|
|
||||||
if not await store.get_user(x_user_id):
|
|
||||||
raise HTTPException(status_code=401, detail="User not found")
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
messages, next_cursor = await store.list_messages(chat_id, x_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":
|
||||||
|
|||||||
@@ -0,0 +1,51 @@
|
|||||||
|
-- Миграция 001: начальная схема для MTUSI Messenger Lab 2
|
||||||
|
-- Запускать idempotently (безопасно повторять)
|
||||||
|
|
||||||
|
-- Таблица пользователей
|
||||||
|
CREATE TABLE IF NOT EXISTS users (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
username VARCHAR(32) NOT NULL UNIQUE CHECK (username ~ '^[a-z0-9_]{3,32}$'),
|
||||||
|
display_name VARCHAR(100) NOT NULL CHECK (length(display_name) >= 1),
|
||||||
|
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 VARCHAR(100) NOT NULL CHECK (length(title) >= 1),
|
||||||
|
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) ON DELETE CASCADE,
|
||||||
|
text TEXT NOT NULL CHECK (length(text) >= 1 AND length(text) <= 4000),
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||||
|
);
|
||||||
|
|
||||||
|
-- Таблица сессий
|
||||||
|
CREATE TABLE IF NOT EXISTS sessions (
|
||||||
|
token TEXT PRIMARY KEY,
|
||||||
|
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||||
|
expires_at TIMESTAMPTZ NOT NULL,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||||
|
);
|
||||||
|
|
||||||
|
-- Индекс для cursor-based пагинации сообщений
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_messages_chat_created ON messages(chat_id, created_at, id);
|
||||||
|
|
||||||
|
-- Индекс для очистки истёкших сессий
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_sessions_expires ON sessions(expires_at);
|
||||||
|
|
||||||
|
-- Индекс для быстрого поиска чатов пользователя
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_chat_members_user ON chat_members(user_id);
|
||||||
+28
-195
@@ -1,7 +1,5 @@
|
|||||||
from datetime import datetime, timezone
|
from datetime import datetime, timezone
|
||||||
from typing import Optional, Dict, List
|
from typing import Optional, List
|
||||||
from uuid import uuid4
|
|
||||||
import asyncio
|
|
||||||
from pydantic import BaseModel, Field, field_validator
|
from pydantic import BaseModel, Field, field_validator
|
||||||
import re
|
import re
|
||||||
|
|
||||||
@@ -9,14 +7,15 @@ import re
|
|||||||
class CreateUserRequest(BaseModel):
|
class CreateUserRequest(BaseModel):
|
||||||
username: str = Field(..., min_length=3, max_length=32)
|
username: str = Field(..., min_length=3, max_length=32)
|
||||||
display_name: str = Field(..., min_length=1, max_length=100)
|
display_name: str = Field(..., min_length=1, max_length=100)
|
||||||
|
password: str = Field(..., min_length=12, max_length=128)
|
||||||
|
|
||||||
@field_validator('username')
|
@field_validator('username')
|
||||||
@classmethod
|
@classmethod
|
||||||
def validate_username(cls, v):
|
def validate_username(cls, v):
|
||||||
if not re.match(r'^[a-z0-9_]{3,32}$', v):
|
if not re.match(r'^[a-z0-9_]{3,32}$', v):
|
||||||
raise ValueError('username должен содержать только a-z, 0-9, _ (3-32 символа)')
|
raise ValueError('username должен содержать только a-z, 0-9, _ (3-32 символа)')
|
||||||
return v
|
return v
|
||||||
|
|
||||||
@field_validator('display_name')
|
@field_validator('display_name')
|
||||||
@classmethod
|
@classmethod
|
||||||
def validate_display_name(cls, v):
|
def validate_display_name(cls, v):
|
||||||
@@ -24,10 +23,18 @@ class CreateUserRequest(BaseModel):
|
|||||||
raise ValueError('display_name не может состоять только из пробелов')
|
raise ValueError('display_name не может состоять только из пробелов')
|
||||||
return v
|
return v
|
||||||
|
|
||||||
|
@field_validator('password')
|
||||||
|
@classmethod
|
||||||
|
def validate_password(cls, v):
|
||||||
|
if not v.strip():
|
||||||
|
raise ValueError('password не может состоять только из пробелов')
|
||||||
|
return v
|
||||||
|
|
||||||
|
|
||||||
class CreateChatRequest(BaseModel):
|
class CreateChatRequest(BaseModel):
|
||||||
title: str = Field(..., min_length=1, max_length=100)
|
title: str = Field(..., min_length=1, max_length=100)
|
||||||
member_ids: List[str] = Field(..., min_length=1, max_length=100)
|
member_ids: List[str] = Field(..., min_length=1, max_length=100)
|
||||||
|
|
||||||
@field_validator('title')
|
@field_validator('title')
|
||||||
@classmethod
|
@classmethod
|
||||||
def validate_title(cls, v):
|
def validate_title(cls, v):
|
||||||
@@ -35,9 +42,10 @@ class CreateChatRequest(BaseModel):
|
|||||||
raise ValueError('title не может состоять только из пробелов')
|
raise ValueError('title не может состоять только из пробелов')
|
||||||
return v
|
return v
|
||||||
|
|
||||||
|
|
||||||
class CreateMessageRequest(BaseModel):
|
class CreateMessageRequest(BaseModel):
|
||||||
text: str = Field(..., min_length=1, max_length=4000)
|
text: str = Field(..., min_length=1, max_length=4000)
|
||||||
|
|
||||||
@field_validator('text')
|
@field_validator('text')
|
||||||
@classmethod
|
@classmethod
|
||||||
def validate_text(cls, v):
|
def validate_text(cls, v):
|
||||||
@@ -52,12 +60,14 @@ class UserResponse(BaseModel):
|
|||||||
display_name: str
|
display_name: str
|
||||||
created_at: str
|
created_at: str
|
||||||
|
|
||||||
|
|
||||||
class ChatResponse(BaseModel):
|
class ChatResponse(BaseModel):
|
||||||
id: str
|
id: str
|
||||||
title: str
|
title: str
|
||||||
member_ids: List[str]
|
member_ids: List[str]
|
||||||
created_at: str
|
created_at: str
|
||||||
|
|
||||||
|
|
||||||
class MessageResponse(BaseModel):
|
class MessageResponse(BaseModel):
|
||||||
id: str
|
id: str
|
||||||
chat_id: str
|
chat_id: str
|
||||||
@@ -65,200 +75,23 @@ class MessageResponse(BaseModel):
|
|||||||
text: str
|
text: str
|
||||||
created_at: str
|
created_at: str
|
||||||
|
|
||||||
|
|
||||||
class ChatPage(BaseModel):
|
class ChatPage(BaseModel):
|
||||||
items: List[ChatResponse]
|
items: List[ChatResponse]
|
||||||
next_cursor: Optional[str] = None
|
next_cursor: Optional[str] = None
|
||||||
|
|
||||||
|
|
||||||
class MessagePage(BaseModel):
|
class MessagePage(BaseModel):
|
||||||
items: List[MessageResponse]
|
items: List[MessageResponse]
|
||||||
next_cursor: Optional[str] = None
|
next_cursor: Optional[str] = None
|
||||||
|
|
||||||
|
|
||||||
|
class SessionResponse(BaseModel):
|
||||||
|
token: str
|
||||||
|
token_type: str = "Bearer"
|
||||||
|
expires_at: str
|
||||||
|
user: UserResponse
|
||||||
|
|
||||||
|
|
||||||
class HealthResponse(BaseModel):
|
class HealthResponse(BaseModel):
|
||||||
status: str = "ok"
|
status: str = "ok"
|
||||||
|
|
||||||
class ErrorResponse(BaseModel):
|
|
||||||
error: dict
|
|
||||||
|
|
||||||
|
|
||||||
class InMemoryStore:
|
|
||||||
def __init__(self):
|
|
||||||
self._lock = asyncio.Lock()
|
|
||||||
self.users: Dict[str, dict] = {} # id -> user
|
|
||||||
self.chats: Dict[str, dict] = {} # id -> chat
|
|
||||||
self.messages: Dict[str, List[dict]] = {} # chat_id -> [messages]
|
|
||||||
self.usernames: Dict[str, str] = {} # username -> user_id (для проверки уникальности)
|
|
||||||
|
|
||||||
|
|
||||||
async def create_user(self, username: str, display_name: str) -> dict:
|
|
||||||
async with self._lock:
|
|
||||||
if username in self.usernames:
|
|
||||||
raise ValueError("username_already_exists")
|
|
||||||
|
|
||||||
user_id = str(uuid4())
|
|
||||||
now = datetime.now(timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ')
|
|
||||||
|
|
||||||
user = {
|
|
||||||
"id": user_id,
|
|
||||||
"username": username,
|
|
||||||
"display_name": display_name,
|
|
||||||
"created_at": now
|
|
||||||
}
|
|
||||||
|
|
||||||
self.users[user_id] = user
|
|
||||||
self.usernames[username] = user_id
|
|
||||||
|
|
||||||
return user
|
|
||||||
|
|
||||||
async def get_user(self, user_id: str) -> Optional[dict]:
|
|
||||||
async with self._lock:
|
|
||||||
return self.users.get(user_id)
|
|
||||||
|
|
||||||
async def get_user_by_username(self, username: str) -> Optional[dict]:
|
|
||||||
async with self._lock:
|
|
||||||
user_id = self.usernames.get(username)
|
|
||||||
if user_id:
|
|
||||||
return self.users.get(user_id)
|
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
async def create_chat(self, title: str, member_ids: List[str], creator_id: str) -> dict:
|
|
||||||
async with self._lock:
|
|
||||||
# Проверяем, что все участники существуют
|
|
||||||
for member_id in member_ids:
|
|
||||||
if member_id not in self.users:
|
|
||||||
raise ValueError("user_not_found")
|
|
||||||
|
|
||||||
# Проверяем, что создатель входит в список участников
|
|
||||||
if creator_id not in member_ids:
|
|
||||||
raise ValueError("creator_not_in_members")
|
|
||||||
|
|
||||||
# Проверяем уникальность member_ids
|
|
||||||
if len(member_ids) != len(set(member_ids)):
|
|
||||||
raise ValueError("duplicate_members")
|
|
||||||
|
|
||||||
chat_id = str(uuid4())
|
|
||||||
now = datetime.now(timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ')
|
|
||||||
|
|
||||||
chat = {
|
|
||||||
"id": chat_id,
|
|
||||||
"title": title,
|
|
||||||
"member_ids": member_ids,
|
|
||||||
"created_at": now
|
|
||||||
}
|
|
||||||
|
|
||||||
self.chats[chat_id] = chat
|
|
||||||
self.messages[chat_id] = []
|
|
||||||
|
|
||||||
return chat
|
|
||||||
|
|
||||||
async def get_chat(self, chat_id: str, user_id: str) -> Optional[dict]:
|
|
||||||
async with self._lock:
|
|
||||||
chat = self.chats.get(chat_id)
|
|
||||||
if not chat:
|
|
||||||
return None
|
|
||||||
|
|
||||||
# Проверяем, что пользователь является участником
|
|
||||||
if user_id not in chat["member_ids"]:
|
|
||||||
return None
|
|
||||||
|
|
||||||
return chat
|
|
||||||
|
|
||||||
async def list_chats(self, user_id: str, limit: int = 50, cursor: Optional[str] = None) -> tuple:
|
|
||||||
async with self._lock:
|
|
||||||
# Получаем все чаты пользователя
|
|
||||||
user_chats = [
|
|
||||||
chat for chat in self.chats.values()
|
|
||||||
if user_id in chat["member_ids"]
|
|
||||||
]
|
|
||||||
|
|
||||||
# Сортируем по (created_at, id)
|
|
||||||
user_chats.sort(key=lambda c: (c["created_at"], c["id"]))
|
|
||||||
|
|
||||||
# Применяем cursor
|
|
||||||
if cursor:
|
|
||||||
# cursor — это "created_at,id" последнего элемента предыдущей страницы
|
|
||||||
cursor_parts = cursor.split(",", 1)
|
|
||||||
if len(cursor_parts) == 2:
|
|
||||||
cursor_time, cursor_id = cursor_parts
|
|
||||||
user_chats = [
|
|
||||||
c for c in user_chats
|
|
||||||
if (c["created_at"], c["id"]) > (cursor_time, cursor_id)
|
|
||||||
]
|
|
||||||
|
|
||||||
# Ограничиваем количество
|
|
||||||
has_more = len(user_chats) > limit
|
|
||||||
page = user_chats[:limit]
|
|
||||||
|
|
||||||
# Формируем next_cursor
|
|
||||||
next_cursor = None
|
|
||||||
if has_more and page:
|
|
||||||
last_item = page[-1]
|
|
||||||
next_cursor = f"{last_item['created_at']},{last_item['id']}"
|
|
||||||
|
|
||||||
return page, next_cursor
|
|
||||||
|
|
||||||
|
|
||||||
async def create_message(self, chat_id: str, sender_id: str, text: str) -> dict:
|
|
||||||
async with self._lock:
|
|
||||||
# Проверяем, что чат существует
|
|
||||||
if chat_id not in self.chats:
|
|
||||||
raise ValueError("chat_not_found")
|
|
||||||
|
|
||||||
# Проверяем, что отправитель является участником чата
|
|
||||||
chat = self.chats[chat_id]
|
|
||||||
if sender_id not in chat["member_ids"]:
|
|
||||||
raise ValueError("sender_not_in_chat")
|
|
||||||
|
|
||||||
message_id = str(uuid4())
|
|
||||||
now = datetime.now(timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ')
|
|
||||||
|
|
||||||
message = {
|
|
||||||
"id": message_id,
|
|
||||||
"chat_id": chat_id,
|
|
||||||
"sender_id": sender_id,
|
|
||||||
"text": text,
|
|
||||||
"created_at": now
|
|
||||||
}
|
|
||||||
|
|
||||||
self.messages[chat_id].append(message)
|
|
||||||
|
|
||||||
return message
|
|
||||||
|
|
||||||
async def list_messages(self, chat_id: str, user_id: str, limit: int = 50, cursor: Optional[str] = None) -> tuple:
|
|
||||||
async with self._lock:
|
|
||||||
# Проверяем, что чат существует и пользователь является участником
|
|
||||||
chat = self.chats.get(chat_id)
|
|
||||||
if not chat:
|
|
||||||
raise ValueError("chat_not_found")
|
|
||||||
|
|
||||||
if user_id not in chat["member_ids"]:
|
|
||||||
raise ValueError("user_not_in_chat")
|
|
||||||
|
|
||||||
messages = self.messages.get(chat_id, [])
|
|
||||||
|
|
||||||
# Сортируем по (created_at, id)
|
|
||||||
messages.sort(key=lambda m: (m["created_at"], m["id"]))
|
|
||||||
|
|
||||||
# Применяем cursor
|
|
||||||
if cursor:
|
|
||||||
cursor_parts = cursor.split(",", 1)
|
|
||||||
if len(cursor_parts) == 2:
|
|
||||||
cursor_time, cursor_id = cursor_parts
|
|
||||||
messages = [
|
|
||||||
m for m in messages
|
|
||||||
if (m["created_at"], m["id"]) > (cursor_time, cursor_id)
|
|
||||||
]
|
|
||||||
|
|
||||||
# Ограничиваем количество
|
|
||||||
has_more = len(messages) > limit
|
|
||||||
page = messages[:limit]
|
|
||||||
|
|
||||||
# Формируем next_cursor
|
|
||||||
next_cursor = None
|
|
||||||
if has_more and page:
|
|
||||||
last_item = page[-1]
|
|
||||||
next_cursor = f"{last_item['created_at']},{last_item['id']}"
|
|
||||||
|
|
||||||
return page, next_cursor
|
|
||||||
|
|
||||||
store = InMemoryStore()
|
|
||||||
Reference in New Issue
Block a user