5 Commits
Author SHA1 Message Date
RitaTimaeva 65541c8c3b level 5 track 1 charts 2026-11-23 12:46:23 +03:00
RitaTimaeva b3a8b2e4e0 level 5 track 1 2026-11-22 19:20:51 +03:00
RitaTimaeva 813fc03da5 level 4 2026-11-22 17:59:11 +03:00
RitaTimaeva 7e1780be67 level 3 2026-11-22 17:20:34 +03:00
RitaTimaeva c10bf08feb lab4 minimum moved to lab5 2026-11-22 15:47:13 +03:00
52 changed files with 6177 additions and 15 deletions
+34 -3
View File
@@ -2,11 +2,15 @@
# These are logical interface suggestions; map actual framework names in REPORT.md.
APP_HOST=0.0.0.0
APP_PORT=8080
# Host port published by the LB. Default 8080; change if that port is already taken.
LB_PORT=8080
APP_ENV=lab
SESSION_TTL_SECONDS=3600
# Choose credentials locally. File paths contain no secret values.
DATABASE_URL_FILE=/run/secrets/database_url
# Optional on 3, required use on 4 in lab2; Redis OR Valkey:
# compose.yaml gives api/migrate DB_HOST/DB_USER/DB_NAME and
# DB_PASSWORD_FILE=/run/secrets/postgres_password (secret from POSTGRES_PASSWORD).
POSTGRES_USER=messenger
POSTGRES_PASSWORD=change-me-locally
POSTGRES_DB=messenger
SESSION_STORE=postgres
CACHE_URL_FILE=/run/secrets/cache_url
API_REPLICAS=2
@@ -14,12 +18,39 @@ IDEMPOTENCY_TTL_SECONDS=86400
S3_ENDPOINT=http://s3:9000
S3_REGION=us-east-1
S3_BUCKET=messenger-attachments
# compose.yaml gives minio MINIO_ROOT_USER_FILE / MINIO_ROOT_PASSWORD_FILE
# (secrets from MINIO_ROOT_USER / MINIO_ROOT_PASSWORD). Root is bootstrap-only.
# The API user is created by minio-init and limited to S3_BUCKET.
# App containers should read the files below, not these values as env vars.
MINIO_ROOT_USER=messenger-root
MINIO_ROOT_PASSWORD=change-me-minio-root
S3_ACCESS_KEY_ID=messenger-api
S3_SECRET_ACCESS_KEY=change-me-minio-api
S3_ACCESS_KEY_ID_FILE=/run/secrets/s3_access_key_id
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
# Upload returns 429 once this many attachments are queued or processing.
# The rejected body is not stored. Already accepted jobs keep running.
MAX_INFLIGHT_JOBS=20
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.
+40
View File
@@ -0,0 +1,40 @@
# Закреплённая среда выполнения. Тег называет версию, digest — то, что Docker реально скачает.
FROM python:3.14.8-slim-bookworm@sha256:c8137f4c460908c8763f281c8f22c431eb5c538514ba9553fc3a89c06b7cfb88
ENV PYTHONDONTWRITEBYTECODE=1 \
PYTHONUNBUFFERED=1
# Значения по умолчанию, секретов нет. `docker run --env-file .env` перекрывает их при запуске.
ENV APP_HOST=0.0.0.0 \
APP_PORT=8080 \
APP_ENV=lab \
LOG_LEVEL=info \
DRAIN_SECONDS=4 \
SHUTDOWN_TIMEOUT_SECONDS=3 \
SESSION_TTL_SECONDS=3600
RUN groupadd --gid 10001 app \
&& useradd --uid 10001 --gid app --create-home --shell /usr/sbin/nologin app
WORKDIR /app
COPY requirements.txt .
RUN python -m pip install --no-cache-dir --disable-pip-version-check --root-user-action=ignore -r requirements.txt
COPY --chown=app:app app ./app
COPY --chown=app:app migrations ./migrations
COPY --chown=app:app contracts/openapi.json ./contracts/openapi.json
USER app
# Visible as X-App-Version: shows which build served a request during a rolling update.
ARG APP_VERSION=dev
ENV APP_VERSION=${APP_VERSION}
EXPOSE 8080
HEALTHCHECK --interval=5s --timeout=3s --start-period=15s --retries=3 \
CMD ["python", "-c", "import os, urllib.request; urllib.request.urlopen('http://127.0.0.1:%s/health/ready' % os.environ['APP_PORT'], timeout=2)"]
STOPSIGNAL SIGTERM
CMD ["python", "-m", "app"]
+112 -12
View File
@@ -1,37 +1,137 @@
# Отчёт — лабораторная 5
- Автор, группа: TODO
- Целевая оценка; выбранный трек 5, если нужен: TODO
- Целевая оценка; выбранный трек 5, если нужен: **5, трек 1** (очередь под перегрузкой).
- 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
python scripts/track1_overload.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/<id>` и в одной транзакции пишет `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). Приём ограничен `MAX_INFLIGHT_JOBS` (20): это число строк `queued`+`processing`. Сверх него upload отвечает 429 и объект в бакет не кладётся. Уже принятые задания этот отказ не отменяет. На время обработки берётся 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 <id>` для `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 |
| Трек 1: три prefetch, backlog 15, затем 429 и восстановление | `python scripts/track1_overload.py` | prefetch 1/2/4, p95 8.196/7.647/7.366 с, RSS до 275.8 МиБ; 9 ответов 429, принятые дошли до ready | evidence/track1.json |
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 и объяснить ограничения измерения.
Сравнение prefetch и перегрузка — в разделе «Трек 5». Ниже по-прежнему только сценарии уровня 4.
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
| --- | --- | --- | --- |
| 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
Трек 1. Гипотеза: на одном и том же backlog больший prefetch поднимет throughput и снизит p95 времени до ready, но увеличит RSS worker. Отдельно: при остановленном worker API перестанет принимать работу на границе `MAX_INFLIGHT_JOBS`, а уже принятое после старта дойдёт до ready без новой загрузки.
Методика. `python scripts/track1_overload.py`. Для prefetch 1, 2 и 4 контейнер worker пересоздаётся с этим `WORKER_CONCURRENCY` (он же prefetch), затем останавливается. Клиент один раз кладёт 15 PNG: 5 штук 128×128, 5 штук 640×480, 5 штук 2560×1920. Файлы одноцветные, поэтому в бакете они маленькие, а worker всё равно декодирует все пиксели. Перед стартом в `attachment.jobs` было 15 `messages_ready`. Часы drain начинаются, когда процесс снова пишет в лог свой prefetch. p95 — время клиента от ответа 202 до `ready`. Throughput — 15 / длительность drain. RSS — максимум `docker stats` по контейнеру worker за этот интервал. Лимит памяти worker в compose — 512M.
Затем worker снова остановлен и отправлено 28 крошечных PNG при лимите 20.
Сырой JSON: [evidence/track1.json](evidence/track1.json). Графики собраны из него командой `python scripts/track1_charts.py` (SVG) и лежат рядом как PNG для слайдов. Стенд тот же, что у уровня 4, дата 2026-11-22.
![p95 по размеру и prefetch](evidence/track1-p95.png)
![throughput и RSS](evidence/track1-tradeoff.png)
![отказы 429 при остановленном worker](evidence/track1-overload.png)
| prefetch | backlog ready | drain, с | throughput, 1/с | p95 202→ready, с | p95 small / medium / large, с | RSS max, МиБ |
| --- | --- | --- | --- | --- | --- | --- |
| 1 | 15 | 3.134 | 4.786 | 8.196 | 5.953 / 6.088 / 8.196 | 110.3 |
| 2 | 15 | 3.088 | 4.858 | 7.647 | 5.502 / 5.676 / 7.647 | 110.6 |
| 4 | 15 | 3.453 | 4.344 | 7.366 | 5.230 / 5.044 / 7.366 | 275.8 |
Все 15 в каждом прогоне стали ready, failed не было. `queue_ready_max` уже во время drain (4, 1 и 7) меньше 15: prefetch забирает сообщения в unacked, а `rabbitmqctl` не успевает снять пик. Lag до старта — сами 15 сообщений.
Вывод. Throughput на этом стенде почти не вырос: узкое место — запись оригинала и трёх вариантов в MinIO плюс фиксация в PostgreSQL, а не свободные ядра. p95 от 202 до ready снизился примерно на 0.8 с. RSS при prefetch 4 вырос примерно в 2.5 раза, до 276 МиБ из лимита 512. Дальше увеличивать prefetch на этих картинках нет смысла: latency почти стоит, память растёт.
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
| --- | --- | --- | --- |
| Worker остановлен, 28 upload при лимите 20 | часть 202, остальные 429, байты отклонённых не становятся заданием | 19×202, 9×429, `messages_ready` = 19 | отказ сразу, принятые не потеряны |
| Старт того же worker | те же id доходят до ready, новый upload снова 202 | `pending_after_restart` пустой, следующий статус 202 и тоже ready | всё окно перегрузки 6.364 с, включая сами upload |
## Ограничения и следующие шаги
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза.
- Доставка at least once. Повтор идемпотентен по ключу варианта, это не exactly-once.
- `runs` ограничивает цикл «процесс умер до ack». Обычный retry с backoff считает `attempt` и сбрасывает `runs`.
- Если процесс убит OOM посреди decode, попытка сгорает так же, как crash до ack. В треке 1 снят только максимум RSS контейнера, не профиль по времени: за drain около 3 с `docker stats` успел дать 3 отсчёта.
- Replay после `STAGING_RETENTION_SECONDS` может не найти исходник, если финальный объект так и не был скопирован.
- DLQ не вычитывается автоматически. Повтор успешной job туда не добавляет второй прогон.
- Краны `lab_faults` учебные. В обычном запуске таблица пустая.
- Трек 1 смотрел одноцветные PNG и один backlog из 15 файлов. На фотографиях decode тяжелее, соотношение latency и RSS может сдвинуться. Повтор: `python scripts/track1_overload.py --skip-build`, если образ уже собран.
View File
+49
View File
@@ -0,0 +1,49 @@
import logging
import threading
import uvicorn
from .config import load_settings
from .drain import draining
logger = logging.getLogger('messenger')
class DrainingServer(uvicorn.Server):
"""First SIGTERM/SIGINT: keep serving for drain_seconds with readiness 503, then uvicorn's graceful stop.
drain_seconds must exceed the LB detection time (HAProxy inter 1s x fall 2 + timeout check 1s),
so the replica is out of rotation before it stops accepting connections.
"""
def __init__(self, config: uvicorn.Config, drain_seconds: float):
super().__init__(config)
self.drain_seconds = drain_seconds
def handle_exit(self, sig, frame) -> None:
if draining.is_set() or self.drain_seconds <= 0:
draining.set()
super().handle_exit(sig, frame)
return
draining.set()
logger.warning('signal %s: draining for %.1f s before shutdown', sig, self.drain_seconds)
timer = threading.Timer(self.drain_seconds, super().handle_exit, (sig, frame))
timer.daemon = True
timer.start()
def main() -> None:
settings = load_settings()
config = uvicorn.Config(
'app.main:app',
host=settings.host,
port=settings.port,
log_level=settings.log_level,
timeout_graceful_shutdown=settings.shutdown_timeout,
timeout_keep_alive=settings.keepalive_timeout,
)
DrainingServer(config, settings.drain_seconds).run()
if __name__ == '__main__':
main()
+30
View File
@@ -0,0 +1,30 @@
"""Basic is only for creating a session. Every other route accepts only Bearer."""
import base64
import binascii
from typing import Optional, Tuple
BASIC_CHALLENGE = 'Basic realm="messenger", charset="UTF-8"'
BEARER_CHALLENGE = 'Bearer realm="messenger"'
def parse_basic(header: str) -> Optional[Tuple[str, str]]:
"""username:password. The password may itself contain a colon."""
scheme, separator, param = header.partition(' ')
if separator != ' ' or scheme.lower() != 'basic' or not param or param != param.strip():
return None
try:
decoded = base64.b64decode(param, validate=True)
text = decoded.decode('utf-8')
except (binascii.Error, UnicodeDecodeError, ValueError):
return None
username, separator, password = text.partition(':')
if separator != ':':
return None
return username, password
def parse_bearer(header: str) -> Optional[str]:
scheme, separator, token = header.partition(' ')
if separator != ' ' or scheme.lower() != 'bearer' or not token or token != token.strip() or ' ' in token:
return None
return token
+76
View File
@@ -0,0 +1,76 @@
"""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 DLQ, DLQ_ARGUMENTS, 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
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._declare(self.channel)
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 open_consumer(self, prefetch: int):
"""A channel that only consumes. prefetch caps how many jobs sit unacked."""
if self._connection is None:
raise BrokerDown()
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,
)
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
+184
View File
@@ -0,0 +1,184 @@
import os
import socket
from dataclasses import dataclass
from pathlib import Path
from urllib.parse import quote
@dataclass(frozen=True)
class ObjectSettings:
endpoint: str
region: str
bucket: str
access_key: str
secret_key: str
@dataclass(frozen=True)
class Settings:
host: str
port: int
env: str
log_level: str
shutdown_timeout: int
drain_seconds: float
keepalive_timeout: int
session_ttl_seconds: int
idempotency_ttl_seconds: int
database_url: str
instance_id: str
app_version: str
def _read_secret_file(file_var: str, file_name: str) -> str:
try:
value = Path(file_name).read_text(encoding='utf-8').strip()
except OSError:
raise RuntimeError('%s could not be read' % file_var) from None
if not value:
raise RuntimeError('%s is empty' % file_var)
return value
def _database_url() -> str:
"""DATABASE_URL_FILE, then DATABASE_URL, then DB_* parts with the password from DB_PASSWORD_FILE.
Secret values are never logged.
"""
file_name = os.getenv('DATABASE_URL_FILE', '').strip()
if file_name:
return _read_secret_file('DATABASE_URL_FILE', file_name)
value = os.getenv('DATABASE_URL', '').strip()
if value:
return value
password_file = os.getenv('DB_PASSWORD_FILE', '').strip()
if not password_file:
raise RuntimeError('DATABASE_URL, DATABASE_URL_FILE or DB_PASSWORD_FILE is required')
password = _read_secret_file('DB_PASSWORD_FILE', password_file)
parts = {name: os.getenv(name, '').strip() for name in ('DB_HOST', 'DB_USER', 'DB_NAME')}
missing = [name for name, part in parts.items() if not part]
if missing:
raise RuntimeError('%s required with DB_PASSWORD_FILE' % ', '.join(missing))
return 'postgresql://%s:%s@%s:%s/%s' % (
quote(parts['DB_USER'], safe=''),
quote(password, safe=''),
parts['DB_HOST'],
int(os.getenv('DB_PORT', '5432')),
quote(parts['DB_NAME'], safe=''),
)
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 max_inflight_jobs() -> int:
"""How many queued plus processing attachments may exist. The next upload is 429."""
return _bounded_int('MAX_INFLIGHT_JOBS', 20, 100000)
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()
region = os.getenv('S3_REGION', 'us-east-1').strip() or 'us-east-1'
bucket = os.getenv('S3_BUCKET', '').strip()
key_file = os.getenv('S3_ACCESS_KEY_ID_FILE', '').strip()
secret_file = os.getenv('S3_SECRET_ACCESS_KEY_FILE', '').strip()
missing = [
name for name, value in (
('S3_ENDPOINT', endpoint),
('S3_BUCKET', bucket),
('S3_ACCESS_KEY_ID_FILE', key_file),
('S3_SECRET_ACCESS_KEY_FILE', secret_file),
) if not value
]
if missing:
raise RuntimeError('%s is required' % ', '.join(missing))
return ObjectSettings(
endpoint,
region,
bucket,
_read_secret_file('S3_ACCESS_KEY_ID_FILE', key_file),
_read_secret_file('S3_SECRET_ACCESS_KEY_FILE', secret_file),
)
def load_settings() -> Settings:
return Settings(
host=os.getenv('APP_HOST', '0.0.0.0'),
port=int(os.getenv('APP_PORT', '8080')),
env=os.getenv('APP_ENV', 'lab'),
log_level=os.getenv('LOG_LEVEL', 'info').lower(),
shutdown_timeout=int(os.getenv('SHUTDOWN_TIMEOUT_SECONDS', '3')),
drain_seconds=float(os.getenv('DRAIN_SECONDS', '4')),
# Longer than HAProxy's idle-connection purge (pool-purge-delay 5 s), so the LB usually closes them first.
keepalive_timeout=int(os.getenv('KEEPALIVE_TIMEOUT_SECONDS', '10')),
session_ttl_seconds=int(os.getenv('SESSION_TTL_SECONDS', '3600')),
idempotency_ttl_seconds=int(os.getenv('IDEMPOTENCY_TTL_SECONDS', '86400')),
database_url=_database_url(),
# Docker sets the hostname to the short container ID, which stop-one.sh maps back to a container.
instance_id=os.getenv('INSTANCE_ID', '').strip() or socket.gethostname(),
app_version=os.getenv('APP_VERSION', 'dev').strip() or 'dev',
)
+47
View File
@@ -0,0 +1,47 @@
"""Connection pool. The URL is never written to the log."""
import asyncio
import logging
import os
import asyncpg
logger = logging.getLogger('messenger')
_ATTEMPTS = 40
def _pool_size(name: str, default: int) -> int:
raw = os.getenv(name, '').strip()
return int(raw) if raw else default
async def open_pool(database_url: str) -> asyncpg.Pool:
delay = 0.5
last_type = 'error'
min_size = _pool_size('DB_POOL_MIN', 1)
max_size = max(min_size, _pool_size('DB_POOL_MAX', 10))
for attempt in range(1, _ATTEMPTS + 1):
pool = None
try:
pool = await asyncpg.create_pool(
database_url,
min_size=min_size,
max_size=max_size,
timeout=5,
# Uploads are capped at 10 MiB; give that write room past the old 5 s JSON timeout.
command_timeout=30,
server_settings={'statement_timeout': '30000'},
)
async with pool.acquire() as conn:
await conn.execute('SELECT 1')
return pool
except Exception as exc:
last_type = type(exc).__name__
if pool is not None:
await pool.close()
if attempt == _ATTEMPTS:
break
logger.warning('database is not ready (%s), retrying', last_type)
await asyncio.sleep(delay)
delay = min(delay * 1.5, 2)
raise RuntimeError('database did not become reachable (%s)' % last_type)
+4
View File
@@ -0,0 +1,4 @@
"""Set on SIGTERM: readiness turns 503 so the LB stops routing here while requests are still served."""
import threading
draining = threading.Event()
+41
View File
@@ -0,0 +1,41 @@
class ApiError(Exception):
"""Expected failure: the message never contains internal details."""
def __init__(self, status: int, code: str, message: str, challenge: str | None = None) -> None:
super().__init__(message)
self.status = status
self.code = code
self.message = message
self.challenge = challenge
def invalid_request(message: str) -> ApiError:
return ApiError(400, 'invalid_request', message)
def unauthorized(message: str, challenge: str) -> ApiError:
return ApiError(401, 'unauthorized', message, challenge)
def not_found(message: str) -> ApiError:
return ApiError(404, 'not_found', message)
def conflict(message: str) -> ApiError:
return ApiError(409, 'conflict', message)
def payload_too_large(message: str) -> ApiError:
return ApiError(413, 'payload_too_large', message)
def unsupported_media_type(message: str) -> ApiError:
return ApiError(415, 'unsupported_media_type', message)
def rate_limited(message: str) -> ApiError:
return ApiError(429, 'rate_limited', message)
def unavailable(message: str) -> ApiError:
return ApiError(503, 'unavailable', message)
+117
View File
@@ -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()
+119
View File
@@ -0,0 +1,119 @@
"""PNG/JPEG checks that look at the header only.
Dimensions come from IHDR or a JPEG SOF marker. The compressed pixel data is never unpacked,
so a small file cannot expand into an unbounded bitmap before the pixel limit is applied.
"""
from typing import NoReturn, Optional
from .errors import payload_too_large, unsupported_media_type
MAX_UPLOAD_BYTES = 10_485_760
MAX_IMAGE_PIXELS = 40_000_000
# SOF/IHDR almost always sit in the first tens of kilobytes. The rest of the
# object is hashed and stored without being held as one Python bytes object.
INSPECT_PREFIX = 256 * 1024
_PNG = b'\x89PNG\r\n\x1a\n'
# SOF markers that carry width and height. DHT/DAC/JPG are skipped by the length field.
_JPEG_SOF = {0xC0, 0xC1, 0xC2, 0xC3, 0xC5, 0xC6, 0xC7, 0xC9, 0xCA, 0xCB, 0xCD, 0xCE, 0xCF}
class _NeedMore(Exception):
"""The prefix does not yet contain a complete PNG IHDR or JPEG SOF."""
def _reject() -> NoReturn:
raise unsupported_media_type('Файл не является PNG или JPEG')
def _check_pixels(width: int, height: int) -> None:
if width <= 0 or height <= 0:
_reject()
if width > MAX_IMAGE_PIXELS or height > MAX_IMAGE_PIXELS or width * height > MAX_IMAGE_PIXELS:
raise payload_too_large('Изображение превышает 40 миллионов пикселей')
def _png_size(data: bytes) -> str:
if len(data) < 8:
if _PNG.startswith(data):
raise _NeedMore()
_reject()
if not data.startswith(_PNG):
_reject()
if len(data) < 24:
raise _NeedMore()
if int.from_bytes(data[8:12], 'big') != 13 or data[12:16] != b'IHDR':
_reject()
width = int.from_bytes(data[16:20], 'big')
height = int.from_bytes(data[20:24], 'big')
_check_pixels(width, height)
return 'image/png'
def _jpeg_size(data: bytes) -> str:
if len(data) < 2:
if b'\xff\xd8'.startswith(data):
raise _NeedMore()
_reject()
if data[0:2] != b'\xff\xd8':
_reject()
index = 2
while index < len(data):
if data[index] != 0xFF:
_reject()
index += 1
while index < len(data) and data[index] == 0xFF:
index += 1
if index >= len(data):
raise _NeedMore()
marker = data[index]
index += 1
if marker in (0x01, 0xD8, 0xD9) or 0xD0 <= marker <= 0xD7:
if marker == 0xD9:
break
continue
if index + 2 > len(data):
raise _NeedMore()
segment_length = int.from_bytes(data[index:index + 2], 'big')
if segment_length < 2:
_reject()
if index + segment_length > len(data):
raise _NeedMore()
# Start of scan: entropy-coded bytes follow. Dimensions must already have been seen.
if marker == 0xDA:
break
if marker in _JPEG_SOF:
if segment_length < 7:
_reject()
height = int.from_bytes(data[index + 3:index + 5], 'big')
width = int.from_bytes(data[index + 5:index + 7], 'big')
_check_pixels(width, height)
return 'image/jpeg'
index += segment_length
_reject()
def inspect_prefix(data: bytes, *, complete: bool) -> Optional[str]:
"""Return image/png or image/jpeg, or None if `complete` is false and more bytes are required."""
if not data:
if complete:
_reject()
return None
try:
if data[0] == 0x89:
return _png_size(data)
if data[0] == 0xFF:
return _jpeg_size(data)
_reject()
except _NeedMore:
if complete:
_reject()
return None
def inspect_image(data: bytes) -> str:
"""Return image/png or image/jpeg after a header check. Raises 413 or 415."""
result = inspect_prefix(data, complete=True)
if result is None:
_reject()
return result
+115
View File
@@ -0,0 +1,115 @@
"""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}$')
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 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,
'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,
}
+144
View File
@@ -0,0 +1,144 @@
import asyncio
import json
import logging
import re
import uuid
from contextlib import asynccontextmanager, suppress
from pathlib import Path
from fastapi import FastAPI, Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from starlette.exceptions import HTTPException as StarletteHTTPException
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
from .outbox import relay_forever
from .routes import router
from .store import Store
logger = logging.getLogger('messenger')
_SAFE_REQUEST_ID = re.compile(r'^[A-Za-z0-9._:-]{1,128}$')
_CODES = {
400: 'invalid_request',
401: 'unauthorized',
404: 'not_found',
409: 'conflict',
413: 'payload_too_large',
415: 'unsupported_media_type',
429: 'rate_limited',
503: 'unavailable',
}
_MESSAGES = {
'invalid_request': 'Некорректный запрос',
'unauthorized': 'Требуется идентификация',
'not_found': 'Объект не найден',
'internal_error': 'Внутренняя ошибка',
}
_BEARER_CHALLENGE = 'Bearer realm="messenger"'
def _error(status: int, code: str, message: str, request_id: str, challenge: str | None = None) -> JSONResponse:
body = {'error': {'code': code, 'message': message, 'request_id': request_id}}
headers = {'X-Request-Id': request_id}
if challenge:
headers['WWW-Authenticate'] = challenge
return JSONResponse(body, status_code=status, headers=headers)
def _request_id(request: Request) -> str:
return getattr(request.state, 'request_id', None) or str(uuid.uuid4())
_OPENAPI_PATH = Path(__file__).resolve().parents[1] / 'contracts' / 'openapi.json'
@asynccontextmanager
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())
stop_relay = asyncio.Event()
relay = None
try:
await broker.connect()
app.state.broker = broker
app.state.store = Store(
pool,
settings.session_ttl_seconds,
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()
def create_app() -> FastAPI:
app = FastAPI(
title='MTUSI Messenger lab5',
version='1.5.0',
lifespan=lifespan,
)
settings = load_settings()
instance_id = settings.instance_id
app_version = settings.app_version
def openapi():
if app.openapi_schema is None:
app.openapi_schema = json.loads(_OPENAPI_PATH.read_text(encoding='utf-8'))
return app.openapi_schema
app.openapi = openapi
@app.middleware('http')
async def request_context(request: Request, call_next):
"""Gives every response, including unexpected failures, an X-Request-Id, X-Instance-Id and X-App-Version."""
incoming = request.headers.get('X-Request-Id')
request_id = incoming if incoming and _SAFE_REQUEST_ID.match(incoming) else str(uuid.uuid4())
request.state.request_id = request_id
try:
response = await call_next(request)
except Exception:
logger.exception('request %s failed: %s %s', request_id, request.method, request.url.path)
response = _error(500, 'internal_error', _MESSAGES['internal_error'], request_id)
response.headers['X-Request-Id'] = request_id
response.headers['X-Instance-Id'] = instance_id
response.headers['X-App-Version'] = app_version
return response
@app.exception_handler(ApiError)
async def handle_api_error(request: Request, exc: ApiError) -> JSONResponse:
return _error(exc.status, exc.code, exc.message, _request_id(request), exc.challenge)
@app.exception_handler(RequestValidationError)
async def handle_validation_error(request: Request, exc: RequestValidationError) -> JSONResponse:
return _error(400, 'invalid_request', _MESSAGES['invalid_request'], _request_id(request))
@app.exception_handler(StarletteHTTPException)
async def handle_http_error(request: Request, exc: StarletteHTTPException) -> JSONResponse:
code = _CODES.get(exc.status_code, 'internal_error' if exc.status_code >= 500 else 'invalid_request')
challenge = _BEARER_CHALLENGE if exc.status_code == 401 else None
return _error(exc.status_code, code, _MESSAGES.get(code, _MESSAGES['invalid_request']), _request_id(request), challenge)
app.include_router(router)
return app
app = create_app()
+64
View File
@@ -0,0 +1,64 @@
"""Apply numbered SQL files once. Run as a separate one-shot step: python -m app.migrate."""
import asyncio
import logging
from pathlib import Path
import asyncpg
from .config import load_settings
from .db import open_pool
logger = logging.getLogger('messenger')
_MIGRATIONS = Path(__file__).resolve().parents[1] / 'migrations'
# Any constant shared by all runners; serializes concurrent migrators across processes.
_LOCK_ID = 4_2026_0004
_BOOTSTRAP = """
CREATE TABLE IF NOT EXISTS schema_migrations (
version TEXT PRIMARY KEY,
applied_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp()
)
"""
def expected_versions() -> list[str]:
return sorted(path.name for path in _MIGRATIONS.glob('*.sql'))
async def apply_migrations(pool: asyncpg.Pool) -> None:
async with pool.acquire() as conn:
await conn.execute('SET statement_timeout = 0')
await conn.execute('SELECT pg_advisory_lock($1)', _LOCK_ID)
try:
await conn.execute(_BOOTSTRAP)
rows = await conn.fetch('SELECT version FROM schema_migrations')
applied = {row['version'] for row in rows}
for version in expected_versions():
if version in applied:
logger.info('migration %s already applied', version)
continue
sql = (_MIGRATIONS / version).read_text(encoding='utf-8')
async with conn.transaction():
await conn.execute(sql)
await conn.execute(
'INSERT INTO schema_migrations (version) VALUES ($1)',
version,
)
logger.info('applied migration %s', version)
finally:
await conn.execute('SELECT pg_advisory_unlock($1)', _LOCK_ID)
async def _main() -> None:
settings = load_settings()
pool = await open_pool(settings.database_url)
try:
await apply_migrations(pool)
finally:
await pool.close()
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO, format='%(levelname)s %(message)s')
asyncio.run(_main())
+206
View File
@@ -0,0 +1,206 @@
"""Private S3 bucket. Callers pass a server-generated key; the display filename never becomes one."""
from concurrent.futures import ThreadPoolExecutor
from concurrent.futures import TimeoutError as FutureTimeout
from dataclasses import dataclass
from datetime import datetime
from typing import BinaryIO, List
import boto3
from botocore.config import Config
from botocore.exceptions import BotoCoreError, ClientError
from .config import ObjectSettings
ORIGINAL_PREFIX = 'originals/'
# Docker DNS can spend several seconds on a stopped MinIO name. The HTTP handler
# must still answer inside HAProxy's one-second health check.
_POOL = ThreadPoolExecutor(max_workers=32, thread_name_prefix='s3')
class MissingObject(Exception):
"""The key is not in the bucket."""
class StorageError(Exception):
"""The object store could not complete the call. The message stays internal."""
@dataclass(frozen=True)
class StoredObject:
key: str
last_modified: datetime
size: int
@dataclass(frozen=True)
class MultipartUpload:
key: str
upload_id: str
initiated: datetime
class ObjectStore:
def __init__(self, settings: ObjectSettings) -> None:
self._bucket = settings.bucket
self._client = boto3.client(
's3',
endpoint_url=settings.endpoint,
region_name=settings.region,
aws_access_key_id=settings.access_key,
aws_secret_access_key=settings.secret_key,
config=Config(
signature_version='s3v4',
s3={'addressing_style': 'path'},
connect_timeout=1,
read_timeout=30,
retries={'max_attempts': 1},
),
)
def ready(self) -> None:
self._bounded(self._head, 0.7)
def put(self, key: str, body: bytes, content_type: str) -> None:
self._bounded(lambda: self._put_bytes(key, body, content_type), 30)
def put_stream(self, key: str, body: BinaryIO, size: int, content_type: str) -> None:
self._bounded(lambda: self._put_stream(key, body, size, content_type), 30)
def get(self, key: str) -> bytes:
return self._bounded(lambda: self._get(key), 15)
def delete(self, key: str) -> None:
self._bounded(lambda: self._delete(key), 8)
def list_originals(self, timeout: float = 15) -> List[StoredObject]:
return self._bounded(self._list_originals, timeout)
def list_multipart(self) -> List[MultipartUpload]:
return self._bounded(self._list_multipart, 15)
def abort_multipart(self, key: str, upload_id: str) -> None:
self._bounded(lambda: self._abort_multipart(key, upload_id), 8)
def _bounded(self, fn, timeout: float):
future = _POOL.submit(fn)
try:
return future.result(timeout=timeout)
except FutureTimeout:
raise StorageError() from None
def _head(self) -> None:
try:
self._client.head_bucket(Bucket=self._bucket)
except (BotoCoreError, ClientError):
raise StorageError() from None
def _put_bytes(self, key: str, body: bytes, content_type: str) -> None:
try:
self._client.put_object(
Bucket=self._bucket,
Key=key,
Body=body,
ContentType=content_type,
ContentLength=len(body),
)
except (BotoCoreError, ClientError):
raise StorageError() from None
def _put_stream(self, key: str, body: BinaryIO, size: int, content_type: str) -> None:
body.seek(0)
try:
self._client.put_object(
Bucket=self._bucket,
Key=key,
Body=body,
ContentType=content_type,
ContentLength=size,
)
except (BotoCoreError, ClientError):
raise StorageError() from None
def _get(self, key: str) -> bytes:
try:
response = self._client.get_object(Bucket=self._bucket, Key=key)
except ClientError as exc:
code = exc.response.get('Error', {}).get('Code', '')
if code in ('NoSuchKey', '404', 'NotFound'):
raise MissingObject() from None
raise StorageError() from None
except BotoCoreError:
raise StorageError() from None
payload = response['Body']
try:
return payload.read()
finally:
payload.close()
def _delete(self, key: str) -> None:
try:
self._client.delete_object(Bucket=self._bucket, Key=key)
except (BotoCoreError, ClientError):
raise StorageError() from None
def _list_originals(self) -> List[StoredObject]:
objects: List[StoredObject] = []
token = None
try:
while True:
kwargs = {'Bucket': self._bucket, 'Prefix': ORIGINAL_PREFIX}
if token:
kwargs['ContinuationToken'] = token
response = self._client.list_objects_v2(**kwargs)
for item in response.get('Contents') or ():
key = item['Key']
if not key.startswith(ORIGINAL_PREFIX) or key.endswith('/'):
continue
objects.append(StoredObject(key, item['LastModified'], int(item['Size'])))
if not response.get('IsTruncated'):
return objects
token = response.get('NextContinuationToken')
if not token:
return objects
except (BotoCoreError, ClientError):
raise StorageError() from None
def _list_multipart(self) -> List[MultipartUpload]:
uploads: List[MultipartUpload] = []
key_marker = ''
upload_marker = ''
try:
while True:
kwargs = {'Bucket': self._bucket, 'Prefix': ORIGINAL_PREFIX}
if key_marker:
kwargs['KeyMarker'] = key_marker
if upload_marker:
kwargs['UploadIdMarker'] = upload_marker
response = self._client.list_multipart_uploads(**kwargs)
for item in response.get('Uploads') or ():
key = item['Key']
if not key.startswith(ORIGINAL_PREFIX):
continue
uploads.append(MultipartUpload(key, item['UploadId'], item['Initiated']))
if not response.get('IsTruncated'):
return uploads
key_marker = response.get('NextKeyMarker') or ''
upload_marker = response.get('NextUploadIdMarker') or ''
if not key_marker and not upload_marker:
return uploads
except ClientError as exc:
code = exc.response.get('Error', {}).get('Code', '')
if code in ('NotImplemented', 'AccessDenied'):
return []
raise StorageError() from None
except BotoCoreError:
raise StorageError() from None
def _abort_multipart(self, key: str, upload_id: str) -> None:
try:
self._client.abort_multipart_upload(
Bucket=self._bucket,
Key=key,
UploadId=upload_id,
)
except (BotoCoreError, ClientError):
raise StorageError() from None
+165
View File
@@ -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)
+43
View File
@@ -0,0 +1,43 @@
import base64
import json
import re
from typing import Mapping, Optional, Tuple
from .errors import invalid_request
# Position of the last item returned to the client.
Key = Tuple[str, str]
DEFAULT_LIMIT = 50
MAX_LIMIT = 100
_LIMIT = re.compile(r'^\d{1,3}$')
def encode_cursor(scope: str, key: Key) -> str:
"""Scope binds the cursor to one resource, so a foreign cursor is detectable."""
payload = json.dumps({'s': scope, 't': key[0], 'i': key[1]}, separators=(',', ':'))
return base64.urlsafe_b64encode(payload.encode('utf-8')).decode('ascii').rstrip('=')
def decode_cursor(value: str, scope: str) -> Key:
try:
raw = base64.urlsafe_b64decode(value + '=' * (-len(value) % 4))
payload = json.loads(raw)
created_at, item_id = payload['t'], payload['i']
belongs = payload['s'] == scope
except (ValueError, TypeError, KeyError):
raise invalid_request('Некорректный cursor') from None
if not belongs or not isinstance(created_at, str) or not isinstance(item_id, str):
raise invalid_request('Cursor относится к другому запросу') from None
return created_at, item_id
def parse_page(params: Mapping[str, str], scope: str) -> Tuple[int, Optional[Key]]:
raw_limit = params.get('limit')
limit = DEFAULT_LIMIT
if raw_limit is not None:
if not _LIMIT.match(raw_limit) or not 1 <= int(raw_limit) <= MAX_LIMIT:
raise invalid_request('limit должен быть целым числом от 1 до %d' % MAX_LIMIT)
limit = int(raw_limit)
raw_cursor = params.get('cursor')
return limit, decode_cursor(raw_cursor, scope) if raw_cursor is not None else None
+27
View File
@@ -0,0 +1,27 @@
"""Argon2id password hashes. The hash never leaves this module in an API response."""
from argon2 import PasswordHasher
from argon2.exceptions import VerificationError
_hasher = PasswordHasher()
# Same cost as a real hash, so a missing user is not faster than a wrong password.
_DUMMY_HASH = _hasher.hash('not-a-user-password')
_DUMMY_PASSWORD = 'not-a-user-password'
def hash_password(password: str) -> str:
return _hasher.hash(password)
def verify_password(password_hash: str, password: str) -> bool:
try:
return _hasher.verify(password_hash, password)
except VerificationError:
return False
def password_matches(stored_hash: str | None, password: str) -> bool:
"""One Argon2 check either way. An out-of-range secret is never the stored password."""
if stored_hash is None or not 12 <= len(password) <= 128 or not password.strip():
verify_password(_DUMMY_HASH, _DUMMY_PASSWORD)
return False
return verify_password(stored_hash, password)
+130
View File
@@ -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()
+365
View File
@@ -0,0 +1,365 @@
import hashlib
import json
import logging
import os
import re
import tempfile
import uuid
from typing import BinaryIO, Optional, Sequence, Tuple, Type, TypeVar
from fastapi import APIRouter, Depends, Request
from fastapi.responses import JSONResponse
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 .fault import consume_fault
from .outbox import publish_job
from .drain import draining
from .errors import (
conflict,
invalid_request,
not_found,
payload_too_large,
unauthorized,
unavailable,
unsupported_media_type,
)
from .images import INSPECT_PREFIX, MAX_UPLOAD_BYTES, inspect_image, inspect_prefix
from .pagination import encode_cursor, parse_page
from .schemas import CreateChat, CreateMessage, CreateUser
from .store import Chat, Store, User
# Bytes kept in RAM before SpooledTemporaryFile rolls over to an ephemeral file.
# 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)
_IDEMPOTENCY_KEY = re.compile(r'[A-Za-z0-9._:-]{1,128}')
async def get_store(request: Request) -> Store:
return request.app.state.store
async def current_user(request: Request) -> User:
"""Bearer only. X-User-Id is ignored and does not identify anyone."""
token = parse_bearer(request.headers.get('Authorization', ''))
if token is None:
raise unauthorized('Требуется действительная сессия', BEARER_CHALLENGE)
user = await request.app.state.store.user_for_token(token)
if user is None:
raise unauthorized('Требуется действительная сессия', BEARER_CHALLENGE)
return user
async def read_body(request: Request, model: Type[Body]) -> Body:
try:
payload = json.loads(await request.body())
except (UnicodeDecodeError, ValueError):
raise invalid_request('Тело запроса не является корректным JSON') from None
if not isinstance(payload, dict):
raise invalid_request('Тело запроса должно быть JSON-объектом')
try:
return model.model_validate(payload)
except ValidationError:
raise invalid_request('Тело запроса не соответствует контракту') from None
def _request_hash(payload: BaseModel) -> str:
"""Key order in the client JSON does not matter: the validated body is re-serialized canonically.
CreateMessage always includes attachment_ids, so a missing field and [] are the same body.
"""
canonical = json.dumps(payload.model_dump(), sort_keys=True, separators=(',', ':'), ensure_ascii=False)
return hashlib.sha256(canonical.encode('utf-8')).hexdigest()
def _filename(value: Optional[str]) -> str:
if value is None or not value.strip() or len(value) > 255:
raise invalid_request('Некорректное filename')
if any(ord(char) < 32 or ord(char) == 127 or char in '/\\' for char in value):
raise invalid_request('Некорректное filename')
return value
def _declared_image_type(value: Optional[str]) -> str:
if not value:
raise unsupported_media_type('Требуется Content-Type image/png или image/jpeg')
media = value.split(';', 1)[0].strip().lower()
if media not in ('image/png', 'image/jpeg'):
raise unsupported_media_type('Требуется Content-Type image/png или image/jpeg')
return media
async def _spool_upload(request: Request, declared: str) -> Tuple[BinaryIO, int, str, str]:
"""Stream the body into a size-capped spool, hash it, and inspect the header.
Returns (spool, size, sha256, sniffed_type). The caller must close the spool.
One request never holds more than INSPECT_PREFIX plus _SPOOL_RAM in Python heap;
the rest, if any, is an ephemeral tempfile deleted in finally.
"""
length = request.headers.get('content-length')
if length is not None:
try:
size = int(length)
except ValueError:
raise invalid_request('Некорректный Content-Length') from None
if size > MAX_UPLOAD_BYTES:
raise payload_too_large('Файл больше 10 МиБ')
spool = tempfile.SpooledTemporaryFile(max_size=_SPOOL_RAM)
hasher = hashlib.sha256()
head = bytearray()
total = 0
sniffed: Optional[str] = None
try:
async for chunk in request.stream():
if not chunk:
continue
if total + len(chunk) > MAX_UPLOAD_BYTES:
raise payload_too_large('Файл больше 10 МиБ')
hasher.update(chunk)
spool.write(chunk)
total += len(chunk)
if len(head) < INSPECT_PREFIX:
head.extend(chunk[: INSPECT_PREFIX - len(head)])
if sniffed is None and len(head) >= 24:
sniffed = inspect_prefix(bytes(head), complete=False)
if sniffed is not None and sniffed != declared:
raise unsupported_media_type('Содержимое не соответствует Content-Type')
if sniffed is None:
sniffed = inspect_image(bytes(head))
if sniffed != declared:
raise unsupported_media_type('Содержимое не соответствует Content-Type')
spool.seek(0)
return spool, total, hasher.hexdigest(), sniffed
except BaseException:
spool.close()
raise
async def _member_chat(store: Store, chat_id: str, actor: User) -> Chat:
try:
canonical = str(uuid.UUID(chat_id))
except ValueError:
raise invalid_request('Некорректный chat_id') from None
chat = await store.find_chat(canonical, actor.id)
if chat is None:
raise not_found('Чат не найден')
return chat
def _page(items: Sequence, has_more: bool, scope: str) -> dict:
cursor: Optional[str] = None
if has_more and items:
cursor = encode_cursor(scope, (items[-1].created_at, items[-1].id))
return {'items': [item.to_dict() for item in items], 'next_cursor': cursor}
@router.get('/health/live')
async def liveness() -> JSONResponse:
return JSONResponse({'status': 'ok'})
@router.get('/health/ready')
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'})
@router.post('/api/v1/users')
async def register_user(request: Request, store: Store = Depends(get_store)) -> JSONResponse:
payload = await read_body(request, CreateUser)
user = await store.create_user(payload.username, payload.display_name, payload.password)
return JSONResponse(user.to_dict(), status_code=201)
@router.post('/api/v1/auth/sessions')
async def create_session(request: Request, store: Store = Depends(get_store)) -> JSONResponse:
parsed = parse_basic(request.headers.get('Authorization', ''))
if parsed is None:
raise unauthorized('Неверные учётные данные', BASIC_CHALLENGE)
user = await store.authenticate(*parsed)
if user is None:
raise unauthorized('Неверные учётные данные', BASIC_CHALLENGE)
token, expires_at = await store.create_session(user.id)
body = {
'token': token,
'token_type': 'Bearer',
'expires_at': expires_at,
'user': user.to_dict(),
}
return JSONResponse(body, status_code=201)
@router.delete('/api/v1/auth/sessions/current')
async def revoke_session(request: Request, actor: User = Depends(current_user)) -> Response:
token = parse_bearer(request.headers.get('Authorization', ''))
if token is None or not await request.app.state.store.revoke_session(token):
raise unauthorized('Требуется действительная сессия', BEARER_CHALLENGE)
return Response(status_code=204)
@router.get('/api/v1/users/me')
async def show_current_user(actor: User = Depends(current_user)) -> JSONResponse:
return JSONResponse(actor.to_dict())
@router.post('/api/v1/chats')
async def create_chat(
request: Request,
actor: User = Depends(current_user),
store: Store = Depends(get_store),
) -> JSONResponse:
payload = await read_body(request, CreateChat)
if actor.id not in payload.member_ids:
raise invalid_request('Создатель чата должен быть указан в member_ids')
chat = await store.create_chat(payload.title, payload.member_ids)
return JSONResponse(chat.to_dict(), status_code=201)
@router.get('/api/v1/chats')
async def list_chats(
request: Request,
actor: User = Depends(current_user),
store: Store = Depends(get_store),
) -> JSONResponse:
scope = 'chats:' + actor.id
limit, after = parse_page(request.query_params, scope)
chats, has_more = await store.list_chats(actor.id, limit, after)
return JSONResponse(_page(chats, has_more, scope))
@router.get('/api/v1/chats/{chat_id}')
async def show_chat(
chat_id: str,
actor: User = Depends(current_user),
store: Store = Depends(get_store),
) -> JSONResponse:
return JSONResponse((await _member_chat(store, chat_id, actor)).to_dict())
@router.post('/api/v1/chats/{chat_id}/messages')
async def send_message(
chat_id: str,
request: Request,
actor: User = Depends(current_user),
store: Store = Depends(get_store),
) -> JSONResponse:
chat = await _member_chat(store, chat_id, actor)
payload = await read_body(request, CreateMessage)
key = request.headers.get('Idempotency-Key')
if key is None or not _IDEMPOTENCY_KEY.fullmatch(key):
raise invalid_request('Требуется корректный Idempotency-Key')
message = await store.add_message(
chat.id,
actor.id,
payload.text,
payload.attachment_ids,
path='/api/v1/chats/%s/messages' % chat.id,
key=key,
request_hash=_request_hash(payload),
)
return JSONResponse(message.to_dict(), status_code=201)
@router.post('/api/v1/chats/{chat_id}/attachments')
async def upload_attachment(
chat_id: str,
request: Request,
actor: User = Depends(current_user),
store: Store = Depends(get_store),
) -> JSONResponse:
chat = await _member_chat(store, chat_id, actor)
filename = _filename(request.query_params.get('filename'))
declared = _declared_image_type(request.headers.get('content-type'))
spool = None
try:
spool, size, digest, actual = await _spool_upload(request, declared)
queued = await store.create_attachment(
chat.id,
actor.id,
filename,
actual,
spool,
size,
digest,
)
finally:
if spool is not None:
spool.close()
# 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 publish_job(store.pool, request.app.state.broker, queued.job_id)
except BrokerDown:
logger.warning('upload %s is committed and waits in the outbox', queued.attachment.id)
return JSONResponse(queued.attachment.to_dict(), status_code=202)
def _variant(request: Request) -> str:
raw = request.query_params.get('variant')
variant = 'original' if raw is None else raw
if variant not in ('original', 'thumbnail', 'crop', 'optimized'):
raise invalid_request('Некорректный variant')
return variant
@router.get('/api/v1/attachments/{attachment_id}')
async def show_attachment(
attachment_id: str,
actor: User = Depends(current_user),
store: Store = Depends(get_store),
) -> JSONResponse:
attachment = await store.find_attachment(attachment_id, actor.id)
if attachment is None:
raise not_found('Вложение не найдено')
return JSONResponse(attachment.to_dict())
@router.get('/api/v1/attachments/{attachment_id}/content')
async def download_attachment(
attachment_id: str,
request: Request,
actor: User = Depends(current_user),
store: Store = Depends(get_store),
) -> Response:
variant = _variant(request)
attachment = await store.find_attachment(attachment_id, actor.id)
if attachment is None:
raise not_found('Вложение не найдено')
if attachment.status != 'ready':
raise conflict('Вложение ещё не готово')
found = await store.read_content(attachment_id, actor.id, variant)
if found is None:
raise not_found('Вариант не найден' if variant != 'original' else 'Вложение не найдено')
content_type, body = found
return Response(content=body, media_type=content_type)
@router.get('/api/v1/chats/{chat_id}/messages')
async def list_messages(
chat_id: str,
request: Request,
actor: User = Depends(current_user),
store: Store = Depends(get_store),
) -> JSONResponse:
chat = await _member_chat(store, chat_id, actor)
scope = 'messages:' + chat.id
limit, after = parse_page(request.query_params, scope)
messages, has_more = await store.list_messages(chat.id, limit, after)
return JSONResponse(_page(messages, has_more, scope))
+73
View File
@@ -0,0 +1,73 @@
"""Request bodies. The contract forbids unknown fields, wrong types and blank strings."""
import uuid
from typing import List
from pydantic import AfterValidator, BaseModel, ConfigDict, Field, field_validator, model_validator
from typing_extensions import Annotated
def _not_blank(value: str) -> str:
if not value.strip():
raise ValueError('value must not be whitespace only')
return value
def _canonical_uuid(value: str) -> str:
parsed = uuid.UUID(value)
if str(parsed) != value.lower():
raise ValueError('value must be a canonical UUID')
return str(parsed)
Username = Annotated[str, Field(pattern=r'^[a-z0-9_]{3,32}$')]
DisplayName = Annotated[str, Field(min_length=1, max_length=100), AfterValidator(_not_blank)]
Title = Annotated[str, Field(min_length=1, max_length=100), AfterValidator(_not_blank)]
Password = Annotated[str, Field(min_length=12, max_length=128), AfterValidator(_not_blank)]
UserId = Annotated[str, AfterValidator(_canonical_uuid)]
class CreateUser(BaseModel):
model_config = ConfigDict(extra='forbid')
username: Username
display_name: DisplayName
password: Password
class CreateChat(BaseModel):
model_config = ConfigDict(extra='forbid')
title: Title
member_ids: Annotated[List[UserId], Field(min_length=1, max_length=100)]
@field_validator('member_ids')
@classmethod
def _unique(cls, value: List[str]) -> List[str]:
if len(set(value)) != len(value):
raise ValueError('member_ids must be unique')
return value
class CreateMessage(BaseModel):
"""text is required. attachment_ids defaults to [], so a lab3 body {"text": "..."} stays valid.
A blank text is accepted only together with at least one attachment.
"""
model_config = ConfigDict(extra='forbid')
text: Annotated[str, Field(max_length=4000)]
attachment_ids: Annotated[List[UserId], Field(default_factory=list, max_length=10)]
@field_validator('attachment_ids')
@classmethod
def _unique_attachments(cls, value: List[str]) -> List[str]:
if len(set(value)) != len(value):
raise ValueError('attachment_ids must be unique')
return value
@model_validator(mode='after')
def _has_content(self) -> 'CreateMessage':
if not self.text.strip() and not self.attachment_ids:
raise ValueError('text or attachment_ids is required')
return self
+101
View File
@@ -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
+903
View File
@@ -0,0 +1,903 @@
import asyncio
import hashlib
import json
import logging
import secrets
import threading
import uuid
from dataclasses import dataclass
from datetime import datetime, timedelta, timezone
from typing import BinaryIO, Dict, List, Optional, Sequence, Tuple
import asyncpg
from .config import job_max_attempts, max_inflight_jobs
from .errors import conflict, invalid_request, not_found, rate_limited, unavailable
from .jobs import PIPELINE_VERSION, original_key, staging_key
from .migrate import expected_versions
from .objects import MissingObject, ObjectStore, StorageError
from .pagination import Key
from .passwords import hash_password, password_matches
logger = logging.getLogger('messenger')
@dataclass(frozen=True)
class User:
id: str
username: str
display_name: str
created_at: str
def to_dict(self) -> dict:
return {
'id': self.id,
'username': self.username,
'display_name': self.display_name,
'created_at': self.created_at,
}
@dataclass(frozen=True)
class Chat:
id: str
title: str
member_ids: Tuple[str, ...]
created_at: str
def to_dict(self) -> dict:
return {
'id': self.id,
'title': self.title,
'member_ids': list(self.member_ids),
'created_at': self.created_at,
}
@dataclass(frozen=True)
class Message:
id: str
chat_id: str
sender_id: str
text: str
created_at: str
attachment_ids: Tuple[str, ...] = ()
def to_dict(self) -> dict:
return {
'id': self.id,
'chat_id': self.chat_id,
'sender_id': self.sender_id,
'text': self.text,
'created_at': self.created_at,
'attachment_ids': list(self.attachment_ids),
}
@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
chat_id: str
owner_id: str
filename: str
content_type: str
size_bytes: int
sha256: str
status: str
created_at: str
updated_at: str
variants: Tuple[Variant, ...] = ()
error_code: Optional[str] = None
def to_dict(self) -> dict:
return {
'id': self.id,
'chat_id': self.chat_id,
'owner_id': self.owner_id,
'filename': self.filename,
'content_type': self.content_type,
'size_bytes': self.size_bytes,
'sha256': self.sha256,
'status': self.status,
'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
job_id: str
@dataclass(frozen=True)
class AttachmentRef:
"""One metadata row as the reconciler sees it. Not an API response."""
id: str
object_key: str
created_at: datetime
in_use: bool
sha256: str
def _token_key(token: str) -> str:
return hashlib.sha256(token.encode('utf-8')).hexdigest()
def _stamp(moment: datetime) -> str:
return moment.astimezone(timezone.utc).isoformat(timespec='microseconds').replace('+00:00', 'Z')
def _parse_stamp(value: str) -> datetime:
if value.endswith('Z'):
value = value[:-1] + '+00:00'
return datetime.fromisoformat(value)
def _user(row: asyncpg.Record) -> User:
return User(str(row['id']), row['username'], row['display_name'], _stamp(row['created_at']))
def _as_uuid(value: str, message: str) -> uuid.UUID:
try:
return uuid.UUID(value)
except ValueError:
raise invalid_request(message) from None
def _db_down(exc: BaseException) -> bool:
return isinstance(exc, (
asyncpg.PostgresConnectionError,
asyncpg.InterfaceError,
asyncpg.CannotConnectNowError,
OSError,
TimeoutError,
))
class Store:
"""PostgreSQL holds users, chats, sessions, messages and attachment metadata.
Original bytes are in the private bucket. Any replica can read them by the server-assigned key.
"""
def __init__(
self,
pool: asyncpg.Pool,
session_ttl_seconds: int = 3600,
idempotency_ttl_seconds: int = 86400,
*,
objects: ObjectStore,
) -> None:
self._pool = pool
self._objects = objects
self._session_ttl = timedelta(seconds=session_ttl_seconds)
self._idempotency_ttl = timedelta(seconds=idempotency_ttl_seconds)
self._lock = threading.Lock()
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:
moment = datetime.now(timezone.utc)
if self._last_moment is not None and moment <= self._last_moment:
moment = self._last_moment + timedelta(microseconds=1)
self._last_moment = moment
return moment
async def ready(self) -> None:
"""Ready when PostgreSQL has this build's schema and the private bucket answers."""
try:
async with self._pool.acquire() as conn:
applied = await conn.fetchval(
'SELECT count(*) FROM schema_migrations WHERE version = ANY($1::text[])',
self._migrations,
)
except Exception:
raise unavailable('Хранилище недоступно') from None
if applied != len(self._migrations):
raise unavailable('Схема БД ещё не применена')
try:
await asyncio.to_thread(self._objects.ready)
except StorageError:
raise unavailable('Хранилище недоступно') from None
async def create_user(self, username: str, display_name: str, password: str) -> User:
password_hash = hash_password(password)
user_id = uuid.uuid4()
created = self._now()
try:
async with self._pool.acquire() as conn:
await conn.execute(
'''
INSERT INTO users (id, username, display_name, password_hash, created_at)
VALUES ($1, $2, $3, $4, $5)
''',
user_id,
username,
display_name,
password_hash,
created,
)
except asyncpg.UniqueViolationError:
raise conflict('Username уже занят') from None
return User(str(user_id), username, display_name, _stamp(created))
async def authenticate(self, username: str, password: str) -> Optional[User]:
try:
async with self._pool.acquire() as conn:
row = await conn.fetchrow(
'''
SELECT id, username, display_name, created_at, password_hash
FROM users
WHERE username = $1
''',
username,
)
except Exception as exc:
if _db_down(exc):
raise unavailable('Хранилище недоступно') from None
raise
stored_hash = row['password_hash'] if row is not None else None
if not password_matches(stored_hash, password) or row is None:
return None
return _user(row)
async def create_session(self, user_id: str) -> Tuple[str, str]:
token = secrets.token_urlsafe(32)
expires = datetime.now(timezone.utc) + self._session_ttl
try:
async with self._pool.acquire() as conn:
await conn.execute(
'INSERT INTO sessions (token_hash, user_id, expires_at) VALUES ($1, $2, $3)',
_token_key(token),
_as_uuid(user_id, 'Некорректный user_id'),
expires,
)
except Exception as exc:
if _db_down(exc):
raise unavailable('Хранилище недоступно') from None
raise
return token, _stamp(expires)
async def user_for_token(self, token: str) -> Optional[User]:
now = datetime.now(timezone.utc)
key = _token_key(token)
try:
async with self._pool.acquire() as conn:
row = await conn.fetchrow(
'''
SELECT u.id, u.username, u.display_name, u.created_at, s.expires_at
FROM sessions s
JOIN users u ON u.id = s.user_id
WHERE s.token_hash = $1
''',
key,
)
if row is None:
return None
if row['expires_at'] <= now:
await conn.execute('DELETE FROM sessions WHERE token_hash = $1', key)
return None
return _user(row)
except Exception as exc:
if _db_down(exc):
raise unavailable('Хранилище недоступно') from None
raise
async def revoke_session(self, token: str) -> bool:
try:
async with self._pool.acquire() as conn:
row = await conn.fetchrow(
'''
DELETE FROM sessions
WHERE token_hash = $1 AND expires_at > $2
RETURNING token_hash
''',
_token_key(token),
datetime.now(timezone.utc),
)
except Exception as exc:
if _db_down(exc):
raise unavailable('Хранилище недоступно') from None
raise
return row is not None
async def create_chat(self, title: str, member_ids: Sequence[str]) -> Chat:
ids = [_as_uuid(member_id, 'Некорректный user_id') for member_id in member_ids]
chat_id = uuid.uuid4()
created = self._now()
async with self._pool.acquire() as conn:
async with conn.transaction():
found = await conn.fetch('SELECT id FROM users WHERE id = ANY($1::uuid[])', ids)
if len(found) != len(ids):
raise invalid_request('Все участники должны быть существующими пользователями')
await conn.execute(
'INSERT INTO chats (id, title, created_at) VALUES ($1, $2, $3)',
chat_id,
title,
created,
)
await conn.execute(
'''
INSERT INTO chat_members (chat_id, user_id, position)
SELECT $1, member_id, (ordinality - 1)::integer
FROM unnest($2::uuid[]) WITH ORDINALITY AS members(member_id, ordinality)
''',
chat_id,
ids,
)
return Chat(str(chat_id), title, tuple(member_ids), _stamp(created))
async def find_chat(self, chat_id: str, member_id: str) -> Optional[Chat]:
"""A chat of somebody else is indistinguishable from a missing one."""
chat_uuid = _as_uuid(chat_id, 'Некорректный chat_id')
member_uuid = _as_uuid(member_id, 'Некорректный user_id')
async with self._pool.acquire() as conn:
row = await conn.fetchrow(
'''
SELECT c.id, c.title, c.created_at
FROM chats c
JOIN chat_members mine ON mine.chat_id = c.id AND mine.user_id = $2
WHERE c.id = $1
''',
chat_uuid,
member_uuid,
)
if row is None:
return None
members = await self._members(conn, [chat_uuid])
return Chat(str(row['id']), row['title'], members.get(chat_uuid, ()), _stamp(row['created_at']))
async def list_chats(self, member_id: str, limit: int, after: Optional[Key]) -> Tuple[List[Chat], bool]:
member_uuid = _as_uuid(member_id, 'Некорректный user_id')
after_at, after_id = self._cursor(after)
async with self._pool.acquire() as conn:
if after_at is None:
rows = await conn.fetch(
'''
SELECT c.id, c.title, c.created_at
FROM chats c
JOIN chat_members mine ON mine.chat_id = c.id AND mine.user_id = $1
ORDER BY c.created_at, c.id
LIMIT $2
''',
member_uuid,
limit + 1,
)
else:
rows = await conn.fetch(
'''
SELECT c.id, c.title, c.created_at
FROM chats c
JOIN chat_members mine ON mine.chat_id = c.id AND mine.user_id = $1
WHERE (c.created_at, c.id) > ($2::timestamptz, $3::uuid)
ORDER BY c.created_at, c.id
LIMIT $4
''',
member_uuid,
after_at,
after_id,
limit + 1,
)
page = rows[:limit]
members = await self._members(conn, [row['id'] for row in page])
chats = [
Chat(str(row['id']), row['title'], members.get(row['id'], ()), _stamp(row['created_at']))
for row in page
]
return chats, len(rows) > limit
async def create_attachment(
self,
chat_id: str,
owner_id: str,
filename: str,
content_type: str,
body: BinaryIO,
size_bytes: int,
sha256: str,
) -> QueuedUpload:
chat_uuid = _as_uuid(chat_id, 'Некорректный chat_id')
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 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()
# Reject before the object is stored when the cap is already reached.
# The transaction below locks and counts again, so concurrent uploads cannot all slip in.
if await self._inflight_jobs() >= max_inflight_jobs():
raise rate_limited('Очередь заполнена, новая работа не принята')
try:
await asyncio.to_thread(self._objects.put_stream, staged, body, size_bytes, content_type)
except StorageError:
await self._discard_object(staged)
raise unavailable('Хранилище недоступно') from None
try:
async with self._pool.acquire() as conn:
async with conn.transaction():
await self._admit_job(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
)
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,
)
except Exception:
await self._discard_object(staged)
raise
stamp = _stamp(created)
attachment = Attachment(
str(attachment_id),
str(chat_uuid),
str(owner_uuid),
filename,
content_type,
size_bytes,
sha256,
'queued',
stamp,
stamp,
)
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.
The reconciler uses this instead of the HTTP API. A row linked from
message_attachments must survive even when the object is gone: the
foreign key has no ON DELETE CASCADE, and the message would lose its file.
"""
async with self._pool.acquire() as conn:
rows = await conn.fetch(
'''
SELECT a.id, a.object_key, a.created_at, a.sha256,
EXISTS (
SELECT 1 FROM message_attachments m
WHERE m.attachment_id = a.id
) AS in_use
FROM attachments a
'''
)
return [
AttachmentRef(
str(row['id']),
row['object_key'],
row['created_at'],
bool(row['in_use']),
row['sha256'],
)
for row in rows
]
async def object_key_referenced(self, object_key: str) -> bool:
"""True when a metadata row owns this key. Checked again immediately before delete."""
async with self._pool.acquire() as conn:
found = await conn.fetchval(
'SELECT 1 FROM attachments WHERE object_key = $1',
object_key,
)
return found is not None
async def delete_attachment_if_unlinked(self, attachment_id: str, created_before: datetime) -> bool:
"""Delete a stale row that no message references. A link or a young row keeps it.
`created_before` is the scan clock minus grace, so the row deleted here is the
same row the scan classified as stale. The originals/ predicate matches the
prefix the reconciler is allowed to own.
"""
async with self._pool.acquire() as conn:
result = await conn.execute(
'''
DELETE FROM attachments
WHERE id = $1
AND object_key LIKE 'originals/%'
AND created_at <= $2
AND NOT EXISTS (
SELECT 1 FROM message_attachments WHERE attachment_id = $1
)
''',
_as_uuid(attachment_id, 'Некорректный attachment_id'),
created_before,
)
return result == 'DELETE 1'
async def rewind_attachment_created_at(self, attachment_id: str, created_at: datetime) -> None:
"""Move one row's clock back. The track-2 experiment uses this to age a fixture."""
async with self._pool.acquire() as conn:
result = await conn.execute(
'UPDATE attachments SET created_at = $2 WHERE id = $1',
_as_uuid(attachment_id, 'Некорректный attachment_id'),
created_at,
)
if result != 'UPDATE 1':
raise RuntimeError('attachment row missing')
async def find_attachment(self, attachment_id: str, user_id: str) -> Optional[Attachment]:
"""Metadata for a chat member. Missing and foreign attachments are both absent."""
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.id, a.chat_id, a.owner_id, a.filename, a.content_type,
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
''',
attachment_uuid,
user_uuid,
)
variants = () if row is None else await self._variants(conn, attachment_uuid)
if row is None:
return None
return Attachment(
str(row['id']),
str(row['chat_id']),
str(row['owner_id']),
row['filename'],
row['content_type'],
row['size_bytes'],
row['sha256'],
row['status'],
_stamp(row['created_at']),
_stamp(row['updated_at']),
variants,
row['error_code'],
)
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:
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:
body = await asyncio.to_thread(self._objects.get, row['object_key'])
except MissingObject:
return None
except StorageError:
raise unavailable('Хранилище недоступно') from None
if len(body) != row['size_bytes'] or hashlib.sha256(body).hexdigest() != row['sha256']:
logger.warning('object bytes do not match attachment metadata')
raise unavailable('Хранилище недоступно')
return row['content_type'], body
async def _inflight_jobs(self) -> int:
async with self._pool.acquire() as conn:
value = await conn.fetchval(
"SELECT count(*)::int FROM attachments WHERE status IN ('queued', 'processing')"
)
return int(value or 0)
async def _admit_job(self, conn) -> None:
"""One lock for the cap. Held only until this transaction commits or rolls back."""
await conn.execute('SELECT pg_advisory_xact_lock($1)', 48151)
inflight = await conn.fetchval(
"SELECT count(*)::int FROM attachments WHERE status IN ('queued', 'processing')"
)
if int(inflight or 0) >= max_inflight_jobs():
raise rate_limited('Очередь заполнена, новая работа не принята')
async def _discard_object(self, object_key: str) -> None:
try:
await asyncio.to_thread(self._objects.delete, object_key)
except StorageError:
logger.warning('object left in the bucket after a failed metadata write')
async def add_message(
self,
chat_id: str,
sender_id: str,
text: str,
attachment_ids: Sequence[str],
*,
path: str,
key: str,
request_hash: str,
) -> Message:
"""Exactly one message per (sender, POST, path, key), whichever replica receives the request.
Concurrent duplicates block on the primary key of idempotency_keys until the first
transaction commits or rolls back, so a rolled-back attempt leaves the key free.
"""
chat_uuid = _as_uuid(chat_id, 'Некорректный chat_id')
sender_uuid = _as_uuid(sender_id, 'Некорректный user_id')
linked = tuple(_as_uuid(item, 'Некорректный attachment_id') for item in attachment_ids)
message = Message(
str(uuid.uuid4()),
str(chat_uuid),
sender_id,
text,
_stamp(self._now()),
tuple(str(item) for item in linked),
)
cutoff = datetime.now(timezone.utc) - self._idempotency_ttl
async with self._pool.acquire() as conn:
async with conn.transaction():
await conn.execute(
'''
DELETE FROM idempotency_keys
WHERE user_id = $1 AND method = 'POST' AND path = $2 AND key = $3 AND created_at < $4
''',
sender_uuid,
path,
key,
cutoff,
)
claimed = await conn.fetchval(
'''
INSERT INTO idempotency_keys (user_id, method, path, key, request_hash, status_code, response)
VALUES ($1, 'POST', $2, $3, $4, 201, $5::jsonb)
ON CONFLICT (user_id, method, path, key) DO NOTHING
RETURNING 1
''',
sender_uuid,
path,
key,
request_hash,
json.dumps(message.to_dict()),
)
if claimed is None:
return await self._replay(conn, sender_uuid, path, key, request_hash)
if linked:
rows = await conn.fetch(
'SELECT id, chat_id, status FROM attachments WHERE id = ANY($1::uuid[])',
list(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)
VALUES ($1, $2, $3, $4, $5)
''',
uuid.UUID(message.id),
chat_uuid,
sender_uuid,
text,
_parse_stamp(message.created_at),
)
if linked:
await conn.executemany(
'''
INSERT INTO message_attachments (message_id, attachment_id, position)
VALUES ($1, $2, $3)
''',
[(uuid.UUID(message.id), item, index) for index, item in enumerate(linked)],
)
return message
async def _replay(
self,
conn: asyncpg.Connection,
sender_uuid: uuid.UUID,
path: str,
key: str,
request_hash: str,
) -> Message:
row = await conn.fetchrow(
'''
SELECT request_hash, response
FROM idempotency_keys
WHERE user_id = $1 AND method = 'POST' AND path = $2 AND key = $3
''',
sender_uuid,
path,
key,
)
if row is None:
raise unavailable('Повторите запрос с тем же Idempotency-Key')
if row['request_hash'] != request_hash:
raise conflict('Idempotency-Key уже использован с другим сообщением')
data = json.loads(row['response'])
return Message(
data['id'],
data['chat_id'],
data['sender_id'],
data['text'],
data['created_at'],
tuple(data.get('attachment_ids') or ()),
)
async def list_messages(self, chat_id: str, limit: int, after: Optional[Key]) -> Tuple[List[Message], bool]:
chat_uuid = _as_uuid(chat_id, 'Некорректный chat_id')
after_at, after_id = self._cursor(after)
async with self._pool.acquire() as conn:
if after_at is None:
rows = await conn.fetch(
'''
SELECT id, chat_id, sender_id, text, created_at
FROM messages
WHERE chat_id = $1
ORDER BY created_at, id
LIMIT $2
''',
chat_uuid,
limit + 1,
)
else:
rows = await conn.fetch(
'''
SELECT id, chat_id, sender_id, text, created_at
FROM messages
WHERE chat_id = $1
AND (created_at, id) > ($2::timestamptz, $3::uuid)
ORDER BY created_at, id
LIMIT $4
''',
chat_uuid,
after_at,
after_id,
limit + 1,
)
page = rows[:limit]
links = await self._attachment_ids(conn, [row['id'] for row in page])
messages = [
Message(
str(row['id']),
str(row['chat_id']),
str(row['sender_id']),
row['text'],
_stamp(row['created_at']),
links.get(row['id'], ()),
)
for row in page
]
return messages, len(rows) > limit
async def _attachment_ids(
self,
conn: asyncpg.Connection,
message_ids: Sequence[uuid.UUID],
) -> Dict[uuid.UUID, Tuple[str, ...]]:
if not message_ids:
return {}
rows = await conn.fetch(
'''
SELECT message_id, attachment_id
FROM message_attachments
WHERE message_id = ANY($1::uuid[])
ORDER BY message_id, position
''',
list(message_ids),
)
grouped: Dict[uuid.UUID, List[str]] = {}
for row in rows:
grouped.setdefault(row['message_id'], []).append(str(row['attachment_id']))
return {message_id: tuple(ids) for message_id, ids in grouped.items()}
async def _members(self, conn: asyncpg.Connection, chat_ids: Sequence[uuid.UUID]) -> Dict[uuid.UUID, Tuple[str, ...]]:
if not chat_ids:
return {}
rows = await conn.fetch(
'''
SELECT chat_id, user_id
FROM chat_members
WHERE chat_id = ANY($1::uuid[])
ORDER BY chat_id, position
''',
list(chat_ids),
)
grouped: Dict[uuid.UUID, List[str]] = {}
for row in rows:
grouped.setdefault(row['chat_id'], []).append(str(row['user_id']))
return {chat_id: tuple(member_ids) for chat_id, member_ids in grouped.items()}
def _cursor(self, after: Optional[Key]) -> Tuple[Optional[datetime], Optional[uuid.UUID]]:
if after is None:
return None, None
try:
return _parse_stamp(after[0]), uuid.UUID(after[1])
except ValueError:
raise invalid_request('Некорректный cursor') from None
+155
View File
@@ -0,0 +1,155 @@
"""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 Dict, Tuple
from PIL import Image, ImageOps, UnidentifiedImageError
from .errors import ApiError
from .images import MAX_IMAGE_PIXELS, MAX_UPLOAD_BYTES, inspect_image
THUMBNAIL_BOX = 256
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):
"""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 _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:
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()
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, MemoryError):
raise ImageRejected() from None
finally:
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'])
+587
View File
@@ -0,0 +1,587 @@
"""Separate process: publish the staged original and the level-4 variants.
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, timedelta, timezone
from pathlib import Path
import asyncpg
from .broker import Broker, BrokerDown
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 .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 _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:
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:
rendered = render_variants(data)
except ImageRejected:
raise PermanentJobError('invalid_image') from None
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 _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():
status = await conn.fetchval(
'SELECT status FROM attachments WHERE id = $1 FOR UPDATE',
attachment_id,
)
if status == 'ready':
return
await conn.execute(
'''
UPDATE attachments
SET status = 'failed', error_code = $2, updated_at = clock_timestamp()
WHERE id = $1 AND status = 'processing'
''',
attachment_id,
code,
)
await _record_failure(conn, job, code, permanent)
await conn.execute(
'''
UPDATE attachment_jobs
SET lease_until = NULL, last_error = $2, updated_at = clock_timestamp()
WHERE id = $1
''',
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 = 'queued', error_code = NULL, updated_at = clock_timestamp()
WHERE id = $1 AND status = 'processing'
''',
attachment_id,
)
logger.info('attachment %s attempt %s will retry in %.3fs (%s)', job['attachment_id'], job['attempt'], delay, code)
return True
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))
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
''',
job_id,
)
if row is None or row['status'] in ('ready', 'failed'):
return
if job['attempt'] != row['attempt']:
# A newer attempt is already in the outbox, or this delivery is stale.
return
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'],
)
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
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))
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, lease_seconds, timeout)
async def _alive(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 _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')
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)
# Imported for the side effect of validating the pool settings the API also uses.
load_settings()
job_max_attempts()
timeout = job_timeout_seconds()
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())
alive = asyncio.create_task(_alive(stop))
maintain = None
try:
await broker.connect()
# 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, lease_seconds, timeout)
except BrokerDown:
async with _ACK_LOCK:
await message.nack(requeue=True)
return
except Exception:
logger.exception('job was not finished')
async with _ACK_LOCK:
await message.nack(requeue=True)
return
else:
async with _ACK_LOCK:
await message.ack()
finally:
_inflight -= 1
consumer = await queue.consume(on_message)
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)
for _ in range(500):
if _inflight == 0:
break
await asyncio.sleep(0.05)
finally:
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())
if __name__ == '__main__':
main()
+379
View File
@@ -0,0 +1,379 @@
# Client -> lb (HAProxy) -> api x API_REPLICAS -> postgres + minio + rabbitmq.
# 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
x-db-client: &db-client
APP_ENV: ${APP_ENV:-lab}
LOG_LEVEL: ${LOG_LEVEL:-info}
DB_HOST: postgres
DB_USER: ${POSTGRES_USER:?set in .env}
DB_NAME: ${POSTGRES_DB:?set in .env}
DB_PASSWORD_FILE: /run/secrets/postgres_password
x-app-build: &app-build
context: .
dockerfile: Dockerfile
args:
APP_VERSION: ${APP_VERSION:-dev}
services:
postgres:
image: postgres:16.10-alpine@sha256:029660641a0cfc575b14f336ba448fb8a75fd595d42e1fa316b9fb4378742297
environment:
POSTGRES_USER: ${POSTGRES_USER}
POSTGRES_PASSWORD_FILE: /run/secrets/postgres_password
POSTGRES_DB: ${POSTGRES_DB}
secrets:
- postgres_password
volumes:
- pgdata:/var/lib/postgresql/data
networks:
- data
healthcheck:
test: ["CMD-SHELL", 'pg_isready -U "$$POSTGRES_USER" -d "$$POSTGRES_DB"']
interval: 2s
timeout: 5s
retries: 30
deploy:
resources:
limits:
cpus: "${POSTGRES_CPUS:-1.0}"
memory: "${POSTGRES_MEMORY:-512M}"
reservations:
cpus: "0.25"
memory: 256M
restart: unless-stopped
# One-shot schema step. Replicas never migrate on startup, so there is no race between them;
# an advisory lock additionally serializes accidental parallel runs.
migrate:
image: messenger-lab5-app:${APP_VERSION:-dev}
build: *app-build
command: ["python", "-m", "app.migrate"]
environment:
<<: *db-client
secrets:
- source: postgres_password
uid: "10001"
gid: "10001"
mode: 0400
networks:
- data
depends_on:
postgres:
condition: service_healthy
deploy:
resources:
limits:
cpus: "0.5"
memory: 128M
restart: "no"
# MinIO Community RELEASE.2025-09-07T16-13-09Z. The digest is the official
# multi-arch manifest list (linux/amd64 inside it is sha256:a1a8bd4a…).
# docker.io/minio/minio and quay.io/minio/minio no longer allow an anonymous
# pull; this GHCR mirror still serves that same manifest list.
# No host ports. MINIO_BROWSER=off: the admin console is not started.
# S3 API is http://minio:9000, also http://s3:9000 (network alias).
minio:
image: ghcr.io/tsouza/cerberus-mirror/minio/minio:RELEASE.2025-09-07T16-13-09Z@sha256:14cea493d9a34af32f524e538b8346cf79f3321eff8e708c1e2960462bd8936e
command: ["server", "/data"]
environment:
MINIO_ROOT_USER_FILE: /run/secrets/minio_root_user
MINIO_ROOT_PASSWORD_FILE: /run/secrets/minio_root_password
MINIO_BROWSER: "off"
MINIO_UPDATE: "off"
secrets:
- minio_root_user
- minio_root_password
volumes:
- miniodata:/data
networks:
data:
aliases:
- s3
healthcheck:
test: ["CMD", "curl", "-fsS", "http://127.0.0.1:9000/minio/health/ready"]
interval: 2s
timeout: 5s
retries: 30
start_period: 10s
deploy:
resources:
limits:
cpus: "${MINIO_CPUS:-1.0}"
memory: "${MINIO_MEMORY:-512M}"
reservations:
cpus: "0.25"
memory: 256M
restart: unless-stopped
# Creates the private bucket and the bucket-scoped API user. Re-running is a no-op.
minio-init:
image: ghcr.io/tsouza/cerberus-mirror/minio/minio:RELEASE.2025-09-07T16-13-09Z@sha256:14cea493d9a34af32f524e538b8346cf79f3321eff8e708c1e2960462bd8936e
entrypoint: ["/bin/sh", "/bootstrap/minio-bootstrap.sh"]
environment:
S3_BUCKET: ${S3_BUCKET:?set in .env}
S3_REGION: ${S3_REGION:-us-east-1}
MINIO_ENDPOINT: http://minio:9000
secrets:
- minio_root_user
- minio_root_password
- s3_access_key_id
- s3_secret_access_key
volumes:
- ./infra/minio/bootstrap.sh:/bootstrap/minio-bootstrap.sh:ro
networks:
- data
depends_on:
minio:
condition: service_healthy
deploy:
resources:
limits:
cpus: "0.5"
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
deploy:
replicas: ${API_REPLICAS:-2}
resources:
limits:
cpus: "${API_CPUS:-1.0}"
memory: "${API_MEMORY:-256M}"
reservations:
cpus: "0.25"
memory: 128M
environment:
<<: *db-client
APP_HOST: 0.0.0.0
APP_PORT: "8080"
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600}
IDEMPOTENCY_TTL_SECONDS: ${IDEMPOTENCY_TTL_SECONDS:-86400}
DRAIN_SECONDS: ${DRAIN_SECONDS:-4}
SHUTDOWN_TIMEOUT_SECONDS: ${SHUTDOWN_TIMEOUT_SECONDS:-3}
DB_POOL_MIN: ${DB_POOL_MIN:-1}
DB_POOL_MAX: ${DB_POOL_MAX:-10}
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}
# queued + processing. Past this, upload is 429 and the bytes are not stored.
MAX_INFLIGHT_JOBS: ${MAX_INFLIGHT_JOBS:-20}
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:
- edge
- data
expose:
- "8080"
depends_on:
postgres:
condition: service_healthy
migrate:
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:
- CMD
- python
- -c
- import urllib.request; urllib.request.urlopen('http://127.0.0.1:8080/health/ready', timeout=2)
interval: 3s
timeout: 3s
retries: 3
start_period: 20s
# SIGTERM -> readiness 503 for DRAIN_SECONDS (LB drops the replica in <= 3 s) -> uvicorn finishes
# in-flight requests within SHUTDOWN_TIMEOUT_SECONDS. 4 + 3 < 10, so SIGKILL is not reached.
stop_signal: SIGTERM
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}
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"
# 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"
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.
ports:
- "127.0.0.1:${LB_PORT:-8080}:8080"
- "[::1]:${LB_PORT:-8080}:8080"
volumes:
- ./infra/haproxy/haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro
networks:
- edge
depends_on:
api:
condition: service_healthy
healthcheck:
test: ["CMD", "wget", "-qO-", "http://127.0.0.1:8080/lb/health"]
interval: 5s
timeout: 3s
retries: 3
deploy:
resources:
limits:
cpus: "0.5"
memory: 128M
reservations:
cpus: "0.1"
memory: 32M
restart: unless-stopped
networks:
edge: {}
data:
internal: true
secrets:
postgres_password:
environment: POSTGRES_PASSWORD
minio_root_user:
environment: MINIO_ROOT_USER
minio_root_password:
environment: MINIO_ROOT_PASSWORD
s3_access_key_id:
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:
+32
View File
@@ -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
Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

+28
View File
@@ -0,0 +1,28 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" width="960" height="540" viewBox="0 0 960 540" role="img">
<title>Backpressure: часть upload отклонена, пока worker остановлен</title>
<rect width="100%" height="100%" fill="#ffffff"/>
<text x="48" y="42" fill="#1c1c1c" font-family="Segoe UI, sans-serif" font-size="22" font-weight="500" text-anchor="start">Пока worker остановлен, лишняя работа не принимается</text>
<text x="48" y="68" fill="#5c5c5c" font-family="Segoe UI, sans-serif" font-size="14" font-weight="400" text-anchor="start">28 попыток. Лимит queued + processing = 20. После старта принятые дошли до ready</text>
<line x1="140" y1="430" x2="820" y2="430" stroke="#e6e6e6"/>
<text x="130" y="434" fill="#5c5c5c" font-family="Segoe UI, sans-serif" font-size="13" font-weight="400" text-anchor="end">0</text>
<line x1="140" y1="350" x2="820" y2="350" stroke="#e6e6e6"/>
<text x="130" y="354" fill="#5c5c5c" font-family="Segoe UI, sans-serif" font-size="13" font-weight="400" text-anchor="end">8</text>
<line x1="140" y1="270" x2="820" y2="270" stroke="#e6e6e6"/>
<text x="130" y="274" fill="#5c5c5c" font-family="Segoe UI, sans-serif" font-size="13" font-weight="400" text-anchor="end">16</text>
<line x1="140" y1="190" x2="820" y2="190" stroke="#e6e6e6"/>
<text x="130" y="194" fill="#5c5c5c" font-family="Segoe UI, sans-serif" font-size="13" font-weight="400" text-anchor="end">24</text>
<line x1="140" y1="110" x2="820" y2="110" stroke="#e6e6e6"/>
<text x="130" y="114" fill="#5c5c5c" font-family="Segoe UI, sans-serif" font-size="13" font-weight="400" text-anchor="end">32</text>
<line x1="140" y1="110" x2="140" y2="430" stroke="#1c1c1c"/>
<line x1="140" y1="430" x2="820" y2="430" stroke="#1c1c1c"/>
<rect x="274" y="240" width="72" height="190" fill="#2E7D4F"/>
<text x="310" y="264" fill="#ffffff" font-family="Segoe UI, sans-serif" font-size="16" font-weight="500" text-anchor="middle">19</text>
<text x="310" y="458" fill="#1c1c1c" font-family="Segoe UI, sans-serif" font-size="16" font-weight="400" text-anchor="middle">202 принято</text>
<rect x="614" y="340" width="72" height="90" fill="#C05621"/>
<text x="650" y="364" fill="#ffffff" font-family="Segoe UI, sans-serif" font-size="16" font-weight="500" text-anchor="middle">9</text>
<text x="650" y="458" fill="#1c1c1c" font-family="Segoe UI, sans-serif" font-size="16" font-weight="400" text-anchor="middle">429 отклонено</text>
<line x1="140" y1="230" x2="820" y2="230" stroke="#5c5c5c" stroke-dasharray="5 4"/>
<text x="828" y="234" fill="#5c5c5c" font-family="Segoe UI, sans-serif" font-size="14" font-weight="400" text-anchor="start">лимит 20</text>
<text x="36" y="270" fill="#5c5c5c" font-family="Segoe UI, sans-serif" font-size="14" font-weight="400" text-anchor="middle" transform="rotate(-90 36 270)">ответы</text>
</svg>

After

Width:  |  Height:  |  Size: 2.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

+49
View File
@@ -0,0 +1,49 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" width="960" height="560" viewBox="0 0 960 560" role="img">
<title>p95 времени от 202 до ready по размеру изображения</title>
<rect width="100%" height="100%" fill="#ffffff"/>
<text x="48" y="42" fill="#1c1c1c" font-family="Segoe UI, sans-serif" font-size="22" font-weight="500" text-anchor="start">p95 времени от ответа 202 до ready</text>
<text x="48" y="68" fill="#5c5c5c" font-family="Segoe UI, sans-serif" font-size="14" font-weight="400" text-anchor="start">5 файлов каждого размера. Время включает ожидание, пока worker был остановлен</text>
<line x1="90" y1="460" x2="910" y2="460" stroke="#e6e6e6"/>
<text x="80" y="464" fill="#5c5c5c" font-family="Segoe UI, sans-serif" font-size="13" font-weight="400" text-anchor="end">0</text>
<line x1="90" y1="388" x2="910" y2="388" stroke="#e6e6e6"/>
<text x="80" y="392" fill="#5c5c5c" font-family="Segoe UI, sans-serif" font-size="13" font-weight="400" text-anchor="end">2</text>
<line x1="90" y1="316" x2="910" y2="316" stroke="#e6e6e6"/>
<text x="80" y="320" fill="#5c5c5c" font-family="Segoe UI, sans-serif" font-size="13" font-weight="400" text-anchor="end">4</text>
<line x1="90" y1="244" x2="910" y2="244" stroke="#e6e6e6"/>
<text x="80" y="248" fill="#5c5c5c" font-family="Segoe UI, sans-serif" font-size="13" font-weight="400" text-anchor="end">6</text>
<line x1="90" y1="172" x2="910" y2="172" stroke="#e6e6e6"/>
<text x="80" y="176" fill="#5c5c5c" font-family="Segoe UI, sans-serif" font-size="13" font-weight="400" text-anchor="end">8</text>
<line x1="90" y1="100" x2="910" y2="100" stroke="#e6e6e6"/>
<text x="80" y="104" fill="#5c5c5c" font-family="Segoe UI, sans-serif" font-size="13" font-weight="400" text-anchor="end">10</text>
<line x1="90" y1="100" x2="90" y2="460" stroke="#1c1c1c"/>
<line x1="90" y1="460" x2="910" y2="460" stroke="#1c1c1c"/>
<text x="226.667" y="486" fill="#1c1c1c" font-family="Segoe UI, sans-serif" font-size="15" font-weight="400" text-anchor="middle">128×128</text>
<rect x="162.667" y="245.692" width="28" height="214.308" fill="#1F4E79"/>
<text x="176.667" y="237.692" fill="#1c1c1c" font-family="Segoe UI, sans-serif" font-size="13" font-weight="400" text-anchor="middle">5.953</text>
<rect x="212.667" y="261.928" width="28" height="198.072" fill="#2E7D4F"/>
<text x="226.667" y="253.928" fill="#1c1c1c" font-family="Segoe UI, sans-serif" font-size="13" font-weight="400" text-anchor="middle">5.502</text>
<rect x="262.667" y="271.72" width="28" height="188.28" fill="#C05621"/>
<text x="276.667" y="263.72" fill="#1c1c1c" font-family="Segoe UI, sans-serif" font-size="13" font-weight="400" text-anchor="middle">5.230</text>
<text x="500" y="486" fill="#1c1c1c" font-family="Segoe UI, sans-serif" font-size="15" font-weight="400" text-anchor="middle">640×480</text>
<rect x="436" y="240.832" width="28" height="219.168" fill="#1F4E79"/>
<text x="450" y="232.832" fill="#1c1c1c" font-family="Segoe UI, sans-serif" font-size="13" font-weight="400" text-anchor="middle">6.088</text>
<rect x="486" y="255.664" width="28" height="204.336" fill="#2E7D4F"/>
<text x="500" y="247.664" fill="#1c1c1c" font-family="Segoe UI, sans-serif" font-size="13" font-weight="400" text-anchor="middle">5.676</text>
<rect x="536" y="278.416" width="28" height="181.584" fill="#C05621"/>
<text x="550" y="270.416" fill="#1c1c1c" font-family="Segoe UI, sans-serif" font-size="13" font-weight="400" text-anchor="middle">5.044</text>
<text x="773.333" y="486" fill="#1c1c1c" font-family="Segoe UI, sans-serif" font-size="15" font-weight="400" text-anchor="middle">2560×1920</text>
<rect x="709.333" y="164.944" width="28" height="295.056" fill="#1F4E79"/>
<text x="723.333" y="156.944" fill="#1c1c1c" font-family="Segoe UI, sans-serif" font-size="13" font-weight="400" text-anchor="middle">8.196</text>
<rect x="759.333" y="184.708" width="28" height="275.292" fill="#2E7D4F"/>
<text x="773.333" y="176.708" fill="#1c1c1c" font-family="Segoe UI, sans-serif" font-size="13" font-weight="400" text-anchor="middle">7.647</text>
<rect x="809.333" y="194.824" width="28" height="265.176" fill="#C05621"/>
<text x="823.333" y="186.824" fill="#1c1c1c" font-family="Segoe UI, sans-serif" font-size="13" font-weight="400" text-anchor="middle">7.366</text>
<text x="28" y="280" fill="#5c5c5c" font-family="Segoe UI, sans-serif" font-size="14" font-weight="400" text-anchor="middle" transform="rotate(-90 28 280)">секунды</text>
<rect x="90" y="512" width="14" height="14" fill="#1F4E79"/>
<text x="110" y="524" fill="#1c1c1c" font-family="Segoe UI, sans-serif" font-size="15" font-weight="400" text-anchor="start">prefetch 1</text>
<rect x="240" y="512" width="14" height="14" fill="#2E7D4F"/>
<text x="260" y="524" fill="#1c1c1c" font-family="Segoe UI, sans-serif" font-size="15" font-weight="400" text-anchor="start">prefetch 2</text>
<rect x="390" y="512" width="14" height="14" fill="#C05621"/>
<text x="410" y="524" fill="#1c1c1c" font-family="Segoe UI, sans-serif" font-size="15" font-weight="400" text-anchor="start">prefetch 4</text>
</svg>

After

Width:  |  Height:  |  Size: 5.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

+49
View File
@@ -0,0 +1,49 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" width="960" height="560" viewBox="0 0 960 560" role="img">
<title>Throughput и RSS worker при prefetch 1, 2 и 4</title>
<rect width="100%" height="100%" fill="#ffffff"/>
<text x="48" y="42" fill="#1c1c1c" font-family="Segoe UI, sans-serif" font-size="22" font-weight="500" text-anchor="start">Throughput почти не вырос, RSS при prefetch 4 вырос</text>
<text x="48" y="68" fill="#5c5c5c" font-family="Segoe UI, sans-serif" font-size="14" font-weight="400" text-anchor="start">15 из 15 файлов стали ready. Память контейнера worker ограничена 512 МиБ</text>
<line x1="80" y1="440" x2="460" y2="440" stroke="#e6e6e6"/>
<text x="70" y="444" fill="#5c5c5c" font-family="Segoe UI, sans-serif" font-size="13" font-weight="400" text-anchor="end">0</text>
<line x1="80" y1="333.333" x2="460" y2="333.333" stroke="#e6e6e6"/>
<text x="70" y="337.333" fill="#5c5c5c" font-family="Segoe UI, sans-serif" font-size="13" font-weight="400" text-anchor="end">2</text>
<line x1="80" y1="226.667" x2="460" y2="226.667" stroke="#e6e6e6"/>
<text x="70" y="230.667" fill="#5c5c5c" font-family="Segoe UI, sans-serif" font-size="13" font-weight="400" text-anchor="end">4</text>
<line x1="80" y1="120" x2="460" y2="120" stroke="#e6e6e6"/>
<text x="70" y="124" fill="#5c5c5c" font-family="Segoe UI, sans-serif" font-size="13" font-weight="400" text-anchor="end">6</text>
<line x1="80" y1="120" x2="80" y2="440" stroke="#1c1c1c"/>
<line x1="80" y1="440" x2="460" y2="440" stroke="#1c1c1c"/>
<rect x="107.333" y="184.747" width="72" height="255.253" fill="#1F4E79"/>
<text x="143.333" y="208.747" fill="#ffffff" font-family="Segoe UI, sans-serif" font-size="16" font-weight="500" text-anchor="middle">4.786</text>
<text x="143.333" y="468" fill="#1c1c1c" font-family="Segoe UI, sans-serif" font-size="16" font-weight="400" text-anchor="middle">prefetch 1</text>
<rect x="234" y="180.907" width="72" height="259.093" fill="#1F4E79"/>
<text x="270" y="204.907" fill="#ffffff" font-family="Segoe UI, sans-serif" font-size="16" font-weight="500" text-anchor="middle">4.858</text>
<text x="270" y="468" fill="#1c1c1c" font-family="Segoe UI, sans-serif" font-size="16" font-weight="400" text-anchor="middle">prefetch 2</text>
<rect x="360.667" y="208.32" width="72" height="231.68" fill="#1F4E79"/>
<text x="396.667" y="232.32" fill="#ffffff" font-family="Segoe UI, sans-serif" font-size="16" font-weight="500" text-anchor="middle">4.344</text>
<text x="396.667" y="468" fill="#1c1c1c" font-family="Segoe UI, sans-serif" font-size="16" font-weight="400" text-anchor="middle">prefetch 4</text>
<line x1="530" y1="440" x2="910" y2="440" stroke="#e6e6e6"/>
<text x="520" y="444" fill="#5c5c5c" font-family="Segoe UI, sans-serif" font-size="13" font-weight="400" text-anchor="end">0</text>
<line x1="530" y1="360" x2="910" y2="360" stroke="#e6e6e6"/>
<text x="520" y="364" fill="#5c5c5c" font-family="Segoe UI, sans-serif" font-size="13" font-weight="400" text-anchor="end">128</text>
<line x1="530" y1="280" x2="910" y2="280" stroke="#e6e6e6"/>
<text x="520" y="284" fill="#5c5c5c" font-family="Segoe UI, sans-serif" font-size="13" font-weight="400" text-anchor="end">256</text>
<line x1="530" y1="200" x2="910" y2="200" stroke="#e6e6e6"/>
<text x="520" y="204" fill="#5c5c5c" font-family="Segoe UI, sans-serif" font-size="13" font-weight="400" text-anchor="end">384</text>
<line x1="530" y1="120" x2="910" y2="120" stroke="#e6e6e6"/>
<text x="520" y="124" fill="#5c5c5c" font-family="Segoe UI, sans-serif" font-size="13" font-weight="400" text-anchor="end">512</text>
<line x1="530" y1="120" x2="530" y2="440" stroke="#1c1c1c"/>
<line x1="530" y1="440" x2="910" y2="440" stroke="#1c1c1c"/>
<rect x="557.333" y="371.062" width="72" height="68.9375" fill="#C05621"/>
<text x="593.333" y="395.062" fill="#ffffff" font-family="Segoe UI, sans-serif" font-size="16" font-weight="500" text-anchor="middle">110.3</text>
<text x="593.333" y="468" fill="#1c1c1c" font-family="Segoe UI, sans-serif" font-size="16" font-weight="400" text-anchor="middle">prefetch 1</text>
<rect x="684" y="370.875" width="72" height="69.125" fill="#C05621"/>
<text x="720" y="394.875" fill="#ffffff" font-family="Segoe UI, sans-serif" font-size="16" font-weight="500" text-anchor="middle">110.6</text>
<text x="720" y="468" fill="#1c1c1c" font-family="Segoe UI, sans-serif" font-size="16" font-weight="400" text-anchor="middle">prefetch 2</text>
<rect x="810.667" y="267.625" width="72" height="172.375" fill="#C05621"/>
<text x="846.667" y="291.625" fill="#ffffff" font-family="Segoe UI, sans-serif" font-size="16" font-weight="500" text-anchor="middle">275.8</text>
<text x="846.667" y="468" fill="#1c1c1c" font-family="Segoe UI, sans-serif" font-size="16" font-weight="400" text-anchor="middle">prefetch 4</text>
<text x="270" y="104" fill="#5c5c5c" font-family="Segoe UI, sans-serif" font-size="14" font-weight="400" text-anchor="middle">готовых в секунду</text>
<text x="720" y="104" fill="#5c5c5c" font-family="Segoe UI, sans-serif" font-size="14" font-weight="400" text-anchor="middle">RSS worker, МиБ</text>
</svg>

After

Width:  |  Height:  |  Size: 5.1 KiB

+128
View File
@@ -0,0 +1,128 @@
{
"base_url": "http://127.0.0.1:8080",
"sizes": [
{
"name": "small",
"width": 128,
"height": 128,
"count": 5
},
{
"name": "medium",
"width": 640,
"height": 480,
"count": 5
},
{
"name": "large",
"width": 2560,
"height": 1920,
"count": 5
}
],
"note": "Each setting stops the worker, accepts the same backlog, then starts that prefetch. prefetch equals WORKER_CONCURRENCY. p95_s is client time from the 202 to ready. throughput is ready count divided by drain time after the worker starts. rss_max_mib is the worker container during the drain.",
"runs": [
{
"label": "compare",
"concurrency_prefetch": 1,
"uploaded": 15,
"ready": 15,
"failed": [],
"drain_s": 3.134,
"throughput_ready_per_s": 4.786,
"queue_ready_at_start": 15,
"queue_ready_max": 4,
"p95_s": 8.196,
"p95_drain_s": 3.134,
"p95_by_size": {
"small": {
"n": 5,
"p95_s": 5.953
},
"medium": {
"n": 5,
"p95_s": 6.088
},
"large": {
"n": 5,
"p95_s": 8.196
}
},
"rss_max_mib": 110.3,
"rss_samples": 3,
"still_pending": []
},
{
"label": "compare",
"concurrency_prefetch": 2,
"uploaded": 15,
"ready": 15,
"failed": [],
"drain_s": 3.088,
"throughput_ready_per_s": 4.858,
"queue_ready_at_start": 15,
"queue_ready_max": 1,
"p95_s": 7.647,
"p95_drain_s": 3.088,
"p95_by_size": {
"small": {
"n": 5,
"p95_s": 5.502
},
"medium": {
"n": 5,
"p95_s": 5.676
},
"large": {
"n": 5,
"p95_s": 7.647
}
},
"rss_max_mib": 110.6,
"rss_samples": 3,
"still_pending": []
},
{
"label": "compare",
"concurrency_prefetch": 4,
"uploaded": 15,
"ready": 15,
"failed": [],
"drain_s": 3.453,
"throughput_ready_per_s": 4.344,
"queue_ready_at_start": 15,
"queue_ready_max": 7,
"p95_s": 7.366,
"p95_drain_s": 3.453,
"p95_by_size": {
"small": {
"n": 5,
"p95_s": 5.23
},
"medium": {
"n": 5,
"p95_s": 5.044
},
"large": {
"n": 5,
"p95_s": 7.366
}
},
"rss_max_mib": 275.8,
"rss_samples": 3,
"still_pending": []
}
],
"overload": {
"label": "overload",
"cap": 20,
"attempted": 28,
"accepted": 19,
"rejected_429": 9,
"queue_ready_while_stopped": 19,
"pending_after_restart": [],
"follow_up_status": 202,
"follow_up_pending": [],
"elapsed_s": 6.364
}
}
+92
View File
@@ -0,0 +1,92 @@
# Client -> HAProxy -> api x N. Replicas are discovered through Docker DNS and checked actively.
#
# Timing contract (keep in sync with compose.yaml and app settings):
# check period inter 1s, timeout check 1s
# marked DOWN after fall 2 failed checks -> hung/draining replica leaves the pool in <= 3 s
# marked UP after rise 2 good checks -> new replica gets traffic ~2 s after it is ready
# DNS refresh every 1 s (hold valid 1s); a removed container disappears within ~1-2 s
# crashed process connect refused -> request redispatched to another replica at once
# app DRAIN_SECONDS=4 > 3 s, so a replica receiving SIGTERM is out of rotation before it closes its socket.
global
log stdout format raw local0 info
maxconn 2048
# Runtime API for evidence (scripts/lb-status.sh); loopback inside the container only.
stats socket ipv4@127.0.0.1:9999 level operator
resolvers docker
nameserver dns 127.0.0.11:53
accepted_payload_size 8192
resolve_retries 3
timeout resolve 1s
timeout retry 1s
hold valid 1s
hold other 1s
hold refused 1s
hold nx 1s
hold timeout 1s
hold obsolete 0s
defaults
mode http
log global
option httplog
option dontlognull
option forwardfor
timeout connect 1s
timeout client 30s
timeout server 10s
# Body arrival for a 10 MiB attachment; JSON posts finish well under this.
timeout http-request 30s
timeout http-keep-alive 5s
timeout queue 2s
timeout check 1s
# A request whose connection to a replica failed is sent to another replica.
retries 2
option redispatch 1
frontend public
bind :8080
monitor-uri /lb/health
# Attachment uploads are raw bytes, up to 10 MiB. A larger Content-Length is
# rejected here, before the body is read or an API replica is contacted.
# The body matches the API error envelope; request_id echoes a safe client
# X-Request-Id and otherwise stays "lb", like the other gateway errors.
acl upload_too_large req.hdr_val(content-length) gt 10485760
acl safe_request_id req.hdr(X-Request-Id) -m reg ^[A-Za-z0-9._:-]{1,128}$
http-request set-var(txn.reqid) req.hdr(X-Request-Id) if upload_too_large safe_request_id
http-request set-var(txn.reqid) str(lb) if upload_too_large !safe_request_id
http-request return status 413 content-type application/json lf-string "{\"error\":{\"code\":\"payload_too_large\",\"message\":\"Файл больше 10 МиБ\",\"request_id\":\"%[var(txn.reqid)]\"}}" hdr X-Request-Id %[var(txn.reqid)] hdr X-Instance-Id %[str(lb)] if upload_too_large
# Message POST carries a mandatory Idempotency-Key, so replaying it on another replica is safe.
# Other POSTs (users, chats, sessions) are retried only when the connection was never established.
acl message_post method POST
acl message_post_path path_reg ^/api/v1/chats/[^/]+/messages$
http-request disable-l7-retry if message_post !message_post_path
default_backend api
backend api
# Round robin, no stickiness: any replica serves any session from PostgreSQL.
# Attachment PUT to S3 can outlast the default 10 s server timeout under concurrent load.
acl attachment_upload method POST
acl attachment_upload_path path_reg ^/api/v1/chats/[^/]+/attachments$
http-request set-timeout server 30s if attachment_upload attachment_upload_path
balance roundrobin
option httpchk
http-check send meth GET uri /health/ready ver HTTP/1.1 hdr Host lb
http-check expect status 200
retry-on conn-failure empty-response response-timeout
http-error status 503 content-type application/json string "{\"error\":{\"code\":\"unavailable\",\"message\":\"No API replica is available\",\"request_id\":\"lb\"}}"
http-error status 502 content-type application/json string "{\"error\":{\"code\":\"internal_error\",\"message\":\"Bad gateway\",\"request_id\":\"lb\"}}"
http-error status 504 content-type application/json string "{\"error\":{\"code\":\"internal_error\",\"message\":\"Gateway timeout\",\"request_id\":\"lb\"}}"
default-server check inter 1s fall 2 rise 2 resolvers docker resolve-prefer ipv4 init-addr none
server-template api 1-10 api:8080
# Read-only stats for evidence; not published, reachable only inside the container.
frontend stats
bind 127.0.0.1:8404
stats enable
stats uri /stats
stats refresh 5s
http-request set-log-level silent
+116
View File
@@ -0,0 +1,116 @@
#!/bin/sh
# Idempotent private-bucket bootstrap for MinIO. Root credentials are read from
# files and are not printed. A second run leaves the bucket, policy and API user in place.
set -eu
bucket=${S3_BUCKET:?S3_BUCKET is required}
region=${S3_REGION:-us-east-1}
endpoint=${MINIO_ENDPOINT:-http://minio:9000}
policy_name=attachments-api
case "$bucket" in
[a-z0-9][a-z0-9.-]*[a-z0-9]) ;;
*)
echo "S3_BUCKET must be a DNS-style name" >&2
exit 1
;;
esac
read_secret() {
tr -d '\r\n' < "$1"
}
root_user=$(read_secret /run/secrets/minio_root_user)
root_password=$(read_secret /run/secrets/minio_root_password)
access_key=$(read_secret /run/secrets/s3_access_key_id)
secret_key=$(read_secret /run/secrets/s3_secret_access_key)
if [ -z "$root_user" ] || [ -z "$root_password" ] || [ -z "$access_key" ] || [ -z "$secret_key" ]; then
echo "MinIO bootstrap secrets are empty" >&2
exit 1
fi
i=0
until mc alias set local "$endpoint" "$root_user" "$root_password" >/dev/null; do
i=$((i + 1))
if [ "$i" -ge 30 ]; then
echo "MinIO is not accepting the root credentials" >&2
exit 1
fi
sleep 1
done
# A new MinIO bucket has no anonymous policy. Set none explicitly so a later
# public policy cannot survive a repeated bootstrap.
mc mb --ignore-existing --region "$region" "local/${bucket}" >/dev/null
mc anonymous set none "local/${bucket}" >/dev/null
anon=$(mc anonymous get "local/${bucket}")
case "$anon" in
*private*) ;;
*)
echo "bucket ${bucket} is not private" >&2
exit 1
;;
esac
probe_key=".bootstrap/private-probe"
printf 'probe' | mc pipe "local/${bucket}/${probe_key}" >/dev/null
code=$(curl -s -o /dev/null -w '%{http_code}' "${endpoint}/${bucket}/${probe_key}")
mc rm --force "local/${bucket}/${probe_key}" >/dev/null
if [ "$code" != "403" ]; then
echo "unauthenticated GET returned ${code}, expected 403" >&2
exit 1
fi
policy_file=/tmp/attachments-api-policy.json
cat > "$policy_file" <<EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": ["s3:GetBucketLocation", "s3:ListBucket", "s3:ListBucketMultipartUploads"],
"Resource": ["arn:aws:s3:::${bucket}"]
},
{
"Effect": "Allow",
"Action": [
"s3:GetObject",
"s3:PutObject",
"s3:DeleteObject",
"s3:AbortMultipartUpload",
"s3:ListMultipartUploadParts"
],
"Resource": ["arn:aws:s3:::${bucket}/*"]
}
]
}
EOF
# Recreate the canned policy on every run so added actions (multipart list) apply.
if mc admin user info local "$access_key" >/dev/null 2>&1; then
mc admin policy detach local "$policy_name" --user "$access_key" >/dev/null 2>&1 || true
fi
mc admin policy remove local "$policy_name" >/dev/null 2>&1 || \
mc admin policy rm local "$policy_name" >/dev/null 2>&1 || true
mc admin policy create local "$policy_name" "$policy_file" >/dev/null
if ! mc admin user info local "$access_key" >/dev/null 2>&1; then
mc admin user add local "$access_key" "$secret_key" >/dev/null
fi
mc admin policy attach local "$policy_name" --user "$access_key" >/dev/null
mc alias set api "$endpoint" "$access_key" "$secret_key" >/dev/null
api_key=".bootstrap/api-probe"
printf 'ok' | mc pipe "api/${bucket}/${api_key}" >/dev/null
mc cat "api/${bucket}/${api_key}" >/dev/null
mc rm --force "api/${bucket}/${api_key}" >/dev/null
if mc ls "api/not-this-bucket" >/dev/null 2>&1; then
echo "API credentials can list a different bucket" >&2
exit 1
fi
echo "bucket ${bucket} is private"
+18
View File
@@ -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
+53
View File
@@ -0,0 +1,53 @@
-- Initial schema. The runner records this file in schema_migrations and skips it on the next start.
CREATE TABLE IF NOT EXISTS schema_migrations (
version TEXT PRIMARY KEY,
applied_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp()
);
CREATE TABLE users (
id UUID PRIMARY KEY,
username TEXT NOT NULL,
display_name TEXT NOT NULL,
password_hash TEXT NOT NULL,
created_at TIMESTAMPTZ NOT NULL,
CONSTRAINT users_username_unique UNIQUE (username),
CONSTRAINT users_username_format CHECK (username ~ '^[a-z0-9_]{3,32}$'),
CONSTRAINT users_display_name_len CHECK (char_length(display_name) BETWEEN 1 AND 100)
);
CREATE TABLE sessions (
token_hash TEXT PRIMARY KEY,
user_id UUID NOT NULL REFERENCES users (id),
expires_at TIMESTAMPTZ NOT NULL
);
CREATE TABLE chats (
id UUID PRIMARY KEY,
title TEXT NOT NULL,
created_at TIMESTAMPTZ NOT NULL,
CONSTRAINT chats_title_len CHECK (char_length(title) BETWEEN 1 AND 100)
);
CREATE TABLE chat_members (
chat_id UUID NOT NULL REFERENCES chats (id),
user_id UUID NOT NULL REFERENCES users (id),
position INTEGER NOT NULL,
PRIMARY KEY (chat_id, user_id),
CONSTRAINT chat_members_position_nonnegative CHECK (position >= 0)
);
CREATE TABLE messages (
id UUID PRIMARY KEY,
chat_id UUID NOT NULL REFERENCES chats (id),
sender_id UUID NOT NULL REFERENCES users (id),
text TEXT NOT NULL,
created_at TIMESTAMPTZ NOT NULL,
CONSTRAINT messages_text_len CHECK (char_length(text) BETWEEN 1 AND 4000)
);
-- Keyset history: WHERE chat_id = ? AND (created_at, id) > cursor ORDER BY created_at, id.
CREATE INDEX messages_history_idx ON messages (chat_id, created_at, id);
-- Chat list is filtered by the caller, then ordered by the chat's own (created_at, id).
CREATE INDEX chat_members_user_idx ON chat_members (user_id);
+16
View File
@@ -0,0 +1,16 @@
-- Result of POST /chats/{id}/messages per (user, method, path, Idempotency-Key).
-- The row and the message are written in one transaction, so a failed attempt leaves no key behind.
CREATE TABLE idempotency_keys (
user_id UUID NOT NULL REFERENCES users (id),
method TEXT NOT NULL,
path TEXT NOT NULL,
key TEXT NOT NULL,
request_hash TEXT NOT NULL,
status_code INTEGER NOT NULL,
response JSONB NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(),
PRIMARY KEY (user_id, method, path, key),
CONSTRAINT idempotency_keys_key_format CHECK (key ~ '^[A-Za-z0-9._:-]{1,128}$')
);
CREATE INDEX idempotency_keys_created_idx ON idempotency_keys (created_at);
+4
View File
@@ -0,0 +1,4 @@
-- Expand-only: new indexes, no column/table removal or rename, so replicas of the previous build keep working
-- while the rolling update is in progress. Destructive changes go to a later release, after old replicas are gone.
CREATE INDEX IF NOT EXISTS sessions_user_idx ON sessions (user_id);
CREATE INDEX IF NOT EXISTS sessions_expires_idx ON sessions (expires_at);
+40
View File
@@ -0,0 +1,40 @@
-- Lab4: message may be text, attachments, or both. Empty text is stored only when
-- an attachment is linked; the API rejects a blank message that has neither.
ALTER TABLE messages DROP CONSTRAINT messages_text_len;
ALTER TABLE messages ADD CONSTRAINT messages_text_len CHECK (char_length(text) BETWEEN 0 AND 4000);
-- filename is the display name only. object_key is assigned by the server and is never taken from filename.
-- The original bytes live in the private S3 bucket under that key, not in this table.
CREATE TABLE attachments (
id UUID PRIMARY KEY,
chat_id UUID NOT NULL REFERENCES chats (id),
owner_id UUID NOT NULL REFERENCES users (id),
filename TEXT NOT NULL,
content_type TEXT NOT NULL,
size_bytes INTEGER NOT NULL,
sha256 TEXT NOT NULL,
object_key TEXT NOT NULL,
-- Durable location of the accepted original. This step stores the same key as object_key.
staging_key TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'queued',
created_at TIMESTAMPTZ NOT NULL,
updated_at TIMESTAMPTZ NOT NULL,
CONSTRAINT attachments_filename_len CHECK (char_length(filename) BETWEEN 1 AND 255),
CONSTRAINT attachments_content_type CHECK (content_type IN ('image/png', 'image/jpeg')),
CONSTRAINT attachments_size CHECK (size_bytes BETWEEN 1 AND 10485760),
CONSTRAINT attachments_sha256 CHECK (sha256 ~ '^[a-f0-9]{64}$'),
CONSTRAINT attachments_object_key_unique UNIQUE (object_key),
CONSTRAINT attachments_status CHECK (status IN ('queued', 'processing', 'ready', 'failed'))
);
CREATE INDEX attachments_chat_idx ON attachments (chat_id);
CREATE TABLE message_attachments (
message_id UUID NOT NULL REFERENCES messages (id),
attachment_id UUID NOT NULL REFERENCES attachments (id),
position INTEGER NOT NULL,
PRIMARY KEY (message_id, attachment_id),
CONSTRAINT message_attachments_position CHECK (position >= 0 AND position < 10)
);
CREATE INDEX message_attachments_message_idx ON message_attachments (message_id, position);
@@ -0,0 +1,4 @@
-- Databases that already applied the earlier 004 kept the original in a BYTEA column.
-- Drop it. Fresh installs create the table without that column; both statements are then no-ops.
ALTER TABLE attachments DROP CONSTRAINT IF EXISTS attachments_body_len;
ALTER TABLE attachments DROP COLUMN IF EXISTS body;
+47
View File
@@ -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)
);
+48
View File
@@ -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'
))
);
+33
View File
@@ -0,0 +1,33 @@
# Direct: fastapi, pydantic, uvicorn, argon2-cffi, boto3. The rest are their dependencies, pinned.
boto3==1.43.126
botocore==1.43.126
asyncpg==0.32.0
annotated-doc==0.0.5
annotated-types==0.8.0
anyio==4.15.1
argon2-cffi==25.1.0
argon2-cffi-bindings==25.1.0
cffi==2.0.0
click==8.5.0
fastapi==0.141.1
h11==0.16.0
idna==3.20
jmespath==1.1.0
pycparser==3.0
python-dateutil==2.9.0.post0
pydantic==2.13.5
pydantic_core==2.46.5
s3transfer==0.19.3
six==1.17.0
starlette==1.7.0
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
+464
View File
@@ -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)
+9
View File
@@ -0,0 +1,9 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
# 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
+29
View File
@@ -0,0 +1,29 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
# Stop exactly ONE API replica and leave it stopped. DB, LB and volumes are untouched.
# X-Instance-Id is the container hostname, i.e. the short Docker container ID.
# Restore afterwards with: docker compose --env-file .env up -d --wait
: "${TARGET_INSTANCE_ID:?test provides target API instance alias}"
case "$TARGET_INSTANCE_ID" in
*[!0-9a-f]*) valid=no ;;
*) valid=yes ;;
esac
if [ "$valid" = no ] || [ "${#TARGET_INSTANCE_ID}" -lt 12 ]; then
echo "TARGET_INSTANCE_ID is not a container ID" >&2
exit 2
fi
project="${COMPOSE_PROJECT_NAME:-messenger-lab5}"
matches=$(docker ps -q --no-trunc \
--filter "label=com.docker.compose.project=$project" \
--filter "label=com.docker.compose.service=api" | grep "^$TARGET_INSTANCE_ID" || true)
count=$(printf '%s' "$matches" | grep -c . || true)
if [ "$count" -ne 1 ]; then
echo "expected one running api container for $TARGET_INSTANCE_ID, found $count" >&2
exit 1
fi
name=$(docker inspect --format '{{.Name}}' "$matches")
# Graceful: SIGTERM -> 4 s drain (readiness 503, LB drops it) -> <= 3 s in-flight finish.
# SIGKILL only after 9 s, so the hook still returns before the test's 10 s limit.
docker stop --time 9 "$matches" >/dev/null
echo "stopped api replica ${name#/} ($TARGET_INSTANCE_ID)"
+180
View File
@@ -0,0 +1,180 @@
#!/usr/bin/env python3
"""Draw the track 1 charts from evidence/track1.json. Standard library only."""
import json
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
SOURCE = ROOT / 'evidence' / 'track1.json'
OUT = ROOT / 'evidence'
COLORS = ('#1F4E79', '#2E7D4F', '#C05621')
INK = '#1c1c1c'
MUTED = '#5c5c5c'
GRID = '#e6e6e6'
FONT = 'Segoe UI, sans-serif'
def esc(text):
return str(text).replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;')
def fmt(value):
if abs(value - round(value)) < 1e-9:
return str(int(round(value)))
if abs(value * 10 - round(value * 10)) < 1e-6:
return '%.1f' % value
return '%.3f' % value
def header(width, height, title):
return (
'<?xml version="1.0" encoding="UTF-8"?>\n'
'<svg xmlns="http://www.w3.org/2000/svg" width="%d" height="%d" viewBox="0 0 %d %d" role="img">\n'
'<title>%s</title>\n'
'<rect width="100%%" height="100%%" fill="#ffffff"/>\n'
) % (width, height, width, height, esc(title))
def text(x, y, value, size=14, fill=INK, anchor='start', weight='400', rotate=None):
transform = ''
if rotate is not None:
transform = ' transform="rotate(%g %g %g)"' % (rotate, x, y)
return (
'<text x="%g" y="%g" fill="%s" font-family="%s" font-size="%d" font-weight="%s" text-anchor="%s"%s>%s</text>\n'
% (x, y, fill, FONT, size, weight, anchor, transform, esc(value))
)
def ticks(ymax, count):
step = ymax / count
return [step * i for i in range(count + 1)]
def grouped(parts, box, ymax, tick_values, categories, series):
"""series: (name, color, values). One group of bars per category."""
left, top, width, height = box
bottom = top + height
for tick in tick_values:
y = bottom - (tick / ymax) * height
parts.append('<line x1="%g" y1="%g" x2="%g" y2="%g" stroke="%s"/>\n' % (left, y, left + width, y, GRID))
parts.append(text(left - 10, y + 4, fmt(tick), 13, MUTED, 'end'))
parts.append('<line x1="%g" y1="%g" x2="%g" y2="%g" stroke="%s"/>\n' % (left, top, left, bottom, INK))
parts.append('<line x1="%g" y1="%g" x2="%g" y2="%g" stroke="%s"/>\n' % (left, bottom, left + width, bottom, INK))
slot = width / len(categories)
bar_w = 28
gap = 22
group_w = len(series) * bar_w + (len(series) - 1) * gap
for index, label in enumerate(categories):
origin = left + index * slot + (slot - group_w) / 2
parts.append(text(left + index * slot + slot / 2, bottom + 26, label, 15, INK, 'middle'))
for series_index, (_name, color, values) in enumerate(series):
value = values[index]
bar_h = (value / ymax) * height
x = origin + series_index * (bar_w + gap)
y = bottom - bar_h
parts.append('<rect x="%g" y="%g" width="%g" height="%g" fill="%s"/>\n' % (x, y, bar_w, max(bar_h, 0), color))
parts.append(text(x + bar_w / 2, y - 8, fmt(value), 13, INK, 'middle'))
def bars(parts, box, ymax, tick_values, categories, values, colors):
left, top, width, height = box
bottom = top + height
for tick in tick_values:
y = bottom - (tick / ymax) * height
parts.append('<line x1="%g" y1="%g" x2="%g" y2="%g" stroke="%s"/>\n' % (left, y, left + width, y, GRID))
parts.append(text(left - 10, y + 4, fmt(tick), 13, MUTED, 'end'))
parts.append('<line x1="%g" y1="%g" x2="%g" y2="%g" stroke="%s"/>\n' % (left, top, left, bottom, INK))
parts.append('<line x1="%g" y1="%g" x2="%g" y2="%g" stroke="%s"/>\n' % (left, bottom, left + width, bottom, INK))
slot = width / len(categories)
bar_w = 72
for index, label in enumerate(categories):
value = values[index]
bar_h = (value / ymax) * height
x = left + index * slot + (slot - bar_w) / 2
y = bottom - bar_h
parts.append('<rect x="%g" y="%g" width="%g" height="%g" fill="%s"/>\n' % (x, y, bar_w, bar_h, colors[index]))
if bar_h >= 36:
parts.append(text(x + bar_w / 2, y + 24, fmt(value), 16, '#ffffff', 'middle', '500'))
else:
parts.append(text(x + bar_w / 2, y - 8, fmt(value), 16, INK, 'middle', '500'))
parts.append(text(left + index * slot + slot / 2, bottom + 28, label, 16, INK, 'middle'))
def legend(parts, x, y, series):
cursor = x
for name, color, _values in series:
parts.append('<rect x="%g" y="%g" width="14" height="14" fill="%s"/>\n' % (cursor, y - 12, color))
parts.append(text(cursor + 20, y, name, 15))
cursor += 150
def write_p95(runs):
labels = ('128×128', '640×480', '2560×1920')
keys = ('small', 'medium', 'large')
series = []
for color, run in zip(COLORS, runs):
series.append((
'prefetch %s' % run['concurrency_prefetch'],
color,
[run['p95_by_size'][key]['p95_s'] for key in keys],
))
parts = [header(960, 560, 'p95 времени от 202 до ready по размеру изображения')]
parts.append(text(48, 42, 'p95 времени от ответа 202 до ready', 22, INK, 'start', '500'))
parts.append(text(48, 68, '5 файлов каждого размера. Время включает ожидание, пока worker был остановлен', 14, MUTED))
grouped(parts, (90, 100, 820, 360), 10, ticks(10, 5), labels, series)
parts.append(text(28, 280, 'секунды', 14, MUTED, 'middle', '400', -90))
legend(parts, 90, 524, series)
parts.append('</svg>\n')
(OUT / 'track1-p95.svg').write_text(''.join(parts), encoding='utf-8')
def write_tradeoff(runs):
labels = ['prefetch %s' % run['concurrency_prefetch'] for run in runs]
throughput = [run['throughput_ready_per_s'] for run in runs]
rss = [run['rss_max_mib'] for run in runs]
parts = [header(960, 560, 'Throughput и RSS worker при prefetch 1, 2 и 4')]
parts.append(text(48, 42, 'Throughput почти не вырос, RSS при prefetch 4 вырос', 22, INK, 'start', '500'))
parts.append(text(48, 68, '15 из 15 файлов стали ready. Память контейнера worker ограничена 512 МиБ', 14, MUTED))
bars(parts, (80, 120, 380, 320), 6, ticks(6, 3), labels, throughput, (COLORS[0], COLORS[0], COLORS[0]))
bars(parts, (530, 120, 380, 320), 512, ticks(512, 4), labels, rss, (COLORS[2], COLORS[2], COLORS[2]))
parts.append(text(270, 104, 'готовых в секунду', 14, MUTED, 'middle'))
parts.append(text(720, 104, 'RSS worker, МиБ', 14, MUTED, 'middle'))
parts.append('</svg>\n')
(OUT / 'track1-tradeoff.svg').write_text(''.join(parts), encoding='utf-8')
def write_overload(overload):
labels = ('202 принято', '429 отклонено')
values = [overload['accepted'], overload['rejected_429']]
parts = [header(960, 540, 'Backpressure: часть upload отклонена, пока worker остановлен')]
parts.append(text(48, 42, 'Пока worker остановлен, лишняя работа не принимается', 22, INK, 'start', '500'))
parts.append(text(
48,
68,
'28 попыток. Лимит queued + processing = %s. После старта принятые дошли до ready' % overload['cap'],
14,
MUTED,
))
bars(parts, (140, 110, 680, 320), 32, ticks(32, 4), labels, values, (COLORS[1], COLORS[2]))
cap_y = 110 + 320 - (overload['cap'] / 32) * 320
parts.append('<line x1="140" y1="%g" x2="820" y2="%g" stroke="%s" stroke-dasharray="5 4"/>\n' % (cap_y, cap_y, MUTED))
parts.append(text(828, cap_y + 4, 'лимит %s' % overload['cap'], 14, MUTED))
parts.append(text(36, 270, 'ответы', 14, MUTED, 'middle', '400', -90))
parts.append('</svg>\n')
(OUT / 'track1-overload.svg').write_text(''.join(parts), encoding='utf-8')
def main():
data = json.loads(SOURCE.read_text(encoding='utf-8'))
runs = data['runs']
if [run['concurrency_prefetch'] for run in runs] != [1, 2, 4]:
raise SystemExit('track1.json runs are not prefetch 1, 2, 4')
write_p95(runs)
write_tradeoff(runs)
write_overload(data['overload'])
for name in ('track1-p95.svg', 'track1-tradeoff.svg', 'track1-overload.svg'):
print('wrote evidence/%s' % name)
if __name__ == '__main__':
main()
+428
View File
@@ -0,0 +1,428 @@
#!/usr/bin/env python3
"""Track 1. Three prefetch settings, three image sizes, then a full queue.
The worker is recreated with WORKER_CONCURRENCY 1, 2 and 4. Each run uploads
the same burst and records throughput, max queue depth, p95 time to ready and
worker RSS. Then the worker is stopped, uploads continue until 429, and the
worker is started again. Already accepted ids must reach ready.
Prints counts and ids only. No tokens or file bytes.
"""
import json
import math
import os
import struct
import subprocess
import sys
import threading
import time
import urllib.error
import urllib.request
import zlib
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
from client import Client # noqa: E402
SETTINGS = (1, 2, 4)
SIZES = (('small', 128, 128), ('medium', 640, 480), ('large', 2560, 1920))
PER_SIZE = 5
EVIDENCE = ROOT / 'evidence' / 'track1.json'
def read_env():
values = {}
for line in (ROOT / '.env').read_text(encoding='utf-8').splitlines():
text = line.strip()
if not text or text.startswith('#') or '=' not in text:
continue
key, value = text.split('=', 1)
values[key.strip()] = value.strip()
return values
def docker(args, check=True):
completed = subprocess.run(['docker', *args], text=True, capture_output=True)
if check and completed.returncode != 0:
tail = (completed.stderr or completed.stdout or '').strip().splitlines()
raise SystemExit('docker %s failed\n%s' % (' '.join(args), '\n'.join(tail[-20:])))
return completed
def worker_name():
completed = compose(['ps', '-a', '--format', '{{.Service}}\t{{.Name}}'])
for line in completed.stdout.splitlines():
service, _, name = line.partition('\t')
if service.strip() == 'worker':
return name.strip()
raise SystemExit('worker container was not found')
def wait_prefetch_since(name, value, since):
needle = 'prefetch' if value is None else 'prefetch %s' % value
deadline = time.monotonic() + 45
while time.monotonic() < deadline:
logs = docker(['logs', '--since', since, '--tail', '40', name], check=False)
text = (logs.stdout or '') + (logs.stderr or '')
if needle in text:
return
time.sleep(0.3)
raise SystemExit('worker did not log %s after start' % needle)
def compose(args, env=None, check=True):
merged = os.environ.copy()
if env:
merged.update(env)
completed = subprocess.run(
['docker', 'compose', '--env-file', '.env', *args],
cwd=ROOT,
env=merged,
text=True,
capture_output=True,
)
if check and completed.returncode != 0:
tail = (completed.stderr or completed.stdout or '').strip().splitlines()
raise SystemExit('compose %s failed\n%s' % (' '.join(args), '\n'.join(tail[-20:])))
return completed
def png(width, height):
"""Solid RGB PNG. The file is small; the worker still decodes width*height."""
row = b'\x00' + bytes((40, 90, 160)) * width
raw = row * height
def chunk(tag, data):
return struct.pack('>I', len(data)) + tag + data + struct.pack('>I', zlib.crc32(tag + data) & 0xFFFFFFFF)
ihdr = struct.pack('>IIBBBBB', width, height, 8, 2, 0, 0, 0)
return b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', ihdr) + chunk(b'IDAT', zlib.compress(raw, 1)) + chunk(b'IEND', b'')
def percentile(values, p):
if not values:
return None
ordered = sorted(values)
index = max(0, math.ceil(p * len(ordered)) - 1)
return round(ordered[index], 3)
def parse_mib(text):
match_number = ''
for char in text:
if char.isdigit() or char == '.':
match_number += char
elif match_number:
break
if not match_number:
return None
number = float(match_number)
lower = text.lower()
if 'gib' in lower or lower.startswith(match_number + 'gb'):
return number * 1024
if 'kib' in lower:
return number / 1024
return number
def worker_rss_mib():
completed = subprocess.run(
['docker', 'stats', '--no-stream', '--format', '{{.Name}}\t{{.MemUsage}}'],
text=True,
capture_output=True,
)
if completed.returncode != 0:
return None
peak = None
for line in completed.stdout.splitlines():
if 'worker' not in line:
continue
usage = line.split('\t', 1)[-1].split('/')[0].strip()
value = parse_mib(usage)
if value is not None:
peak = value if peak is None else max(peak, value)
return None if peak is None else round(peak, 1)
def queue_ready():
completed = compose(
['exec', '-T', 'rabbitmq', 'rabbitmqctl', 'list_queues', 'name', 'messages_ready', '--quiet'],
check=False,
)
if completed.returncode != 0:
return None
for line in completed.stdout.splitlines():
parts = line.split()
if len(parts) >= 2 and parts[0] == 'attachment.jobs':
return int(parts[1])
return 0
class Probe(threading.Thread):
"""RSS only. rabbitmqctl is slow and was starving the memory samples."""
def __init__(self):
super().__init__(daemon=True)
self.rss = []
self._stop = threading.Event()
def run(self):
while not self._stop.is_set():
rss = worker_rss_mib()
if rss is not None:
self.rss.append(rss)
def finish(self):
self._stop.set()
self.join(timeout=5)
class Depth(threading.Thread):
def __init__(self):
super().__init__(daemon=True)
self.depth = []
self._stop = threading.Event()
def run(self):
while not self._stop.is_set():
value = queue_ready()
if value is not None:
self.depth.append(value)
self._stop.wait(0.3)
def finish(self):
self._stop.set()
self.join(timeout=5)
def wait_http(base):
deadline = time.monotonic() + 120
while time.monotonic() < deadline:
try:
urllib.request.urlopen(base + '/health/ready', timeout=2).read()
return
except (OSError, urllib.error.URLError):
time.sleep(2)
raise SystemExit('API did not become ready')
def wait_prefetch(value):
needle = 'prefetch %s' % value
deadline = time.monotonic() + 45
while time.monotonic() < deadline:
logs = compose(['logs', 'worker', '--tail', '40'], check=False)
if needle in (logs.stdout or '') or needle in (logs.stderr or ''):
return
time.sleep(1)
raise SystemExit('worker did not log %s' % needle)
def upload_one(client, actor, chat_id, body, filename):
local = Client(client.base, timeout=30)
started = time.monotonic()
try:
response = local.call(
'POST',
'/api/v1/chats/%s/attachments?filename=%s' % (chat_id, filename),
[202, 429],
actor=actor,
raw=body,
headers={'Content-Type': 'image/png'},
schema='Attachment',
)
except Exception as exc:
return {'status': 0, 'error': type(exc).__name__, 'accepted_at': started}
item = {'status': response['status'], 'accepted_at': time.monotonic()}
if response['status'] == 202:
item['id'] = response['json']['id']
return item
def wait_ready(client, actor, items, timeout, worker_started=None):
pending = {item['id']: item for item in items if item.get('id')}
deadline = time.monotonic() + timeout
while pending and time.monotonic() < deadline:
for attachment_id in list(pending):
body = client.call(
'GET',
'/api/v1/attachments/' + attachment_id,
actor=actor,
schema='Attachment',
)['json']
now = time.monotonic()
if body['status'] == 'ready':
item = pending.pop(attachment_id)
item['seconds_to_ready'] = round(now - item['accepted_at'], 3)
if worker_started is not None:
item['drain_s'] = round(now - worker_started, 3)
elif body['status'] == 'failed':
item = pending.pop(attachment_id)
item['failed'] = body.get('error_code')
if pending:
time.sleep(0.25)
return [item['id'] for item in pending.values()]
def summarize(concurrency, items, probe, depth, queued_at_start):
ready = [item for item in items if 'seconds_to_ready' in item]
drains = [item['drain_s'] for item in ready if 'drain_s' in item]
drain_elapsed = max(drains) if drains else 0.001
by_size = {}
for size, _width, _height in SIZES:
sample = [item['seconds_to_ready'] for item in ready if item.get('size') == size]
by_size[size] = {
'n': len(sample),
'p95_s': percentile(sample, 0.95),
}
failed = [item['id'] for item in items if item.get('failed')]
return {
'label': 'compare',
'concurrency_prefetch': concurrency,
'uploaded': len(items),
'ready': len(ready),
'failed': failed,
'drain_s': round(drain_elapsed, 3),
'throughput_ready_per_s': round(len(ready) / drain_elapsed, 3),
'queue_ready_at_start': queued_at_start,
'queue_ready_max': max(depth.depth) if depth.depth else queued_at_start,
'p95_s': percentile([item['seconds_to_ready'] for item in ready], 0.95),
'p95_drain_s': percentile(drains, 0.95),
'p95_by_size': by_size,
'rss_max_mib': max(probe.rss) if probe.rss else None,
'rss_samples': len(probe.rss),
}
def run_setting(client, actor, chat, concurrency, pictures):
"""Stop the worker, accept one backlog, then drain it at this prefetch."""
print('setting prefetch=%s' % concurrency, flush=True)
compose(
['up', '-d', '--no-deps', '--force-recreate', 'worker'],
env={'WORKER_CONCURRENCY': str(concurrency)},
)
wait_prefetch(concurrency)
name = worker_name()
docker(['stop', '-t', '10', name])
with ThreadPoolExecutor(max_workers=6) as pool:
uploaded = list(pool.map(
lambda job: dict(upload_one(client, actor, chat['id'], job[1], job[0] + '.png'), size=job[0]),
pictures,
))
rejected = sum(1 for item in uploaded if item['status'] == 429)
if rejected:
raise SystemExit('comparison burst hit 429 (%s) at prefetch %s' % (rejected, concurrency))
accepted_n = sum(1 for item in uploaded if item['status'] == 202)
queued_at_start = 0
deadline = time.monotonic() + 20
while time.monotonic() < deadline:
queued_at_start = queue_ready() or 0
if queued_at_start >= accepted_n:
break
time.sleep(0.4)
probe = Probe()
depth = Depth()
probe.start()
depth.start()
since = time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime(time.time() - 2))
docker(['start', name])
wait_prefetch_since(name, concurrency, since)
worker_started = time.monotonic()
missing = wait_ready(client, actor, uploaded, 240, worker_started)
probe.finish()
depth.finish()
summary = summarize(concurrency, uploaded, probe, depth, queued_at_start)
summary['still_pending'] = missing
print(json.dumps(summary, ensure_ascii=False), flush=True)
if missing or summary['failed'] or summary['ready'] != len(pictures):
raise SystemExit('prefetch %s did not finish the burst' % concurrency)
return summary
def run_overload(client, actor, chat, limit):
print('overload cap=%s' % limit, flush=True)
name = worker_name()
docker(['stop', '-t', '10', name])
body = png(32, 32)
started = time.monotonic()
with ThreadPoolExecutor(max_workers=8) as pool:
uploaded = list(pool.map(
lambda index: upload_one(client, actor, chat['id'], body, 'overload-%s.png' % index),
range(limit + 8),
))
accepted = [item for item in uploaded if item.get('status') == 202]
rejected = sum(1 for item in uploaded if item.get('status') == 429)
depth = queue_ready()
print('accepted=%s rejected=%s queue_ready=%s' % (len(accepted), rejected, depth), flush=True)
since = time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime(time.time() - 2))
docker(['start', name])
wait_prefetch_since(name, None, since)
missing = wait_ready(client, actor, accepted, 180)
follow = upload_one(client, actor, chat['id'], body, 'after-drain.png')
follow_missing = []
if follow.get('status') == 202:
follow_missing = wait_ready(client, actor, [follow], 120)
elapsed = time.monotonic() - started
summary = {
'label': 'overload',
'cap': limit,
'attempted': len(uploaded),
'accepted': len(accepted),
'rejected_429': rejected,
'queue_ready_while_stopped': depth,
'pending_after_restart': missing,
'follow_up_status': follow.get('status'),
'follow_up_pending': follow_missing,
'elapsed_s': round(elapsed, 3),
'accepted_ids': [item['id'] for item in accepted],
}
print(json.dumps({key: value for key, value in summary.items() if key != 'accepted_ids'}, ensure_ascii=False), flush=True)
if rejected < 1 or not accepted or missing or follow.get('status') != 202 or follow_missing:
raise SystemExit('overload recovery did not complete')
return summary
def main():
values = read_env()
port = values.get('LB_PORT') or '8080'
limit = int(values.get('MAX_INFLIGHT_JOBS') or '20')
base = 'http://127.0.0.1:%s' % port
pictures = []
for name, width, height in SIZES:
body = png(width, height)
pictures.extend((name, body) for _ in range(PER_SIZE))
if '--skip-build' in sys.argv:
print('skip build', flush=True)
compose(['up', '-d'])
else:
print('build and start', flush=True)
compose(['up', '-d', '--build'])
wait_http(base)
client = Client(base, timeout=30)
actor, _bob, _eve, chat = client.bootstrap()
rows = []
try:
for concurrency in SETTINGS:
rows.append(run_setting(client, actor, chat, concurrency, pictures))
overload = run_overload(client, actor, chat, limit)
finally:
saved = values.get('WORKER_CONCURRENCY') or '2'
compose(
['up', '-d', '--no-deps', '--force-recreate', 'worker'],
env={'WORKER_CONCURRENCY': saved},
)
report = {
'base_url': base,
'sizes': [{'name': name, 'width': width, 'height': height, 'count': PER_SIZE} for name, width, height in SIZES],
'note': 'Each setting stops the worker, accepts the same backlog, then starts that prefetch. prefetch equals WORKER_CONCURRENCY. p95_s is client time from the 202 to ready. throughput is ready count divided by drain time after the worker starts. rss_max_mib is the worker container during the drain.',
'runs': rows,
'overload': {key: value for key, value in overload.items() if key != 'accepted_ids'},
}
EVIDENCE.parent.mkdir(parents=True, exist_ok=True)
EVIDENCE.write_text(json.dumps(report, ensure_ascii=False, indent=2) + '\n', encoding='utf-8')
print('wrote %s' % EVIDENCE, flush=True)
if __name__ == '__main__':
main()