From 19d3767ef3e19c94308634092b95a16e0e21d9cb Mon Sep 17 00:00:00 2001 From: vasyukova Date: Wed, 30 Sep 2026 22:38:32 +0300 Subject: [PATCH] =?UTF-8?q?+=20=D0=B4=D0=BE=D0=B1=D0=B0=D0=B2=D0=B8=D0=BB?= =?UTF-8?q?=D0=B0=20=D0=91=D0=94=20=D0=BF=D0=BE=D1=81=D1=82=D0=B3=D1=80?= =?UTF-8?q?=D0=B5=D1=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .env.example | 2 +- requirements.txt | 1 + src/app/api/auth.py | 2 +- src/app/api/chats.py | 2 +- src/app/api/messages.py | 2 +- src/app/api/security.py | 2 +- src/app/api/users.py | 2 +- src/app/main.py | 2 + src/app/storage/db.py | 69 ++++++++++ src/app/storage/postgres.py | 249 ++++++++++++++++++++++++++++++++++++ 10 files changed, 327 insertions(+), 6 deletions(-) create mode 100644 src/app/storage/db.py create mode 100644 src/app/storage/postgres.py diff --git a/.env.example b/.env.example index 714c8076..daa1b84e 100644 --- a/.env.example +++ b/.env.example @@ -5,7 +5,7 @@ APP_PORT=8080 APP_ENV=lab SESSION_TTL_SECONDS=3600 # Choose credentials locally. File paths contain no secret values. -DATABASE_URL_FILE=/run/secrets/database_url +DATABASE_URL_FILE=postgresql://user:password@localhost:5432/high_load_messenger # Optional on 3, required use on 4 in lab2; Redis OR Valkey: SESSION_STORE=postgres CACHE_URL_FILE=/run/secrets/cache_url diff --git a/requirements.txt b/requirements.txt index e17eb12c..3c3be538 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,3 +1,4 @@ fastapi==0.115.0 uvicorn[standard]==0.32.0 +psycopg[binary]==3.2.3 openapi-spec-validator==0.7.2 \ No newline at end of file diff --git a/src/app/api/auth.py b/src/app/api/auth.py index 907ffe44..9c29e100 100644 --- a/src/app/api/auth.py +++ b/src/app/api/auth.py @@ -6,7 +6,7 @@ from fastapi import APIRouter, Depends, HTTPException, Request from fastapi.security import HTTPBasic, HTTPBasicCredentials from ..models.schemas import Session -from ..storage.memory import storage +from ..storage.postgres import storage router = APIRouter(prefix="/api/v1/auth", tags=["auth"]) diff --git a/src/app/api/chats.py b/src/app/api/chats.py index d1d92660..46132ed0 100644 --- a/src/app/api/chats.py +++ b/src/app/api/chats.py @@ -3,7 +3,7 @@ import json from uuid import UUID from fastapi import APIRouter, Depends, HTTPException, Query from ..models.schemas import Chat, ChatPage, CreateChat, User -from ..storage.memory import storage +from ..storage.postgres import storage from .security import current_user diff --git a/src/app/api/messages.py b/src/app/api/messages.py index 0c405e6b..2449112c 100644 --- a/src/app/api/messages.py +++ b/src/app/api/messages.py @@ -3,7 +3,7 @@ import json from uuid import UUID from fastapi import APIRouter, Depends, HTTPException, Query from ..models.schemas import CreateMessage, Message, MessagePage, User -from ..storage.memory import storage +from ..storage.postgres import storage from .security import current_user diff --git a/src/app/api/security.py b/src/app/api/security.py index d20025a3..fc09938f 100644 --- a/src/app/api/security.py +++ b/src/app/api/security.py @@ -4,7 +4,7 @@ from fastapi import HTTPException, Security from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer from ..models.schemas import User -from ..storage.memory import storage +from ..storage.postgres import storage bearer_scheme = HTTPBearer(auto_error=False, scheme_name="bearerAuth") diff --git a/src/app/api/users.py b/src/app/api/users.py index 727cc080..b821024f 100644 --- a/src/app/api/users.py +++ b/src/app/api/users.py @@ -1,6 +1,6 @@ from fastapi import APIRouter, Depends, HTTPException from ..models.schemas import CreateUser, User -from ..storage.memory import storage +from ..storage.postgres import storage from .security import current_user router = APIRouter(prefix="/api/v1", tags=["users"]) diff --git a/src/app/main.py b/src/app/main.py index d8981b70..1dc82ec0 100644 --- a/src/app/main.py +++ b/src/app/main.py @@ -12,6 +12,7 @@ from fastapi.responses import JSONResponse from starlette.exceptions import HTTPException as StarletteHTTPException import uvicorn from .api import auth, chats, health, messages, users +from .storage.db import init_schema # --- Логирование: структурированный stdout, без содержимого сообщений --- @@ -25,6 +26,7 @@ logger = logging.getLogger("app") @asynccontextmanager async def lifespan(app: FastAPI): + init_schema() logger.info("event=startup app_env=%s", os.environ.get("APP_ENV", "lab")) yield logger.info("event=shutdown_complete") diff --git a/src/app/storage/db.py b/src/app/storage/db.py new file mode 100644 index 00000000..40be8902 --- /dev/null +++ b/src/app/storage/db.py @@ -0,0 +1,69 @@ +import os +from contextlib import contextmanager +from typing import Iterator + +import psycopg + + +def _dsn() -> str: + dsn = os.environ.get("DATABASE_URL") + if not dsn: + raise RuntimeError("DATABASE_URL is not set") + return dsn + + +@contextmanager +def connection() -> Iterator[psycopg.Connection]: + """Одно соединение на запрос; autocommit=False для явных транзакций.""" + conn = psycopg.connect(_dsn()) + try: + yield conn + finally: + conn.close() + + +SCHEMA_SQL = """ +CREATE TABLE IF NOT EXISTS users ( + id UUID PRIMARY KEY, + username TEXT NOT NULL UNIQUE, + display_name TEXT NOT NULL, + password_hash TEXT NOT NULL, + created_at TIMESTAMPTZ NOT NULL +); + +CREATE TABLE IF NOT EXISTS chats ( + id UUID PRIMARY KEY, + title TEXT NOT NULL, + created_at TIMESTAMPTZ NOT NULL +); + +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, + 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, + created_at TIMESTAMPTZ NOT NULL +); +CREATE INDEX IF NOT EXISTS idx_messages_chat_created + ON messages (chat_id, created_at, id); + +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 +); +""" + + +def init_schema() -> None: + """Идемпотентная миграция: запускается на старте приложения.""" + with connection() as conn: + with conn.cursor() as cur: + cur.execute(SCHEMA_SQL) + conn.commit() \ No newline at end of file diff --git a/src/app/storage/postgres.py b/src/app/storage/postgres.py new file mode 100644 index 00000000..8f6f4a4d --- /dev/null +++ b/src/app/storage/postgres.py @@ -0,0 +1,249 @@ +import hashlib +import hmac +import secrets +import threading +from datetime import datetime, timedelta, timezone +from typing import List, Optional +from uuid import UUID, uuid4 + +from ..models.schemas import Chat, Message, User +from .db import connection + + +def now_utc() -> datetime: + return datetime.now(timezone.utc) + + +# --- Password KDF (stdlib scrypt) --- +_SCRYPT_N = 2 ** 14 +_SCRYPT_R = 8 +_SCRYPT_P = 1 +_SCRYPT_DKLEN = 32 + + +def _hash_password(password: str) -> str: + salt = secrets.token_bytes(16) + dk = hashlib.scrypt( + password.encode("utf-8"), + salt=salt, + n=_SCRYPT_N, r=_SCRYPT_R, p=_SCRYPT_P, dklen=_SCRYPT_DKLEN, + ) + return "scrypt$%d$%d$%d$%s$%s" % ( + _SCRYPT_N, _SCRYPT_R, _SCRYPT_P, salt.hex(), dk.hex(), + ) + + +def _verify_password(password: str, stored: str) -> bool: + try: + scheme, n, r, p, salt_hex, dk_hex = stored.split("$") + if scheme != "scrypt": + return False + dk = hashlib.scrypt( + password.encode("utf-8"), + salt=bytes.fromhex(salt_hex), + n=int(n), r=int(r), p=int(p), + dklen=len(bytes.fromhex(dk_hex)), + ) + return hmac.compare_digest(dk.hex(), dk_hex) + except Exception: + return False + + +def _row_to_user(row) -> User: + return User(id=row[0], username=row[1], display_name=row[2], created_at=row[3]) + + +def _row_to_chat(row, member_ids: List[UUID]) -> Chat: + return Chat(id=row[0], title=row[1], member_ids=member_ids, created_at=row[2]) + + +def _row_to_message(row) -> Message: + return Message( + id=row[0], chat_id=row[1], sender_id=row[2], + text=row[3], created_at=row[4], + ) + + +class PostgresStorage: + """Потокобезопасная обёртка; параллелизм обеспечивает PostgreSQL.""" + + def __init__(self) -> None: + self._lock = threading.RLock() + + # ---------- Пользователи ---------- + def create_user(self, username: str, display_name: str, password: str) -> User: + with self._lock, connection() as conn: + with conn.cursor() as cur: + cur.execute("SELECT 1 FROM users WHERE username = %s", (username,)) + if cur.fetchone() is not None: + raise ValueError("username_taken") + user = User( + id=uuid4(), username=username, + display_name=display_name, created_at=now_utc(), + ) + cur.execute( + "INSERT INTO users (id, username, display_name, password_hash, created_at)" + " VALUES (%s, %s, %s, %s, %s)", + (user.id, user.username, user.display_name, + _hash_password(password), user.created_at), + ) + conn.commit() + return user + + def get_user(self, user_id: UUID) -> Optional[User]: + with connection() as conn, conn.cursor() as cur: + cur.execute( + "SELECT id, username, display_name, created_at FROM users WHERE id = %s", + (user_id,), + ) + row = cur.fetchone() + return _row_to_user(row) if row else None + + def get_user_by_username(self, username: str) -> Optional[User]: + with connection() as conn, conn.cursor() as cur: + cur.execute( + "SELECT id, username, display_name, created_at FROM users WHERE username = %s", + (username,), + ) + row = cur.fetchone() + return _row_to_user(row) if row else None + + def verify_credentials(self, username: str, password: str) -> Optional[User]: + with connection() as conn, conn.cursor() as cur: + cur.execute( + "SELECT id, username, display_name, created_at, password_hash" + " FROM users WHERE username = %s", + (username,), + ) + row = cur.fetchone() + if row is None: + return None + if not _verify_password(password, row[4]): + return None + return _row_to_user(row[:4]) + + # ---------- Сессии ---------- + def create_session(self, user_id: UUID, ttl_seconds: int) -> tuple: + token = secrets.token_urlsafe(32) + expires_at = now_utc() + timedelta(seconds=ttl_seconds) + with self._lock, connection() as conn: + with conn.cursor() as cur: + cur.execute( + "INSERT INTO sessions (token, user_id, expires_at) VALUES (%s, %s, %s)", + (token, user_id, expires_at), + ) + conn.commit() + return token, expires_at + + def get_session_user(self, token: str) -> Optional[User]: + with connection() as conn, conn.cursor() as cur: + cur.execute( + "SELECT u.id, u.username, u.display_name, u.created_at, s.expires_at" + " FROM sessions s JOIN users u ON u.id = s.user_id" + " WHERE s.token = %s", + (token,), + ) + row = cur.fetchone() + if row is None: + return None + if row[4] <= now_utc(): + with conn.cursor() as cur2: + cur2.execute("DELETE FROM sessions WHERE token = %s", (token,)) + conn.commit() + return None + return _row_to_user(row[:4]) + + def revoke_session(self, token: str) -> None: + with self._lock, connection() as conn: + with conn.cursor() as cur: + cur.execute("DELETE FROM sessions WHERE token = %s", (token,)) + conn.commit() + + # ---------- Чаты ---------- + def create_chat(self, title: str, member_ids: List[UUID]) -> Chat: + with self._lock, connection() as conn: + with conn.cursor() as cur: + # проверяем всех участников + cur.execute( + "SELECT id FROM users WHERE id = ANY(%s)", + (list(member_ids),), + ) + found = {r[0] for r in cur.fetchall()} + if len(found) != len(set(member_ids)): + raise ValueError("unknown_member") + chat = Chat( + id=uuid4(), title=title, + member_ids=list(member_ids), created_at=now_utc(), + ) + cur.execute( + "INSERT INTO chats (id, title, created_at) VALUES (%s, %s, %s)", + (chat.id, chat.title, chat.created_at), + ) + cur.executemany( + "INSERT INTO chat_members (chat_id, user_id) VALUES (%s, %s)", + [(chat.id, uid) for uid in member_ids], + ) + conn.commit() + return chat + + def get_chat(self, chat_id: UUID) -> Optional[Chat]: + with connection() as conn, conn.cursor() as cur: + cur.execute( + "SELECT id, title, created_at FROM chats WHERE id = %s", + (chat_id,), + ) + row = cur.fetchone() + if row is None: + return None + cur.execute( + "SELECT user_id FROM chat_members WHERE chat_id = %s", (chat_id,), + ) + members = [r[0] for r in cur.fetchall()] + return _row_to_chat(row, members) + + def list_chats_for_user(self, user_id: UUID) -> List[Chat]: + with connection() as conn, conn.cursor() as cur: + cur.execute( + "SELECT c.id, c.title, c.created_at FROM chats c" + " JOIN chat_members m ON m.chat_id = c.id" + " WHERE m.user_id = %s ORDER BY c.created_at, c.id", + (user_id,), + ) + rows = cur.fetchall() + chats = [] + for row in rows: + cur.execute( + "SELECT user_id FROM chat_members WHERE chat_id = %s", (row[0],), + ) + members = [r[0] for r in cur.fetchall()] + chats.append(_row_to_chat(row, members)) + return chats + + # ---------- Сообщения ---------- + def add_message(self, chat_id: UUID, sender_id: UUID, text: str) -> Message: + with self._lock, connection() as conn: + message = Message( + id=uuid4(), chat_id=chat_id, sender_id=sender_id, + text=text, created_at=now_utc(), + ) + with conn.cursor() as cur: + cur.execute( + "INSERT INTO messages (id, chat_id, sender_id, text, created_at)" + " VALUES (%s, %s, %s, %s, %s)", + (message.id, message.chat_id, message.sender_id, + message.text, message.created_at), + ) + conn.commit() + return message + + def list_messages(self, chat_id: UUID) -> List[Message]: + with connection() as conn, conn.cursor() as cur: + cur.execute( + "SELECT id, chat_id, sender_id, text, created_at FROM messages" + " WHERE chat_id = %s ORDER BY created_at, id", + (chat_id,), + ) + return [_row_to_message(r) for r in cur.fetchall()] + + +storage = PostgresStorage() # единственный экземпляр на процесс \ No newline at end of file