forked from mtusi2026/mtusi2026lab2
+ добавила функционал на 4 + тесты
This commit is contained in:
+56
-38
@@ -2,12 +2,17 @@ import hashlib
|
||||
import hmac
|
||||
import secrets
|
||||
import threading
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from datetime import datetime, timezone
|
||||
from typing import List, Optional
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
from ..models.schemas import Chat, Message, User
|
||||
from .db import connection
|
||||
from .sessions import (
|
||||
create_session as _sess_create,
|
||||
get_session_user as _sess_get,
|
||||
revoke_session as _sess_revoke,
|
||||
)
|
||||
|
||||
|
||||
def now_utc() -> datetime:
|
||||
@@ -74,6 +79,8 @@ class PostgresStorage:
|
||||
def create_user(self, username: str, display_name: str, password: str) -> User:
|
||||
with self._lock, connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
# SELECT-проверка + INSERT в одной транзакции; уникальный индекс
|
||||
# users.username отсекает гонку на уровне БД (UniqueViolation).
|
||||
cur.execute("SELECT 1 FROM users WHERE username = %s", (username,))
|
||||
if cur.fetchone() is not None:
|
||||
raise ValueError("username_taken")
|
||||
@@ -81,12 +88,19 @@ class PostgresStorage:
|
||||
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),
|
||||
)
|
||||
try:
|
||||
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),
|
||||
)
|
||||
except Exception as exc:
|
||||
# Параллельная регистрация того же username: уникальный индекс
|
||||
# выбросил UniqueViolation — превращаем в доменную ошибку.
|
||||
if exc.__class__.__name__ == "UniqueViolation":
|
||||
raise ValueError("username_taken")
|
||||
raise
|
||||
conn.commit()
|
||||
return user
|
||||
|
||||
@@ -122,42 +136,17 @@ class PostgresStorage:
|
||||
return None
|
||||
return _row_to_user(row[:4])
|
||||
|
||||
# ---------- Сессии ----------
|
||||
# ---------- Сессии (Redis или PostgreSQL — см. storage/sessions.py) ----------
|
||||
# Тонкие делегаты: роутеры продолжают вызывать storage.create_session(...),
|
||||
# storage.get_session_user(...), storage.revoke_session(...) без изменений.
|
||||
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
|
||||
return _sess_create(user_id, ttl_seconds)
|
||||
|
||||
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])
|
||||
return _sess_get(token)
|
||||
|
||||
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()
|
||||
_sess_revoke(token)
|
||||
|
||||
# ---------- Чаты ----------
|
||||
def create_chat(self, title: str, member_ids: List[UUID]) -> Chat:
|
||||
@@ -245,5 +234,34 @@ class PostgresStorage:
|
||||
)
|
||||
return [_row_to_message(r) for r in cur.fetchall()]
|
||||
|
||||
def list_messages_page(
|
||||
self,
|
||||
chat_id: UUID,
|
||||
limit: int,
|
||||
after: Optional[tuple] = None,
|
||||
) -> List[Message]:
|
||||
"""Keyset-пагинация в SQL
|
||||
|
||||
after = (created_at, id) последней записи предыдущей страницы или None.
|
||||
Запрос использует индекс idx_messages_chat_created (chat_id, created_at, id)
|
||||
и не делает полный scan всей истории на каждую страницу.
|
||||
"""
|
||||
with connection() as conn, conn.cursor() as cur:
|
||||
if after is None:
|
||||
cur.execute(
|
||||
"SELECT id, chat_id, sender_id, text, created_at FROM messages"
|
||||
" WHERE chat_id = %s ORDER BY created_at, id LIMIT %s",
|
||||
(chat_id, limit),
|
||||
)
|
||||
else:
|
||||
after_ts, after_id = after
|
||||
cur.execute(
|
||||
"SELECT id, chat_id, sender_id, text, created_at FROM messages"
|
||||
" WHERE chat_id = %s AND (created_at, id) > (%s, %s)"
|
||||
" ORDER BY created_at, id LIMIT %s",
|
||||
(chat_id, after_ts, after_id, limit),
|
||||
)
|
||||
return [_row_to_message(r) for r in cur.fetchall()]
|
||||
|
||||
|
||||
storage = PostgresStorage() # единственный экземпляр на процесс
|
||||
Reference in New Issue
Block a user