forked from mtusi2026/mtusi2026lab4
ЛР4 на 5: вложения в MinIO, отказоустойчивость, трек 2 (сверка S3 и PostgreSQL)
Уровень 3: - код lab3 перенесён; MinIO (сборка релиза 2025-10-15, по digest) в общем Compose, идемпотентный bootstrap: приватные bucket, отдельный пользователь API с ограниченной политикой - метаданные вложений в PostgreSQL (миграции 0003, 0004), байты в S3; ключ назначает сервер - upload PNG/JPEG: лимиты до чтения/декодирования, MIME по содержимому, проверка целостности, безопасный filename; 201 только после PUT и COMMIT; download потоком через API - attachment_ids в сообщениях (только файлы своего чата, FK в БД) - 503 API больше не повторяется в HAProxy (отказ общей зависимости), S3 не входит в readiness Уровень 4: - 45 тестов вложений: размер, повреждение, подмена MIME, чужой id, файл другого чата, отказы S3/БД - компенсация при сбое COMMIT; слоты загрузки (8 на реплику) против неограниченной памяти - эксперименты: пик RAM при 10-40 одновременных загрузках, оборванная загрузка и сироты; исправлены удержание соединения БД во время загрузки и таймаут отправки в S3 Уровень 5, трек 2: - reconciler: слияние листинга S3 и курсора БД, 7 категорий расхождений, dry-run, grace period, перепроверка перед действием, тормоз --max-deletes, advisory lock; сервис reconciler в Compose - 8 тестов сверки; эксперимент с 70 внедрёнными ошибками на 10 000 объектах (точное обнаружение, безопасное исправление, идемпотентность) и замер стоимости обхода на 1k/10k/50k Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
ec540a1a72
commit
0ccaf8e542
@@ -0,0 +1,44 @@
|
||||
import uuid
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from models import Attachment, ChatMember
|
||||
|
||||
|
||||
def object_key_for(attachment_id: uuid.UUID) -> str:
|
||||
# Ключ назначает сервер: случайный UUID, без имени файла и без данных пользователя.
|
||||
return f"originals/{attachment_id}"
|
||||
|
||||
|
||||
def create_attachment(db: Session, attachment_id: uuid.UUID, chat_id: uuid.UUID, owner_id: uuid.UUID,
|
||||
filename: str, content_type: str, size_bytes: int, sha256: str, object_key: str) -> Attachment:
|
||||
attachment = Attachment(
|
||||
id=attachment_id, chat_id=chat_id, owner_id=owner_id, filename=filename, content_type=content_type,
|
||||
size_bytes=size_bytes, sha256=sha256, object_key=object_key,
|
||||
)
|
||||
db.add(attachment)
|
||||
db.commit()
|
||||
return attachment
|
||||
|
||||
|
||||
def get_member_attachment(db: Session, attachment_id: uuid.UUID, user_id: uuid.UUID) -> Attachment | None:
|
||||
"""Вложение, если пользователь — участник его чата. Чужое и несуществующее неразличимы (None -> 404)."""
|
||||
query = (
|
||||
select(Attachment)
|
||||
.join(ChatMember, ChatMember.chat_id == Attachment.chat_id)
|
||||
.where(Attachment.id == attachment_id, ChatMember.user_id == user_id)
|
||||
)
|
||||
return db.scalar(query)
|
||||
|
||||
|
||||
def find_chat_attachments(db: Session, chat_id: uuid.UUID, attachment_ids: list[uuid.UUID]) -> list[Attachment]:
|
||||
# Вложения других чатов сюда не попадают: для отправителя они «не найдены».
|
||||
if not attachment_ids:
|
||||
return []
|
||||
# FOR KEY SHARE: пока сообщение со ссылкой не закоммичено, сверка хранилищ не может удалить эти строки
|
||||
# (её DELETE ждёт, а потом откажет по FK); если сверка удалила раньше — вложение просто «не найдено».
|
||||
query = (select(Attachment)
|
||||
.where(Attachment.chat_id == chat_id, Attachment.id.in_(attachment_ids))
|
||||
.with_for_update(key_share=True, read=True))
|
||||
return list(db.scalars(query))
|
||||
@@ -0,0 +1,50 @@
|
||||
import uuid
|
||||
|
||||
from sqlalchemy import func, select, tuple_
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from models import Chat, ChatMember, User
|
||||
from utils.pagination import Position
|
||||
|
||||
|
||||
def create_chat(db: Session, title: str, member_ids: list[uuid.UUID]) -> Chat | None:
|
||||
"""Чат и участники — одна транзакция. None — есть несуществующий участник."""
|
||||
found = db.scalar(select(func.count()).select_from(User).where(User.id.in_(member_ids)))
|
||||
if found != len(member_ids):
|
||||
return None
|
||||
|
||||
chat = Chat(title=title, members=[ChatMember(user_id=user_id) for user_id in sorted(member_ids)])
|
||||
db.add(chat)
|
||||
try:
|
||||
db.commit()
|
||||
except IntegrityError:
|
||||
db.rollback()
|
||||
return None
|
||||
return chat
|
||||
|
||||
|
||||
def is_chat_member(db: Session, chat_id: uuid.UUID, user_id: uuid.UUID) -> bool:
|
||||
return db.get(ChatMember, (chat_id, user_id)) is not None
|
||||
|
||||
|
||||
def get_member_chat(db: Session, chat_id: uuid.UUID, user_id: uuid.UUID) -> Chat | None:
|
||||
query = (
|
||||
select(Chat)
|
||||
.join(ChatMember, ChatMember.chat_id == Chat.id)
|
||||
.where(Chat.id == chat_id, ChatMember.user_id == user_id)
|
||||
)
|
||||
return db.scalar(query)
|
||||
|
||||
|
||||
def list_user_chats(db: Session, user_id: uuid.UUID, limit: int, after: Position | None) -> list[Chat]:
|
||||
query = (
|
||||
select(Chat)
|
||||
.join(ChatMember, ChatMember.chat_id == Chat.id)
|
||||
.where(ChatMember.user_id == user_id)
|
||||
.order_by(Chat.created_at, Chat.id)
|
||||
.limit(limit + 1)
|
||||
)
|
||||
if after is not None:
|
||||
query = query.where(tuple_(Chat.created_at, Chat.id) > tuple_(*after))
|
||||
return list(db.scalars(query))
|
||||
@@ -0,0 +1,87 @@
|
||||
import uuid
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from sqlalchemy import func, select, tuple_, update
|
||||
from sqlalchemy.dialects.postgresql import insert
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from database_functions.attachments_functions import find_chat_attachments
|
||||
from models import IdempotencyKey, Message, MessageAttachment
|
||||
from utils.pagination import Position
|
||||
|
||||
|
||||
class IdempotencyKeyReused(Exception):
|
||||
"""Тот же Idempotency-Key уже использован с другим телом запроса."""
|
||||
|
||||
|
||||
class AttachmentNotFound(Exception):
|
||||
"""Вложения нет или оно из другого чата (для клиента это 404)."""
|
||||
|
||||
|
||||
class AttachmentNotReady(Exception):
|
||||
"""Вложение ещё не готово или с ошибкой обработки (409)."""
|
||||
|
||||
|
||||
def create_message_once(db: Session, chat_id: uuid.UUID, sender_id: uuid.UUID, text: str,
|
||||
attachment_ids: list[uuid.UUID],
|
||||
key: str, request_hash: bytes, ttl_seconds: int) -> Message:
|
||||
"""Создать сообщение ровно один раз для (пользователь, чат, ключ), в том числе при конкурентных повторах.
|
||||
|
||||
Всё в одной транзакции: «заявка» на ключ, сообщение и ссылка ключа на сообщение фиксируются вместе.
|
||||
Если транзакция откатится (5xx, обрыв), ключ не сохранится и клиент безопасно повторит запрос.
|
||||
Параллельный повтор через другую реплику блокируется на уникальном индексе до COMMIT первой
|
||||
транзакции, затем видит её строку и возвращает то же сообщение.
|
||||
"""
|
||||
cutoff = datetime.now(timezone.utc) - timedelta(seconds=ttl_seconds)
|
||||
claim = (
|
||||
insert(IdempotencyKey)
|
||||
.values(user_id=sender_id, chat_id=chat_id, key=key, request_hash=request_hash)
|
||||
# Строка старше TTL считается свободной ключом: перехватываем её, остальные конфликты не меняем.
|
||||
.on_conflict_do_update(
|
||||
index_elements=[IdempotencyKey.user_id, IdempotencyKey.chat_id, IdempotencyKey.key],
|
||||
set_={"request_hash": request_hash, "message_id": None, "created_at": func.clock_timestamp()},
|
||||
where=IdempotencyKey.created_at < cutoff,
|
||||
)
|
||||
.returning(IdempotencyKey.key)
|
||||
)
|
||||
if db.execute(claim).first() is None:
|
||||
existing = db.scalars(select(IdempotencyKey).where(
|
||||
IdempotencyKey.user_id == sender_id, IdempotencyKey.chat_id == chat_id, IdempotencyKey.key == key,
|
||||
)).one()
|
||||
if existing.request_hash != request_hash:
|
||||
raise IdempotencyKeyReused()
|
||||
return db.get_one(Message, existing.message_id)
|
||||
|
||||
attachments = {a.id: a for a in find_chat_attachments(db, chat_id, attachment_ids)}
|
||||
if len(attachments) != len(attachment_ids):
|
||||
# Откат снимает и «заявку» на ключ: исправленный запрос с тем же ключом пройдёт.
|
||||
db.rollback()
|
||||
raise AttachmentNotFound()
|
||||
if any(a.status != "ready" for a in attachments.values()):
|
||||
db.rollback()
|
||||
raise AttachmentNotReady()
|
||||
|
||||
message = Message(chat_id=chat_id, sender_id=sender_id, text=text, attachment_links=[
|
||||
MessageAttachment(attachment_id=attachment_id, chat_id=chat_id, position=position)
|
||||
for position, attachment_id in enumerate(attachment_ids)
|
||||
])
|
||||
db.add(message)
|
||||
db.flush()
|
||||
db.execute(update(IdempotencyKey).where(
|
||||
IdempotencyKey.user_id == sender_id, IdempotencyKey.chat_id == chat_id, IdempotencyKey.key == key,
|
||||
).values(message_id=message.id))
|
||||
db.commit()
|
||||
return message
|
||||
|
||||
|
||||
def list_messages(db: Session, chat_id: uuid.UUID, limit: int, after: Position | None) -> list[Message]:
|
||||
# Keyset-пагинация по индексу messages_chat_history_idx (chat_id, created_at, id).
|
||||
query = (
|
||||
select(Message)
|
||||
.where(Message.chat_id == chat_id)
|
||||
.order_by(Message.created_at, Message.id)
|
||||
.limit(limit + 1)
|
||||
)
|
||||
if after is not None:
|
||||
query = query.where(tuple_(Message.created_at, Message.id) > tuple_(*after))
|
||||
return list(db.scalars(query))
|
||||
@@ -0,0 +1,29 @@
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import delete, func, select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from models import AuthSession
|
||||
|
||||
|
||||
def create_session(db: Session, token_hash: bytes, user_id: uuid.UUID,
|
||||
created_at: datetime, expires_at: datetime) -> AuthSession:
|
||||
auth_session = AuthSession(token_hash=token_hash, user_id=user_id, created_at=created_at, expires_at=expires_at)
|
||||
db.add(auth_session)
|
||||
db.commit()
|
||||
return auth_session
|
||||
|
||||
|
||||
def get_active_session(db: Session, token_hash: bytes) -> AuthSession | None:
|
||||
query = select(AuthSession).where(
|
||||
AuthSession.token_hash == token_hash,
|
||||
AuthSession.expires_at > func.now(),
|
||||
)
|
||||
return db.scalar(query)
|
||||
|
||||
|
||||
def delete_session(db: Session, token_hash: bytes) -> bool:
|
||||
result = db.execute(delete(AuthSession).where(AuthSession.token_hash == token_hash))
|
||||
db.commit()
|
||||
return result.rowcount > 0
|
||||
@@ -0,0 +1,30 @@
|
||||
import uuid
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from models import User
|
||||
|
||||
|
||||
def create_user(db: Session, username: str, display_name: str, password_hash: str) -> User | None:
|
||||
"""None — username уже занят."""
|
||||
user = User(username=username, display_name=display_name, password_hash=password_hash)
|
||||
db.add(user)
|
||||
try:
|
||||
db.commit()
|
||||
except IntegrityError as exc:
|
||||
db.rollback()
|
||||
# Уникальность проверяет сама БД, поэтому гонка регистрации невозможна.
|
||||
if exc.orig.diag.constraint_name == "users_username_key":
|
||||
return None
|
||||
raise
|
||||
return user
|
||||
|
||||
|
||||
def get_user(db: Session, user_id: uuid.UUID) -> User | None:
|
||||
return db.get(User, user_id)
|
||||
|
||||
|
||||
def get_user_by_username(db: Session, username: str) -> User | None:
|
||||
return db.scalar(select(User).where(User.username == username))
|
||||
Reference in New Issue
Block a user