From 7e1780be672247d551377a73c58d92688d8e1e3f Mon Sep 17 00:00:00 2001 From: Sunrise443 Date: Sun, 22 Nov 2026 17:20:34 +0300 Subject: [PATCH] level 3 --- .env.example | 5 + app/broker.py | 58 ++++++ app/config.py | 34 ++++ app/jobs.py | 80 ++++++++ app/main.py | 10 +- app/routes.py | 23 ++- app/store.py | 212 ++++++++++++++++---- app/thumbnail.py | 64 ++++++ app/worker.py | 310 +++++++++++++++++++++++++++++ compose.yaml | 123 +++++++++++- infra/rabbitmq/entrypoint.sh | 18 ++ migrations/006_attachment_jobs.sql | 47 +++++ requirements.txt | 7 + scripts/restart.sh | 7 +- 14 files changed, 938 insertions(+), 60 deletions(-) create mode 100644 app/broker.py create mode 100644 app/jobs.py create mode 100644 app/thumbnail.py create mode 100644 app/worker.py create mode 100644 infra/rabbitmq/entrypoint.sh create mode 100644 migrations/006_attachment_jobs.sql diff --git a/.env.example b/.env.example index e80abf70..21680a0b 100644 --- a/.env.example +++ b/.env.example @@ -31,6 +31,11 @@ S3_SECRET_ACCESS_KEY_FILE=/run/secrets/s3_secret_access_key MAX_UPLOAD_BYTES=10485760 MAX_IMAGE_PIXELS=40000000 BROKER_URL_FILE=/run/secrets/broker_url +# First boot of RabbitMQ creates this user. BROKER_URL must use the same +# user and password; the app reads the URL from the file above. +RABBITMQ_USER=messenger +RABBITMQ_PASSWORD=change-me-rabbit +BROKER_URL=amqp://messenger:change-me-rabbit@rabbitmq:5672/ WORKER_CONCURRENCY=2 JOB_MAX_ATTEMPTS=5 JOB_TIMEOUT_SECONDS=60 diff --git a/app/broker.py b/app/broker.py new file mode 100644 index 00000000..def2b811 --- /dev/null +++ b/app/broker.py @@ -0,0 +1,58 @@ +"""Durable RabbitMQ queue. Publish waits for a broker confirm; the worker acks later.""" +import logging + +import aio_pika +from aio_pika import DeliveryMode, Message + +from .jobs import QUEUE, QUEUE_ARGUMENTS + +logger = logging.getLogger('messenger') + + +class BrokerDown(Exception): + """The broker did not confirm. The message stays internal and has no URL.""" + + +class Broker: + def __init__(self, url: str) -> None: + self._url = url + self._connection: aio_pika.abc.AbstractRobustConnection | None = None + self.channel: aio_pika.abc.AbstractChannel | None = None + + async def connect(self) -> None: + try: + self._connection = await aio_pika.connect_robust(self._url, timeout=10) + # Confirms make publish wait until the broker has the message, not only the socket. + self.channel = await self._connection.channel(publisher_confirms=True, on_return_raises=True) + await self.channel.declare_queue(QUEUE, durable=True, arguments=QUEUE_ARGUMENTS) + except Exception: + raise RuntimeError('broker did not become reachable') from None + + async def close(self) -> None: + if self._connection is not None: + await self._connection.close() + + async def ready(self) -> None: + connection = self._connection + if connection is None or connection.is_closed or connection.reconnecting: + raise BrokerDown() + + async def publish(self, body: bytes) -> None: + """Persistent message. Returns after the broker confirms it, or raises BrokerDown.""" + if self.channel is None: + raise BrokerDown() + message = Message( + body, + content_type='application/json', + delivery_mode=DeliveryMode.PERSISTENT, + ) + try: + await self.channel.default_exchange.publish( + message, + routing_key=QUEUE, + mandatory=True, + timeout=10, + ) + except Exception as exc: + logger.warning('broker did not confirm a job (%s)', type(exc).__name__) + raise BrokerDown() from None diff --git a/app/config.py b/app/config.py index a71beb94..adccc7aa 100644 --- a/app/config.py +++ b/app/config.py @@ -68,6 +68,40 @@ def _database_url() -> str: ) +def load_broker_url() -> str: + """AMQP URL from a file. The value is not logged.""" + file_name = os.getenv('BROKER_URL_FILE', '').strip() + if not file_name: + raise RuntimeError('BROKER_URL_FILE is required') + url = _read_secret_file('BROKER_URL_FILE', file_name) + if not url.startswith(('amqp://', 'amqps://')): + raise RuntimeError('BROKER_URL_FILE must be an amqp URL') + return url + + +def _bounded_int(name: str, default: int, upper: int) -> int: + raw = os.getenv(name, '').strip() + try: + value = int(raw) if raw else default + except ValueError: + raise RuntimeError('%s must be an integer' % name) from None + if value < 1 or value > upper: + raise RuntimeError('%s must be between 1 and %d' % (name, upper)) + return value + + +def job_max_attempts() -> int: + return _bounded_int('JOB_MAX_ATTEMPTS', 5, 20) + + +def job_timeout_seconds() -> int: + return _bounded_int('JOB_TIMEOUT_SECONDS', 60, 600) + + +def worker_concurrency() -> int: + return _bounded_int('WORKER_CONCURRENCY', 1, 8) + + def load_object_settings() -> ObjectSettings: """S3 credentials come from files. The values are not logged.""" endpoint = os.getenv('S3_ENDPOINT', '').strip() diff --git a/app/jobs.py b/app/jobs.py new file mode 100644 index 00000000..fd0be86c --- /dev/null +++ b/app/jobs.py @@ -0,0 +1,80 @@ +"""Job payload for the broker. Bytes and credentials never go into the message.""" +import json +import re +from typing import Optional + +JOB_TYPE = 'attachment.process.v1' +PIPELINE_VERSION = 1 +QUEUE = 'attachment.jobs' +# Same arguments on every declare, otherwise RabbitMQ rejects the second one. +QUEUE_ARGUMENTS = {'x-queue-type': 'classic'} + +_UUID = re.compile(r'^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$') + + +class PermanentJobError(Exception): + """Do not retry: another attempt would fail the same way.""" + + def __init__(self, code: str) -> None: + super().__init__(code) + self.code = code + + +class TransientJobError(Exception): + """Worth another attempt: storage or the broker blinked.""" + + +def staging_key(attachment_id: str) -> str: + return 'staging/' + attachment_id + + +def original_key(attachment_id: str) -> str: + return 'originals/' + attachment_id + + +def variant_key(attachment_id: str, name: str) -> str: + return 'variants/' + attachment_id + '/' + name + + +def dump_job(job_id: str, attachment_id: str, attempt: int, created_at: str) -> bytes: + payload = { + 'schema_version': 1, + 'job_id': job_id, + 'type': JOB_TYPE, + 'attachment_id': attachment_id, + 'pipeline_version': PIPELINE_VERSION, + 'attempt': attempt, + 'created_at': created_at, + } + return json.dumps(payload, separators=(',', ':')).encode('utf-8') + + +def load_job(raw: bytes) -> Optional[dict]: + """Return the fields the worker trusts, or None when the body is not our job.""" + try: + data = json.loads(raw.decode('utf-8')) + except (UnicodeDecodeError, ValueError): + return None + if not isinstance(data, dict): + return None + if data.get('schema_version') != 1 or data.get('type') != JOB_TYPE: + return None + if data.get('pipeline_version') != PIPELINE_VERSION: + return None + attempt = data.get('attempt') + if type(attempt) is not int or attempt < 1: + return None + for field in ('job_id', 'attachment_id'): + value = data.get(field) + if not isinstance(value, str) or _UUID.fullmatch(value) is None: + return None + created_at = data.get('created_at') + if not isinstance(created_at, str) or not created_at.endswith('Z') or len(created_at) > 40: + return None + return { + 'job_id': data['job_id'], + 'attachment_id': data['attachment_id'], + 'pipeline_version': PIPELINE_VERSION, + 'attempt': attempt, + 'created_at': created_at, + } diff --git a/app/main.py b/app/main.py index 0a3caa22..8679db5a 100644 --- a/app/main.py +++ b/app/main.py @@ -10,7 +10,8 @@ from fastapi.exceptions import RequestValidationError from fastapi.responses import JSONResponse from starlette.exceptions import HTTPException as StarletteHTTPException -from .config import load_object_settings, load_settings +from .broker import Broker +from .config import load_broker_url, load_object_settings, load_settings from .db import open_pool from .errors import ApiError from .objects import ObjectStore @@ -58,8 +59,14 @@ _OPENAPI_PATH = Path(__file__).resolve().parents[1] / 'contracts' / 'openapi.jso async def lifespan(app: FastAPI): """Migrations are not applied here: the one-shot migrate service runs them before replicas start.""" settings = load_settings() + # The client logs can echo the AMQP URL. Leave them off. + logging.getLogger('aio_pika').setLevel(logging.ERROR) + logging.getLogger('aiormq').setLevel(logging.ERROR) pool = await open_pool(settings.database_url) + broker = Broker(load_broker_url()) try: + await broker.connect() + app.state.broker = broker app.state.store = Store( pool, settings.session_ttl_seconds, @@ -69,6 +76,7 @@ async def lifespan(app: FastAPI): logger.info('instance %s started', settings.instance_id) yield finally: + await broker.close() await pool.close() diff --git a/app/routes.py b/app/routes.py index 433ad176..d8d8ab2e 100644 --- a/app/routes.py +++ b/app/routes.py @@ -11,6 +11,7 @@ from pydantic import BaseModel, ValidationError from starlette.responses import Response from .auth import BASIC_CHALLENGE, BEARER_CHALLENGE, parse_basic, parse_bearer +from .broker import BrokerDown from .drain import draining from .errors import ( conflict, @@ -160,10 +161,14 @@ async def liveness() -> JSONResponse: @router.get('/health/ready') -async def readiness(store: Store = Depends(get_store)) -> JSONResponse: +async def readiness(request: Request, store: Store = Depends(get_store)) -> JSONResponse: if draining.is_set(): raise unavailable('Реплика завершает работу') await store.ready() + try: + await request.app.state.broker.ready() + except BrokerDown: + raise unavailable('Очередь недоступна') from None return JSONResponse({'status': 'ok'}) @@ -276,7 +281,7 @@ async def upload_attachment( spool = None try: spool, size, digest, actual = await _spool_upload(request, declared) - attachment = await store.create_attachment( + queued = await store.create_attachment( chat.id, actor.id, filename, @@ -288,7 +293,13 @@ async def upload_attachment( finally: if spool is not None: spool.close() - return JSONResponse(attachment.to_dict(), status_code=202) + # The row is committed. 202 follows only a broker confirm, so a stopped API keeps the job. + try: + await request.app.state.broker.publish(queued.body) + except BrokerDown: + await store.abandon_upload(queued.attachment.id) + raise unavailable('Очередь недоступна') from None + return JSONResponse(queued.attachment.to_dict(), status_code=202) def _variant(request: Request) -> str: @@ -324,11 +335,9 @@ async def download_attachment( raise not_found('Вложение не найдено') if attachment.status != 'ready': raise conflict('Вложение ещё не готово') - if variant != 'original': - raise not_found('Вариант не найден') - found = await store.read_original(attachment_id, actor.id) + found = await store.read_content(attachment_id, actor.id, variant) if found is None: - raise not_found('Вложение не найдено') + raise not_found('Вариант не найден' if variant != 'original' else 'Вложение не найдено') content_type, body = found return Response(content=body, media_type=content_type) diff --git a/app/store.py b/app/store.py index 51dc03c8..aa93ad0d 100644 --- a/app/store.py +++ b/app/store.py @@ -11,9 +11,11 @@ from typing import BinaryIO, Dict, List, Optional, Sequence, Tuple import asyncpg +from .config import job_max_attempts from .errors import conflict, invalid_request, not_found, unavailable +from .jobs import PIPELINE_VERSION, dump_job, original_key, staging_key from .migrate import expected_versions -from .objects import ORIGINAL_PREFIX, MissingObject, ObjectStore, StorageError +from .objects import MissingObject, ObjectStore, StorageError from .pagination import Key from .passwords import hash_password, password_matches @@ -72,6 +74,26 @@ class Message: } +@dataclass(frozen=True) +class Variant: + name: str + content_type: str + size_bytes: int + width: int + height: int + sha256: str + + def to_dict(self) -> dict: + return { + 'name': self.name, + 'content_type': self.content_type, + 'size_bytes': self.size_bytes, + 'width': self.width, + 'height': self.height, + 'sha256': self.sha256, + } + + @dataclass(frozen=True) class Attachment: id: str @@ -84,6 +106,8 @@ class Attachment: status: str created_at: str updated_at: str + variants: Tuple[Variant, ...] = () + error_code: Optional[str] = None def to_dict(self) -> dict: return { @@ -95,13 +119,19 @@ class Attachment: 'size_bytes': self.size_bytes, 'sha256': self.sha256, 'status': self.status, - 'variants': [], - 'error_code': None, + 'variants': [item.to_dict() for item in self.variants], + 'error_code': self.error_code if self.status == 'failed' else None, 'created_at': self.created_at, 'updated_at': self.updated_at, } +@dataclass(frozen=True) +class QueuedUpload: + attachment: Attachment + body: bytes + + @dataclass(frozen=True) class AttachmentRef: """One metadata row as the reconciler sees it. Not an API response.""" @@ -391,45 +421,63 @@ class Store: body: BinaryIO, size_bytes: int, sha256: str, - ) -> Attachment: + ) -> QueuedUpload: chat_uuid = _as_uuid(chat_id, 'Некорректный chat_id') owner_uuid = _as_uuid(owner_id, 'Некорректный user_id') attachment_id = uuid.uuid4() - # The key is not derived from filename. A crash after PUT and before INSERT leaves an - # unreferenced object; a failed INSERT deletes it. 202 is returned only after both succeed. - # Status stays queued: readiness is a later metadata read, not this response. - object_key = ORIGINAL_PREFIX + str(attachment_id) + job_id = uuid.uuid4() + # filename is never a storage key. Bytes go to staging/ first; the worker copies them + # unchanged to originals/ and writes the thumbnail. 202 is sent only after the broker + # confirms the job, which happens in the route after this commit. + staged = staging_key(str(attachment_id)) + final = original_key(str(attachment_id)) created = self._now() try: - await asyncio.to_thread(self._objects.put_stream, object_key, body, size_bytes, content_type) + await asyncio.to_thread(self._objects.put_stream, staged, body, size_bytes, content_type) except StorageError: - await self._discard_object(object_key) + await self._discard_object(staged) raise unavailable('Хранилище недоступно') from None try: async with self._pool.acquire() as conn: - await conn.execute( - ''' - INSERT INTO attachments ( - id, chat_id, owner_id, filename, content_type, size_bytes, sha256, - object_key, staging_key, status, 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, + object_key, staging_key, status, created_at, updated_at + ) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, 'queued', $10, $10) + ''', + attachment_id, + chat_uuid, + owner_uuid, + filename, + content_type, + size_bytes, + sha256, + final, + staged, + created, + ) + await conn.execute( + ''' + INSERT INTO attachment_jobs ( + id, attachment_id, pipeline_version, attempt, max_attempts, + created_at, updated_at + ) + VALUES ($1, $2, $3, 1, $4, $5, $5) + ''', + job_id, + attachment_id, + PIPELINE_VERSION, + job_max_attempts(), + created, ) - VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $8, 'queued', $9, $9) - ''', - attachment_id, - chat_uuid, - owner_uuid, - filename, - content_type, - size_bytes, - sha256, - object_key, - created, - ) except Exception: - await self._discard_object(object_key) + await self._discard_object(staged) raise stamp = _stamp(created) - return Attachment( + attachment = Attachment( str(attachment_id), str(chat_uuid), str(owner_uuid), @@ -441,6 +489,39 @@ class Store: stamp, stamp, ) + return QueuedUpload( + attachment, + dump_job(str(job_id), str(attachment_id), 1, stamp), + ) + + async def abandon_upload(self, attachment_id: str) -> None: + """Drop a queued upload whose job never reached the broker.""" + attachment_uuid = _as_uuid(attachment_id, 'Некорректный attachment_id') + staged: Optional[str] = None + async with self._pool.acquire() as conn: + async with conn.transaction(): + row = await conn.fetchrow( + ''' + SELECT staging_key + FROM attachments + WHERE id = $1 AND status = 'queued' + FOR UPDATE + ''', + attachment_uuid, + ) + if row is None: + return + staged = row['staging_key'] + await conn.execute( + 'DELETE FROM attachment_jobs WHERE attachment_id = $1', + attachment_uuid, + ) + await conn.execute( + "DELETE FROM attachments WHERE id = $1 AND status = 'queued'", + attachment_uuid, + ) + if staged: + await self._discard_object(staged) async def attachment_index(self) -> List[AttachmentRef]: """Every attachment row. `in_use` means a message still points at it. @@ -522,7 +603,7 @@ class Store: 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.created_at, a.updated_at + a.size_bytes, a.sha256, 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 @@ -530,6 +611,7 @@ class Store: attachment_uuid, user_uuid, ) + variants = () if row is None else await self._variants(conn, attachment_uuid) if row is None: return None return Attachment( @@ -543,22 +625,62 @@ class Store: row['status'], _stamp(row['created_at']), _stamp(row['updated_at']), + variants, + row['error_code'], ) - async def read_original(self, attachment_id: str, user_id: str) -> Optional[Tuple[str, bytes]]: + async def _variants(self, conn: asyncpg.Connection, attachment_id: uuid.UUID) -> Tuple[Variant, ...]: + rows = await conn.fetch( + ''' + SELECT name, content_type, size_bytes, width, height, sha256 + FROM attachment_variants + WHERE attachment_id = $1 AND pipeline_version = $2 + ORDER BY name + ''', + attachment_id, + PIPELINE_VERSION, + ) + return tuple( + Variant( + row['name'], + row['content_type'], + row['size_bytes'], + row['width'], + row['height'], + row['sha256'], + ) + for row in rows + ) + + async def read_content(self, attachment_id: str, user_id: str, variant: str) -> Optional[Tuple[str, bytes]]: attachment_uuid = _as_uuid(attachment_id, 'Некорректный attachment_id') user_uuid = _as_uuid(user_id, 'Некорректный user_id') async with self._pool.acquire() as conn: - row = await conn.fetchrow( - ''' - SELECT a.content_type, a.size_bytes, a.sha256, a.object_key - FROM attachments a - JOIN chat_members m ON m.chat_id = a.chat_id AND m.user_id = $2 - WHERE a.id = $1 - ''', - attachment_uuid, - user_uuid, - ) + if variant == 'original': + row = await conn.fetchrow( + ''' + SELECT a.content_type, a.size_bytes, a.sha256, a.object_key + FROM attachments a + JOIN chat_members m ON m.chat_id = a.chat_id AND m.user_id = $2 + WHERE a.id = $1 + ''', + attachment_uuid, + user_uuid, + ) + else: + row = await conn.fetchrow( + ''' + SELECT v.content_type, v.size_bytes, v.sha256, v.object_key + FROM attachment_variants v + JOIN attachments a ON a.id = v.attachment_id + JOIN chat_members m ON m.chat_id = a.chat_id AND m.user_id = $2 + WHERE v.attachment_id = $1 AND v.pipeline_version = $3 AND v.name = $4 + ''', + attachment_uuid, + user_uuid, + PIPELINE_VERSION, + variant, + ) if row is None: return None try: @@ -635,12 +757,14 @@ class Store: return await self._replay(conn, sender_uuid, path, key, request_hash) if linked: rows = await conn.fetch( - 'SELECT id, chat_id FROM attachments WHERE id = ANY($1::uuid[])', + 'SELECT id, chat_id, status FROM attachments WHERE id = ANY($1::uuid[])', list(linked), ) - found = {row['id']: row['chat_id'] for row in rows} - if len(found) != len(linked) or any(found[item] != chat_uuid for item in linked): + found = {row['id']: row for row in rows} + if len(found) != len(linked) or any(found[item]['chat_id'] != chat_uuid for item in linked): raise not_found('Вложение не найдено') + if any(found[item]['status'] == 'failed' for item in linked): + raise conflict('Нельзя прикрепить повреждённое вложение') await conn.execute( ''' INSERT INTO messages (id, chat_id, sender_id, text, created_at) diff --git a/app/thumbnail.py b/app/thumbnail.py new file mode 100644 index 00000000..ead02fad --- /dev/null +++ b/app/thumbnail.py @@ -0,0 +1,64 @@ +"""JPEG thumbnail for pipeline v1. Crop and WebP belong to the next grade.""" +import io +from typing import Tuple + +from PIL import Image, ImageOps, UnidentifiedImageError + +from .images import MAX_IMAGE_PIXELS + +THUMBNAIL_BOX = 256 +# Pillow's default 75 is fine for a preview; the contract only fixes the pixel size. +_JPEG_QUALITY = 85 + + +class ImageRejected(Exception): + """The bytes are not a PNG/JPEG we can decode inside the pixel limit.""" + + +def _fit(width: int, height: int, box: int) -> Tuple[int, int]: + """Fit inside box×box, keep the aspect ratio, never upscale, round down, at least 1 px.""" + if width <= box and height <= box: + return width, height + fitted_width = box + fitted_height = (height * box) // width + if fitted_height > box: + fitted_height = box + fitted_width = (width * box) // height + return max(1, fitted_width), max(1, fitted_height) + + +def _on_white(image: Image.Image) -> Image.Image: + if image.mode == 'RGB': + return image + rgba = image.convert('RGBA') + background = Image.new('RGB', rgba.size, (255, 255, 255)) + background.paste(rgba, mask=rgba.getchannel('A')) + return background + + +def make_thumbnail(data: bytes) -> Tuple[bytes, int, int]: + """Return JPEG bytes and the size actually written. 320×200 becomes 256×160.""" + Image.MAX_IMAGE_PIXELS = MAX_IMAGE_PIXELS + source = Image.open(io.BytesIO(data)) + try: + oriented = ImageOps.exif_transpose(source) + if oriented is not source: + source.close() + source = oriented + source.load() + width, height = source.size + if width <= 0 or height <= 0 or width * height > MAX_IMAGE_PIXELS: + raise ImageRejected() + fitted = _fit(width, height, THUMBNAIL_BOX) + if fitted != (width, height): + source = source.resize(fitted, Image.Resampling.LANCZOS) + rgb = _on_white(source) + buffer = io.BytesIO() + rgb.save(buffer, format='JPEG', quality=_JPEG_QUALITY) + return buffer.getvalue(), fitted[0], fitted[1] + except ImageRejected: + raise + except (UnidentifiedImageError, Image.DecompressionBombError, OSError, ValueError): + raise ImageRejected() from None + finally: + source.close() diff --git a/app/worker.py b/app/worker.py new file mode 100644 index 00000000..03516122 --- /dev/null +++ b/app/worker.py @@ -0,0 +1,310 @@ +"""Separate process: copy the staged original and write one thumbnail. + +Ack happens only after that result is committed. A kill before ack redelivers the same +job id; the variant primary key keeps the second run from creating a second thumbnail. +Staging is left in place. Removing it is a later step, after the result is known to be safe. +""" +import asyncio +import hashlib +import logging +import signal +import uuid +from datetime import datetime, timezone +from pathlib import Path + +import asyncpg + +from .broker import Broker, BrokerDown +from .config import job_max_attempts, job_timeout_seconds, load_broker_url, load_object_settings, load_settings, worker_concurrency +from .db import open_pool +from .jobs import PIPELINE_VERSION, QUEUE, QUEUE_ARGUMENTS, PermanentJobError, TransientJobError, dump_job, load_job, variant_key +from .objects import MissingObject, ObjectStore, StorageError +from .thumbnail import ImageRejected, make_thumbnail + +logger = logging.getLogger('messenger') + +_HEARTBEAT = Path('/tmp/worker-alive') +_inflight = 0 + + +def _lock_key(attachment_id: uuid.UUID) -> int: + return attachment_id.int & ((1 << 63) - 1) + + +def _prepare( + objects: ObjectStore, + attachment_id: str, + staging: str, + final: str, + size: int, + digest: str, + content_type: str, +) -> dict: + """Copy the original unchanged and build the thumbnail. Runs off the event loop.""" + try: + data = objects.get(staging) + except MissingObject: + raise TransientJobError() from None + except StorageError: + raise TransientJobError() from None + if len(data) != size or hashlib.sha256(data).hexdigest() != digest: + raise PermanentJobError('processing_failed') + if staging != final: + try: + objects.put(final, data, content_type) + except StorageError: + raise TransientJobError() from None + try: + jpeg, width, height = make_thumbnail(data) + except ImageRejected: + raise PermanentJobError('invalid_image') from None + thumb_key = variant_key(attachment_id, 'thumbnail') + try: + objects.put(thumb_key, jpeg, 'image/jpeg') + except StorageError: + raise TransientJobError() from None + return { + 'object_key': thumb_key, + 'size_bytes': len(jpeg), + 'width': width, + 'height': height, + 'sha256': hashlib.sha256(jpeg).hexdigest(), + } + + +async def _mark_failed(conn: asyncpg.Connection, attachment_id: uuid.UUID, code: str) -> None: + now = datetime.now(timezone.utc) + async with conn.transaction(): + await conn.execute( + ''' + UPDATE attachments + SET status = 'failed', error_code = $2, updated_at = $3 + WHERE id = $1 AND status IN ('queued', 'processing') + ''', + attachment_id, + code, + now, + ) + + +async def _schedule_retry( + conn: asyncpg.Connection, + broker: Broker, + job: dict, + attachment_id: uuid.UUID, + limit: int, +) -> None: + """Advance attempt and publish the next message before the caller acks this one.""" + nxt = job['attempt'] + 1 + now = datetime.now(timezone.utc) + if nxt > limit: + await _mark_failed(conn, attachment_id, 'retry_exhausted') + return + async with conn.transaction(): + moved = await conn.fetchval( + ''' + UPDATE attachment_jobs + SET attempt = $2, updated_at = $3 + WHERE id = $1 AND attempt = $4 + RETURNING attempt + ''', + uuid.UUID(job['job_id']), + nxt, + now, + job['attempt'], + ) + if moved is None: + return + await conn.execute( + ''' + UPDATE attachments + SET status = 'queued', error_code = NULL, updated_at = $2 + WHERE id = $1 AND status IN ('queued', 'processing') + ''', + attachment_id, + now, + ) + await broker.publish(dump_job(job['job_id'], job['attachment_id'], nxt, job['created_at'])) + + +async def _finish(conn: asyncpg.Connection, attachment_id: uuid.UUID, thumb: dict) -> None: + now = datetime.now(timezone.utc) + async with conn.transaction(): + await conn.execute( + ''' + INSERT INTO attachment_variants ( + attachment_id, pipeline_version, name, content_type, size_bytes, + width, height, sha256, object_key + ) + VALUES ($1, $2, 'thumbnail', 'image/jpeg', $3, $4, $5, $6, $7) + ON CONFLICT (attachment_id, pipeline_version, name) DO UPDATE + SET content_type = EXCLUDED.content_type, + size_bytes = EXCLUDED.size_bytes, + width = EXCLUDED.width, + height = EXCLUDED.height, + sha256 = EXCLUDED.sha256, + object_key = EXCLUDED.object_key + ''', + attachment_id, + PIPELINE_VERSION, + thumb['size_bytes'], + thumb['width'], + thumb['height'], + thumb['sha256'], + thumb['object_key'], + ) + await conn.execute( + ''' + UPDATE attachments + SET status = 'ready', error_code = NULL, updated_at = $2 + WHERE id = $1 AND status IN ('queued', 'processing') + ''', + attachment_id, + now, + ) + + +async def _process(pool: asyncpg.Pool, objects: ObjectStore, broker: Broker, job: dict, limit: int, timeout: int) -> None: + attachment_id = uuid.UUID(job['attachment_id']) + async with pool.acquire() as conn: + await conn.execute('SELECT pg_advisory_lock($1)', _lock_key(attachment_id)) + try: + row = await conn.fetchrow( + ''' + SELECT a.status, a.staging_key, a.object_key, a.size_bytes, a.sha256, + a.content_type, j.attempt, j.max_attempts + FROM attachment_jobs j + JOIN attachments a ON a.id = j.attachment_id + WHERE j.id = $1 + ''', + uuid.UUID(job['job_id']), + ) + if row is None or row['status'] in ('ready', 'failed'): + return + if job['attempt'] < row['attempt']: + # The previous attempt crashed after the counter moved and before its ack. + await broker.publish(dump_job(job['job_id'], job['attachment_id'], row['attempt'], job['created_at'])) + return + if job['attempt'] > row['max_attempts']: + await _mark_failed(conn, attachment_id, 'retry_exhausted') + return + now = datetime.now(timezone.utc) + await conn.execute( + ''' + UPDATE attachments + SET status = 'processing', error_code = NULL, updated_at = $2 + WHERE id = $1 AND status IN ('queued', 'processing') + ''', + attachment_id, + now, + ) + try: + thumb = await asyncio.wait_for( + asyncio.to_thread( + _prepare, + objects, + job['attachment_id'], + row['staging_key'], + row['object_key'], + row['size_bytes'], + row['sha256'], + row['content_type'], + ), + timeout=timeout, + ) + except PermanentJobError as exc: + await _mark_failed(conn, attachment_id, exc.code) + return + except (TransientJobError, asyncio.TimeoutError): + await _schedule_retry(conn, broker, job, attachment_id, row['max_attempts']) + return + except Exception: + logger.exception('attachment %s attempt %s failed', job['attachment_id'], job['attempt']) + await _schedule_retry(conn, broker, job, attachment_id, row['max_attempts']) + return + await _finish(conn, attachment_id, thumb) + logger.info('attachment %s ready on attempt %s', job['attachment_id'], job['attempt']) + finally: + await conn.execute('SELECT pg_advisory_unlock($1)', _lock_key(attachment_id)) + + +async def _handle(pool, objects, broker, body: bytes, limit: int, timeout: int) -> None: + job = load_job(body) + if job is None: + logger.warning('dropped a job message that does not match the contract') + return + await _process(pool, objects, broker, job, limit, timeout) + + +async def _beat(stop: asyncio.Event) -> None: + while not stop.is_set(): + _HEARTBEAT.write_text('ok', encoding='ascii') + try: + await asyncio.wait_for(stop.wait(), timeout=5) + except asyncio.TimeoutError: + pass + + +async def _run() -> None: + logging.basicConfig(level=logging.INFO, format='%(levelname)s %(message)s') + # Library logs can include the AMQP URL. Keep them quiet. + logging.getLogger('aio_pika').setLevel(logging.ERROR) + logging.getLogger('aiormq').setLevel(logging.ERROR) + stop = asyncio.Event() + loop = asyncio.get_running_loop() + for sig in (signal.SIGTERM, signal.SIGINT): + loop.add_signal_handler(sig, stop.set) + + settings = load_settings() + limit = job_max_attempts() + timeout = job_timeout_seconds() + pool = await open_pool(settings.database_url) + objects = ObjectStore(load_object_settings()) + broker = Broker(load_broker_url()) + beat = asyncio.create_task(_beat(stop)) + try: + await broker.connect() + channel = broker.channel + if channel is None: + raise RuntimeError('broker did not become reachable') + await channel.set_qos(prefetch_count=worker_concurrency()) + queue = await channel.declare_queue(QUEUE, durable=True, arguments=QUEUE_ARGUMENTS) + + async def on_message(message) -> None: + global _inflight + _inflight += 1 + try: + await _handle(pool, objects, broker, message.body, limit, timeout) + except BrokerDown: + await message.nack(requeue=True) + return + except Exception: + logger.exception('job was not finished') + await message.nack(requeue=True) + return + else: + await message.ack() + finally: + _inflight -= 1 + + consumer = await queue.consume(on_message) + logger.info('worker consuming %s', queue.name) + await stop.wait() + logger.info('worker draining') + await queue.cancel(consumer) + for _ in range(500): + if _inflight == 0: + break + await asyncio.sleep(0.05) + finally: + beat.cancel() + await broker.close() + await pool.close() + + +def main() -> None: + asyncio.run(_run()) + + +if __name__ == '__main__': + main() diff --git a/compose.yaml b/compose.yaml index a4db2d47..ebd71686 100644 --- a/compose.yaml +++ b/compose.yaml @@ -1,8 +1,8 @@ -# Client -> lb (HAProxy) -> api x API_REPLICAS -> postgres (metadata) + minio (private bucket). -# HTTP upload still receives the whole body. POST returns 202 only after the original is stored; -# status stays queued, and a later GET of the metadata is how the client learns readiness. -# Only the LB publishes a port. Networks: edge = lb<->api, data = api/migrate/minio (no LB, no internet). -# DB and MinIO passwords come from .env (not committed) as Compose secret files, never as container env vars. +# Client -> lb (HAProxy) -> api x API_REPLICAS -> postgres + minio + rabbitmq. +# HTTP upload still receives the whole body. POST returns 202 only after the original is in +# staging and RabbitMQ confirms the job. The worker copies the original and writes the thumbnail. +# Only the LB publishes a port. Networks: edge = lb<->api, data = api/worker/stores (no LB, no internet). +# Passwords come from .env (not committed) as Compose secret files, never as container env vars. name: messenger-lab5 x-db-client: &db-client @@ -138,6 +138,36 @@ services: memory: 256M restart: "no" + # Stable hostname: the data directory is rabbit@rabbitmq, so a new container keeps old jobs. + rabbitmq: + image: rabbitmq:4.1-alpine@sha256:cd4009416f83d7e5895020cd71b0963f3b8a4dfc3de74bbb6fb3bfe5f81f01e0 + hostname: rabbitmq + entrypoint: ["/bin/sh", "/bootstrap/rabbitmq-entrypoint.sh"] + secrets: + - rabbitmq_user + - rabbitmq_password + volumes: + - ./infra/rabbitmq/entrypoint.sh:/bootstrap/rabbitmq-entrypoint.sh:ro + - rabbitmqdata:/var/lib/rabbitmq + networks: + - data + healthcheck: + test: ["CMD", "rabbitmq-diagnostics", "-q", "ping"] + interval: 5s + timeout: 10s + retries: 12 + start_period: 20s + deploy: + resources: + limits: + cpus: "1.0" + memory: 512M + reservations: + cpus: "0.25" + memory: 256M + stop_grace_period: 30s + restart: unless-stopped + api: image: messenger-lab5-app:${APP_VERSION:-dev} build: *app-build @@ -165,6 +195,10 @@ services: S3_BUCKET: ${S3_BUCKET:?set in .env} S3_ACCESS_KEY_ID_FILE: /run/secrets/s3_access_key_id S3_SECRET_ACCESS_KEY_FILE: /run/secrets/s3_secret_access_key + BROKER_URL_FILE: /run/secrets/broker_url + JOB_MAX_ATTEMPTS: ${JOB_MAX_ATTEMPTS:-5} + JOB_TIMEOUT_SECONDS: ${JOB_TIMEOUT_SECONDS:-60} + WORKER_CONCURRENCY: ${WORKER_CONCURRENCY:-1} secrets: - source: postgres_password uid: "10001" @@ -178,6 +212,10 @@ services: uid: "10001" gid: "10001" mode: 0400 + - source: broker_url + uid: "10001" + gid: "10001" + mode: 0400 networks: - edge - data @@ -190,6 +228,8 @@ services: condition: service_completed_successfully minio-init: condition: service_completed_successfully + rabbitmq: + condition: service_healthy # Docker health gates startup order and rolling update; the LB runs its own checks (infra/haproxy/haproxy.cfg). healthcheck: test: @@ -207,6 +247,72 @@ services: stop_grace_period: 10s restart: unless-stopped + worker: + image: messenger-lab5-app:${APP_VERSION:-dev} + command: ["python", "-m", "app.worker"] + environment: + <<: *db-client + S3_ENDPOINT: ${S3_ENDPOINT:?set in .env} + S3_REGION: ${S3_REGION:-us-east-1} + S3_BUCKET: ${S3_BUCKET:?set in .env} + S3_ACCESS_KEY_ID_FILE: /run/secrets/s3_access_key_id + S3_SECRET_ACCESS_KEY_FILE: /run/secrets/s3_secret_access_key + BROKER_URL_FILE: /run/secrets/broker_url + JOB_MAX_ATTEMPTS: ${JOB_MAX_ATTEMPTS:-5} + JOB_TIMEOUT_SECONDS: ${JOB_TIMEOUT_SECONDS:-60} + WORKER_CONCURRENCY: ${WORKER_CONCURRENCY:-1} + DB_POOL_MIN: "1" + DB_POOL_MAX: "4" + secrets: + - source: postgres_password + uid: "10001" + gid: "10001" + mode: 0400 + - source: s3_access_key_id + uid: "10001" + gid: "10001" + mode: 0400 + - source: s3_secret_access_key + uid: "10001" + gid: "10001" + mode: 0400 + - source: broker_url + uid: "10001" + gid: "10001" + mode: 0400 + networks: + - data + depends_on: + postgres: + condition: service_healthy + migrate: + condition: service_completed_successfully + minio-init: + condition: service_completed_successfully + rabbitmq: + condition: service_healthy + healthcheck: + test: + - CMD + - python + - -c + - import os,sys,time; p='/tmp/worker-alive'; sys.exit(0 if os.path.exists(p) and time.time()-os.path.getmtime(p)<20 else 1) + interval: 5s + timeout: 3s + retries: 6 + start_period: 25s + stop_signal: SIGTERM + stop_grace_period: 30s + deploy: + resources: + limits: + cpus: "1.0" + memory: 512M + reservations: + cpus: "0.25" + memory: 256M + restart: unless-stopped + lb: image: haproxy:3.2.26-alpine@sha256:96ec3c75a9264ba94e733eeacb44051ed6e7b79bb77a73c2c36f236b6423f1f0 # Loopback only. Both families: on Windows "localhost" tries ::1 first and waits ~2 s if nothing listens. @@ -251,7 +357,14 @@ secrets: environment: S3_ACCESS_KEY_ID s3_secret_access_key: environment: S3_SECRET_ACCESS_KEY + rabbitmq_user: + environment: RABBITMQ_USER + rabbitmq_password: + environment: RABBITMQ_PASSWORD + broker_url: + environment: BROKER_URL volumes: pgdata: miniodata: + rabbitmqdata: diff --git a/infra/rabbitmq/entrypoint.sh b/infra/rabbitmq/entrypoint.sh new file mode 100644 index 00000000..dcf78807 --- /dev/null +++ b/infra/rabbitmq/entrypoint.sh @@ -0,0 +1,18 @@ +#!/bin/sh +# RabbitMQ 4 no longer reads RABBITMQ_DEFAULT_*_FILE. The password is written into a +# root-only config the server reads after it drops privileges. It is not printed. +set -eu + +user=$(tr -d '\r\n' < /run/secrets/rabbitmq_user) +pass=$(tr -d '\r\n' < /run/secrets/rabbitmq_password) +if [ -z "$user" ] || [ -z "$pass" ]; then + echo "RabbitMQ credentials are empty" >&2 + exit 1 +fi + +umask 077 +printf 'default_user = %s\ndefault_pass = %s\ndisk_free_limit.absolute = 50MB\n' \ + "$user" "$pass" > /etc/rabbitmq/conf.d/10-lab.conf +chown rabbitmq:rabbitmq /etc/rabbitmq/conf.d/10-lab.conf + +exec docker-entrypoint.sh rabbitmq-server diff --git a/migrations/006_attachment_jobs.sql b/migrations/006_attachment_jobs.sql new file mode 100644 index 00000000..356f43af --- /dev/null +++ b/migrations/006_attachment_jobs.sql @@ -0,0 +1,47 @@ +-- Job row is the durable intention. published_at stays null until a later outbox +-- step; lease_until is left for a stuck-worker timeout. Neither is required to finish a job. +ALTER TABLE attachments ADD COLUMN error_code TEXT; +ALTER TABLE attachments ADD CONSTRAINT attachments_error_code + CHECK (error_code IS NULL OR (char_length(error_code) >= 1 AND char_length(error_code) <= 64)); + +ALTER TABLE attachments ADD COLUMN pipeline_version INTEGER NOT NULL DEFAULT 1; +ALTER TABLE attachments ADD CONSTRAINT attachments_pipeline CHECK (pipeline_version >= 1); + +CREATE TABLE attachment_jobs ( + id UUID PRIMARY KEY, + attachment_id UUID NOT NULL REFERENCES attachments (id), + pipeline_version INTEGER NOT NULL, + attempt INTEGER NOT NULL, + max_attempts INTEGER NOT NULL, + lease_until TIMESTAMPTZ, + published_at TIMESTAMPTZ, + created_at TIMESTAMPTZ NOT NULL, + updated_at TIMESTAMPTZ NOT NULL, + CONSTRAINT attachment_jobs_attempt CHECK (attempt >= 1 AND attempt <= max_attempts), + CONSTRAINT attachment_jobs_max CHECK (max_attempts >= 1), + CONSTRAINT attachment_jobs_pipeline CHECK (pipeline_version >= 1), + CONSTRAINT attachment_jobs_one UNIQUE (attachment_id, pipeline_version) +); + +CREATE INDEX attachment_jobs_unpublished_idx + ON attachment_jobs (created_at) + WHERE published_at IS NULL; + +CREATE TABLE attachment_variants ( + attachment_id UUID NOT NULL REFERENCES attachments (id), + pipeline_version INTEGER NOT NULL, + name TEXT NOT NULL, + content_type TEXT NOT NULL, + size_bytes INTEGER NOT NULL, + width INTEGER NOT NULL, + height INTEGER NOT NULL, + sha256 TEXT NOT NULL, + object_key TEXT NOT NULL, + PRIMARY KEY (attachment_id, pipeline_version, name), + CONSTRAINT attachment_variants_name CHECK (name IN ('thumbnail', 'crop', 'optimized')), + CONSTRAINT attachment_variants_type CHECK (content_type IN ('image/jpeg', 'image/png', 'image/webp')), + CONSTRAINT attachment_variants_size CHECK (size_bytes >= 1), + CONSTRAINT attachment_variants_dim CHECK (width >= 1 AND height >= 1), + CONSTRAINT attachment_variants_sha CHECK (sha256 ~ '^[a-f0-9]{64}$'), + CONSTRAINT attachment_variants_key UNIQUE (object_key) +); diff --git a/requirements.txt b/requirements.txt index 3298a46c..833fcafa 100644 --- a/requirements.txt +++ b/requirements.txt @@ -24,3 +24,10 @@ typing-inspection==0.4.4 typing_extensions==4.16.0 urllib3==2.8.0 uvicorn==0.53.0 +aio-pika==10.2.3 +aiormq==7.2.5 +multidict==7.2.1 +pamqp==5.0.0 +pillow==13.0.0 +propcache==0.5.4 +yarl==1.25.1 diff --git a/scripts/restart.sh b/scripts/restart.sh index efc12d4e..a7217cd6 100644 --- a/scripts/restart.sh +++ b/scripts/restart.sh @@ -1,8 +1,9 @@ #!/bin/sh set -eu cd "$(dirname "$0")/.." -# Restart the LB, every API replica, PostgreSQL and MinIO. Volumes stay; nothing is re-seeded. -docker compose --env-file .env stop lb api -docker compose --env-file .env restart postgres minio +# Restart the LB, every API replica, the worker, PostgreSQL, MinIO and RabbitMQ. +# Volumes stay; nothing is re-seeded. The broker hostname is stable, so its volume keeps queued jobs. +docker compose --env-file .env stop lb api worker +docker compose --env-file .env restart postgres minio rabbitmq # Brings back all replicas (including one left stopped by stop-one.sh); migrate re-runs as a no-op. docker compose --env-file .env up -d --wait