forked from mtusi2026/mtusi2026lab5
Compare commits
10
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
670fac52f0 | ||
|
|
c872d95208 | ||
|
|
346720166b | ||
|
|
179c795758 | ||
|
|
f8ca7a7218 | ||
|
|
5442dfd3bc | ||
|
|
6ba7db4b7d | ||
|
|
6e09da0b46 | ||
|
|
f2000a7883 | ||
|
|
97b43a9c98 |
@@ -1,18 +1,18 @@
|
|||||||
## Лабораторная 5
|
## Лабораторная 5
|
||||||
|
|
||||||
Автор / группа: TODO
|
Автор / группа: Белоусов Анатолий Фахраддинович, БПИ2303
|
||||||
Целевая оценка (3/4/5): TODO
|
Целевая оценка (3/4/5): 5
|
||||||
Трек 5, если заявлен: TODO
|
Трек 5, если заявлен: Трек 2
|
||||||
|
|
||||||
Что реализовано и что перенесено: TODO
|
Что реализовано и что перенесено: решение lab4 (PostgreSQL, Redis-сессии, S3, API вложений, reconciler) расширено RabbitMQ, transactional outbox, отдельным worker, версиями pipeline, retry/replay и fault-injection тестами.
|
||||||
Команды запуска из чистого clone: TODO
|
Команды запуска из чистого clone: см. `REPORT.md`, раздел «Запуск из чистого clone».
|
||||||
Результаты проверок и ссылка на REPORT.md: TODO
|
Результаты проверок и ссылка на REPORT.md: `make check`, `make test`, `make contract-go`, `make worker-go`, `make pipeline-go`; подробности в `REPORT.md`.
|
||||||
Ограничения / известные ошибки: TODO
|
Ограничения / известные ошибки: указаны в `REPORT.md`, раздел «Ограничения и следующие шаги».
|
||||||
Источники и использование ИИ: TODO
|
Источники и использование ИИ: материалы лабораторной, официальная документация зависимостей; Codex использован для анализа и проверки.
|
||||||
|
|
||||||
- [ ] Весь обязательный минимум текущей и предыдущих работ сохранён с объявленными переходами.
|
- [x] Весь обязательный минимум текущей и предыдущих работ сохранён с объявленными переходами.
|
||||||
- [ ] Контракт и публичные тесты не ослаблены.
|
- [x] Контракт и публичные тесты не ослаблены.
|
||||||
- [ ] make check и make test выполнены; приложен реальный вывод.
|
- [x] make check и make test выполнены; приложен реальный вывод.
|
||||||
- [ ] Сценарии отказов/безопасности своего уровня воспроизведены.
|
- [x] Сценарии отказов/безопасности своего уровня воспроизведены.
|
||||||
- [ ] Все секреты и приватные ключи находятся вне Git; отчёт не содержит tokens.
|
- [x] Все секреты и приватные ключи находятся вне Git; отчёт не содержит tokens.
|
||||||
- [ ] README задания сохранён, REPORT.md содержит инструкцию именно моего решения.
|
- [x] README задания сохранён, REPORT.md содержит инструкцию именно моего решения.
|
||||||
|
|||||||
@@ -1,37 +1,146 @@
|
|||||||
# Отчёт — лабораторная 5
|
# Отчёт — лабораторная 5
|
||||||
|
|
||||||
- Автор, группа: TODO
|
- Автор, группа: Белоусов Анатолий Фахраддинович, БПИ2303
|
||||||
- Целевая оценка; выбранный трек 5, если нужен: TODO
|
- Целевая оценка; выбранный трек 5, если нужен: 5; трек 2
|
||||||
- Commit/PR: TODO после публикации
|
- Commit/PR: ветка `solution/bpi2303-belousov`, PR в `mtusi2026/mtusi2026lab5`
|
||||||
- Использованные источники, библиотеки и помощь ИИ: TODO
|
- Использованные источники, библиотеки и помощь ИИ: материалы лабораторной; Go 1.26+, chi v5, pgx v5, sqlc, goose, AWS SDK for Go v2, amqp091-go, imaging, gen2brain/webp, golang.org/x/image, PostgreSQL 18.6, Redis 8.8.3, Nginx 1.31.7, Docker Compose, SeaweedFS 4.51, RabbitMQ 4.2.9; Codex - для анализа реализации и проверок, оформления отчёта
|
||||||
|
|
||||||
## Запуск из чистого clone
|
## Запуск из чистого clone
|
||||||
|
|
||||||
TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных.
|
Требуются Go 1.26+ и Docker с Compose. Образы: `golang:1.27.1`, `postgres:18.6`, `redis:8.8.3-alpine3.23`, `nginx:1.31.7-alpine3.24`, `chrislusf/seaweedfs:4.51`, `rabbitmq:4.2.9-alpine`.
|
||||||
|
|
||||||
|
Создать локальные секреты - файлы в `secrets/`, в каждый записать значение без лишних символов:
|
||||||
|
|
||||||
|
- `database_url.txt` - URL PostgreSQL для API и worker;
|
||||||
|
- `cache_url.txt` - URL Redis;
|
||||||
|
- `postgres_password.txt` - пароль пользователя PostgreSQL `messenger`;
|
||||||
|
- `test_database_url.txt` - URL БД для тестов с хоста;
|
||||||
|
- `s3_access_key_id.txt` - S3 access key ID для API и worker;
|
||||||
|
- `s3_secret_access_key.txt` - S3 secret access key для API и worker;
|
||||||
|
- `s3_bootstrap_access_key_id.txt` - bootstrap access key ID;
|
||||||
|
- `s3_bootstrap_secret_access_key.txt` - bootstrap secret access key;
|
||||||
|
- `broker_url.txt` - AMQP URL для API и worker;
|
||||||
|
- `broker_password.txt` - пароль пользователя RabbitMQ `messenger`.
|
||||||
|
|
||||||
|
Пример (значения заменить своими):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
mkdir -p secrets
|
||||||
|
printf '%s' 'CHANGE_ME' > secrets/postgres_password.txt
|
||||||
|
printf '%s' 'postgres://messenger:CHANGE_ME@postgres:5432/messenger?sslmode=disable' > secrets/database_url.txt
|
||||||
|
printf '%s' 'redis://redis:6379/0' > secrets/cache_url.txt
|
||||||
|
```
|
||||||
|
|
||||||
|
Скопировать шаблон переменных окружения:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cp .env.example .env
|
||||||
|
```
|
||||||
|
|
||||||
|
Сборка и запуск:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker compose up --build -d
|
||||||
|
```
|
||||||
|
|
||||||
|
Готовность API проверяется запросом к `/health/ready`; после этого API доступен на http://localhost:8080.
|
||||||
|
|
||||||
|
Сваггер доступен на http://localhost:8080/swagger/.
|
||||||
|
|
||||||
|
Безопасная остановка (данные PostgreSQL, S3 и RabbitMQ в volumes сохраняются):
|
||||||
|
```bash
|
||||||
|
docker compose down
|
||||||
|
```
|
||||||
|
|
||||||
|
Намеренное удаление учебных данных:
|
||||||
|
```bash
|
||||||
|
docker compose down -v
|
||||||
|
```
|
||||||
|
|
||||||
## Архитектура и решения
|
## Архитектура и решения
|
||||||
|
|
||||||
TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab4, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации.
|
**Процессы/хранилища:** клиент → nginx → `api` × `API_REPLICAS` (по умолчанию 2) → staging в SeaweedFS S3 + PostgreSQL → outbox publisher → RabbitMQ → `worker` → оригинал и варианты в S3 + результат в PostgreSQL. Redis используется как кэш сессий с fallback в PostgreSQL. Единственная публичная точка входа API - `127.0.0.1:8080`.
|
||||||
|
|
||||||
|
**Источник истины** - PostgreSQL: метаданные вложений, состояния заданий, попытки, lease (срок захвата задания обработчиком), версии pipeline и outbox. Байты оригиналов и вариантов хранятся в приватном S3 bucket `messenger-attachments`. Сообщения брокера содержат ID и служебные поля, без байтов изображений и credentials.
|
||||||
|
|
||||||
|
**Что перенесено из lab4:** Go-приложение и PostgreSQL, аутентификация, сессии, чаты, сообщения, идемпотентность и `X-Instance-Id`, Redis-кэш сессий, S3-хранилище (SeaweedFS), API вложений и `attachment_ids` в сообщениях, reconciler, `compose.yaml`, `deploy/nginx.conf`, `Dockerfile`, `Dockerfile.migrate`, `Dockerfile.s3config`, `Dockerfile.reconcile`, `scripts/restart.sh`, `scripts/stop-one.sh`, `student-tests`, `student.mk`, `Makefile`, `web/swagger`, `contracts`.
|
||||||
|
|
||||||
|
**Что изменено в lab5:** upload возвращает `202 queued` после сохранения оригинала в staging и транзакции с метаданными и outbox; добавлены RabbitMQ и отдельный worker, состояния `processing`/`ready`/`failed`, thumbnail JPEG, crop JPEG и optimized WebP; миграция pipeline с таблицами вариантов, outbox и audit replay; ограниченные повторы, lease recovery, команды просмотра failed, replay и upgrade версии pipeline. Обработка изображений выполняется в worker, API проверяет загружаемый файл и сохраняет источник.
|
||||||
|
|
||||||
|
**Транзакционные границы.** API сначала сохраняет проверенный оригинал в staging, затем в одной транзакции PostgreSQL создаёт вложение `queued` и запись outbox. Ответ `202` возвращается после COMMIT. Worker записывает оригинал и все варианты в S3, затем под блокировкой строки проверяет job ID, версию, попытку и срок захвата задания. Метаданные вариантов и переход в `ready` фиксируются одной транзакцией. Общей транзакции S3 и PostgreSQL нет: сбой между операциями может оставить объекты без опубликованного результата.
|
||||||
|
|
||||||
|
**Брокер и подтверждения.** RabbitMQ хранит durable очередь `attachments.process.v1`, сообщения публикуются как persistent. Publisher в API читает outbox и отмечает публикацию только после publisher confirm - подтверждения приёма брокером. При сбое запись остаётся для повторной публикации. Consumer ack подтверждает обработку: worker отправляет его после устойчивой фиксации результата, повтора или `failed`. Доставка at least once допускает дубли; повтор готового задания проверяет размеры и SHA-256 объектов и не создаёт новые варианты.
|
||||||
|
|
||||||
|
**Обработка изображений.** Оригинал сохраняется без изменения байтов. Thumbnail - JPEG с качеством 85, до 256×256 с сохранением пропорций, без увеличения; crop - JPEG с качеством 85, центральная обрезка 128×128 с допустимым увеличением. Optimized - WebP, до 1280×1280 с сохранением пропорций, без увеличения, Method 4, качество 80 для v1 и 75 для v2. Перед обработкой применяется EXIF orientation; EXIF/XMP/ICC в варианты не переносятся. Прозрачность в JPEG заменяется белым фоном, в WebP сохраняется.
|
||||||
|
|
||||||
|
**Ограничения обработки.** Размер загрузки - до 10 MiB, число пикселей - до 40 млн. Worker проверяет размер и SHA-256 источника, размеры изображения проверяются до полного декодирования. По умолчанию работают 2 consumer с prefetch 1, одновременно декодируется одно изображение. Декодирование, resize и кодирование выполняются в дочернем процессе, который завершается при истечении таймаута задания (по умолчанию 60 с). Лимиты контейнера worker - 1 CPU и 1 GiB RAM, общие для основного и дочернего процессов; отдельного лимита памяти дочернего процесса нет.
|
||||||
|
|
||||||
|
**Повторы и восстановление.** По умолчанию допускается 5 попыток. Для временных ошибок используется экспоненциальная задержка со случайным разбросом (backoff с jitter): 1-2 с, 2-4 с и далее до 32-64 с. Повреждённый или отсутствующий источник переводит задание в `failed` с `invalid_source`, исчерпание попыток - с `retry_exhausted`. Возврат в `queued` и outbox следующей попытки фиксируются одной транзакцией. Если worker завершился во время обработки, после истечения срока захвата задания фоновая проверка возвращает его на повтор либо фиксирует `failed`, если попытки закончились.
|
||||||
|
|
||||||
|
**Реестр failed и replay.** Неуспешные задания хранятся в PostgreSQL и доступны через `worker -list-failed`. Явный replay разрешён только для `failed` с сохранённым staging и без записанных вариантов. Перед повтором проверяются размер и SHA-256 источника; переход в `queued`, новый бюджет попыток, запись оператора и причины в audit и outbox фиксируются одной транзакцией. Job ID и версия сохраняются. Готовое задание повторно запустить через replay нельзя.
|
||||||
|
|
||||||
|
**Очистка staging.** Worker удаляет источник из staging после COMMIT состояния `ready`; ошибка удаления логируется и не отменяет готовый результат. Остатки staging для `ready`/`failed` и объекты без строки БД удаляет явный запуск reconciler, по умолчанию после 24 часов. Для связанных объектов срок считается от `updated_at`, для объектов без строки - от времени изменения в S3. Источники `queued`/`processing` сохраняются независимо от возраста. Периодической очистки staging нет; после удаления источника replay недоступен.
|
||||||
|
|
||||||
|
**Версии pipeline.** Новые загрузки используют v1. Команда `worker -upgrade UUID` переводит незавершённое вложение v1 (`queued`/`processing` с staging) на v2, сохраняя attachment ID, job ID и исходные байты. Смена версии и outbox фиксируются одной транзакцией. Варианты хранятся по ключам `variants/<attachment_id>/v<version>/<variant>`, уникальность в БД - `(attachment_id, pipeline_version, variant)`. Проверка версии, попытки и срока захвата не позволяет старому worker опубликовать результат вместо нового. Upgrade готового или failed-вложения не поддерживается; остаточные S3-объекты старой версии автоматически не очищаются.
|
||||||
|
|
||||||
|
**Переменные `.env.example`:** `APP_HOST`, `APP_PORT` - адрес и порт API; `MAX_INFLIGHT_REQUESTS` - ограничитель одновременных запросов (0 - выключен); `SESSION_TTL_SECONDS` - срок жизни сессии; `LOG_LEVEL` - уровень логов; `DATABASE_URL_FILE`, `CACHE_URL_FILE` - пути к secrets с URL PostgreSQL и Redis; `SESSION_STORE` - режим хранения сессий (`postgres` или `redis`); `API_REPLICAS` - число реплик API; `IDEMPOTENCY_TTL_SECONDS` - срок хранения ключей идемпотентности; `S3_ENDPOINT`, `S3_REGION`, `S3_BUCKET` - настройки S3; `S3_ACCESS_KEY_ID_FILE`, `S3_SECRET_ACCESS_KEY_FILE`, `S3_BOOTSTRAP_ACCESS_KEY_ID_FILE`, `S3_BOOTSTRAP_SECRET_ACCESS_KEY_FILE` - пути к S3 secrets; `MAX_UPLOAD_BYTES`, `MAX_IMAGE_PIXELS` - лимиты загрузки; `BROKER_URL_FILE` - путь к secret с AMQP URL; `BROKER_PASSWORD_FILE` - путь к secret с паролем RabbitMQ; `WORKER_CONCURRENCY` - число consumer; `JOB_MAX_ATTEMPTS` - лимит попыток; `JOB_TIMEOUT_SECONDS` - таймаут задания и срок его захвата; `STAGING_RETENTION_SECONDS` - срок хранения остатков staging перед очисткой reconciler.
|
||||||
|
|
||||||
## Доказательства критериев
|
## Доказательства критериев
|
||||||
|
|
||||||
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
|
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
|
||||||
| --- | --- | --- | --- |
|
| --- | --- | --- | --- |
|
||||||
| Публичный smoke | make test | TODO | TODO |
|
| Публичный smoke | `make test` | `PASS` | `evidence/make-test.txt` |
|
||||||
| Остальные пункты уровня 3 | TODO | TODO | TODO |
|
| Уровень 3 |
|
||||||
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO |
|
| JPEG, MIME, целостность, лимиты размера и пикселей, безопасный filename, проверка доступа к вложениям | `make contract-go` | `PASS` | `evidence/contract-go.txt` |
|
||||||
| Выбранный трек 5, если заявлен | TODO | TODO | TODO |
|
| Сохранность задания после перезапуска API и broker; queued → ready; неизменный оригинал и JPEG thumbnail; отсутствие дублей вариантов при повторной доставке | `make worker-go`: `TestWorkerPersistenceAndDuplicate` | `PASS` | `evidence/worker-go.txt` |
|
||||||
|
| Ограниченный retry, failed и безопасный error_code | `make worker-go`: `TestWorkerRetryExhausted` | `PASS` | `evidence/worker-go.txt` |
|
||||||
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены.
|
| Уровень 4 |
|
||||||
|
| Размеры thumbnail, сохранение пропорций, отсутствие увеличения, белый фон вместо прозрачности | `make contract-go`: `TestThumbnail` | `PASS` | `evidence/contract-go.txt` |
|
||||||
|
| Центральная обрезка crop 128×128, включая маленькие изображения | `make contract-go`: `TestCrop` | `PASS` | `evidence/contract-go.txt` |
|
||||||
|
| Optimized WebP, ограничение размеров, сохранение пропорций и прозрачности | `make contract-go`: `TestOptimized` | `PASS` | `evidence/contract-go.txt` |
|
||||||
|
| Применение EXIF orientation и удаление EXIF из вариантов | `make contract-go`: `TestVariantsEXIF` | `PASS` | `evidence/contract-go.txt` |
|
||||||
|
| Ограничение времени обработки, завершение дочернего процесса, работоспособность worker после таймаута | `make worker-go`: `TestWorkerProcessingTimeout` | `PASS` | `evidence/worker-go.txt` |
|
||||||
|
| Восстановление задания после COMMIT и падения API до публикации в broker | `make worker-go`: `TestWorkerOutboxRecovery` | `PASS` | `evidence/worker-go.txt` |
|
||||||
|
| Реестр failed, явный replay с audit, отказ повтора без источника и повторного replay готового задания | `make worker-go`: `TestWorkerReplay` | `PASS` | `evidence/worker-go.txt` |
|
||||||
|
| Падение worker после записи объектов до COMMIT/ack, восстановление после истечения срока захвата задания | `make worker-go`: `TestWorkerLeaseRecovery` | `PASS` | `evidence/worker-go.txt` |
|
||||||
|
| Уровень 5, трек 2 |
|
||||||
|
| Позднее завершение v1 после готовности v2 не меняет текущий результат | `make pipeline-go`: `TestPipelineStaleProcessing` | `PASS` | `evidence/pipeline-go.txt` |
|
||||||
|
| Обратный порядок доставки v2/v1 и дубль v2 не меняют результат и не создают новые варианты | `make pipeline-go`: `TestPipelineReorderAndDuplicate` | `PASS` | `evidence/pipeline-go.txt` |
|
||||||
|
| Падение до первой записи результата в S3, восстановление того же задания после истечения срока захвата | `make pipeline-go`: `TestPipelineCrashBeforeWrite` | `PASS` | `evidence/pipeline-go.txt` |
|
||||||
|
|
||||||
## Эксперименты и отказы
|
## Эксперименты и отказы
|
||||||
|
|
||||||
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения.
|
### Трек 2: доказанная идемпотентность pipeline
|
||||||
|
|
||||||
|
**Гипотеза:** повторная доставка и изменение порядка заданий не меняют готовый результат. Старый worker не может заменить результат новой версии своим. После падения API или worker принятое задание восстанавливается и доходит до ready без повторной загрузки файла.
|
||||||
|
|
||||||
|
Инварианты: attachment ID, job ID и байты оригинала сохраняются; после готовности v2 старые задания и дубли не меняют метаданные и байты текущих вариантов; в БД остаётся один набор из трёх вариантов текущей версии; после падения до или после записи объектов то же задание доходит до ready.
|
||||||
|
|
||||||
|
Методика: `make pipeline-go` выполняет три последовательных сценария на свободном стенде с пустой очередью. Каждый создаёт через API синтетическое PNG 320×200 и переводит вложение на v2 штатной командой upgrade. Временный S3-прокси задерживает запись объекта в S3 для проверки позднего завершения v1 и падения до первой записи результата. Для перестановки доставки тест откладывает публикацию v1 через `available_at` в outbox, затем повторно публикует v2 сбросом `published_at`. Проверяются API, байты объектов, строки БД и освобождение очереди после ack. Падение после записи объектов проверяет `TestWorkerLeaseRecovery` из `make worker-go`: INSERT вариантов блокируется, worker завершается через SIGKILL до COMMIT/ack, затем ожидается естественное истечение срока захвата задания.
|
||||||
|
|
||||||
|
Стенд и лимиты описаны выше. Обычный worker использует 2 consumer с prefetch 1; временные worker в pipeline-тестах - 1 consumer, таймаут 120 с для задержанной v1 и 15 с для падения до записи. В тесте падения после записи таймаут также 15 с. Приведён один сохранённый прогон каждого сценария, без нагрузочного профиля и отдельного прогрева; RPS, перцентили задержек и фактическое потребление CPU/RAM не измерялись.
|
||||||
|
|
||||||
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
|
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
|
||||||
| --- | --- | --- | --- |
|
| --- | --- | --- | --- |
|
||||||
| TODO | TODO | TODO | TODO |
|
| Задержка записи optimized WebP версии v1 в S3 до готовности v2 | Старый worker не заменит результат v2 | v2 осталась ready, метаданные и байты не изменились; 0 строк вариантов v1 и 3 строки v2; старое задание подтверждено | Не измерялось / потери нет |
|
||||||
|
| Доставка v1 после v2, затем повтор v2 | Порядок и дубли не повлияют на готовый результат | Job ID, версия, попытка, метаданные и все 4 объекта не изменились; новых строк вариантов и outbox нет | Не измерялось / потери нет |
|
||||||
|
| SIGKILL worker до записи первого объекта результата в S3 | То же задание завершится после восстановления | После истечения срока захвата получен ready v2 на попытке 2, сохранены job ID и оригинал, доступны 3 варианта | Не измерялось / потери нет |
|
||||||
|
| SIGKILL worker после записи объектов в S3 до COMMIT/ack | Повтор завершит то же задание без дублей | После истечения срока захвата получен ready на попытке 2, сохранены job ID и оригинал, в БД 3 варианта | Не измерялось / потери нет |
|
||||||
|
| SIGKILL API после COMMIT до публикации в broker | Outbox восстановит публикацию без создания нового задания | То же задание автоматически опубликовано и завершено на попытке 1, оригинал сохранён, доступны 3 варианта | Не измерялось / потери нет |
|
||||||
|
|
||||||
|
Результаты: все сценарии прошли. Длительности pipeline-тестов - 12,67 / 41,43 / 26,05 с, всего 80,150 с (`evidence/pipeline-go.txt`). Длительности теста падения после записи объектов в S3 - 26,54 с, восстановления outbox - 33,15 с (`evidence/worker-go.txt`). Это полное время тестов с подготовкой и очисткой, время восстановления отдельно не измерялось.
|
||||||
|
|
||||||
|
**Вывод:** гипотеза подтверждена в проверенных сценариях. Принятые задания завершились после восстановления, дубли и старая версия не изменили текущий результат. Доставка остаётся at least once: падение после публикации до фиксации outbox или после COMMIT результата до ack допускает повторную доставку. Идемпотентность результата не означает exactly-once доставку или общую транзакцию S3 и PostgreSQL.
|
||||||
|
|
||||||
## Ограничения и следующие шаги
|
## Ограничения и следующие шаги
|
||||||
|
|
||||||
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза.
|
- Nginx, PostgreSQL и SeaweedFS работают в одном экземпляре на одном хосте. Реплики API не защищают от отказа этих компонентов или самого хоста.
|
||||||
|
- Если удалить сессию из Redis не удалось, logout возвращает `503 unavailable`: сессия уже удалена из PostgreSQL, но старый токен может приниматься из кэша до 60 с. Несмотря на `503`, может потребоваться повторный вход. Пока Redis недоступен, получить `204` нельзя, хотя сессия в БД уже удалена; после восстановления повторный logout вернёт `401`.
|
||||||
|
- Полное декодирование требует памяти под распакованное изображение. Для ограничения расхода RAM на каждой API-реплике работает один декодер, поэтому параллельные загрузки ожидают своей очереди.
|
||||||
|
- Общей транзакции PostgreSQL и S3 нет: расхождения исправляются последующей сверкой. Reconciler отмечает отсутствие оригинала, но не восстанавливает байты. Сохранность volumes не заменяет резервные копии хранилищ.
|
||||||
|
- Reconciler загружает списки объектов и метаданных целиком в память, поэтому расход памяти растёт с объёмом хранилища.
|
||||||
|
- RabbitMQ также работает в одном экземпляре. Проверены перезапуск API и broker с сохранением volumes, падение worker до и после записи объектов, повторная доставка и устаревшая версия задания. Потеря volumes, отказ хоста и одновременные отказы нескольких хранилищ не проверялись.
|
||||||
|
- При удалении staging сбой COMMIT после удаления объекта может оставить старый ключ в БД. Reconciler не сверяет варианты изображений; остатки объектов старой версии автоматически не удаляются.
|
||||||
|
- Replay доступен только для failed с сохранённым staging и без записанных вариантов. Upgrade поддерживает только незавершённую v1; повторная обработка готовых вложений не реализована.
|
||||||
|
- Очистка остатков staging требует явного запуска reconciler. Источники queued/processing защищены от удаления независимо от возраста.
|
||||||
|
- Память ограничена на уровне контейнера worker, отдельного лимита дочернего процесса нет. Поведение при исчерпании памяти и длительной перегрузке не исследовалось. Проверки идемпотентности выполнены на небольших PNG 320×200, без измерения пропускной способности и времени восстановления.
|
||||||
|
|||||||
@@ -0,0 +1,18 @@
|
|||||||
|
# Защита лабораторной 5
|
||||||
|
|
||||||
|
Цель: оценка 5, трек 2 — доказанная идемпотентность pipeline.
|
||||||
|
|
||||||
|
```sh
|
||||||
|
cp .env.example .env
|
||||||
|
# создать secrets по REPORT.md
|
||||||
|
docker compose up --build -d
|
||||||
|
make check
|
||||||
|
make test
|
||||||
|
make contract-go
|
||||||
|
make worker-go
|
||||||
|
make pipeline-go
|
||||||
|
```
|
||||||
|
|
||||||
|
На защите показать: `202 queued` после durable staging + outbox; остановленный worker не теряет задачу; после запуска worker вложение становится `ready`; доступны original/thumbnail/crop/optimized; duplicate/reorder и старая версия не перезаписывают новый результат; replay failed ограничен и аудируется.
|
||||||
|
|
||||||
|
Вопросы и ответы подготовлены в `REPORT.md`: publisher confirm vs consumer ack, источник истины, at-least-once доставка, lease и идемпотентность.
|
||||||
+172
-19
@@ -2,59 +2,192 @@ package main
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"errors"
|
||||||
|
"flag"
|
||||||
"fmt"
|
"fmt"
|
||||||
"os"
|
"os"
|
||||||
"os/signal"
|
"os/signal"
|
||||||
|
"strings"
|
||||||
"syscall"
|
"syscall"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"github.com/jackc/pgx/v5/pgxpool"
|
||||||
"github.com/joho/godotenv"
|
"github.com/joho/godotenv"
|
||||||
|
|
||||||
"mtusi2026-messenger/internal/config"
|
"mtusi2026-messenger/internal/config"
|
||||||
|
"mtusi2026-messenger/internal/db"
|
||||||
"mtusi2026-messenger/internal/logger"
|
"mtusi2026-messenger/internal/logger"
|
||||||
"mtusi2026-messenger/internal/postgres"
|
"mtusi2026-messenger/internal/postgres"
|
||||||
s3store "mtusi2026-messenger/internal/s3"
|
s3store "mtusi2026-messenger/internal/s3"
|
||||||
"mtusi2026-messenger/internal/worker"
|
"mtusi2026-messenger/internal/worker"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
errConflictingReplayFlags = errors.New("replay and list-failed cannot be combined")
|
||||||
|
errInvalidReplayID = errors.New("replay must be an attachment UUID")
|
||||||
|
errMissingReplayAudit = errors.New("replay requires nonempty operator and reason")
|
||||||
|
errConflictingUpgradeFlags = errors.New("upgrade cannot be combined with replay or list-failed")
|
||||||
|
errInvalidUpgradeID = errors.New("upgrade must be an attachment UUID")
|
||||||
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
if err := run(); err != nil {
|
maxPixels := flag.Int("process-image", 0, "process an image from stdin with the given pixel limit")
|
||||||
|
pipelineVersion := flag.Int("pipeline-version", 1, "pipeline version for process-image")
|
||||||
|
replay := flag.String("replay", "", "replay a failed attachment by UUID; requires retained staging and no existing variants")
|
||||||
|
operator := flag.String("operator", "", "operator requesting replay")
|
||||||
|
reason := flag.String("reason", "", "reason for replay")
|
||||||
|
listFailed := flag.Bool("list-failed", false, "list up to 100 failed attachments")
|
||||||
|
upgrade := flag.String("upgrade", "", "upgrade a v1 queued or processing attachment to v2; requires retained staging")
|
||||||
|
flag.Parse()
|
||||||
|
|
||||||
|
if *maxPixels > 0 {
|
||||||
|
if err := worker.ProcessImage(*maxPixels, *pipelineVersion); err != nil {
|
||||||
|
if errors.Is(err, worker.ErrInvalidSource) {
|
||||||
|
os.Exit(2)
|
||||||
|
}
|
||||||
|
|
||||||
|
fmt.Fprintln(os.Stderr, "process image:", err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
|
||||||
|
defer stop()
|
||||||
|
|
||||||
|
var err error
|
||||||
|
switch {
|
||||||
|
case *upgrade != "" && (*listFailed || *replay != ""):
|
||||||
|
err = errConflictingUpgradeFlags
|
||||||
|
case *listFailed && *replay != "":
|
||||||
|
err = errConflictingReplayFlags
|
||||||
|
case *listFailed:
|
||||||
|
err = runListFailed(ctx)
|
||||||
|
case *replay != "":
|
||||||
|
err = runReplay(ctx, *replay, *operator, *reason)
|
||||||
|
case *upgrade != "":
|
||||||
|
err = runUpgrade(ctx, *upgrade)
|
||||||
|
default:
|
||||||
|
err = runWorker(ctx)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
fmt.Fprintln(os.Stderr, "worker:", err)
|
fmt.Fprintln(os.Stderr, "worker:", err)
|
||||||
os.Exit(1)
|
os.Exit(1)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func run() error {
|
func runListFailed(ctx context.Context) error {
|
||||||
if err := godotenv.Load(); err != nil && !os.IsNotExist(err) {
|
ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
|
||||||
return err
|
defer cancel()
|
||||||
}
|
|
||||||
|
|
||||||
cfg := config.Load()
|
_, pool, err := loadDatabase(ctx)
|
||||||
log := logger.New(cfg.Logging.Level)
|
|
||||||
databaseURL, err := cfg.Database.URL()
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
defer pool.Close()
|
||||||
|
|
||||||
|
rows, err := db.New(pool).ListFailedAttachments(ctx, 100)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, row := range rows {
|
||||||
|
code := "-"
|
||||||
|
if row.ErrorCode != nil {
|
||||||
|
code = *row.ErrorCode
|
||||||
|
}
|
||||||
|
|
||||||
|
fmt.Printf("%s attempts=%d error_code=%s\n", row.ID, row.Attempts, code)
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func runReplay(ctx context.Context, replay, operator, reason string) error {
|
||||||
|
replayID, err := uuid.Parse(replay)
|
||||||
|
if err != nil {
|
||||||
|
return errInvalidReplayID
|
||||||
|
}
|
||||||
|
|
||||||
|
operator, reason = strings.TrimSpace(operator), strings.TrimSpace(reason)
|
||||||
|
if operator == "" || reason == "" {
|
||||||
|
return errMissingReplayAudit
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
cfg, pool, err := loadDatabase(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer pool.Close()
|
||||||
|
|
||||||
|
log := logger.New(cfg.Logging.Level)
|
||||||
|
storage, err := s3store.NewAPI(ctx, cfg.S3, log)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := worker.Replay(ctx, pool, storage, replayID, operator, reason); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Info("attachment replay queued", "attachment_id", replayID, "operator", operator)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func runUpgrade(ctx context.Context, upgrade string) error {
|
||||||
|
id, err := uuid.Parse(upgrade)
|
||||||
|
if err != nil {
|
||||||
|
return errInvalidUpgradeID
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
cfg, pool, err := loadDatabase(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer pool.Close()
|
||||||
|
|
||||||
|
log := logger.New(cfg.Logging.Level)
|
||||||
|
storage, err := s3store.NewAPI(ctx, cfg.S3, log)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := worker.Upgrade(ctx, pool, storage, id); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Info("attachment pipeline upgrade queued", "attachment_id", id, "pipeline_version", 2)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func runWorker(ctx context.Context) error {
|
||||||
|
cfg, pool, err := loadDatabase(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer pool.Close()
|
||||||
|
|
||||||
brokerURL, err := cfg.Broker.URL()
|
brokerURL, err := cfg.Broker.URL()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
|
log := logger.New(cfg.Logging.Level)
|
||||||
defer stop()
|
|
||||||
|
|
||||||
pool, err := postgres.New(ctx, databaseURL)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
defer pool.Close()
|
|
||||||
|
|
||||||
storage, err := s3store.NewAPI(ctx, cfg.S3, log)
|
storage, err := s3store.NewAPI(ctx, cfg.S3, log)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
worker.New(
|
w := worker.New(
|
||||||
pool,
|
pool,
|
||||||
storage,
|
storage,
|
||||||
brokerURL,
|
brokerURL,
|
||||||
@@ -62,7 +195,27 @@ func run() error {
|
|||||||
cfg.S3.MaxUploadBytes,
|
cfg.S3.MaxUploadBytes,
|
||||||
cfg.S3.MaxImagePixels,
|
cfg.S3.MaxImagePixels,
|
||||||
log,
|
log,
|
||||||
).Run(ctx)
|
)
|
||||||
|
w.Run(ctx)
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func loadDatabase(ctx context.Context) (config.Config, *pgxpool.Pool, error) {
|
||||||
|
if err := godotenv.Load(); err != nil && !os.IsNotExist(err) {
|
||||||
|
return config.Config{}, nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
cfg := config.Load()
|
||||||
|
databaseURL, err := cfg.Database.URL()
|
||||||
|
if err != nil {
|
||||||
|
return config.Config{}, nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
pool, err := postgres.New(ctx, databaseURL)
|
||||||
|
if err != nil {
|
||||||
|
return config.Config{}, nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return cfg, pool, nil
|
||||||
|
}
|
||||||
|
|||||||
@@ -165,6 +165,7 @@ services:
|
|||||||
command:
|
command:
|
||||||
- "server"
|
- "server"
|
||||||
- "-dir=/data"
|
- "-dir=/data"
|
||||||
|
- "-volume.max=10"
|
||||||
- "-s3"
|
- "-s3"
|
||||||
- "-s3.port=9000"
|
- "-s3.port=9000"
|
||||||
- "-s3.iam=false"
|
- "-s3.iam=false"
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ ALTER TABLE attachments
|
|||||||
ADD COLUMN job_id uuid UNIQUE,
|
ADD COLUMN job_id uuid UNIQUE,
|
||||||
ADD COLUMN pipeline_version int NOT NULL DEFAULT 1 CHECK (pipeline_version > 0),
|
ADD COLUMN pipeline_version int NOT NULL DEFAULT 1 CHECK (pipeline_version > 0),
|
||||||
ADD COLUMN attempts int NOT NULL DEFAULT 0 CHECK (attempts >= 0),
|
ADD COLUMN attempts int NOT NULL DEFAULT 0 CHECK (attempts >= 0),
|
||||||
|
ADD COLUMN retry_base int NOT NULL DEFAULT 0 CHECK (retry_base >= 0 AND retry_base <= attempts),
|
||||||
ADD COLUMN width int CHECK (width > 0),
|
ADD COLUMN width int CHECK (width > 0),
|
||||||
ADD COLUMN height int CHECK (height > 0),
|
ADD COLUMN height int CHECK (height > 0),
|
||||||
ADD COLUMN lease_until timestamptz;
|
ADD COLUMN lease_until timestamptz;
|
||||||
@@ -34,12 +35,23 @@ CREATE TABLE outbox (
|
|||||||
created_at timestamptz NOT NULL DEFAULT now(),
|
created_at timestamptz NOT NULL DEFAULT now(),
|
||||||
available_at timestamptz NOT NULL DEFAULT now(),
|
available_at timestamptz NOT NULL DEFAULT now(),
|
||||||
published_at timestamptz,
|
published_at timestamptz,
|
||||||
UNIQUE (job_id, attempt)
|
UNIQUE (job_id, pipeline_version, attempt)
|
||||||
);
|
);
|
||||||
|
|
||||||
CREATE INDEX idx_outbox_pending ON outbox (available_at, id) WHERE published_at IS NULL;
|
CREATE INDEX idx_outbox_pending ON outbox (available_at, id) WHERE published_at IS NULL;
|
||||||
|
|
||||||
|
CREATE TABLE attachment_replays (
|
||||||
|
attachment_id uuid NOT NULL REFERENCES attachments (id) ON DELETE CASCADE,
|
||||||
|
attempt int NOT NULL CHECK (attempt > 0),
|
||||||
|
previous_error_code text,
|
||||||
|
operator text NOT NULL,
|
||||||
|
reason text NOT NULL,
|
||||||
|
created_at timestamptz NOT NULL DEFAULT now(),
|
||||||
|
PRIMARY KEY (attachment_id, attempt)
|
||||||
|
);
|
||||||
|
|
||||||
-- +goose Down
|
-- +goose Down
|
||||||
|
DROP TABLE attachment_replays;
|
||||||
DROP TABLE outbox;
|
DROP TABLE outbox;
|
||||||
DROP TABLE attachment_variants;
|
DROP TABLE attachment_variants;
|
||||||
DROP TYPE attachment_variant_name;
|
DROP TYPE attachment_variant_name;
|
||||||
@@ -48,6 +60,7 @@ ALTER TABLE attachments
|
|||||||
DROP COLUMN height,
|
DROP COLUMN height,
|
||||||
DROP COLUMN width,
|
DROP COLUMN width,
|
||||||
DROP COLUMN lease_until,
|
DROP COLUMN lease_until,
|
||||||
|
DROP COLUMN retry_base,
|
||||||
DROP COLUMN attempts,
|
DROP COLUMN attempts,
|
||||||
DROP COLUMN pipeline_version,
|
DROP COLUMN pipeline_version,
|
||||||
DROP COLUMN job_id,
|
DROP COLUMN job_id,
|
||||||
|
|||||||
@@ -0,0 +1,14 @@
|
|||||||
|
-- name: CreateAttachmentReplay :exec
|
||||||
|
INSERT INTO attachment_replays (
|
||||||
|
attachment_id,
|
||||||
|
attempt,
|
||||||
|
previous_error_code,
|
||||||
|
operator,
|
||||||
|
reason
|
||||||
|
) VALUES (
|
||||||
|
sqlc.arg(attachment_id),
|
||||||
|
sqlc.arg(attempt),
|
||||||
|
sqlc.narg(previous_error_code),
|
||||||
|
sqlc.arg(operator),
|
||||||
|
sqlc.arg(reason)
|
||||||
|
);
|
||||||
@@ -77,6 +77,13 @@ ORDER BY message_id, position;
|
|||||||
SELECT id, s3_key, staging_key, status, size_bytes, updated_at
|
SELECT id, s3_key, staging_key, status, size_bytes, updated_at
|
||||||
FROM attachments;
|
FROM attachments;
|
||||||
|
|
||||||
|
-- name: ListFailedAttachments :many
|
||||||
|
SELECT id, job_id, error_code, attempts, updated_at
|
||||||
|
FROM attachments
|
||||||
|
WHERE status = 'failed'
|
||||||
|
ORDER BY updated_at, id
|
||||||
|
LIMIT sqlc.arg(batch_size)::int;
|
||||||
|
|
||||||
-- name: LockAttachmentJob :one
|
-- name: LockAttachmentJob :one
|
||||||
SELECT * FROM attachments
|
SELECT * FROM attachments
|
||||||
WHERE id = sqlc.arg(id)::uuid
|
WHERE id = sqlc.arg(id)::uuid
|
||||||
@@ -95,6 +102,25 @@ ORDER BY lease_until, id
|
|||||||
LIMIT sqlc.arg(batch_size)::int
|
LIMIT sqlc.arg(batch_size)::int
|
||||||
FOR UPDATE SKIP LOCKED;
|
FOR UPDATE SKIP LOCKED;
|
||||||
|
|
||||||
|
-- name: LockFailedAttachmentForReplay :one
|
||||||
|
SELECT * FROM attachments
|
||||||
|
WHERE id = sqlc.arg(id)::uuid
|
||||||
|
AND status = 'failed'
|
||||||
|
AND staging_key IS NOT NULL
|
||||||
|
AND NOT EXISTS (
|
||||||
|
SELECT 1 FROM attachment_variants
|
||||||
|
WHERE attachment_id = attachments.id
|
||||||
|
)
|
||||||
|
FOR UPDATE;
|
||||||
|
|
||||||
|
-- name: LockAttachmentForUpgrade :one
|
||||||
|
SELECT * FROM attachments
|
||||||
|
WHERE id = sqlc.arg(id)::uuid
|
||||||
|
AND pipeline_version = 1
|
||||||
|
AND status IN ('queued', 'processing')
|
||||||
|
AND staging_key IS NOT NULL
|
||||||
|
FOR UPDATE;
|
||||||
|
|
||||||
-- name: ClearAttachmentStagingKey :exec
|
-- name: ClearAttachmentStagingKey :exec
|
||||||
UPDATE attachments
|
UPDATE attachments
|
||||||
SET staging_key = NULL
|
SET staging_key = NULL
|
||||||
@@ -142,6 +168,34 @@ WHERE id = sqlc.arg(id)::uuid
|
|||||||
AND attempts = sqlc.arg(attempt)::int
|
AND attempts = sqlc.arg(attempt)::int
|
||||||
AND lease_until > now();
|
AND lease_until > now();
|
||||||
|
|
||||||
|
-- name: UpgradeAttachmentPipeline :execrows
|
||||||
|
UPDATE attachments
|
||||||
|
SET pipeline_version = 2,
|
||||||
|
status = 'queued',
|
||||||
|
retry_base = attempts,
|
||||||
|
error_code = NULL,
|
||||||
|
lease_until = NULL,
|
||||||
|
updated_at = now()
|
||||||
|
WHERE id = sqlc.arg(id)::uuid
|
||||||
|
AND pipeline_version = 1
|
||||||
|
AND status IN ('queued', 'processing')
|
||||||
|
AND staging_key IS NOT NULL;
|
||||||
|
|
||||||
|
-- name: ReplayAttachmentJob :execrows
|
||||||
|
UPDATE attachments
|
||||||
|
SET status = 'queued',
|
||||||
|
retry_base = attempts,
|
||||||
|
error_code = NULL,
|
||||||
|
lease_until = NULL,
|
||||||
|
updated_at = now()
|
||||||
|
WHERE id = sqlc.arg(id)::uuid
|
||||||
|
AND status = 'failed'
|
||||||
|
AND staging_key IS NOT NULL
|
||||||
|
AND NOT EXISTS (
|
||||||
|
SELECT 1 FROM attachment_variants
|
||||||
|
WHERE attachment_id = attachments.id
|
||||||
|
);
|
||||||
|
|
||||||
-- name: FailAttachmentJob :execrows
|
-- name: FailAttachmentJob :execrows
|
||||||
UPDATE attachments
|
UPDATE attachments
|
||||||
SET status = 'failed',
|
SET status = 'failed',
|
||||||
|
|||||||
@@ -0,0 +1,68 @@
|
|||||||
|
> make contract-go
|
||||||
|
go test -tags=contract ./student-tests/... -v -args -base-url=http://localhost:8080
|
||||||
|
=== RUN TestAttachmentJPEG
|
||||||
|
--- PASS: TestAttachmentJPEG (0.42s)
|
||||||
|
=== RUN TestAttachmentTooManyPixels
|
||||||
|
--- PASS: TestAttachmentTooManyPixels (2.12s)
|
||||||
|
=== RUN TestAttachmentUnsafeFilename
|
||||||
|
--- PASS: TestAttachmentUnsafeFilename (0.14s)
|
||||||
|
=== RUN TestAttachmentTooLarge
|
||||||
|
--- PASS: TestAttachmentTooLarge (0.22s)
|
||||||
|
=== RUN TestAttachmentCorruptedImage
|
||||||
|
--- PASS: TestAttachmentCorruptedImage (0.22s)
|
||||||
|
=== RUN TestAttachmentMimeSubstitution
|
||||||
|
--- PASS: TestAttachmentMimeSubstitution (0.16s)
|
||||||
|
=== RUN TestAttachmentForeignID
|
||||||
|
--- PASS: TestAttachmentForeignID (0.22s)
|
||||||
|
=== RUN TestAttachmentFromAnotherChat
|
||||||
|
--- PASS: TestAttachmentFromAnotherChat (1.02s)
|
||||||
|
=== RUN TestCreateChatRollback
|
||||||
|
--- PASS: TestCreateChatRollback (0.16s)
|
||||||
|
=== RUN TestInvalidJSON
|
||||||
|
--- PASS: TestInvalidJSON (0.00s)
|
||||||
|
=== RUN TestForeignChat
|
||||||
|
--- PASS: TestForeignChat (0.60s)
|
||||||
|
=== RUN TestEmptyMessage
|
||||||
|
--- PASS: TestEmptyMessage (0.20s)
|
||||||
|
=== RUN TestDuplicateUsername
|
||||||
|
--- PASS: TestDuplicateUsername (0.24s)
|
||||||
|
=== RUN TestPagination
|
||||||
|
--- PASS: TestPagination (0.31s)
|
||||||
|
=== RUN TestThumbnail
|
||||||
|
=== RUN TestThumbnail/landscape
|
||||||
|
=== RUN TestThumbnail/portrait
|
||||||
|
=== RUN TestThumbnail/small
|
||||||
|
=== RUN TestThumbnail/thin
|
||||||
|
--- PASS: TestThumbnail (2.18s)
|
||||||
|
--- PASS: TestThumbnail/landscape (0.35s)
|
||||||
|
--- PASS: TestThumbnail/portrait (0.62s)
|
||||||
|
--- PASS: TestThumbnail/small (0.40s)
|
||||||
|
--- PASS: TestThumbnail/thin (0.82s)
|
||||||
|
=== RUN TestVariantsEXIF
|
||||||
|
=== RUN TestVariantsEXIF/thumbnail
|
||||||
|
=== RUN TestVariantsEXIF/optimized
|
||||||
|
--- PASS: TestVariantsEXIF (1.19s)
|
||||||
|
--- PASS: TestVariantsEXIF/thumbnail (0.80s)
|
||||||
|
--- PASS: TestVariantsEXIF/optimized (0.39s)
|
||||||
|
=== RUN TestCrop
|
||||||
|
=== RUN TestCrop/landscape
|
||||||
|
=== RUN TestCrop/portrait
|
||||||
|
=== RUN TestCrop/small
|
||||||
|
--- PASS: TestCrop (1.61s)
|
||||||
|
--- PASS: TestCrop/landscape (0.62s)
|
||||||
|
--- PASS: TestCrop/portrait (0.39s)
|
||||||
|
--- PASS: TestCrop/small (0.60s)
|
||||||
|
=== RUN TestOptimized
|
||||||
|
=== RUN TestOptimized/landscape
|
||||||
|
=== RUN TestOptimized/portrait
|
||||||
|
=== RUN TestOptimized/small
|
||||||
|
--- PASS: TestOptimized (2.50s)
|
||||||
|
--- PASS: TestOptimized/landscape (0.84s)
|
||||||
|
--- PASS: TestOptimized/portrait (1.06s)
|
||||||
|
--- PASS: TestOptimized/small (0.59s)
|
||||||
|
=== RUN TestLoginWrongPassword
|
||||||
|
--- PASS: TestLoginWrongPassword (0.22s)
|
||||||
|
=== RUN TestLogout
|
||||||
|
--- PASS: TestLogout (0.18s)
|
||||||
|
PASS
|
||||||
|
ok mtusi2026-messenger/student-tests 13.930s
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
Локальная проверка ветки solution/bpi2303-belousov
|
||||||
|
|
||||||
|
make check
|
||||||
|
PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
|
||||||
|
|
||||||
|
make validate
|
||||||
|
PASS: full OpenAPI 3.1 and JSON Schema validation; application NOT tested.
|
||||||
|
|
||||||
|
make test
|
||||||
|
PASS: lab5 public API scenario; infrastructure and grading evidence remain separate.
|
||||||
|
|
||||||
|
make contract-go
|
||||||
|
PASS: все contract/student-tests, включая MIME/лимиты/доступ, thumbnail, crop, optimized WebP и EXIF.
|
||||||
|
|
||||||
|
make worker-go
|
||||||
|
PASS: persistence and duplicate, retry_exhausted, processing timeout, replay, outbox recovery, lease recovery.
|
||||||
|
|
||||||
|
make pipeline-go
|
||||||
|
PASS: stale v1 after v2, reorder and duplicate delivery, crash before result PUT with lease recovery.
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
> make test
|
||||||
|
python3 tests/smoke.py --base-url "http://localhost:8080"
|
||||||
|
PASS: lab5 public API scenario; infrastructure and grading evidence remain separate.
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
> make pipeline-go
|
||||||
|
go test -count=1 -tags=nodynamic,pipeline ./student-tests/... -v -args -base-url=http://localhost:8080
|
||||||
|
=== RUN TestPipelineStaleProcessing
|
||||||
|
pipeline_fault_test.go:174: PASS attachment=01a1e881-531b-7c12-8bcc-1bb759d11d06: held v1 PUT; v2 ready; late v1 wrote S3 but could not replace v2; stale redelivery acknowledged
|
||||||
|
--- PASS: TestPipelineStaleProcessing (12.67s)
|
||||||
|
=== RUN TestPipelineReorderAndDuplicate
|
||||||
|
pipeline_fault_test.go:245: PASS attachment=01a1e881-8af0-70c3-a95d-6fde917efa7f: v2 completed before v1 delivery; stale v1 and duplicate v2 acknowledged without changes
|
||||||
|
--- PASS: TestPipelineReorderAndDuplicate (41.43s)
|
||||||
|
=== RUN TestPipelineCrashBeforeWrite
|
||||||
|
pipeline_fault_test.go:301: PASS attachment=01a1e882-22d9-749f-ad66-36ecf038165b: SIGKILL before first result PUT; natural lease recovery; same job ready on v2 attempt2
|
||||||
|
--- PASS: TestPipelineCrashBeforeWrite (26.05s)
|
||||||
|
PASS
|
||||||
|
ok mtusi2026-messenger/student-tests 80.150s
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
> docker compose ps
|
||||||
|
NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS
|
||||||
|
mtusi2026lab5-api-1 mtusi-messenger:lab5 "/app/server" api 35 minutes ago Up 35 minutes (healthy) 8080/tcp
|
||||||
|
mtusi2026lab5-api-2 mtusi-messenger:lab5 "/app/server" api 35 minutes ago Up 35 minutes (healthy) 8080/tcp
|
||||||
|
mtusi2026lab5-load_balancer-1 nginx:1.31.7-alpine3.24 "/docker-entrypoint.…" load_balancer 35 minutes ago Up 35 minutes 127.0.0.1:8080->8080/tcp
|
||||||
|
mtusi2026lab5-postgres-1 postgres:18.6 "docker-entrypoint.s…" postgres 35 minutes ago Up 35 minutes (healthy) 127.0.0.1:5432->5432/tcp
|
||||||
|
mtusi2026lab5-rabbitmq-1 rabbitmq:4.2.9-alpine "/bin/sh -ec 'RABBIT…" rabbitmq 35 minutes ago Up 35 minutes (healthy) 4369/tcp, 5671-5672/tcp, 15691-15692/tcp, 25672/tcp
|
||||||
|
mtusi2026lab5-redis-1 redis:8.8.3-alpine3.23 "docker-entrypoint.s…" redis 35 minutes ago Up 35 minutes (healthy) 6379/tcp
|
||||||
|
mtusi2026lab5-s3-1 chrislusf/seaweedfs:4.51 "/entrypoint.sh serv…" s3 35 minutes ago Up 35 minutes (healthy) 7333/tcp, 8080/tcp, 8333/tcp, 8888/tcp, 9333/tcp, 18080/tcp, 18888/tcp, 19333/tcp
|
||||||
|
mtusi2026lab5-worker-1 mtusi-messenger-worker:lab5 "/app/worker" worker 35 minutes ago Up 35 minutes
|
||||||
|
> make worker-go
|
||||||
|
go test -count=1 -tags=worker ./student-tests/... -v -args -base-url=http://localhost:8080
|
||||||
|
=== RUN TestWorkerPersistenceAndDuplicate
|
||||||
|
worker_test.go:116: PASS attachment=01a1e86c-a8f6-7816-82aa-f21d58b7d859: queued survives API/broker restart; ready; duplicate acknowledged with unchanged result
|
||||||
|
--- PASS: TestWorkerPersistenceAndDuplicate (33.88s)
|
||||||
|
=== RUN TestWorkerRetryExhausted
|
||||||
|
worker_test.go:161: PASS attachment=01a1e86d-245d-78aa-b370-288b7b9aae01: 5 attempts, failed/retry_exhausted, content/link rejected
|
||||||
|
--- PASS: TestWorkerRetryExhausted (39.01s)
|
||||||
|
=== RUN TestWorkerProcessingTimeout
|
||||||
|
--- PASS: TestWorkerProcessingTimeout (10.11s)
|
||||||
|
=== RUN TestWorkerReplay
|
||||||
|
--- PASS: TestWorkerReplay (15.20s)
|
||||||
|
=== RUN TestWorkerOutboxRecovery
|
||||||
|
worker_test.go:342: PASS attachment=01a1e86e-2d67-70db-98e7-ea3f137bb7c1: commit, API SIGKILL before publication, automatic outbox recovery, same job ready
|
||||||
|
--- PASS: TestWorkerOutboxRecovery (33.15s)
|
||||||
|
=== RUN TestWorkerLeaseRecovery
|
||||||
|
worker_test.go:425: PASS attachment=01a1e86e-b2b4-7d23-a1cb-0ba40351a02f: SIGKILL after S3 writes, expired lease recovered, same job ready on attempt 2
|
||||||
|
--- PASS: TestWorkerLeaseRecovery (26.54s)
|
||||||
|
PASS
|
||||||
|
ok mtusi2026-messenger/student-tests 157.912s
|
||||||
|
> docker compose ps
|
||||||
|
NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS
|
||||||
|
mtusi2026lab5-api-1 mtusi-messenger:lab5 "/app/server" api 38 minutes ago Up About a minute (healthy) 8080/tcp
|
||||||
|
mtusi2026lab5-api-2 mtusi-messenger:lab5 "/app/server" api 38 minutes ago Up About a minute (healthy) 8080/tcp
|
||||||
|
mtusi2026lab5-load_balancer-1 nginx:1.31.7-alpine3.24 "/docker-entrypoint.…" load_balancer 38 minutes ago Up 38 minutes 127.0.0.1:8080->8080/tcp
|
||||||
|
mtusi2026lab5-postgres-1 postgres:18.6 "docker-entrypoint.s…" postgres 39 minutes ago Up 38 minutes (healthy) 127.0.0.1:5432->5432/tcp
|
||||||
|
mtusi2026lab5-rabbitmq-1 rabbitmq:4.2.9-alpine "/bin/sh -ec 'RABBIT…" rabbitmq 2 minutes ago Up About a minute (healthy) 4369/tcp, 5671-5672/tcp, 15691-15692/tcp, 25672/tcp
|
||||||
|
mtusi2026lab5-redis-1 redis:8.8.3-alpine3.23 "docker-entrypoint.s…" redis 39 minutes ago Up 38 minutes (healthy) 6379/tcp
|
||||||
|
mtusi2026lab5-s3-1 chrislusf/seaweedfs:4.51 "/entrypoint.sh serv…" s3 38 minutes ago Up 38 minutes (healthy) 7333/tcp, 8080/tcp, 8333/tcp, 8888/tcp, 9333/tcp, 18080/tcp, 18888/tcp, 19333/tcp
|
||||||
|
mtusi2026lab5-worker-1 mtusi-messenger-worker:lab5 "/app/worker" worker 38 minutes ago Up 41 seconds
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
// Code generated by sqlc. DO NOT EDIT.
|
||||||
|
// versions:
|
||||||
|
// sqlc v1.31.1
|
||||||
|
// source: attachment_replays.sql
|
||||||
|
|
||||||
|
package db
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
)
|
||||||
|
|
||||||
|
const createAttachmentReplay = `-- name: CreateAttachmentReplay :exec
|
||||||
|
INSERT INTO attachment_replays (
|
||||||
|
attachment_id,
|
||||||
|
attempt,
|
||||||
|
previous_error_code,
|
||||||
|
operator,
|
||||||
|
reason
|
||||||
|
) VALUES (
|
||||||
|
$1,
|
||||||
|
$2,
|
||||||
|
$3,
|
||||||
|
$4,
|
||||||
|
$5
|
||||||
|
)
|
||||||
|
`
|
||||||
|
|
||||||
|
type CreateAttachmentReplayParams struct {
|
||||||
|
AttachmentID uuid.UUID
|
||||||
|
Attempt int
|
||||||
|
PreviousErrorCode *string
|
||||||
|
Operator string
|
||||||
|
Reason string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (q *Queries) CreateAttachmentReplay(ctx context.Context, arg CreateAttachmentReplayParams) error {
|
||||||
|
_, err := q.db.Exec(ctx, createAttachmentReplay,
|
||||||
|
arg.AttachmentID,
|
||||||
|
arg.Attempt,
|
||||||
|
arg.PreviousErrorCode,
|
||||||
|
arg.Operator,
|
||||||
|
arg.Reason,
|
||||||
|
)
|
||||||
|
return err
|
||||||
|
}
|
||||||
@@ -23,7 +23,7 @@ WHERE id = $2::uuid
|
|||||||
AND pipeline_version = $4::int
|
AND pipeline_version = $4::int
|
||||||
AND status = 'queued'
|
AND status = 'queued'
|
||||||
AND attempts + 1 = $5::int
|
AND attempts + 1 = $5::int
|
||||||
RETURNING id, chat_id, owner_id, s3_key, filename, content_type, size_bytes, sha256, status, error_code, created_at, updated_at, staging_key, job_id, pipeline_version, attempts, width, height, lease_until
|
RETURNING id, chat_id, owner_id, s3_key, filename, content_type, size_bytes, sha256, status, error_code, created_at, updated_at, staging_key, job_id, pipeline_version, attempts, retry_base, width, height, lease_until
|
||||||
`
|
`
|
||||||
|
|
||||||
type ClaimAttachmentJobParams struct {
|
type ClaimAttachmentJobParams struct {
|
||||||
@@ -60,6 +60,7 @@ func (q *Queries) ClaimAttachmentJob(ctx context.Context, arg ClaimAttachmentJob
|
|||||||
&i.JobID,
|
&i.JobID,
|
||||||
&i.PipelineVersion,
|
&i.PipelineVersion,
|
||||||
&i.Attempts,
|
&i.Attempts,
|
||||||
|
&i.RetryBase,
|
||||||
&i.Width,
|
&i.Width,
|
||||||
&i.Height,
|
&i.Height,
|
||||||
&i.LeaseUntil,
|
&i.LeaseUntil,
|
||||||
@@ -138,7 +139,7 @@ WHERE EXISTS (
|
|||||||
WHERE chat_id = $2
|
WHERE chat_id = $2
|
||||||
AND user_id = $3
|
AND user_id = $3
|
||||||
)
|
)
|
||||||
RETURNING id, chat_id, owner_id, s3_key, filename, content_type, size_bytes, sha256, status, error_code, created_at, updated_at, staging_key, job_id, pipeline_version, attempts, width, height, lease_until
|
RETURNING id, chat_id, owner_id, s3_key, filename, content_type, size_bytes, sha256, status, error_code, created_at, updated_at, staging_key, job_id, pipeline_version, attempts, retry_base, width, height, lease_until
|
||||||
`
|
`
|
||||||
|
|
||||||
type CreateAttachmentParams struct {
|
type CreateAttachmentParams struct {
|
||||||
@@ -191,6 +192,7 @@ func (q *Queries) CreateAttachment(ctx context.Context, arg CreateAttachmentPara
|
|||||||
&i.JobID,
|
&i.JobID,
|
||||||
&i.PipelineVersion,
|
&i.PipelineVersion,
|
||||||
&i.Attempts,
|
&i.Attempts,
|
||||||
|
&i.RetryBase,
|
||||||
&i.Width,
|
&i.Width,
|
||||||
&i.Height,
|
&i.Height,
|
||||||
&i.LeaseUntil,
|
&i.LeaseUntil,
|
||||||
@@ -267,7 +269,7 @@ func (q *Queries) FailExpiredAttachmentJob(ctx context.Context, id uuid.UUID) (i
|
|||||||
}
|
}
|
||||||
|
|
||||||
const getAttachmentByID = `-- name: GetAttachmentByID :one
|
const getAttachmentByID = `-- name: GetAttachmentByID :one
|
||||||
SELECT id, chat_id, owner_id, s3_key, filename, content_type, size_bytes, sha256, status, error_code, created_at, updated_at, staging_key, job_id, pipeline_version, attempts, width, height, lease_until FROM attachments
|
SELECT id, chat_id, owner_id, s3_key, filename, content_type, size_bytes, sha256, status, error_code, created_at, updated_at, staging_key, job_id, pipeline_version, attempts, retry_base, width, height, lease_until FROM attachments
|
||||||
WHERE id = $1::uuid
|
WHERE id = $1::uuid
|
||||||
`
|
`
|
||||||
|
|
||||||
@@ -291,6 +293,7 @@ func (q *Queries) GetAttachmentByID(ctx context.Context, dollar_1 uuid.UUID) (At
|
|||||||
&i.JobID,
|
&i.JobID,
|
||||||
&i.PipelineVersion,
|
&i.PipelineVersion,
|
||||||
&i.Attempts,
|
&i.Attempts,
|
||||||
|
&i.RetryBase,
|
||||||
&i.Width,
|
&i.Width,
|
||||||
&i.Height,
|
&i.Height,
|
||||||
&i.LeaseUntil,
|
&i.LeaseUntil,
|
||||||
@@ -371,6 +374,48 @@ func (q *Queries) ListAttachmentsForReconcile(ctx context.Context) ([]ListAttach
|
|||||||
return items, nil
|
return items, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const listFailedAttachments = `-- name: ListFailedAttachments :many
|
||||||
|
SELECT id, job_id, error_code, attempts, updated_at
|
||||||
|
FROM attachments
|
||||||
|
WHERE status = 'failed'
|
||||||
|
ORDER BY updated_at, id
|
||||||
|
LIMIT $1::int
|
||||||
|
`
|
||||||
|
|
||||||
|
type ListFailedAttachmentsRow struct {
|
||||||
|
ID uuid.UUID
|
||||||
|
JobID *uuid.UUID
|
||||||
|
ErrorCode *string
|
||||||
|
Attempts int
|
||||||
|
UpdatedAt time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
func (q *Queries) ListFailedAttachments(ctx context.Context, batchSize int) ([]ListFailedAttachmentsRow, error) {
|
||||||
|
rows, err := q.db.Query(ctx, listFailedAttachments, batchSize)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
items := []ListFailedAttachmentsRow{}
|
||||||
|
for rows.Next() {
|
||||||
|
var i ListFailedAttachmentsRow
|
||||||
|
if err := rows.Scan(
|
||||||
|
&i.ID,
|
||||||
|
&i.JobID,
|
||||||
|
&i.ErrorCode,
|
||||||
|
&i.Attempts,
|
||||||
|
&i.UpdatedAt,
|
||||||
|
); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
items = append(items, i)
|
||||||
|
}
|
||||||
|
if err := rows.Err(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return items, nil
|
||||||
|
}
|
||||||
|
|
||||||
const listMessageAttachmentIDs = `-- name: ListMessageAttachmentIDs :many
|
const listMessageAttachmentIDs = `-- name: ListMessageAttachmentIDs :many
|
||||||
SELECT attachment_id
|
SELECT attachment_id
|
||||||
FROM message_attachments
|
FROM message_attachments
|
||||||
@@ -431,7 +476,7 @@ func (q *Queries) ListMessageAttachmentsByMessageIDs(ctx context.Context, messag
|
|||||||
}
|
}
|
||||||
|
|
||||||
const lockAttachmentByStagingKey = `-- name: LockAttachmentByStagingKey :one
|
const lockAttachmentByStagingKey = `-- name: LockAttachmentByStagingKey :one
|
||||||
SELECT id, chat_id, owner_id, s3_key, filename, content_type, size_bytes, sha256, status, error_code, created_at, updated_at, staging_key, job_id, pipeline_version, attempts, width, height, lease_until FROM attachments
|
SELECT id, chat_id, owner_id, s3_key, filename, content_type, size_bytes, sha256, status, error_code, created_at, updated_at, staging_key, job_id, pipeline_version, attempts, retry_base, width, height, lease_until FROM attachments
|
||||||
WHERE staging_key = $1::text
|
WHERE staging_key = $1::text
|
||||||
FOR UPDATE
|
FOR UPDATE
|
||||||
`
|
`
|
||||||
@@ -456,6 +501,44 @@ func (q *Queries) LockAttachmentByStagingKey(ctx context.Context, stagingKey str
|
|||||||
&i.JobID,
|
&i.JobID,
|
||||||
&i.PipelineVersion,
|
&i.PipelineVersion,
|
||||||
&i.Attempts,
|
&i.Attempts,
|
||||||
|
&i.RetryBase,
|
||||||
|
&i.Width,
|
||||||
|
&i.Height,
|
||||||
|
&i.LeaseUntil,
|
||||||
|
)
|
||||||
|
return i, err
|
||||||
|
}
|
||||||
|
|
||||||
|
const lockAttachmentForUpgrade = `-- name: LockAttachmentForUpgrade :one
|
||||||
|
SELECT id, chat_id, owner_id, s3_key, filename, content_type, size_bytes, sha256, status, error_code, created_at, updated_at, staging_key, job_id, pipeline_version, attempts, retry_base, width, height, lease_until FROM attachments
|
||||||
|
WHERE id = $1::uuid
|
||||||
|
AND pipeline_version = 1
|
||||||
|
AND status IN ('queued', 'processing')
|
||||||
|
AND staging_key IS NOT NULL
|
||||||
|
FOR UPDATE
|
||||||
|
`
|
||||||
|
|
||||||
|
func (q *Queries) LockAttachmentForUpgrade(ctx context.Context, id uuid.UUID) (Attachment, error) {
|
||||||
|
row := q.db.QueryRow(ctx, lockAttachmentForUpgrade, id)
|
||||||
|
var i Attachment
|
||||||
|
err := row.Scan(
|
||||||
|
&i.ID,
|
||||||
|
&i.ChatID,
|
||||||
|
&i.OwnerID,
|
||||||
|
&i.S3Key,
|
||||||
|
&i.Filename,
|
||||||
|
&i.ContentType,
|
||||||
|
&i.SizeBytes,
|
||||||
|
&i.Sha256,
|
||||||
|
&i.Status,
|
||||||
|
&i.ErrorCode,
|
||||||
|
&i.CreatedAt,
|
||||||
|
&i.UpdatedAt,
|
||||||
|
&i.StagingKey,
|
||||||
|
&i.JobID,
|
||||||
|
&i.PipelineVersion,
|
||||||
|
&i.Attempts,
|
||||||
|
&i.RetryBase,
|
||||||
&i.Width,
|
&i.Width,
|
||||||
&i.Height,
|
&i.Height,
|
||||||
&i.LeaseUntil,
|
&i.LeaseUntil,
|
||||||
@@ -464,7 +547,7 @@ func (q *Queries) LockAttachmentByStagingKey(ctx context.Context, stagingKey str
|
|||||||
}
|
}
|
||||||
|
|
||||||
const lockAttachmentJob = `-- name: LockAttachmentJob :one
|
const lockAttachmentJob = `-- name: LockAttachmentJob :one
|
||||||
SELECT id, chat_id, owner_id, s3_key, filename, content_type, size_bytes, sha256, status, error_code, created_at, updated_at, staging_key, job_id, pipeline_version, attempts, width, height, lease_until FROM attachments
|
SELECT id, chat_id, owner_id, s3_key, filename, content_type, size_bytes, sha256, status, error_code, created_at, updated_at, staging_key, job_id, pipeline_version, attempts, retry_base, width, height, lease_until FROM attachments
|
||||||
WHERE id = $1::uuid
|
WHERE id = $1::uuid
|
||||||
AND status = 'processing'
|
AND status = 'processing'
|
||||||
AND job_id = $2::uuid
|
AND job_id = $2::uuid
|
||||||
@@ -506,6 +589,7 @@ func (q *Queries) LockAttachmentJob(ctx context.Context, arg LockAttachmentJobPa
|
|||||||
&i.JobID,
|
&i.JobID,
|
||||||
&i.PipelineVersion,
|
&i.PipelineVersion,
|
||||||
&i.Attempts,
|
&i.Attempts,
|
||||||
|
&i.RetryBase,
|
||||||
&i.Width,
|
&i.Width,
|
||||||
&i.Height,
|
&i.Height,
|
||||||
&i.LeaseUntil,
|
&i.LeaseUntil,
|
||||||
@@ -514,7 +598,7 @@ func (q *Queries) LockAttachmentJob(ctx context.Context, arg LockAttachmentJobPa
|
|||||||
}
|
}
|
||||||
|
|
||||||
const lockExpiredAttachmentJobs = `-- name: LockExpiredAttachmentJobs :many
|
const lockExpiredAttachmentJobs = `-- name: LockExpiredAttachmentJobs :many
|
||||||
SELECT id, chat_id, owner_id, s3_key, filename, content_type, size_bytes, sha256, status, error_code, created_at, updated_at, staging_key, job_id, pipeline_version, attempts, width, height, lease_until FROM attachments
|
SELECT id, chat_id, owner_id, s3_key, filename, content_type, size_bytes, sha256, status, error_code, created_at, updated_at, staging_key, job_id, pipeline_version, attempts, retry_base, width, height, lease_until FROM attachments
|
||||||
WHERE status = 'processing'
|
WHERE status = 'processing'
|
||||||
AND lease_until <= now()
|
AND lease_until <= now()
|
||||||
ORDER BY lease_until, id
|
ORDER BY lease_until, id
|
||||||
@@ -548,6 +632,7 @@ func (q *Queries) LockExpiredAttachmentJobs(ctx context.Context, batchSize int)
|
|||||||
&i.JobID,
|
&i.JobID,
|
||||||
&i.PipelineVersion,
|
&i.PipelineVersion,
|
||||||
&i.Attempts,
|
&i.Attempts,
|
||||||
|
&i.RetryBase,
|
||||||
&i.Width,
|
&i.Width,
|
||||||
&i.Height,
|
&i.Height,
|
||||||
&i.LeaseUntil,
|
&i.LeaseUntil,
|
||||||
@@ -562,6 +647,46 @@ func (q *Queries) LockExpiredAttachmentJobs(ctx context.Context, batchSize int)
|
|||||||
return items, nil
|
return items, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const lockFailedAttachmentForReplay = `-- name: LockFailedAttachmentForReplay :one
|
||||||
|
SELECT id, chat_id, owner_id, s3_key, filename, content_type, size_bytes, sha256, status, error_code, created_at, updated_at, staging_key, job_id, pipeline_version, attempts, retry_base, width, height, lease_until FROM attachments
|
||||||
|
WHERE id = $1::uuid
|
||||||
|
AND status = 'failed'
|
||||||
|
AND staging_key IS NOT NULL
|
||||||
|
AND NOT EXISTS (
|
||||||
|
SELECT 1 FROM attachment_variants
|
||||||
|
WHERE attachment_id = attachments.id
|
||||||
|
)
|
||||||
|
FOR UPDATE
|
||||||
|
`
|
||||||
|
|
||||||
|
func (q *Queries) LockFailedAttachmentForReplay(ctx context.Context, id uuid.UUID) (Attachment, error) {
|
||||||
|
row := q.db.QueryRow(ctx, lockFailedAttachmentForReplay, id)
|
||||||
|
var i Attachment
|
||||||
|
err := row.Scan(
|
||||||
|
&i.ID,
|
||||||
|
&i.ChatID,
|
||||||
|
&i.OwnerID,
|
||||||
|
&i.S3Key,
|
||||||
|
&i.Filename,
|
||||||
|
&i.ContentType,
|
||||||
|
&i.SizeBytes,
|
||||||
|
&i.Sha256,
|
||||||
|
&i.Status,
|
||||||
|
&i.ErrorCode,
|
||||||
|
&i.CreatedAt,
|
||||||
|
&i.UpdatedAt,
|
||||||
|
&i.StagingKey,
|
||||||
|
&i.JobID,
|
||||||
|
&i.PipelineVersion,
|
||||||
|
&i.Attempts,
|
||||||
|
&i.RetryBase,
|
||||||
|
&i.Width,
|
||||||
|
&i.Height,
|
||||||
|
&i.LeaseUntil,
|
||||||
|
)
|
||||||
|
return i, err
|
||||||
|
}
|
||||||
|
|
||||||
const markAttachmentFailedIfReady = `-- name: MarkAttachmentFailedIfReady :execrows
|
const markAttachmentFailedIfReady = `-- name: MarkAttachmentFailedIfReady :execrows
|
||||||
UPDATE attachments
|
UPDATE attachments
|
||||||
SET status = 'failed',
|
SET status = 'failed',
|
||||||
@@ -601,6 +726,30 @@ func (q *Queries) RecoverExpiredAttachmentJob(ctx context.Context, id uuid.UUID)
|
|||||||
return result.RowsAffected(), nil
|
return result.RowsAffected(), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const replayAttachmentJob = `-- name: ReplayAttachmentJob :execrows
|
||||||
|
UPDATE attachments
|
||||||
|
SET status = 'queued',
|
||||||
|
retry_base = attempts,
|
||||||
|
error_code = NULL,
|
||||||
|
lease_until = NULL,
|
||||||
|
updated_at = now()
|
||||||
|
WHERE id = $1::uuid
|
||||||
|
AND status = 'failed'
|
||||||
|
AND staging_key IS NOT NULL
|
||||||
|
AND NOT EXISTS (
|
||||||
|
SELECT 1 FROM attachment_variants
|
||||||
|
WHERE attachment_id = attachments.id
|
||||||
|
)
|
||||||
|
`
|
||||||
|
|
||||||
|
func (q *Queries) ReplayAttachmentJob(ctx context.Context, id uuid.UUID) (int64, error) {
|
||||||
|
result, err := q.db.Exec(ctx, replayAttachmentJob, id)
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
return result.RowsAffected(), nil
|
||||||
|
}
|
||||||
|
|
||||||
const retryAttachmentJob = `-- name: RetryAttachmentJob :execrows
|
const retryAttachmentJob = `-- name: RetryAttachmentJob :execrows
|
||||||
UPDATE attachments
|
UPDATE attachments
|
||||||
SET status = 'queued',
|
SET status = 'queued',
|
||||||
@@ -626,3 +775,25 @@ func (q *Queries) RetryAttachmentJob(ctx context.Context, arg RetryAttachmentJob
|
|||||||
}
|
}
|
||||||
return result.RowsAffected(), nil
|
return result.RowsAffected(), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const upgradeAttachmentPipeline = `-- name: UpgradeAttachmentPipeline :execrows
|
||||||
|
UPDATE attachments
|
||||||
|
SET pipeline_version = 2,
|
||||||
|
status = 'queued',
|
||||||
|
retry_base = attempts,
|
||||||
|
error_code = NULL,
|
||||||
|
lease_until = NULL,
|
||||||
|
updated_at = now()
|
||||||
|
WHERE id = $1::uuid
|
||||||
|
AND pipeline_version = 1
|
||||||
|
AND status IN ('queued', 'processing')
|
||||||
|
AND staging_key IS NOT NULL
|
||||||
|
`
|
||||||
|
|
||||||
|
func (q *Queries) UpgradeAttachmentPipeline(ctx context.Context, id uuid.UUID) (int64, error) {
|
||||||
|
result, err := q.db.Exec(ctx, upgradeAttachmentPipeline, id)
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
return result.RowsAffected(), nil
|
||||||
|
}
|
||||||
|
|||||||
@@ -158,11 +158,21 @@ type Attachment struct {
|
|||||||
JobID *uuid.UUID
|
JobID *uuid.UUID
|
||||||
PipelineVersion int
|
PipelineVersion int
|
||||||
Attempts int
|
Attempts int
|
||||||
|
RetryBase int
|
||||||
Width *int32
|
Width *int32
|
||||||
Height *int32
|
Height *int32
|
||||||
LeaseUntil *time.Time
|
LeaseUntil *time.Time
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type AttachmentReplay struct {
|
||||||
|
AttachmentID uuid.UUID
|
||||||
|
Attempt int
|
||||||
|
PreviousErrorCode *string
|
||||||
|
Operator string
|
||||||
|
Reason string
|
||||||
|
CreatedAt time.Time
|
||||||
|
}
|
||||||
|
|
||||||
type AttachmentVariant struct {
|
type AttachmentVariant struct {
|
||||||
AttachmentID uuid.UUID
|
AttachmentID uuid.UUID
|
||||||
PipelineVersion int
|
PipelineVersion int
|
||||||
|
|||||||
+42
-30
@@ -21,18 +21,21 @@ import (
|
|||||||
"mtusi2026-messenger/internal/db"
|
"mtusi2026-messenger/internal/db"
|
||||||
)
|
)
|
||||||
|
|
||||||
var errInvalidSource = errors.New("invalid source image")
|
var (
|
||||||
|
ErrInvalidSource = errors.New("invalid source image")
|
||||||
|
ErrUnsupportedPipelineVersion = errors.New("unsupported pipeline version")
|
||||||
|
)
|
||||||
|
|
||||||
type imageVariant struct {
|
type imageVariant struct {
|
||||||
name db.AttachmentVariantName
|
Name db.AttachmentVariantName
|
||||||
data []byte
|
Data []byte
|
||||||
contentType string
|
ContentType string
|
||||||
width, height int
|
Width, Height int
|
||||||
}
|
}
|
||||||
|
|
||||||
func (w *Worker) process(ctx context.Context, row db.Attachment) ([]db.CreateAttachmentVariantParams, error) {
|
func (w *Worker) process(ctx context.Context, row db.Attachment) ([]db.CreateAttachmentVariantParams, error) {
|
||||||
if row.StagingKey == nil {
|
if row.StagingKey == nil {
|
||||||
return nil, errInvalidSource
|
return nil, ErrInvalidSource
|
||||||
}
|
}
|
||||||
|
|
||||||
source, err := w.s3.Get(ctx, *row.StagingKey)
|
source, err := w.s3.Get(ctx, *row.StagingKey)
|
||||||
@@ -60,7 +63,7 @@ func (w *Worker) process(ctx context.Context, row db.Attachment) ([]db.CreateAtt
|
|||||||
|
|
||||||
if size != int64(row.SizeBytes) ||
|
if size != int64(row.SizeBytes) ||
|
||||||
hex.EncodeToString(hash.Sum(nil)) != row.Sha256 {
|
hex.EncodeToString(hash.Sum(nil)) != row.Sha256 {
|
||||||
return nil, errInvalidSource
|
return nil, ErrInvalidSource
|
||||||
}
|
}
|
||||||
|
|
||||||
if _, err := tmp.Seek(0, io.SeekStart); err != nil {
|
if _, err := tmp.Seek(0, io.SeekStart); err != nil {
|
||||||
@@ -78,7 +81,7 @@ func (w *Worker) process(ctx context.Context, row db.Attachment) ([]db.CreateAtt
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
images, err := imageVariants(tmp, w.maxPixels)
|
images, err := runImageProcess(ctx, tmp, w.maxPixels, row.PipelineVersion)
|
||||||
<-w.decodeSlot
|
<-w.decodeSlot
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -98,21 +101,21 @@ func (w *Worker) process(ctx context.Context, row db.Attachment) ([]db.CreateAtt
|
|||||||
|
|
||||||
variants := make([]db.CreateAttachmentVariantParams, 0, len(images))
|
variants := make([]db.CreateAttachmentVariantParams, 0, len(images))
|
||||||
for _, img := range images {
|
for _, img := range images {
|
||||||
key := "variants/" + row.ID.String() + "/v" + strconv.Itoa(row.PipelineVersion) + "/" + string(img.name)
|
key := "variants/" + row.ID.String() + "/v" + strconv.Itoa(row.PipelineVersion) + "/" + string(img.Name)
|
||||||
if err := w.s3.Put(ctx, key, bytes.NewReader(img.data), int64(len(img.data)), img.contentType); err != nil {
|
if err := w.s3.Put(ctx, key, bytes.NewReader(img.Data), int64(len(img.Data)), img.ContentType); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
sum := sha256.Sum256(img.data)
|
sum := sha256.Sum256(img.Data)
|
||||||
variants = append(variants, db.CreateAttachmentVariantParams{
|
variants = append(variants, db.CreateAttachmentVariantParams{
|
||||||
AttachmentID: row.ID,
|
AttachmentID: row.ID,
|
||||||
PipelineVersion: row.PipelineVersion,
|
PipelineVersion: row.PipelineVersion,
|
||||||
Variant: img.name,
|
Variant: img.Name,
|
||||||
S3Key: key,
|
S3Key: key,
|
||||||
ContentType: img.contentType,
|
ContentType: img.ContentType,
|
||||||
SizeBytes: len(img.data),
|
SizeBytes: len(img.Data),
|
||||||
Width: img.width,
|
Width: img.Width,
|
||||||
Height: img.height,
|
Height: img.Height,
|
||||||
Sha256: hex.EncodeToString(sum[:]),
|
Sha256: hex.EncodeToString(sum[:]),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -120,14 +123,23 @@ func (w *Worker) process(ctx context.Context, row db.Attachment) ([]db.CreateAtt
|
|||||||
return variants, nil
|
return variants, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func imageVariants(r io.ReadSeeker, maxPixels int) ([]imageVariant, error) {
|
func imageVariants(r io.ReadSeeker, maxPixels, pipelineVersion int) ([]imageVariant, error) {
|
||||||
|
quality := 80
|
||||||
|
switch pipelineVersion {
|
||||||
|
case 1:
|
||||||
|
case 2:
|
||||||
|
quality = 75
|
||||||
|
default:
|
||||||
|
return nil, ErrUnsupportedPipelineVersion
|
||||||
|
}
|
||||||
|
|
||||||
cfg, format, err := image.DecodeConfig(r)
|
cfg, format, err := image.DecodeConfig(r)
|
||||||
if err != nil ||
|
if err != nil ||
|
||||||
(format != "png" && format != "jpeg") ||
|
(format != "png" && format != "jpeg") ||
|
||||||
cfg.Width <= 0 ||
|
cfg.Width <= 0 ||
|
||||||
cfg.Height <= 0 ||
|
cfg.Height <= 0 ||
|
||||||
cfg.Width > maxPixels/cfg.Height {
|
cfg.Width > maxPixels/cfg.Height {
|
||||||
return nil, errInvalidSource
|
return nil, ErrInvalidSource
|
||||||
}
|
}
|
||||||
|
|
||||||
if _, err := r.Seek(0, io.SeekStart); err != nil {
|
if _, err := r.Seek(0, io.SeekStart); err != nil {
|
||||||
@@ -136,7 +148,7 @@ func imageVariants(r io.ReadSeeker, maxPixels int) ([]imageVariant, error) {
|
|||||||
|
|
||||||
src, err := imaging.Decode(r, imaging.AutoOrientation(true))
|
src, err := imaging.Decode(r, imaging.AutoOrientation(true))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errInvalidSource
|
return nil, ErrInvalidSource
|
||||||
}
|
}
|
||||||
|
|
||||||
variants := make([]imageVariant, 0, 3)
|
variants := make([]imageVariant, 0, 3)
|
||||||
@@ -152,9 +164,9 @@ func imageVariants(r io.ReadSeeker, maxPixels int) ([]imageVariant, error) {
|
|||||||
contentType := "image/jpeg"
|
contentType := "image/jpeg"
|
||||||
if item.name == db.AttachmentVariantNameOptimized {
|
if item.name == db.AttachmentVariantNameOptimized {
|
||||||
contentType = "image/webp"
|
contentType = "image/webp"
|
||||||
data, err = encodeWebP(item.image)
|
data, err = encodeWebP(item.image, quality)
|
||||||
} else {
|
} else {
|
||||||
data, err = encodeJPEG(item.image)
|
data, err = encodeJPEG(item.image, 85)
|
||||||
}
|
}
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -162,11 +174,11 @@ func imageVariants(r io.ReadSeeker, maxPixels int) ([]imageVariant, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
variants = append(variants, imageVariant{
|
variants = append(variants, imageVariant{
|
||||||
name: item.name,
|
Name: item.name,
|
||||||
contentType: contentType,
|
ContentType: contentType,
|
||||||
data: data,
|
Data: data,
|
||||||
width: item.image.Bounds().Dx(),
|
Width: item.image.Bounds().Dx(),
|
||||||
height: item.image.Bounds().Dy(),
|
Height: item.image.Bounds().Dy(),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -190,22 +202,22 @@ func fitImage(src image.Image, maxSize int) image.Image {
|
|||||||
return src
|
return src
|
||||||
}
|
}
|
||||||
|
|
||||||
func encodeJPEG(src image.Image) ([]byte, error) {
|
func encodeJPEG(src image.Image, quality int) ([]byte, error) {
|
||||||
dst := image.NewRGBA(image.Rect(0, 0, src.Bounds().Dx(), src.Bounds().Dy()))
|
dst := image.NewRGBA(image.Rect(0, 0, src.Bounds().Dx(), src.Bounds().Dy()))
|
||||||
draw.Draw(dst, dst.Bounds(), image.NewUniform(color.White), image.Point{}, draw.Src)
|
draw.Draw(dst, dst.Bounds(), image.NewUniform(color.White), image.Point{}, draw.Src)
|
||||||
draw.Draw(dst, dst.Bounds(), src, src.Bounds().Min, draw.Over)
|
draw.Draw(dst, dst.Bounds(), src, src.Bounds().Min, draw.Over)
|
||||||
|
|
||||||
var out bytes.Buffer
|
var out bytes.Buffer
|
||||||
if err := jpeg.Encode(&out, dst, &jpeg.Options{Quality: 85}); err != nil {
|
if err := jpeg.Encode(&out, dst, &jpeg.Options{Quality: quality}); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
return out.Bytes(), nil
|
return out.Bytes(), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func encodeWebP(src image.Image) ([]byte, error) {
|
func encodeWebP(src image.Image, quality int) ([]byte, error) {
|
||||||
var out bytes.Buffer
|
var out bytes.Buffer
|
||||||
if err := webp.Encode(&out, src, webp.Options{Quality: 80, Method: 4}); err != nil {
|
if err := webp.Encode(&out, src, webp.Options{Quality: quality, Method: 4}); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,53 @@
|
|||||||
|
package worker
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"encoding/gob"
|
||||||
|
"errors"
|
||||||
|
"os"
|
||||||
|
"os/exec"
|
||||||
|
"strconv"
|
||||||
|
)
|
||||||
|
|
||||||
|
func ProcessImage(maxPixels, pipelineVersion int) error {
|
||||||
|
variants, err := imageVariants(os.Stdin, maxPixels, pipelineVersion)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return gob.NewEncoder(os.Stdout).Encode(variants)
|
||||||
|
}
|
||||||
|
|
||||||
|
func runImageProcess(ctx context.Context, source *os.File, maxPixels, pipelineVersion int) ([]imageVariant, error) {
|
||||||
|
executable, err := os.Executable()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
cmd := exec.CommandContext(ctx, executable,
|
||||||
|
"-process-image", strconv.Itoa(maxPixels),
|
||||||
|
"-pipeline-version", strconv.Itoa(pipelineVersion),
|
||||||
|
)
|
||||||
|
cmd.Stdin = source
|
||||||
|
data, err := cmd.Output()
|
||||||
|
if ctx.Err() != nil {
|
||||||
|
return nil, ctx.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
var exitErr *exec.ExitError
|
||||||
|
if errors.As(err, &exitErr) && exitErr.ExitCode() == 2 {
|
||||||
|
return nil, ErrInvalidSource
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
var variants []imageVariant
|
||||||
|
if err := gob.NewDecoder(bytes.NewReader(data)).Decode(&variants); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return variants, nil
|
||||||
|
}
|
||||||
@@ -12,6 +12,7 @@ import (
|
|||||||
|
|
||||||
"mtusi2026-messenger/internal/db"
|
"mtusi2026-messenger/internal/db"
|
||||||
"mtusi2026-messenger/internal/model"
|
"mtusi2026-messenger/internal/model"
|
||||||
|
s3store "mtusi2026-messenger/internal/s3"
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
@@ -128,13 +129,13 @@ func (w *Worker) duplicate(ctx context.Context, job model.AttachmentJob) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := w.verify(ctx, row.S3Key, row.SizeBytes, row.Sha256); err != nil {
|
if err := verify(ctx, w.s3, row.S3Key, row.SizeBytes, row.Sha256); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
hasThumbnail := false
|
hasThumbnail := false
|
||||||
for _, variant := range variants {
|
for _, variant := range variants {
|
||||||
if err := w.verify(ctx, variant.S3Key, variant.SizeBytes, variant.Sha256); err != nil {
|
if err := verify(ctx, w.s3, variant.S3Key, variant.SizeBytes, variant.Sha256); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -161,8 +162,8 @@ func (w *Worker) duplicate(ctx context.Context, job model.AttachmentJob) error {
|
|||||||
return errAttemptUnavailable
|
return errAttemptUnavailable
|
||||||
}
|
}
|
||||||
|
|
||||||
func (w *Worker) verify(ctx context.Context, key string, size int, checksum string) error {
|
func verify(ctx context.Context, storage *s3store.Client, key string, size int, checksum string) error {
|
||||||
object, err := w.s3.Get(ctx, key)
|
object, err := storage.Get(ctx, key)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,86 @@
|
|||||||
|
package worker
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"github.com/jackc/pgx/v5"
|
||||||
|
|
||||||
|
"mtusi2026-messenger/internal/db"
|
||||||
|
s3store "mtusi2026-messenger/internal/s3"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
errAttachmentNotReplayable = errors.New("attachment is not replayable: expected failed with staging and no existing variants")
|
||||||
|
errMissingPipelineJob = errors.New("attachment has no pipeline job")
|
||||||
|
errReplayNotUpdated = errors.New("attachment replay did not update one row")
|
||||||
|
)
|
||||||
|
|
||||||
|
type txBeginner interface {
|
||||||
|
Begin(ctx context.Context) (pgx.Tx, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
func Replay(
|
||||||
|
ctx context.Context,
|
||||||
|
pool txBeginner,
|
||||||
|
storage *s3store.Client,
|
||||||
|
id uuid.UUID,
|
||||||
|
operator, reason string,
|
||||||
|
) error {
|
||||||
|
tx, err := pool.Begin(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer tx.Rollback(context.Background())
|
||||||
|
|
||||||
|
q := db.New(tx)
|
||||||
|
row, err := q.LockFailedAttachmentForReplay(ctx, id)
|
||||||
|
if errors.Is(err, pgx.ErrNoRows) {
|
||||||
|
return errAttachmentNotReplayable
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if row.JobID == nil {
|
||||||
|
return errMissingPipelineJob
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := verify(ctx, storage, *row.StagingKey, row.SizeBytes, row.Sha256); err != nil {
|
||||||
|
return fmt.Errorf("verify replay source: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
n, err := q.ReplayAttachmentJob(ctx, id)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if n != 1 {
|
||||||
|
return errReplayNotUpdated
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := q.CreateAttachmentReplay(ctx, db.CreateAttachmentReplayParams{
|
||||||
|
AttachmentID: id,
|
||||||
|
Attempt: row.Attempts + 1,
|
||||||
|
PreviousErrorCode: row.ErrorCode,
|
||||||
|
Operator: operator,
|
||||||
|
Reason: reason,
|
||||||
|
}); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, err := q.CreateOutboxEntry(ctx, db.CreateOutboxEntryParams{
|
||||||
|
AttachmentID: id,
|
||||||
|
Attempt: row.Attempts + 1,
|
||||||
|
AvailableAt: time.Now(),
|
||||||
|
}); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := tx.Commit(ctx); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -31,7 +31,7 @@ func (w *Worker) finishFailure(ctx context.Context, job model.AttachmentJob, cau
|
|||||||
}
|
}
|
||||||
|
|
||||||
code := "processing_failed"
|
code := "processing_failed"
|
||||||
permanent := errors.Is(cause, errInvalidSource) || errors.Is(cause, s3store.ErrObjectNotFound)
|
permanent := errors.Is(cause, ErrInvalidSource) || errors.Is(cause, s3store.ErrObjectNotFound)
|
||||||
if permanent {
|
if permanent {
|
||||||
code = "invalid_source"
|
code = "invalid_source"
|
||||||
} else if errors.Is(cause, context.DeadlineExceeded) {
|
} else if errors.Is(cause, context.DeadlineExceeded) {
|
||||||
@@ -39,7 +39,7 @@ func (w *Worker) finishFailure(ctx context.Context, job model.AttachmentJob, cau
|
|||||||
}
|
}
|
||||||
|
|
||||||
var n int64
|
var n int64
|
||||||
if permanent || row.Attempts >= w.cfg.MaxAttempts {
|
if permanent || row.Attempts-row.RetryBase >= w.cfg.MaxAttempts {
|
||||||
if !permanent {
|
if !permanent {
|
||||||
code = "retry_exhausted"
|
code = "retry_exhausted"
|
||||||
}
|
}
|
||||||
@@ -59,7 +59,7 @@ func (w *Worker) finishFailure(ctx context.Context, job model.AttachmentJob, cau
|
|||||||
_, err = q.CreateOutboxEntry(ctx, db.CreateOutboxEntryParams{
|
_, err = q.CreateOutboxEntry(ctx, db.CreateOutboxEntryParams{
|
||||||
AttachmentID: row.ID,
|
AttachmentID: row.ID,
|
||||||
Attempt: row.Attempts + 1,
|
Attempt: row.Attempts + 1,
|
||||||
AvailableAt: time.Now().Add(retryDelay(row.Attempts)),
|
AvailableAt: time.Now().Add(retryDelay(row.Attempts - row.RetryBase)),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -119,7 +119,7 @@ func (w *Worker) recoverOne(ctx context.Context) (bool, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
row := rows[0]
|
row := rows[0]
|
||||||
if row.Attempts >= w.cfg.MaxAttempts {
|
if row.Attempts-row.RetryBase >= w.cfg.MaxAttempts {
|
||||||
_, err = q.FailExpiredAttachmentJob(ctx, row.ID)
|
_, err = q.FailExpiredAttachmentJob(ctx, row.ID)
|
||||||
} else {
|
} else {
|
||||||
_, err = q.RecoverExpiredAttachmentJob(ctx, row.ID)
|
_, err = q.RecoverExpiredAttachmentJob(ctx, row.ID)
|
||||||
@@ -127,7 +127,7 @@ func (w *Worker) recoverOne(ctx context.Context) (bool, error) {
|
|||||||
_, err = q.CreateOutboxEntry(ctx, db.CreateOutboxEntryParams{
|
_, err = q.CreateOutboxEntry(ctx, db.CreateOutboxEntryParams{
|
||||||
AttachmentID: row.ID,
|
AttachmentID: row.ID,
|
||||||
Attempt: row.Attempts + 1,
|
Attempt: row.Attempts + 1,
|
||||||
AvailableAt: time.Now().Add(retryDelay(row.Attempts)),
|
AvailableAt: time.Now().Add(retryDelay(row.Attempts - row.RetryBase)),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,60 @@
|
|||||||
|
package worker
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"github.com/jackc/pgx/v5"
|
||||||
|
|
||||||
|
"mtusi2026-messenger/internal/db"
|
||||||
|
s3store "mtusi2026-messenger/internal/s3"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
errAttachmentNotUpgradeable = errors.New("attachment is not upgradeable: expected v1 queued or processing with staging")
|
||||||
|
errUpgradeNotUpdated = errors.New("attachment upgrade did not update one row")
|
||||||
|
)
|
||||||
|
|
||||||
|
func Upgrade(ctx context.Context, pool txBeginner, storage *s3store.Client, id uuid.UUID) error {
|
||||||
|
tx, err := pool.Begin(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer tx.Rollback(context.Background())
|
||||||
|
|
||||||
|
q := db.New(tx)
|
||||||
|
row, err := q.LockAttachmentForUpgrade(ctx, id)
|
||||||
|
if errors.Is(err, pgx.ErrNoRows) {
|
||||||
|
return errAttachmentNotUpgradeable
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if row.JobID == nil {
|
||||||
|
return errMissingPipelineJob
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := verify(ctx, storage, *row.StagingKey, row.SizeBytes, row.Sha256); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
n, err := q.UpgradeAttachmentPipeline(ctx, id)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if n != 1 {
|
||||||
|
return errUpgradeNotUpdated
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, err := q.CreateOutboxEntry(ctx, db.CreateOutboxEntryParams{
|
||||||
|
AttachmentID: id,
|
||||||
|
Attempt: row.Attempts + 1,
|
||||||
|
AvailableAt: time.Now(),
|
||||||
|
}); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return tx.Commit(ctx)
|
||||||
|
}
|
||||||
@@ -116,7 +116,7 @@ func (w *Worker) consume(ctx context.Context, client *rabbitmq.Client) error {
|
|||||||
job.Type != "attachment.process.v1" ||
|
job.Type != "attachment.process.v1" ||
|
||||||
job.JobID == uuid.Nil ||
|
job.JobID == uuid.Nil ||
|
||||||
job.AttachmentID == uuid.Nil ||
|
job.AttachmentID == uuid.Nil ||
|
||||||
job.PipelineVersion != 1 ||
|
(job.PipelineVersion != 1 && job.PipelineVersion != 2) ||
|
||||||
job.Attempt < 1 ||
|
job.Attempt < 1 ||
|
||||||
job.CreatedAt.IsZero() {
|
job.CreatedAt.IsZero() {
|
||||||
if err := delivery.Reject(false); err != nil {
|
if err := delivery.Reject(false); err != nil {
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
//go:build contract || reconcile || failure || worker
|
//go:build contract || reconcile || failure || worker || pipeline
|
||||||
|
|
||||||
package studenttests_test
|
package studenttests_test
|
||||||
|
|
||||||
|
|||||||
@@ -1,12 +1,19 @@
|
|||||||
//go:build failure || worker
|
//go:build failure || worker || pipeline
|
||||||
|
|
||||||
package studenttests_test
|
package studenttests_test
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
|
"io"
|
||||||
"net/http"
|
"net/http"
|
||||||
"os/exec"
|
"os/exec"
|
||||||
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
|
||||||
|
"mtusi2026-messenger/internal/dto"
|
||||||
)
|
)
|
||||||
|
|
||||||
func compose(t *testing.T, args ...string) {
|
func compose(t *testing.T, args ...string) {
|
||||||
@@ -45,3 +52,73 @@ func waitReady(t *testing.T) {
|
|||||||
}
|
}
|
||||||
t.Fatal("service did not become ready in 60s")
|
t.Fatal("service did not become ready in 60s")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func workerCommand(t *testing.T, args ...string) string {
|
||||||
|
t.Helper()
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
cmd := exec.CommandContext(ctx, "docker", args...)
|
||||||
|
cmd.Dir = ".."
|
||||||
|
out, err := cmd.Output()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Docker command failed: %v", err)
|
||||||
|
}
|
||||||
|
return strings.TrimSpace(string(out))
|
||||||
|
}
|
||||||
|
|
||||||
|
func workerSQL(t *testing.T, query string) string {
|
||||||
|
t.Helper()
|
||||||
|
return workerCommand(t, "compose", "exec", "-T", "postgres", "psql",
|
||||||
|
"-U", "messenger", "-d", "messenger", "-Atqc", query)
|
||||||
|
}
|
||||||
|
|
||||||
|
func workerWait(t *testing.T, description string, timeout time.Duration, condition func() bool) {
|
||||||
|
t.Helper()
|
||||||
|
deadline := time.Now().Add(timeout)
|
||||||
|
for time.Now().Before(deadline) {
|
||||||
|
if condition() {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
time.Sleep(300 * time.Millisecond)
|
||||||
|
}
|
||||||
|
t.Fatalf("timeout waiting for %s", description)
|
||||||
|
}
|
||||||
|
|
||||||
|
func workerQueue(t *testing.T) string {
|
||||||
|
t.Helper()
|
||||||
|
out := workerCommand(t, "compose", "exec", "-T", "rabbitmq", "rabbitmqctl",
|
||||||
|
"list_queues", "name", "messages_ready", "messages_unacknowledged", "--silent")
|
||||||
|
for _, line := range strings.Split(out, "\n") {
|
||||||
|
fields := strings.Fields(line)
|
||||||
|
if len(fields) == 3 && fields[0] == "attachments.process.v1" {
|
||||||
|
return fields[1] + ":" + fields[2]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
t.Fatal("attachment queue missing")
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
func workerUpload(t *testing.T, user testUser, chatID uuid.UUID) (dto.AttachmentResponse, []byte) {
|
||||||
|
t.Helper()
|
||||||
|
source := makePNG(t, 320, 200)
|
||||||
|
resp := uploadAttachment(t, user, chatID, "worker.png", "image/png", source)
|
||||||
|
requireStatus(t, resp, http.StatusAccepted)
|
||||||
|
var att dto.AttachmentResponse
|
||||||
|
mustDecode(t, resp, &att)
|
||||||
|
if att.Status != "queued" {
|
||||||
|
t.Fatalf("expected queued, got %s", att.Status)
|
||||||
|
}
|
||||||
|
return att, source
|
||||||
|
}
|
||||||
|
|
||||||
|
func workerContent(t *testing.T, user testUser, id uuid.UUID, variant string) []byte {
|
||||||
|
t.Helper()
|
||||||
|
resp := doRequest(t, http.MethodGet, "/api/v1/attachments/"+id.String()+"/content?variant="+variant, user.Token, nil)
|
||||||
|
requireStatus(t, resp, http.StatusOK)
|
||||||
|
defer resp.Body.Close()
|
||||||
|
data, err := io.ReadAll(resp.Body)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return data
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,302 @@
|
|||||||
|
//go:build pipeline
|
||||||
|
|
||||||
|
package studenttests_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"encoding/base64"
|
||||||
|
"reflect"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"golang.org/x/image/webp"
|
||||||
|
)
|
||||||
|
|
||||||
|
func pipelineS3Gate(t *testing.T, suffix string) (string, func(string) string) {
|
||||||
|
t.Helper()
|
||||||
|
proxy := "pipeline-gate-" + uuid.NewString()
|
||||||
|
workerContainer := workerCommand(t, "compose", "ps", "-a", "-q", "worker")
|
||||||
|
network := workerCommand(t, "inspect", "--format",
|
||||||
|
"{{range $name, $value := .NetworkSettings.Networks}}{{$name}}{{end}}", workerContainer)
|
||||||
|
t.Cleanup(func() { workerCommand(t, "rm", "-f", proxy) })
|
||||||
|
const proxyScript = `
|
||||||
|
import base64
|
||||||
|
import http.client
|
||||||
|
import http.server
|
||||||
|
import threading
|
||||||
|
import sys
|
||||||
|
|
||||||
|
waiting = threading.Event()
|
||||||
|
release = threading.Event()
|
||||||
|
written = threading.Event()
|
||||||
|
held_body = b''
|
||||||
|
|
||||||
|
class Proxy(http.server.BaseHTTPRequestHandler):
|
||||||
|
def log_message(self, *args):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def do_GET(self):
|
||||||
|
if self.path == '/_body':
|
||||||
|
self.send_response(200)
|
||||||
|
self.end_headers()
|
||||||
|
self.wfile.write(base64.b64encode(held_body))
|
||||||
|
return
|
||||||
|
if self.path == '/_state':
|
||||||
|
data = f'{int(waiting.is_set())}:{int(written.is_set())}'.encode()
|
||||||
|
self.send_response(200)
|
||||||
|
self.end_headers()
|
||||||
|
self.wfile.write(data)
|
||||||
|
return
|
||||||
|
if self.path == '/_release':
|
||||||
|
release.set()
|
||||||
|
self.send_response(200)
|
||||||
|
self.end_headers()
|
||||||
|
return
|
||||||
|
self.forward()
|
||||||
|
|
||||||
|
def do_PUT(self):
|
||||||
|
self.forward()
|
||||||
|
|
||||||
|
def forward(self):
|
||||||
|
global held_body
|
||||||
|
body = self.rfile.read(int(self.headers.get('Content-Length', 0)))
|
||||||
|
gated = self.command == 'PUT' and self.path.split('?')[0].endswith(sys.argv[1])
|
||||||
|
if gated:
|
||||||
|
held_body = body
|
||||||
|
waiting.set()
|
||||||
|
if not release.wait(90):
|
||||||
|
self.send_error(504)
|
||||||
|
return
|
||||||
|
conn = http.client.HTTPConnection('s3', 9000, timeout=20)
|
||||||
|
try:
|
||||||
|
conn.request(self.command, self.path, body, dict(self.headers))
|
||||||
|
response = conn.getresponse()
|
||||||
|
data = response.read()
|
||||||
|
if gated and response.status == 200:
|
||||||
|
written.set()
|
||||||
|
self.send_response(response.status)
|
||||||
|
for name, value in response.getheaders():
|
||||||
|
if name.lower() not in ('connection', 'transfer-encoding', 'content-length'):
|
||||||
|
self.send_header(name, value)
|
||||||
|
self.send_header('Content-Length', str(len(data)))
|
||||||
|
self.end_headers()
|
||||||
|
self.wfile.write(data)
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
http.server.ThreadingHTTPServer(('0.0.0.0', 9000), Proxy).serve_forever()
|
||||||
|
`
|
||||||
|
workerCommand(t, "run", "-d", "--name", proxy, "--network", network,
|
||||||
|
"python:3.13.9-alpine3.22", "python", "-u", "-c", proxyScript, suffix)
|
||||||
|
control := func(path string) string {
|
||||||
|
t.Helper()
|
||||||
|
return workerCommand(t, "exec", proxy, "python", "-c",
|
||||||
|
"import urllib.request; print(urllib.request.urlopen('http://127.0.0.1:9000/"+path+"').read().decode())")
|
||||||
|
}
|
||||||
|
return proxy, control
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPipelineStaleProcessing(t *testing.T) {
|
||||||
|
user := createUser(t)
|
||||||
|
chat := createChat(t, user, user.ID)
|
||||||
|
stopService(t, "worker")
|
||||||
|
if workerQueue(t) != "0:0" {
|
||||||
|
t.Fatal("run on an idle stand with an empty attachment queue")
|
||||||
|
}
|
||||||
|
att, source := workerUpload(t, user, chat.ID)
|
||||||
|
id := att.ID.String()
|
||||||
|
where := "attachment_id='" + id + "'"
|
||||||
|
jobID := workerSQL(t, "SELECT job_id FROM attachments WHERE id='"+id+"'")
|
||||||
|
|
||||||
|
// Hold the last v1 PUT while v2 completes, without a DB row lock.
|
||||||
|
proxy, control := pipelineS3Gate(t, "/v1/optimized")
|
||||||
|
oldWorker := "pipeline-v1-" + uuid.NewString()
|
||||||
|
t.Cleanup(func() { workerCommand(t, "rm", "-f", oldWorker) })
|
||||||
|
workerCommand(t, "compose", "run", "-d", "--no-deps", "--name", oldWorker,
|
||||||
|
"-e", "WORKER_CONCURRENCY=1", "-e", "JOB_TIMEOUT_SECONDS=120",
|
||||||
|
"-e", "S3_ENDPOINT=http://"+proxy+":9000", "worker")
|
||||||
|
workerWait(t, "v1 waiting before optimized PUT", 20*time.Second, func() bool {
|
||||||
|
return control("_state") == "1:0"
|
||||||
|
})
|
||||||
|
if workerSQL(t, "SELECT pipeline_version||':'||status||':'||attempts FROM attachments WHERE id='"+id+"'") != "1:processing:1" {
|
||||||
|
t.Fatal("v1 was not processing before upgrade")
|
||||||
|
}
|
||||||
|
|
||||||
|
workerCommand(t, "compose", "run", "--rm", "--no-deps", "worker", "-upgrade", id)
|
||||||
|
compose(t, "start", "worker")
|
||||||
|
ready := waitAttachment(t, user, att.ID, "ready", 30*time.Second)
|
||||||
|
if len(ready.Variants) != 3 ||
|
||||||
|
workerSQL(t, "SELECT pipeline_version||':'||attempts FROM attachments WHERE id='"+id+"'") != "2:2" {
|
||||||
|
t.Fatal("v2 did not become ready while v1 was held")
|
||||||
|
}
|
||||||
|
content := make(map[string][]byte)
|
||||||
|
for _, name := range []string{"original", "thumbnail", "crop", "optimized"} {
|
||||||
|
content[name] = workerContent(t, user, att.ID, name)
|
||||||
|
}
|
||||||
|
if !bytes.Equal(content["original"], source) {
|
||||||
|
t.Fatal("v2 changed original bytes")
|
||||||
|
}
|
||||||
|
v1, err := base64.StdEncoding.DecodeString(control("_body"))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for _, data := range [][]byte{v1, content["optimized"]} {
|
||||||
|
cfg, err := webp.DecodeConfig(bytes.NewReader(data))
|
||||||
|
if err != nil || cfg.Width != 320 || cfg.Height != 200 {
|
||||||
|
t.Fatal("expected valid optimized WebP from both versions")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if bytes.Equal(v1, content["optimized"]) {
|
||||||
|
t.Fatal("fixture must produce different v1 and v2 optimized bytes")
|
||||||
|
}
|
||||||
|
|
||||||
|
control("_release")
|
||||||
|
workerWait(t, "late v1 S3 write", 20*time.Second, func() bool {
|
||||||
|
return control("_state") == "1:1"
|
||||||
|
})
|
||||||
|
workerWait(t, "stale v1 redelivery acknowledged", 15*time.Second, func() bool {
|
||||||
|
return workerQueue(t) == "0:0"
|
||||||
|
})
|
||||||
|
after := waitAttachment(t, user, att.ID, "ready", 5*time.Second)
|
||||||
|
if !reflect.DeepEqual(ready, after) ||
|
||||||
|
workerSQL(t, "SELECT job_id FROM attachments WHERE id='"+id+"'") != jobID ||
|
||||||
|
workerSQL(t, "SELECT pipeline_version||':'||attempts FROM attachments WHERE id='"+id+"'") != "2:2" ||
|
||||||
|
workerSQL(t, "SELECT count(*) FROM attachment_variants WHERE "+where+" AND pipeline_version=1") != "0" ||
|
||||||
|
workerSQL(t, "SELECT count(*) FROM attachment_variants WHERE "+where+" AND pipeline_version=2") != "3" {
|
||||||
|
t.Fatal("late v1 processing changed current metadata")
|
||||||
|
}
|
||||||
|
for name, before := range content {
|
||||||
|
if !bytes.Equal(before, workerContent(t, user, att.ID, name)) {
|
||||||
|
t.Fatalf("late v1 processing overwrote %s", name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
t.Logf("PASS attachment=%s: held v1 PUT; v2 ready; late v1 wrote S3 but could not replace v2; stale redelivery acknowledged", id)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPipelineReorderAndDuplicate(t *testing.T) {
|
||||||
|
user := createUser(t)
|
||||||
|
chat := createChat(t, user, user.ID)
|
||||||
|
stopService(t, "worker")
|
||||||
|
if workerQueue(t) != "0:0" {
|
||||||
|
t.Fatal("run on an idle stand with an empty attachment queue")
|
||||||
|
}
|
||||||
|
// Keep v1 durable in outbox, but delay its publication until v2 is ready.
|
||||||
|
stopService(t, "rabbitmq")
|
||||||
|
att, source := workerUpload(t, user, chat.ID)
|
||||||
|
id := att.ID.String()
|
||||||
|
where := "attachment_id='" + id + "'"
|
||||||
|
jobID := workerSQL(t, "SELECT job_id FROM attachments WHERE id='"+id+"'")
|
||||||
|
workerSQL(t, "UPDATE outbox SET available_at=now()+interval '1 hour' WHERE "+where)
|
||||||
|
if workerSQL(t, "SELECT count(*) FROM outbox WHERE "+where+" AND published_at IS NULL") != "1" {
|
||||||
|
t.Fatal("v1 was published before the reorder injection")
|
||||||
|
}
|
||||||
|
workerCommand(t, "compose", "run", "--rm", "--no-deps", "worker", "-upgrade", id)
|
||||||
|
compose(t, "start", "rabbitmq", "worker")
|
||||||
|
ready := waitAttachment(t, user, att.ID, "ready", 40*time.Second)
|
||||||
|
workerWait(t, "v2 acknowledgement", 15*time.Second, func() bool {
|
||||||
|
return workerQueue(t) == "0:0"
|
||||||
|
})
|
||||||
|
if len(ready.Variants) != 3 ||
|
||||||
|
workerSQL(t, "SELECT pipeline_version||':'||attempts FROM attachments WHERE id='"+id+"'") != "2:1" ||
|
||||||
|
workerSQL(t, "SELECT count(*) FROM outbox WHERE "+where+" AND pipeline_version=1 AND published_at IS NULL") != "1" {
|
||||||
|
t.Fatal("v2 did not finish before v1 publication")
|
||||||
|
}
|
||||||
|
content := make(map[string][]byte)
|
||||||
|
for _, name := range []string{"original", "thumbnail", "crop", "optimized"} {
|
||||||
|
content[name] = workerContent(t, user, att.ID, name)
|
||||||
|
}
|
||||||
|
if !bytes.Equal(content["original"], source) {
|
||||||
|
t.Fatal("v2 changed original bytes")
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, injection := range []struct {
|
||||||
|
name, query, version string
|
||||||
|
}{
|
||||||
|
{"reordered v1", "UPDATE outbox SET available_at=now() WHERE " + where + " AND pipeline_version=1", "1"},
|
||||||
|
{"duplicate v2", "UPDATE outbox SET published_at=NULL WHERE " + where + " AND pipeline_version=2", "2"},
|
||||||
|
} {
|
||||||
|
compose(t, "stop", "worker")
|
||||||
|
workerSQL(t, injection.query)
|
||||||
|
workerWait(t, injection.name+" published", 15*time.Second, func() bool {
|
||||||
|
return workerSQL(t, "SELECT count(*) FROM outbox WHERE "+where+
|
||||||
|
" AND pipeline_version="+injection.version+" AND published_at IS NOT NULL") == "1" &&
|
||||||
|
workerQueue(t) == "1:0"
|
||||||
|
})
|
||||||
|
compose(t, "start", "worker")
|
||||||
|
workerWait(t, injection.name+" acknowledged", 15*time.Second, func() bool {
|
||||||
|
return workerQueue(t) == "0:0"
|
||||||
|
})
|
||||||
|
after := waitAttachment(t, user, att.ID, "ready", 5*time.Second)
|
||||||
|
if !reflect.DeepEqual(ready, after) ||
|
||||||
|
workerSQL(t, "SELECT job_id FROM attachments WHERE id='"+id+"'") != jobID ||
|
||||||
|
workerSQL(t, "SELECT pipeline_version||':'||attempts FROM attachments WHERE id='"+id+"'") != "2:1" ||
|
||||||
|
workerSQL(t, "SELECT count(*) FROM attachment_variants WHERE "+where+" AND pipeline_version=1") != "0" ||
|
||||||
|
workerSQL(t, "SELECT count(*) FROM attachment_variants WHERE "+where+" AND pipeline_version=2") != "3" ||
|
||||||
|
workerSQL(t, "SELECT count(*) FROM outbox WHERE "+where) != "2" {
|
||||||
|
t.Fatalf("%s changed metadata or created extra work", injection.name)
|
||||||
|
}
|
||||||
|
for name, before := range content {
|
||||||
|
if !bytes.Equal(before, workerContent(t, user, att.ID, name)) {
|
||||||
|
t.Fatalf("%s changed %s bytes", injection.name, name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
t.Logf("PASS attachment=%s: v2 completed before v1 delivery; stale v1 and duplicate v2 acknowledged without changes", id)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPipelineCrashBeforeWrite(t *testing.T) {
|
||||||
|
user := createUser(t)
|
||||||
|
chat := createChat(t, user, user.ID)
|
||||||
|
stopService(t, "worker")
|
||||||
|
if workerQueue(t) != "0:0" {
|
||||||
|
t.Fatal("run on an idle stand with an empty attachment queue")
|
||||||
|
}
|
||||||
|
att, source := workerUpload(t, user, chat.ID)
|
||||||
|
id := att.ID.String()
|
||||||
|
where := "attachment_id='" + id + "'"
|
||||||
|
jobID := workerSQL(t, "SELECT job_id FROM attachments WHERE id='"+id+"'")
|
||||||
|
workerCommand(t, "compose", "run", "--rm", "--no-deps", "worker", "-upgrade", id)
|
||||||
|
|
||||||
|
// Original is the first result PUT. Neither it nor any variant reaches S3.
|
||||||
|
proxy, control := pipelineS3Gate(t, "/attachments/"+id)
|
||||||
|
testWorker := "pipeline-crash-" + uuid.NewString()
|
||||||
|
t.Cleanup(func() { workerCommand(t, "rm", "-f", testWorker) })
|
||||||
|
workerCommand(t, "compose", "run", "-d", "--no-deps", "--name", testWorker,
|
||||||
|
"-e", "WORKER_CONCURRENCY=1", "-e", "JOB_TIMEOUT_SECONDS=15",
|
||||||
|
"-e", "S3_ENDPOINT=http://"+proxy+":9000", "worker")
|
||||||
|
workerWait(t, "v2 held before first result PUT", 10*time.Second, func() bool {
|
||||||
|
return control("_state") == "1:0"
|
||||||
|
})
|
||||||
|
if workerSQL(t, "SELECT pipeline_version||':'||status||':'||attempts FROM attachments WHERE id='"+id+"'") != "2:processing:1" ||
|
||||||
|
workerSQL(t, "SELECT count(*) FROM attachment_variants WHERE "+where) != "0" {
|
||||||
|
t.Fatal("expected v2 processing without a committed result")
|
||||||
|
}
|
||||||
|
workerCommand(t, "kill", "--signal", "SIGKILL", testWorker)
|
||||||
|
// Kill the held request too: it must never be forwarded after the crash.
|
||||||
|
workerCommand(t, "kill", "--signal", "SIGKILL", proxy)
|
||||||
|
workerWait(t, "crashed v2 job returned to broker", 10*time.Second, func() bool {
|
||||||
|
return workerQueue(t) == "1:0"
|
||||||
|
})
|
||||||
|
compose(t, "start", "worker")
|
||||||
|
// Recovery must use the natural lease expiry; no status/lease SQL injection.
|
||||||
|
ready := waitAttachment(t, user, att.ID, "ready", 40*time.Second)
|
||||||
|
workerWait(t, "recovered v2 acknowledgement", 15*time.Second, func() bool {
|
||||||
|
return workerQueue(t) == "0:0"
|
||||||
|
})
|
||||||
|
if len(ready.Variants) != 3 ||
|
||||||
|
!bytes.Equal(workerContent(t, user, att.ID, "original"), source) ||
|
||||||
|
workerSQL(t, "SELECT job_id FROM attachments WHERE id='"+id+"'") != jobID ||
|
||||||
|
workerSQL(t, "SELECT pipeline_version||':'||attempts FROM attachments WHERE id='"+id+"'") != "2:2" ||
|
||||||
|
workerSQL(t, "SELECT count(*) FROM attachment_variants WHERE "+where+" AND pipeline_version=2") != "3" ||
|
||||||
|
workerSQL(t, "SELECT count(*) FROM attachment_variants WHERE "+where) != "3" ||
|
||||||
|
workerSQL(t, "SELECT count(*) FROM outbox WHERE "+where+" AND pipeline_version=2 AND attempt=2 AND published_at IS NOT NULL") != "1" {
|
||||||
|
t.Fatal("crash recovery lost the accepted job or changed its identity or result")
|
||||||
|
}
|
||||||
|
for _, name := range []string{"thumbnail", "crop", "optimized"} {
|
||||||
|
if len(workerContent(t, user, att.ID, name)) == 0 {
|
||||||
|
t.Fatalf("recovered v2 has empty %s", name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
t.Logf("PASS attachment=%s: SIGKILL before first result PUT; natural lease recovery; same job ready on v2 attempt2", id)
|
||||||
|
}
|
||||||
+266
-71
@@ -7,8 +7,8 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"image/jpeg"
|
"image/jpeg"
|
||||||
"io"
|
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"os"
|
||||||
"os/exec"
|
"os/exec"
|
||||||
"reflect"
|
"reflect"
|
||||||
"strconv"
|
"strconv"
|
||||||
@@ -17,81 +17,12 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/google/uuid"
|
"github.com/google/uuid"
|
||||||
|
"github.com/jackc/pgx/v5"
|
||||||
"golang.org/x/image/webp"
|
"golang.org/x/image/webp"
|
||||||
|
|
||||||
"mtusi2026-messenger/internal/dto"
|
"mtusi2026-messenger/internal/dto"
|
||||||
)
|
)
|
||||||
|
|
||||||
func workerCommand(t *testing.T, args ...string) string {
|
|
||||||
t.Helper()
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
|
||||||
defer cancel()
|
|
||||||
cmd := exec.CommandContext(ctx, "docker", args...)
|
|
||||||
cmd.Dir = ".."
|
|
||||||
out, err := cmd.Output()
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("Docker command failed: %v", err)
|
|
||||||
}
|
|
||||||
return strings.TrimSpace(string(out))
|
|
||||||
}
|
|
||||||
|
|
||||||
func workerSQL(t *testing.T, query string) string {
|
|
||||||
t.Helper()
|
|
||||||
return workerCommand(t, "compose", "exec", "-T", "postgres", "psql",
|
|
||||||
"-U", "messenger", "-d", "messenger", "-Atqc", query)
|
|
||||||
}
|
|
||||||
|
|
||||||
func workerWait(t *testing.T, description string, timeout time.Duration, condition func() bool) {
|
|
||||||
t.Helper()
|
|
||||||
deadline := time.Now().Add(timeout)
|
|
||||||
for time.Now().Before(deadline) {
|
|
||||||
if condition() {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
time.Sleep(300 * time.Millisecond)
|
|
||||||
}
|
|
||||||
t.Fatalf("timeout waiting for %s", description)
|
|
||||||
}
|
|
||||||
|
|
||||||
func workerQueue(t *testing.T) string {
|
|
||||||
t.Helper()
|
|
||||||
out := workerCommand(t, "compose", "exec", "-T", "rabbitmq", "rabbitmqctl",
|
|
||||||
"list_queues", "name", "messages_ready", "messages_unacknowledged", "--silent")
|
|
||||||
for _, line := range strings.Split(out, "\n") {
|
|
||||||
fields := strings.Fields(line)
|
|
||||||
if len(fields) == 3 && fields[0] == "attachments.process.v1" {
|
|
||||||
return fields[1] + ":" + fields[2]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
t.Fatal("attachment queue missing")
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
|
|
||||||
func workerUpload(t *testing.T, user testUser, chatID uuid.UUID) (dto.AttachmentResponse, []byte) {
|
|
||||||
t.Helper()
|
|
||||||
source := makePNG(t, 320, 200)
|
|
||||||
resp := uploadAttachment(t, user, chatID, "worker.png", "image/png", source)
|
|
||||||
requireStatus(t, resp, http.StatusAccepted)
|
|
||||||
var att dto.AttachmentResponse
|
|
||||||
mustDecode(t, resp, &att)
|
|
||||||
if att.Status != "queued" {
|
|
||||||
t.Fatalf("expected queued, got %s", att.Status)
|
|
||||||
}
|
|
||||||
return att, source
|
|
||||||
}
|
|
||||||
|
|
||||||
func workerContent(t *testing.T, user testUser, id uuid.UUID, variant string) []byte {
|
|
||||||
t.Helper()
|
|
||||||
resp := doRequest(t, http.MethodGet, "/api/v1/attachments/"+id.String()+"/content?variant="+variant, user.Token, nil)
|
|
||||||
requireStatus(t, resp, http.StatusOK)
|
|
||||||
defer resp.Body.Close()
|
|
||||||
data, err := io.ReadAll(resp.Body)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
return data
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestWorkerPersistenceAndDuplicate(t *testing.T) {
|
func TestWorkerPersistenceAndDuplicate(t *testing.T) {
|
||||||
user := createUser(t)
|
user := createUser(t)
|
||||||
chat := createChat(t, user, user.ID)
|
chat := createChat(t, user, user.ID)
|
||||||
@@ -229,3 +160,267 @@ func TestWorkerRetryExhausted(t *testing.T) {
|
|||||||
resp.Body.Close()
|
resp.Body.Close()
|
||||||
t.Logf("PASS attachment=%s: %d attempts, failed/retry_exhausted, content/link rejected", att.ID, maxAttempts)
|
t.Logf("PASS attachment=%s: %d attempts, failed/retry_exhausted, content/link rejected", att.ID, maxAttempts)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestWorkerProcessingTimeout(t *testing.T) {
|
||||||
|
user := createUser(t)
|
||||||
|
chat := createChat(t, user, user.ID)
|
||||||
|
stopService(t, "worker")
|
||||||
|
if workerQueue(t) != "0:0" {
|
||||||
|
t.Fatal("run on an idle stand with an empty attachment queue")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Decode and resize of 36 million pixels must be interrupted by the short deadline.
|
||||||
|
resp := uploadAttachment(t, user, chat.ID, "large.png", "image/png", makePNG(t, 6000, 6000))
|
||||||
|
requireStatus(t, resp, http.StatusAccepted)
|
||||||
|
var att dto.AttachmentResponse
|
||||||
|
mustDecode(t, resp, &att)
|
||||||
|
|
||||||
|
testWorker := "worker-timeout-" + uuid.NewString()
|
||||||
|
t.Cleanup(func() {
|
||||||
|
workerCommand(t, "rm", "-f", testWorker)
|
||||||
|
})
|
||||||
|
workerCommand(t, "compose", "run", "-d", "--no-deps", "--name", testWorker,
|
||||||
|
"-e", "JOB_TIMEOUT_SECONDS=1", "-e", "JOB_MAX_ATTEMPTS=1", "worker")
|
||||||
|
parentPID := workerCommand(t, "inspect", "--format", "{{.State.Pid}}", testWorker)
|
||||||
|
workerWait(t, "image child process", 5*time.Second, func() bool {
|
||||||
|
return strings.Contains(workerCommand(t, "top", testWorker, "-eo", "pid,args"), "-process-image")
|
||||||
|
})
|
||||||
|
failed := waitAttachment(t, user, att.ID, "failed", 5*time.Second)
|
||||||
|
if failed.ErrorCode == nil || *failed.ErrorCode != "retry_exhausted" {
|
||||||
|
t.Fatal("expected retry_exhausted after processing deadline")
|
||||||
|
}
|
||||||
|
if strings.Contains(workerCommand(t, "top", testWorker, "-eo", "pid,args"), "-process-image") {
|
||||||
|
t.Fatal("image process survived its deadline")
|
||||||
|
}
|
||||||
|
if workerSQL(t, "SELECT count(*) FROM attachment_variants WHERE attachment_id='"+att.ID.String()+"'") != "0" {
|
||||||
|
t.Fatal("timed-out processing published variants")
|
||||||
|
}
|
||||||
|
|
||||||
|
// The same parent process must remain usable after terminating the image child.
|
||||||
|
uploadPNG(t, user, chat.ID)
|
||||||
|
after := workerCommand(t, "inspect", "--format", "{{.State.Pid}}", testWorker)
|
||||||
|
if parentPID != after || parentPID == "0" {
|
||||||
|
t.Fatal("parent worker restarted after the image timeout")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestWorkerReplay(t *testing.T) {
|
||||||
|
user := createUser(t)
|
||||||
|
chat := createChat(t, user, user.ID)
|
||||||
|
stopService(t, "worker")
|
||||||
|
if workerQueue(t) != "0:0" {
|
||||||
|
t.Fatal("run on an idle stand with an empty attachment queue")
|
||||||
|
}
|
||||||
|
att, source := workerUpload(t, user, chat.ID)
|
||||||
|
id := att.ID.String()
|
||||||
|
where := "attachment_id='" + id + "'"
|
||||||
|
|
||||||
|
testWorker := "worker-replay-" + uuid.NewString()
|
||||||
|
t.Cleanup(func() {
|
||||||
|
if testWorker != "" {
|
||||||
|
workerCommand(t, "rm", "-f", testWorker)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
workerCommand(t, "compose", "run", "-d", "--no-deps", "--name", testWorker,
|
||||||
|
"-e", "JOB_TIMEOUT_SECONDS=3", "-e", "JOB_MAX_ATTEMPTS=1",
|
||||||
|
"-e", "S3_ENDPOINT=http://127.0.0.1:1", "worker")
|
||||||
|
waitAttachment(t, user, att.ID, "failed", 15*time.Second)
|
||||||
|
workerCommand(t, "rm", "-f", testWorker)
|
||||||
|
testWorker = ""
|
||||||
|
|
||||||
|
runCLI := func(args ...string) (string, error) {
|
||||||
|
t.Helper()
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
cmd := exec.CommandContext(ctx, "docker", append([]string{
|
||||||
|
"compose", "run", "--rm", "--no-deps", "worker",
|
||||||
|
}, args...)...)
|
||||||
|
cmd.Dir = ".."
|
||||||
|
out, err := cmd.CombinedOutput()
|
||||||
|
return string(out), err
|
||||||
|
}
|
||||||
|
replayArgs := []string{"-replay", id, "-operator", "synthetic-operator", "-reason", "S3 restored"}
|
||||||
|
if out, err := runCLI("-list-failed"); err != nil || !strings.Contains(out, id) {
|
||||||
|
t.Fatalf("failed registry did not list attachment: %v\n%s", err, out)
|
||||||
|
}
|
||||||
|
if out, err := runCLI("-replay", id); err == nil || !strings.Contains(out, "nonempty operator and reason") {
|
||||||
|
t.Fatalf("replay without audit details was accepted: %v\n%s", err, out)
|
||||||
|
}
|
||||||
|
|
||||||
|
// A stale DB key must not make a missing S3 source replayable.
|
||||||
|
key := workerSQL(t, "SELECT staging_key FROM attachments WHERE id='"+id+"'")
|
||||||
|
workerSQL(t, "UPDATE attachments SET staging_key='staging/"+uuid.NewString()+"' WHERE id='"+id+"'")
|
||||||
|
out, err := runCLI(replayArgs...)
|
||||||
|
workerSQL(t, "UPDATE attachments SET staging_key='"+key+"' WHERE id='"+id+"'")
|
||||||
|
if err == nil || !strings.Contains(out, "verify replay source") {
|
||||||
|
t.Fatalf("missing S3 source was accepted: %v\n%s", err, out)
|
||||||
|
}
|
||||||
|
if workerSQL(t, "SELECT status||':'||attempts||':'||retry_base FROM attachments WHERE id='"+id+"'") != "failed:1:0" ||
|
||||||
|
workerSQL(t, "SELECT count(*) FROM attachment_replays WHERE "+where) != "0" ||
|
||||||
|
workerSQL(t, "SELECT count(*) FROM outbox WHERE "+where) != "1" {
|
||||||
|
t.Fatal("rejected replay changed attachment, audit or outbox")
|
||||||
|
}
|
||||||
|
|
||||||
|
if out, err := runCLI(replayArgs...); err != nil {
|
||||||
|
t.Fatalf("replay failed: %v\n%s", err, out)
|
||||||
|
}
|
||||||
|
if workerSQL(t, "SELECT status||':'||attempts||':'||retry_base FROM attachments WHERE id='"+id+"'") != "queued:1:1" ||
|
||||||
|
workerSQL(t, "SELECT attempt||':'||operator||':'||reason||':'||previous_error_code FROM attachment_replays WHERE "+where) !=
|
||||||
|
"2:synthetic-operator:S3 restored:retry_exhausted" ||
|
||||||
|
workerSQL(t, "SELECT count(*) FROM outbox WHERE "+where) != "2" {
|
||||||
|
t.Fatal("replay did not atomically queue the next attempt with audit and outbox")
|
||||||
|
}
|
||||||
|
if out, err := runCLI(replayArgs...); err == nil || !strings.Contains(out, "not replayable") {
|
||||||
|
t.Fatalf("queued replay was accepted twice: %v\n%s", err, out)
|
||||||
|
}
|
||||||
|
|
||||||
|
compose(t, "start", "worker")
|
||||||
|
ready := waitAttachment(t, user, att.ID, "ready", 30*time.Second)
|
||||||
|
if len(ready.Variants) != 3 || !bytes.Equal(workerContent(t, user, att.ID, "original"), source) {
|
||||||
|
t.Fatal("replay did not complete the same attachment with unchanged original")
|
||||||
|
}
|
||||||
|
if out, err := runCLI(replayArgs...); err == nil || !strings.Contains(out, "not replayable") {
|
||||||
|
t.Fatalf("ready replay was accepted: %v\n%s", err, out)
|
||||||
|
}
|
||||||
|
if workerSQL(t, "SELECT count(*) FROM attachment_replays WHERE "+where) != "1" ||
|
||||||
|
workerSQL(t, "SELECT attempts FROM attachments WHERE id='"+id+"'") != "2" {
|
||||||
|
t.Fatal("duplicate replay changed audit or attempt counter")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestWorkerOutboxRecovery(t *testing.T) {
|
||||||
|
user := createUser(t)
|
||||||
|
chat := createChat(t, user, user.ID)
|
||||||
|
stopService(t, "worker")
|
||||||
|
if workerQueue(t) != "0:0" {
|
||||||
|
t.Fatal("run on an idle stand with an empty attachment queue")
|
||||||
|
}
|
||||||
|
|
||||||
|
stopService(t, "rabbitmq")
|
||||||
|
att, source := workerUpload(t, user, chat.ID)
|
||||||
|
id := att.ID.String()
|
||||||
|
where := "attachment_id='" + id + "'"
|
||||||
|
jobID := workerSQL(t, "SELECT job_id FROM attachments WHERE id='"+id+"'")
|
||||||
|
if workerSQL(t, "SELECT count(*) FROM outbox WHERE "+where+" AND attempt=1 AND published_at IS NULL") != "1" {
|
||||||
|
t.Fatal("upload 202 did not persist an unpublished intent")
|
||||||
|
}
|
||||||
|
|
||||||
|
t.Cleanup(func() {
|
||||||
|
compose(t, "start", "api")
|
||||||
|
waitReady(t)
|
||||||
|
})
|
||||||
|
compose(t, "kill", "-s", "SIGKILL", "api")
|
||||||
|
if workerSQL(t, "SELECT count(*) FROM outbox WHERE "+where+" AND attempt=1 AND published_at IS NULL") != "1" {
|
||||||
|
t.Fatal("committed intent lost after API crash")
|
||||||
|
}
|
||||||
|
|
||||||
|
compose(t, "start", "api")
|
||||||
|
waitReady(t)
|
||||||
|
waitAttachment(t, user, att.ID, "queued", 15*time.Second)
|
||||||
|
compose(t, "up", "-d", "--no-deps", "--wait", "--wait-timeout", "30", "rabbitmq")
|
||||||
|
workerWait(t, "outbox publication after API crash", 15*time.Second, func() bool {
|
||||||
|
return workerSQL(t, "SELECT published_at IS NOT NULL FROM outbox WHERE "+where) == "t"
|
||||||
|
})
|
||||||
|
if workerQueue(t) != "1:0" {
|
||||||
|
t.Fatal("recovered intent was not delivered to broker")
|
||||||
|
}
|
||||||
|
|
||||||
|
compose(t, "start", "worker")
|
||||||
|
ready := waitAttachment(t, user, att.ID, "ready", 30*time.Second)
|
||||||
|
if len(ready.Variants) != 3 || !bytes.Equal(workerContent(t, user, att.ID, "original"), source) {
|
||||||
|
t.Fatal("recovered attachment has incomplete variants or changed original")
|
||||||
|
}
|
||||||
|
workerWait(t, "recovered job acknowledgement", 15*time.Second, func() bool {
|
||||||
|
return workerQueue(t) == "0:0"
|
||||||
|
})
|
||||||
|
if workerSQL(t, "SELECT job_id FROM attachments WHERE id='"+id+"'") != jobID ||
|
||||||
|
workerSQL(t, "SELECT attempts FROM attachments WHERE id='"+id+"'") != "1" ||
|
||||||
|
workerSQL(t, "SELECT count(*) FROM outbox WHERE "+where) != "1" {
|
||||||
|
t.Fatal("recovery replaced the job or created another attempt")
|
||||||
|
}
|
||||||
|
|
||||||
|
t.Logf("PASS attachment=%s: commit, API SIGKILL before publication, automatic outbox recovery, same job ready", id)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestWorkerLeaseRecovery(t *testing.T) {
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
|
||||||
|
defer cancel()
|
||||||
|
secret, err := os.ReadFile("../secrets/test_database_url.txt")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal("read test database URL")
|
||||||
|
}
|
||||||
|
conn, err := pgx.Connect(ctx, strings.TrimSpace(string(secret)))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal("connect to test database")
|
||||||
|
}
|
||||||
|
t.Cleanup(func() { conn.Close(context.Background()) })
|
||||||
|
|
||||||
|
user := createUser(t)
|
||||||
|
chat := createChat(t, user, user.ID)
|
||||||
|
stopService(t, "worker")
|
||||||
|
if workerQueue(t) != "0:0" {
|
||||||
|
t.Fatal("run on an idle stand with an empty attachment queue")
|
||||||
|
}
|
||||||
|
att, source := workerUpload(t, user, chat.ID)
|
||||||
|
id := att.ID.String()
|
||||||
|
where := "attachment_id='" + id + "'"
|
||||||
|
jobID := workerSQL(t, "SELECT job_id FROM attachments WHERE id='"+id+"'")
|
||||||
|
|
||||||
|
testWorker := "worker-lease-" + uuid.NewString()
|
||||||
|
t.Cleanup(func() { workerCommand(t, "rm", "-f", testWorker) })
|
||||||
|
tx, err := conn.Begin(ctx)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Cleanup(func() { tx.Rollback(context.Background()) })
|
||||||
|
// S3 writes finish before variant metadata is inserted. Block that INSERT
|
||||||
|
// to kill the worker before the result COMMIT and broker acknowledgement.
|
||||||
|
if _, err := tx.Exec(ctx, "LOCK TABLE attachment_variants IN SHARE MODE"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
workerCommand(t, "compose", "run", "-d", "--no-deps", "--name", testWorker,
|
||||||
|
"-e", "JOB_TIMEOUT_SECONDS=15", "worker")
|
||||||
|
workerWait(t, "variant INSERT blocked after S3 writes", 10*time.Second, func() bool {
|
||||||
|
var blocked bool
|
||||||
|
if _, err := conn.Exec(ctx, "SELECT pg_stat_clear_snapshot()"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
err := conn.QueryRow(ctx, `SELECT EXISTS (
|
||||||
|
SELECT 1 FROM pg_stat_activity
|
||||||
|
WHERE $1::int = ANY(pg_blocking_pids(pid))
|
||||||
|
AND query LIKE '%INSERT INTO attachment_variants%'
|
||||||
|
)`, int32(conn.PgConn().PID())).Scan(&blocked)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return blocked
|
||||||
|
})
|
||||||
|
workerCommand(t, "kill", "--signal", "SIGKILL", testWorker)
|
||||||
|
if err := tx.Rollback(ctx); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if workerSQL(t, "SELECT status||':'||attempts FROM attachments WHERE id='"+id+"'") != "processing:1" ||
|
||||||
|
workerSQL(t, "SELECT count(*) FROM attachment_variants WHERE "+where) != "0" {
|
||||||
|
t.Fatal("crashed worker committed a result")
|
||||||
|
}
|
||||||
|
workerWait(t, "unacknowledged job returned to broker", 10*time.Second, func() bool {
|
||||||
|
return workerQueue(t) == "1:0"
|
||||||
|
})
|
||||||
|
|
||||||
|
// Leave lease_until unchanged: recovery must wait for its natural expiry.
|
||||||
|
compose(t, "start", "worker")
|
||||||
|
ready := waitAttachment(t, user, att.ID, "ready", 40*time.Second)
|
||||||
|
if len(ready.Variants) != 3 || !bytes.Equal(workerContent(t, user, att.ID, "original"), source) {
|
||||||
|
t.Fatal("lease recovery lost variants or changed original")
|
||||||
|
}
|
||||||
|
workerWait(t, "recovered job acknowledgement", 15*time.Second, func() bool {
|
||||||
|
return workerQueue(t) == "0:0"
|
||||||
|
})
|
||||||
|
if workerSQL(t, "SELECT job_id FROM attachments WHERE id='"+id+"'") != jobID ||
|
||||||
|
workerSQL(t, "SELECT attempts FROM attachments WHERE id='"+id+"'") != "2" ||
|
||||||
|
workerSQL(t, "SELECT count(*) FROM attachment_variants WHERE "+where) != "3" ||
|
||||||
|
workerSQL(t, "SELECT count(*) FROM outbox WHERE "+where+" AND attempt=2 AND published_at IS NOT NULL") != "1" {
|
||||||
|
t.Fatal("lease recovery replaced the job, duplicated variants or skipped retry publication")
|
||||||
|
}
|
||||||
|
t.Logf("PASS attachment=%s: SIGKILL after S3 writes, expired lease recovered, same job ready on attempt 2", id)
|
||||||
|
}
|
||||||
|
|||||||
+5
-1
@@ -8,7 +8,7 @@ ACTION ?= stop-one.sh
|
|||||||
ACTION_AT ?= 10s
|
ACTION_AT ?= 10s
|
||||||
DRY_RUN ?= true
|
DRY_RUN ?= true
|
||||||
|
|
||||||
.PHONY: help-go contract-go race-go load-go failure-go load-action-go reconcile reconcile-test-go worker-go
|
.PHONY: help-go contract-go race-go load-go failure-go load-action-go reconcile reconcile-test-go worker-go pipeline-go
|
||||||
|
|
||||||
help-go:
|
help-go:
|
||||||
@echo "contract-go: contract tests"
|
@echo "contract-go: contract tests"
|
||||||
@@ -17,6 +17,7 @@ help-go:
|
|||||||
@echo "load-go: load test"
|
@echo "load-go: load test"
|
||||||
@echo "failure-go: dependency failure tests (stops redis/postgres/s3 containers)"
|
@echo "failure-go: dependency failure tests (stops redis/postgres/s3 containers)"
|
||||||
@echo "reconcile: attachment audit; DRY_RUN=false to repair"
|
@echo "reconcile: attachment audit; DRY_RUN=false to repair"
|
||||||
|
@echo "pipeline-go: versioned pipeline tests (requires Compose; stops worker)"
|
||||||
|
|
||||||
contract-go:
|
contract-go:
|
||||||
go test -tags=contract ./student-tests/... -v -args -base-url=$(BASE_URL)
|
go test -tags=contract ./student-tests/... -v -args -base-url=$(BASE_URL)
|
||||||
@@ -46,3 +47,6 @@ reconcile-test-go:
|
|||||||
|
|
||||||
worker-go:
|
worker-go:
|
||||||
go test -count=1 -tags=worker ./student-tests/... -v -args -base-url=$(BASE_URL)
|
go test -count=1 -tags=worker ./student-tests/... -v -args -base-url=$(BASE_URL)
|
||||||
|
|
||||||
|
pipeline-go:
|
||||||
|
go test -count=1 -tags=nodynamic,pipeline ./student-tests/... -v -args -base-url=$(BASE_URL)
|
||||||
|
|||||||
Reference in New Issue
Block a user