forked from mtusi2026/mtusi2026lab5
feat: ЛР5 - асинхронная обработка вложений, RabbitMQ и transactional outbox
This commit is contained in:
+90
-38
@@ -37,6 +37,7 @@ from app.errors import (
|
||||
UnauthorizedError,
|
||||
UnsupportedMediaTypeError,
|
||||
)
|
||||
from app.outbox import outbox_relay
|
||||
from app.schemas import (
|
||||
AttachmentResponse,
|
||||
ChatResponse,
|
||||
@@ -89,6 +90,10 @@ class PostgresStorage:
|
||||
self.redis_client: redis.Redis | None = None
|
||||
self.s3_client: Any = None
|
||||
|
||||
@property
|
||||
def pool(self) -> asyncpg.Pool | None:
|
||||
return self.pg_pool
|
||||
|
||||
@asynccontextmanager
|
||||
async def acquire_conn(self, timeout: float = 2.0):
|
||||
if self.pg_pool is None:
|
||||
@@ -505,8 +510,8 @@ class PostgresStorage:
|
||||
for r in rows:
|
||||
if r["chat_id"] != cid:
|
||||
raise NotFoundError("Вложение принадлежит другому чату")
|
||||
if r["status"] != "ready":
|
||||
raise ConflictError("Вложение еще не готово или повреждено")
|
||||
if r["status"] == "failed":
|
||||
raise ConflictError("Нельзя прикреплять вложение со статусом failed")
|
||||
|
||||
# 1. Проверяем, обрабатывался ли уже этот idempotency_key
|
||||
existing = await conn.fetchrow(
|
||||
@@ -787,53 +792,81 @@ class PostgresStorage:
|
||||
|
||||
# 7. Генерация идентификаторов
|
||||
att_id = uuid.uuid4()
|
||||
s3_key = f"chats/{chat_id}/{att_id}/{filename}"
|
||||
job_id = uuid.uuid4()
|
||||
staging_key = f"staging/{att_id}/{filename}"
|
||||
sha256_hash = hashlib.sha256(data).hexdigest()
|
||||
now = dt.datetime.now(dt.timezone.utc)
|
||||
now_iso = _format_dt(now)
|
||||
|
||||
# 8. Загрузка файла в S3
|
||||
# 8. Загрузка файла в устойчивый staging в S3
|
||||
def _put_to_s3():
|
||||
self.s3_client.put_object(
|
||||
Bucket=S3_BUCKET,
|
||||
Key=s3_key,
|
||||
Key=staging_key,
|
||||
Body=data,
|
||||
ContentType=ct_clean,
|
||||
)
|
||||
|
||||
await asyncio.to_thread(_put_to_s3)
|
||||
|
||||
# 9. Сохранение метаданных в PostgreSQL (с компенсацией удаления из S3 при ошибке)
|
||||
# 9. Атомарное сохранение в PostgreSQL: attachments + outbox_jobs
|
||||
job_payload = {
|
||||
"schema_version": 1,
|
||||
"job_id": str(job_id),
|
||||
"type": "attachment.process.v1",
|
||||
"attachment_id": str(att_id),
|
||||
"pipeline_version": 1,
|
||||
"attempt": 1,
|
||||
"created_at": now_iso,
|
||||
}
|
||||
|
||||
try:
|
||||
async with self.acquire_conn() as conn:
|
||||
await conn.execute(
|
||||
"""
|
||||
INSERT INTO attachments (
|
||||
id, chat_id, owner_id, filename, content_type,
|
||||
size_bytes, sha256, s3_key, status, error_code,
|
||||
created_at, updated_at
|
||||
async with conn.transaction():
|
||||
await conn.execute(
|
||||
"""
|
||||
INSERT INTO attachments (
|
||||
id, chat_id, owner_id, filename, content_type,
|
||||
size_bytes, sha256, s3_key, status, error_code, variants,
|
||||
created_at, updated_at
|
||||
)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 'queued', NULL, '[]'::jsonb, $9, $9)
|
||||
""",
|
||||
att_id,
|
||||
cid,
|
||||
c_caller,
|
||||
filename,
|
||||
ct_clean,
|
||||
size_bytes,
|
||||
sha256_hash,
|
||||
staging_key,
|
||||
now,
|
||||
)
|
||||
await conn.execute(
|
||||
"""
|
||||
INSERT INTO outbox_jobs (
|
||||
job_id, attachment_id, event_type, payload, status, attempt, created_at, updated_at
|
||||
)
|
||||
VALUES ($1, $2, 'attachment.process.v1', $3::jsonb, 'pending', 1, $4, $4)
|
||||
""",
|
||||
job_id,
|
||||
att_id,
|
||||
json.dumps(job_payload),
|
||||
now,
|
||||
)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 'ready', NULL, $9, $9)
|
||||
""",
|
||||
att_id,
|
||||
cid,
|
||||
c_caller,
|
||||
filename,
|
||||
ct_clean,
|
||||
size_bytes,
|
||||
sha256_hash,
|
||||
s3_key,
|
||||
now,
|
||||
)
|
||||
except Exception as db_err:
|
||||
logger.error("Ошибка записи метаданных в БД, компенсация S3: %s", db_err)
|
||||
logger.error("Ошибка записи метаданных/outbox в БД, компенсация staging S3: %s", db_err)
|
||||
try:
|
||||
await asyncio.to_thread(
|
||||
self.s3_client.delete_object, Bucket=S3_BUCKET, Key=s3_key
|
||||
self.s3_client.delete_object, Bucket=S3_BUCKET, Key=staging_key
|
||||
)
|
||||
except Exception as del_err:
|
||||
logger.error("Ошибка удаления S3 объекта при компенсации: %s", del_err)
|
||||
logger.error("Ошибка удаления staging S3 объекта при компенсации: %s", del_err)
|
||||
raise
|
||||
|
||||
# 10. Уведомляем outbox relay для немедленной публикации
|
||||
outbox_relay.notify()
|
||||
|
||||
return AttachmentResponse(
|
||||
id=str(att_id),
|
||||
chat_id=str(cid),
|
||||
@@ -842,11 +875,11 @@ class PostgresStorage:
|
||||
content_type=ct_clean,
|
||||
size_bytes=size_bytes,
|
||||
sha256=sha256_hash,
|
||||
status="ready",
|
||||
status="queued",
|
||||
variants=[],
|
||||
error_code=None,
|
||||
created_at=_format_dt(now),
|
||||
updated_at=_format_dt(now),
|
||||
created_at=now_iso,
|
||||
updated_at=now_iso,
|
||||
)
|
||||
|
||||
async def get_attachment(
|
||||
@@ -862,7 +895,8 @@ class PostgresStorage:
|
||||
row = await conn.fetchrow(
|
||||
"""
|
||||
SELECT a.id, a.chat_id, a.owner_id, a.filename, a.content_type,
|
||||
a.size_bytes, a.sha256, a.status, a.error_code, a.created_at, a.updated_at
|
||||
a.size_bytes, a.sha256, a.status, a.error_code, a.variants,
|
||||
a.created_at, a.updated_at
|
||||
FROM attachments a
|
||||
WHERE a.id = $1
|
||||
""",
|
||||
@@ -879,6 +913,11 @@ class PostgresStorage:
|
||||
if not is_member:
|
||||
raise NotFoundError("Вложение не найдено")
|
||||
|
||||
raw_variants = row["variants"]
|
||||
if isinstance(raw_variants, str):
|
||||
raw_variants = json.loads(raw_variants)
|
||||
variants_list = [VariantResponse(**v) for v in (raw_variants or [])]
|
||||
|
||||
return AttachmentResponse(
|
||||
id=str(row["id"]),
|
||||
chat_id=str(row["chat_id"]),
|
||||
@@ -888,7 +927,7 @@ class PostgresStorage:
|
||||
size_bytes=row["size_bytes"],
|
||||
sha256=row["sha256"],
|
||||
status=row["status"],
|
||||
variants=[],
|
||||
variants=variants_list,
|
||||
error_code=row["error_code"],
|
||||
created_at=_format_dt(row["created_at"]),
|
||||
updated_at=_format_dt(row["updated_at"]),
|
||||
@@ -903,13 +942,14 @@ class PostgresStorage:
|
||||
except ValueError:
|
||||
raise NotFoundError("Вложение не найдено")
|
||||
|
||||
if variant not in (None, "", "original"):
|
||||
raise NotFoundError("Вариант не найден")
|
||||
variant_clean = (variant or "original").strip().lower()
|
||||
if variant_clean not in ("original", "thumbnail", "crop", "optimized"):
|
||||
raise InvalidRequestError("Неизвестный вариант изображения")
|
||||
|
||||
async with self.acquire_conn() as conn:
|
||||
row = await conn.fetchrow(
|
||||
"""
|
||||
SELECT a.chat_id, a.content_type, a.s3_key, a.status
|
||||
SELECT a.chat_id, a.content_type, a.s3_key, a.status, a.variants
|
||||
FROM attachments a
|
||||
WHERE a.id = $1
|
||||
""",
|
||||
@@ -926,11 +966,23 @@ class PostgresStorage:
|
||||
if not is_member:
|
||||
raise NotFoundError("Вложение не найдено")
|
||||
|
||||
# По контракту: для queued/processing/failed возвращается 409 Conflict
|
||||
if row["status"] != "ready":
|
||||
raise ConflictError("Вложение повреждено или еще не готово")
|
||||
raise ConflictError("Вложение еще не готово или завершилось с ошибкой")
|
||||
|
||||
s3_key = row["s3_key"]
|
||||
content_type = row["content_type"]
|
||||
if variant_clean == "original":
|
||||
s3_key = row["s3_key"]
|
||||
content_type = row["content_type"]
|
||||
else:
|
||||
raw_variants = row["variants"]
|
||||
if isinstance(raw_variants, str):
|
||||
raw_variants = json.loads(raw_variants)
|
||||
variants_list = raw_variants or []
|
||||
matched = next((v for v in variants_list if v.get("name") == variant_clean), None)
|
||||
if not matched:
|
||||
raise NotFoundError("Запрошенный вариант не найден")
|
||||
s3_key = f"chats/{row['chat_id']}/{aid}/{variant_clean}"
|
||||
content_type = matched["content_type"]
|
||||
|
||||
def _get_from_s3():
|
||||
resp = self.s3_client.get_object(Bucket=S3_BUCKET, Key=s3_key)
|
||||
|
||||
Reference in New Issue
Block a user