1 Commits
Author SHA1 Message Date
Maria 3938900ec6 Лабораторная 5 2026-11-24 17:58:42 +03:00
40 changed files with 3130 additions and 27 deletions
+5
View File
@@ -2,6 +2,7 @@
# These are logical interface suggestions; map actual framework names in REPORT.md.
APP_HOST=0.0.0.0
APP_PORT=8080
HTTP_PORT=8080
APP_ENV=lab
SESSION_TTL_SECONDS=3600
# Choose credentials locally. File paths contain no secret values.
@@ -22,4 +23,8 @@ BROKER_URL_FILE=/run/secrets/broker_url
WORKER_CONCURRENCY=2
JOB_MAX_ATTEMPTS=5
JOB_TIMEOUT_SECONDS=60
JOB_LEASE_SECONDS=90
JOB_RETRY_BASE_SECONDS=1
JOB_RETRY_MAX_SECONDS=60
WORKER_FAULT_INJECTION=
STAGING_RETENTION_SECONDS=86400
+1 -1
View File
@@ -1,7 +1,7 @@
## Лабораторная 5
Автор / группа: TODO
Целевая оценка (3/4/5): TODO
Целевая оценка (3/4/5): 5
Трек 5, если заявлен: TODO
Что реализовано и что перенесено: TODO
+19
View File
@@ -0,0 +1,19 @@
# syntax=docker/dockerfile:1
FROM python:3.11-slim
ENV PYTHONDONTWRITEBYTECODE=1 \
PYTHONUNBUFFERED=1
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
RUN adduser --disabled-password --gecos "" app
USER app
EXPOSE 8080
CMD ["gunicorn", "--bind", "0.0.0.0:8080", "--workers", "2", "--threads", "4", "--timeout", "120", "src.app:app"]
+53 -16
View File
@@ -1,37 +1,74 @@
# Отчёт — лабораторная 5
- Автор, группа: TODO
- Целевая оценка; выбранный трек 5, если нужен: TODO
- Автор, группа: Алексеева Мария БПИ2304
- Целевая оценка: 5; выбранный трек: идемпотентность versioned pipeline
- Commit/PR: TODO после публикации
- Использованные источники, библиотеки и помощь ИИ: TODO
- Источники: README.md, COURSE.md и contracts/ этой лабораторной; библиотеки и версии перечислены в requirements.txt. При реализации использовалась помощь Copilot.
## Запуск из чистого clone
Prerequisites: Docker Engine/Compose, Python 3.11 для локальных public-тестов.
TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных.
```bash
docker compose up -d --build
docker compose ps
python3 tests/smoke.py --base-url http://localhost:8080
```
Сервер ожидает готовности PostgreSQL, SeaweedFS и RabbitMQ. Миграции выполняются приложением при старте.
Учебные volumes удаляются только явной командой:
```bash
docker compose down -v
```
## Архитектура и решения
TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab4, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации.
API: две реплики Flask/Gunicorn за nginx load balancer.
PostgreSQL: users, sessions, chats, membership, messages, idempotency, attachments, jobs.
S3: SeaweedFS для staging и final object storage.
Broker: RabbitMQ с durable topic exchange и durable queue.
Worker: отдельный процесс Python/Pillow переносит original в final prefix и создаёт thumbnail JPEG 256-fit, centered crop JPEG 128x128 и optimized WebP 1280-fit. Pipeline v2 является текущей версией для новых upload (JPEG quality=86, WebP quality=80); сохранённый v1 обрабатывается со своими зафиксированными JPEG quality=88 и WebP quality=82. Версия записана и в job, и в broker event.
Источник истины для метаданных — PostgreSQL. Staging и final bytes — S3. Сообщение брокера содержит только job/attachment ID и служебные поля.
Staging, attachment, job и outbox записываются в одной PostgreSQL-транзакции. Отдельный publisher worker читает unpublished outbox, публикует в RabbitMQ с confirm и только затем устанавливает published_at.
Исходник в staging удаляется только после `ready` и истечения retention (24 часа после последнего обновления); удаление идемпотентно и отмечается в PostgreSQL.
Обработка изображений ограничена размером входа 10 MiB, 40 млн пикселей, timeout=60 секунд и лимитами контейнера worker (1 CPU, 512 MiB). Timeout выполняется отдельным дочерним процессом worker; превышение завершает процесс, не подтверждая сообщение. Устаревшие версии и попытки отсекаются до S3 side effects. EXIF не копируется в варианты; alpha компонуется на белый фон.
Временные ошибки обрабатываются с экспоненциальной задержкой и jitter (1–60 секунд), максимум пять попыток; некорректное изображение завершается без повторов. Lease на 90 секунд длиннее timeout обработки (60 секунд); publisher восстанавливает задачи с истёкшим lease через outbox. Failed jobs записываются в PostgreSQL и маршрутизируются в durable failed queue. Оператор может явно replay только failed-вложение; replay, аудит оператора и новое событие outbox фиксируются атомарно.
## Доказательства критериев
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
| --- | --- | --- | --- |
| Публичный smoke | make test | TODO | TODO |
| Остальные пункты уровня 3 | TODO | TODO | TODO |
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO |
| Выбранный трек 5, если заявлен | TODO | TODO | TODO |
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены.
| Offline contract | python scripts/check_contract.py | PASS: offline skeleton structure, local refs and Python syntax | evidence/first-point.txt |
| OpenAPI | python scripts/validate_openapi.py | PASS: full OpenAPI 3.1 and JSON Schema validation | evidence/first-point.txt |
| Compose | docker compose config --quiet; docker compose up -d --build | Все сервисы запущены и health checks green | evidence/first-point.txt |
| Public smoke через nginx | `python tests/smoke.py --base-url http://127.0.0.1:18080` | PASS: сценарий публичного API лабораторной 5 | evidence/live-runtime.txt |
| Transactional outbox и сохранность принятой задачи | `python scripts/worker_outage_live.py` (worker остановлен при upload; затем полный Compose restart без удаления volumes) | Upload принят как `queued`; после restart `ready|1|1|1` (job status, attempt, outbox events, publisher-confirmed events); исходный файл и подтверждённое сообщение сохранены | evidence/live-runtime.txt, evidence/outbox.txt |
| Image variants | Focused Pillow execution; `python -m unittest discover -s student-tests` | JPEG 256x160, JPEG 128x128, WebP 320x200, no WebP EXIF; all 23 student tests pass | evidence/image-variants.txt |
| Retry, lease, DLQ, replay | `python scripts/replay_live.py`; `python -m unittest discover -s student-tests` | Live failed event получил publisher confirm, явный replay с operator audit вернул attachment в `ready`; искусственно истёкший lease восстановлен до `ready|3|1|1`; unit suite PASS (23 tests) | evidence/live-runtime.txt, evidence/pipeline-faults.txt |
| Versioned pipeline and fault injection | `python scripts/fault_injection_live.py`; `python -m unittest discover -s student-tests` | Live crashes до и после записи original повторно обработаны: обе задачи `ready`, attempt 2, retry recorded, original неизменён. Unit suite дополнительно проверяет duplicate, reorder/stale v1 после v2, fencing и детерминированные ключи | evidence/live-runtime.txt, evidence/pipeline-faults.txt |
| Failover двух API-реплик | `tests/resilience.py --mode failover --action-script scripts/stop-one.cmd` | 101 успешная запись, 1 переходный отказ; восстановление за 0,687 с. Подтверждённые сообщения и вложение сохранились; обе реплики восстановлены | evidence/live-runtime.txt |
| Безопасная очистка staging | Live synthetic-object cleanup scenario | Для синтетического вложения marker удаления установлен, staging object отсутствует, final original сохранён | evidence/live-runtime.txt |
## Эксперименты и отказы
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения.
Трек идемпотентности. Гипотеза: повторная доставка безопасна, если обработчик fenced по номеру попытки и версии pipeline, а S3 side effects используют детерминированные ключи. Инварианты: подтверждённая задача не теряется; устаревшие attempt/version и дубль после `ready` не перезаписывают результат; retry повторно использует ключ original. Методика сочетает 23 unit-теста production worker-функций на in-memory адаптерах с live crash/retry на Compose (PostgreSQL, RabbitMQ и SeaweedFS): failpoints до/после original put, а также worker outage с upload и полным restart стека. В live outage test outbox восстановил единственное задание (`ready|1|1|1`), original остался побайтно неизменным. Оба live crash-сценария завершились `ready|2|1|retry`; replay и expired lease тоже проверены live. Варианты v1/v2 используют фиксированные параметры JPEG/WebP. Доставка остаётся at-least-once, а не exactly-once: безопасность достигается fencing и идемпотентными side effects, не гарантией однократной доставки.
Результаты failover измерены на локальном стенде: две реплики за nginx, 101 успешная запись, один переходный отказ; время до восстановления потока записей — 0,687 с. Это короткий smoke, не нагрузочный benchmark и не оценка p95/p99. В текущей Windows-среде порт 8080 занят другим учебным Compose-проектом, поэтому проверка выполнена через `HTTP_PORT=18080`; его контейнеры не останавливались. Failpoint выключен по умолчанию. Для адресного сбоя worker используется `WORKER_FAULT_INJECTION=<attachment-uuid>:<attempt>:before_original_put`, `after_original_put` или `before_ready_commit`; дочерний worker завершится exit code 86 только для совпавшей задачи/попытки.
Явный replay (только для статуса failed; `OPERATOR_ID` — локальный идентификатор оператора):
```sh
docker compose exec worker python -m src.replay ATTACHMENT_UUID --operator OPERATOR_ID
```
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
| --- | --- | --- | --- |
| TODO | TODO | TODO | TODO |
| Worker остановлен до upload; затем полный restart без удаления volumes | 202/queued не зависит от доступности worker; outbox публикует задание после восстановления | Attachment стал `ready`, состояние `ready|1|1|1`; original и подтверждённое сообщение сохранены | Время отдельно не замерялось; потери подтверждённых данных нет |
| Сбой до записи original в S3 | Retry создаёт original и variants | Live failpoint; job `ready|2|1|retry`, original побайтно совпал | Таймер отдельно не измерялся; потери данных нет |
| Сбой после записи original в S3 | Повтор использует тот же ключ и завершает job без перезаписи другим результатом | Live failpoint; job `ready|2|1|retry`, original побайтно совпал | Таймер отдельно не измерялся; потери данных нет |
| Failed job и явный replay | Ошибка регистрируется и publisher-confirmed; только операторский replay создаёт повтор | Live: replay `ready|1|1|1`, оператор `live-lab5-test`, original совпал | Replay выполнен в пределах 60-секундного test timeout; потери данных нет |
| Истёкший processing lease | Publisher восстанавливает задачу через новое задание | Live recovery завершилась `ready|3|1|1` | В пределах 60-секундного test timeout; дублирующий результат не появился |
| Failover API replica | Оставшаяся реплика принимает записи, ранее подтверждённые данные доступны | 101 успешная запись, один переходный отказ, восстановление за 0,687 с; обе реплики затем подняты | Короткий failover сценарий; подтверждённые сообщения и вложение сохранены |
| Повтор/перестановка сообщения и устаревший v1 после перехода к v2 | Дубль/stale событие не меняет сохранённые результаты | Unit-тесты подтвердили stale/duplicate fencing; live crashes до/после side effect проверены отдельно | Нет потери или перезаписи в проверенных сценариях; доставка по-прежнему at-least-once |
## Ограничения и следующие шаги
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза.
Все пункты базовой реализации и выбранный трек проверены unit-тестами и live-сценариями на Compose. Текущий стенд лабораторной оставлен запущенным на порту 18080; volumes сохраняются. Очистка данных намеренно не выполнялась.
+133
View File
@@ -0,0 +1,133 @@
name: mtusi-lab5
services:
postgres:
image: postgres:16.10
environment:
POSTGRES_DB: messenger
POSTGRES_USER: messenger
POSTGRES_PASSWORD: messenger
volumes:
- postgres-data:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U messenger -d messenger"]
interval: 5s
timeout: 3s
retries: 20
s3:
image: chrislusf/seaweedfs:4.02
command: server -s3 -dir=/data -s3.port=9000 -s3.config=/etc/seaweedfs/s3.json
volumes:
- s3-data:/data
- ./infra/seaweedfs-s3.json:/etc/seaweedfs/s3.json:ro
ports:
- "9000:9000"
healthcheck:
test: ["CMD-SHELL", "wget -q -O /dev/null http://127.0.0.1:9333/cluster/status"]
interval: 5s
timeout: 3s
retries: 20
broker:
image: rabbitmq:3.13-management
volumes:
- broker-data:/var/lib/rabbitmq
ports:
- "15672:15672"
healthcheck:
test: ["CMD", "rabbitmq-diagnostics", "-q", "ping"]
interval: 5s
timeout: 5s
retries: 30
api1:
build: .
environment: &api-env
DATABASE_URL: postgresql://messenger:messenger@postgres:5432/messenger
S3_ENDPOINT: http://s3:9000
S3_REGION: us-east-1
S3_BUCKET: messenger-attachments
S3_ACCESS_KEY_ID: minioadmin
S3_SECRET_ACCESS_KEY: minioadmin123
BROKER_URL: amqp://guest:guest@broker:5672/%2F
SESSION_TTL_SECONDS: "3600"
API_INSTANCE_ID: api-1
depends_on:
postgres:
condition: service_healthy
s3:
condition: service_healthy
broker:
condition: service_healthy
healthcheck:
test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8080/health/live')"]
interval: 5s
timeout: 3s
retries: 20
api2:
build: .
environment:
<<: *api-env
API_INSTANCE_ID: api-2
depends_on:
postgres:
condition: service_healthy
s3:
condition: service_healthy
broker:
condition: service_healthy
healthcheck:
test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8080/health/live')"]
interval: 5s
timeout: 3s
retries: 20
load-balancer:
image: nginx:1.28.0
volumes:
- ./nginx.conf:/etc/nginx/nginx.conf:ro
ports:
- "${HTTP_PORT:-8080}:8080"
depends_on:
api1:
condition: service_healthy
api2:
condition: service_healthy
worker:
build: .
command: ["python", "-m", "src.worker"]
environment:
DATABASE_URL: postgresql://messenger:messenger@postgres:5432/messenger
S3_ENDPOINT: http://s3:9000
S3_REGION: us-east-1
S3_BUCKET: messenger-attachments
S3_ACCESS_KEY_ID: minioadmin
S3_SECRET_ACCESS_KEY: minioadmin123
BROKER_URL: amqp://guest:guest@broker:5672/%2F
WORKER_CONCURRENCY: "2"
JOB_MAX_ATTEMPTS: "5"
JOB_TIMEOUT_SECONDS: "60"
JOB_LEASE_SECONDS: "90"
JOB_RETRY_BASE_SECONDS: "1"
JOB_RETRY_MAX_SECONDS: "60"
WORKER_FAULT_INJECTION: "${WORKER_FAULT_INJECTION:-}"
STAGING_RETENTION_SECONDS: "86400"
MAX_UPLOAD_BYTES: "10485760"
MAX_IMAGE_PIXELS: "40000000"
mem_limit: 512m
cpus: 1.0
depends_on:
postgres:
condition: service_healthy
s3:
condition: service_healthy
broker:
condition: service_healthy
volumes:
postgres-data:
s3-data:
broker-data:
+14
View File
@@ -0,0 +1,14 @@
python scripts/check_contract.py
PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
python scripts/validate_openapi.py
PASS: full OpenAPI 3.1 and JSON Schema validation; application NOT tested.
docker compose config --quiet
PASS
docker compose up -d --build
PASS; postgres, s3, broker, api1, api2, load-balancer and worker started.
docker exec mtusi-lab5-api1-1 python tests/smoke.py --base-url http://127.0.0.1:8080
PASS: lab5 public API scenario; infrastructure and grading evidence remain separate.
+12
View File
@@ -0,0 +1,12 @@
Focused code execution using Pillow 12, executing the actual worker image functions:
input: RGBA PNG, 320x200
thumbnail: JPEG 256x160
crop: JPEG 128x128
optimized: WebP 320x200 (small source was not upscaled)
EXIF: absent from WebP result
Focused execution output: PASS.
Unit tests:
python -m unittest discover -s student-tests
Result: PASS (23 tests).
+53
View File
@@ -0,0 +1,53 @@
Live runtime verification
=========================
Environment:
Windows; Docker Compose stack for this repository.
HTTP_PORT=18080 because port 8080 was occupied by another lab; that stack was not stopped.
Tests use synthetic users, messages, and images only. No volumes were removed.
Public API smoke through nginx:
python tests/smoke.py --base-url http://127.0.0.1:18080
PASS: lab5 public API scenario.
Accepted upload while worker was stopped, then full stack restart:
BASE_URL=http://127.0.0.1:18080 HTTP_PORT=18080 python scripts/worker_outage_live.py
PASS:
accepted_status=queued
final_status=ready
durable job/outbox state=ready|1|1|1
original_unchanged=true
confirmed_message_preserved=true
The test stops only this lab's worker, uploads an attachment and confirms the API
remains available, then runs scripts/restart.cmd (compose down/up without -v).
It verifies the same attachment and confirmed message after recovery.
Crash immediately before and after original S3 put:
BASE_URL=http://127.0.0.1:18080 HTTP_PORT=18080 python scripts/fault_injection_live.py
PASS:
before_original_put: ready|2|1|retry; original_unchanged=true
after_original_put: ready|2|1|retry; original_unchanged=true
Failed event, explicit replay, and expired lease:
BASE_URL=http://127.0.0.1:18080 HTTP_PORT=18080 python scripts/replay_live.py
PASS:
failed_event_published=true
replay_state=ready|1|1|1
lease_recovery_state=ready|3|1|1
operator=live-lab5-test
original_unchanged=true
API replica failover:
tests/resilience.py --mode failover --action-script scripts/stop-one.cmd
PASS: two API instances observed before failure; 101 successful writes,
1 transition failure, first recovery in 0.687 seconds. Confirmed messages and
attachment remained available; both API replicas were restored after the test.
This is a short failover test, not a load benchmark or p95/p99 measurement.
Staging cleanup:
Synthetic attachment cleanup scenario: deletion marker recorded, staging object
absent, final original still present.
All live test scripts use unique synthetic records. Runtime failpoint injection is
disabled by default and was cleared after testing. No user data or secrets are in
this evidence.
+18
View File
@@ -0,0 +1,18 @@
Migration: migrations/001_lab5.sql
Outbox table verified in PostgreSQL.
Observed after public smoke:
event_type=attachment.process
publish_attempt=1
published_at=2026-11-24 13:36:03.511287+00
job status=ready
Publisher behavior:
- API inserts staging, attachment, job and outbox in one transaction.
- Worker publisher polls unpublished rows.
- Publish is accepted only through RabbitMQ publisher confirm.
- published_at is set only after confirm.
Live recovery of a queued attachment with the worker stopped and the full Compose
stack restarted is recorded in evidence/live-runtime.txt. The job completed from
the durable outbox without a new client upload.
+30
View File
@@ -0,0 +1,30 @@
Command:
python -m unittest discover -s student-tests
Result:
PASS (23 tests)
Fault-injection coverage:
- Triggered the production child-exit failpoint before and after the original S3 write
(the test substitutes os._exit with a sentinel exception to inspect resulting state).
- Verified retry is scheduled with the next attempt number.
- Verified stale first-attempt redelivery does not create side effects.
- Verified retry uses deterministic object keys and reaches ready.
- Verified duplicate delivery after ready does not overwrite objects.
- Verified a v1 event cannot process or overwrite a v2 job; the v2 event completes.
- Verified pipeline versions use distinct, fixed encoding qualities.
- Verified staging cleanup ignores processing jobs and is idempotent for ready jobs.
- Verified publisher marks outbox published only after confirm; publish failure remains retryable.
- Verified expired leases enqueue the next attempt.
- Verified replay is limited to failed attachments and writes operator audit/outbox intent.
- Verified permanent failures and exhausted retries are registered and routed to the failed event.
Scope:
The tests exercise production worker functions with in-memory PostgreSQL/S3 adapters.
Live Docker/PostgreSQL/S3/RabbitMQ crash scenarios were also verified; see
evidence/live-runtime.txt for the exact scenarios and observed states.
Invariants:
- HTTP-accepted jobs have staging, job, and outbox intent committed atomically (see evidence/outbox.txt).
- The worker acknowledges only after a ready/failed state or a retry outbox event is committed.
- Delivery is at-least-once, not exactly-once; deterministic keys and version/attempt fences make repeats safe.
+14
View File
@@ -0,0 +1,14 @@
{
"identities": [
{
"name": "lab",
"credentials": [
{
"accessKey": "minioadmin",
"secretKey": "minioadmin123"
}
],
"actions": ["Admin", "Read", "Write", "List"]
}
]
}
+113
View File
@@ -0,0 +1,113 @@
CREATE TABLE IF NOT EXISTS users (
id UUID PRIMARY KEY,
username VARCHAR(32) UNIQUE NOT NULL,
display_name VARCHAR(100) NOT NULL,
password_hash TEXT NOT NULL,
created_at TIMESTAMPTZ NOT NULL
);
CREATE TABLE IF NOT EXISTS sessions (
token TEXT PRIMARY KEY,
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
expires_at TIMESTAMPTZ NOT NULL
);
CREATE TABLE IF NOT EXISTS chats (
id UUID PRIMARY KEY,
title VARCHAR(100) NOT NULL,
created_at TIMESTAMPTZ NOT NULL
);
CREATE TABLE IF NOT EXISTS chat_members (
chat_id UUID NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
PRIMARY KEY (chat_id, user_id)
);
CREATE TABLE IF NOT EXISTS messages (
id UUID PRIMARY KEY,
chat_id UUID NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
sender_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
text VARCHAR(4000) NOT NULL,
attachment_ids JSONB NOT NULL DEFAULT '[]',
created_at TIMESTAMPTZ NOT NULL
);
CREATE TABLE IF NOT EXISTS idempotency (
user_id UUID NOT NULL,
chat_id UUID NOT NULL,
key TEXT NOT NULL,
request_hash TEXT NOT NULL,
message_id UUID NOT NULL,
response JSONB NOT NULL,
expires_at TIMESTAMPTZ NOT NULL,
PRIMARY KEY (user_id, chat_id, key)
);
CREATE TABLE IF NOT EXISTS attachments (
id UUID PRIMARY KEY,
chat_id UUID NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
owner_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
filename VARCHAR(255) NOT NULL,
content_type VARCHAR(32) NOT NULL,
size_bytes INTEGER NOT NULL,
sha256 VARCHAR(64) NOT NULL,
staging_key TEXT NOT NULL,
original_key TEXT,
status VARCHAR(16) NOT NULL,
variants JSONB NOT NULL DEFAULT '[]',
error_code TEXT,
created_at TIMESTAMPTZ NOT NULL,
updated_at TIMESTAMPTZ NOT NULL
);
ALTER TABLE attachments
ADD COLUMN IF NOT EXISTS staging_deleted_at TIMESTAMPTZ;
CREATE TABLE IF NOT EXISTS jobs (
id UUID PRIMARY KEY,
attachment_id UUID UNIQUE NOT NULL REFERENCES attachments(id) ON DELETE CASCADE,
pipeline_version INTEGER NOT NULL DEFAULT 1,
attempt INTEGER NOT NULL DEFAULT 0,
status VARCHAR(16) NOT NULL,
created_at TIMESTAMPTZ NOT NULL,
updated_at TIMESTAMPTZ NOT NULL
);
ALTER TABLE jobs
ADD COLUMN IF NOT EXISTS lease_until TIMESTAMPTZ,
ADD COLUMN IF NOT EXISTS replay_count INTEGER NOT NULL DEFAULT 0,
ADD COLUMN IF NOT EXISTS last_error_code TEXT;
CREATE TABLE IF NOT EXISTS outbox (
id UUID PRIMARY KEY,
event_type VARCHAR(64) NOT NULL,
payload JSONB NOT NULL,
published_at TIMESTAMPTZ,
publish_attempt INTEGER NOT NULL DEFAULT 0,
created_at TIMESTAMPTZ NOT NULL
);
ALTER TABLE outbox
ADD COLUMN IF NOT EXISTS available_at TIMESTAMPTZ NOT NULL DEFAULT NOW();
CREATE INDEX IF NOT EXISTS outbox_available_idx
ON outbox(available_at,created_at)
WHERE published_at IS NULL;
CREATE TABLE IF NOT EXISTS job_attempts (
id BIGSERIAL PRIMARY KEY,
job_id UUID NOT NULL REFERENCES jobs(id) ON DELETE CASCADE,
attempt INTEGER NOT NULL,
outcome VARCHAR(16) NOT NULL,
error_code TEXT NOT NULL,
occurred_at TIMESTAMPTZ NOT NULL
);
CREATE TABLE IF NOT EXISTS job_replays (
id UUID PRIMARY KEY,
job_id UUID NOT NULL REFERENCES jobs(id) ON DELETE CASCADE,
attachment_id UUID NOT NULL REFERENCES attachments(id) ON DELETE CASCADE,
operator TEXT NOT NULL,
replayed_at TIMESTAMPTZ NOT NULL
);
+24
View File
@@ -0,0 +1,24 @@
events {}
http {
upstream api {
server api1:8080 max_fails=1 fail_timeout=5s;
server api2:8080 max_fails=1 fail_timeout=5s;
}
server {
listen 8080;
client_max_body_size 11m;
location / {
proxy_pass http://api;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Authorization $http_authorization;
proxy_set_header Idempotency-Key $http_idempotency_key;
proxy_connect_timeout 1s;
proxy_read_timeout 5s;
proxy_next_upstream error timeout http_502 http_503 http_504;
proxy_next_upstream_tries 2;
}
}
}
+7
View File
@@ -0,0 +1,7 @@
Flask==3.1.2
gunicorn==23.0.0
psycopg[binary]==3.2.12
bcrypt==4.3.0
boto3==1.40.64
Pillow==12.0.0
pika==1.3.2
+4 -4
View File
@@ -8,8 +8,8 @@ import re
ROOT = Path(__file__).resolve().parents[1]
def main():
lab = json.loads((ROOT/'lab.json').read_text())['number']
spec = json.loads((ROOT/'contracts/openapi.json').read_text())
lab = json.loads((ROOT/'lab.json').read_text(encoding='utf-8'))['number']
spec = json.loads((ROOT/'contracts/openapi.json').read_text(encoding='utf-8'))
assert spec['openapi']=='3.1.0'
assert spec['info']['version']=='1.%d.0'%lab
operation_ids = set()
@@ -41,11 +41,11 @@ def main():
assert ('/api/v1/auth/sessions' in spec['paths']) == (lab>=2)
assert ('/api/v1/attachments/{attachment_id}' in spec['paths']) == (lab>=4)
for file in list((ROOT/'tests').glob('*.py'))+list((ROOT/'scripts').glob('*.py')):
ast.parse(file.read_text(),filename=str(file))
ast.parse(file.read_text(encoding='utf-8'),filename=str(file))
for file in ROOT.rglob('*.json'):
if any(part in {'.git','.venv','node_modules','vendor','output'} for part in file.parts):
continue
json.loads(file.read_text())
json.loads(file.read_text(encoding='utf-8'))
for required in ('README.md','COURSE.md','CONTRIBUTING.md','REPORT.md','contracts/README.md','tests/smoke.py','tests/README.md'):
assert (ROOT/required).is_file(), 'missing '+required
print('PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.')
+94
View File
@@ -0,0 +1,94 @@
#!/usr/bin/env python3
"""Exercise worker crash failpoints against the running local Compose stack."""
import json
import os
from pathlib import Path
import subprocess
import sys
from urllib.parse import urlparse
import uuid
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, LAB, check
def compose(args, env, timeout=90):
result = subprocess.run(
["docker", "compose", *args],
cwd=ROOT,
env=env,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
timeout=timeout,
)
if result.returncode:
raise RuntimeError("docker compose failed: " + "\n".join(result.stdout.splitlines()[-25:]))
return result.stdout.strip()
def retry_record(attachment_id, env):
attachment_id = str(uuid.UUID(attachment_id))
query = (
"SELECT concat_ws('|',j.status,j.attempt::text,count(ja.id)::text,"
"coalesce(min(ja.outcome),'none')) "
"FROM jobs j LEFT JOIN job_attempts ja ON ja.job_id=j.id "
f"WHERE j.attachment_id='{attachment_id}' GROUP BY j.id"
)
return compose(
["exec", "-T", "postgres", "psql", "-X", "-A", "-t", "-U", "messenger", "-d", "messenger", "-c", query],
env,
timeout=15,
).strip()
def main():
if LAB < 5:
raise RuntimeError("live fault injection requires lab5")
base_url = os.environ.get("BASE_URL", "http://localhost:8080")
parsed = urlparse(base_url)
if not parsed.hostname:
raise ValueError("BASE_URL must be an absolute HTTP(S) URL")
env = dict(os.environ)
env["HTTP_PORT"] = str(parsed.port or (443 if parsed.scheme == "https" else 80))
env["WORKER_FAULT_INJECTION"] = ""
client = Client(base_url, timeout=10)
alice, _, _, chat = client.bootstrap()
results = []
try:
for stage in ("before_original_put", "after_original_put"):
compose(["stop", "worker"], env)
attachment, original = client.attachment(alice, chat)
injection_env = dict(env)
injection_env["WORKER_FAULT_INJECTION"] = f"{attachment['id']}:1:{stage}"
compose(["up", "-d", "--force-recreate", "worker"], injection_env)
ready = client.wait_ready(alice, attachment, wait_seconds=60)
downloaded = client.call(
"GET",
f"/api/v1/attachments/{attachment['id']}/content",
actor=alice,
)
check(downloaded["bytes"] == original, "original changed during injected retry")
check({item["name"] for item in ready["variants"]} == {"thumbnail", "crop", "optimized"},
"retry did not create all pipeline variants")
record = retry_record(attachment["id"], env)
check(record == "ready|2|1|retry", "injected crash did not recover through retry: " + record)
results.append({
"stage": stage,
"attachment_id": attachment["id"],
"status": ready["status"],
"job_retry_record": record,
"original_unchanged": True,
})
finally:
env["WORKER_FAULT_INJECTION"] = ""
compose(["up", "-d", "--force-recreate", "worker"], env)
print(json.dumps({"result": "PASS", "faults": results}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
+178
View File
@@ -0,0 +1,178 @@
#!/usr/bin/env python3
"""Verify failed-job routing and explicit replay against the local Compose stack."""
import os
from pathlib import Path
import subprocess
import sys
import time
import uuid
from urllib.parse import urlparse
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, LAB, check
def compose(args, env, input_bytes=None, timeout=90):
result = subprocess.run(
["docker", "compose", *args],
cwd=ROOT,
env=env,
input=input_bytes,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
timeout=timeout,
)
if result.returncode:
output = result.stdout.decode("utf-8", errors="replace")
raise RuntimeError("docker compose failed: " + "\n".join(output.splitlines()[-25:]))
return result.stdout.decode("utf-8", errors="replace").strip()
def put_staging_object(key, data, env):
code = (
"import os,sys,boto3; "
"from botocore.config import Config; "
"boto3.client('s3',endpoint_url=os.environ['S3_ENDPOINT'],"
"region_name=os.environ.get('S3_REGION','us-east-1'),"
"aws_access_key_id=os.environ['S3_ACCESS_KEY_ID'],"
"aws_secret_access_key=os.environ['S3_SECRET_ACCESS_KEY'],"
"config=Config(signature_version='s3v4',s3={'addressing_style':'path'})).put_object("
"Bucket=os.environ['S3_BUCKET'],Key=sys.argv[1],Body=sys.stdin.buffer.read(),"
"ContentType='image/png')"
)
compose(
["run", "--rm", "--no-deps", "-T", "--entrypoint", "python", "worker", "-c", code, key],
env,
input_bytes=data,
timeout=45,
)
def psql(query, env):
return compose(
["exec", "-T", "postgres", "psql", "-X", "-A", "-t", "-U", "messenger", "-d", "messenger", "-c", query],
env,
timeout=15,
)
def main():
if LAB < 5:
raise RuntimeError("live replay test requires lab5")
base_url = os.environ.get("BASE_URL", "http://localhost:8080")
parsed = urlparse(base_url)
if not parsed.hostname:
raise ValueError("BASE_URL must be an absolute HTTP(S) URL")
env = dict(os.environ)
env["HTTP_PORT"] = str(parsed.port or (443 if parsed.scheme == "https" else 80))
env["WORKER_FAULT_INJECTION"] = ""
client = Client(base_url, timeout=10)
alice, _, _, chat = client.bootstrap()
attachment = None
original = None
staging_key = None
try:
compose(["stop", "worker"], env)
attachment, original = client.attachment(alice, chat)
staging_key = f"staging/{attachment['id']}/original"
put_staging_object(staging_key, b"invalid-test-payload", env)
compose(["up", "-d", "worker"], env)
deadline = time.monotonic() + 60
failed = None
while time.monotonic() < deadline:
failed = client.call(
"GET",
f"/api/v1/attachments/{attachment['id']}",
actor=alice,
schema="Attachment",
)["json"]
if failed["status"] == "failed":
break
time.sleep(0.25)
check(failed is not None and failed["status"] == "failed", "invalid staging object did not fail permanently")
check(failed["error_code"] == "processing_failed", "unexpected permanent error code")
attachment_id = str(uuid.UUID(attachment["id"]))
failed_event_count = psql(
"SELECT count(*) FROM outbox WHERE event_type='attachment.failed' "
f"AND payload->>'attachment_id'='{attachment_id}' AND published_at IS NOT NULL",
env,
)
check(failed_event_count == "1", "failed event was not publisher-confirmed")
put_staging_object(staging_key, original, env)
replay_output = compose(
["exec", "-T", "worker", "python", "-m", "src.replay", attachment_id, "--operator", "live-lab5-test"],
env,
timeout=30,
)
ready = client.wait_ready(alice, failed, wait_seconds=60)
downloaded = client.call(
"GET",
f"/api/v1/attachments/{attachment_id}/content",
actor=alice,
)
check(downloaded["bytes"] == original, "replayed original differs from accepted bytes")
state = psql(
"SELECT concat_ws('|',j.status,j.attempt::text,j.replay_count::text,count(ja.id)::text) "
"FROM jobs j LEFT JOIN job_attempts ja ON ja.job_id=j.id "
f"WHERE j.attachment_id='{attachment_id}' GROUP BY j.id",
env,
)
check(state == "ready|1|1|1", "unexpected job state after replay: " + state)
operator = psql(
"SELECT operator FROM job_replays "
f"WHERE attachment_id='{attachment_id}' ORDER BY replayed_at DESC LIMIT 1",
env,
)
check(operator == "live-lab5-test", "replay audit entry is missing")
psql(
"UPDATE jobs SET status='processing',attempt=2,lease_until=NOW()-INTERVAL '1 second' "
f"WHERE attachment_id='{attachment_id}'; "
"UPDATE attachments SET status='processing',updated_at=NOW() "
f"WHERE id='{attachment_id}'",
env,
)
lease_deadline = time.monotonic() + 60
leased = None
while time.monotonic() < lease_deadline:
leased = client.call(
"GET",
f"/api/v1/attachments/{attachment_id}",
actor=alice,
schema="Attachment",
)["json"]
if leased["status"] == "ready":
break
time.sleep(0.25)
check(leased is not None and leased["status"] == "ready", "expired lease did not recover")
lease_state = psql(
"SELECT concat_ws('|',j.status,j.attempt::text,j.replay_count::text,count(ja.id)::text) "
"FROM jobs j LEFT JOIN job_attempts ja ON ja.job_id=j.id "
f"WHERE j.attachment_id='{attachment_id}' GROUP BY j.id",
env,
)
check(lease_state == "ready|3|1|1", "unexpected state after lease recovery: " + lease_state)
print({
"result": "PASS",
"attachment_id": attachment_id,
"failed_event_published": True,
"replay_state": state,
"lease_recovery_state": lease_state,
"operator": operator,
"original_unchanged": True,
"replay_command_result": replay_output,
"final_status": ready["status"],
})
finally:
if attachment and original and staging_key:
put_staging_object(staging_key, original, env)
compose(["up", "-d", "worker"], env)
if __name__ == "__main__":
main()
+7
View File
@@ -0,0 +1,7 @@
@echo off
setlocal
cd /d "%~dp0.."
docker compose down
if errorlevel 1 exit /b 1
docker compose up -d
exit /b %errorlevel%
+5
View File
@@ -0,0 +1,5 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
docker compose down
docker compose up -d
+13
View File
@@ -0,0 +1,13 @@
@echo off
setlocal
cd /d "%~dp0.."
if /I "%TARGET_INSTANCE_ID%"=="api-1" (
docker compose stop api1
exit /b %errorlevel%
)
if /I "%TARGET_INSTANCE_ID%"=="api-2" (
docker compose stop api2
exit /b %errorlevel%
)
echo Unknown TARGET_INSTANCE_ID 1>&2
exit /b 1
+16
View File
@@ -0,0 +1,16 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
case "${TARGET_INSTANCE_ID:-}" in
api-1)
docker compose stop api1
;;
api-2)
docker compose stop api2
;;
*)
echo "Unknown TARGET_INSTANCE_ID" >&2
exit 1
;;
esac
+3 -3
View File
@@ -6,17 +6,17 @@ from openapi_spec_validator import validate
from jsonschema import Draft202012Validator
root = Path(__file__).resolve().parents[1]
spec = json.loads((root/'contracts/openapi.json').read_text())
spec = json.loads((root/'contracts/openapi.json').read_text(encoding='utf-8'))
validate(spec)
from referencing import Registry, Resource
# The base URI resolves local #/components references inside examples.
resource = dict(spec, **{'$schema': 'https://json-schema.org/draft/2020-12/schema'})
registry = Registry().with_resource('urn:mtusi:openapi', Resource.from_contents(resource))
for name, example in json.loads((root/'contracts/examples.json').read_text()).items():
for name, example in json.loads((root/'contracts/examples.json').read_text(encoding='utf-8')).items():
schema = {'$ref': 'urn:mtusi:openapi#/components/schemas/' + name}
Draft202012Validator(schema, registry=registry).validate(example)
for path in (root/'contracts').glob('*.schema.json'):
schema = json.loads(path.read_text())
schema = json.loads(path.read_text(encoding='utf-8'))
Draft202012Validator.check_schema(schema)
for example in schema.get('examples',[]):
Draft202012Validator(schema).validate(example)
+129
View File
@@ -0,0 +1,129 @@
#!/usr/bin/env python3
"""Verify an accepted attachment survives worker and full-stack restart."""
import os
from pathlib import Path
import subprocess
import sys
import time
import uuid
from urllib.parse import urlparse
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, Failure, LAB, check
def compose(args, env, timeout=120):
result = subprocess.run(
["docker", "compose", *args],
cwd=ROOT,
env=env,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
timeout=timeout,
)
if result.returncode:
raise RuntimeError("docker compose failed: " + "\n".join(result.stdout.splitlines()[-25:]))
return result.stdout.strip()
def main():
if LAB < 5:
raise RuntimeError("worker outage test requires lab5")
base_url = os.environ.get("BASE_URL", "http://localhost:8080")
parsed = urlparse(base_url)
if not parsed.hostname:
raise ValueError("BASE_URL must be an absolute HTTP(S) URL")
env = dict(os.environ)
env["HTTP_PORT"] = str(parsed.port or (443 if parsed.scheme == "https" else 80))
env["WORKER_FAULT_INJECTION"] = ""
client = Client(base_url, timeout=10)
alice, _, _, chat = client.bootstrap()
worker_stopped = False
try:
compose(["stop", "worker"], env)
worker_stopped = True
attachment, original = client.attachment(alice, chat)
check(attachment["status"] == "queued", "upload was not accepted as queued")
unavailable = client.call(
"GET",
f"/api/v1/attachments/{attachment['id']}/content",
expected=409,
actor=alice,
)
check(unavailable["json"]["error"]["code"] == "conflict", "queued content was not rejected")
confirmed_message = client.message(alice, chat, "API remains available while worker is stopped")
restart = subprocess.run(
[str(ROOT / "scripts" / "restart.cmd")],
cwd=ROOT,
env=env,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
timeout=120,
)
if restart.returncode:
raise RuntimeError("restart hook failed: " + "\n".join(restart.stdout.splitlines()[-25:]))
worker_stopped = False
deadline = time.monotonic() + 90
while True:
try:
client.call("GET", "/health/ready", schema="Health")
client.call("GET", "/api/v1/users/me", actor=alice, schema="User")
break
except Failure:
if time.monotonic() >= deadline:
raise
time.sleep(0.5)
ready = client.wait_ready(alice, attachment, wait_seconds=60)
downloaded = client.call(
"GET",
f"/api/v1/attachments/{attachment['id']}/content",
actor=alice,
)
check(downloaded["bytes"] == original, "accepted original changed across restart")
message_page = client.call(
"GET",
f"/api/v1/chats/{chat['id']}/messages?limit=100",
actor=alice,
schema="MessagePage",
)["json"]
check(any(item == confirmed_message["json"] for item in message_page["items"]),
"confirmed message was lost across restart")
attachment_id = str(uuid.UUID(attachment["id"]))
query = (
"SELECT concat_ws('|',j.status,j.attempt::text,"
"(SELECT count(*) FROM outbox o WHERE o.event_type='attachment.process' "
f"AND o.payload->>'attachment_id'='{attachment_id}'),"
"(SELECT count(*) FROM outbox o WHERE o.event_type='attachment.process' "
f"AND o.payload->>'attachment_id'='{attachment_id}' AND o.published_at IS NOT NULL)) "
f"FROM jobs j WHERE j.attachment_id='{attachment_id}'"
)
state = compose(
["exec", "-T", "postgres", "psql", "-X", "-A", "-t", "-U", "messenger", "-d", "messenger", "-c", query],
env,
timeout=15,
)
check(state == "ready|1|1|1", "unexpected durable job/outbox state: " + state)
print({
"result": "PASS",
"attachment_id": attachment_id,
"accepted_status": attachment["status"],
"final_status": ready["status"],
"state": state,
"original_unchanged": True,
"confirmed_message_preserved": True,
})
finally:
if worker_stopped:
compose(["up", "-d", "worker"], env)
if __name__ == "__main__":
main()
View File
+756
View File
@@ -0,0 +1,756 @@
import base64
import hashlib
import io
import json
import os
import re
import secrets
import uuid
from datetime import datetime, timedelta, timezone
from pathlib import Path
import bcrypt
from flask import Flask, Response, g, jsonify, request
from PIL import Image, ImageOps
from .broker import ensure_topology
from .db import transaction
from .pipeline import CURRENT_PIPELINE_VERSION
from .storage import ensure_bucket, put_object, s3_client
app = Flask(__name__)
app.config["MAX_CONTENT_LENGTH"] = 10 * 1024 * 1024 + 1024
INSTANCE_ID = os.environ.get("API_INSTANCE_ID") or secrets.token_hex(8)
SESSION_TTL = int(os.environ.get("SESSION_TTL_SECONDS", "3600"))
USERNAME_RE = re.compile(r"^[a-z0-9_]{3,32}$")
def utc_now():
return datetime.now(timezone.utc)
def rfc3339(value):
if isinstance(value, str):
value = datetime.fromisoformat(value.replace("Z", "+00:00"))
return value.astimezone(timezone.utc).isoformat(timespec="seconds").replace("+00:00", "Z")
def request_id():
rid = getattr(g, "request_id", None)
if rid is None:
rid = request.headers.get("X-Request-Id") or str(uuid.uuid4())
g.request_id = rid
return rid
@app.after_request
def add_headers(response):
response.headers["X-Request-Id"] = request_id()
response.headers["X-Instance-Id"] = INSTANCE_ID
return response
def error(status, code, message, headers=None):
rid = request_id()
response = jsonify({"error": {"code": code, "message": message, "request_id": rid}})
response.status_code = status
if headers:
for key, value in headers.items():
response.headers[key] = value
return response
def parse_json():
if not request.is_json:
return None
try:
value = request.get_json(silent=False)
except Exception:
return None
return value if isinstance(value, dict) else None
def user_row(row):
return {
"id": str(row["id"]),
"username": row["username"],
"display_name": row["display_name"],
"created_at": rfc3339(row["created_at"]),
}
def bearer_user():
authorization = request.headers.get("Authorization", "")
if not authorization.lower().startswith("bearer ") or " " not in authorization:
return None
token = authorization.split(None, 1)[1].strip()
if not token:
return None
with transaction() as conn:
row = conn.execute(
"""
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=%s
""",
(token,),
).fetchone()
if not row or row["expires_at"] <= utc_now():
return None
return row
def require_bearer():
row = bearer_user()
if not row:
return None, error(
401,
"unauthorized",
"Требуется действительная сессия",
{"WWW-Authenticate": 'Bearer realm="messenger"'},
)
return row, None
def chat_row(row, member_ids):
return {
"id": str(row["id"]),
"title": row["title"],
"member_ids": member_ids,
"created_at": rfc3339(row["created_at"]),
}
def chat_is_member(conn, chat_id, user_id):
row = conn.execute(
"SELECT 1 FROM chat_members WHERE chat_id=%s AND user_id=%s",
(chat_id, user_id),
).fetchone()
return row is not None
def encode_cursor(created_at, message_id):
if isinstance(created_at, str):
created_at = datetime.fromisoformat(created_at.replace("Z", "+00:00"))
stamp = created_at.astimezone(timezone.utc).isoformat(timespec="microseconds")
value = f"{stamp}|{message_id}"
return base64.urlsafe_b64encode(value.encode()).decode().rstrip("=")
def decode_cursor(cursor):
try:
padded = cursor + "=" * (-len(cursor) % 4)
value = base64.urlsafe_b64decode(padded).decode()
stamp, message_id = value.split("|", 1)
return datetime.fromisoformat(stamp.replace("Z", "+00:00")), uuid.UUID(message_id)
except Exception:
return None
def migrate():
migration = Path(__file__).resolve().parents[1] / "migrations" / "001_lab5.sql"
with transaction() as conn:
conn.execute(migration.read_text(encoding="utf-8"))
ensure_bucket()
ensure_topology()
try:
migrate()
except Exception as exc:
app.logger.warning("Startup migration deferred: %s", type(exc).__name__)
@app.get("/health/live")
def health_live():
return jsonify({"status": "ok"})
@app.get("/health/ready")
def health_ready():
try:
with transaction() as conn:
conn.execute("SELECT 1").fetchone()
ensure_bucket()
ensure_topology()
return jsonify({"status": "ok"})
except Exception:
return error(503, "unavailable", "Сервис временно недоступен")
@app.post("/api/v1/users")
def create_user():
body = parse_json()
if body is None:
return error(400, "invalid_request", "Некорректный JSON")
allowed = {"username", "display_name", "password"}
if set(body) != allowed:
return error(400, "invalid_request", "Неверные поля запроса")
username = body["username"]
display_name = body["display_name"]
password = body["password"]
if not isinstance(username, str) or not USERNAME_RE.match(username):
return error(400, "invalid_request", "Некорректное имя пользователя")
if not isinstance(display_name, str) or not display_name.strip() or len(display_name) > 100:
return error(400, "invalid_request", "Некорректное отображаемое имя")
if not isinstance(password, str) or not 12 <= len(password) <= 128:
return error(400, "invalid_request", "Некорректный пароль")
user_id = str(uuid.uuid4())
now = utc_now()
password_hash = bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt(rounds=12)).decode("ascii")
try:
with transaction() as conn:
conn.execute(
"""
INSERT INTO users(id, username, display_name, password_hash, created_at)
VALUES (%s,%s,%s,%s,%s)
""",
(user_id, username, display_name, password_hash, now),
)
except Exception as exc:
if "users_username_key" in str(exc) or "duplicate key" in str(exc).lower():
return error(409, "conflict", "Имя пользователя уже занято")
return error(500, "internal_error", "Не удалось создать пользователя")
return jsonify({
"id": user_id,
"username": username,
"display_name": display_name,
"created_at": rfc3339(now),
}), 201
@app.get("/api/v1/users/me")
def current_user():
row, auth_error = require_bearer()
if auth_error:
return auth_error
return jsonify(user_row(row))
@app.post("/api/v1/auth/sessions")
def create_session():
authorization = request.headers.get("Authorization", "")
challenge = {"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'}
if not authorization.lower().startswith("basic "):
return error(401, "unauthorized", "Неверные учетные данные", challenge)
try:
raw = base64.b64decode(authorization.split(None, 1)[1].strip(), validate=True)
credentials = raw.decode("utf-8")
username, password = credentials.split(":", 1)
except Exception:
return error(401, "unauthorized", "Неверные учетные данные", challenge)
with transaction() as conn:
row = conn.execute(
"SELECT id, username, display_name, password_hash, created_at FROM users WHERE username=%s",
(username,),
).fetchone()
if not row or not bcrypt.checkpw(password.encode("utf-8"), row["password_hash"].encode("ascii")):
return error(401, "unauthorized", "Неверные учетные данные", challenge)
token = secrets.token_urlsafe(48)
expires_at = utc_now() + timedelta(seconds=SESSION_TTL)
with transaction() as conn:
conn.execute(
"INSERT INTO sessions(token,user_id,expires_at) VALUES (%s,%s,%s)",
(token, row["id"], expires_at),
)
user = user_row(row)
return jsonify({
"token": token,
"token_type": "Bearer",
"expires_at": rfc3339(expires_at),
"user": user,
}), 201
@app.delete("/api/v1/auth/sessions/current")
def revoke_session():
authorization = request.headers.get("Authorization", "")
if not authorization.lower().startswith("bearer "):
return error(401, "unauthorized", "Требуется действительная сессия",
{"WWW-Authenticate": 'Bearer realm="messenger"'})
token = authorization.split(None, 1)[1].strip()
with transaction() as conn:
row = conn.execute(
"SELECT expires_at FROM sessions WHERE token=%s",
(token,),
).fetchone()
if row:
conn.execute("DELETE FROM sessions WHERE token=%s", (token,))
if not row or row["expires_at"] <= utc_now():
return error(401, "unauthorized", "Требуется действительная сессия",
{"WWW-Authenticate": 'Bearer realm="messenger"'})
return Response(status=204)
@app.post("/api/v1/chats")
def create_chat():
actor, auth_error = require_bearer()
if auth_error:
return auth_error
body = parse_json()
if body is None or set(body) != {"title", "member_ids"}:
return error(400, "invalid_request", "Неверные поля запроса")
title = body["title"]
member_ids = body["member_ids"]
if not isinstance(title, str) or not title.strip() or len(title) > 100:
return error(400, "invalid_request", "Некорректное название чата")
if not isinstance(member_ids, list) or not 1 <= len(member_ids) <= 100:
return error(400, "invalid_request", "Некорректный список участников")
if len(member_ids) != len(set(member_ids)):
return error(400, "invalid_request", "Участники не должны повторяться")
try:
member_ids = [str(uuid.UUID(value)) for value in member_ids]
except (TypeError, ValueError, AttributeError):
return error(400, "invalid_request", "Некорректный UUID участника")
if str(actor["id"]) not in member_ids:
return error(400, "invalid_request", "Создатель должен быть участником")
chat_id = str(uuid.uuid4())
now = utc_now()
try:
with transaction() as conn:
for member_id in member_ids:
found = conn.execute("SELECT id FROM users WHERE id=%s", (member_id,)).fetchone()
if not found:
return error(404, "not_found", "Один из участников не найден")
conn.execute(
"INSERT INTO chats(id,title,created_at) VALUES (%s,%s,%s)",
(chat_id, title, now),
)
for member_id in member_ids:
conn.execute(
"INSERT INTO chat_members(chat_id,user_id) VALUES (%s,%s)",
(chat_id, member_id),
)
except Exception as exc:
app.logger.error("create_chat_failed=%s", type(exc).__name__)
return error(500, "internal_error", "Не удалось создать чат")
return jsonify(chat_row({"id": chat_id, "title": title, "created_at": now},
member_ids)), 201
@app.get("/api/v1/chats")
def list_chats():
actor, auth_error = require_bearer()
if auth_error:
return auth_error
limit = request.args.get("limit", "50")
cursor = request.args.get("cursor")
try:
limit = int(limit)
except ValueError:
return error(400, "invalid_request", "Некорректный limit")
if not 1 <= limit <= 100:
return error(400, "invalid_request", "Некорректный limit")
if cursor:
decoded = decode_cursor(cursor)
if not decoded:
return error(400, "invalid_request", "Некорректный cursor")
with transaction() as conn:
rows = conn.execute(
"""
SELECT c.id,c.title,c.created_at
FROM chats c JOIN chat_members cm ON cm.chat_id=c.id
WHERE cm.user_id=%s
ORDER BY c.created_at ASC,c.id ASC
""",
(actor["id"],),
).fetchall()
items = []
for row in rows[:limit]:
member_rows = []
with transaction() as conn:
member_rows = [str(r["user_id"]) for r in conn.execute(
"SELECT user_id FROM chat_members WHERE chat_id=%s ORDER BY user_id",
(row["id"],),
).fetchall()]
items.append(chat_row(row, member_rows))
return jsonify({"items": items, "next_cursor": None})
@app.get("/api/v1/chats/<chat_id>")
def get_chat(chat_id):
actor, auth_error = require_bearer()
if auth_error:
return auth_error
try:
chat_uuid = uuid.UUID(chat_id)
except ValueError:
return error(400, "invalid_request", "Некорректный UUID")
with transaction() as conn:
row = conn.execute("SELECT id,title,created_at FROM chats WHERE id=%s", (chat_uuid,)).fetchone()
if not row or not chat_is_member(conn, chat_uuid, actor["id"]):
return error(404, "not_found", "Чат не найден")
member_rows = [str(r["user_id"]) for r in conn.execute(
"SELECT user_id FROM chat_members WHERE chat_id=%s ORDER BY user_id",
(chat_uuid,),
).fetchall()]
return jsonify(chat_row(row, member_rows))
def message_row(row):
attachment_ids = row["attachment_ids"]
if isinstance(attachment_ids, str):
attachment_ids = json.loads(attachment_ids)
return {
"id": str(row["id"]),
"chat_id": str(row["chat_id"]),
"sender_id": str(row["sender_id"]),
"text": row["text"],
"created_at": rfc3339(row["created_at"]),
"attachment_ids": [str(value) for value in attachment_ids],
}
@app.post("/api/v1/chats/<chat_id>/messages")
def create_message(chat_id):
actor, auth_error = require_bearer()
if auth_error:
return auth_error
try:
chat_uuid = uuid.UUID(chat_id)
except ValueError:
return error(400, "invalid_request", "Некорректный UUID")
body = parse_json()
if body is None:
return error(400, "invalid_request", "Некорректный JSON")
if set(body) - {"text", "attachment_ids"} or "text" not in body:
return error(400, "invalid_request", "Неверные поля запроса")
text = body["text"]
attachments = body.get("attachment_ids", [])
if not isinstance(text, str) or len(text) > 4000:
return error(400, "invalid_request", "Некорректный текст")
if not isinstance(attachments, list) or len(attachments) > 10 or len(set(attachments)) != len(attachments):
return error(400, "invalid_request", "Некорректный список вложений")
if not text and not attachments:
return error(400, "invalid_request", "Сообщение должно содержать текст или вложение")
idempotency_key = request.headers.get("Idempotency-Key")
if not idempotency_key or not re.match(r"^[A-Za-z0-9._:-]{1,128}$", idempotency_key):
return error(400, "invalid_request", "Некорректный Idempotency-Key")
canonical = {"text": text, "attachment_ids": attachments}
request_hash = hashlib.sha256(
json.dumps(canonical, ensure_ascii=False, sort_keys=True).encode()
).hexdigest()
with transaction() as conn:
if not chat_is_member(conn, chat_uuid, actor["id"]):
return error(404, "not_found", "Чат не найден")
prior = conn.execute(
"""
SELECT request_hash,response,expires_at FROM idempotency
WHERE user_id=%s AND chat_id=%s AND key=%s
""",
(actor["id"], chat_uuid, idempotency_key),
).fetchone()
if prior:
if prior["expires_at"] <= utc_now():
conn.execute(
"DELETE FROM idempotency WHERE user_id=%s AND chat_id=%s AND key=%s",
(actor["id"], chat_uuid, idempotency_key),
)
elif prior["request_hash"] != request_hash:
return error(409, "conflict", "Ключ уже использован для другого сообщения")
else:
replay = dict(prior["response"])
replay["attachment_ids"] = replay.get("attachment_ids", [])
return Response(
json.dumps(replay, ensure_ascii=False),
status=201,
mimetype="application/json",
)
try:
attachment_ids = [str(uuid.UUID(value)) for value in attachments]
except (TypeError, ValueError, AttributeError):
return error(400, "invalid_request", "Некорректный UUID вложения")
for attachment_id in attachment_ids:
attachment = conn.execute(
"SELECT chat_id,status FROM attachments WHERE id=%s",
(attachment_id,),
).fetchone()
if not attachment or str(attachment["chat_id"]) != str(chat_uuid):
return error(404, "not_found", "Вложение не найдено")
if attachment["status"] == "failed":
return error(409, "conflict", "Не удалось прикрепить failed-вложение")
message_id = str(uuid.uuid4())
now = utc_now().replace(microsecond=0)
conn.execute(
"""
INSERT INTO messages(id,chat_id,sender_id,text,attachment_ids,created_at)
VALUES (%s,%s,%s,%s,%s,%s)
""",
(message_id, chat_uuid, actor["id"], text,
json.dumps(attachment_ids), now),
)
response = {
"id": message_id,
"chat_id": str(chat_uuid),
"sender_id": str(actor["id"]),
"text": text,
"created_at": rfc3339(now),
"attachment_ids": attachment_ids,
}
conn.execute(
"""
INSERT INTO idempotency(user_id,chat_id,key,request_hash,message_id,response,expires_at)
VALUES (%s,%s,%s,%s,%s,%s,%s)
""",
(actor["id"], chat_uuid, idempotency_key, request_hash,
message_id, json.dumps(response), utc_now() + timedelta(hours=24)),
)
return Response(
json.dumps(response, ensure_ascii=False),
status=201,
mimetype="application/json",
)
@app.get("/api/v1/chats/<chat_id>/messages")
def list_messages(chat_id):
actor, auth_error = require_bearer()
if auth_error:
return auth_error
try:
chat_uuid = uuid.UUID(chat_id)
except ValueError:
return error(400, "invalid_request", "Некорректный UUID")
try:
limit = int(request.args.get("limit", "50"))
except ValueError:
return error(400, "invalid_request", "Некорректный limit")
if not 1 <= limit <= 100:
return error(400, "invalid_request", "Некорректный limit")
cursor = request.args.get("cursor")
decoded = decode_cursor(cursor) if cursor else None
if cursor and not decoded:
return error(400, "invalid_request", "Некорректный cursor")
with transaction() as conn:
if not chat_is_member(conn, chat_uuid, actor["id"]):
return error(404, "not_found", "Чат не найден")
if decoded:
stamp, message_id = decoded
rows = conn.execute(
"""
SELECT id,chat_id,sender_id,text,attachment_ids,created_at
FROM messages
WHERE chat_id=%s AND (created_at,id) > (%s,%s)
ORDER BY created_at ASC,id ASC
LIMIT %s
""",
(chat_uuid, stamp, message_id, limit + 1),
).fetchall()
else:
rows = conn.execute(
"""
SELECT id,chat_id,sender_id,text,attachment_ids,created_at
FROM messages
WHERE chat_id=%s
ORDER BY created_at ASC,id ASC
LIMIT %s
""",
(chat_uuid, limit + 1),
).fetchall()
has_more = len(rows) > limit
rows = rows[:limit]
items = [message_row(row) for row in rows]
next_cursor = None
if has_more and rows:
last = rows[-1]
next_cursor = encode_cursor(last["created_at"], last["id"])
return jsonify({"items": items, "next_cursor": next_cursor})
@app.post("/api/v1/chats/<chat_id>/attachments")
def upload_attachment(chat_id):
actor, auth_error = require_bearer()
if auth_error:
return auth_error
try:
chat_uuid = uuid.UUID(chat_id)
except ValueError:
return error(400, "invalid_request", "Некорректный UUID")
filename = request.args.get("filename")
if not filename or len(filename) > 255 or filename.strip() != filename:
return error(400, "invalid_request", "Некорректное имя файла")
if any(char in filename for char in "/\\\0\r\n\t") or any(ord(char) < 32 for char in filename):
return error(400, "invalid_request", "Некорректное имя файла")
with transaction() as conn:
if not chat_is_member(conn, chat_uuid, actor["id"]):
return error(404, "not_found", "Чат не найден")
data = request.get_data(cache=False)
if len(data) > 10 * 1024 * 1024:
return error(413, "payload_too_large", "Файл превышает лимит")
declared = request.headers.get("Content-Type", "").split(";", 1)[0].strip().lower()
if declared not in ("image/png", "image/jpeg"):
return error(415, "unsupported_media_type", "Поддерживаются только PNG и JPEG")
try:
image = Image.open(io.BytesIO(data))
image_format = image.format
width, height = image.size
if width * height > 40_000_000:
return error(413, "payload_too_large", "Изображение содержит слишком много пикселей")
actual = "image/png" if image_format == "PNG" else "image/jpeg" if image_format == "JPEG" else None
if actual is None or actual != declared:
return error(415, "unsupported_media_type", "Содержимое не соответствует формату")
image.verify()
except Exception:
return error(415, "unsupported_media_type", "Поврежденное изображение")
sha256 = hashlib.sha256(data).hexdigest()
attachment_id = str(uuid.uuid4())
job_id = str(uuid.uuid4())
now = utc_now()
staging_key = f"staging/{attachment_id}/original"
try:
put_object(os.environ["S3_BUCKET"], staging_key, data, declared)
with transaction() as conn:
conn.execute(
"""
INSERT INTO attachments(
id,chat_id,owner_id,filename,content_type,size_bytes,sha256,
staging_key,status,variants,error_code,created_at,updated_at
) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,'queued','[]',NULL,%s,%s)
""",
(attachment_id, chat_uuid, actor["id"], filename, declared, len(data),
sha256, staging_key, now, now),
)
conn.execute(
"""
INSERT INTO jobs(id,attachment_id,pipeline_version,attempt,status,created_at,updated_at)
VALUES (%s,%s,%s,0,'queued',%s,%s)
""",
(job_id, attachment_id, CURRENT_PIPELINE_VERSION, now, now),
)
conn.execute(
"""
INSERT INTO outbox(id,event_type,payload,published_at,publish_attempt,created_at)
VALUES (%s,'attachment.process',%s,NULL,0,%s)
""",
(
str(uuid.uuid4()),
json.dumps({
"schema_version": 1,
"job_id": job_id,
"type": "attachment.process.v1",
"attachment_id": attachment_id,
"pipeline_version": CURRENT_PIPELINE_VERSION,
"attempt": 1,
"created_at": rfc3339(now),
}),
now,
),
)
except Exception:
return error(503, "unavailable", "Не удалось принять вложение")
result = attachment_payload(attachment_id)
return jsonify(result), 202
def attachment_payload(attachment_id):
with transaction() as conn:
row = conn.execute(
"""
SELECT id,chat_id,owner_id,filename,content_type,size_bytes,sha256,
status,variants,error_code,created_at,updated_at
FROM attachments WHERE id=%s
""",
(attachment_id,),
).fetchone()
variants = row["variants"]
if isinstance(variants, str):
variants = json.loads(variants)
return {
"id": str(row["id"]),
"chat_id": str(row["chat_id"]),
"owner_id": str(row["owner_id"]),
"filename": row["filename"],
"content_type": row["content_type"],
"size_bytes": row["size_bytes"],
"sha256": row["sha256"],
"status": row["status"],
"variants": variants,
"error_code": row["error_code"],
"created_at": rfc3339(row["created_at"]),
"updated_at": rfc3339(row["updated_at"]),
}
@app.get("/api/v1/attachments/<attachment_id>")
def get_attachment(attachment_id):
actor, auth_error = require_bearer()
if auth_error:
return auth_error
try:
attachment_uuid = uuid.UUID(attachment_id)
except ValueError:
return error(400, "invalid_request", "Некорректный UUID")
with transaction() as conn:
row = conn.execute(
"""
SELECT a.*,cm.user_id
FROM attachments a
JOIN chat_members cm ON cm.chat_id=a.chat_id
WHERE a.id=%s AND cm.user_id=%s
""",
(attachment_uuid, actor["id"]),
).fetchone()
if not row:
return error(404, "not_found", "Вложение не найдено")
return jsonify(attachment_payload(attachment_id))
@app.get("/api/v1/attachments/<attachment_id>/content")
def download_attachment(attachment_id):
actor, auth_error = require_bearer()
if auth_error:
return auth_error
try:
attachment_uuid = uuid.UUID(attachment_id)
except ValueError:
return error(400, "invalid_request", "Некорректный UUID")
variant = request.args.get("variant", "original")
if variant not in ("original", "thumbnail", "crop", "optimized"):
return error(400, "invalid_request", "Некорректный variant")
with transaction() as conn:
row = conn.execute(
"""
SELECT a.*
FROM attachments a JOIN chat_members cm ON cm.chat_id=a.chat_id
WHERE a.id=%s AND cm.user_id=%s
""",
(attachment_uuid, actor["id"]),
).fetchone()
if not row:
return error(404, "not_found", "Вложение не найдено")
if row["status"] in ("queued", "processing", "failed"):
return error(409, "conflict", "Содержимое вложения недоступно")
if variant == "original":
key = f"final/{attachment_id}/original"
content_type = row["content_type"]
else:
variants = row["variants"]
if isinstance(variants, str):
variants = json.loads(variants)
matching = next((item for item in variants if item["name"] == variant), None)
if matching is None:
return error(404, "not_found", "Вариант не найден")
key = f"final/{attachment_id}/{variant}"
content_type = matching["content_type"]
try:
obj = s3_client().get_object(Bucket=os.environ["S3_BUCKET"], Key=key)
data = obj["Body"].read()
except Exception:
return error(404, "not_found", "Содержимое не найдено")
return Response(data, status=200, content_type=content_type)
+51
View File
@@ -0,0 +1,51 @@
import json
import os
import pika
def connection():
parameters = pika.URLParameters(os.environ["BROKER_URL"])
parameters.heartbeat = 30
return pika.BlockingConnection(parameters)
def ensure_topology():
conn = connection()
channel = conn.channel()
channel.exchange_declare(exchange="attachment.events", exchange_type="topic", durable=True)
channel.queue_declare(
queue="attachment.processing",
durable=True,
arguments={"x-dead-letter-exchange": "attachment.events", "x-dead-letter-routing-key": "attachment.failed"},
)
channel.queue_declare(queue="attachment.failed", durable=True)
channel.queue_bind(queue="attachment.processing", exchange="attachment.events", routing_key="attachment.process")
channel.queue_bind(queue="attachment.failed", exchange="attachment.events", routing_key="attachment.failed")
conn.close()
def publish(job, routing_key="attachment.process"):
conn = connection()
try:
channel = conn.channel()
channel.confirm_delivery()
channel.exchange_declare(exchange="attachment.events", exchange_type="topic", durable=True)
channel.queue_declare(
queue="attachment.processing",
durable=True,
arguments={"x-dead-letter-exchange": "attachment.events", "x-dead-letter-routing-key": "attachment.failed"},
)
channel.basic_publish(
exchange="attachment.events",
routing_key=routing_key,
body=json.dumps(job, ensure_ascii=False).encode("utf-8"),
properties=pika.BasicProperties(
content_type="application/json",
delivery_mode=2,
message_id=job["job_id"],
),
mandatory=True,
)
finally:
conn.close()
+26
View File
@@ -0,0 +1,26 @@
import os
from contextlib import contextmanager
import psycopg
from psycopg.rows import dict_row
def database_url():
return os.environ["DATABASE_URL"]
def connect():
return psycopg.connect(database_url(), row_factory=dict_row, autocommit=False)
@contextmanager
def transaction():
conn = connect()
try:
yield conn
conn.commit()
except Exception:
conn.rollback()
raise
finally:
conn.close()
+11
View File
@@ -0,0 +1,11 @@
CURRENT_PIPELINE_VERSION = 2
SUPPORTED_PIPELINE_VERSIONS = frozenset({1, 2})
PIPELINE_QUALITIES = {
1: (88, 82),
2: (86, 80),
}
def pipeline_qualities(version):
return PIPELINE_QUALITIES[version]
+87
View File
@@ -0,0 +1,87 @@
import argparse
import json
import sys
import uuid
from datetime import timezone
from .db import transaction
def replay_failed_attachment(attachment_id, operator):
attachment_uuid = uuid.UUID(attachment_id)
operator = operator.strip() if isinstance(operator, str) else ""
if not operator or len(operator) > 100:
raise ValueError("operator must contain 1-100 characters")
with transaction() as conn:
row = conn.execute(
"""
SELECT j.id,j.attachment_id,j.pipeline_version,j.created_at,j.status,
a.status AS attachment_status
FROM jobs j JOIN attachments a ON a.id=j.attachment_id
WHERE a.id=%s
FOR UPDATE OF j,a
""",
(attachment_uuid,),
).fetchone()
if not row:
raise ValueError("attachment not found")
if row["status"] != "failed" or row["attachment_status"] != "failed":
raise ValueError("only a failed attachment can be replayed")
conn.execute(
"""
UPDATE jobs
SET status='queued',attempt=0,lease_until=NULL,last_error_code=NULL,
replay_count=replay_count+1,updated_at=NOW()
WHERE id=%s
""",
(row["id"],),
)
conn.execute(
"UPDATE attachments SET status='queued',error_code=NULL,updated_at=NOW() WHERE id=%s",
(attachment_uuid,),
)
conn.execute(
"INSERT INTO job_replays(id,job_id,attachment_id,operator,replayed_at) "
"VALUES (%s,%s,%s,%s,NOW())",
(str(uuid.uuid4()), row["id"], attachment_uuid, operator),
)
created_at = row["created_at"]
if created_at.tzinfo is None:
created_at = created_at.replace(tzinfo=timezone.utc)
payload = {
"schema_version": 1,
"job_id": str(row["id"]),
"type": "attachment.process.v1",
"attachment_id": str(attachment_uuid),
"pipeline_version": row["pipeline_version"],
"attempt": 1,
"created_at": created_at.astimezone(timezone.utc).isoformat(timespec="seconds").replace("+00:00", "Z"),
}
conn.execute(
"""
INSERT INTO outbox(id,event_type,payload,published_at,publish_attempt,created_at,available_at)
VALUES (%s,'attachment.process',%s,NULL,0,NOW(),NOW())
""",
(str(uuid.uuid4()), json.dumps(payload)),
)
return {"job_id": str(row["id"]), "attachment_id": str(attachment_uuid), "status": "queued"}
def main():
parser = argparse.ArgumentParser(description="Explicitly replay one failed attachment job")
parser.add_argument("attachment_id")
parser.add_argument("--operator", required=True, help="Local operator identifier for the audit record")
args = parser.parse_args()
try:
result = replay_failed_attachment(args.attachment_id, args.operator)
except (ValueError, KeyError) as exc:
print(f"Replay rejected: {exc}", file=sys.stderr)
return 2
print(json.dumps(result))
return 0
if __name__ == "__main__":
raise SystemExit(main())
+40
View File
@@ -0,0 +1,40 @@
import io
import os
import boto3
from botocore.config import Config
def s3_client():
endpoint = os.environ["S3_ENDPOINT"]
region = os.environ.get("S3_REGION", "us-east-1")
access_key = os.environ["S3_ACCESS_KEY_ID"]
secret_key = os.environ["S3_SECRET_ACCESS_KEY"]
return boto3.client(
"s3",
endpoint_url=endpoint,
region_name=region,
aws_access_key_id=access_key,
aws_secret_access_key=secret_key,
config=Config(signature_version="s3v4", s3={"addressing_style": "path"}),
)
def ensure_bucket():
client = s3_client()
bucket = os.environ["S3_BUCKET"]
try:
client.head_bucket(Bucket=bucket)
except Exception:
client.create_bucket(Bucket=bucket)
return client
def put_object(bucket, key, data, content_type):
s3_client().put_object(
Bucket=bucket,
Key=key,
Body=data,
ContentType=content_type,
)
+506
View File
@@ -0,0 +1,506 @@
import hashlib
import io
import json
import logging
import multiprocessing
import os
import random
import threading
import time
import uuid
import warnings
import pika
from PIL import Image, ImageOps
from .db import transaction
from .storage import ensure_bucket, put_object, s3_client
from .broker import ensure_topology, publish
from .pipeline import SUPPORTED_PIPELINE_VERSIONS, pipeline_qualities
MAX_ATTEMPTS = int(os.environ.get("JOB_MAX_ATTEMPTS", "5"))
MAX_UPLOAD_BYTES = int(os.environ.get("MAX_UPLOAD_BYTES", str(10 * 1024 * 1024)))
MAX_IMAGE_PIXELS = int(os.environ.get("MAX_IMAGE_PIXELS", "40000000"))
JOB_TIMEOUT_SECONDS = int(os.environ.get("JOB_TIMEOUT_SECONDS", "60"))
JOB_LEASE_SECONDS = int(os.environ.get("JOB_LEASE_SECONDS", "90"))
RETRY_BASE_SECONDS = float(os.environ.get("JOB_RETRY_BASE_SECONDS", "1"))
RETRY_MAX_SECONDS = float(os.environ.get("JOB_RETRY_MAX_SECONDS", "60"))
STAGING_RETENTION_SECONDS = int(os.environ.get("STAGING_RETENTION_SECONDS", "86400"))
JPEG_QUALITY = 88
WEBP_QUALITY = 82
logger = logging.getLogger(__name__)
if MAX_ATTEMPTS < 1:
raise ValueError("JOB_MAX_ATTEMPTS must be at least 1")
if JOB_TIMEOUT_SECONDS < 1 or JOB_LEASE_SECONDS <= JOB_TIMEOUT_SECONDS:
raise ValueError("JOB_LEASE_SECONDS must exceed a positive JOB_TIMEOUT_SECONDS")
if RETRY_BASE_SECONDS <= 0 or RETRY_MAX_SECONDS < RETRY_BASE_SECONDS:
raise ValueError("retry maximum must be at least the positive retry base")
if STAGING_RETENTION_SECONDS < 1:
raise ValueError("STAGING_RETENTION_SECONDS must be positive")
class PermanentJobError(Exception):
def __init__(self, error_code):
super().__init__(error_code)
self.error_code = error_code
class TransientJobError(Exception):
pass
def retry_delay(attempt):
maximum = min(RETRY_BASE_SECONDS * (2 ** max(0, attempt - 1)), RETRY_MAX_SECONDS)
return random.SystemRandom().uniform(maximum / 2, maximum)
def publish_pending_outbox():
next_staging_cleanup = 0
while True:
try:
recover_expired_leases()
now = time.monotonic()
if now >= next_staging_cleanup:
next_staging_cleanup = now + 60
cleanup_staging()
publish_one_outbox_event()
except Exception:
logger.exception("Outbox publication failed; pending row will be retried")
time.sleep(0.5)
def publish_one_outbox_event():
with transaction() as conn:
row = conn.execute(
"""
SELECT id,event_type,payload
FROM outbox
WHERE published_at IS NULL AND available_at<=NOW()
ORDER BY available_at,created_at
LIMIT 1
FOR UPDATE SKIP LOCKED
"""
).fetchone()
if not row:
return False
conn.execute(
"UPDATE outbox SET publish_attempt=publish_attempt+1 WHERE id=%s",
(row["id"],),
)
payload = row["payload"]
if isinstance(payload, str):
payload = json.loads(payload)
publish(payload, row["event_type"])
conn.execute(
"UPDATE outbox SET published_at=NOW() WHERE id=%s",
(row["id"],),
)
return True
def cleanup_staging(batch_size=25):
deleted = 0
for _ in range(batch_size):
with transaction() as conn:
row = conn.execute(
"""
SELECT id,staging_key
FROM attachments
WHERE status='ready' AND staging_deleted_at IS NULL
AND updated_at < NOW()-(%s * INTERVAL '1 second')
ORDER BY updated_at
LIMIT 1
FOR UPDATE SKIP LOCKED
""",
(STAGING_RETENTION_SECONDS,),
).fetchone()
if not row:
break
s3_client().delete_object(Bucket=os.environ["S3_BUCKET"], Key=row["staging_key"])
conn.execute(
"""
UPDATE attachments SET staging_deleted_at=NOW()
WHERE id=%s AND status='ready' AND staging_deleted_at IS NULL
""",
(row["id"],),
)
deleted += 1
return deleted
def decode_image(data):
if not data or len(data) > MAX_UPLOAD_BYTES:
raise ValueError("invalid_image_size")
with warnings.catch_warnings():
warnings.simplefilter("error", Image.DecompressionBombWarning)
source = Image.open(io.BytesIO(data))
width, height = source.size
if width < 1 or height < 1 or width * height > MAX_IMAGE_PIXELS:
raise ValueError("image_pixel_limit")
source.load()
return ImageOps.exif_transpose(source)
def rgb_on_white(image):
if image.mode in ("RGBA", "LA") or "transparency" in image.info:
rgba = image.convert("RGBA")
base = Image.new("RGB", rgba.size, "white")
base.paste(rgba, mask=rgba.getchannel("A"))
return base
return image.convert("RGB")
def thumbnail(image, quality=JPEG_QUALITY):
original_width, original_height = image.size
scale = min(256 / original_width, 256 / original_height, 1.0)
width = max(1, int(original_width * scale))
height = max(1, int(original_height * scale))
resized = image.resize((width, height), Image.Resampling.LANCZOS) if (width, height) != image.size else image
image = rgb_on_white(resized)
output = io.BytesIO()
image.save(output, format="JPEG", quality=quality, optimize=True)
return output.getvalue(), width, height
def crop(image, quality=JPEG_QUALITY):
width, height = image.size
side = min(width, height)
left = (width - side) // 2
top = (height - side) // 2
square = image.crop((left, top, left + side, top + side))
square = square.resize((128, 128), Image.Resampling.LANCZOS)
output = io.BytesIO()
rgb_on_white(square).save(output, format="JPEG", quality=quality, optimize=True)
return output.getvalue(), 128, 128
def optimized(image, quality=WEBP_QUALITY):
width, height = image.size
scale = min(1280 / width, 1280 / height, 1.0)
out_width = max(1, int(width * scale))
out_height = max(1, int(height * scale))
resized = image.resize((out_width, out_height), Image.Resampling.LANCZOS) if (out_width, out_height) != image.size else image
output = io.BytesIO()
rgb_on_white(resized).save(output, format="WEBP", quality=quality, method=6)
return output.getvalue(), out_width, out_height
def store_variant(attachment_id, name, content_type, data, width, height):
key = f"final/{attachment_id}/{name}"
put_object(os.environ["S3_BUCKET"], key, data, content_type)
return {
"name": name,
"content_type": content_type,
"size_bytes": len(data),
"width": width,
"height": height,
"sha256": hashlib.sha256(data).hexdigest(),
}
def maybe_inject_fault(job, stage):
configured = os.environ.get("WORKER_FAULT_INJECTION")
expected = f"{job['attachment_id']}:{job['attempt']}:{stage}"
if configured == expected:
os._exit(86)
def process(job):
pipeline_version = job["pipeline_version"]
if pipeline_version not in SUPPORTED_PIPELINE_VERSIONS:
raise PermanentJobError("unsupported_pipeline_version")
jpeg_quality, webp_quality = pipeline_qualities(pipeline_version)
attachment_id = job["attachment_id"]
with transaction() as conn:
row = conn.execute(
"""
SELECT a.staging_key,a.status,a.content_type,a.size_bytes,a.sha256,
j.status AS job_status,j.lease_until,j.attempt,
j.pipeline_version
FROM attachments a JOIN jobs j ON j.attachment_id=a.id
WHERE a.id=%s AND j.id=%s
FOR UPDATE OF a,j
""",
(attachment_id, job["job_id"]),
).fetchone()
if not row:
return True
if (
row["status"] == "ready"
or row["job_status"] in ("ready", "failed")
or job["attempt"] <= row["attempt"]
or job["attempt"] != row["attempt"] + 1
or job["pipeline_version"] != row["pipeline_version"]
):
return True
if row["job_status"] == "processing" and row["lease_until"] and row["lease_until"] > time_now():
return True
conn.execute(
"UPDATE attachments SET status='processing', updated_at=NOW() WHERE id=%s",
(attachment_id,),
)
conn.execute(
"""
UPDATE jobs
SET attempt=attempt+1,status='processing',
lease_until=NOW()+(%s * INTERVAL '1 second'),updated_at=NOW()
WHERE attachment_id=%s
""",
(JOB_LEASE_SECONDS, attachment_id),
)
obj = s3_client().get_object(Bucket=os.environ["S3_BUCKET"], Key=row["staging_key"])
original = obj["Body"].read()
if len(original) != row["size_bytes"] or hashlib.sha256(original).hexdigest() != row["sha256"]:
raise PermanentJobError("processing_failed")
try:
image = decode_image(original)
except (ValueError, OSError, Image.DecompressionBombWarning):
raise PermanentJobError("invalid_image") from None
maybe_inject_fault(job, "before_original_put")
put_object(
os.environ["S3_BUCKET"],
f"final/{attachment_id}/original",
original,
row["content_type"],
)
maybe_inject_fault(job, "after_original_put")
variants = []
thumb, width, height = thumbnail(image, jpeg_quality)
variants.append(store_variant(attachment_id, "thumbnail", "image/jpeg", thumb, width, height))
crop_data, width, height = crop(image, jpeg_quality)
variants.append(store_variant(attachment_id, "crop", "image/jpeg", crop_data, width, height))
webp, width, height = optimized(image, webp_quality)
variants.append(store_variant(attachment_id, "optimized", "image/webp", webp, width, height))
maybe_inject_fault(job, "before_ready_commit")
with transaction() as conn:
conn.execute(
"""
UPDATE attachments
SET status='ready',original_key=%s,variants=%s,error_code=NULL,updated_at=NOW()
WHERE id=%s AND status!='ready'
""",
(f"final/{attachment_id}/original", json.dumps(variants), attachment_id),
)
conn.execute(
"UPDATE jobs SET status='ready',lease_until=NULL,last_error_code=NULL,updated_at=NOW() WHERE attachment_id=%s",
(attachment_id,),
)
return True
def _process_job_child(job, result_pipe):
try:
process(job)
result_pipe.send((True, None, None))
except PermanentJobError as exc:
result_pipe.send((False, "permanent", exc.error_code))
except Exception as exc:
result_pipe.send((False, "transient", type(exc).__name__))
finally:
result_pipe.close()
def process_with_timeout(job):
context = multiprocessing.get_context("spawn")
receive_pipe, send_pipe = context.Pipe(duplex=False)
child = context.Process(target=_process_job_child, args=(job, send_pipe))
child.start()
send_pipe.close()
child.join(JOB_TIMEOUT_SECONDS)
if child.is_alive():
child.terminate()
child.join()
receive_pipe.close()
raise TimeoutError("job_timeout")
if child.exitcode != 0 or not receive_pipe.poll():
receive_pipe.close()
raise TransientJobError("worker_process_failed")
succeeded, failure_class, error_code = receive_pipe.recv()
receive_pipe.close()
if succeeded:
return
if failure_class == "permanent":
raise PermanentJobError(error_code)
if error_code == "TimeoutError":
error_code = "job_timeout"
raise TransientJobError(error_code)
def time_now():
from datetime import datetime, timezone
return datetime.now(timezone.utc)
def recover_expired_leases():
with transaction() as conn:
rows = conn.execute(
"""
SELECT j.id,j.attachment_id,j.pipeline_version,j.created_at
,j.attempt
FROM jobs j
WHERE j.status='processing' AND j.lease_until<NOW()
ORDER BY j.lease_until
LIMIT 50
FOR UPDATE SKIP LOCKED
"""
).fetchall()
for row in rows:
conn.execute(
"UPDATE jobs SET status='queued',lease_until=NULL,updated_at=NOW() WHERE id=%s",
(row["id"],),
)
conn.execute(
"UPDATE attachments SET status='queued',updated_at=NOW() WHERE id=%s",
(row["attachment_id"],),
)
insert_outbox(conn, row, row["attempt"] + 1)
def insert_outbox(conn, job_row, attempt, event_type="attachment.process", delay=0, error_code=None):
from datetime import timezone
created_at = job_row["created_at"]
if created_at.tzinfo is None:
created_at = created_at.replace(tzinfo=timezone.utc)
created_at_text = created_at.astimezone(timezone.utc).isoformat(timespec="seconds").replace("+00:00", "Z")
payload = {
"schema_version": 1,
"job_id": str(job_row["id"]),
"type": "attachment.failed.v1" if event_type == "attachment.failed" else "attachment.process.v1",
"attachment_id": str(job_row["attachment_id"]),
"pipeline_version": job_row["pipeline_version"],
"attempt": attempt,
"created_at": created_at_text,
}
if error_code is not None:
payload["error_code"] = error_code
conn.execute(
"""
INSERT INTO outbox(id,event_type,payload,published_at,publish_attempt,created_at,available_at)
VALUES (%s,%s,%s,NULL,0,NOW(),NOW()+(%s * INTERVAL '1 second'))
""",
(
str(uuid.uuid4()),
event_type,
json.dumps(payload),
delay,
),
)
def record_failure(job, failure):
attachment_id = job["attachment_id"]
with transaction() as conn:
row = conn.execute(
"""
SELECT j.id,j.attachment_id,j.attempt,j.pipeline_version,j.created_at,a.status
FROM jobs j JOIN attachments a ON a.id=j.attachment_id
WHERE j.attachment_id=%s
FOR UPDATE OF j,a
""",
(attachment_id,),
).fetchone()
if not row or row["status"] == "ready":
return
permanent = isinstance(failure, PermanentJobError)
attempt = max(1, row["attempt"])
exhausted = attempt >= MAX_ATTEMPTS
error_code = failure.error_code if permanent else (
"retry_exhausted" if exhausted else "processing_failed"
)
outcome = "failed" if permanent or exhausted else "retry"
conn.execute(
"""
INSERT INTO job_attempts(job_id,attempt,outcome,error_code,occurred_at)
VALUES (%s,%s,%s,%s,NOW())
""",
(row["id"], attempt, outcome, error_code),
)
if permanent or exhausted:
conn.execute(
"""
UPDATE jobs SET status='failed',lease_until=NULL,last_error_code=%s,updated_at=NOW()
WHERE id=%s
""",
(error_code, row["id"]),
)
conn.execute(
"UPDATE attachments SET status='failed',error_code=%s,updated_at=NOW() WHERE id=%s",
(error_code, attachment_id),
)
insert_outbox(conn, row, attempt, event_type="attachment.failed", error_code=error_code)
return
delay = retry_delay(attempt)
conn.execute(
"""
UPDATE jobs SET status='queued',lease_until=NULL,last_error_code=%s,updated_at=NOW()
WHERE id=%s
""",
("processing_failed", row["id"]),
)
conn.execute(
"UPDATE attachments SET status='queued',error_code=NULL,updated_at=NOW() WHERE id=%s",
(attachment_id,),
)
insert_outbox(conn, row, attempt + 1, delay=delay)
def handle_message(channel, delivery_tag, body):
try:
job = json.loads(body)
if (
not isinstance(job, dict)
or type(job.get("schema_version")) is not int
or job["schema_version"] != 1
or job.get("type") != "attachment.process.v1"
or type(job.get("attempt")) is not int
or job["attempt"] < 1
or type(job.get("pipeline_version")) is not int
or job["pipeline_version"] < 1
or not isinstance(job.get("created_at"), str)
or set(job) - {
"schema_version", "job_id", "type", "attachment_id",
"pipeline_version", "attempt", "created_at", "traceparent", "tracestate",
}
):
raise ValueError("invalid_job")
uuid.UUID(job["job_id"])
uuid.UUID(job["attachment_id"])
except (ValueError, TypeError, AttributeError):
channel.basic_nack(delivery_tag=delivery_tag, requeue=False)
return
try:
process_with_timeout(job)
except PermanentJobError as exc:
record_failure(job, exc)
except Exception as exc:
record_failure(job, exc)
channel.basic_ack(delivery_tag=delivery_tag)
def main():
ensure_bucket()
ensure_topology()
publisher = threading.Thread(target=publish_pending_outbox, daemon=True)
publisher.start()
connection = pika.BlockingConnection(pika.URLParameters(os.environ["BROKER_URL"]))
channel = connection.channel()
channel.basic_qos(prefetch_count=int(os.environ.get("WORKER_CONCURRENCY", "2")))
def callback(ch, method, _properties, body):
try:
handle_message(ch, method.delivery_tag, body)
except Exception:
logger.exception("Could not persist job outcome; broker delivery will be retried")
ch.basic_nack(delivery_tag=method.delivery_tag, requeue=True)
channel.basic_consume(queue="attachment.processing", on_message_callback=callback)
channel.start_consuming()
if __name__ == "__main__":
main()
+87
View File
@@ -0,0 +1,87 @@
import json
import unittest
from contextlib import contextmanager
from datetime import datetime, timezone
from unittest.mock import patch
from src.worker import PermanentJobError, TransientJobError, record_failure
class FakeDatabase:
def __init__(self, attempt):
self.row = {
"id": "job-id",
"attachment_id": "9c554d5e-2d59-4c10-ae40-7f6f7aef6350",
"attempt": attempt,
"pipeline_version": 2,
"created_at": datetime.now(timezone.utc),
"status": "processing",
}
self.job_status = "processing"
self.attachment_status = "processing"
self.attempt_records = []
self.outbox = []
@contextmanager
def transaction(self):
yield self
def execute(self, query, params=()):
statement = " ".join(query.split())
if statement.startswith("SELECT j.id,j.attachment_id,j.attempt"):
self.result = self.row
elif statement.startswith("INSERT INTO job_attempts"):
self.attempt_records.append(params)
elif statement.startswith("UPDATE jobs SET status='failed'"):
self.job_status = "failed"
elif statement.startswith("UPDATE attachments SET status='failed'"):
self.attachment_status = "failed"
elif statement.startswith("INSERT INTO outbox"):
self.outbox.append({
"event_type": params[1],
"payload": json.loads(params[2]),
})
else:
raise AssertionError(f"Unexpected SQL in test fake: {statement}")
return self
def fetchone(self):
return self.result
class FailureRegistryTests(unittest.TestCase):
def make_job(self, db):
return {
"job_id": db.row["id"],
"attachment_id": db.row["attachment_id"],
"attempt": db.row["attempt"],
"pipeline_version": db.row["pipeline_version"],
}
def test_permanent_failure_is_recorded_and_sent_to_failed_route(self):
db = FakeDatabase(attempt=1)
with patch("src.worker.transaction", db.transaction):
record_failure(self.make_job(db), PermanentJobError("invalid_image"))
self.assertEqual(db.job_status, "failed")
self.assertEqual(db.attachment_status, "failed")
self.assertEqual(db.attempt_records[0][2:], ("failed", "invalid_image"))
self.assertEqual(db.outbox[0]["event_type"], "attachment.failed")
self.assertEqual(db.outbox[0]["payload"]["type"], "attachment.failed.v1")
self.assertEqual(db.outbox[0]["payload"]["error_code"], "invalid_image")
def test_transient_failure_at_attempt_limit_is_terminal(self):
db = FakeDatabase(attempt=5)
with patch("src.worker.transaction", db.transaction):
record_failure(self.make_job(db), TransientJobError("temporary"))
self.assertEqual(db.job_status, "failed")
self.assertEqual(db.attempt_records[0][2:], ("failed", "retry_exhausted"))
self.assertEqual(db.outbox[0]["event_type"], "attachment.failed")
self.assertEqual(db.outbox[0]["payload"]["error_code"], "retry_exhausted")
if __name__ == "__main__":
unittest.main()
+68
View File
@@ -0,0 +1,68 @@
import io
import unittest
from PIL import Image
from src.worker import crop, decode_image, optimized, thumbnail
def encoded_image(image, image_format="PNG", **save_options):
buffer = io.BytesIO()
image.save(buffer, format=image_format, **save_options)
return buffer.getvalue()
class ImageVariantTests(unittest.TestCase):
def test_variants_follow_contract_dimensions_and_formats(self):
image = decode_image(encoded_image(Image.new("RGB", (320, 200), "navy")))
thumb_bytes, thumb_width, thumb_height = thumbnail(image)
crop_bytes, crop_width, crop_height = crop(image)
webp_bytes, webp_width, webp_height = optimized(image)
self.assertEqual((thumb_width, thumb_height), (256, 160))
self.assertEqual((crop_width, crop_height), (128, 128))
self.assertEqual((webp_width, webp_height), (320, 200))
self.assertEqual(Image.open(io.BytesIO(thumb_bytes)).format, "JPEG")
self.assertEqual(Image.open(io.BytesIO(crop_bytes)).format, "JPEG")
self.assertEqual(Image.open(io.BytesIO(webp_bytes)).format, "WEBP")
self.assertEqual(Image.open(io.BytesIO(webp_bytes)).getexif(), {})
def test_small_optimized_image_is_not_upscaled(self):
image = decode_image(encoded_image(Image.new("RGB", (64, 32), "white")))
_, width, height = optimized(image)
self.assertEqual((width, height), (64, 32))
def test_large_optimized_image_fits_inside_1280(self):
image = decode_image(encoded_image(Image.new("RGB", (1600, 800), "white")))
_, width, height = optimized(image)
self.assertEqual((width, height), (1280, 640))
def test_crop_and_thumbnail_composite_transparency_on_white(self):
image = decode_image(encoded_image(Image.new("RGBA", (320, 200), (0, 0, 0, 0))))
thumb_bytes, _, _ = thumbnail(image)
crop_bytes, _, _ = crop(image)
self.assertEqual(Image.open(io.BytesIO(thumb_bytes)).getpixel((0, 0)), (255, 255, 255))
self.assertEqual(Image.open(io.BytesIO(crop_bytes)).getpixel((0, 0)), (255, 255, 255))
def test_decode_applies_exif_orientation(self):
exif = Image.Exif()
exif[274] = 6
data = encoded_image(Image.new("RGB", (320, 200), "navy"), "JPEG", exif=exif)
image = decode_image(data)
self.assertEqual(image.size, (200, 320))
def test_decode_rejects_non_image_payload(self):
with self.assertRaises((ValueError, OSError)):
decode_image(b"not an image")
if __name__ == "__main__":
unittest.main()
+60
View File
@@ -0,0 +1,60 @@
import json
import unittest
from contextlib import contextmanager
from datetime import datetime, timezone
from unittest.mock import patch
from src.worker import recover_expired_leases
class FakeDatabase:
def __init__(self):
self.job = {
"id": "job-id",
"attachment_id": "attachment-id",
"pipeline_version": 2,
"created_at": datetime.now(timezone.utc),
"attempt": 1,
}
self.job_status = "processing"
self.attachment_status = "processing"
self.outbox = []
@contextmanager
def transaction(self):
yield self
def execute(self, query, params=()):
statement = " ".join(query.split())
if statement.startswith("SELECT j.id,j.attachment_id,j.pipeline_version"):
self.rows = [self.job] if self.job_status == "processing" else []
elif statement.startswith("UPDATE jobs SET status='queued'"):
self.job_status = "queued"
elif statement.startswith("UPDATE attachments SET status='queued'"):
self.attachment_status = "queued"
elif statement.startswith("INSERT INTO outbox"):
self.outbox.append(json.loads(params[2]))
else:
raise AssertionError(f"Unexpected SQL in test fake: {statement}")
return self
def fetchall(self):
return self.rows
class LeaseRecoveryTests(unittest.TestCase):
def test_expired_lease_is_requeued_with_the_next_attempt(self):
db = FakeDatabase()
with patch("src.worker.transaction", db.transaction):
recover_expired_leases()
self.assertEqual(db.job_status, "queued")
self.assertEqual(db.attachment_status, "queued")
self.assertEqual(len(db.outbox), 1)
self.assertEqual(db.outbox[0]["attempt"], 2)
self.assertEqual(db.outbox[0]["pipeline_version"], 2)
if __name__ == "__main__":
unittest.main()
+89
View File
@@ -0,0 +1,89 @@
import json
import unittest
from contextlib import contextmanager
from unittest.mock import patch
from src.worker import publish_one_outbox_event
class FakeDatabase:
def __init__(self, payload=None):
self.row = None if payload is None else {
"id": "outbox-id",
"event_type": "attachment.process",
"payload": json.dumps(payload),
"available": True,
"published_at": None,
"publish_attempt": 0,
}
@contextmanager
def transaction(self):
snapshot = None if self.row is None else dict(self.row)
try:
yield self
except Exception:
self.row = snapshot
raise
def execute(self, query, params=()):
statement = " ".join(query.split())
if statement.startswith("SELECT id,event_type,payload"):
self.result = (
{key: self.row[key] for key in ("id", "event_type", "payload")}
if self.row and self.row["available"] and self.row["published_at"] is None
else None
)
elif statement.startswith("UPDATE outbox SET publish_attempt"):
self.row["publish_attempt"] += 1
elif statement.startswith("UPDATE outbox SET published_at=NOW()"):
self.row["published_at"] = "confirmed"
else:
raise AssertionError(f"Unexpected SQL in test fake: {statement}")
return self
def fetchone(self):
return self.result
class OutboxPublisherTests(unittest.TestCase):
def test_published_timestamp_is_set_only_after_broker_confirm(self):
payload = {"job_id": "job-id", "type": "attachment.process.v1"}
db = FakeDatabase(payload)
published = []
def confirm(message, routing_key):
self.assertEqual(db.row["published_at"], None)
self.assertEqual(db.row["publish_attempt"], 1)
published.append((message, routing_key))
with patch("src.worker.transaction", db.transaction), \
patch("src.worker.publish", side_effect=confirm):
self.assertTrue(publish_one_outbox_event())
self.assertEqual(published, [(payload, "attachment.process")])
self.assertEqual(db.row["published_at"], "confirmed")
def test_publish_failure_leaves_row_unpublished_for_retry(self):
db = FakeDatabase({"job_id": "job-id"})
with patch("src.worker.transaction", db.transaction), \
patch("src.worker.publish", side_effect=RuntimeError("broker unavailable")):
with self.assertRaisesRegex(RuntimeError, "broker unavailable"):
publish_one_outbox_event()
self.assertIsNone(db.row["published_at"])
self.assertEqual(db.row["publish_attempt"], 0)
def test_empty_outbox_does_not_publish(self):
db = FakeDatabase()
with patch("src.worker.transaction", db.transaction), \
patch("src.worker.publish") as publish:
self.assertFalse(publish_one_outbox_event())
publish.assert_not_called()
if __name__ == "__main__":
unittest.main()
+195
View File
@@ -0,0 +1,195 @@
import hashlib
import io
import json
import unittest
from contextlib import contextmanager
from datetime import datetime, timezone
from unittest.mock import patch
from PIL import Image
from src.pipeline import CURRENT_PIPELINE_VERSION, pipeline_qualities
from src.worker import PermanentJobError, TransientJobError, process, record_failure
class InjectedCrash(BaseException):
pass
class FakeDatabase:
def __init__(self, attachment_id, job_id, image_bytes, pipeline_version=2):
self.attachment_id = attachment_id
self.job_id = job_id
self.image_bytes = image_bytes
self.staging_key = f"staging/{attachment_id}/original"
self.content_type = "image/png"
self.sha256 = hashlib.sha256(image_bytes).hexdigest()
self.attachment_status = "queued"
self.job_status = "queued"
self.attempt = 0
self.pipeline_version = pipeline_version
self.created_at = datetime.now(timezone.utc)
self.outbox = []
self.attempts = []
self.variants = []
@contextmanager
def transaction(self):
yield self
def execute(self, query, params=()):
statement = " ".join(query.split())
if statement.startswith("SELECT a.staging_key"):
if str(params[0]) != self.attachment_id or str(params[1]) != self.job_id:
self.result = None
else:
self.result = {
"staging_key": self.staging_key,
"status": self.attachment_status,
"content_type": self.content_type,
"size_bytes": len(self.image_bytes),
"sha256": self.sha256,
"job_status": self.job_status,
"lease_until": None,
"attempt": self.attempt,
"pipeline_version": self.pipeline_version,
}
elif statement.startswith("UPDATE attachments SET status='processing'"):
self.attachment_status = "processing"
elif statement.startswith("UPDATE jobs SET attempt=attempt+1"):
self.attempt += 1
self.job_status = "processing"
elif statement.startswith("UPDATE attachments SET status='ready'"):
self.attachment_status = "ready"
self.variants = json.loads(params[1])
elif statement.startswith("UPDATE jobs SET status='ready'"):
self.job_status = "ready"
elif statement.startswith("SELECT j.id,j.attachment_id,j.attempt"):
self.result = {
"id": self.job_id,
"attachment_id": self.attachment_id,
"attempt": self.attempt,
"pipeline_version": self.pipeline_version,
"created_at": self.created_at,
"status": self.attachment_status,
}
elif statement.startswith("INSERT INTO job_attempts"):
self.attempts.append(params)
elif statement.startswith("UPDATE jobs SET status='queued'"):
self.job_status = "queued"
elif statement.startswith("UPDATE attachments SET status='queued'"):
self.attachment_status = "queued"
elif statement.startswith("INSERT INTO outbox"):
payload = params[2]
self.outbox.append(json.loads(payload) if isinstance(payload, str) else payload)
else:
raise AssertionError(f"Unexpected SQL in test fake: {statement}")
return self
def fetchone(self):
return self.result
class FakeStorage:
def __init__(self, image_bytes):
self.image_bytes = image_bytes
def get_object(self, **kwargs):
return {"Body": io.BytesIO(self.image_bytes)}
def png_fixture():
buffer = io.BytesIO()
Image.new("RGB", (320, 200), "navy").save(buffer, format="PNG")
return buffer.getvalue()
class PipelineFaultTests(unittest.TestCase):
def test_pipeline_versions_are_explicit_and_quality_is_versioned(self):
self.assertEqual(CURRENT_PIPELINE_VERSION, 2)
self.assertEqual(pipeline_qualities(1), (88, 82))
self.assertEqual(pipeline_qualities(2), (86, 80))
def make_job(self, db, attempt=1, pipeline_version=2):
return {
"job_id": db.job_id,
"attachment_id": db.attachment_id,
"attempt": attempt,
"pipeline_version": pipeline_version,
}
def run_process(self, db, objects, job):
def put_object(_bucket, key, data, _content_type):
objects[key] = data
with patch("src.worker.transaction", db.transaction), \
patch("src.worker.s3_client", return_value=FakeStorage(db.image_bytes)), \
patch("src.worker.put_object", side_effect=put_object), \
patch.dict("os.environ", {"S3_BUCKET": "test-bucket"}):
process(job)
def test_crash_before_and_after_object_write_retries_idempotently(self):
for stage in ("before_original_put", "after_original_put"):
with self.subTest(stage=stage):
image_bytes = png_fixture()
attachment_id = "9c554d5e-2d59-4c10-ae40-7f6f7aef6350"
job_id = "8f4b65d8-091d-423f-9565-d6ab08c8814c"
db = FakeDatabase(attachment_id, job_id, image_bytes)
objects = {}
first_job = self.make_job(db)
injection = f"{attachment_id}:1:{stage}"
with patch("src.worker.transaction", db.transaction), \
patch("src.worker.s3_client", return_value=FakeStorage(image_bytes)), \
patch("src.worker.put_object", side_effect=lambda _b, key, data, _c: objects.__setitem__(key, data)), \
patch.dict("os.environ", {"S3_BUCKET": "test-bucket", "WORKER_FAULT_INJECTION": injection}), \
patch("src.worker.os._exit", side_effect=InjectedCrash):
with self.assertRaises(InjectedCrash):
process(first_job)
original_key = f"final/{attachment_id}/original"
self.assertEqual(original_key in objects, stage == "after_original_put")
self.assertEqual(db.job_status, "processing")
with patch("src.worker.transaction", db.transaction):
record_failure(first_job, TransientJobError("worker_process_failed"))
self.assertEqual(db.outbox[0]["attempt"], 2)
# The redelivered first attempt is stale; the scheduled retry owns the next attempt.
self.run_process(db, objects, first_job)
self.assertEqual(db.job_status, "queued")
self.run_process(db, objects, db.outbox[0])
self.assertEqual(db.job_status, "ready")
self.assertEqual(db.attachment_status, "ready")
self.assertEqual(set(objects), {
original_key,
f"final/{attachment_id}/thumbnail",
f"final/{attachment_id}/crop",
f"final/{attachment_id}/optimized",
})
objects_before_duplicate = dict(objects)
self.run_process(db, objects, db.outbox[0])
self.assertEqual(objects, objects_before_duplicate)
def test_old_pipeline_message_cannot_overwrite_new_version(self):
image_bytes = png_fixture()
attachment_id = "9c554d5e-2d59-4c10-ae40-7f6f7aef6350"
job_id = "8f4b65d8-091d-423f-9565-d6ab08c8814c"
db = FakeDatabase(attachment_id, job_id, image_bytes, pipeline_version=2)
objects = {}
with self.assertRaises(PermanentJobError):
self.run_process(db, objects, self.make_job(db, pipeline_version=3))
self.run_process(db, objects, self.make_job(db, pipeline_version=1))
self.assertEqual(objects, {})
self.assertEqual(db.job_status, "queued")
self.run_process(db, objects, self.make_job(db, pipeline_version=2))
self.assertEqual(db.job_status, "ready")
self.assertTrue(objects)
if __name__ == "__main__":
unittest.main()
+81
View File
@@ -0,0 +1,81 @@
import json
import unittest
from contextlib import contextmanager
from datetime import datetime, timezone
from unittest.mock import patch
from src.replay import replay_failed_attachment
class FakeDatabase:
def __init__(self, status="failed"):
self.row = {
"id": "job-id",
"attachment_id": "9c554d5e-2d59-4c10-ae40-7f6f7aef6350",
"pipeline_version": 1,
"created_at": datetime.now(timezone.utc),
"status": status,
"attachment_status": status,
}
self.job_status = status
self.attachment_status = status
self.attempt = 5
self.replay_count = 0
self.audit = []
self.outbox = []
@contextmanager
def transaction(self):
yield self
def execute(self, query, params=()):
statement = " ".join(query.split())
if statement.startswith("SELECT j.id,j.attachment_id,j.pipeline_version"):
self.result = self.row if str(params[0]) == self.row["attachment_id"] else None
elif statement.startswith("UPDATE jobs"):
self.job_status = "queued"
self.attempt = 0
self.replay_count += 1
elif statement.startswith("UPDATE attachments"):
self.attachment_status = "queued"
elif statement.startswith("INSERT INTO job_replays"):
self.audit.append(params)
elif statement.startswith("INSERT INTO outbox"):
self.outbox.append(json.loads(params[1]))
else:
raise AssertionError(f"Unexpected SQL in test fake: {statement}")
return self
def fetchone(self):
return self.result
class ReplayTests(unittest.TestCase):
def test_failed_attachment_replay_is_audited_and_uses_transactional_outbox(self):
db = FakeDatabase()
with patch("src.replay.transaction", db.transaction):
result = replay_failed_attachment(db.row["attachment_id"], " operator-1 ")
self.assertEqual(result["status"], "queued")
self.assertEqual(db.job_status, "queued")
self.assertEqual(db.attachment_status, "queued")
self.assertEqual(db.attempt, 0)
self.assertEqual(db.replay_count, 1)
self.assertEqual(db.audit[0][3], "operator-1")
self.assertEqual(db.outbox[0]["pipeline_version"], 1)
self.assertEqual(db.outbox[0]["attempt"], 1)
def test_ready_attachment_cannot_be_replayed(self):
db = FakeDatabase(status="ready")
with patch("src.replay.transaction", db.transaction):
with self.assertRaisesRegex(ValueError, "only a failed attachment"):
replay_failed_attachment(db.row["attachment_id"], "operator-1")
self.assertEqual(db.replay_count, 0)
self.assertEqual(db.outbox, [])
if __name__ == "__main__":
unittest.main()
+50
View File
@@ -0,0 +1,50 @@
import unittest
from unittest.mock import Mock, patch
from src.worker import handle_message, retry_delay
class RetryPolicyTests(unittest.TestCase):
def test_exponential_backoff_is_jittered_within_attempt_window(self):
with patch("src.worker.RETRY_BASE_SECONDS", 1), patch("src.worker.RETRY_MAX_SECONDS", 60):
delay = retry_delay(4)
self.assertGreaterEqual(delay, 4)
self.assertLessEqual(delay, 8)
def test_backoff_respects_configured_cap(self):
with patch("src.worker.RETRY_BASE_SECONDS", 1), patch("src.worker.RETRY_MAX_SECONDS", 20):
delay = retry_delay(10)
self.assertGreaterEqual(delay, 10)
self.assertLessEqual(delay, 20)
def test_malformed_job_is_dead_lettered_without_processing(self):
channel = Mock()
body = b'{"schema_version":1,"type":"attachment.process.v1","job_id":"bad","attachment_id":"bad","pipeline_version":1,"attempt":1,"created_at":"now"}'
with patch("src.worker.process_with_timeout") as process:
handle_message(channel, 7, body)
channel.basic_nack.assert_called_once_with(delivery_tag=7, requeue=False)
process.assert_not_called()
def test_valid_job_is_acknowledged_after_processing(self):
channel = Mock()
job_id = "1b671a64-40d5-491e-99b0-da01ff1f3341"
attachment_id = "0e8c4c49-6d3e-4d3e-8ca0-cf4ed9a36e9a"
body = (
'{"schema_version":1,"type":"attachment.process.v1",'
f'"job_id":"{job_id}","attachment_id":"{attachment_id}",'
'"pipeline_version":1,"attempt":1,"created_at":"2026-01-01T00:00:00Z"}'
).encode()
with patch("src.worker.process_with_timeout"):
handle_message(channel, 8, body)
channel.basic_ack.assert_called_once_with(delivery_tag=8)
channel.basic_nack.assert_not_called()
if __name__ == "__main__":
unittest.main()
+72
View File
@@ -0,0 +1,72 @@
import unittest
from contextlib import contextmanager
from unittest.mock import patch
from src.worker import cleanup_staging
class FakeDatabase:
def __init__(self, status):
self.status = status
self.staging_deleted_at = None
@contextmanager
def transaction(self):
yield self
def execute(self, query, params=()):
statement = " ".join(query.split())
if statement.startswith("SELECT id,staging_key"):
self.result = (
{"id": "attachment-id", "staging_key": "staging/attachment-id/original"}
if self.status == "ready" and self.staging_deleted_at is None
else None
)
elif statement.startswith("UPDATE attachments SET staging_deleted_at=NOW()"):
self.staging_deleted_at = "deleted"
else:
raise AssertionError(f"Unexpected SQL in test fake: {statement}")
return self
def fetchone(self):
return self.result
class FakeStorage:
def __init__(self):
self.deleted = []
def delete_object(self, **kwargs):
self.deleted.append(kwargs)
class StagingCleanupTests(unittest.TestCase):
def test_only_ready_objects_are_deleted_and_cleanup_is_idempotent(self):
db = FakeDatabase(status="ready")
storage = FakeStorage()
with patch("src.worker.transaction", db.transaction), \
patch("src.worker.s3_client", return_value=storage), \
patch.dict("os.environ", {"S3_BUCKET": "test-bucket"}):
self.assertEqual(cleanup_staging(), 1)
self.assertEqual(cleanup_staging(), 0)
self.assertEqual(storage.deleted, [{
"Bucket": "test-bucket",
"Key": "staging/attachment-id/original",
}])
def test_processing_attachment_is_not_cleaned(self):
db = FakeDatabase(status="processing")
storage = FakeStorage()
with patch("src.worker.transaction", db.transaction), \
patch("src.worker.s3_client", return_value=storage), \
patch.dict("os.environ", {"S3_BUCKET": "test-bucket"}):
self.assertEqual(cleanup_staging(), 0)
self.assertEqual(storage.deleted, [])
if __name__ == "__main__":
unittest.main()
+6 -3
View File
@@ -13,8 +13,8 @@ import urllib.request
import uuid
ROOT = Path(__file__).resolve().parents[1]
LAB = json.loads((ROOT / 'lab.json').read_text())['number']
SPEC = json.loads((ROOT / 'contracts/openapi.json').read_text())
LAB = json.loads((ROOT / 'lab.json').read_text(encoding='utf-8'))['number']
SPEC = json.loads((ROOT / 'contracts/openapi.json').read_text(encoding='utf-8'))
class Failure(AssertionError):
pass
@@ -140,7 +140,10 @@ class Client:
payload = json.loads(data)
except (ValueError,UnicodeError):
raise Failure('invalid response JSON') from None
shape(payload, 'Error' if status>=400 else schema)
try:
shape(payload, 'Error' if status>=400 else schema)
except Failure as exc:
raise Failure(method + ' ' + path.split('?')[0] + ': ' + str(exc)) from None
if status>=400:
check(payload['error']['request_id']==rh.get('X-Request-Id'),'error request_id differs from header')
if status==401 and LAB>=2: