4grade_and_report

This commit is contained in:
caramelteawithmint
2026-11-20 15:17:03 +03:00
parent a306a68aa4
commit a11a36754c
6 changed files with 231 additions and 72 deletions
+10 -25
View File
@@ -3,13 +3,11 @@ import io
import tempfile
import uuid
import json
import aio_pika
from fastapi import APIRouter, Depends, Request, Query
from fastapi.responses import StreamingResponse
from psycopg.rows import dict_row
from ..config import get_settings
from ..db import transaction, connection
from ..errors import ApiError
from ..s3 import upload_fileobj, download_fileobj, delete_file
@@ -20,24 +18,6 @@ from .sessions import require_actor
router = APIRouter(prefix="/api/v1")
MAX_SIZE = 10 * 1024 * 1024
async def _publish_task(attachment_id: str, object_key: str):
"""Отправляет задачу в RabbitMQ."""
settings = get_settings()
try:
connection = await aio_pika.connect_robust(settings.broker_url)
async with connection:
channel = await connection.channel()
await channel.declare_queue(settings.broker_queue, durable=True)
message = aio_pika.Message(
body=json.dumps({"attachment_id": attachment_id, "object_key": object_key}).encode(),
delivery_mode=aio_pika.DeliveryMode.PERSISTENT
)
await channel.default_exchange.publish(message, routing_key=settings.broker_queue)
except Exception as e:
print(f"Broker error: {e}")
# Если брокер упал, мы можем либо откатить загрузку, либо оставить статус queued
# Для лабы: логируем, воркер потом не найдет задачу, но health/ready покажет ошибку
@router.post("/chats/{chat_id}/attachments", status_code=202)
async def upload_attachment(
chat_id: str,
@@ -79,7 +59,6 @@ async def upload_attachment(
if size == 0:
raise ApiError(400, "invalid_request", "Пустой файл")
# Только быстрая проверка magic bytes, глубокий анализ оставляем воркеру
try:
content_type, _, _ = check_image(first_chunk, ["image/png", "image/jpeg"])
except ValueError:
@@ -98,6 +77,7 @@ async def upload_attachment(
try:
with transaction() as conn:
with conn.cursor(row_factory=dict_row) as cur:
# 1. Сохраняем вложение
cur.execute(
"""
INSERT INTO attachments (chat_id, owner_id, filename, content_type, size_bytes, sha256, object_key, status)
@@ -107,6 +87,13 @@ async def upload_attachment(
(chat_id, actor["user_id"], filename, content_type, size, sha256_hex, object_key),
)
att = cur.fetchone()
# 2. Сохраняем задачу в Outbox в ТОЙ ЖЕ транзакции
payload = {"attachment_id": str(att["id"]), "object_key": object_key}
cur.execute(
"INSERT INTO outbox_messages (attachment_id, payload) VALUES (%s, %s)",
(att["id"], json.dumps(payload))
)
except Exception as e:
print(f"DB failed, compensating S3: {e}")
try:
@@ -115,9 +102,6 @@ async def upload_attachment(
print(f"Failed to compensate S3: {s3_e}")
raise ApiError(500, "internal_error", "Ошибка сохранения")
# Публикуем задачу
await _publish_task(str(att["id"]), object_key)
return {
"id": str(att["id"]),
"chat_id": str(att["chat_id"]),
@@ -133,6 +117,7 @@ async def upload_attachment(
"updated_at": iso_z(att["updated_at"]),
}
@router.get("/attachments/{attachment_id}")
def get_attachment(attachment_id: str, actor: dict = Depends(require_actor)):
try:
@@ -186,6 +171,7 @@ def get_attachment(attachment_id: str, actor: dict = Depends(require_actor)):
"updated_at": iso_z(att["updated_at"]),
}
@router.get("/attachments/{attachment_id}/content")
def download_attachment(
attachment_id: str,
@@ -225,7 +211,6 @@ def download_attachment(
)
var = cur.fetchone()
if not var:
# Если вариант еще не готов, возвращаем 404 или 409
raise ApiError(404, "not_found", "Вариант еще не готов или недоступен")
obj_key = var["object_key"]
content_type = var["content_type"]