+ добавила функционал на 4 + тесты

This commit is contained in:
vasyukova
2026-10-02 01:06:35 +03:00
parent 6aed50419f
commit afd49a3515
9 changed files with 328 additions and 61 deletions
+33 -5
View File
@@ -3,6 +3,10 @@ from contextlib import contextmanager
from typing import Iterator
import psycopg
from psycopg_pool import ConnectionPool
_pool: ConnectionPool | None = None
def _dsn() -> str:
@@ -12,14 +16,37 @@ def _dsn() -> str:
return dsn
def init_pool() -> None:
"""Ограниченный пул соединений с таймаутами. Вызывается один раз на старте."""
global _pool
if _pool is not None:
return
_pool = ConnectionPool(
conninfo=_dsn(),
min_size=2,
max_size=10,
timeout=5.0,
max_idle=300.0,
kwargs={"options": "-c statement_timeout=5000"},
open=True,
)
def close_pool() -> None:
global _pool
if _pool is not None:
_pool.close()
_pool = None
@contextmanager
def connection() -> Iterator[psycopg.Connection]:
"""Одно соединение на запрос; autocommit=False для явных транзакций."""
conn = psycopg.connect(_dsn())
try:
"""Соединение из пула; autocommit=False для явных транзакций."""
if _pool is None:
init_pool()
assert _pool is not None
with _pool.connection() as conn:
yield conn
finally:
conn.close()
SCHEMA_SQL = """
@@ -53,6 +80,7 @@ CREATE TABLE IF NOT EXISTS messages (
CREATE INDEX IF NOT EXISTS idx_messages_chat_created
ON messages (chat_id, created_at, id);
-- sessions остаются как fallback, если SESSION_STORE=postgres.
CREATE TABLE IF NOT EXISTS sessions (
token TEXT PRIMARY KEY,
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+56 -38
View File
@@ -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() # единственный экземпляр на процесс