From 813fc03da53b5fbae10eced7373bdfb42b9a4079 Mon Sep 17 00:00:00 2001 From: Sunrise443 Date: Sun, 22 Nov 2026 17:59:11 +0300 Subject: [PATCH] level 4 --- .env.example | 11 + REPORT.md | 100 +++++- app/broker.py | 58 +-- app/config.py | 32 ++ app/fault.py | 117 ++++++ app/jobs.py | 35 ++ app/main.py | 12 +- app/outbox.py | 165 +++++++++ app/replay.py | 130 +++++++ app/routes.py | 17 +- app/selfcheck.py | 101 ++++++ app/store.py | 47 +-- app/thumbnail.py | 125 ++++++- app/worker.py | 615 +++++++++++++++++++++++--------- compose.yaml | 15 +- evidence/level4.txt | 32 ++ migrations/007_outbox_retry.sql | 48 +++ scripts/level4_demo.py | 464 ++++++++++++++++++++++++ 18 files changed, 1859 insertions(+), 265 deletions(-) create mode 100644 app/fault.py create mode 100644 app/outbox.py create mode 100644 app/replay.py create mode 100644 app/selfcheck.py create mode 100644 evidence/level4.txt create mode 100644 migrations/007_outbox_retry.sql create mode 100644 scripts/level4_demo.py diff --git a/.env.example b/.env.example index 21680a0b..a9f8df49 100644 --- a/.env.example +++ b/.env.example @@ -39,4 +39,15 @@ BROKER_URL=amqp://messenger:change-me-rabbit@rabbitmq:5672/ WORKER_CONCURRENCY=2 JOB_MAX_ATTEMPTS=5 JOB_TIMEOUT_SECONDS=60 +# Full jitter before the next attempt: uniform(0, min(cap, base * 2^(attempt-1))). +JOB_RETRY_BASE_SECONDS=0.5 +JOB_RETRY_CAP_SECONDS=30 +# A dead worker's processing row is queued again after this. A live worker refreshes it. +# The effective lease is at least JOB_TIMEOUT_SECONDS + 30. +JOB_LEASE_SECONDS=90 +# Ready staging is deleted after the ready commit. Failed staging is kept this long so +# `python -m app.replay` can still read it, then removed. STAGING_RETENTION_SECONDS=86400 +# Derivative parameters are fixed in app/thumbnail.py, not here: +# thumbnail JPEG q=85 inside 256, crop JPEG q=85 at 128, optimized WebP q=80 method=4 inside 1280. +# EXIF orientation is applied, then metadata is not copied into the derivatives. diff --git a/REPORT.md b/REPORT.md index e98f75e9..d1d60e11 100644 --- a/REPORT.md +++ b/REPORT.md @@ -1,37 +1,113 @@ # Отчёт — лабораторная 5 - Автор, группа: TODO -- Целевая оценка; выбранный трек 5, если нужен: TODO +- Целевая оценка; выбранный трек 5, если нужен: **4**. Трек 5 не выбран и не начат. - Commit/PR: TODO после публикации -- Использованные источники, библиотеки и помощь ИИ: TODO +- Использованные источники: README и контракты этой лабораторной, [RabbitMQ reliability](https://www.rabbitmq.com/docs/reliability), [publisher confirms](https://www.rabbitmq.com/docs/confirms), Pillow (JPEG/WebP). Код уровня 4 собран с ассистентом Cursor; цифры ниже сняты с локального стенда 2026-11-22, не придуманы. ## Запуск из чистого clone -TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных. +Нужны Docker Compose, Python 3.9+ и свободный порт из `LB_PORT` (по умолчанию 8080). На этой Windows-машине команда `python3` — заглушка Store и не запускает тесты; рабочий интерпретатор — `python` 3.14. На Linux достаточно `python3` / `make`. + +```sh +cp .env.example .env +# В .env задать свои локальные пароли. Файл не коммитить. +# BROKER_URL должен совпадать с RABBITMQ_USER и RABBITMQ_PASSWORD. + +docker compose --env-file .env config --quiet +docker compose --env-file .env up -d --build +# Дождаться healthy у lb. Миграции применяет одноразовый сервис migrate, не процесс API. + +python tests/smoke.py --base-url http://127.0.0.1:8080 +# то же самое, если python3 настоящий: make test PYTHON=python +python scripts/level4_demo.py +docker compose --env-file .env exec -T worker python -m app.selfcheck +``` + +Остановка без удаления данных: `docker compose --env-file .env down`. +Удаление учебных volume: `docker compose --env-file .env down -v`. + +Секреты читаются из файлов `/run/secrets/*`, не из переменных окружения процесса приложения. `GET /health/ready` требует PostgreSQL с применёнными миграциями, доступный бакет и брокер. Worker в эту проверку не входит: остановленный worker не заставляет API уменьшать картинку в запросе. + +Образы закреплены в `compose.yaml`: Postgres 16.10, MinIO `RELEASE.2025-09-07`, RabbitMQ 4.1, HAProxy 3.2.26, приложение `python:3.14.8-slim-bookworm`. ## Архитектура и решения -TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab4, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации. +Из lab4 сохранены пользователи, сессии, чаты, keyset-история, идемпотентность сообщений, две реплики API за HAProxy и приватный бакет MinIO. Upload больше не отвечает 201. Клиент по-прежнему отдаёт все байты в HTTP. + +Цепочка: API кладёт оригинал в `staging/` и в одной транзакции пишет `attachments` (status `queued`) и `attachment_jobs`. Это и есть ответ 202. В сообщении брокера только `job_id`, `attachment_id`, `pipeline_version=1`, `attempt`, `created_at`. Байтов и паролей там нет. + +`published_at` выставляется после publisher confirm. Пока он пустой, реплики API и worker раз в секунду забирают строку `FOR UPDATE SKIP LOCKED` и публикуют её. Подтверждение брокера и ack worker — разные границы: confirm значит «брокер принял стойкое сообщение», ack — «результат уже в PostgreSQL». Повторная доставка нормальна. Ключ эффекта — `(attachment_id, pipeline_version, variant)`; повтор пишет те же ключи S3 и делает `ON CONFLICT` по этому первичному ключу. + +Worker отдельно от API. Prefetch равен `WORKER_CONCURRENCY` (в локальном `.env` это 2, потолок в коде 8). На время обработки берётся advisory lock по вложению и обновляется `lease_until`. Живой worker продлевает lease. Если lease истёк и lock уже никто не держит, строка снова становится `queued` с пустым `published_at`. Долгая живая обработка lock не отпускает, второй прогон её не забирает. + +Повтор при временной ошибке (`storage`, `timeout`, неожиданный сбой хранилища) считает full jitter: равномерно от 0 до `min(cap, base * 2^(attempt-1))`, по умолчанию base 0.5 с и cap 30 с. Число попыток — `JOB_MAX_ATTEMPTS` (5), оно пишется в строку job. Постоянная ошибка (`invalid_image`, битый checksum) и исчерпание попыток ставят `failed`, пишут `attachment_job_failures` и копию сообщения в durable-очередь `attachment.jobs.dlq`. Стек в `error_code` не попадает. + +`python -m app.replay ` для `failed` снова ставит ту же job в очередь (attempt 1, те же ключи вариантов). Для `ready` только дописывает аудит `already_ready` и ничего не запускает. Для `queued`/`processing` тоже не создаёт вторую job. + +Варианты, без которых статус не становится `ready`: + +| Вариант | Формат | Правило | +| --- | --- | --- | +| thumbnail | JPEG quality 85 | вписать в 256×256, не увеличивать; 320×200 → 256×160 | +| crop | JPEG quality 85 | центральный квадрат, затем 128×128, маленькие исходники увеличиваются | +| optimized | WebP quality 80, method 4 | вписать в 1280×1280, не увеличивать; EXIF в файл не пишется | + +Перед этим применяется EXIF orientation, альфа кладётся на белый. Ограничения: 10 МиБ и 40 млн пикселей на приёме и ещё раз в worker до полного decode, `JOB_TIMEOUT_SECONDS` (60) на попытку, память контейнера worker 512M. Staging удаляется после commit `ready` (`staging_key` становится равен `object_key`). Staging у `failed` хранится `STAGING_RETENTION_SECONDS` (86400), чтобы replay ещё мог прочитать оригинал; текущие `queued`/`processing` не чистятся. + +Переключатели `lab_faults` пустые в обычной работе. Их ставит только `python -m app.fault` внутри контейнера `api`. Это учебный кран для разрыва commit/publish и для остановки worker, не часть публичного API. ## Доказательства критериев +Сырой вывод: [evidence/level4.txt](evidence/level4.txt). Команда демо: `python scripts/level4_demo.py` (около 86 с на все сценарии ниже). + | Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства | | --- | --- | --- | --- | -| Публичный smoke | make test | TODO | TODO | -| Остальные пункты уровня 3 | TODO | TODO | TODO | -| Все пункты уровня 4, если заявлен | TODO | TODO | TODO | -| Выбранный трек 5, если заявлен | TODO | TODO | TODO | +| Публичный smoke, 202 и JPEG thumbnail 256×160 | `python tests/smoke.py --base-url http://127.0.0.1:8080` | PASS, в том числе после демо сбоев | evidence/level4.txt | +| Офлайн-контракт | `python scripts/check_contract.py` | PASS | evidence/level4.txt | +| Брокер и worker отдельные, сообщение переживает confirm | `docker compose up`, очереди classic durable | smoke доходит до ready, пока worker не делает resize внутри HTTP | evidence/level4.txt | +| Состояния и один набор вариантов | `scripts/level4_demo.py` | у готовых вложений ровно 3 строки `attachment_variants` | evidence/level4.txt | +| Crop 128 и WebP | selfcheck в контейнере worker и скачивание в демо | JPEG 128×128, WebP `RIFF/WEBP`, для 320×200 optimized остаётся 320×200; EXIF orientation 6 даёт thumbnail 160×256 и в WebP EXIF не остаётся | evidence/level4.txt | +| Лимиты bytes/пикселей | `python -m app.selfcheck` | обрезки и мусор отвергаются до decode | evidence/level4.txt | +| Outbox: пауза между commit и publish | fault `pause-outbox`, upload `1ebba94c-516f-4007-8c47-d240db28de5f` | 202, две секунды `published_at` пустой, после `fault clear` тот же id становится ready | evidence/level4.txt | +| Crash после COMMIT и до publish | fault `commit-before-publish` вместе с паузой, id `1fabbbaa-3b68-45da-bbf3-deca86ac8e82` | процесс API завершился (вырос RestartCount реплики), строка жива, `published_at` пустой, после снятия паузы тот же id ready. Новое задание вручную не создавалось | evidence/level4.txt | +| Lease зависшего processing | id `cd637725-a1e2-463a-99c3-49d6f126525d`: status processing и lease в прошлом, сообщения в очереди нет | sweeper вернул `queued` и пустой `published_at`, затем тот же id ready | evidence/level4.txt | +| Остановка после записи объекта и до ack | fault `exit-after-put`, id `78f62eb7-771d-4cf4-90a3-923e757aa462` | worker умер после put, повторная доставка довела тот же id до ready, строк вариантов 3 | evidence/level4.txt | +| Backoff и временная/постоянная ошибка | `transient-once` id `5da2a975-9ccd-4a85-8bd9-c593e00f7b3b`; `permanent-once` id `6d4bdc1d-d6d1-4ecd-a920-0459adfebcf2` | в логе worker есть `will retry in …s`; постоянная ошибка сразу `failed` / `invalid_image`, без серии backoff | evidence/level4.txt | +| DLQ и реестр failed | `rabbitmqctl list_queues` и `attachment_job_failures` | код `invalid_image` в таблице; `attachment.jobs.dlq` = 2 (эта попытка и предыдущая на том же volume) | evidence/level4.txt | +| Безопасный replay | `python -m app.replay` дважды для `6d4bdc1d-d6d1-4ecd-a920-0459adfebcf2` | первый ответ `requeued`, вложение стало ready; второй `already_ready`, строк вариантов по-прежнему 3 | evidence/level4.txt | +| Staging после фиксации | проверка `staging_key = object_key` в том же скрипте | для каждого ready из демо равенство стало истинным | evidence/level4.txt | +| Трек 5 | не запускался | нет измерений throughput, lag, RSS и нет versioned pipeline | раздел ниже | -TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены. +Повтор сценария: `docker compose --env-file .env exec -T api python -m app.fault arm pause-outbox`, затем upload, затем `python -m app.fault clear`. Имена кранов: `pause-outbox`, `commit-before-publish`, `exit-after-put`, `transient-once`, `permanent-once`. После защиты кран должен быть пуст: `python -m app.fault status` печатает `none`. ## Эксперименты и отказы -TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения. +Нагрузочный профиль, RPS и перцентили очереди сюда не входят: это был бы трек 5, он не делался. | Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных | | --- | --- | --- | --- | -| TODO | TODO | TODO | TODO | +| Пауза outbox | 202, job не в брокере, затем сама доходит до ready | id `1ebba94c-516f-4007-8c47-d240db28de5f`, `published_at` пустой, потом ready и 3 варианта | внутри лимита скрипта 60 с на ready; байты оригинала на месте | +| `os._exit` API после commit и до publish | реплика перезапускается, та же строка становится ready | RestartCount вырос, id `1fabbbaa-3b68-45da-bbf3-deca86ac8e82` дошёл до ready | вторая реплика продолжала принимать трафик; новая job не создавалась | +| Lease в прошлом при status processing | строка снова queued и потом ready | id `cd637725-a1e2-463a-99c3-49d6f126525d` | секунды до reclaim, затем ready | +| Worker убит после put и до ack | повтор пишет те же ключи | id `78f62eb7-771d-4cf4-90a3-923e757aa462`, вариантов 3 | worker поднялся политикой restart, сообщение вернулось в очередь | +| Постоянная ошибка и replay | failed, DLQ, повтор не плодит варианты, второй replay ничего не исполняет | id `6d4bdc1d-d6d1-4ecd-a920-0459adfebcf2` | ready после первого replay; второй — `already_ready` | +| Временная ошибка | одна отложенная попытка и затем ready | id `5da2a975-9ccd-4a85-8bd9-c593e00f7b3b`, в логе есть delay | ready, вариантов 3 | + +## Трек 5 + +Не начат. Этот отчёт закрывает оценку 4. Сюда позже кладётся один законченный трек из README (очередь под перегрузкой или доказанная идемпотентность pipeline): гипотеза, методика, сырые цифры, ограничения. Таблицу критериев выше из-за этого переписывать не нужно, достаточно добавить строку. + +| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных | +| --- | --- | --- | --- | +| TODO трек 5 | TODO | TODO | TODO | ## Ограничения и следующие шаги -TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза. +- Доставка at least once. Повтор идемпотентен по ключу варианта, это не exactly-once. +- `runs` ограничивает цикл «процесс умер до ack». Обычный retry с backoff считает `attempt` и сбрасывает `runs`. +- Если процесс убит OOM посреди decode, попытка сгорает так же, как crash до ack. Отдельного RSS-профиля нет. +- Replay после `STAGING_RETENTION_SECONDS` может не найти исходник, если финальный объект так и не был скопирован. +- DLQ не вычитывается автоматически. Повтор успешной job туда не добавляет второй прогон. +- Краны `lab_faults` учебные. В обычном запуске таблица пустая. +- Трек 5 (нагрузка или versioned pipeline) не реализован. diff --git a/app/broker.py b/app/broker.py index def2b811..0e714893 100644 --- a/app/broker.py +++ b/app/broker.py @@ -1,10 +1,11 @@ -"""Durable RabbitMQ queue. Publish waits for a broker confirm; the worker acks later.""" +"""Durable RabbitMQ queues. Publish waits for a broker confirm; the worker acks later.""" +import asyncio import logging import aio_pika from aio_pika import DeliveryMode, Message -from .jobs import QUEUE, QUEUE_ARGUMENTS +from .jobs import DLQ, DLQ_ARGUMENTS, QUEUE, QUEUE_ARGUMENTS logger = logging.getLogger('messenger') @@ -18,13 +19,19 @@ class Broker: self._url = url self._connection: aio_pika.abc.AbstractRobustConnection | None = None self.channel: aio_pika.abc.AbstractChannel | None = None + self._publish_lock = asyncio.Lock() + + async def _declare(self, channel: aio_pika.abc.AbstractChannel) -> aio_pika.abc.AbstractQueue: + await channel.declare_queue(DLQ, durable=True, arguments=DLQ_ARGUMENTS) + return await channel.declare_queue(QUEUE, durable=True, arguments=QUEUE_ARGUMENTS) 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. + # Consume uses a second channel so acks and confirms do not share one multiplexer. self.channel = await self._connection.channel(publisher_confirms=True, on_return_raises=True) - await self.channel.declare_queue(QUEUE, durable=True, arguments=QUEUE_ARGUMENTS) + await self._declare(self.channel) except Exception: raise RuntimeError('broker did not become reachable') from None @@ -37,22 +44,33 @@ class Broker: 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: + async def open_consumer(self, prefetch: int): + """A channel that only consumes. prefetch caps how many jobs sit unacked.""" + if self._connection 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, + channel = await self._connection.channel() + await channel.set_qos(prefetch_count=prefetch) + queue = await self._declare(channel) + return channel, queue + + async def publish(self, body: bytes, queue: str = QUEUE, headers: dict | None = None) -> None: + """Persistent message. Returns after the broker confirms it, or raises BrokerDown.""" + async with self._publish_lock: + if self.channel is None: + raise BrokerDown() + message = Message( + body, + content_type='application/json', + delivery_mode=DeliveryMode.PERSISTENT, + headers=headers, ) - except Exception as exc: - logger.warning('broker did not confirm a job (%s)', type(exc).__name__) - raise BrokerDown() from None + 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 adccc7aa..aafe153e 100644 --- a/app/config.py +++ b/app/config.py @@ -102,6 +102,38 @@ def worker_concurrency() -> int: return _bounded_int('WORKER_CONCURRENCY', 1, 8) +def _bounded_float(name: str, default: float, upper: float) -> float: + raw = os.getenv(name, '').strip() + try: + value = float(raw) if raw else default + except ValueError: + raise RuntimeError('%s must be a number' % name) from None + if value <= 0 or value > upper: + raise RuntimeError('%s must be greater than 0 and at most %s' % (name, upper)) + return value + + +def retry_base_seconds() -> float: + return _bounded_float('JOB_RETRY_BASE_SECONDS', 0.5, 60) + + +def retry_cap_seconds() -> float: + return _bounded_float('JOB_RETRY_CAP_SECONDS', 30, 600) + + +def job_lease_seconds() -> int: + return _bounded_int('JOB_LEASE_SECONDS', 90, 3600) + + +def effective_lease_seconds() -> int: + """A live attempt refreshes this. It stays longer than the processing timeout.""" + return max(job_lease_seconds(), job_timeout_seconds() + 30) + + +def staging_retention_seconds() -> int: + return _bounded_int('STAGING_RETENTION_SECONDS', 86400, 86400 * 30) + + 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/fault.py b/app/fault.py new file mode 100644 index 00000000..98a7a8d8 --- /dev/null +++ b/app/fault.py @@ -0,0 +1,117 @@ +"""Operator faults stored in Postgres so every replica sees the same switch. + +Armed only from `python -m app.fault`. An empty table changes nothing. +""" +import asyncio +import logging +import sys + +import asyncpg + +ONE_SHOT = frozenset({ + 'commit-before-publish', + 'exit-after-put', + 'transient-once', + 'permanent-once', +}) +HELD = frozenset({'pause-outbox'}) +NAMES = ONE_SHOT | HELD + +_PAUSE = 'pause-outbox' + + +async def fault_armed(conn: asyncpg.Connection, name: str = _PAUSE) -> bool: + found = await conn.fetchval('SELECT 1 FROM lab_faults WHERE name = $1', name) + return found is not None + + +async def consume_fault(pool: asyncpg.Pool, name: str) -> bool: + """Delete a one-shot fault. True only for the caller that won the row.""" + if name not in ONE_SHOT: + raise ValueError(name) + async with pool.acquire() as conn: + row = await conn.fetchrow( + 'DELETE FROM lab_faults WHERE name = $1 RETURNING name', + name, + ) + return row is not None + + +async def _arm(pool: asyncpg.Pool, name: str) -> None: + async with pool.acquire() as conn: + await conn.execute( + ''' + INSERT INTO lab_faults (name, armed_at) + VALUES ($1, clock_timestamp()) + ON CONFLICT (name) DO UPDATE SET armed_at = EXCLUDED.armed_at + ''', + name, + ) + + +async def _clear(pool: asyncpg.Pool, name: str | None) -> None: + async with pool.acquire() as conn: + if name is None: + await conn.execute('DELETE FROM lab_faults') + else: + await conn.execute('DELETE FROM lab_faults WHERE name = $1', name) + + +async def _status(pool: asyncpg.Pool) -> list[str]: + async with pool.acquire() as conn: + rows = await conn.fetch('SELECT name FROM lab_faults ORDER BY name') + return [row['name'] for row in rows] + + +def _usage() -> None: + print('usage: python -m app.fault arm NAME | clear [NAME] | status', file=sys.stderr) + + +async def _main(argv: list[str]) -> int: + from .config import load_settings + from .db import open_pool + + if not argv or argv[0] not in ('arm', 'clear', 'status'): + _usage() + return 2 + name = argv[1] if len(argv) > 1 else None + if argv[0] == 'arm' and (name not in NAMES or len(argv) != 2): + _usage() + return 2 + if argv[0] == 'clear' and len(argv) > 2: + _usage() + return 2 + if argv[0] == 'clear' and name is not None and name not in NAMES: + _usage() + return 2 + if argv[0] == 'status' and len(argv) != 1: + _usage() + return 2 + pool = await open_pool(load_settings().database_url) + try: + if argv[0] == 'arm': + await _arm(pool, name) + print('armed %s' % name) + elif argv[0] == 'clear': + await _clear(pool, name) + print('cleared %s' % (name or 'all')) + else: + names = await _status(pool) + print('\n'.join(names) if names else 'none') + finally: + await pool.close() + return 0 + + +def main() -> None: + logging.basicConfig(level=logging.WARNING, format='%(levelname)s %(message)s') + try: + code = asyncio.run(_main(sys.argv[1:])) + except Exception as exc: + print('fault command failed (%s)' % type(exc).__name__, file=sys.stderr) + raise SystemExit(1) from None + raise SystemExit(code) + + +if __name__ == '__main__': + main() diff --git a/app/jobs.py b/app/jobs.py index fd0be86c..6ea535fc 100644 --- a/app/jobs.py +++ b/app/jobs.py @@ -1,13 +1,19 @@ """Job payload for the broker. Bytes and credentials never go into the message.""" import json +import random import re +import uuid +from datetime import datetime, timezone from typing import Optional JOB_TYPE = 'attachment.process.v1' PIPELINE_VERSION = 1 QUEUE = 'attachment.jobs' +DLQ = 'attachment.jobs.dlq' # Same arguments on every declare, otherwise RabbitMQ rejects the second one. QUEUE_ARGUMENTS = {'x-queue-type': 'classic'} +DLQ_ARGUMENTS = {'x-queue-type': 'classic'} +REQUIRED_VARIANTS = ('thumbnail', 'crop', 'optimized') _UUID = re.compile(r'^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$') @@ -36,6 +42,35 @@ def variant_key(attachment_id: str, name: str) -> str: return 'variants/' + attachment_id + '/' + name +def lock_key(attachment_id: uuid.UUID) -> int: + """Stable bigint for a session advisory lock. One attachment, one runner.""" + return attachment_id.int & ((1 << 63) - 1) + + +def format_timestamp(moment: datetime) -> str: + if moment.tzinfo is None: + moment = moment.replace(tzinfo=timezone.utc) + text = moment.astimezone(timezone.utc).isoformat(timespec='microseconds').replace('+00:00', 'Z') + if not text.endswith('Z') or len(text) > 40: + raise ValueError('timestamp does not fit the job contract') + return text + + +def backoff_seconds(attempt: int, base: float, cap: float, rng: Optional[random.Random] = None) -> float: + """Full jitter. The ceiling is min(cap, base * 2^(attempt-1)); the draw is uniform below it.""" + step = attempt - 1 + if step < 0: + step = 0 + if step > 20: + step = 20 + ceiling = min(cap, base * float(2 ** step)) + if ceiling <= 0: + return 0.0 + if rng is None: + return random.uniform(0, ceiling) + return rng.uniform(0, ceiling) + + def dump_job(job_id: str, attachment_id: str, attempt: int, created_at: str) -> bytes: payload = { 'schema_version': 1, diff --git a/app/main.py b/app/main.py index 8679db5a..ea4736fc 100644 --- a/app/main.py +++ b/app/main.py @@ -1,8 +1,9 @@ +import asyncio import json import logging import re import uuid -from contextlib import asynccontextmanager +from contextlib import asynccontextmanager, suppress from pathlib import Path from fastapi import FastAPI, Request @@ -15,6 +16,7 @@ from .config import load_broker_url, load_object_settings, load_settings from .db import open_pool from .errors import ApiError from .objects import ObjectStore +from .outbox import relay_forever from .routes import router from .store import Store @@ -64,6 +66,8 @@ async def lifespan(app: FastAPI): logging.getLogger('aiormq').setLevel(logging.ERROR) pool = await open_pool(settings.database_url) broker = Broker(load_broker_url()) + stop_relay = asyncio.Event() + relay = None try: await broker.connect() app.state.broker = broker @@ -73,9 +77,15 @@ async def lifespan(app: FastAPI): settings.idempotency_ttl_seconds, objects=ObjectStore(load_object_settings()), ) + relay = asyncio.create_task(relay_forever(pool, broker, stop_relay)) logger.info('instance %s started', settings.instance_id) yield finally: + stop_relay.set() + if relay is not None: + relay.cancel() + with suppress(asyncio.CancelledError): + await relay await broker.close() await pool.close() diff --git a/app/outbox.py b/app/outbox.py new file mode 100644 index 00000000..2f2cc3af --- /dev/null +++ b/app/outbox.py @@ -0,0 +1,165 @@ +"""Publish job rows that Postgres has committed and the broker has not confirmed yet. + +published_at moves only after the confirm. A crash in between leaves the same row, +and the next pass of this relay sends it. The body is ids and timestamps only. +""" +import asyncio +import logging +import uuid +from datetime import datetime, timedelta, timezone + +import asyncpg + +from .broker import Broker, BrokerDown +from .fault import fault_armed +from .jobs import QUEUE, dump_job, format_timestamp, lock_key + +logger = logging.getLogger('messenger') + +_PAUSE = 'pause-outbox' + + +def _body(row) -> bytes: + return dump_job( + str(row['id']), + str(row['attachment_id']), + int(row['attempt']), + format_timestamp(row['created_at']), + ) + + +async def publish_job(pool: asyncpg.Pool, broker: Broker, job_id: str) -> None: + """Confirm one committed job. BrokerDown leaves published_at null for the relay.""" + async with pool.acquire() as conn: + async with conn.transaction(): + if await fault_armed(conn, _PAUSE): + return + row = await conn.fetchrow( + ''' + SELECT j.id, j.attachment_id, j.attempt, j.created_at + FROM attachment_jobs j + JOIN attachments a ON a.id = j.attachment_id + WHERE j.id = $1 AND j.published_at IS NULL AND a.status = 'queued' + FOR UPDATE OF j + ''', + uuid.UUID(job_id), + ) + if row is None: + return + await broker.publish(_body(row), QUEUE) + await conn.execute( + ''' + UPDATE attachment_jobs + SET published_at = clock_timestamp(), updated_at = clock_timestamp() + WHERE id = $1 + ''', + row['id'], + ) + + +async def publish_pending(pool: asyncpg.Pool, broker: Broker, batch: int = 8) -> int: + """Send due, unpublished queued jobs. Skip-locked so replicas do not double-send.""" + sent = 0 + for _ in range(batch): + try: + async with pool.acquire() as conn: + async with conn.transaction(): + if await fault_armed(conn, _PAUSE): + return sent + row = await conn.fetchrow( + ''' + SELECT j.id, j.attachment_id, j.attempt, j.created_at + FROM attachment_jobs j + JOIN attachments a ON a.id = j.attachment_id + WHERE j.published_at IS NULL + AND a.status = 'queued' + AND (j.available_at IS NULL OR j.available_at <= clock_timestamp()) + ORDER BY j.created_at + FOR UPDATE OF j SKIP LOCKED + LIMIT 1 + ''' + ) + if row is None: + return sent + await broker.publish(_body(row), QUEUE) + await conn.execute( + ''' + UPDATE attachment_jobs + SET published_at = clock_timestamp(), updated_at = clock_timestamp() + WHERE id = $1 + ''', + row['id'], + ) + except BrokerDown: + return sent + sent += 1 + logger.info('outbox published job %s', row['id']) + return sent + + +async def reclaim_expired(pool: asyncpg.Pool) -> int: + """Return processing rows whose lease expired and whose worker no longer holds the lock. + + The attempt number stays. The next entry increments runs, which caps a crash loop. + A worker that is still inside the advisory lock is left alone. + """ + reclaimed = 0 + async with pool.acquire() as conn: + async with conn.transaction(): + rows = await conn.fetch( + ''' + SELECT j.id, j.attachment_id + FROM attachment_jobs j + JOIN attachments a ON a.id = j.attachment_id + WHERE a.status = 'processing' + AND j.lease_until IS NOT NULL + AND j.lease_until < clock_timestamp() + ORDER BY j.lease_until + FOR UPDATE OF j SKIP LOCKED + LIMIT 8 + ''' + ) + for row in rows: + key = lock_key(row['attachment_id']) + if not await conn.fetchval('SELECT pg_try_advisory_lock($1)', key): + continue + try: + await conn.execute( + ''' + UPDATE attachments + SET status = 'queued', error_code = NULL, updated_at = clock_timestamp() + WHERE id = $1 AND status = 'processing' + ''', + row['attachment_id'], + ) + await conn.execute( + ''' + UPDATE attachment_jobs + SET published_at = NULL, lease_until = NULL, available_at = NULL, + updated_at = clock_timestamp() + WHERE id = $1 + ''', + row['id'], + ) + reclaimed += 1 + finally: + await conn.execute('SELECT pg_advisory_unlock($1)', key) + if reclaimed: + logger.info('reclaimed %s expired processing lease(s)', reclaimed) + return reclaimed + + +async def relay_forever(pool: asyncpg.Pool, broker: Broker, stop: asyncio.Event) -> None: + while not stop.is_set(): + try: + await publish_pending(pool, broker) + except Exception: + logger.exception('outbox relay failed') + try: + await asyncio.wait_for(stop.wait(), timeout=1) + except asyncio.TimeoutError: + pass + + +def due_at(delay_seconds: float) -> datetime: + return datetime.now(timezone.utc) + timedelta(seconds=delay_seconds) diff --git a/app/replay.py b/app/replay.py new file mode 100644 index 00000000..b68ef174 --- /dev/null +++ b/app/replay.py @@ -0,0 +1,130 @@ +"""Explicit replay of a failed attachment job. + +A ready job is recorded and left alone: replay does not run the pipeline again. +Queued and processing jobs are left to the worker that already owns them. +""" +import asyncio +import logging +import sys +import uuid + +from .broker import Broker, BrokerDown +from .config import load_broker_url, load_settings +from .db import open_pool +from .jobs import PIPELINE_VERSION +from .outbox import publish_job + + +def _parse_id(value: str) -> uuid.UUID: + try: + parsed = uuid.UUID(value) + except ValueError: + raise SystemExit(2) from None + if str(parsed) != value.lower(): + raise SystemExit(2) + return parsed + + +async def _decide(pool, attachment_id: uuid.UUID) -> tuple[str, str | None]: + async with pool.acquire() as conn: + async with conn.transaction(): + row = await conn.fetchrow( + ''' + SELECT a.status, j.id AS job_id + FROM attachments a + JOIN attachment_jobs j + ON j.attachment_id = a.id AND j.pipeline_version = $2 + WHERE a.id = $1 + FOR UPDATE + ''', + attachment_id, + PIPELINE_VERSION, + ) + if row is None: + return 'missing', None + job_id = row['job_id'] + if row['status'] == 'ready': + outcome = 'already_ready' + elif row['status'] != 'failed': + outcome = 'not_failed' + else: + outcome = 'requeued' + await conn.execute( + ''' + UPDATE attachment_jobs + SET attempt = 1, + runs = 0, + lease_until = NULL, + available_at = NULL, + published_at = NULL, + last_error = NULL, + updated_at = clock_timestamp() + WHERE id = $1 + ''', + job_id, + ) + await conn.execute( + ''' + UPDATE attachments + SET status = 'queued', error_code = NULL, updated_at = clock_timestamp() + WHERE id = $1 AND status = 'failed' + ''', + attachment_id, + ) + await conn.execute( + ''' + INSERT INTO attachment_job_replays (id, job_id, attachment_id, outcome, created_at) + VALUES ($1, $2, $3, $4, clock_timestamp()) + ''', + uuid.uuid4(), + job_id, + attachment_id, + outcome, + ) + return outcome, str(job_id) + + +async def _main(attachment_id: uuid.UUID) -> int: + pool = await open_pool(load_settings().database_url) + broker = None + try: + outcome, job_id = await _decide(pool, attachment_id) + if outcome == 'missing': + print('missing') + return 1 + if outcome == 'requeued' and job_id is not None: + try: + broker = Broker(load_broker_url()) + await broker.connect() + await publish_job(pool, broker, job_id) + except (BrokerDown, RuntimeError): + print('requeued %s outbox' % attachment_id) + return 0 + print('%s %s' % (outcome, attachment_id)) + return 0 + finally: + if broker is not None: + await broker.close() + await pool.close() + + +def main() -> None: + logging.basicConfig(level=logging.WARNING, format='%(levelname)s %(message)s') + logging.getLogger('aio_pika').setLevel(logging.ERROR) + logging.getLogger('aiormq').setLevel(logging.ERROR) + if len(sys.argv) != 2: + print('usage: python -m app.replay ATTACHMENT_ID', file=sys.stderr) + raise SystemExit(2) + try: + attachment_id = _parse_id(sys.argv[1]) + code = asyncio.run(_main(attachment_id)) + except SystemExit: + raise + except Exception as exc: + print('replay failed (%s)' % type(exc).__name__, file=sys.stderr) + raise SystemExit(1) from None + raise SystemExit(code) + + +if __name__ == '__main__': + main() diff --git a/app/routes.py b/app/routes.py index d8d8ab2e..25331220 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,5 +1,7 @@ import hashlib import json +import logging +import os import re import tempfile import uuid @@ -12,6 +14,8 @@ from starlette.responses import Response from .auth import BASIC_CHALLENGE, BEARER_CHALLENGE, parse_basic, parse_bearer from .broker import BrokerDown +from .fault import consume_fault +from .outbox import publish_job from .drain import draining from .errors import ( conflict, @@ -31,6 +35,8 @@ from .store import Chat, Store, User # The original is never persisted on the API volume; the spool dies with the request. _SPOOL_RAM = 64 * 1024 +logger = logging.getLogger('messenger') + router = APIRouter() Body = TypeVar('Body', bound=BaseModel) @@ -293,12 +299,15 @@ async def upload_attachment( finally: if spool is not None: spool.close() - # The row is committed. 202 follows only a broker confirm, so a stopped API keeps the job. + # The row is committed. A crash before the confirm leaves it for the outbox relay. + if await consume_fault(store.pool, 'commit-before-publish'): + logger.warning('fault commit-before-publish: exiting before publish of %s', queued.attachment.id) + logging.shutdown() + os._exit(75) try: - await request.app.state.broker.publish(queued.body) + await publish_job(store.pool, request.app.state.broker, queued.job_id) except BrokerDown: - await store.abandon_upload(queued.attachment.id) - raise unavailable('Очередь недоступна') from None + logger.warning('upload %s is committed and waits in the outbox', queued.attachment.id) return JSONResponse(queued.attachment.to_dict(), status_code=202) diff --git a/app/selfcheck.py b/app/selfcheck.py new file mode 100644 index 00000000..26290d95 --- /dev/null +++ b/app/selfcheck.py @@ -0,0 +1,101 @@ +"""Offline checks for variant geometry and retry delay. No database and no broker.""" +import io +import random +import sys + +from PIL import Image + +from .jobs import REQUIRED_VARIANTS, backoff_seconds +from .thumbnail import ( + CROP_SIDE, + OPTIMIZED_WEBP_QUALITY, + THUMBNAIL_BOX, + ImageRejected, + render_variants, +) + + +def _png(width: int, height: int, mode: str = 'RGB') -> bytes: + color = (20, 40, 60, 128) if mode == 'RGBA' else (20, 40, 60) + image = Image.new(mode, (width, height), color) + buffer = io.BytesIO() + image.save(buffer, format='PNG') + image.close() + return buffer.getvalue() + + +def _jpeg_oriented(width: int, height: int) -> bytes: + image = Image.new('RGB', (width, height), (10, 20, 30)) + exif = Image.Exif() + exif[274] = 6 + buffer = io.BytesIO() + image.save(buffer, format='JPEG', quality=90, exif=exif.tobytes()) + image.close() + return buffer.getvalue() + + +def _expect(name: str, item: dict, width: int, height: int, content_type: str) -> None: + if item['width'] != width or item['height'] != height or item['content_type'] != content_type: + raise SystemExit('%s: got %s %sx%s' % (name, item['content_type'], item['width'], item['height'])) + opened = Image.open(io.BytesIO(item['data'])) + try: + if opened.size != (width, height): + raise SystemExit('%s pixels %s' % (name, opened.size)) + if content_type == 'image/webp' and list(opened.getexif()): + raise SystemExit('optimized still carries EXIF') + finally: + opened.close() + + +def _check_image(data: bytes, thumb: tuple, optimized: tuple) -> None: + rendered = render_variants(data) + if tuple(rendered) != REQUIRED_VARIANTS: + raise SystemExit('variant set %s' % (tuple(rendered),)) + _expect('thumbnail', rendered['thumbnail'], thumb[0], thumb[1], 'image/jpeg') + _expect('crop', rendered['crop'], CROP_SIDE, CROP_SIDE, 'image/jpeg') + _expect('optimized', rendered['optimized'], optimized[0], optimized[1], 'image/webp') + if rendered['optimized']['data'][:4] != b'RIFF' or rendered['optimized']['data'][8:12] != b'WEBP': + raise SystemExit('optimized is not WebP') + + +def _check_backoff() -> None: + rng = random.Random(0) + for attempt in range(1, 8): + ceiling = min(30.0, 0.5 * float(2 ** (attempt - 1))) + delay = backoff_seconds(attempt, 0.5, 30.0, rng) + if delay < 0 or delay > ceiling: + raise SystemExit('backoff attempt %s delay %s ceiling %s' % (attempt, delay, ceiling)) + if backoff_seconds(1, 0.5, 0.1, random.Random(1)) > 0.1: + raise SystemExit('backoff ignored the cap') + + +def main() -> None: + _check_image(_png(320, 200), (THUMBNAIL_BOX, 160), (320, 200)) + _check_image(_png(64, 40), (64, 40), (64, 40)) + _check_image(_png(10, 10, 'RGBA'), (10, 10), (10, 10)) + _check_image(_jpeg_oriented(320, 200), (160, THUMBNAIL_BOX), (200, 320)) + _check_backoff() + try: + render_variants(b'not an image') + except ImageRejected: + pass + else: + raise SystemExit('invalid image was accepted') + try: + render_variants(b'\x89PNG\r\n\x1a\n' + b'0' * (10_485_760)) + except ImageRejected: + pass + else: + raise SystemExit('oversized image was accepted') + if OPTIMIZED_WEBP_QUALITY != 80: + raise SystemExit('webp quality changed') + print('PASS: thumbnail 256, crop 128, webp 1280-box, exif stripped, backoff capped') + + +if __name__ == '__main__': + try: + main() + except SystemExit as exc: + if exc.code not in (0, None): + print(exc, file=sys.stderr) + raise diff --git a/app/store.py b/app/store.py index aa93ad0d..76f6b9ef 100644 --- a/app/store.py +++ b/app/store.py @@ -13,7 +13,7 @@ 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 .jobs import PIPELINE_VERSION, original_key, staging_key from .migrate import expected_versions from .objects import MissingObject, ObjectStore, StorageError from .pagination import Key @@ -129,7 +129,7 @@ class Attachment: @dataclass(frozen=True) class QueuedUpload: attachment: Attachment - body: bytes + job_id: str @dataclass(frozen=True) @@ -200,6 +200,10 @@ class Store: self._last_moment: Optional[datetime] = None self._migrations = expected_versions() + @property + def pool(self) -> asyncpg.Pool: + return self._pool + def _now(self) -> datetime: """Strictly increasing within one process; across replicas order relies on the shared host clock.""" with self._lock: @@ -426,9 +430,8 @@ class Store: owner_uuid = _as_uuid(owner_id, 'Некорректный user_id') attachment_id = uuid.uuid4() 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. + # filename is never a storage key. Bytes go to staging/ first. The job row is the + # outbox: 202 follows this commit, and a missing broker confirm is retried from the row. staged = staging_key(str(attachment_id)) final = original_key(str(attachment_id)) created = self._now() @@ -489,39 +492,7 @@ 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) + return QueuedUpload(attachment, str(job_id)) async def attachment_index(self) -> List[AttachmentRef]: """Every attachment row. `in_use` means a message still points at it. diff --git a/app/thumbnail.py b/app/thumbnail.py index ead02fad..dde69433 100644 --- a/app/thumbnail.py +++ b/app/thumbnail.py @@ -1,14 +1,32 @@ -"""JPEG thumbnail for pipeline v1. Crop and WebP belong to the next grade.""" +"""Derivatives for pipeline v1. + +thumbnail: JPEG quality 85, fit inside 256×256, never upscaled, EXIF orientation applied, +alpha composited on white. 320×200 becomes 256×160. + +crop: JPEG quality 85, centered square resized to 128×128. Sources smaller than 128 px +are scaled up. Orientation and alpha match the thumbnail. + +optimized: WebP quality 80, encoder method 4, fit inside 1280×1280, never upscaled. +EXIF is not written. A small source is not promised to get smaller. + +Bytes are capped at 10 MiB and pixels at 40 million before decode. The worker container +memory limit is the hard cap around that. +""" import io -from typing import Tuple +from typing import Dict, Tuple from PIL import Image, ImageOps, UnidentifiedImageError -from .images import MAX_IMAGE_PIXELS +from .errors import ApiError +from .images import MAX_IMAGE_PIXELS, MAX_UPLOAD_BYTES, inspect_image THUMBNAIL_BOX = 256 -# Pillow's default 75 is fine for a preview; the contract only fixes the pixel size. -_JPEG_QUALITY = 85 +THUMBNAIL_JPEG_QUALITY = 85 +CROP_SIDE = 128 +CROP_JPEG_QUALITY = 85 +OPTIMIZED_BOX = 1280 +OPTIMIZED_WEBP_QUALITY = 80 +OPTIMIZED_WEBP_METHOD = 4 class ImageRejected(Exception): @@ -36,29 +54,102 @@ def _on_white(image: Image.Image) -> Image.Image: return background -def make_thumbnail(data: bytes) -> Tuple[bytes, int, int]: - """Return JPEG bytes and the size actually written. 320×200 becomes 256×160.""" +def _encode(image: Image.Image, fmt: str, **options) -> bytes: + """Save a metadata-free copy. The caller's image is left open.""" + bare = Image.frombytes(image.mode, image.size, image.tobytes()) + try: + buffer = io.BytesIO() + bare.save(buffer, format=fmt, **options) + return buffer.getvalue() + finally: + bare.close() + + +def _fitted(base: Image.Image, box: int) -> Tuple[Image.Image, int, int]: + width, height = _fit(base.width, base.height, box) + if (width, height) == base.size: + return base, width, height + return base.resize((width, height), Image.Resampling.LANCZOS), width, height + + +def _jpeg_box(base: Image.Image, box: int, quality: int) -> Dict[str, object]: + image, width, height = _fitted(base, box) + try: + blob = _encode(image, 'JPEG', quality=quality) + finally: + if image is not base: + image.close() + return {'content_type': 'image/jpeg', 'width': width, 'height': height, 'data': blob} + + +def _crop(base: Image.Image) -> Dict[str, object]: + side = min(base.width, base.height) + left = (base.width - side) // 2 + top = (base.height - side) // 2 + square = base if side == base.width and side == base.height else base.crop((left, top, left + side, top + side)) + try: + sized = square if square.size == (CROP_SIDE, CROP_SIDE) else square.resize( + (CROP_SIDE, CROP_SIDE), Image.Resampling.LANCZOS + ) + try: + blob = _encode(sized, 'JPEG', quality=CROP_JPEG_QUALITY) + finally: + if sized is not square: + sized.close() + finally: + if square is not base: + square.close() + return {'content_type': 'image/jpeg', 'width': CROP_SIDE, 'height': CROP_SIDE, 'data': blob} + + +def _webp(base: Image.Image) -> Dict[str, object]: + image, width, height = _fitted(base, OPTIMIZED_BOX) + try: + blob = _encode(image, 'WEBP', quality=OPTIMIZED_WEBP_QUALITY, method=OPTIMIZED_WEBP_METHOD) + finally: + if image is not base: + image.close() + return {'content_type': 'image/webp', 'width': width, 'height': height, 'data': blob} + + +def render_variants(data: bytes) -> Dict[str, Dict[str, object]]: + """Decode once and return thumbnail, crop and optimized. Raises ImageRejected.""" + if len(data) > MAX_UPLOAD_BYTES: + raise ImageRejected() + try: + inspect_image(data) + except ApiError: + raise ImageRejected() from None Image.MAX_IMAGE_PIXELS = MAX_IMAGE_PIXELS source = Image.open(io.BytesIO(data)) + owned = [source] try: oriented = ImageOps.exif_transpose(source) if oriented is not source: - source.close() + owned.append(oriented) 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] + base = _on_white(source) + if base is not source: + owned.append(base) + return { + 'thumbnail': _jpeg_box(base, THUMBNAIL_BOX, THUMBNAIL_JPEG_QUALITY), + 'crop': _crop(base), + 'optimized': _webp(base), + } except ImageRejected: raise - except (UnidentifiedImageError, Image.DecompressionBombError, OSError, ValueError): + except (UnidentifiedImageError, Image.DecompressionBombError, OSError, ValueError, MemoryError): raise ImageRejected() from None finally: - source.close() + for image in owned: + image.close() + + +def make_thumbnail(data: bytes) -> Tuple[bytes, int, int]: + """JPEG thumbnail bytes and the size actually written. 320×200 becomes 256×160.""" + item = render_variants(data)['thumbnail'] + return item['data'], int(item['width']), int(item['height']) diff --git a/app/worker.py b/app/worker.py index 03516122..57d72504 100644 --- a/app/worker.py +++ b/app/worker.py @@ -1,46 +1,59 @@ -"""Separate process: copy the staged original and write one thumbnail. +"""Separate process: publish the staged original and the level-4 variants. -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. +Ack happens only after the ready row is committed. A kill after the object put and +before ack redelivers the same job id; variant primary keys keep a single set. +Staging is removed only after that commit. Failed staging stays until retention so +an operator can still replay. """ import asyncio import hashlib import logging +import os import signal import uuid -from datetime import datetime, timezone +from datetime import datetime, timedelta, 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 .config import ( + effective_lease_seconds, + job_max_attempts, + job_timeout_seconds, + load_broker_url, + load_object_settings, + load_settings, + retry_base_seconds, + retry_cap_seconds, + staging_retention_seconds, + worker_concurrency, +) +from .fault import consume_fault +from .jobs import ( + DLQ, + PIPELINE_VERSION, + REQUIRED_VARIANTS, + PermanentJobError, + TransientJobError, + backoff_seconds, + load_job, + lock_key, + variant_key, +) from .objects import MissingObject, ObjectStore, StorageError -from .thumbnail import ImageRejected, make_thumbnail +from .outbox import due_at, publish_pending, reclaim_expired +from .thumbnail import ImageRejected, render_variants logger = logging.getLogger('messenger') _HEARTBEAT = Path('/tmp/worker-alive') _inflight = 0 +_ACK_LOCK = asyncio.Lock() -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.""" +def _prepare(objects: ObjectStore, attachment_id: str, staging: str, final: str, size: int, digest: str, content_type: str) -> list: + """Copy the original unchanged and write every required variant. Runs off the event loop.""" try: data = objects.get(staging) except MissingObject: @@ -55,119 +68,228 @@ def _prepare( except StorageError: raise TransientJobError() from None try: - jpeg, width, height = make_thumbnail(data) + rendered = render_variants(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(), - } + except MemoryError: + raise PermanentJobError('invalid_image') from None + if set(rendered) != set(REQUIRED_VARIANTS): + raise PermanentJobError('processing_failed') + stored = [] + for name in REQUIRED_VARIANTS: + item = rendered[name] + key = variant_key(attachment_id, name) + blob = item['data'] + try: + objects.put(key, blob, str(item['content_type'])) + except StorageError: + raise TransientJobError() from None + stored.append({ + 'name': name, + 'content_type': item['content_type'], + 'object_key': key, + 'size_bytes': len(blob), + 'width': int(item['width']), + 'height': int(item['height']), + 'sha256': hashlib.sha256(blob).hexdigest(), + }) + return stored -async def _mark_failed(conn: asyncpg.Connection, attachment_id: uuid.UUID, code: str) -> None: - now = datetime.now(timezone.utc) +async def _record_failure(conn: asyncpg.Connection, job: dict, code: str, permanent: bool) -> None: + await conn.execute( + ''' + INSERT INTO attachment_job_failures (job_id, attempt, error_code, permanent, created_at) + VALUES ($1, $2, $3, $4, clock_timestamp()) + ON CONFLICT (job_id, attempt, error_code) DO NOTHING + ''', + uuid.UUID(job['job_id']), + job['attempt'], + code, + permanent, + ) + + +async def _fail(conn: asyncpg.Connection, broker: Broker, job: dict, attachment_id: uuid.UUID, code: str, permanent: bool) -> None: + """Terminal state plus the failure registry. The DLQ copy is best-effort after the commit.""" 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') - ''', + status = await conn.fetchval( + 'SELECT status FROM attachments WHERE id = $1 FOR UPDATE', 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: + if status == 'ready': return await conn.execute( ''' UPDATE attachments - SET status = 'queued', error_code = NULL, updated_at = $2 - WHERE id = $1 AND status IN ('queued', 'processing') + SET status = 'failed', error_code = $2, updated_at = clock_timestamp() + WHERE id = $1 AND status = 'processing' ''', attachment_id, - now, + code, ) - 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 _record_failure(conn, job, code, permanent) 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 + UPDATE attachment_jobs + SET lease_until = NULL, last_error = $2, updated_at = clock_timestamp() + WHERE id = $1 ''', - attachment_id, - PIPELINE_VERSION, - thumb['size_bytes'], - thumb['width'], - thumb['height'], - thumb['sha256'], - thumb['object_key'], + uuid.UUID(job['job_id']), + code, ) + try: + await broker.publish(dump_current(job), DLQ, {'x-error-code': code}) + except BrokerDown: + logger.warning('job %s recorded as %s; DLQ did not confirm', job['job_id'], code) + + +def dump_current(job: dict) -> bytes: + from .jobs import dump_job + + return dump_job(job['job_id'], job['attachment_id'], job['attempt'], job['created_at']) + + +async def _schedule_retry(conn: asyncpg.Connection, job: dict, attachment_id: uuid.UUID, limit: int, code: str) -> None: + """Park the next attempt in the outbox. The current delivery is acked by the caller.""" + nxt = job['attempt'] + 1 + if nxt > limit: + return False + delay = backoff_seconds(job['attempt'], retry_base_seconds(), retry_cap_seconds()) + async with conn.transaction(): + moved = await conn.fetchval( + ''' + UPDATE attachment_jobs + SET attempt = $2, + runs = 0, + available_at = $3, + published_at = NULL, + lease_until = NULL, + last_error = $4, + updated_at = clock_timestamp() + WHERE id = $1 AND attempt = $5 + RETURNING attempt + ''', + uuid.UUID(job['job_id']), + nxt, + due_at(delay), + code, + job['attempt'], + ) + if moved is None: + return True await conn.execute( ''' UPDATE attachments - SET status = 'ready', error_code = NULL, updated_at = $2 - WHERE id = $1 AND status IN ('queued', 'processing') + SET status = 'queued', error_code = NULL, updated_at = clock_timestamp() + WHERE id = $1 AND status = 'processing' ''', attachment_id, - now, ) + logger.info('attachment %s attempt %s will retry in %.3fs (%s)', job['attachment_id'], job['attempt'], delay, code) + return True -async def _process(pool: asyncpg.Pool, objects: ObjectStore, broker: Broker, job: dict, limit: int, timeout: int) -> None: +async def _finish(conn: asyncpg.Connection, attachment_id: uuid.UUID, job_id: uuid.UUID, variants: list) -> bool: + async with conn.transaction(): + status = await conn.fetchval( + 'SELECT status FROM attachments WHERE id = $1 FOR UPDATE', + attachment_id, + ) + if status != 'processing': + return False + for item in variants: + await conn.execute( + ''' + INSERT INTO attachment_variants ( + attachment_id, pipeline_version, name, content_type, size_bytes, + width, height, sha256, object_key + ) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) + 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, + item['name'], + item['content_type'], + item['size_bytes'], + item['width'], + item['height'], + item['sha256'], + item['object_key'], + ) + await conn.execute( + ''' + UPDATE attachments + SET status = 'ready', error_code = NULL, updated_at = clock_timestamp() + WHERE id = $1 AND status = 'processing' + ''', + attachment_id, + ) + await conn.execute( + ''' + UPDATE attachment_jobs + SET lease_until = NULL, last_error = NULL, updated_at = clock_timestamp() + WHERE id = $1 + ''', + job_id, + ) + return True + + +async def _drop_staging(conn: asyncpg.Connection, objects: ObjectStore, attachment_id: uuid.UUID, staging: str, final: str) -> None: + """Remove staging only after ready is committed and the final object is the copy.""" + if not staging or staging == final: + return + try: + await asyncio.to_thread(objects.delete, staging) + except StorageError: + logger.warning('staging left in place for %s', attachment_id) + return + await conn.execute( + ''' + UPDATE attachments + SET staging_key = object_key + WHERE id = $1 AND status = 'ready' AND staging_key = $2 + ''', + attachment_id, + staging, + ) + + +async def _beat_lease(pool: asyncpg.Pool, job_id: uuid.UUID, stop: asyncio.Event, lease_seconds: int) -> None: + interval = max(1.0, lease_seconds / 3) + while not stop.is_set(): + try: + async with pool.acquire() as conn: + await conn.execute( + ''' + UPDATE attachment_jobs + SET lease_until = $2 + WHERE id = $1 + ''', + job_id, + datetime.now(timezone.utc) + timedelta(seconds=lease_seconds), + ) + except Exception: + logger.warning('lease refresh failed') + try: + await asyncio.wait_for(stop.wait(), timeout=interval) + except asyncio.TimeoutError: + pass + + +async def _process(pool: asyncpg.Pool, objects: ObjectStore, broker: Broker, job: dict, lease_seconds: int, timeout: int) -> None: attachment_id = uuid.UUID(job['attachment_id']) + job_id = uuid.UUID(job['job_id']) async with pool.acquire() as conn: - await conn.execute('SELECT pg_advisory_lock($1)', _lock_key(attachment_id)) + await conn.execute('SELECT pg_advisory_lock($1)', lock_key(attachment_id)) try: row = await conn.fetchrow( ''' @@ -177,66 +299,129 @@ async def _process(pool: asyncpg.Pool, objects: ObjectStore, broker: Broker, job JOIN attachments a ON a.id = j.attachment_id WHERE j.id = $1 ''', - uuid.UUID(job['job_id']), + 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'])) + if job['attempt'] != row['attempt']: + # A newer attempt is already in the outbox, or this delivery is stale. 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, + lease_until = datetime.now(timezone.utc) + timedelta(seconds=lease_seconds) + async with conn.transaction(): + runs = await conn.fetchval( + ''' + UPDATE attachment_jobs + SET runs = runs + 1, lease_until = $2, updated_at = clock_timestamp() + WHERE id = $1 AND attempt = $3 + RETURNING runs + ''', + job_id, + lease_until, + job['attempt'], ) - except PermanentJobError as exc: - await _mark_failed(conn, attachment_id, exc.code) + if runs is None: + return + if runs > row['max_attempts']: + await conn.execute( + ''' + UPDATE attachments + SET status = 'failed', error_code = 'retry_exhausted', updated_at = clock_timestamp() + WHERE id = $1 AND status IN ('queued', 'processing') + ''', + attachment_id, + ) + await _record_failure(conn, job, 'retry_exhausted', True) + await conn.execute( + ''' + UPDATE attachment_jobs + SET lease_until = NULL, last_error = 'retry_exhausted', updated_at = clock_timestamp() + WHERE id = $1 + ''', + job_id, + ) + exhausted = True + else: + await conn.execute( + ''' + UPDATE attachments + SET status = 'processing', error_code = NULL, updated_at = clock_timestamp() + WHERE id = $1 AND status IN ('queued', 'processing') + ''', + attachment_id, + ) + exhausted = False + if exhausted: + try: + await broker.publish(dump_current(job), DLQ, {'x-error-code': 'retry_exhausted'}) + except BrokerDown: + logger.warning('job %s exhausted; DLQ did not confirm', job['job_id']) 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']) + stop_lease = asyncio.Event() + beat = asyncio.create_task(_beat_lease(pool, job_id, stop_lease, lease_seconds)) + try: + try: + if await consume_fault(pool, 'transient-once'): + raise TransientJobError() + if await consume_fault(pool, 'permanent-once'): + raise PermanentJobError('invalid_image') + variants = 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 _fail(conn, broker, job, attachment_id, exc.code, True) + return + except TransientJobError: + if not await _schedule_retry(conn, job, attachment_id, row['max_attempts'], 'storage'): + await _fail(conn, broker, job, attachment_id, 'retry_exhausted', True) + return + except asyncio.TimeoutError: + if not await _schedule_retry(conn, job, attachment_id, row['max_attempts'], 'timeout'): + await _fail(conn, broker, job, attachment_id, 'retry_exhausted', True) + return + except Exception as exc: + logger.warning( + 'attachment %s attempt %s failed (%s)', + job['attachment_id'], + job['attempt'], + type(exc).__name__, + ) + if not await _schedule_retry(conn, job, attachment_id, row['max_attempts'], 'processing_failed'): + await _fail(conn, broker, job, attachment_id, 'retry_exhausted', True) + return + if await consume_fault(pool, 'exit-after-put'): + logger.warning('fault exit-after-put: leaving %s unacked after object put', job['attachment_id']) + logging.shutdown() + os._exit(75) + finished = await _finish(conn, attachment_id, job_id, variants) + if finished: + await _drop_staging(conn, objects, attachment_id, row['staging_key'], row['object_key']) + logger.info('attachment %s ready on attempt %s', job['attachment_id'], job['attempt']) + finally: + stop_lease.set() + beat.cancel() finally: - await conn.execute('SELECT pg_advisory_unlock($1)', _lock_key(attachment_id)) + 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: +async def _handle(pool, objects, broker, body: bytes, lease_seconds: 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) + await _process(pool, objects, broker, job, lease_seconds, timeout) -async def _beat(stop: asyncio.Event) -> None: +async def _alive(stop: asyncio.Event) -> None: while not stop.is_set(): _HEARTBEAT.write_text('ok', encoding='ascii') try: @@ -245,9 +430,81 @@ async def _beat(stop: asyncio.Event) -> None: pass +async def _cleanup_staging(pool: asyncpg.Pool, objects: ObjectStore, retention: int) -> None: + cutoff = datetime.now(timezone.utc) - timedelta(seconds=retention) + async with pool.acquire() as conn: + ready = await conn.fetch( + ''' + SELECT id, staging_key, object_key + FROM attachments + WHERE status = 'ready' AND staging_key <> object_key + LIMIT 20 + ''' + ) + failed = await conn.fetch( + ''' + SELECT id, staging_key + FROM attachments + WHERE status = 'failed' AND staging_key <> object_key AND updated_at <= $1 + LIMIT 20 + ''', + cutoff, + ) + for row in ready: + try: + await asyncio.to_thread(objects.delete, row['staging_key']) + except StorageError: + continue + async with pool.acquire() as conn: + await conn.execute( + ''' + UPDATE attachments + SET staging_key = object_key + WHERE id = $1 AND status = 'ready' AND staging_key = $2 + ''', + row['id'], + row['staging_key'], + ) + for row in failed: + async with pool.acquire() as conn: + claimed = await conn.fetchval( + ''' + UPDATE attachments + SET staging_key = object_key + WHERE id = $1 AND status = 'failed' AND staging_key = $2 AND updated_at <= $3 + RETURNING id + ''', + row['id'], + row['staging_key'], + cutoff, + ) + if claimed is None: + continue + try: + await asyncio.to_thread(objects.delete, row['staging_key']) + except StorageError: + logger.warning('failed staging %s was unlinked in metadata and is still in the bucket', row['id']) + + +async def _maintain(pool, broker, objects, stop: asyncio.Event, retention: int) -> None: + ticks = 0 + while not stop.is_set(): + try: + await publish_pending(pool, broker) + await reclaim_expired(pool) + ticks += 1 + if ticks % 30 == 0: + await _cleanup_staging(pool, objects, retention) + except Exception: + logger.exception('worker maintenance failed') + try: + await asyncio.wait_for(stop.wait(), timeout=1) + 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() @@ -255,40 +512,52 @@ async def _run() -> None: for sig in (signal.SIGTERM, signal.SIGINT): loop.add_signal_handler(sig, stop.set) - settings = load_settings() - limit = job_max_attempts() + # Imported for the side effect of validating the pool settings the API also uses. + load_settings() + job_max_attempts() timeout = job_timeout_seconds() - pool = await open_pool(settings.database_url) + lease_seconds = effective_lease_seconds() + retention = staging_retention_seconds() + prefetch = worker_concurrency() + pool = await open_pool_from_settings() objects = ObjectStore(load_object_settings()) broker = Broker(load_broker_url()) - beat = asyncio.create_task(_beat(stop)) + alive = asyncio.create_task(_alive(stop)) + maintain = None 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) + # consumer_channel stays referenced until this function returns, so it is not closed early. + consumer_channel, queue = await broker.open_consumer(prefetch) + maintain = asyncio.create_task(_maintain(pool, broker, objects, stop, retention)) async def on_message(message) -> None: global _inflight _inflight += 1 try: - await _handle(pool, objects, broker, message.body, limit, timeout) + await _handle(pool, objects, broker, message.body, lease_seconds, timeout) except BrokerDown: - await message.nack(requeue=True) + async with _ACK_LOCK: + await message.nack(requeue=True) return except Exception: logger.exception('job was not finished') - await message.nack(requeue=True) + async with _ACK_LOCK: + await message.nack(requeue=True) return else: - await message.ack() + async with _ACK_LOCK: + await message.ack() finally: _inflight -= 1 consumer = await queue.consume(on_message) - logger.info('worker consuming %s', queue.name) + logger.info( + 'worker consuming %s prefetch %s lease %ss channel %s', + queue.name, + prefetch, + lease_seconds, + id(consumer_channel), + ) await stop.wait() logger.info('worker draining') await queue.cancel(consumer) @@ -297,11 +566,19 @@ async def _run() -> None: break await asyncio.sleep(0.05) finally: - beat.cancel() + alive.cancel() + if maintain is not None: + maintain.cancel() await broker.close() await pool.close() +async def open_pool_from_settings(): + from .db import open_pool + + return await open_pool(load_settings().database_url) + + def main() -> None: asyncio.run(_run()) diff --git a/compose.yaml b/compose.yaml index ebd71686..c38f0e35 100644 --- a/compose.yaml +++ b/compose.yaml @@ -1,6 +1,8 @@ # 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. +# HTTP upload still receives the whole body. POST returns 202 after staging and the job row +# commit. The outbox relay confirms the job to RabbitMQ; a crash between those two is the +# same row, republished later. The worker writes the original, a 256 JPEG thumbnail, a +# 128 JPEG crop and a WebP fit inside 1280. Worker memory limit below is the decode cap. # 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 @@ -33,7 +35,7 @@ services: networks: - data healthcheck: - test: ["CMD-SHELL", "pg_isready -U \"$$POSTGRES_USER\" -d \"$$POSTGRES_DB\""] + test: ["CMD-SHELL", 'pg_isready -U "$$POSTGRES_USER" -d "$$POSTGRES_DB"'] interval: 2s timeout: 5s retries: 30 @@ -260,9 +262,14 @@ services: BROKER_URL_FILE: /run/secrets/broker_url JOB_MAX_ATTEMPTS: ${JOB_MAX_ATTEMPTS:-5} JOB_TIMEOUT_SECONDS: ${JOB_TIMEOUT_SECONDS:-60} + JOB_RETRY_BASE_SECONDS: ${JOB_RETRY_BASE_SECONDS:-0.5} + JOB_RETRY_CAP_SECONDS: ${JOB_RETRY_CAP_SECONDS:-30} + JOB_LEASE_SECONDS: ${JOB_LEASE_SECONDS:-90} + STAGING_RETENTION_SECONDS: ${STAGING_RETENTION_SECONDS:-86400} WORKER_CONCURRENCY: ${WORKER_CONCURRENCY:-1} DB_POOL_MIN: "1" - DB_POOL_MAX: "4" + # Two in-flight jobs hold a connection each, plus a lease heartbeat and the outbox relay. + DB_POOL_MAX: "8" secrets: - source: postgres_password uid: "10001" diff --git a/evidence/level4.txt b/evidence/level4.txt new file mode 100644 index 00000000..9ef71a30 --- /dev/null +++ b/evidence/level4.txt @@ -0,0 +1,32 @@ +# Level 4 evidence, 2026-11-22 +# Synthetic users only. No session tokens, passwords or broker URLs. +# Interpreter: C:\Python314\python.exe +# `python3` on this Windows host is the Store alias and exits 9009, so make was not used. + +python scripts/check_contract.py +PASS: offline skeleton structure, local refs and Python syntax; application NOT tested. + +docker compose --env-file .env logs migrate +applied migration 007_outbox_retry.sql + +docker compose --env-file .env exec -T worker python -m app.selfcheck +PASS: thumbnail 256, crop 128, webp 1280-box, exif stripped, backoff capped + +python tests/smoke.py --base-url http://127.0.0.1:8080 +PASS: lab5 public API scenario; infrastructure and grading evidence remain separate. +(repeated after the demo below, same PASS) + +python scripts/level4_demo.py +pause-outbox attachment=1ebba94c-516f-4007-8c47-d240db28de5f published_at_while_paused=null status_after=ready variants=3 +commit-before-publish attachment=1fabbbaa-3b68-45da-bbf3-deca86ac8e82 published_at_while_paused=null status_after=ready variants=3 +lease-expired attachment=cd637725-a1e2-463a-99c3-49d6f126525d reclaimed=queued status_after=ready variants=3 +exit-after-put attachment=78f62eb7-771d-4cf4-90a3-923e757aa462 variants=3 same_result=yes +replay requeued 6d4bdc1d-d6d1-4ecd-a920-0459adfebcf2 +replay already_ready 6d4bdc1d-d6d1-4ecd-a920-0459adfebcf2 +permanent-once attachment=6d4bdc1d-d6d1-4ecd-a920-0459adfebcf2 failed=invalid_image dlq=2 replay=requeued second=already_ready variants=3 +transient-once attachment=5da2a975-9ccd-4a85-8bd9-c593e00f7b3b backoff=logged variants=3 +PASS: level 4 outbox, crash, lease redelivery, DLQ replay, backoff + +dlq=2 counts both this run and an earlier permanent-once on the same RabbitMQ volume. +docker compose --env-file .env exec -T api python -m app.fault status +none diff --git a/migrations/007_outbox_retry.sql b/migrations/007_outbox_retry.sql new file mode 100644 index 00000000..aede1e4b --- /dev/null +++ b/migrations/007_outbox_retry.sql @@ -0,0 +1,48 @@ +-- Level 4: the job row is the outbox. published_at is set only after a broker confirm. +-- available_at holds the next backoff instant. runs counts entries into processing so a +-- crash before ack cannot loop forever. Replay resets both counters. +ALTER TABLE attachment_jobs ADD COLUMN available_at TIMESTAMPTZ; +ALTER TABLE attachment_jobs ADD COLUMN last_error TEXT; +ALTER TABLE attachment_jobs ADD COLUMN runs INTEGER NOT NULL DEFAULT 0; + +ALTER TABLE attachment_jobs ADD CONSTRAINT attachment_jobs_runs CHECK (runs >= 0); +ALTER TABLE attachment_jobs ADD CONSTRAINT attachment_jobs_last_error + CHECK (last_error IS NULL OR (char_length(last_error) >= 1 AND char_length(last_error) <= 64)); + +CREATE INDEX attachment_jobs_lease_idx + ON attachment_jobs (lease_until) + WHERE lease_until IS NOT NULL; + +-- Registry of terminal failures. The broker DLQ is a copy of the same fact. +CREATE TABLE attachment_job_failures ( + job_id UUID NOT NULL REFERENCES attachment_jobs (id), + attempt INTEGER NOT NULL, + error_code TEXT NOT NULL, + permanent BOOLEAN NOT NULL, + created_at TIMESTAMPTZ NOT NULL, + PRIMARY KEY (job_id, attempt, error_code), + CONSTRAINT attachment_job_failures_code CHECK (char_length(error_code) BETWEEN 1 AND 64) +); + +-- One row per operator replay decision, including a refusal to run an already ready job. +CREATE TABLE attachment_job_replays ( + id UUID PRIMARY KEY, + job_id UUID NOT NULL REFERENCES attachment_jobs (id), + attachment_id UUID NOT NULL REFERENCES attachments (id), + outcome TEXT NOT NULL, + created_at TIMESTAMPTZ NOT NULL, + CONSTRAINT attachment_job_replays_outcome CHECK (outcome IN ('requeued', 'already_ready', 'not_failed')) +); + +-- Demo switches. Empty unless an operator runs `python -m app.fault`. Not a public API. +CREATE TABLE lab_faults ( + name TEXT PRIMARY KEY, + armed_at TIMESTAMPTZ NOT NULL, + CONSTRAINT lab_faults_name CHECK (name IN ( + 'pause-outbox', + 'commit-before-publish', + 'exit-after-put', + 'transient-once', + 'permanent-once' + )) +); diff --git a/scripts/level4_demo.py b/scripts/level4_demo.py new file mode 100644 index 00000000..238cdc2f --- /dev/null +++ b/scripts/level4_demo.py @@ -0,0 +1,464 @@ +#!/usr/bin/env python3 +"""Reproducible level-4 checks against the compose stack. + +Prints attachment ids, statuses and variant counts. Does not print tokens, +passwords or broker URLs. Track 5 is not part of this script. +""" +import base64 +import json +import secrets +import shlex +import subprocess +import time +import urllib.error +import urllib.request +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +BASE = 'http://127.0.0.1:8080' +FIXTURE = ROOT / 'tests' / 'fixtures' / 'sample.png' +UUID = __import__('re').compile(r'^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$') + + +class DemoError(Exception): + pass + + +def run(args, check=True): + completed = subprocess.run( + args, + cwd=str(ROOT), + capture_output=True, + text=True, + check=False, + ) + if check and completed.returncode != 0: + detail = (completed.stderr or completed.stdout or '').strip().splitlines() + tail = detail[-1] if detail else 'exit %s' % completed.returncode + raise DemoError(args[0] + ' failed: ' + tail[:200]) + return completed + + +def compose(*args, check=True): + return run(['docker', 'compose', '--env-file', '.env', *args], check=check) + + +def fault(*args): + last = None + for _ in range(20): + last = compose('exec', '-T', 'api', 'python', '-m', 'app.fault', *args, check=False) + if last.returncode == 0: + return last.stdout.strip() + time.sleep(1) + raise DemoError('fault %s failed' % ' '.join(args)) + + +def psql(sql): + script = 'psql -U "$POSTGRES_USER" -d "$POSTGRES_DB" -tA -c %s' % shlex.quote(sql) + last = None + for _ in range(10): + last = compose('exec', '-T', 'postgres', 'sh', '-c', script, check=False) + if last.returncode == 0: + return last.stdout.strip() + time.sleep(1) + raise DemoError('psql failed') + + +def replay(attachment_id): + if UUID.fullmatch(attachment_id) is None: + raise DemoError('replay id is not a uuid') + text = None + for _ in range(20): + completed = compose('exec', '-T', 'api', 'python', '-m', 'app.replay', attachment_id, check=False) + if completed.returncode == 0: + text = completed.stdout.strip() + break + time.sleep(1) + if text is None: + raise DemoError('replay did not run') + print('replay %s' % text) + return text + + +def restart_counts(): + listed = compose('ps', '-a', '-q', 'api') + counts = {} + for container_id in listed.stdout.split(): + inspected = run(['docker', 'inspect', '-f', '{{.RestartCount}}', container_id]) + counts[container_id[:12]] = int(inspected.stdout.strip() or '0') + return counts + + +def request(method, path, token=None, body=None, raw=None, content_type=None, accept=None): + data = raw + headers = {} + if body is not None: + data = json.dumps(body).encode('utf-8') + headers['Content-Type'] = 'application/json' + if content_type: + headers['Content-Type'] = content_type + if token: + headers['Authorization'] = 'Bearer ' + token + req = urllib.request.Request(BASE + path, data=data, headers=headers, method=method) + try: + with urllib.request.urlopen(req, timeout=30) as response: + payload = response.read() + code = response.status + except urllib.error.HTTPError as exc: + payload = exc.read() + code = exc.code + except urllib.error.URLError as exc: + reason = exc.reason + raise DemoError('%s %s connection failed (%s)' % (method, path, type(reason).__name__)) from None + except OSError as exc: + raise DemoError('%s %s connection failed (%s)' % (method, path, type(exc).__name__)) from None + if accept is not None and code not in accept: + raise DemoError('%s %s -> %s' % (method, path.split('?')[0], code)) + return code, payload + + +def json_body(payload): + return json.loads(payload.decode('utf-8')) + + +def wait_ready_http(): + deadline = time.monotonic() + 90 + while time.monotonic() < deadline: + try: + code, _payload = request('GET', '/health/ready', accept=(200, 503)) + except DemoError: + time.sleep(1) + continue + if code == 200: + return + time.sleep(1) + raise DemoError('API did not become ready') + + +def session(): + username = 'u' + secrets.token_hex(4) + password = secrets.token_urlsafe(18) + code, payload = request( + 'POST', + '/api/v1/users', + body={'username': username, 'display_name': 'Демо', 'password': password}, + accept=(201,), + ) + user = json_body(payload) + basic = base64.b64encode((username + ':' + password).encode('utf-8')).decode('ascii') + req = urllib.request.Request( + BASE + '/api/v1/auth/sessions', + headers={'Authorization': 'Basic ' + basic}, + method='POST', + ) + try: + with urllib.request.urlopen(req, timeout=30) as response: + opened = json.loads(response.read().decode('utf-8')) + except urllib.error.HTTPError as exc: + raise DemoError('login -> %s' % exc.code) from None + token = opened['token'] + code, payload = request( + 'POST', + '/api/v1/chats', + token=token, + body={'title': 'Уровень 4', 'member_ids': [user['id']]}, + accept=(201,), + ) + chat = json_body(payload) + return token, chat['id'] + + +def upload(token, chat_id): + """Return (status, attachment id). status 0 means the connection died. The token is not logged.""" + try: + code, payload = request( + 'POST', + '/api/v1/chats/%s/attachments?filename=sample.png' % chat_id, + token=token, + raw=FIXTURE.read_bytes(), + content_type='image/png', + accept=(202, 500, 502, 503, 504), + ) + except DemoError: + return 0, None + if code != 202: + return code, None + return 202, json_body(payload)['id'] + + +def meta(token, attachment_id): + deadline = time.monotonic() + 30 + while True: + try: + code, payload = request( + 'GET', + '/api/v1/attachments/' + attachment_id, + token=token, + accept=(200, 503), + ) + except DemoError: + if time.monotonic() > deadline: + raise + time.sleep(0.5) + continue + if code == 200: + return json_body(payload) + if time.monotonic() > deadline: + raise DemoError('metadata unavailable') + time.sleep(0.5) + + +def wait_status(token, attachment_id, wanted, seconds=60): + deadline = time.monotonic() + seconds + last = None + while time.monotonic() < deadline: + last = meta(token, attachment_id) + if last['status'] == wanted: + return last + if wanted != 'failed' and last['status'] == 'failed': + raise DemoError('%s failed with %s' % (attachment_id, last.get('error_code'))) + time.sleep(0.4) + raise DemoError('%s stayed %s' % (attachment_id, last['status'] if last else 'unknown')) + + +def published_at(attachment_id): + if UUID.fullmatch(attachment_id) is None: + raise DemoError('id is not a uuid') + return psql( + "SELECT COALESCE(published_at::text, 'null') FROM attachment_jobs WHERE attachment_id = '%s'" + % attachment_id + ) + + +def variant_count(attachment_id): + if UUID.fullmatch(attachment_id) is None: + raise DemoError('id is not a uuid') + return int(psql("SELECT count(*) FROM attachment_variants WHERE attachment_id = '%s'" % attachment_id)) + + +def jpeg_size(data): + if data[:2] != b'\xff\xd8': + raise DemoError('not a jpeg') + index = 2 + sof = {0xC0, 0xC1, 0xC2, 0xC3, 0xC5, 0xC6, 0xC7, 0xC9, 0xCA, 0xCB, 0xCD, 0xCE, 0xCF} + while index < len(data): + if data[index] != 0xFF: + raise DemoError('bad jpeg') + while index < len(data) and data[index] == 0xFF: + index += 1 + marker = data[index] + index += 1 + if marker in (0xD8, 0xD9, 0xDA) or 0xD0 <= marker <= 0xD7: + if marker in (0xD9, 0xDA): + break + continue + if index + 2 > len(data): + raise DemoError('short jpeg') + length = int.from_bytes(data[index:index + 2], 'big') + if marker in sof: + height = int.from_bytes(data[index + 3:index + 5], 'big') + width = int.from_bytes(data[index + 5:index + 7], 'big') + return width, height + index += length + raise DemoError('jpeg size missing') + + +def download(token, attachment_id, variant): + code, payload = request( + 'GET', + '/api/v1/attachments/%s/content?variant=%s' % (attachment_id, variant), + token=token, + accept=(200,), + ) + return code, payload + + +def assert_ready_variants(token, attachment_id): + ready = wait_status(token, attachment_id, 'ready') + names = {} + for item in ready['variants']: + names[item['name']] = item + if set(names) != {'thumbnail', 'crop', 'optimized'}: + raise DemoError('variants %s' % sorted(names)) + if (names['thumbnail']['width'], names['thumbnail']['height']) != (256, 160): + raise DemoError('thumbnail metadata') + if (names['crop']['width'], names['crop']['height']) != (128, 128): + raise DemoError('crop metadata') + if names['optimized']['content_type'] != 'image/webp': + raise DemoError('optimized type') + if (names['optimized']['width'], names['optimized']['height']) != (320, 200): + raise DemoError('optimized metadata') + _code, thumb = download(token, attachment_id, 'thumbnail') + if jpeg_size(thumb) != (256, 160): + raise DemoError('thumbnail bytes') + _code, crop = download(token, attachment_id, 'crop') + if jpeg_size(crop) != (128, 128): + raise DemoError('crop bytes') + _code, optimized = download(token, attachment_id, 'optimized') + if optimized[:4] != b'RIFF' or optimized[8:12] != b'WEBP': + raise DemoError('optimized bytes') + if variant_count(attachment_id) != 3: + raise DemoError('variant rows %s' % variant_count(attachment_id)) + deadline = time.monotonic() + 15 + while time.monotonic() < deadline: + cleared = psql( + "SELECT (staging_key = object_key) FROM attachments WHERE id = '%s'" % attachment_id + ) + if cleared == 't': + break + time.sleep(0.4) + else: + raise DemoError('staging was kept after ready') + return ready + + +def attachment_ids(): + found = psql('SELECT id FROM attachments') + return {item for item in found.splitlines() if UUID.fullmatch(item)} + + +def pause_gap(token, chat_id, label): + before = attachment_ids() + before_restarts = restart_counts() + fault('arm', 'pause-outbox') + crash = label == 'commit-before-publish' + if crash: + fault('arm', 'commit-before-publish') + status, uploaded = upload(token, chat_id) + if not crash and status != 202: + raise DemoError('pause-outbox upload -> %s' % status) + if crash: + deadline = time.monotonic() + 30 + while time.monotonic() < deadline: + after = restart_counts() + if sum(after.values()) > sum(before_restarts.values()): + break + time.sleep(1) + else: + raise DemoError('commit-before-publish did not restart an API replica') + created = sorted(attachment_ids() - before) + if uploaded and uploaded not in created: + created.append(uploaded) + if not created: + raise DemoError('%s created no attachment' % label) + attachment_id = uploaded or created[-1] + time.sleep(2) + stamp = published_at(attachment_id) + if stamp != 'null': + raise DemoError('%s published_at=%s while outbox is paused' % (label, stamp)) + if meta(token, attachment_id)['status'] == 'ready': + raise DemoError('%s became ready while outbox is paused' % label) + fault('clear') + assert_ready_variants(token, attachment_id) + print('%s attachment=%s published_at_while_paused=null status_after=ready variants=3' % (label, attachment_id)) + + +def lease_reclaim(token, chat_id): + """A processing row with an expired lease and no live lock is queued again, then finishes.""" + fault('arm', 'pause-outbox') + status, attachment_id = upload(token, chat_id) + if status != 202 or UUID.fullmatch(attachment_id or '') is None: + raise DemoError('lease upload -> %s' % status) + psql( + "UPDATE attachments SET status = 'processing' WHERE id = '%s' AND status = 'queued'" + % attachment_id + ) + psql( + "UPDATE attachment_jobs SET lease_until = clock_timestamp() - interval '1 minute', " + "published_at = clock_timestamp() WHERE attachment_id = '%s'" + % attachment_id + ) + deadline = time.monotonic() + 20 + while time.monotonic() < deadline: + if meta(token, attachment_id)['status'] == 'queued' and published_at(attachment_id) == 'null': + break + time.sleep(0.4) + else: + raise DemoError('expired lease was not reclaimed') + fault('clear') + assert_ready_variants(token, attachment_id) + print('lease-expired attachment=%s reclaimed=queued status_after=ready variants=3' % attachment_id) + + +def worker_crash(token, chat_id): + fault('arm', 'exit-after-put') + status, attachment_id = upload(token, chat_id) + if status != 202 or not attachment_id: + raise DemoError('exit-after-put upload -> %s' % status) + assert_ready_variants(token, attachment_id) + print('exit-after-put attachment=%s variants=3 same_result=yes' % attachment_id) + + +def permanent_and_replay(token, chat_id): + fault('arm', 'permanent-once') + status, attachment_id = upload(token, chat_id) + if status != 202 or not attachment_id: + raise DemoError('permanent-once upload -> %s' % status) + failed = wait_status(token, attachment_id, 'failed') + if failed['error_code'] != 'invalid_image': + raise DemoError('error_code %s' % failed.get('error_code')) + rows = psql( + "SELECT error_code FROM attachment_job_failures f JOIN attachment_jobs j ON j.id = f.job_id " + "WHERE j.attachment_id = '%s'" % attachment_id + ) + if 'invalid_image' not in rows.splitlines(): + raise DemoError('failure registry missed invalid_image') + queues = compose('exec', '-T', 'rabbitmq', 'rabbitmqctl', 'list_queues', 'name', 'messages') + dlq = '0' + for line in queues.stdout.splitlines(): + parts = line.split() + if len(parts) == 2 and parts[0] == 'attachment.jobs.dlq': + dlq = parts[1] + if dlq == '0': + raise DemoError('DLQ is empty') + first = replay(attachment_id) + if not first.startswith('requeued '): + raise DemoError('first replay was %s' % first.split()[0]) + assert_ready_variants(token, attachment_id) + second = replay(attachment_id) + if not second.startswith('already_ready '): + raise DemoError('second replay was %s' % second.split()[0]) + if variant_count(attachment_id) != 3: + raise DemoError('replay duplicated variants') + print('permanent-once attachment=%s failed=invalid_image dlq=%s replay=requeued second=already_ready variants=3' % (attachment_id, dlq)) + + +def transient(token, chat_id): + fault('arm', 'transient-once') + status, attachment_id = upload(token, chat_id) + if status != 202 or not attachment_id: + raise DemoError('transient-once upload -> %s' % status) + assert_ready_variants(token, attachment_id) + logs = compose('logs', '--since', '3m', 'worker', check=False) + text = logs.stdout + '\n' + logs.stderr + logged = any('will retry in ' in line and attachment_id in line for line in text.splitlines()) + if not logged: + raise DemoError('backoff line was not logged') + print('transient-once attachment=%s backoff=logged variants=3' % attachment_id) + + +def main(): + wait_ready_http() + fault('clear') + token, chat_id = session() + try: + pause_gap(token, chat_id, 'pause-outbox') + pause_gap(token, chat_id, 'commit-before-publish') + lease_reclaim(token, chat_id) + worker_crash(token, chat_id) + permanent_and_replay(token, chat_id) + transient(token, chat_id) + finally: + try: + fault('clear') + except DemoError as exc: + print(exc) + print('PASS: level 4 outbox, crash, lease redelivery, DLQ replay, backoff') + + +if __name__ == '__main__': + try: + main() + except DemoError as exc: + print('FAIL:', exc) + raise SystemExit(1)