import hashlib import json from datetime import timedelta from uuid import UUID, uuid4 from sqlalchemy import delete, select, text, tuple_ from sqlalchemy.exc import IntegrityError from app.db import map_integrity, session_scope from app.errors import AppError from app.models import ChatMember, IdempotencyRecord, Message from app.pagination import decode_position, slice_page from app.present import PublicMessage from app.runtime import require_settings from app.timeutil import utcnow def message_path(chat_id: UUID) -> str: return "/api/v1/chats/%s/messages" % chat_id def request_fingerprint(text_value: str) -> str: payload = json.dumps({"text": text_value}, ensure_ascii=False, separators=(",", ":")) return hashlib.sha256(payload.encode("utf-8")).hexdigest() def _lock_keys(scope: str) -> tuple[int, int]: digest = hashlib.sha256(scope.encode("utf-8")).digest() first = int.from_bytes(digest[:4], "big", signed=True) second = int.from_bytes(digest[4:8], "big", signed=True) return first, second def _public(row: Message) -> PublicMessage: return PublicMessage( id=row.id, chat_id=row.chat_id, sender_id=row.sender_id, text=row.text, created_at=row.created_at, ) async def _require_member(session, chat_id: UUID, user_id: UUID) -> None: member = await session.scalar( select(ChatMember.user_id).where(ChatMember.chat_id == chat_id, ChatMember.user_id == user_id) ) if member is None: raise AppError(404, "not_found", "Объект не найден") async def create_message( chat_id: UUID, sender_id: UUID, text_value: str, idempotency_key: str, ) -> PublicMessage: settings = require_settings() path = message_path(chat_id) request_hash = request_fingerprint(text_value) lock_a, lock_b = _lock_keys("POST:%s:%s:%s" % (sender_id, path, idempotency_key)) ttl = timedelta(seconds=settings.idempotency_ttl_seconds) async with session_scope() as session: try: async with session.begin(): await session.execute( text("SELECT pg_advisory_xact_lock(:a, :b)"), {"a": lock_a, "b": lock_b}, ) await _require_member(session, chat_id, sender_id) existing = await session.scalar( select(IdempotencyRecord).where( IdempotencyRecord.user_id == sender_id, IdempotencyRecord.method == "POST", IdempotencyRecord.request_path == path, IdempotencyRecord.idempotency_key == idempotency_key, ) ) now = utcnow() if existing is not None and existing.created_at + ttl >= now: if existing.request_hash != request_hash: raise AppError(409, "conflict", "Повтор ключа с другим сообщением") row = await session.get(Message, existing.message_id) if row is None: raise AppError(500, "internal_error", "Внутренняя ошибка") return _public(row) if existing is not None: await session.execute( delete(IdempotencyRecord).where( IdempotencyRecord.user_id == existing.user_id, IdempotencyRecord.method == existing.method, IdempotencyRecord.request_path == existing.request_path, IdempotencyRecord.idempotency_key == existing.idempotency_key, ) ) await session.flush() message_id = uuid4() created_at = now session.add( Message( id=message_id, chat_id=chat_id, sender_id=sender_id, text=text_value, created_at=created_at, ) ) await session.flush() session.add( IdempotencyRecord( user_id=sender_id, method="POST", request_path=path, idempotency_key=idempotency_key, request_hash=request_hash, status_code=201, message_id=message_id, created_at=created_at, ) ) await session.flush() except IntegrityError as exc: raise map_integrity(exc, "Конфликт записи") from None return PublicMessage( id=message_id, chat_id=chat_id, sender_id=sender_id, text=text_value, created_at=created_at, ) async def messages_for_member(chat_id: UUID, user_id: UUID, limit: int, cursor: str | None) -> dict: async with session_scope() as session: async with session.begin(): await _require_member(session, chat_id, user_id) position = decode_position(cursor, "m", chat_id) if cursor else None stmt = select(Message).where(Message.chat_id == chat_id) if position is not None: created_at, message_id = position stmt = stmt.where(tuple_(Message.created_at, Message.id) > tuple_(created_at, message_id)) stmt = stmt.order_by(Message.created_at.asc(), Message.id.asc()).limit(limit + 1) rows = (await session.scalars(stmt)).all() public = [_public(row) for row in rows] return slice_page(public, limit, "m", chat_id)