From 4602b83074aa9d1418b45d6593cc0a0c90d6831b Mon Sep 17 00:00:00 2001 From: casablanca Date: Thu, 5 Nov 2026 21:32:43 +0300 Subject: [PATCH] =?UTF-8?q?=D0=BB=D0=B0=D0=B1=D0=B0=20=D0=BD=D0=B0=203?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 2 + compose.yaml | 54 ++++- .../versions/e5a12026a001_async_jobs.py | 77 ++++++ requirements.txt | 3 +- src/dispatcher.py | 94 ++++++++ src/main.py | 54 ++++- src/models.py | 2 +- src/queue.py | 61 +++++ src/repositories.py | 5 +- src/worker.py | 225 ++++++++++++++++++ tests/queue_grade3.py | 108 +++++++++ 11 files changed, 676 insertions(+), 9 deletions(-) create mode 100644 migrations/versions/e5a12026a001_async_jobs.py create mode 100644 src/dispatcher.py create mode 100644 src/queue.py create mode 100644 src/worker.py create mode 100644 tests/queue_grade3.py diff --git a/.gitignore b/.gitignore index b5a71896..9ffeb2f0 100644 --- a/.gitignore +++ b/.gitignore @@ -30,3 +30,5 @@ coverage/ .vscode/ # Keep small, sanitized evidence summaries in evidence/ under version control. # Inspect git diff --cached: ignore rules are not a secret scanner. + +infra/rabbitmq/rabbitmq.conf diff --git a/compose.yaml b/compose.yaml index 6887b172..3d7dda66 100644 --- a/compose.yaml +++ b/compose.yaml @@ -14,11 +14,14 @@ x-api: &api S3_SECRET_ACCESS_KEY_FILE: /run/secrets/s3_secret_access_key MAX_UPLOAD_BYTES: 10485760 MAX_IMAGE_PIXELS: 40000000 + RABBITMQ_HOST: rabbitmq + RABBITMQ_PASSWORD_FILE: /run/secrets/rabbitmq_password secrets: - database_url - cache_url - s3_access_key_id - s3_secret_access_key + - rabbitmq_password depends_on: migrate: condition: service_completed_successfully @@ -154,6 +157,52 @@ services: cpus: 0.5 mem_limit: 256m + rabbitmq: + image: rabbitmq:4.1.4-management-alpine + hostname: rabbitmq + environment: + RABBITMQ_CONFIG_FILE: /etc/rabbitmq/rabbitmq + secrets: + - rabbitmq_password + volumes: + - rabbitmq_data:/var/lib/rabbitmq + - ./infra/rabbitmq/rabbitmq.conf:/etc/rabbitmq/rabbitmq.conf:ro + healthcheck: + test: ["CMD", "rabbitmq-diagnostics", "-q", "check_running"] + interval: 10s + timeout: 15s + retries: 10 + start_period: 40s + restart: unless-stopped + mem_limit: 512m + cpus: 0.5 + + dispatcher: + <<: *api + command: [ "python", "-m", "src.dispatcher" ] + depends_on: + migrate: + condition: service_completed_successfully + rabbitmq: + condition: service_healthy + s3-init: + condition: service_completed_successfully + healthcheck: + disable: true + + worker: + <<: *api + command: [ "python", "-m", "src.worker" ] + depends_on: + migrate: + condition: service_completed_successfully + rabbitmq: + condition: service_healthy + s3-init: + condition: service_completed_successfully + healthcheck: + disable: true + secrets: postgres_password: file: ./secrets/postgres_password @@ -169,8 +218,11 @@ secrets: file: ./secrets/s3_access_key_id s3_secret_access_key: file: ./secrets/s3_secret_access_key + rabbitmq_password: + file: ./secrets/rabbitmq_password volumes: postgres_data: redis_data: - s3_data: \ No newline at end of file + s3_data: + rabbitmq_data: \ No newline at end of file diff --git a/migrations/versions/e5a12026a001_async_jobs.py b/migrations/versions/e5a12026a001_async_jobs.py new file mode 100644 index 00000000..d6f87082 --- /dev/null +++ b/migrations/versions/e5a12026a001_async_jobs.py @@ -0,0 +1,77 @@ +from alembic import op +import sqlalchemy as sa + +revision = "e5a12026a001" +down_revision = "d9e53b20f7c1" +branch_labels = None +depends_on = None + + +def upgrade(): + op.drop_constraint( + "ck_attachments_status", + "attachments", + type_="check", + ) + op.create_check_constraint( + "ck_attachments_status", + "attachments", + "status IN ('queued', 'processing', 'ready', 'failed')", + ) + + op.create_table( + "attachment_jobs", + sa.Column("id", sa.Uuid(), primary_key=True), + sa.Column( + "attachment_id", + sa.Uuid(), + sa.ForeignKey("attachments.id", ondelete="CASCADE"), + nullable=False, + unique=True, + ), + sa.Column( + "attempt", + sa.Integer(), + nullable=False, + server_default="1", + ), + sa.Column( + "status", + sa.String(20), + nullable=False, + server_default="queued", + ), + sa.Column("published_at", sa.DateTime(timezone=True)), + sa.Column("started_at", sa.DateTime(timezone=True)), + sa.Column( + "created_at", + sa.DateTime(timezone=True), + nullable=False, + server_default=sa.text("CURRENT_TIMESTAMP"), + ), + ) + + op.create_index( + "ix_attachment_jobs_unpublished", + "attachment_jobs", + ["published_at"], + ) + + +def downgrade(): + op.drop_index( + "ix_attachment_jobs_unpublished", + table_name="attachment_jobs", + ) + op.drop_table("attachment_jobs") + + op.drop_constraint( + "ck_attachments_status", + "attachments", + type_="check", + ) + op.create_check_constraint( + "ck_attachments_status", + "attachments", + "status IN ('pending', 'ready')", + ) \ No newline at end of file diff --git a/requirements.txt b/requirements.txt index 418ea3c4..3084fe48 100644 --- a/requirements.txt +++ b/requirements.txt @@ -19,4 +19,5 @@ argon2-cffi==25.1.0 redis==7.0.1 boto3==1.43.120 Pillow==13.0.0 -python-multipart==0.0.32 \ No newline at end of file +python-multipart==0.0.32 +pika==1.3.2 diff --git a/src/dispatcher.py b/src/dispatcher.py new file mode 100644 index 00000000..6a581cad --- /dev/null +++ b/src/dispatcher.py @@ -0,0 +1,94 @@ +import asyncio +import logging + +from sqlalchemy import text + +from src.database import SessionFactory, engine +from src.queue import connect, publish + +logging.basicConfig(level=logging.INFO) + + +async def dispatch(channel): + async with SessionFactory() as session: + async with session.begin(): + await session.execute( + text(""" + UPDATE attachment_jobs + SET status = 'queued', + published_at = NULL, + started_at = NULL + WHERE status = 'processing' + AND started_at < now() - interval '90 seconds' + """) + ) + + await session.execute( + text(""" + UPDATE attachments + SET status = 'queued', + updated_at = now() + WHERE status = 'processing' + AND id IN ( + SELECT attachment_id + FROM attachment_jobs + WHERE status = 'queued' + ) + """) + ) + + result = await session.execute( + text(""" + SELECT id, attachment_id, attempt, created_at + FROM attachment_jobs + WHERE published_at IS NULL + AND status = 'queued' + ORDER BY created_at + LIMIT 25 + FOR UPDATE SKIP LOCKED + """) + ) + + rows = result.all() + + for row in rows: + publish(channel, row) + + await session.execute( + text(""" + UPDATE attachment_jobs + SET published_at = now() + WHERE id = :id + """), + {"id": row.id}, + ) + + return len(rows) + + +async def main(): + while True: + connection = None + + try: + connection, channel = connect() + channel.confirm_delivery() + + while True: + count = await dispatch(channel) + await asyncio.sleep(0.2 if count else 1) + + except Exception: + logging.exception("Dispatcher reconnect") + await asyncio.sleep(3) + + finally: + if connection and connection.is_open: + connection.close() + + +if __name__ == "__main__": + try: + asyncio.run(main()) + finally: + asyncio.run(engine.dispose()) \ No newline at end of file diff --git a/src/main.py b/src/main.py index cdce042f..aee19592 100644 --- a/src/main.py +++ b/src/main.py @@ -14,6 +14,7 @@ from fastapi.security import ( HTTPBearer, ) from botocore.exceptions import BotoCoreError, ClientError +from sqlalchemy import text from sqlalchemy.exc import IntegrityError, SQLAlchemyError from sqlalchemy.ext.asyncio import AsyncSession from starlette.exceptions import HTTPException as StarletteHTTPException @@ -552,7 +553,7 @@ async def get_messages_endpoint( @app.post( "/api/v1/chats/{chat_id}/attachments", response_model=Attachment, - status_code=201, + status_code=202, ) async def upload_attachment_endpoint( chat_id: UUID, @@ -600,7 +601,7 @@ async def upload_attachment_endpoint( attachment_id = uuid4() extension = "png" if content_type == "image/png" else "jpg" - s3_key = f"attachments/{chat_id}/{attachment_id}.{extension}" + s3_key = f"staging/{chat_id}/{attachment_id}.{extension}" try: await put_object( @@ -628,6 +629,17 @@ async def upload_attachment_endpoint( s3_key=s3_key, ) + await session.execute( + text(""" + INSERT INTO attachment_jobs (id, attachment_id) + VALUES (:job_id, :attachment_id) + """), + { + "job_id": uuid4(), + "attachment_id": attachment_id, + }, + ) + await session.commit() except BaseException: @@ -688,6 +700,7 @@ async def get_attachment_content_endpoint( attachment_id: UUID, current_user: User = Depends(get_current_user), session: AsyncSession = Depends(get_db_session), + variant: str = Query(default="original"), ): result = await get_attachment( session=session, @@ -704,6 +717,41 @@ async def get_attachment_content_endpoint( attachment, s3_key = result + if attachment.status != "ready": + raise APIError( + status_code=409, + code="conflict", + message="Attachment is not ready", + ) + + if variant == "thumbnail": + selected = next( + (item for item in attachment.variants if item.name == "thumbnail"), + None, + ) + + if selected is None: + raise APIError( + status_code=404, + code="not_found", + message="Variant not found", + ) + + s3_key = ( + f"variants/{attachment.chat_id}/{attachment_id}/thumbnail.jpg" + ) + media_type = selected.content_type + + elif variant == "original": + media_type = attachment.content_type + + else: + raise APIError( + status_code=404, + code="not_found", + message="Variant not found", + ) + try: body = await get_object(s3_key) except (BotoCoreError, ClientError, OSError, TimeoutError) as exc: @@ -715,7 +763,7 @@ async def get_attachment_content_endpoint( return Response( content=body, - media_type=attachment.content_type, + media_type=media_type, headers={ "Cache-Control": "private, no-store", "X-Content-Type-Options": "nosniff", diff --git a/src/models.py b/src/models.py index f579d3a4..f24e5ecb 100644 --- a/src/models.py +++ b/src/models.py @@ -145,7 +145,7 @@ class Attachment(BaseModel): content_type: str = Field(pattern=r"^image/(png|jpeg)$") size_bytes: int = Field(ge=1, le=10485760) sha256: str = Field(pattern=r"^[a-f0-9]{64}$") - status: str = Field(pattern=r"^ready$") + status: str = Field(pattern=r"^(queued|processing|ready|failed)$") variants: list[Variant] error_code: str | None created_at: datetime diff --git a/src/queue.py b/src/queue.py new file mode 100644 index 00000000..65d5d775 --- /dev/null +++ b/src/queue.py @@ -0,0 +1,61 @@ +import json +import os +from datetime import timezone +from pathlib import Path + +import pika + +QUEUE = "attachment.process.v1" + + +def connect(): + password = Path( + os.environ["RABBITMQ_PASSWORD_FILE"] + ).read_text().strip() + + credentials = pika.PlainCredentials( + "messenger", + password, + ) + + connection = pika.BlockingConnection( + pika.ConnectionParameters( + host=os.getenv("RABBITMQ_HOST", "rabbitmq"), + credentials=credentials, + heartbeat=60, + blocked_connection_timeout=30, + connection_attempts=3, + retry_delay=2, + ) + ) + + channel = connection.channel() + channel.queue_declare(queue=QUEUE, durable=True) + + return connection, channel + + +def publish(channel, row): + payload = { + "schema_version": 1, + "job_id": str(row.id), + "type": "attachment.process.v1", + "attachment_id": str(row.attachment_id), + "pipeline_version": 1, + "attempt": row.attempt, + "created_at": row.created_at.astimezone( + timezone.utc + ).isoformat().replace("+00:00", "Z"), + } + + channel.basic_publish( + exchange="", + routing_key=QUEUE, + body=json.dumps(payload).encode(), + properties=pika.BasicProperties( + delivery_mode=2, + content_type="application/json", + message_id=str(row.id), + ), + mandatory=True, + ) \ No newline at end of file diff --git a/src/repositories.py b/src/repositories.py index 258ac91f..9f9f312a 100644 --- a/src/repositories.py +++ b/src/repositories.py @@ -478,7 +478,7 @@ async def create_message( FROM attachments WHERE id = ANY (:attachment_ids) AND chat_id = :chat_id - AND status = 'ready' + AND status != 'failed' """), { "attachment_ids": data.attachment_ids, @@ -793,7 +793,7 @@ async def create_attachment( :size_bytes, :sha256, :s3_key, - 'ready' + 'queued' ) RETURNING id, @@ -852,7 +852,6 @@ async def get_attachment( ON cm.chat_id = a.chat_id WHERE a.id = :attachment_id AND cm.user_id = :current_user_id - AND a.status = 'ready' """ ), { diff --git a/src/worker.py b/src/worker.py new file mode 100644 index 00000000..81190b46 --- /dev/null +++ b/src/worker.py @@ -0,0 +1,225 @@ +import asyncio +import hashlib +import io +import json +import logging +import time +from uuid import UUID + +from PIL import Image, ImageOps +from sqlalchemy import text + +from src.database import SessionFactory +from src.queue import QUEUE, connect +from src.storage import get_object, put_object + +logging.basicConfig(level=logging.INFO) + + +def make_thumbnail(body: bytes): + with Image.open(io.BytesIO(body)) as source: + source.load() + image = ImageOps.exif_transpose(source) + image.thumbnail((256, 256), Image.Resampling.LANCZOS) + + if image.mode != "RGB": + rgba = image.convert("RGBA") + background = Image.new("RGBA", rgba.size, "white") + background.alpha_composite(rgba) + image = background.convert("RGB") + + output = io.BytesIO() + image.save(output, format="JPEG", quality=85, optimize=True) + + return output.getvalue(), image.width, image.height + + +async def process(payload: dict): + job_id = UUID(payload["job_id"]) + attachment_id = UUID(payload["attachment_id"]) + + async with SessionFactory() as session: + async with session.begin(): + result = await session.execute( + text(""" + SELECT j.status, j.attempt, + a.s3_key, a.content_type, a.chat_id + FROM attachment_jobs j + JOIN attachments a ON a.id = j.attachment_id + WHERE j.id = :job_id + AND j.attachment_id = :attachment_id + FOR UPDATE OF j + """), + {"job_id": job_id, "attachment_id": attachment_id}, + ) + + row = result.one_or_none() + + if row is None or row.status in ("ready", "failed"): + return + + if row.attempt != payload["attempt"]: + return + + if row.status == "processing": + return + + await session.execute( + text(""" + UPDATE attachment_jobs + SET status = 'processing', started_at = now() + WHERE id = :id + """), + {"id": job_id}, + ) + + await session.execute( + text(""" + UPDATE attachments + SET status = 'processing', updated_at = now() + WHERE id = :id + """), + {"id": attachment_id}, + ) + + try: + body = await get_object(row.s3_key) + thumbnail, width, height = await asyncio.to_thread( + make_thumbnail, body + ) + + original_key = ( + f"attachments/{row.chat_id}/{attachment_id}/original" + ) + thumbnail_key = ( + f"variants/{row.chat_id}/{attachment_id}/thumbnail.jpg" + ) + + await put_object(original_key, body, row.content_type) + await put_object(thumbnail_key, thumbnail, "image/jpeg") + + variant = { + "name": "thumbnail", + "content_type": "image/jpeg", + "size_bytes": len(thumbnail), + "width": width, + "height": height, + "sha256": hashlib.sha256(thumbnail).hexdigest(), + } + + async with SessionFactory() as session: + async with session.begin(): + await session.execute( + text(""" + UPDATE attachments + SET status = 'ready', + s3_key = :key, + variants = CAST(:variants AS json), + error_code = NULL, + updated_at = now() + WHERE id = :id + """), + { + "id": attachment_id, + "key": original_key, + "variants": json.dumps([variant]), + }, + ) + + await session.execute( + text(""" + UPDATE attachment_jobs + SET status = 'ready' + WHERE id = :id + """), + {"id": job_id}, + ) + + except Exception: + logging.exception("Processing failed: %s", attachment_id) + + async with SessionFactory() as session: + async with session.begin(): + if row.attempt >= 5: + await session.execute( + text(""" + UPDATE attachment_jobs + SET status = 'failed' + WHERE id = :id + """), + {"id": job_id}, + ) + + await session.execute( + text(""" + UPDATE attachments + SET status = 'failed', + error_code = 'retry_exhausted', + updated_at = now() + WHERE id = :id + """), + {"id": attachment_id}, + ) + else: + await session.execute( + text(""" + UPDATE attachment_jobs + SET status = 'queued', + attempt = attempt + 1, + published_at = NULL, + started_at = NULL + WHERE id = :id + """), + {"id": job_id}, + ) + + await session.execute( + text(""" + UPDATE attachments + SET status = 'queued', updated_at = now() + WHERE id = :id + """), + {"id": attachment_id}, + ) + + +def main(): + while True: + connection = None + + try: + connection, channel = connect() + channel.basic_qos(prefetch_count=1) + + loop = asyncio.new_event_loop() + asyncio.set_event_loop(loop) + + def callback(ch, method, properties, body): + try: + loop.run_until_complete(process(json.loads(body))) + ch.basic_ack(delivery_tag=method.delivery_tag) + except Exception: + logging.exception("Worker processing error") + ch.basic_nack( + delivery_tag=method.delivery_tag, + requeue=True, + ) + time.sleep(2) + + channel.basic_consume( + queue=QUEUE, + on_message_callback=callback, + ) + channel.start_consuming() + + except Exception: + logging.exception("Worker reconnect") + time.sleep(3) + + finally: + if connection and connection.is_open: + connection.close() + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/tests/queue_grade3.py b/tests/queue_grade3.py new file mode 100644 index 00000000..e0def2c8 --- /dev/null +++ b/tests/queue_grade3.py @@ -0,0 +1,108 @@ + +import sys +import time +from pathlib import Path + +from client import Client, check +from image_probe import jpeg_size + +BASE_URL = "http://localhost:8080" +STATE_FILE = Path("/tmp/lab5_grade3_attachment.txt") + + +def prepare(): + c = Client(BASE_URL) + alice, bob, _, chat = c.bootstrap() + + attachment, original = c.attachment(alice, chat) + attachment_id = attachment["id"] + + current = c.call( + "GET", + f"/api/v1/attachments/{attachment_id}", + actor=bob, + schema="Attachment", + )["json"] + + check(current["status"] == "queued", "expected queued while worker is stopped") + + message = c.message( + alice, + chat, + "Проверка очереди", + attachments=[attachment_id], + )["json"] + + check( + message["attachment_ids"] == [attachment_id], + "message did not retain attachment", + ) + + STATE_FILE.write_text( + "\n".join([attachment_id, bob["token"], original.hex()]), + encoding="utf-8", + ) + + print("PASS: HTTP 202, queued, message linked") + print("Attachment:", attachment_id) + print("Now restart API and RabbitMQ, then start worker") + + +def verify(): + attachment_id, token, original_hex = STATE_FILE.read_text( + encoding="utf-8" + ).splitlines() + + c = Client(BASE_URL) + actor = {"token": token} + deadline = time.monotonic() + 90 + + while time.monotonic() < deadline: + attachment = c.call( + "GET", + f"/api/v1/attachments/{attachment_id}", + actor=actor, + schema="Attachment", + )["json"] + + check(attachment["status"] != "failed", "processing failed") + + if attachment["status"] == "ready": + break + + time.sleep(0.5) + else: + raise AssertionError("attachment did not become ready") + + original = c.call( + "GET", + f"/api/v1/attachments/{attachment_id}/content", + actor=actor, + ) + + check(original["bytes"] == bytes.fromhex(original_hex), "original changed") + + thumbnail = c.call( + "GET", + f"/api/v1/attachments/{attachment_id}/content?variant=thumbnail", + actor=actor, + ) + + check( + thumbnail["headers"].get_content_type() == "image/jpeg", + "thumbnail is not JPEG", + ) + + check( + jpeg_size(thumbnail["bytes"]) == (256, 160), + "incorrect thumbnail dimensions", + ) + + print("PASS: restart recovery, ready, original, JPEG thumbnail 256x160") + + +if __name__ == "__main__": + if len(sys.argv) != 2 or sys.argv[1] not in {"prepare", "verify"}: + raise SystemExit("Usage: python tests/queue_grade3.py prepare|verify") + + {"prepare": prepare, "verify": verify}[sys.argv[1]]()