Реализация лабораторной работы 4 на 4

This commit is contained in:
2026-11-06 19:23:06 +03:00
parent ec540a1a72
commit b72fa4b82d
134 changed files with 8344 additions and 20 deletions
+7
View File
@@ -0,0 +1,7 @@
from .auth_service import AuthService
from .chat_service import ChatService
from .message_service import MessageService
from .user_service import UserService
from .attachment_service import AttachmentService
__all__ = ["UserService", "AuthService", "ChatService", "MessageService", "AttachmentService", ]
@@ -0,0 +1,2 @@
from .attachment_service import AttachmentService
__all__ = ["AttachmentService"]
@@ -0,0 +1,98 @@
import struct
import os
from uuid import uuid4
from datetime import datetime, UTC
from config import LOGGER
from domain import AttachmentSchema
from domain.errors import AppError, ErrorCode, InvalidRequestError, NotFoundError
from interfaces import AttachmentRepository, ChatRepository
from infrastructure.s3_client import S3Client
class PayloadTooLargeError(AppError):
status_code = 413
code = ErrorCode.PAYLOAD_TOO_LARGE
default_message = "Превышен лимит размера"
class UnsupportedMediaTypeError(AppError):
status_code = 415
code = ErrorCode.UNSUPPORTED_MEDIA_TYPE
default_message = "Неподдерживаемый формат"
def validate_image_and_get_mime(file_path: str) -> str:
with open(file_path, "rb") as f:
header = f.read(24)
if header.startswith(b"\x89PNG\r\n\x1a\n"):
w, h = struct.unpack(">II", header[16:24])
if w * h > 40_000_000:
raise PayloadTooLargeError("Разрешение больше 40М пикселей")
return "image/png"
elif header[:2] == b"\xff\xd8":
with open(file_path, "rb") as f:
data = f.read()
i = 2
sof = {0xc0, 0xc1, 0xc2, 0xc3, 0xc5, 0xc6, 0xc7, 0xc9, 0xca, 0xcb, 0xcd, 0xce, 0xcf}
while i < len(data):
if data[i] != 0xff: raise UnsupportedMediaTypeError("Поврежденный JPEG")
while i < len(data) and data[i] == 0xff: i += 1
if i >= len(data): break
marker = data[i]
i += 1
if marker in {0xd9, 0xda}: break
if marker in {0x01, 0xd8} or 0xd0 <= marker <= 0xd7: continue
if i + 2 > len(data): break
length = int.from_bytes(data[i:i+2], "big")
if marker in sof:
if i + 7 > len(data): break
h = int.from_bytes(data[i+3:i+5], "big")
w = int.from_bytes(data[i+5:i+7], "big")
if w * h > 40_000_000:
raise PayloadTooLargeError("Разрешение больше 40М пикселей")
return "image/jpeg"
i += length
raise UnsupportedMediaTypeError("Не удалось найти размеры JPEG")
raise UnsupportedMediaTypeError("Формат не поддерживается")
class AttachmentService:
def __init__(self, s3_client: S3Client, attachment_repo: AttachmentRepository, chat_repo: ChatRepository):
self._s3 = s3_client
self._attachments = attachment_repo
self._chats = chat_repo
async def process_and_save(self, temp_file_path: str, filename: str, chat_id, owner_id, size_bytes: int, sha256_hash: str) -> AttachmentSchema:
if "/" in filename or "\\" in filename or "\0" in filename:
raise InvalidRequestError("Недопустимое имя файла")
chat = await self._chats.get_for_member(chat_id, owner_id)
if not chat:
raise NotFoundError()
mime = validate_image_and_get_mime(temp_file_path)
attachment_id = uuid4()
object_name = f"{chat_id}/{attachment_id}"
await self._s3.upload_file(temp_file_path, object_name, mime)
LOGGER.info(f"Файл {attachment_id} загружен в S3")
now = datetime.now(UTC)
attachment = AttachmentSchema(
id=attachment_id, chat_id=chat_id, owner_id=owner_id,
filename=filename, content_type=mime, size_bytes=size_bytes,
sha256=sha256_hash, status="ready", variants=[],
error_code=None, created_at=now, updated_at=now
)
return await self._attachments.create(attachment)
async def get_attachment_meta(self, attachment_id, user_id) -> AttachmentSchema:
att = await self._attachments.get_by_id(attachment_id)
if not att or not await self._chats.get_for_member(att.chat_id, user_id):
raise NotFoundError()
return att
async def get_attachment_stream(self, attachment_id, user_id):
att = await self.get_attachment_meta(attachment_id, user_id)
if att.status != "ready":
from domain.errors import ConflictError
raise ConflictError("Файл еще не готов")
object_name = f"{att.chat_id}/{att.id}"
return self._s3.stream_file(object_name), att.content_type
@@ -0,0 +1,3 @@
from .auth_service import AuthService
__all__ = ["AuthService"]
@@ -0,0 +1,92 @@
from datetime import UTC, datetime
from config import LOGGER
from domain import BasicCredentialsSchema, SessionSchema, UserSchema
from domain.errors import InvalidCredentialsError, UnauthorizedError
from infrastructure.security import PasswordHasher, generate_token, hash_token
from interfaces import SessionCache, SessionRepository, UserRepository
TOKEN_MAX_LENGTH = 256
class AuthService:
"""
Basic → opaque Bearer-сессия.
Источник истины — SessionRepository (PostgreSQL), SessionCache (Valkey) —
read-through кэш: при промахе или недоступности кэша сессия читается из БД.
"""
def __init__(
self,
user_repository: UserRepository,
session_repository: SessionRepository,
session_cache: SessionCache,
hasher: PasswordHasher,
session_ttl_seconds: int,
) -> None:
self._users = user_repository
self._sessions = session_repository
self._cache = session_cache
self._hasher = hasher
self._session_ttl = session_ttl_seconds
async def login(self, credentials: BasicCredentialsSchema) -> SessionSchema:
"""
Создание сессии по username и паролю.
Raises:
InvalidCredentialsError: неизвестный username или неверный пароль —
одинаковый ответ и сопоставимое время
"""
found = await self._users.get_credentials(credentials.username)
if found is None:
await self._hasher.verify_dummy(credentials.password)
raise InvalidCredentialsError()
if not await self._hasher.verify(found.password_hash, credentials.password):
raise InvalidCredentialsError()
token = generate_token()
expires_at = await self._sessions.create(
hash_token(token), found.user.id, self._session_ttl
)
LOGGER.info(f"Создана сессия пользователя {found.user.id}")
return SessionSchema(token=token, expires_at=expires_at, user=found.user)
async def authenticate(self, token: str | None) -> UserSchema:
"""
Владелец действующей сессии.
Raises:
UnauthorizedError: токена нет, он неизвестен, истёк или отозван
UnavailableError: кэш промахнулся, а PostgreSQL недоступен
"""
if not token or len(token) > TOKEN_MAX_LENGTH:
raise UnauthorizedError()
token_hash = hash_token(token)
session = await self._cache.get(token_hash)
if session is not None and session.expires_at > datetime.now(UTC):
return session.user
session = await self._sessions.get_active(token_hash)
if session is None:
raise UnauthorizedError()
await self._cache.set(token_hash, session)
return session.user
async def logout(self, token: str | None) -> None:
"""
Отзыв в источнике истины, затем инвалидация кэша.
Raises:
UnauthorizedError: действующей сессии с таким токеном нет
"""
if not token or len(token) > TOKEN_MAX_LENGTH:
raise UnauthorizedError()
token_hash = hash_token(token)
if not await self._sessions.revoke(token_hash):
raise UnauthorizedError()
if not await self._cache.delete(token_hash):
LOGGER.warning(
"Сессия отозвана в PostgreSQL, но запись кэша не удалена: "
"она истечёт по TTL кэша"
)
LOGGER.info("Сессия отозвана")
@@ -0,0 +1,3 @@
from .chat_service import ChatService
__all__ = ["ChatService"]
@@ -0,0 +1,46 @@
from uuid import UUID
from config import LOGGER
from domain import ChatPageSchema, ChatSchema, CreateChatSchema, UserSchema
from domain.errors import InvalidRequestError, NotFoundError
from infrastructure.utils import build_page, decode_cursor
from interfaces import ChatRepository
class ChatService:
def __init__(self, chat_repository: ChatRepository) -> None:
self._chats = chat_repository
async def create_chat(
self, current_user: UserSchema, data: CreateChatSchema
) -> ChatSchema:
"""
Чат создаётся из явного списка существующих участников, включая создателя.
Существование участников проверяет FK в транзакции создания: отдельная
предварительная проверка была бы гонкой и не нужна для отката.
"""
if current_user.id not in data.member_ids:
raise InvalidRequestError(
"member_ids должен содержать текущего пользователя"
)
chat = await self._chats.create(data.title, current_user.id, data.member_ids)
LOGGER.info(
f"Создан чат {chat.id} пользователем {current_user.id}, "
f"участников: {len(chat.member_ids)}"
)
return chat
async def get_chat(self, current_user: UserSchema, chat_id: UUID) -> ChatSchema:
chat = await self._chats.get_for_member(chat_id, current_user.id)
if chat is None:
raise NotFoundError()
return chat
async def list_chats(
self, current_user: UserSchema, limit: int, cursor: str | None
) -> ChatPageSchema:
scope = f"chats:{current_user.id}"
after = decode_cursor(cursor, scope)
fetched = await self._chats.list_for_member(current_user.id, after, limit + 1)
items, next_cursor = build_page(fetched, limit, scope)
return ChatPageSchema(items=items, next_cursor=next_cursor)
@@ -0,0 +1,3 @@
from .message_service import MessageService
__all__ = ["MessageService"]
@@ -0,0 +1,83 @@
import hashlib
from uuid import UUID
from config import LOGGER
from domain import (
CreateMessageSchema,
IdempotencyKeySchema,
MessagePageSchema,
MessageSchema,
UserSchema,
)
from domain.errors import NotFoundError
from infrastructure.utils import build_page, decode_cursor
from interfaces import ChatRepository, MessageRepository
class MessageService:
def __init__(
self,
chat_repository: ChatRepository,
message_repository: MessageRepository,
idempotency_ttl_seconds: int,
) -> None:
self._chats = chat_repository
self._messages = message_repository
self._idempotency_ttl = idempotency_ttl_seconds
async def send_message(
self,
current_user: UserSchema,
chat_id: UUID,
data: CreateMessageSchema,
idempotency_key: str,
) -> MessageSchema:
"""
Отправитель берётся из текущей идентификации; текст в логи не пишется.
Повтор с тем же Idempotency-Key заново проверяет доступ к чату
и возвращает исходное сообщение.
"""
await self._ensure_member(current_user, chat_id)
idempotency = IdempotencyKeySchema(
key=idempotency_key,
request_hash=self._request_hash(data),
ttl_seconds=self._idempotency_ttl,
)
message, created = await self._messages.create(
chat_id, current_user.id, data.text, data.attachment_ids, idempotency
)
if created:
LOGGER.info(
f"Сообщение {message.id} отправлено в чат {chat_id} "
f"пользователем {current_user.id}"
)
else:
LOGGER.info(
f"Повтор по Idempotency-Key: возвращено сообщение {message.id} "
f"чата {chat_id}"
)
return message
async def list_messages(
self, current_user: UserSchema, chat_id: UUID, limit: int, cursor: str | None
) -> MessagePageSchema:
await self._ensure_member(current_user, chat_id)
scope = f"messages:{chat_id}"
after = decode_cursor(cursor, scope)
fetched = await self._messages.list_for_chat(chat_id, after, limit + 1)
items, next_cursor = build_page(fetched, limit, scope)
return MessagePageSchema(items=items, next_cursor=next_cursor)
async def _ensure_member(self, current_user: UserSchema, chat_id: UUID) -> None:
"""Посторонний получает 404: существование чужого чата не раскрывается"""
if await self._chats.get_for_member(chat_id, current_user.id) is None:
raise NotFoundError()
@staticmethod
def _request_hash(data: CreateMessageSchema) -> bytes:
"""
SHA-256 канонического тела. Порядок полей задаёт схема, а не клиент,
поэтому JSON с другим порядком ключей считается тем же запросом.
"""
return hashlib.sha256(data.model_dump_json().encode()).digest()
@@ -0,0 +1,3 @@
from .user_service import UserService
__all__ = ["UserService"]
@@ -0,0 +1,17 @@
from config import LOGGER
from domain import CreateUserSchema, UserSchema
from infrastructure.security import PasswordHasher
from interfaces import UserRepository
class UserService:
def __init__(self, repository: UserRepository, hasher: PasswordHasher) -> None:
self._repo = repository
self._hasher = hasher
async def register(self, data: CreateUserSchema) -> UserSchema:
"""Пароль сохраняется только как hash Argon2id"""
password_hash = await self._hasher.hash(data.password)
user = await self._repo.create(data.username, data.display_name, password_hash)
LOGGER.info(f"Зарегистрирован пользователь {user.id}")
return user