import asyncio import hashlib import uuid from collections.abc import AsyncIterator from dataclasses import dataclass from typing import Literal from urllib.parse import quote from fastapi import APIRouter, Depends, HTTPException, Query, Request from fastapi.responses import StreamingResponse from sqlalchemy.orm import Session from starlette.requests import ClientDisconnect from api.dependencies import get_current_user from core import s3 from core.config import settings from core.db import get_db from core.logger import logger from database_functions.attachments_functions import create_attachment, get_member_attachment, object_key_for from database_functions.chats_functions import is_chat_member from models import User from schemas.attachments_schemas import AttachmentResponse from utils.images import ImageRejected, inspect_image, validate_filename upload_router = APIRouter( prefix=settings.api.prefix + settings.api.v1.prefix + settings.api.v1.chats, tags=["attachments"], ) roter = APIRouter( prefix=settings.api.prefix + settings.api.v1.prefix + settings.api.v1.attachments, tags=["attachments"], ) ALLOWED_TYPES = {"image/png", "image/jpeg"} @dataclass class UploadBody: data: bytes declared_type: str def member_chat_id(chat_id: uuid.UUID, current_user: User = Depends(get_current_user), db: Session = Depends(get_db)) -> uuid.UUID: # Сначала аутентификация и доступ к чату — и только потом чтение тела запроса. if not is_chat_member(db, chat_id, current_user.id): raise HTTPException(status_code=404, detail="Чат не найден") # Вернуть соединение в пул до приёма тела и PUT в S3 (секунды): иначе одновременные загрузки # выбирали весь пул (10 на реплику) и остальные запросы получали 503 по таймауту пула. db.commit() return chat_id # Слоты загрузки на процесс: пик памяти реплики ~ max_concurrent_uploads * max_bytes, а не число соединений. upload_slots = asyncio.Semaphore(settings.attachments.max_concurrent_uploads) async def upload_slot() -> AsyncIterator[None]: """Занять слот до чтения тела и держать до конца обработки; нет слота за slot_wait_seconds — 503.""" try: await asyncio.wait_for(upload_slots.acquire(), timeout=settings.attachments.slot_wait_seconds) except TimeoutError: raise HTTPException(status_code=503, detail="Слишком много одновременных загрузок, повторите позже", headers={"Retry-After": "1"}) try: yield finally: upload_slots.release() async def read_upload(request: Request) -> UploadBody: """Прочитать сырые байты не больше лимита: лишнее не читается и в память не попадает.""" limit = settings.attachments.max_bytes declared_type = request.headers.get("content-type", "").split(";")[0].strip().lower() if declared_type not in ALLOWED_TYPES: raise HTTPException(status_code=415, detail="Content-Type должен быть image/png или image/jpeg") # Заявленная длина больше лимита — отказ сразу, без чтения тела. content_length = request.headers.get("content-length") if content_length is not None and content_length.isdigit() and int(content_length) > limit: raise HTTPException(status_code=413, detail="Файл больше 10 MiB") # Content-Length может отсутствовать или врать: считаем фактически полученные байты. buffer = bytearray() try: async for chunk in request.stream(): buffer.extend(chunk) if len(buffer) > limit: raise HTTPException(status_code=413, detail="Файл больше 10 MiB") except ClientDisconnect: # Клиент оборвал передачу: в S3 и БД ещё ничего не записано, следов не остаётся. logger.info(f"Загрузка прервана клиентом после {len(buffer)} байт") raise HTTPException(status_code=400, detail="Загрузка прервана") if not buffer: raise HTTPException(status_code=400, detail="Пустой файл") return UploadBody(data=bytes(buffer), declared_type=declared_type) @upload_router.post("/{chat_id}/attachments", status_code=201, response_model=AttachmentResponse) def upload_attachment_api( filename: str = Query(min_length=1, max_length=255), chat_id: uuid.UUID = Depends(member_chat_id), _slot: None = Depends(upload_slot), body: UploadBody = Depends(read_upload), current_user: User = Depends(get_current_user), db: Session = Depends(get_db), ): try: validate_filename(filename) image = inspect_image(body.data, body.declared_type, settings.attachments.max_pixels) except ImageRejected as exc: raise HTTPException(status_code=exc.status_code, detail=exc.message) attachment_id = uuid.uuid4() object_key = object_key_for(attachment_id) sha256 = hashlib.sha256(body.data).hexdigest() # 1) байты в S3; при ошибке в БД ничего не записано, клиент получает 503. s3.put_object(object_key, body.data, image.content_type, sha256) # 2) метаданные в PostgreSQL. 201 — только после COMMIT: тогда файл и скачивается, и прикрепляется. try: attachment = create_attachment( db, attachment_id=attachment_id, chat_id=chat_id, owner_id=current_user.id, filename=filename, content_type=image.content_type, size_bytes=len(body.data), sha256=sha256, object_key=object_key, ) except Exception: # COMMIT не прошёл: объект без метаданных никому не виден. Пытаемся удалить его сразу; # если и это не вышло, его найдёт сверка хранилищ. try: s3.delete_object(object_key) except s3.StorageUnavailable: logger.warning(f"Не удалось удалить объект после отката БД: attachment_id={attachment_id}") raise return AttachmentResponse.model_validate(attachment) def find_attachment(attachment_id: uuid.UUID, current_user: User, db: Session): attachment = get_member_attachment(db, attachment_id, current_user.id) if attachment is None: raise HTTPException(status_code=404, detail="Вложение не найдено") return attachment @roter.get("/{attachment_id}", response_model=AttachmentResponse) def get_attachment_api(attachment_id: uuid.UUID, current_user: User = Depends(get_current_user), db: Session = Depends(get_db)): return AttachmentResponse.model_validate(find_attachment(attachment_id, current_user, db)) @roter.get("/{attachment_id}/content") def download_attachment_api( attachment_id: uuid.UUID, variant: Literal["original", "thumbnail", "crop", "optimized"] = "original", current_user: User = Depends(get_current_user), db: Session = Depends(get_db), ): attachment = find_attachment(attachment_id, current_user, db) # Соединение с БД больше не нужно: не держать его, пока файл идёт клиенту. db.commit() if variant != "original": # Производных вариантов в lab4 нет. raise HTTPException(status_code=404, detail="Вариант не найден") try: response = s3.open_object(attachment.object_key) except s3.ObjectMissing: logger.error(f"Объект вложения отсутствует в S3: attachment_id={attachment.id}") raise HTTPException(status_code=500, detail="Содержимое вложения недоступно") # Байты идут из S3 клиенту потоком через API, без redirect и без открытия bucket наружу. return StreamingResponse( s3.iter_object(response), media_type=attachment.content_type, headers={ "Content-Length": str(attachment.size_bytes), "Content-Disposition": f"inline; filename*=UTF-8''{quote(attachment.filename)}", "X-Content-Type-Options": "nosniff", "Cache-Control": "private, no-store", }, )