forked from mtusi2026/mtusi2026lab5
Скопировала все файлы проекта из предыдущей лаб. работы
This commit is contained in:
@@ -0,0 +1,458 @@
|
||||
import hashlib
|
||||
import hmac
|
||||
import secrets
|
||||
import threading
|
||||
from datetime import datetime, timezone
|
||||
from typing import List, Optional
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
from ..models.schemas import Attachment, Chat, Message, User, Variant
|
||||
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:
|
||||
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, attachment_ids: List[UUID]) -> Message:
|
||||
return Message(
|
||||
id=row[0], chat_id=row[1], sender_id=row[2],
|
||||
text=row[3], created_at=row[4],
|
||||
attachment_ids=attachment_ids,
|
||||
)
|
||||
|
||||
|
||||
def _row_to_attachment(row) -> Attachment:
|
||||
# row: id, chat_id, owner_id, filename, content_type, size_bytes, sha256,
|
||||
# status, error_code, created_at, updated_at
|
||||
return Attachment(
|
||||
id=row[0], chat_id=row[1], owner_id=row[2],
|
||||
filename=row[3], content_type=row[4], size_bytes=row[5],
|
||||
sha256=row[6], status=row[7], variants=[], error_code=row[8],
|
||||
created_at=row[9], updated_at=row[10],
|
||||
)
|
||||
|
||||
|
||||
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:
|
||||
# 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")
|
||||
user = User(
|
||||
id=uuid4(), username=username,
|
||||
display_name=display_name, created_at=now_utc(),
|
||||
)
|
||||
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
|
||||
|
||||
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])
|
||||
|
||||
# ---------- Сессии (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:
|
||||
return _sess_create(user_id, ttl_seconds)
|
||||
|
||||
def get_session_user(self, token: str) -> Optional[User]:
|
||||
return _sess_get(token)
|
||||
|
||||
def revoke_session(self, token: str) -> None:
|
||||
_sess_revoke(token)
|
||||
|
||||
# ---------- Чаты ----------
|
||||
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 _load_message_attachments(
|
||||
self, cur, message_ids: List[UUID]
|
||||
) -> dict[UUID, List[UUID]]:
|
||||
"""Одним запросом достаём attachment_ids для набора сообщений."""
|
||||
if not message_ids:
|
||||
return {}
|
||||
cur.execute(
|
||||
"SELECT message_id, attachment_id, position FROM message_attachments"
|
||||
" WHERE message_id = ANY(%s) ORDER BY message_id, position",
|
||||
(list(message_ids),),
|
||||
)
|
||||
result: dict[UUID, List[UUID]] = {}
|
||||
for mid, aid, _pos in cur.fetchall():
|
||||
result.setdefault(mid, []).append(aid)
|
||||
return result
|
||||
|
||||
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),
|
||||
)
|
||||
rows = cur.fetchall()
|
||||
ids = [r[0] for r in rows]
|
||||
att_map = self._load_message_attachments(cur, ids)
|
||||
return [_row_to_message(r, att_map.get(r[0], [])) for r in rows]
|
||||
|
||||
# ---------- Идемпотентность (lab3) ----------
|
||||
def add_message_idempotent(
|
||||
self,
|
||||
chat_id: UUID,
|
||||
sender_id: UUID,
|
||||
text: str,
|
||||
attachment_ids: List[UUID],
|
||||
user_id: UUID,
|
||||
method: str,
|
||||
path: str,
|
||||
key: str,
|
||||
body_hash: str,
|
||||
) -> tuple[str, Optional[Message], Optional[dict]]:
|
||||
"""Атомарная отправка сообщения с идемпотентностью.
|
||||
|
||||
Возвращает одно из:
|
||||
('created', message, None) — мы выиграли гонку и создали сообщение;
|
||||
('replay', None, info) — ключ уже занят; info = {body_hash,
|
||||
response_status, response_body}
|
||||
('retry', None, None) — конфликт при INSERT, но строки нет
|
||||
(крайне редко); вызывающий может
|
||||
повторить запрос.
|
||||
|
||||
ВСЁ делается в ОДНОЙ транзакции: либо строка idempotency_keys
|
||||
и строка messages фиксируются вместе, либо не фиксируется ничего.
|
||||
Это устраняет блокер, когда сообщение сохранено, а ключ остался
|
||||
с response_status=0 и повтор зависал.
|
||||
"""
|
||||
import json as _json
|
||||
with connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
# 1) Пытаемся занять ключ. ON CONFLICT DO NOTHING — атомарно.
|
||||
cur.execute(
|
||||
"INSERT INTO idempotency_keys"
|
||||
" (user_id, method, path, key, body_hash, response_status, response_body)"
|
||||
" VALUES (%s, %s, %s, %s, %s, 0, '{}'::jsonb)"
|
||||
" ON CONFLICT (user_id, method, path, key) DO NOTHING"
|
||||
" RETURNING key",
|
||||
(user_id, method, path, key, body_hash),
|
||||
)
|
||||
won = cur.fetchone() is not None
|
||||
|
||||
if won:
|
||||
# 2) Мы выиграли: создаём сообщение в ТОЙ ЖЕ транзакции.
|
||||
message = Message(
|
||||
id=uuid4(), chat_id=chat_id, sender_id=sender_id,
|
||||
text=text, created_at=now_utc(),
|
||||
attachment_ids=list(attachment_ids),
|
||||
)
|
||||
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),
|
||||
)
|
||||
if attachment_ids:
|
||||
cur.executemany(
|
||||
"INSERT INTO message_attachments"
|
||||
" (message_id, attachment_id, position)"
|
||||
" VALUES (%s, %s, %s)",
|
||||
[(message.id, aid, idx)
|
||||
for idx, aid in enumerate(attachment_ids)],
|
||||
)
|
||||
# 3) Пишем финальный ответ в ту же строку ключа.
|
||||
body_json = _json.loads(message.model_dump_json())
|
||||
cur.execute(
|
||||
"UPDATE idempotency_keys"
|
||||
" SET response_status = %s, response_body = %s"
|
||||
" WHERE user_id = %s AND method = %s AND path = %s AND key = %s",
|
||||
(201, _json.dumps(body_json),
|
||||
user_id, method, path, key),
|
||||
)
|
||||
# Один commit — либо всё, либо ничего.
|
||||
conn.commit()
|
||||
return ("created", message, None)
|
||||
|
||||
# Ключ уже занят. Читаем строку в этой же транзакции.
|
||||
cur.execute(
|
||||
"SELECT body_hash, response_status, response_body"
|
||||
" FROM idempotency_keys"
|
||||
" WHERE user_id = %s AND method = %s AND path = %s AND key = %s",
|
||||
(user_id, method, path, key),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
conn.commit()
|
||||
|
||||
if row is None:
|
||||
# Только что был конфликт, а строки нет — редкий случай; повтор.
|
||||
return ("retry", None, None)
|
||||
return (
|
||||
"replay",
|
||||
None,
|
||||
{
|
||||
"body_hash": row[0],
|
||||
"response_status": row[1],
|
||||
"response_body": row[2],
|
||||
},
|
||||
)
|
||||
|
||||
# ---------- Вложения ----------
|
||||
def create_attachment(
|
||||
self,
|
||||
attachment: Attachment,
|
||||
object_key: str,
|
||||
) -> Attachment:
|
||||
with connection() as conn, conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"INSERT INTO attachments"
|
||||
" (id, chat_id, owner_id, filename, content_type, size_bytes,"
|
||||
" sha256, object_key, status, error_code, created_at, updated_at)"
|
||||
" VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)",
|
||||
(
|
||||
attachment.id, attachment.chat_id, attachment.owner_id,
|
||||
attachment.filename, attachment.content_type,
|
||||
attachment.size_bytes, attachment.sha256, object_key,
|
||||
attachment.status, attachment.error_code,
|
||||
attachment.created_at, attachment.updated_at,
|
||||
),
|
||||
)
|
||||
conn.commit()
|
||||
return attachment
|
||||
|
||||
def get_attachment(self, attachment_id: UUID) -> Optional[Attachment]:
|
||||
with connection() as conn, conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"SELECT id, chat_id, owner_id, filename, content_type, size_bytes,"
|
||||
" sha256, status, error_code, created_at, updated_at"
|
||||
" FROM attachments WHERE id = %s",
|
||||
(attachment_id,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if row is None:
|
||||
return None
|
||||
cur.execute(
|
||||
"SELECT object_key FROM attachments WHERE id = %s", (attachment_id,),
|
||||
)
|
||||
obj_row = cur.fetchone()
|
||||
att = _row_to_attachment(row)
|
||||
att_variants: List[Variant] = [] # lab4: вариантов нет
|
||||
att.variants = att_variants
|
||||
# object_key нужен вызывающему для чтения из S3; отдаём через
|
||||
# отдельный метод get_attachment_with_key.
|
||||
return att
|
||||
|
||||
def get_attachment_with_key(
|
||||
self, attachment_id: UUID
|
||||
) -> Optional[tuple[Attachment, str]]:
|
||||
with connection() as conn, conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"SELECT id, chat_id, owner_id, filename, content_type, size_bytes,"
|
||||
" sha256, status, error_code, created_at, updated_at, object_key"
|
||||
" FROM attachments WHERE id = %s",
|
||||
(attachment_id,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if row is None:
|
||||
return None
|
||||
att = _row_to_attachment(row[:11])
|
||||
return att, row[11]
|
||||
|
||||
def list_attachments_by_ids(
|
||||
self, ids: List[UUID], chat_id: UUID
|
||||
) -> dict[UUID, tuple[Attachment, str]]:
|
||||
"""Достаём вложения этого чата. Возвращает {id: (Attachment, object_key)}."""
|
||||
if not ids:
|
||||
return {}
|
||||
with connection() as conn, conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"SELECT id, chat_id, owner_id, filename, content_type, size_bytes,"
|
||||
" sha256, status, error_code, created_at, updated_at, object_key"
|
||||
" FROM attachments WHERE chat_id = %s AND id = ANY(%s)",
|
||||
(chat_id, list(ids)),
|
||||
)
|
||||
result: dict[UUID, tuple[Attachment, str]] = {}
|
||||
for row in cur.fetchall():
|
||||
att = _row_to_attachment(row[:11])
|
||||
att.variants = []
|
||||
result[row[0]] = (att, row[11])
|
||||
return result
|
||||
|
||||
def delete_attachment(self, attachment_id: UUID) -> None:
|
||||
with connection() as conn, conn.cursor() as cur:
|
||||
cur.execute("DELETE FROM attachments WHERE id = %s", (attachment_id,))
|
||||
conn.commit()
|
||||
|
||||
|
||||
storage = PostgresStorage() # единственный экземпляр на процесс
|
||||
Reference in New Issue
Block a user