ЛР 2 — PostgreSQL и сессии Redis
This commit is contained in:
@@ -0,0 +1,140 @@
|
||||
"""PostgreSQL storage for users, chats, membership and message history."""
|
||||
|
||||
from contextlib import contextmanager
|
||||
from uuid import UUID
|
||||
|
||||
from psycopg import OperationalError
|
||||
from psycopg.errors import ForeignKeyViolation, LockNotAvailable, QueryCanceled
|
||||
from psycopg.rows import dict_row
|
||||
from psycopg_pool import ConnectionPool, TooManyRequests
|
||||
|
||||
from .config import postgres_options
|
||||
from .errors import bad_request, conflict, not_found, unavailable
|
||||
from .pagination import Cursors
|
||||
|
||||
|
||||
class Store:
|
||||
def __init__(self, cursor_secret: bytes):
|
||||
self.cursors = Cursors(cursor_secret)
|
||||
self.pool = ConnectionPool(
|
||||
kwargs={**postgres_options(), "row_factory": dict_row},
|
||||
min_size=1, max_size=8, max_waiting=16, timeout=2, open=False,
|
||||
)
|
||||
self.pool.open()
|
||||
|
||||
@contextmanager
|
||||
def connection(self):
|
||||
try:
|
||||
# Commits on success and rolls back on any exception before reuse.
|
||||
with self.pool.connection() as conn:
|
||||
yield conn
|
||||
except (OperationalError, TooManyRequests, LockNotAvailable, QueryCanceled):
|
||||
raise unavailable("PostgreSQL unavailable") from None
|
||||
|
||||
def ready(self) -> None:
|
||||
with self.connection() as conn:
|
||||
conn.execute("SELECT 1")
|
||||
|
||||
def create_user(self, username: str, display_name: str, salt: bytes, password_hash: bytes) -> dict:
|
||||
with self.connection() as conn:
|
||||
user = conn.execute("""
|
||||
INSERT INTO users (username, display_name, password_salt, password_hash)
|
||||
VALUES (%s, %s, %s, %s)
|
||||
ON CONFLICT (username) DO NOTHING
|
||||
RETURNING id, username, display_name, created_at
|
||||
""", (username, display_name, salt, password_hash)).fetchone()
|
||||
if user is None:
|
||||
raise conflict("username is already taken")
|
||||
return user
|
||||
|
||||
def get_user(self, user_id: UUID) -> dict | None:
|
||||
with self.connection() as conn:
|
||||
return conn.execute("""
|
||||
SELECT id, username, display_name, created_at FROM users WHERE id = %s
|
||||
""", (user_id,)).fetchone()
|
||||
|
||||
def credentials(self, username: str) -> dict | None:
|
||||
with self.connection() as conn:
|
||||
return conn.execute("""
|
||||
SELECT id, username, display_name, created_at, password_salt, password_hash
|
||||
FROM users WHERE username = %s
|
||||
""", (username,)).fetchone()
|
||||
|
||||
def create_chat(self, user_id: UUID, title: str, member_ids: list[UUID]) -> dict:
|
||||
if user_id not in member_ids:
|
||||
raise bad_request("member_ids must include the current user")
|
||||
try:
|
||||
with self.connection() as conn:
|
||||
chat = conn.execute("""
|
||||
INSERT INTO chats (title) VALUES (%s) RETURNING id, title, created_at
|
||||
""", (title,)).fetchone()
|
||||
conn.execute("""
|
||||
INSERT INTO chat_members (chat_id, user_id, position)
|
||||
SELECT %s, user_id, position
|
||||
FROM unnest(%s::uuid[]) WITH ORDINALITY AS members(user_id, position)
|
||||
""", (chat["id"], member_ids))
|
||||
except ForeignKeyViolation:
|
||||
raise bad_request("member_ids contains an unknown user") from None
|
||||
return {**chat, "member_ids": member_ids}
|
||||
|
||||
def get_chat(self, user_id: UUID, chat_id: UUID) -> dict:
|
||||
with self.connection() as conn:
|
||||
chat = conn.execute("""
|
||||
SELECT c.id, c.title, c.created_at,
|
||||
ARRAY(SELECT m.user_id FROM chat_members m
|
||||
WHERE m.chat_id = c.id ORDER BY m.position) AS member_ids
|
||||
FROM chat_members member JOIN chats c ON c.id = member.chat_id
|
||||
WHERE member.user_id = %s AND c.id = %s
|
||||
""", (user_id, chat_id)).fetchone()
|
||||
if chat is None:
|
||||
raise not_found("chat not found")
|
||||
return chat
|
||||
|
||||
def list_chats(self, user_id: UUID, limit: int, cursor: str | None) -> dict:
|
||||
scope = f"chats:{user_id}"
|
||||
query = """
|
||||
SELECT c.id, c.title, c.created_at,
|
||||
ARRAY(SELECT m.user_id FROM chat_members m
|
||||
WHERE m.chat_id = c.id ORDER BY m.position) AS member_ids
|
||||
FROM chat_members member JOIN chats c ON c.id = member.chat_id
|
||||
WHERE member.user_id = %s
|
||||
"""
|
||||
params = (user_id,)
|
||||
if cursor is not None:
|
||||
query += " AND (c.created_at, c.id) > (%s, %s)"
|
||||
params += self.cursors.decode(scope, cursor)
|
||||
with self.connection() as conn:
|
||||
items = conn.execute(
|
||||
query + " ORDER BY c.created_at, c.id LIMIT %s", (*params, limit + 1)
|
||||
).fetchall()
|
||||
return self.cursors.page(scope, items, limit)
|
||||
|
||||
def add_message(self, user_id: UUID, chat_id: UUID, text: str) -> dict:
|
||||
with self.connection() as conn:
|
||||
message = conn.execute("""
|
||||
INSERT INTO messages (chat_id, sender_id, text)
|
||||
SELECT chat_id, user_id, %s FROM chat_members
|
||||
WHERE chat_id = %s AND user_id = %s
|
||||
RETURNING id, chat_id, sender_id, text, created_at
|
||||
""", (text, chat_id, user_id)).fetchone()
|
||||
if message is None:
|
||||
raise not_found("chat not found")
|
||||
return message
|
||||
|
||||
def list_messages(self, user_id: UUID, chat_id: UUID, limit: int, cursor: str | None) -> dict:
|
||||
scope = f"messages:{chat_id}"
|
||||
query = "SELECT id, chat_id, sender_id, text, created_at FROM messages WHERE chat_id = %s"
|
||||
params = (chat_id,)
|
||||
with self.connection() as conn:
|
||||
member = conn.execute(
|
||||
"SELECT 1 FROM chat_members WHERE chat_id = %s AND user_id = %s", (chat_id, user_id)
|
||||
).fetchone()
|
||||
if member is None:
|
||||
raise not_found("chat not found")
|
||||
if cursor is not None:
|
||||
query += " AND (created_at, id) > (%s, %s)"
|
||||
params += self.cursors.decode(scope, cursor)
|
||||
items = conn.execute(
|
||||
query + " ORDER BY created_at, id LIMIT %s", (*params, limit + 1)
|
||||
).fetchall()
|
||||
return self.cursors.page(scope, items, limit)
|
||||
Reference in New Issue
Block a user