This commit is contained in:
caramelteawithmint
2026-11-20 11:53:35 +03:00
parent 2b68813b33
commit f856651e57
12 changed files with 409 additions and 153 deletions
+5 -1
View File
@@ -31,13 +31,17 @@ class Settings(BaseSettings):
database_url: str = ""
database_url_file: str = "/run/secrets/database_url"
# S3 / MinIO (для 4-й лабы)
# S3 / MinIO
s3_endpoint: str = "http://minio:9000"
s3_access_key: str = "minioadmin"
s3_secret_key: str = "minioadmin"
s3_bucket: str = "messenger-attachments"
s3_region: str = "us-east-1"
# Брокер (RabbitMQ)
broker_url: str = "amqp://guest:guest@broker:5672/"
broker_queue: str = "attachment_processing"
@property
def db_dsn(self) -> str:
from_file = _read_secret(self.database_url_file)
+79 -32
View File
@@ -2,11 +2,14 @@ import hashlib
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
@@ -15,11 +18,27 @@ from ..serializers import iso_z
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=201)
@router.post("/chats/{chat_id}/attachments", status_code=202)
async def upload_attachment(
chat_id: str,
request: Request,
@@ -34,7 +53,6 @@ async def upload_attachment(
if "/" in filename or "\\" in filename or "\0" in filename:
raise ApiError(400, "invalid_request", "Опасное имя файла")
# Проверяем доступ к чату
with connection() as conn:
with conn.cursor() as cur:
cur.execute(
@@ -48,34 +66,28 @@ async def upload_attachment(
size = 0
first_chunk = b""
# Читаем потоково во временный файл (чтобы не забивать RAM)
with tempfile.SpooledTemporaryFile(max_size=MAX_SIZE, mode="w+b") as spooled:
async for chunk in request.stream():
size += len(chunk)
if size > MAX_SIZE:
raise ApiError(413, "payload_too_large", "Файл слишком большой")
if not first_chunk:
first_chunk = chunk[:16] # для детекта MIME
first_chunk = chunk[:16]
sha256.update(chunk)
spooled.write(chunk)
if size == 0:
raise ApiError(400, "invalid_request", "Пустой файл")
# Полная проверка картинки через Pillow
# Только быстрая проверка magic bytes, глубокий анализ оставляем воркеру
try:
spooled.seek(0)
content = spooled.read()
content_type, _, _ = check_image(first_chunk, ["image/png", "image/jpeg"])
from PIL import Image
Image.open(io.BytesIO(content)).verify()
except Exception:
raise ApiError(415, "unsupported_media_type", "Неподдерживаемый или битый формат")
except ValueError:
raise ApiError(415, "unsupported_media_type", "Неподдерживаемый формат")
sha256_hex = sha256.hexdigest()
object_key = f"chats/{chat_id}/{uuid.uuid4().hex}"
# Загружаем в S3
try:
spooled.seek(0)
upload_fileobj(spooled, object_key, content_type)
@@ -83,21 +95,19 @@ async def upload_attachment(
print(f"S3 error: {e}")
raise ApiError(503, "unavailable", "S3 недоступен")
# Сохраняем в БД (с компенсацией)
try:
with transaction() as conn:
with conn.cursor(row_factory=dict_row) as cur:
cur.execute(
"""
INSERT INTO attachments (chat_id, owner_id, filename, content_type, size_bytes, sha256, object_key)
VALUES (%s, %s, %s, %s, %s, %s, %s)
RETURNING id, chat_id, owner_id, filename, content_type, size_bytes, sha256, created_at
INSERT INTO attachments (chat_id, owner_id, filename, content_type, size_bytes, sha256, object_key, status)
VALUES (%s, %s, %s, %s, %s, %s, %s, 'queued')
RETURNING id, chat_id, owner_id, filename, content_type, size_bytes, sha256, status, created_at, updated_at
""",
(chat_id, actor["user_id"], filename, content_type, size, sha256_hex, object_key),
)
att = cur.fetchone()
except Exception as e:
# КОМПЕНСАЦИЯ: удаляем из S3, если БД упала
print(f"DB failed, compensating S3: {e}")
try:
delete_file(object_key)
@@ -105,6 +115,9 @@ 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"]),
@@ -113,14 +126,13 @@ async def upload_attachment(
"content_type": att["content_type"],
"size_bytes": att["size_bytes"],
"sha256": att["sha256"],
"status": "ready",
"status": att["status"],
"variants": [],
"error_code": None,
"created_at": iso_z(att["created_at"]),
"updated_at": iso_z(att["created_at"]),
"updated_at": iso_z(att["updated_at"]),
}
@router.get("/attachments/{attachment_id}")
def get_attachment(attachment_id: str, actor: dict = Depends(require_actor)):
try:
@@ -140,6 +152,12 @@ def get_attachment(attachment_id: str, actor: dict = Depends(require_actor)):
(actor["user_id"], attachment_id),
)
att = cur.fetchone()
if att:
cur.execute("SELECT * FROM attachment_variants WHERE attachment_id = %s", (attachment_id,))
variants = cur.fetchall()
else:
variants = []
if att is None:
raise ApiError(404, "not_found", "Вложение не найдено")
@@ -152,16 +170,28 @@ def get_attachment(attachment_id: str, actor: dict = Depends(require_actor)):
"content_type": att["content_type"],
"size_bytes": att["size_bytes"],
"sha256": att["sha256"],
"status": "ready",
"variants": [],
"error_code": None,
"status": att["status"],
"variants": [
{
"name": v["name"],
"content_type": v["content_type"],
"size_bytes": v["size_bytes"],
"width": v["width"],
"height": v["height"],
"sha256": v["sha256"],
} for v in variants
],
"error_code": att["error_code"],
"created_at": iso_z(att["created_at"]),
"updated_at": iso_z(att["created_at"]),
"updated_at": iso_z(att["updated_at"]),
}
@router.get("/attachments/{attachment_id}/content")
def download_attachment(attachment_id: str, actor: dict = Depends(require_actor)):
def download_attachment(
attachment_id: str,
variant: str = Query("original", pattern="^(original|thumbnail|crop|optimized)$"),
actor: dict = Depends(require_actor)
):
try:
uuid.UUID(attachment_id)
except ValueError:
@@ -171,7 +201,7 @@ def download_attachment(attachment_id: str, actor: dict = Depends(require_actor)
with conn.cursor(row_factory=dict_row) as cur:
cur.execute(
"""
SELECT a.object_key, a.content_type, a.filename
SELECT a.object_key, a.content_type, a.filename, a.status
FROM attachments a
JOIN chat_members cm ON cm.chat_id = a.chat_id AND cm.user_id = %s
WHERE a.id = %s
@@ -180,11 +210,28 @@ def download_attachment(attachment_id: str, actor: dict = Depends(require_actor)
)
att = cur.fetchone()
if att is None:
raise ApiError(404, "not_found", "Вложение не найдено")
if att is None:
raise ApiError(404, "not_found", "Вложение не найдено")
if variant == "original":
if att["status"] == "failed":
raise ApiError(409, "conflict", "Обработка вложения завершилась ошибкой")
obj_key = att["object_key"]
content_type = att["content_type"]
else:
cur.execute(
"SELECT object_key, content_type FROM attachment_variants WHERE attachment_id = %s AND name = %s",
(attachment_id, variant)
)
var = cur.fetchone()
if not var:
# Если вариант еще не готов, возвращаем 404 или 409
raise ApiError(404, "not_found", "Вариант еще не готов или недоступен")
obj_key = var["object_key"]
content_type = var["content_type"]
try:
body = download_fileobj(att["object_key"])
body = download_fileobj(obj_key)
except Exception:
raise ApiError(503, "unavailable", "S3 недоступен")
@@ -193,6 +240,6 @@ def download_attachment(attachment_id: str, actor: dict = Depends(require_actor)
return StreamingResponse(
iter_body(),
media_type=att["content_type"],
media_type=content_type,
headers={"Content-Disposition": f'attachment; filename="{att["filename"]}"'},
)
+19 -3
View File
@@ -1,25 +1,41 @@
from fastapi import APIRouter, Request
from fastapi.responses import JSONResponse
import socket
from urllib.parse import urlparse
from ..config import get_settings
from ..db import connection
from ..errors import error_response
from ..s3 import get_s3_client
router = APIRouter()
@router.get("/health/live")
def live():
return {"status": "ok"}
@router.get("/health/ready")
def ready(request: Request):
try:
with connection() as conn:
with conn.cursor() as cur:
cur.execute("SELECT 1")
cur.fetchone()
except Exception:
get_s3_client().head_bucket(Bucket=get_settings().s3_bucket)
# 3. Broker (простая проверка TCP-порта)
settings = get_settings()
parsed = urlparse(settings.broker_url)
host = parsed.hostname or "broker"
port = parsed.port or 5672
with socket.create_connection((host, port), timeout=2):
pass
except Exception as e:
print(f"Readiness check failed: {e}")
return error_response(
request, 503, "unavailable", "Зависимость недоступна"
)