Отделить обработку вложений от приёма файла.
Upload отвечает 202 после staging и записи задания, worker через RabbitMQ собирает thumbnail, crop и optimized и переживает разрыв до publish. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
+95
-9
@@ -8,7 +8,7 @@ import logging
|
||||
from datetime import datetime, timezone
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
from app import config, db, s3
|
||||
from app import config, db, jobs, s3
|
||||
from app.errors import AppError
|
||||
from app.store import format_ts
|
||||
|
||||
@@ -16,7 +16,8 @@ logger = logging.getLogger("messenger.attachments")
|
||||
_sweep_task: asyncio.Task | None = None
|
||||
|
||||
|
||||
def _public(row) -> dict:
|
||||
def _public(row, variants=None) -> dict:
|
||||
error_code = row["error_code"] if "error_code" in row.keys() else None
|
||||
return {
|
||||
"id": str(row["id"]),
|
||||
"chat_id": str(row["chat_id"]),
|
||||
@@ -26,13 +27,47 @@ def _public(row) -> dict:
|
||||
"size_bytes": row["size_bytes"],
|
||||
"sha256": row["sha256"],
|
||||
"status": row["status"],
|
||||
"variants": [],
|
||||
"error_code": None,
|
||||
"variants": variants or [],
|
||||
"error_code": error_code if row["status"] == "failed" else None,
|
||||
"created_at": format_ts(row["created_at"]),
|
||||
"updated_at": format_ts(row["updated_at"]),
|
||||
}
|
||||
|
||||
|
||||
async def _variants(attachment_id) -> list:
|
||||
async with db.require().acquire() as conn:
|
||||
rows = await conn.fetch(
|
||||
"""
|
||||
SELECT name, content_type, size_bytes, width, height, sha256
|
||||
FROM attachment_variants
|
||||
WHERE attachment_id = $1 AND pipeline_version = 1
|
||||
ORDER BY CASE name
|
||||
WHEN 'thumbnail' THEN 1
|
||||
WHEN 'crop' THEN 2
|
||||
WHEN 'optimized' THEN 3
|
||||
ELSE 4
|
||||
END
|
||||
""",
|
||||
attachment_id,
|
||||
)
|
||||
return [
|
||||
{
|
||||
"name": row["name"],
|
||||
"content_type": row["content_type"],
|
||||
"size_bytes": row["size_bytes"],
|
||||
"width": row["width"],
|
||||
"height": row["height"],
|
||||
"sha256": row["sha256"],
|
||||
}
|
||||
for row in rows
|
||||
]
|
||||
|
||||
|
||||
async def present(row) -> dict:
|
||||
variants = await _variants(row["id"]) if row["status"] == "ready" else []
|
||||
return _public(row, variants)
|
||||
|
||||
|
||||
async def _drop_intent(key: str) -> None:
|
||||
async with db.require().acquire() as conn:
|
||||
await conn.execute(
|
||||
@@ -61,7 +96,7 @@ async def create_attachment(
|
||||
data: bytes,
|
||||
) -> dict:
|
||||
attachment_id = uuid4()
|
||||
key = f"originals/{attachment_id}"
|
||||
key = f"staging/{attachment_id}"
|
||||
created = datetime.now(timezone.utc)
|
||||
digest = hashlib.sha256(data).hexdigest()
|
||||
async with db.require().acquire() as conn:
|
||||
@@ -93,7 +128,7 @@ async def create_attachment(
|
||||
id, chat_id, owner_id, filename, content_type, size_bytes,
|
||||
sha256, object_key, status, error_code, created_at, updated_at
|
||||
)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 'ready', NULL, $9, $9)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 'queued', NULL, $9, $9)
|
||||
""",
|
||||
attachment_id,
|
||||
UUID(chat_id),
|
||||
@@ -105,6 +140,7 @@ async def create_attachment(
|
||||
key,
|
||||
created,
|
||||
)
|
||||
await jobs.insert_job(conn, attachment_id, created)
|
||||
await conn.execute(
|
||||
"UPDATE blob_writes SET committed = TRUE WHERE object_key = $1",
|
||||
key,
|
||||
@@ -115,6 +151,7 @@ async def create_attachment(
|
||||
except Exception:
|
||||
await _compensate(key)
|
||||
raise AppError(503, "service unavailable") from None
|
||||
jobs.kick_publish()
|
||||
return _public(
|
||||
{
|
||||
"id": attachment_id,
|
||||
@@ -124,7 +161,8 @@ async def create_attachment(
|
||||
"content_type": content_type,
|
||||
"size_bytes": len(data),
|
||||
"sha256": digest,
|
||||
"status": "ready",
|
||||
"status": "queued",
|
||||
"error_code": None,
|
||||
"created_at": created,
|
||||
"updated_at": created,
|
||||
}
|
||||
@@ -136,7 +174,8 @@ async def get_for_member(attachment_id: str, user_id: str):
|
||||
row = await conn.fetchrow(
|
||||
"""
|
||||
SELECT a.id, a.chat_id, a.owner_id, a.filename, a.content_type,
|
||||
a.size_bytes, a.sha256, a.object_key, a.status, a.created_at, a.updated_at
|
||||
a.size_bytes, a.sha256, a.object_key, a.status, a.error_code,
|
||||
a.created_at, a.updated_at
|
||||
FROM attachments a
|
||||
JOIN chat_members m ON m.chat_id = a.chat_id AND m.user_id = $2
|
||||
WHERE a.id = $1
|
||||
@@ -167,9 +206,31 @@ async def sweep_orphans() -> int:
|
||||
for row in rows:
|
||||
key = row["object_key"]
|
||||
linked = await conn.fetchval(
|
||||
"SELECT 1 FROM attachments WHERE object_key = $1",
|
||||
"""
|
||||
SELECT 1 FROM attachments WHERE object_key = $1
|
||||
UNION ALL
|
||||
SELECT 1 FROM attachment_variants WHERE object_key = $1
|
||||
LIMIT 1
|
||||
""",
|
||||
key,
|
||||
)
|
||||
busy = False
|
||||
parts = key.split("/")
|
||||
if len(parts) >= 2:
|
||||
try:
|
||||
owner = UUID(parts[1])
|
||||
except ValueError:
|
||||
owner = None
|
||||
if owner is not None:
|
||||
busy = await conn.fetchval(
|
||||
"""
|
||||
SELECT 1 FROM attachment_jobs
|
||||
WHERE attachment_id = $1 AND status IN ('queued', 'processing')
|
||||
""",
|
||||
owner,
|
||||
)
|
||||
if busy:
|
||||
continue
|
||||
if linked:
|
||||
await conn.execute(
|
||||
"UPDATE blob_writes SET committed = TRUE WHERE object_key = $1",
|
||||
@@ -192,10 +253,35 @@ async def sweep_orphans() -> int:
|
||||
return deleted
|
||||
|
||||
|
||||
async def sweep_failed_staging() -> int:
|
||||
"""Drop staging bytes of failed jobs after the retention window. Metadata stays."""
|
||||
deleted = 0
|
||||
async with db.require().acquire() as conn:
|
||||
rows = await conn.fetch(
|
||||
"""
|
||||
SELECT id, object_key
|
||||
FROM attachments
|
||||
WHERE status = 'failed'
|
||||
AND object_key LIKE 'staging/%'
|
||||
AND updated_at < now() - ($1::int * interval '1 second')
|
||||
ORDER BY updated_at
|
||||
LIMIT 20
|
||||
""",
|
||||
config.STAGING_RETENTION_SECONDS,
|
||||
)
|
||||
for row in rows:
|
||||
await s3.delete_key(row["object_key"])
|
||||
async with db.require().acquire() as conn:
|
||||
await conn.execute("DELETE FROM blob_writes WHERE object_key = $1", row["object_key"])
|
||||
deleted += 1
|
||||
return deleted
|
||||
|
||||
|
||||
async def _sweep_loop() -> None:
|
||||
while True:
|
||||
try:
|
||||
await sweep_orphans()
|
||||
await sweep_failed_staging()
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except Exception:
|
||||
|
||||
Reference in New Issue
Block a user