forked from mtusi2026/mtusi2026lab5
add level 3
This commit is contained in:
+29
-9
@@ -1,4 +1,5 @@
|
||||
import asyncio
|
||||
from datetime import datetime, timezone
|
||||
from hashlib import sha256
|
||||
import os
|
||||
from tempfile import TemporaryFile
|
||||
@@ -15,6 +16,7 @@ from .errors import ApiError
|
||||
from .models import Attachment
|
||||
from .routes import get_current_user, get_store
|
||||
from .storage.postgres import PostgresStore
|
||||
from .broker import publish
|
||||
|
||||
router = APIRouter()
|
||||
Image.MAX_IMAGE_PIXELS = 40000000
|
||||
@@ -42,7 +44,7 @@ def inspect_image(file, content_type, max_pixels):
|
||||
file.seek(0)
|
||||
|
||||
|
||||
@router.post("/api/v1/chats/{chat_id}/attachments", response_model=Attachment, status_code=201)
|
||||
@router.post("/api/v1/chats/{chat_id}/attachments", response_model=Attachment, status_code=202)
|
||||
async def upload(chat_id: UUID, request: Request, filename: str = Query(...),
|
||||
user: dict = Depends(get_current_user), store: PostgresStore = Depends(get_store)):
|
||||
await store.get_chat_for_member(chat_id, user["id"])
|
||||
@@ -80,8 +82,8 @@ async def upload(chat_id: UUID, request: Request, filename: str = Query(...),
|
||||
digest.update(chunk)
|
||||
await run_in_threadpool(file.write, chunk)
|
||||
await run_in_threadpool(inspect_image, file, content_type, s3.settings.max_pixels)
|
||||
attachment_id = uuid4()
|
||||
key = f"originals/{attachment_id}"
|
||||
attachment_id, job_id = uuid4(), uuid4()
|
||||
key = f"staging/{attachment_id}/original"
|
||||
async with store.attachment_transaction() as connection:
|
||||
await s3.put(key, file, size, content_type)
|
||||
# Disabled by default; models a crash after PUT, before INSERT.
|
||||
@@ -89,9 +91,15 @@ async def upload(chat_id: UUID, request: Request, filename: str = Query(...),
|
||||
raise ApiError(503, "unavailable", "Инъецирован отказ после S3 PUT")
|
||||
attachment = await store.create_attachment(
|
||||
attachment_id, chat_id, user["id"], filename, content_type,
|
||||
size, digest.hexdigest(), key, connection=connection,
|
||||
size, digest.hexdigest(), key, job_id, connection=connection,
|
||||
)
|
||||
return attachment # Transaction has committed before 201.
|
||||
await publish({
|
||||
"schema_version": 1, "job_id": str(job_id), "type": "attachment.process.v1",
|
||||
"attachment_id": str(attachment_id), "pipeline_version": 1, "attempt": 1,
|
||||
"created_at": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"),
|
||||
})
|
||||
attachment["variants"] = []
|
||||
return attachment
|
||||
except ClientDisconnect:
|
||||
raise ApiError(400, "invalid_request", "Загрузка прервана") from None
|
||||
except TimeoutError:
|
||||
@@ -109,8 +117,20 @@ async def download(attachment_id: UUID, request: Request,
|
||||
variant: str = Query("original", pattern="^(original|thumbnail|crop|optimized)$"),
|
||||
user: dict = Depends(get_current_user), store: PostgresStore = Depends(get_store)):
|
||||
attachment = await store.attachment_for_member(attachment_id, user["id"])
|
||||
if variant != "original":
|
||||
raise ApiError(404, "not_found", "Вариант не найден")
|
||||
data = await request.app.state.s3.download(attachment)
|
||||
return Response(data, media_type=attachment["content_type"],
|
||||
if attachment["status"] != "ready":
|
||||
raise ApiError(409, "conflict", "Вложение ещё не готово")
|
||||
if variant == "original":
|
||||
data = await request.app.state.s3.download(attachment)
|
||||
content_type = attachment["content_type"]
|
||||
else:
|
||||
matching = [item for item in attachment["variants"] if item["name"] == variant]
|
||||
if not matching:
|
||||
raise ApiError(404, "not_found", "Вариант не найден")
|
||||
item = matching[0]
|
||||
suffix = {"thumbnail": "thumbnail.jpg", "crop": "crop.jpg", "optimized": "optimized.webp"}[variant]
|
||||
data = await request.app.state.s3.download_key(
|
||||
f"variants/{attachment_id}/{suffix}", item["size_bytes"], item["sha256"]
|
||||
)
|
||||
content_type = item["content_type"]
|
||||
return Response(data, media_type=content_type,
|
||||
headers={"X-Content-Type-Options": "nosniff", "Cache-Control": "private, no-store"})
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
"""Small durable RabbitMQ adapter; broker messages contain no attachment bytes."""
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
import pika
|
||||
from starlette.concurrency import run_in_threadpool
|
||||
|
||||
from .errors import ApiError
|
||||
|
||||
QUEUE = "attachment.process.v1"
|
||||
|
||||
|
||||
def broker_url() -> str:
|
||||
path = os.environ.get("BROKER_URL_FILE")
|
||||
value = Path(path).read_text(encoding="utf-8").strip() if path else os.environ.get("BROKER_URL", "")
|
||||
if not value.startswith(("amqp://", "amqps://")):
|
||||
raise ValueError("BROKER_URL или BROKER_URL_FILE должен содержать AMQP URL")
|
||||
return value
|
||||
|
||||
|
||||
def _connection() -> pika.BlockingConnection:
|
||||
connection = pika.BlockingConnection(pika.URLParameters(broker_url()))
|
||||
connection.channel().queue_declare(queue=QUEUE, durable=True)
|
||||
return connection
|
||||
|
||||
|
||||
def _publish(payload: dict) -> None:
|
||||
connection = _connection()
|
||||
try:
|
||||
channel = connection.channel()
|
||||
channel.confirm_delivery()
|
||||
channel.basic_publish(
|
||||
exchange="", routing_key=QUEUE,
|
||||
body=json.dumps(payload, separators=(",", ":")).encode("utf-8"),
|
||||
properties=pika.BasicProperties(delivery_mode=pika.DeliveryMode.Persistent, content_type="application/json"),
|
||||
mandatory=True,
|
||||
)
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
|
||||
async def publish(payload: dict) -> None:
|
||||
try:
|
||||
await run_in_threadpool(_publish, payload)
|
||||
except (pika.exceptions.AMQPError, OSError, ValueError) as error:
|
||||
raise ApiError(503, "unavailable", "Брокер недоступен") from error
|
||||
|
||||
|
||||
async def ready() -> None:
|
||||
connection = None
|
||||
try:
|
||||
connection = await run_in_threadpool(_connection)
|
||||
except (pika.exceptions.AMQPError, OSError, ValueError) as error:
|
||||
raise ApiError(503, "unavailable", "Брокер недоступен") from error
|
||||
finally:
|
||||
if connection is not None:
|
||||
await run_in_threadpool(connection.close)
|
||||
@@ -18,8 +18,10 @@ _CONFIGURATION_KEYS = {
|
||||
"S3_ENDPOINT", "S3_REGION", "S3_BUCKET",
|
||||
"S3_ACCESS_KEY_ID", "S3_ACCESS_KEY_ID_FILE",
|
||||
"S3_SECRET_ACCESS_KEY", "S3_SECRET_ACCESS_KEY_FILE",
|
||||
"BROKER_URL", "BROKER_URL_FILE",
|
||||
"MAX_UPLOAD_BYTES", "MAX_IMAGE_PIXELS",
|
||||
"UPLOAD_CONCURRENCY", "UPLOAD_TIMEOUT_SECONDS", "UPLOAD_FAULT_AFTER_S3_PUT",
|
||||
"WORKER_CONCURRENCY", "JOB_MAX_ATTEMPTS", "JOB_TIMEOUT_SECONDS", "STAGING_RETENTION_SECONDS",
|
||||
}
|
||||
|
||||
|
||||
|
||||
+13
-2
@@ -133,8 +133,19 @@ class Attachment(BaseModel):
|
||||
content_type: str
|
||||
size_bytes: int
|
||||
sha256: str
|
||||
status: str = "ready"
|
||||
variants: list = Field(default_factory=list)
|
||||
status: str
|
||||
variants: list["Variant"] = Field(default_factory=list)
|
||||
error_code: str | None = None
|
||||
created_at: datetime
|
||||
updated_at: datetime
|
||||
|
||||
|
||||
class Variant(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
name: str
|
||||
content_type: str
|
||||
size_bytes: int
|
||||
width: int
|
||||
height: int
|
||||
sha256: str
|
||||
|
||||
@@ -8,6 +8,7 @@ from fastapi import APIRouter, Depends, Header, Query, Request, Response
|
||||
from .cursor import CursorError, decode_cursor, encode_cursor
|
||||
from .errors import ApiError
|
||||
from .storage.postgres import PostgresStore
|
||||
from .broker import ready as broker_ready
|
||||
from .models import (
|
||||
Chat,
|
||||
ChatPageResponse,
|
||||
@@ -84,6 +85,7 @@ async def readiness(request: Request, store: PostgresStore = Depends(get_store))
|
||||
raise ApiError(503, "unavailable", "API завершает работу")
|
||||
await store.ready()
|
||||
await request.app.state.s3.ready()
|
||||
await broker_ready()
|
||||
return {"status": "ok"}
|
||||
|
||||
@router.post("/api/v1/users", response_model=User, status_code=201)
|
||||
|
||||
+84
-5
@@ -320,12 +320,15 @@ class PostgresStore:
|
||||
raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error
|
||||
|
||||
async def create_attachment(self, attachment_id, chat_id, owner_id, filename,
|
||||
content_type, size_bytes, digest, object_key, *, connection=None) -> dict:
|
||||
content_type, size_bytes, digest, staging_key, job_id, *, connection=None) -> dict:
|
||||
try:
|
||||
row = await (connection or self.pool).fetchrow(
|
||||
"INSERT INTO attachments (id, chat_id, owner_id, filename, content_type, size_bytes, sha256, object_key) "
|
||||
"INSERT INTO attachments (id, chat_id, owner_id, filename, content_type, size_bytes, sha256, staging_key) "
|
||||
"VALUES ($1,$2,$3,$4,$5,$6,$7,$8) RETURNING *",
|
||||
attachment_id, chat_id, owner_id, filename, content_type, size_bytes, digest, object_key,
|
||||
attachment_id, chat_id, owner_id, filename, content_type, size_bytes, digest, staging_key,
|
||||
)
|
||||
await (connection or self.pool).execute(
|
||||
"INSERT INTO attachment_jobs (job_id, attachment_id) VALUES ($1, $2)", job_id, attachment_id
|
||||
)
|
||||
except DB_ERRORS as error:
|
||||
raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error
|
||||
@@ -341,12 +344,88 @@ class PostgresStore:
|
||||
raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error
|
||||
if row is None:
|
||||
raise ApiError(404, "not_found", "Вложение не найдено")
|
||||
return dict(row)
|
||||
return await self._attachment_with_variants(row)
|
||||
|
||||
async def _attachment_with_variants(self, row: asyncpg.Record | dict) -> dict:
|
||||
result = dict(row)
|
||||
variants = await self.pool.fetch(
|
||||
"SELECT name, content_type, size_bytes, width, height, sha256 FROM attachment_variants "
|
||||
"WHERE attachment_id = $1 AND pipeline_version = $2 ORDER BY name",
|
||||
result["id"], result["pipeline_version"],
|
||||
)
|
||||
result["variants"] = [dict(item) for item in variants]
|
||||
return result
|
||||
|
||||
async def claim_attachment_job(self, attachment_id: UUID) -> dict | None:
|
||||
try:
|
||||
async with self.pool.acquire() as connection, connection.transaction():
|
||||
row = await connection.fetchrow("SELECT * FROM attachments WHERE id = $1 FOR UPDATE", attachment_id)
|
||||
if row is None or row["status"] in {"ready", "failed"}:
|
||||
return None
|
||||
await connection.execute(
|
||||
"UPDATE attachments SET status = 'processing', processing_started_at = now(), updated_at = now() WHERE id = $1",
|
||||
attachment_id,
|
||||
)
|
||||
await connection.execute(
|
||||
"UPDATE attachment_jobs SET status = 'processing', updated_at = now() WHERE attachment_id = $1", attachment_id
|
||||
)
|
||||
return dict(row)
|
||||
except DB_ERRORS as error:
|
||||
raise RuntimeError("PostgreSQL is unavailable") from error
|
||||
|
||||
async def complete_attachment_job(self, attachment_id: UUID, original_key: str, variant: dict) -> None:
|
||||
try:
|
||||
async with self.pool.acquire() as connection, connection.transaction():
|
||||
await connection.execute(
|
||||
"INSERT INTO attachment_variants (attachment_id, pipeline_version, name, object_key, content_type, size_bytes, width, height, sha256) "
|
||||
"VALUES ($1, 1, 'thumbnail', $2, $3, $4, $5, $6, $7) "
|
||||
"ON CONFLICT (attachment_id, pipeline_version, name) DO UPDATE SET object_key = EXCLUDED.object_key, content_type = EXCLUDED.content_type, size_bytes = EXCLUDED.size_bytes, width = EXCLUDED.width, height = EXCLUDED.height, sha256 = EXCLUDED.sha256",
|
||||
attachment_id, variant["object_key"], variant["content_type"], variant["size_bytes"], variant["width"], variant["height"], variant["sha256"],
|
||||
)
|
||||
await connection.execute(
|
||||
"UPDATE attachments SET status = 'ready', original_key = $2, error_code = NULL, updated_at = now() WHERE id = $1",
|
||||
attachment_id, original_key,
|
||||
)
|
||||
await connection.execute("UPDATE attachment_jobs SET status = 'ready', updated_at = now() WHERE attachment_id = $1", attachment_id)
|
||||
except DB_ERRORS as error:
|
||||
raise RuntimeError("PostgreSQL is unavailable") from error
|
||||
|
||||
async def fail_attachment_job(self, attachment_id: UUID, code: str) -> None:
|
||||
try:
|
||||
await self.pool.execute(
|
||||
"UPDATE attachments SET status = 'failed', error_code = $2, updated_at = now() WHERE id = $1", attachment_id, code
|
||||
)
|
||||
await self.pool.execute(
|
||||
"UPDATE attachment_jobs SET status = 'failed', last_error = $2, updated_at = now() WHERE attachment_id = $1", attachment_id, code
|
||||
)
|
||||
except DB_ERRORS as error:
|
||||
raise RuntimeError("PostgreSQL is unavailable") from error
|
||||
|
||||
async def retry_attachment_job(self, attachment_id: UUID, max_attempts: int) -> bool:
|
||||
"""Return true only when a bounded at-least-once retry was recorded."""
|
||||
try:
|
||||
async with self.pool.acquire() as connection, connection.transaction():
|
||||
job = await connection.fetchrow(
|
||||
"SELECT attempt FROM attachment_jobs WHERE attachment_id = $1 FOR UPDATE", attachment_id
|
||||
)
|
||||
if job is not None and job["attempt"] < max_attempts:
|
||||
await connection.execute(
|
||||
"UPDATE attachment_jobs SET attempt = attempt + 1, status = 'queued', last_error = 'processing_failed', updated_at = now() WHERE attachment_id = $1",
|
||||
attachment_id,
|
||||
)
|
||||
await connection.execute(
|
||||
"UPDATE attachments SET status = 'queued', updated_at = now() WHERE id = $1", attachment_id
|
||||
)
|
||||
return True
|
||||
await self.fail_attachment_job(attachment_id, "retry_exhausted")
|
||||
return False
|
||||
except DB_ERRORS as error:
|
||||
raise RuntimeError("PostgreSQL is unavailable") from error
|
||||
|
||||
async def attachment_keys(self) -> dict[str, UUID]:
|
||||
"""Inventory used only by the maintenance reconciler."""
|
||||
try:
|
||||
rows = await self.pool.fetch("SELECT object_key, id FROM attachments")
|
||||
rows = await self.pool.fetch("SELECT COALESCE(original_key, staging_key) AS object_key, id FROM attachments")
|
||||
except DB_ERRORS as error:
|
||||
raise RuntimeError("PostgreSQL is unavailable") from error
|
||||
return {row["object_key"]: row["id"] for row in rows}
|
||||
|
||||
+14
-4
@@ -69,6 +69,13 @@ class S3Store:
|
||||
await self.call("put_object", Bucket=self.settings.bucket, Key=key,
|
||||
Body=file, ContentLength=size, ContentType=content_type)
|
||||
|
||||
async def copy(self, source_key: str, destination_key: str, content_type: str) -> None:
|
||||
await self.call(
|
||||
"copy_object", Bucket=self.settings.bucket, Key=destination_key,
|
||||
CopySource={"Bucket": self.settings.bucket, "Key": source_key},
|
||||
ContentType=content_type, MetadataDirective="REPLACE",
|
||||
)
|
||||
|
||||
async def list(self, prefix: str) -> dict[str, object]:
|
||||
"""Return every object under a controlled prefix, handling S3 pagination."""
|
||||
objects, _ = await self.list_with_pages(prefix)
|
||||
@@ -95,8 +102,11 @@ class S3Store:
|
||||
await self.call("delete_object", Bucket=self.settings.bucket, Key=key)
|
||||
|
||||
async def download(self, attachment):
|
||||
response = await self.call("get_object", Bucket=self.settings.bucket,
|
||||
Key=attachment["object_key"])
|
||||
return await self.download_key(attachment["original_key"], attachment["size_bytes"], attachment["sha256"])
|
||||
|
||||
async def download_key(self, key: str, expected_size: int | None = None,
|
||||
expected_sha256: str | None = None) -> bytes:
|
||||
response = await self.call("get_object", Bucket=self.settings.bucket, Key=key)
|
||||
body = response["Body"]
|
||||
try:
|
||||
data = await run_in_threadpool(body.read, self.settings.max_bytes + 1)
|
||||
@@ -104,7 +114,7 @@ class S3Store:
|
||||
raise ApiError(503, "unavailable", "S3 недоступно") from error
|
||||
finally:
|
||||
body.close()
|
||||
if (len(data) != attachment["size_bytes"] or
|
||||
sha256(data).hexdigest() != attachment["sha256"]):
|
||||
if ((expected_size is not None and len(data) != expected_size) or
|
||||
(expected_sha256 is not None and sha256(data).hexdigest() != expected_sha256)):
|
||||
raise ApiError(503, "unavailable", "Оригинал недоступен")
|
||||
return data
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
"""RabbitMQ consumer for the version-1 attachment pipeline."""
|
||||
import asyncio
|
||||
from hashlib import sha256
|
||||
from io import BytesIO
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
from uuid import UUID
|
||||
|
||||
from PIL import Image, ImageOps
|
||||
|
||||
from .broker import QUEUE, _connection
|
||||
from .config import load_settings
|
||||
from .storage.postgres import PostgresStore
|
||||
from .storage.s3 import S3Settings, S3Store
|
||||
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s worker %(message)s")
|
||||
|
||||
|
||||
def thumbnail(data: bytes) -> tuple[bytes, int, int]:
|
||||
with Image.open(BytesIO(data), formats=("PNG", "JPEG")) as source:
|
||||
image = ImageOps.exif_transpose(source)
|
||||
if image.mode in {"RGBA", "LA"} or (image.mode == "P" and "transparency" in image.info):
|
||||
background = Image.new("RGBA", image.size, "white")
|
||||
background.alpha_composite(image.convert("RGBA"))
|
||||
image = background.convert("RGB")
|
||||
else:
|
||||
image = image.convert("RGB")
|
||||
image.thumbnail((256, 256), Image.Resampling.LANCZOS)
|
||||
output = BytesIO()
|
||||
image.save(output, format="JPEG", quality=85, optimize=True)
|
||||
return output.getvalue(), image.width, image.height
|
||||
|
||||
|
||||
async def process(store: PostgresStore, s3: S3Store, payload: dict) -> None:
|
||||
attachment_id = UUID(payload["attachment_id"])
|
||||
attachment = await store.claim_attachment_job(attachment_id)
|
||||
if attachment is None:
|
||||
return
|
||||
original_key = f"originals/{attachment_id}"
|
||||
variant_key = f"variants/{attachment_id}/thumbnail.jpg"
|
||||
await s3.copy(attachment["staging_key"], original_key, attachment["content_type"])
|
||||
original = await s3.download_key(attachment["staging_key"], attachment["size_bytes"], attachment["sha256"])
|
||||
rendered, width, height = await asyncio.to_thread(thumbnail, original)
|
||||
await s3.put(variant_key, BytesIO(rendered), len(rendered), "image/jpeg")
|
||||
await store.complete_attachment_job(attachment_id, original_key, {
|
||||
"object_key": variant_key, "content_type": "image/jpeg", "size_bytes": len(rendered),
|
||||
"width": width, "height": height, "sha256": sha256(rendered).hexdigest(),
|
||||
})
|
||||
await s3.delete(attachment["staging_key"])
|
||||
|
||||
|
||||
def main() -> None:
|
||||
settings = load_settings()
|
||||
store = PostgresStore(settings.database_url)
|
||||
asyncio.run(store.connect())
|
||||
s3 = S3Store(S3Settings.load())
|
||||
connection = _connection()
|
||||
channel = connection.channel()
|
||||
channel.basic_qos(prefetch_count=max(1, int(os.environ.get("WORKER_CONCURRENCY", "2"))))
|
||||
|
||||
def consume(ch, method, properties, body):
|
||||
del properties
|
||||
try:
|
||||
payload = json.loads(body)
|
||||
if payload["type"] != "attachment.process.v1" or payload["schema_version"] != 1:
|
||||
raise ValueError("unexpected broker payload")
|
||||
asyncio.run(process(store, s3, payload))
|
||||
except Exception:
|
||||
logging.exception("job failed")
|
||||
try:
|
||||
attachment_id = UUID(payload["attachment_id"])
|
||||
retry = asyncio.run(store.retry_attachment_job(
|
||||
attachment_id, max(1, int(os.environ.get("JOB_MAX_ATTEMPTS", "5")))
|
||||
))
|
||||
except Exception:
|
||||
retry = False
|
||||
if retry:
|
||||
ch.basic_nack(method.delivery_tag, requeue=True)
|
||||
else:
|
||||
ch.basic_ack(method.delivery_tag)
|
||||
else:
|
||||
ch.basic_ack(method.delivery_tag)
|
||||
|
||||
try:
|
||||
channel.basic_consume(queue=QUEUE, on_message_callback=consume, auto_ack=False)
|
||||
channel.start_consuming()
|
||||
finally:
|
||||
connection.close()
|
||||
s3.client.close()
|
||||
asyncio.run(store.close())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user