+ добавила БД постгрес
This commit is contained in:
+1
-1
@@ -5,7 +5,7 @@ APP_PORT=8080
|
|||||||
APP_ENV=lab
|
APP_ENV=lab
|
||||||
SESSION_TTL_SECONDS=3600
|
SESSION_TTL_SECONDS=3600
|
||||||
# Choose credentials locally. File paths contain no secret values.
|
# 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:
|
# Optional on 3, required use on 4 in lab2; Redis OR Valkey:
|
||||||
SESSION_STORE=postgres
|
SESSION_STORE=postgres
|
||||||
CACHE_URL_FILE=/run/secrets/cache_url
|
CACHE_URL_FILE=/run/secrets/cache_url
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
fastapi==0.115.0
|
fastapi==0.115.0
|
||||||
uvicorn[standard]==0.32.0
|
uvicorn[standard]==0.32.0
|
||||||
|
psycopg[binary]==3.2.3
|
||||||
openapi-spec-validator==0.7.2
|
openapi-spec-validator==0.7.2
|
||||||
+1
-1
@@ -6,7 +6,7 @@ from fastapi import APIRouter, Depends, HTTPException, Request
|
|||||||
from fastapi.security import HTTPBasic, HTTPBasicCredentials
|
from fastapi.security import HTTPBasic, HTTPBasicCredentials
|
||||||
|
|
||||||
from ..models.schemas import Session
|
from ..models.schemas import Session
|
||||||
from ..storage.memory import storage
|
from ..storage.postgres import storage
|
||||||
|
|
||||||
|
|
||||||
router = APIRouter(prefix="/api/v1/auth", tags=["auth"])
|
router = APIRouter(prefix="/api/v1/auth", tags=["auth"])
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ import json
|
|||||||
from uuid import UUID
|
from uuid import UUID
|
||||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||||
from ..models.schemas import Chat, ChatPage, CreateChat, User
|
from ..models.schemas import Chat, ChatPage, CreateChat, User
|
||||||
from ..storage.memory import storage
|
from ..storage.postgres import storage
|
||||||
from .security import current_user
|
from .security import current_user
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ import json
|
|||||||
from uuid import UUID
|
from uuid import UUID
|
||||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||||
from ..models.schemas import CreateMessage, Message, MessagePage, User
|
from ..models.schemas import CreateMessage, Message, MessagePage, User
|
||||||
from ..storage.memory import storage
|
from ..storage.postgres import storage
|
||||||
from .security import current_user
|
from .security import current_user
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ from fastapi import HTTPException, Security
|
|||||||
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
||||||
|
|
||||||
from ..models.schemas import User
|
from ..models.schemas import User
|
||||||
from ..storage.memory import storage
|
from ..storage.postgres import storage
|
||||||
|
|
||||||
bearer_scheme = HTTPBearer(auto_error=False, scheme_name="bearerAuth")
|
bearer_scheme = HTTPBearer(auto_error=False, scheme_name="bearerAuth")
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
from fastapi import APIRouter, Depends, HTTPException
|
from fastapi import APIRouter, Depends, HTTPException
|
||||||
from ..models.schemas import CreateUser, User
|
from ..models.schemas import CreateUser, User
|
||||||
from ..storage.memory import storage
|
from ..storage.postgres import storage
|
||||||
from .security import current_user
|
from .security import current_user
|
||||||
|
|
||||||
router = APIRouter(prefix="/api/v1", tags=["users"])
|
router = APIRouter(prefix="/api/v1", tags=["users"])
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ from fastapi.responses import JSONResponse
|
|||||||
from starlette.exceptions import HTTPException as StarletteHTTPException
|
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||||
import uvicorn
|
import uvicorn
|
||||||
from .api import auth, chats, health, messages, users
|
from .api import auth, chats, health, messages, users
|
||||||
|
from .storage.db import init_schema
|
||||||
|
|
||||||
|
|
||||||
# --- Логирование: структурированный stdout, без содержимого сообщений ---
|
# --- Логирование: структурированный stdout, без содержимого сообщений ---
|
||||||
@@ -25,6 +26,7 @@ logger = logging.getLogger("app")
|
|||||||
|
|
||||||
@asynccontextmanager
|
@asynccontextmanager
|
||||||
async def lifespan(app: FastAPI):
|
async def lifespan(app: FastAPI):
|
||||||
|
init_schema()
|
||||||
logger.info("event=startup app_env=%s", os.environ.get("APP_ENV", "lab"))
|
logger.info("event=startup app_env=%s", os.environ.get("APP_ENV", "lab"))
|
||||||
yield
|
yield
|
||||||
logger.info("event=shutdown_complete")
|
logger.info("event=shutdown_complete")
|
||||||
|
|||||||
@@ -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()
|
||||||
@@ -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() # единственный экземпляр на процесс
|
||||||
Reference in New Issue
Block a user