forked from mtusi2026/mtusi2026lab5
Compare commits
21
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c872d95208 | ||
|
|
346720166b | ||
|
|
179c795758 | ||
|
|
f8ca7a7218 | ||
|
|
5442dfd3bc | ||
|
|
6ba7db4b7d | ||
|
|
6e09da0b46 | ||
|
|
f2000a7883 | ||
|
|
97b43a9c98 | ||
|
|
be10119910 | ||
|
|
73d57e31a5 | ||
|
|
9149dddf11 | ||
|
|
eafc437933 | ||
|
|
4a6176fe81 | ||
|
|
b35faa5af8 | ||
|
|
19152e7d18 | ||
|
|
8b0ab5440d | ||
|
|
4dbbd65bcf | ||
|
|
425ffc6182 | ||
|
|
d745395aa0 | ||
|
|
e889d2e292 |
@@ -25,6 +25,7 @@ MAX_UPLOAD_BYTES=10485760
|
||||
MAX_IMAGE_PIXELS=40000000
|
||||
|
||||
BROKER_URL_FILE=/run/secrets/broker_url
|
||||
BROKER_PASSWORD_FILE=/run/secrets/broker_password
|
||||
WORKER_CONCURRENCY=2
|
||||
JOB_MAX_ATTEMPTS=5
|
||||
JOB_TIMEOUT_SECONDS=60
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
FROM golang:1.27.1 AS build
|
||||
WORKDIR /src
|
||||
|
||||
COPY go.mod go.sum ./
|
||||
RUN go mod download
|
||||
|
||||
COPY . .
|
||||
RUN CGO_ENABLED=0 GOOS=linux go build -tags=nodynamic -o /out/worker ./cmd/worker
|
||||
|
||||
FROM gcr.io/distroless/static-debian12:nonroot
|
||||
WORKDIR /app
|
||||
COPY --from=build /out/worker .
|
||||
ENTRYPOINT ["/app/worker"]
|
||||
@@ -1,37 +1,146 @@
|
||||
# Отчёт — лабораторная 5
|
||||
|
||||
- Автор, группа: TODO
|
||||
- Целевая оценка; выбранный трек 5, если нужен: TODO
|
||||
- Commit/PR: TODO после публикации
|
||||
- Использованные источники, библиотеки и помощь ИИ: TODO
|
||||
- Автор, группа: Каменски Лин, БПИ2301
|
||||
- Целевая оценка; выбранный трек 5, если нужен: 5; трек 2
|
||||
- Commit/PR: [Pull Request 83](https://gitea.privcloud.tech/mtusi2026/mtusi2026lab5/pulls/83)
|
||||
- Использованные источники, библиотеки и помощь ИИ: материалы лабораторной; Go 1.27.1, 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
|
||||
|
||||
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 | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
|
||||
| --- | --- | --- | --- |
|
||||
| Публичный smoke | make test | TODO | TODO |
|
||||
| Остальные пункты уровня 3 | TODO | TODO | TODO |
|
||||
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO |
|
||||
| Выбранный трек 5, если заявлен | TODO | TODO | TODO |
|
||||
|
||||
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены.
|
||||
| Публичный smoke | `make test` | `PASS` | `evidence/make-test.txt` |
|
||||
| Уровень 3 |
|
||||
| JPEG, MIME, целостность, лимиты размера и пикселей, безопасный filename, проверка доступа к вложениям | `make contract-go` | `PASS` | `evidence/contract-go.txt` |
|
||||
| Сохранность задания после перезапуска 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` |
|
||||
| Уровень 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, без измерения пропускной способности и времени восстановления.
|
||||
|
||||
+12
-13
@@ -59,12 +59,13 @@ func run() error {
|
||||
return err
|
||||
}
|
||||
|
||||
reconciler := reconcile.New(s3Client, db.New(pool), log)
|
||||
reconciler := reconcile.New(pool, s3Client, db.New(pool), log)
|
||||
|
||||
report, err := reconciler.Run(ctx, reconcile.Options{
|
||||
DryRun: *dryRun,
|
||||
Grace: *grace,
|
||||
MaxDeletes: *maxDeletes,
|
||||
DryRun: *dryRun,
|
||||
Grace: *grace,
|
||||
MaxDeletes: *maxDeletes,
|
||||
StagingRetention: cfg.S3.StagingRetention,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -96,25 +97,26 @@ func printReport(report reconcile.Report) {
|
||||
report.ListPages,
|
||||
)
|
||||
fmt.Printf(
|
||||
"found orphan_objects=%d missing_attachments=%d stale_uploads=%d corrupt_objects=%d\n",
|
||||
"found staging_objects=%d orphan_objects=%d missing_attachments=%d corrupt_objects=%d\n",
|
||||
len(report.StagingObjects),
|
||||
len(report.OrphanObjects),
|
||||
len(report.MissingAttachments),
|
||||
len(report.StaleUploads),
|
||||
len(report.CorruptObjects),
|
||||
)
|
||||
fmt.Printf(
|
||||
"skipped fresh=%d referenced=%d inactive=%d\n",
|
||||
"skipped fresh=%d inactive=%d\n",
|
||||
report.SkippedFresh,
|
||||
report.SkippedReferenced,
|
||||
report.SkippedInactive,
|
||||
)
|
||||
fmt.Printf(
|
||||
"changes deleted_objects=%d deleted_rows=%d marked_failed=%d\n",
|
||||
"changes deleted_objects=%d marked_failed=%d\n",
|
||||
report.DeletedObjects,
|
||||
report.DeletedRows,
|
||||
report.MarkedFailed,
|
||||
)
|
||||
|
||||
for _, key := range report.StagingObjects {
|
||||
fmt.Printf("staging_object %s\n", key)
|
||||
}
|
||||
for _, key := range report.OrphanObjects {
|
||||
fmt.Printf("orphan_object %s\n", key)
|
||||
}
|
||||
@@ -124,9 +126,6 @@ func printReport(report reconcile.Report) {
|
||||
for _, id := range report.MissingAttachments {
|
||||
fmt.Printf("missing_attachment %s\n", id)
|
||||
}
|
||||
for _, id := range report.StaleUploads {
|
||||
fmt.Printf("stale_upload %s\n", id)
|
||||
}
|
||||
for _, message := range report.Errors {
|
||||
fmt.Printf("error %s\n", message)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,221 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/signal"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"github.com/joho/godotenv"
|
||||
|
||||
"mtusi2026-messenger/internal/config"
|
||||
"mtusi2026-messenger/internal/db"
|
||||
"mtusi2026-messenger/internal/logger"
|
||||
"mtusi2026-messenger/internal/postgres"
|
||||
s3store "mtusi2026-messenger/internal/s3"
|
||||
"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() {
|
||||
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)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
func runListFailed(ctx context.Context) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
|
||||
defer cancel()
|
||||
|
||||
_, pool, err := loadDatabase(ctx)
|
||||
if err != nil {
|
||||
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()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
log := logger.New(cfg.Logging.Level)
|
||||
storage, err := s3store.NewAPI(ctx, cfg.S3, log)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
w := worker.New(
|
||||
pool,
|
||||
storage,
|
||||
brokerURL,
|
||||
config.LoadWorker(),
|
||||
cfg.S3.MaxUploadBytes,
|
||||
cfg.S3.MaxImagePixels,
|
||||
log,
|
||||
)
|
||||
w.Run(ctx)
|
||||
|
||||
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
|
||||
}
|
||||
+63
-1
@@ -3,12 +3,13 @@ services:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
image: mtusi-messenger:lab4
|
||||
image: mtusi-messenger:lab5
|
||||
env_file:
|
||||
- .env
|
||||
secrets:
|
||||
- database_url
|
||||
- cache_url
|
||||
- broker_url
|
||||
- s3_access_key_id
|
||||
- s3_secret_access_key
|
||||
- s3_bootstrap_access_key_id
|
||||
@@ -26,6 +27,32 @@ services:
|
||||
condition: service_healthy
|
||||
restart: unless-stopped
|
||||
|
||||
worker:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile.worker
|
||||
image: mtusi-messenger-worker:lab5
|
||||
env_file:
|
||||
- .env
|
||||
secrets:
|
||||
- database_url
|
||||
- broker_url
|
||||
- s3_access_key_id
|
||||
- s3_secret_access_key
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
cpus: "1.0"
|
||||
memory: 1G
|
||||
depends_on:
|
||||
migrate:
|
||||
condition: service_completed_successfully
|
||||
s3:
|
||||
condition: service_healthy
|
||||
rabbitmq:
|
||||
condition: service_healthy
|
||||
restart: unless-stopped
|
||||
|
||||
postgres:
|
||||
image: postgres:18.6
|
||||
ports:
|
||||
@@ -81,6 +108,35 @@ services:
|
||||
memory: 128M
|
||||
restart: unless-stopped
|
||||
|
||||
rabbitmq:
|
||||
image: rabbitmq:4.2.9-alpine
|
||||
hostname: rabbitmq
|
||||
environment:
|
||||
RABBITMQ_DEFAULT_USER: messenger
|
||||
BROKER_PASSWORD_FILE: ${BROKER_PASSWORD_FILE:-/run/secrets/broker_password}
|
||||
entrypoint: ["/bin/sh", "-ec"]
|
||||
command:
|
||||
- |
|
||||
RABBITMQ_DEFAULT_PASS="$$(cat "$$BROKER_PASSWORD_FILE")"
|
||||
export RABBITMQ_DEFAULT_PASS
|
||||
exec docker-entrypoint.sh rabbitmq-server
|
||||
secrets:
|
||||
- broker_password
|
||||
volumes:
|
||||
- rabbitmq:/var/lib/rabbitmq
|
||||
healthcheck:
|
||||
test: ["CMD", "rabbitmq-diagnostics", "-q", "check_running"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 10
|
||||
start_period: 30s
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
cpus: "0.5"
|
||||
memory: 512M
|
||||
restart: unless-stopped
|
||||
|
||||
s3-config-init:
|
||||
build:
|
||||
context: .
|
||||
@@ -109,6 +165,7 @@ services:
|
||||
command:
|
||||
- "server"
|
||||
- "-dir=/data"
|
||||
- "-volume.max=10"
|
||||
- "-s3"
|
||||
- "-s3.port=9000"
|
||||
- "-s3.iam=false"
|
||||
@@ -181,6 +238,10 @@ secrets:
|
||||
file: ./secrets/database_url.txt
|
||||
cache_url:
|
||||
file: ./secrets/cache_url.txt
|
||||
broker_password:
|
||||
file: ./secrets/broker_password.txt
|
||||
broker_url:
|
||||
file: ./secrets/broker_url.txt
|
||||
s3_access_key_id:
|
||||
file: ./secrets/s3_access_key_id.txt
|
||||
s3_secret_access_key:
|
||||
@@ -194,3 +255,4 @@ volumes:
|
||||
pgdata:
|
||||
seaweedfs:
|
||||
s3config:
|
||||
rabbitmq:
|
||||
|
||||
@@ -6,6 +6,7 @@ ALTER TABLE attachments
|
||||
ADD COLUMN job_id uuid UNIQUE,
|
||||
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 retry_base int NOT NULL DEFAULT 0 CHECK (retry_base >= 0 AND retry_base <= attempts),
|
||||
ADD COLUMN width int CHECK (width > 0),
|
||||
ADD COLUMN height int CHECK (height > 0),
|
||||
ADD COLUMN lease_until timestamptz;
|
||||
@@ -34,12 +35,23 @@ CREATE TABLE outbox (
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
available_at timestamptz NOT NULL DEFAULT now(),
|
||||
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 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
|
||||
DROP TABLE attachment_replays;
|
||||
DROP TABLE outbox;
|
||||
DROP TABLE attachment_variants;
|
||||
DROP TYPE attachment_variant_name;
|
||||
@@ -48,6 +60,7 @@ ALTER TABLE attachments
|
||||
DROP COLUMN height,
|
||||
DROP COLUMN width,
|
||||
DROP COLUMN lease_until,
|
||||
DROP COLUMN retry_base,
|
||||
DROP COLUMN attempts,
|
||||
DROP COLUMN pipeline_version,
|
||||
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)
|
||||
);
|
||||
+66
-27
@@ -19,8 +19,8 @@ SELECT
|
||||
sqlc.arg(chat_id)::uuid,
|
||||
sqlc.arg(owner_id)::uuid,
|
||||
sqlc.arg(s3_key)::text,
|
||||
sqlc.narg(staging_key)::text,
|
||||
sqlc.narg(job_id)::uuid,
|
||||
sqlc.arg(staging_key)::text,
|
||||
sqlc.arg(job_id)::uuid,
|
||||
sqlc.arg(filename)::text,
|
||||
sqlc.arg(content_type)::attachment_content_type,
|
||||
sqlc.arg(size_bytes)::int,
|
||||
@@ -50,6 +50,11 @@ INSERT INTO message_attachments (
|
||||
SELECT * FROM attachments
|
||||
WHERE id = $1::uuid;
|
||||
|
||||
-- name: LockAttachmentByStagingKey :one
|
||||
SELECT * FROM attachments
|
||||
WHERE staging_key = sqlc.arg(staging_key)::text
|
||||
FOR UPDATE;
|
||||
|
||||
-- name: ListAttachmentsByIDs :many
|
||||
SELECT status
|
||||
FROM attachments
|
||||
@@ -68,22 +73,16 @@ FROM message_attachments
|
||||
WHERE message_id = ANY(sqlc.arg(message_ids)::uuid[])
|
||||
ORDER BY message_id, position;
|
||||
|
||||
-- name: ListStaleAttachmentUploads :many
|
||||
SELECT id, s3_key FROM attachments
|
||||
WHERE status = 'queued' AND created_at < sqlc.arg(cutoff)::timestamptz;
|
||||
|
||||
-- name: ListAttachmentsForReconcile :many
|
||||
SELECT
|
||||
a.id,
|
||||
a.s3_key,
|
||||
a.status,
|
||||
a.size_bytes,
|
||||
a.created_at,
|
||||
EXISTS (
|
||||
SELECT 1 FROM message_attachments ma
|
||||
WHERE ma.attachment_id = a.id
|
||||
) AS referenced
|
||||
FROM attachments a;
|
||||
SELECT id, s3_key, staging_key, status, size_bytes, updated_at
|
||||
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
|
||||
SELECT * FROM attachments
|
||||
@@ -103,11 +102,29 @@ ORDER BY lease_until, id
|
||||
LIMIT sqlc.arg(batch_size)::int
|
||||
FOR UPDATE SKIP LOCKED;
|
||||
|
||||
-- name: MarkAttachmentReady :one
|
||||
UPDATE attachments
|
||||
SET status = 'ready', updated_at = now()
|
||||
-- name: LockFailedAttachmentForReplay :one
|
||||
SELECT * FROM attachments
|
||||
WHERE id = sqlc.arg(id)::uuid
|
||||
RETURNING *;
|
||||
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
|
||||
UPDATE attachments
|
||||
SET staging_key = NULL
|
||||
WHERE id = sqlc.arg(id)::uuid;
|
||||
|
||||
-- name: MarkAttachmentFailedIfReady :execrows
|
||||
UPDATE attachments
|
||||
@@ -134,8 +151,6 @@ UPDATE attachments
|
||||
SET status = 'ready',
|
||||
error_code = NULL,
|
||||
lease_until = NULL,
|
||||
width = sqlc.arg(width)::int,
|
||||
height = sqlc.arg(height)::int,
|
||||
updated_at = now()
|
||||
WHERE id = sqlc.arg(id)::uuid
|
||||
AND status = 'processing'
|
||||
@@ -153,6 +168,34 @@ WHERE id = sqlc.arg(id)::uuid
|
||||
AND attempts = sqlc.arg(attempt)::int
|
||||
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
|
||||
UPDATE attachments
|
||||
SET status = 'failed',
|
||||
@@ -182,7 +225,3 @@ SET status = 'failed',
|
||||
WHERE id = sqlc.arg(id)::uuid
|
||||
AND status = 'processing'
|
||||
AND lease_until <= now();
|
||||
|
||||
-- name: DeleteQueuedAttachment :execrows
|
||||
DELETE FROM attachments
|
||||
WHERE id = sqlc.arg(id)::uuid AND status = 'queued';
|
||||
|
||||
@@ -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,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
|
||||
@@ -8,12 +8,16 @@ require (
|
||||
github.com/aws/aws-sdk-go-v2/credentials v1.20.13
|
||||
github.com/aws/aws-sdk-go-v2/service/s3 v1.114.6
|
||||
github.com/aws/smithy-go v1.28.7
|
||||
github.com/disintegration/imaging v1.6.2
|
||||
github.com/gen2brain/webp v0.6.4
|
||||
github.com/go-chi/chi/v5 v5.5.0
|
||||
github.com/google/uuid v1.6.0
|
||||
github.com/jackc/pgx/v5 v5.11.0
|
||||
github.com/joho/godotenv v1.5.1
|
||||
github.com/rabbitmq/amqp091-go v1.10.0
|
||||
github.com/redis/go-redis/v9 v9.23.0
|
||||
golang.org/x/crypto v0.58.0
|
||||
golang.org/x/image v0.48.0
|
||||
)
|
||||
|
||||
require (
|
||||
@@ -31,11 +35,12 @@ require (
|
||||
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.44.1 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/sts v1.51.6 // indirect
|
||||
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
||||
github.com/ebitengine/purego v0.10.1 // indirect
|
||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
||||
github.com/jackc/puddle/v2 v2.2.2 // indirect
|
||||
go.uber.org/atomic v1.12.0 // indirect
|
||||
golang.org/x/sync v0.24.0 // indirect
|
||||
golang.org/x/sys v0.49.0 // indirect
|
||||
golang.org/x/text v0.43.0 // indirect
|
||||
golang.org/x/sync v0.25.0 // indirect
|
||||
golang.org/x/sys v0.50.0 // indirect
|
||||
golang.org/x/text v0.44.0 // indirect
|
||||
)
|
||||
|
||||
@@ -41,6 +41,12 @@ github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0
|
||||
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
|
||||
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/disintegration/imaging v1.6.2 h1:w1LecBlG2Lnp8B3jk5zSuNqd7b4DXhcjwek1ei82L+c=
|
||||
github.com/disintegration/imaging v1.6.2/go.mod h1:44/5580QXChDfwIclfc/PCwrr44amcmDAg8hxG0Ewe4=
|
||||
github.com/ebitengine/purego v0.10.1 h1:dewVBCBT2GaMu1SrNTYxQhgQBethzfhiwvZiLGP/qyY=
|
||||
github.com/ebitengine/purego v0.10.1/go.mod h1:iIjxzd6CiRiOG0UyXP+V1+jWqUXVjPKLAI0mRfJZTmQ=
|
||||
github.com/gen2brain/webp v0.6.4 h1:SUDdmxADOAiPQ+5ylNmuHhuYf2dOi0KgKZHL5vpVCNU=
|
||||
github.com/gen2brain/webp v0.6.4/go.mod h1:iGWMaCSw7t3I/Cv9llzEKmpnR36S8lS8VL/ZVjxU0JE=
|
||||
github.com/go-chi/chi/v5 v5.5.0 h1:xdKQ1dJmVJsmgahrXSKhUx8NyVPzpwdlyrrQFpMPJgg=
|
||||
github.com/go-chi/chi/v5 v5.5.0/go.mod h1:d1IG7GtKPSjPyBP365PH8sAGVHk3qfB/IhjFNRH1wWM=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
@@ -58,6 +64,8 @@ github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwA
|
||||
github.com/klauspost/cpuid/v2 v2.4.0 h1:S6Hrbc7+ywsr0r+RLapfGBHfyefhCTwEh3A0tV913Dw=
|
||||
github.com/klauspost/cpuid/v2 v2.4.0/go.mod h1:19jmZ9mjzoF//ddRSUsv0zfBTJWh3QJh9FNxZTMrGxU=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/rabbitmq/amqp091-go v1.10.0 h1:STpn5XsHlHGcecLmMFCtg7mqq0RnD+zFr4uzukfVhBw=
|
||||
github.com/rabbitmq/amqp091-go v1.10.0/go.mod h1:Hy4jKW5kQART1u+JkDTF9YYOQUHXqMuhrgxOEeS7G4o=
|
||||
github.com/redis/go-redis/v9 v9.23.0 h1:/TTVdJa8BRNsybwwGGnmiYktHNlUXtbOQxlWpHBPL3s=
|
||||
github.com/redis/go-redis/v9 v9.23.0/go.mod h1:EWP2UUk+XDaI1s5nQB5mablZN6vccXlmBQTyfnF87D0=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
@@ -69,15 +77,21 @@ github.com/zeebo/xxh3 v1.1.0 h1:s7DLGDK45Dyfg7++yxI0khrfwq9661w9EN78eP/UZVs=
|
||||
github.com/zeebo/xxh3 v1.1.0/go.mod h1:IisAie1LELR4xhVinxWS5+zf1lA4p0MW4T+w+W07F5s=
|
||||
go.uber.org/atomic v1.12.0 h1:BvcXdFKuviU4fTL/f+SxdQ5qJX/Jix8pAkgdUcb3XOE=
|
||||
go.uber.org/atomic v1.12.0/go.mod h1:I6c4cg+6HCxRjfjSsYtApoFILnpc0CGUdGkXVqbYVNk=
|
||||
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
|
||||
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
|
||||
go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=
|
||||
go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
|
||||
golang.org/x/crypto v0.58.0 h1:COkYLr4k7nDI4r6QtMML2AfzeIswWHAJthLS6K/M/54=
|
||||
golang.org/x/crypto v0.58.0/go.mod h1:Xh+kl5A+M0gMiWDytH2Hhr5Z7WbNCpv/eB/EFgfSk+w=
|
||||
golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA=
|
||||
golang.org/x/sync v0.24.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
|
||||
golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA=
|
||||
golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
|
||||
golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc=
|
||||
golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s=
|
||||
golang.org/x/image v0.0.0-20191009234506-e7c1f5e7dbb8/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
|
||||
golang.org/x/image v0.48.0 h1:1AvuPcuoOTJpA7s4VZ5umrb90T3So0rkB/bSGmxkxik=
|
||||
golang.org/x/image v0.48.0/go.mod h1:mmtg64iqJKGqEgy+r13dfybl85tmxUd2lMnmaiSdWYY=
|
||||
golang.org/x/sync v0.25.0 h1:dJnifr0nMV8/SBnBvdo4eSGGnrc3O4FFx6IqvtLcmRs=
|
||||
golang.org/x/sync v0.25.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
|
||||
golang.org/x/sys v0.50.0 h1:dkKZEFTEKaLr1sjhs0WiKqoi8Jj5nHbS3Njmx1UoMJs=
|
||||
golang.org/x/sys v0.50.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.44.0 h1:YItdp/mQNGnsmrgpcdA5yQ3bnRxCfo/Tj/iByGW9GGo=
|
||||
golang.org/x/text v0.44.0/go.mod h1:S4FR1waQ9LbjQTls97SyRjDaUUVkaM+cXwwuG/G+MwY=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
|
||||
+20
-18
@@ -16,6 +16,7 @@ import (
|
||||
"mtusi2026-messenger/internal/config"
|
||||
"mtusi2026-messenger/internal/db"
|
||||
"mtusi2026-messenger/internal/logger"
|
||||
"mtusi2026-messenger/internal/outbox"
|
||||
"mtusi2026-messenger/internal/postgres"
|
||||
"mtusi2026-messenger/internal/redis"
|
||||
s3store "mtusi2026-messenger/internal/s3"
|
||||
@@ -80,34 +81,35 @@ func Run() error {
|
||||
|
||||
log.Info("s3 storage ready", "endpoint", cfg.S3.Endpoint, "bucket", s3Client.Bucket())
|
||||
|
||||
cleanupCtx, stopCleanup := context.WithCancel(context.Background())
|
||||
var cleanupWG sync.WaitGroup
|
||||
cleanupWG.Go(func() {
|
||||
runSessionCleanup(cleanupCtx, log, queries, sessionCleanupInterval)
|
||||
brokerURL, err := cfg.Broker.URL()
|
||||
if err != nil {
|
||||
log.Error("read broker url", "error", err)
|
||||
return err
|
||||
}
|
||||
publisher := outbox.NewPublisher(pool, brokerURL, log)
|
||||
|
||||
backgroundCtx, stopBackground := context.WithCancel(context.Background())
|
||||
var backgroundWG sync.WaitGroup
|
||||
backgroundWG.Go(func() {
|
||||
publisher.Run(backgroundCtx)
|
||||
})
|
||||
cleanupWG.Go(func() {
|
||||
runIdempotencyCleanup(cleanupCtx, log, queries, cfg.Server.IdempotencyTTL, idempotencyCleanupInterval)
|
||||
backgroundWG.Go(func() {
|
||||
runSessionCleanup(backgroundCtx, log, queries, sessionCleanupInterval)
|
||||
})
|
||||
cleanupWG.Go(func() {
|
||||
runAttachmentCleanup(
|
||||
cleanupCtx,
|
||||
log,
|
||||
queries,
|
||||
s3Client,
|
||||
attachmentOrphanGracePeriod,
|
||||
attachmentCleanupInterval,
|
||||
)
|
||||
backgroundWG.Go(func() {
|
||||
runIdempotencyCleanup(backgroundCtx, log, queries, cfg.Server.IdempotencyTTL, idempotencyCleanupInterval)
|
||||
})
|
||||
|
||||
defer func() {
|
||||
stopCleanup()
|
||||
cleanupWG.Wait()
|
||||
stopBackground()
|
||||
backgroundWG.Wait()
|
||||
}()
|
||||
|
||||
authService := service.NewAuthService(queries, rdb, cfg.Server.SessionTTL, log)
|
||||
userService := service.NewUserService(queries)
|
||||
chatService := service.NewChatService(pool, queries)
|
||||
messageService := service.NewMessageService(pool, queries)
|
||||
attachmentService := service.NewAttachmentService(queries, s3Client, cfg.S3.MaxUploadBytes, cfg.S3.MaxImagePixels)
|
||||
attachmentService := service.NewAttachmentService(pool, queries, s3Client, cfg.S3.MaxUploadBytes, cfg.S3.MaxImagePixels)
|
||||
|
||||
router := NewRouter(
|
||||
log,
|
||||
|
||||
@@ -4,18 +4,11 @@ import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"mtusi2026-messenger/internal/db"
|
||||
)
|
||||
|
||||
const (
|
||||
sessionCleanupInterval = time.Hour
|
||||
idempotencyCleanupInterval = time.Hour
|
||||
|
||||
attachmentCleanupInterval = 10 * time.Minute
|
||||
attachmentOrphanGracePeriod = time.Hour
|
||||
)
|
||||
|
||||
type sessionCleaner interface {
|
||||
@@ -26,15 +19,6 @@ type idempotencyCleaner interface {
|
||||
DeleteExpiredIdempotencyKeys(ctx context.Context, cutoff time.Time) (int64, error)
|
||||
}
|
||||
|
||||
type staleUploadLister interface {
|
||||
ListStaleAttachmentUploads(ctx context.Context, cutoff time.Time) ([]db.ListStaleAttachmentUploadsRow, error)
|
||||
DeleteQueuedAttachment(ctx context.Context, id uuid.UUID) (int64, error)
|
||||
}
|
||||
|
||||
type objectDeleter interface {
|
||||
DeleteAdmin(ctx context.Context, key string) error
|
||||
}
|
||||
|
||||
func runSessionCleanup(ctx context.Context, log *slog.Logger, q sessionCleaner, interval time.Duration) {
|
||||
ticker := time.NewTicker(interval)
|
||||
defer ticker.Stop()
|
||||
@@ -86,64 +70,3 @@ func runIdempotencyCleanup(
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func runAttachmentCleanup(
|
||||
ctx context.Context,
|
||||
log *slog.Logger,
|
||||
q staleUploadLister,
|
||||
store objectDeleter,
|
||||
grace time.Duration,
|
||||
interval time.Duration,
|
||||
) {
|
||||
ticker := time.NewTicker(interval)
|
||||
defer ticker.Stop()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
cleanupStaleUploads(ctx, log, q, store, grace)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func cleanupStaleUploads(
|
||||
ctx context.Context,
|
||||
log *slog.Logger,
|
||||
q staleUploadLister,
|
||||
store objectDeleter,
|
||||
grace time.Duration,
|
||||
) {
|
||||
cutoff := time.Now().Add(-grace)
|
||||
|
||||
rows, err := q.ListStaleAttachmentUploads(ctx, cutoff)
|
||||
if err != nil {
|
||||
if ctx.Err() == nil {
|
||||
log.Error("list stale attachment uploads", "error", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
deleted := 0
|
||||
|
||||
for _, row := range rows {
|
||||
removed, err := q.DeleteQueuedAttachment(ctx, row.ID)
|
||||
if err != nil {
|
||||
log.Error("delete stale upload row", "id", row.ID, "error", err)
|
||||
continue
|
||||
}
|
||||
if removed == 0 {
|
||||
continue
|
||||
}
|
||||
if err := store.DeleteAdmin(ctx, row.S3Key); err != nil {
|
||||
log.Error("delete stale upload object", "key", row.S3Key, "error", err)
|
||||
continue
|
||||
}
|
||||
deleted++
|
||||
}
|
||||
|
||||
if deleted > 0 {
|
||||
log.Info("stale attachment uploads deleted", "count", deleted)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,6 +20,7 @@ type Config struct {
|
||||
Logging LoggingConfig
|
||||
Database DatabaseConfig
|
||||
Redis RedisConfig
|
||||
Broker BrokerConfig
|
||||
S3 S3Config
|
||||
SessionStore string
|
||||
}
|
||||
@@ -57,6 +58,14 @@ func (c RedisConfig) URL() (string, error) {
|
||||
return readSecretFile(c.URLFile)
|
||||
}
|
||||
|
||||
type BrokerConfig struct {
|
||||
URLFile string
|
||||
}
|
||||
|
||||
func (c BrokerConfig) URL() (string, error) {
|
||||
return readSecretFile(c.URLFile)
|
||||
}
|
||||
|
||||
type S3Config struct {
|
||||
Endpoint string
|
||||
Region string
|
||||
@@ -67,6 +76,7 @@ type S3Config struct {
|
||||
BootstrapSecretKeyFile string
|
||||
MaxUploadBytes int
|
||||
MaxImagePixels int
|
||||
StagingRetention time.Duration
|
||||
}
|
||||
|
||||
func (c S3Config) APIAccessKey() (string, error) {
|
||||
@@ -108,6 +118,10 @@ func Load() Config {
|
||||
URLFile: getEnv("CACHE_URL_FILE", "/run/secrets/cache_url"),
|
||||
},
|
||||
|
||||
Broker: BrokerConfig{
|
||||
URLFile: getEnv("BROKER_URL_FILE", "/run/secrets/broker_url"),
|
||||
},
|
||||
|
||||
S3: LoadS3(),
|
||||
|
||||
SessionStore: getEnvSessionStore("SESSION_STORE", SessionStorePostgres),
|
||||
@@ -125,6 +139,21 @@ func LoadS3() S3Config {
|
||||
BootstrapSecretKeyFile: getEnv("S3_BOOTSTRAP_SECRET_ACCESS_KEY_FILE", "/run/secrets/s3_bootstrap_secret_access_key"),
|
||||
MaxUploadBytes: getEnvPositiveInt("MAX_UPLOAD_BYTES", 10485760),
|
||||
MaxImagePixels: getEnvPositiveInt("MAX_IMAGE_PIXELS", 40000000),
|
||||
StagingRetention: time.Duration(getEnvPositiveInt("STAGING_RETENTION_SECONDS", 86400)) * time.Second,
|
||||
}
|
||||
}
|
||||
|
||||
type WorkerConfig struct {
|
||||
Concurrency int
|
||||
MaxAttempts int
|
||||
Timeout time.Duration
|
||||
}
|
||||
|
||||
func LoadWorker() WorkerConfig {
|
||||
return WorkerConfig{
|
||||
Concurrency: getEnvPositiveInt("WORKER_CONCURRENCY", 2),
|
||||
MaxAttempts: getEnvPositiveInt("JOB_MAX_ATTEMPTS", 5),
|
||||
Timeout: time.Duration(getEnvPositiveInt("JOB_TIMEOUT_SECONDS", 60)) * time.Second,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
}
|
||||
+225
-105
@@ -23,7 +23,7 @@ WHERE id = $2::uuid
|
||||
AND pipeline_version = $4::int
|
||||
AND status = 'queued'
|
||||
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 {
|
||||
@@ -60,6 +60,7 @@ func (q *Queries) ClaimAttachmentJob(ctx context.Context, arg ClaimAttachmentJob
|
||||
&i.JobID,
|
||||
&i.PipelineVersion,
|
||||
&i.Attempts,
|
||||
&i.RetryBase,
|
||||
&i.Width,
|
||||
&i.Height,
|
||||
&i.LeaseUntil,
|
||||
@@ -67,34 +68,36 @@ func (q *Queries) ClaimAttachmentJob(ctx context.Context, arg ClaimAttachmentJob
|
||||
return i, err
|
||||
}
|
||||
|
||||
const clearAttachmentStagingKey = `-- name: ClearAttachmentStagingKey :exec
|
||||
UPDATE attachments
|
||||
SET staging_key = NULL
|
||||
WHERE id = $1::uuid
|
||||
`
|
||||
|
||||
func (q *Queries) ClearAttachmentStagingKey(ctx context.Context, id uuid.UUID) error {
|
||||
_, err := q.db.Exec(ctx, clearAttachmentStagingKey, id)
|
||||
return err
|
||||
}
|
||||
|
||||
const completeAttachmentJob = `-- name: CompleteAttachmentJob :execrows
|
||||
UPDATE attachments
|
||||
SET status = 'ready',
|
||||
error_code = NULL,
|
||||
lease_until = NULL,
|
||||
width = $1::int,
|
||||
height = $2::int,
|
||||
updated_at = now()
|
||||
WHERE id = $3::uuid
|
||||
WHERE id = $1::uuid
|
||||
AND status = 'processing'
|
||||
AND attempts = $4::int
|
||||
AND attempts = $2::int
|
||||
AND lease_until > now()
|
||||
`
|
||||
|
||||
type CompleteAttachmentJobParams struct {
|
||||
Width int
|
||||
Height int
|
||||
ID uuid.UUID
|
||||
Attempt int
|
||||
}
|
||||
|
||||
func (q *Queries) CompleteAttachmentJob(ctx context.Context, arg CompleteAttachmentJobParams) (int64, error) {
|
||||
result, err := q.db.Exec(ctx, completeAttachmentJob,
|
||||
arg.Width,
|
||||
arg.Height,
|
||||
arg.ID,
|
||||
arg.Attempt,
|
||||
)
|
||||
result, err := q.db.Exec(ctx, completeAttachmentJob, arg.ID, arg.Attempt)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
@@ -136,7 +139,7 @@ WHERE EXISTS (
|
||||
WHERE chat_id = $2
|
||||
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 {
|
||||
@@ -144,8 +147,8 @@ type CreateAttachmentParams struct {
|
||||
ChatID uuid.UUID
|
||||
OwnerID uuid.UUID
|
||||
S3Key string
|
||||
StagingKey *string
|
||||
JobID *uuid.UUID
|
||||
StagingKey string
|
||||
JobID uuid.UUID
|
||||
Filename string
|
||||
ContentType AttachmentContentType
|
||||
SizeBytes int
|
||||
@@ -189,6 +192,7 @@ func (q *Queries) CreateAttachment(ctx context.Context, arg CreateAttachmentPara
|
||||
&i.JobID,
|
||||
&i.PipelineVersion,
|
||||
&i.Attempts,
|
||||
&i.RetryBase,
|
||||
&i.Width,
|
||||
&i.Height,
|
||||
&i.LeaseUntil,
|
||||
@@ -219,19 +223,6 @@ func (q *Queries) CreateMessageAttachment(ctx context.Context, arg CreateMessage
|
||||
return err
|
||||
}
|
||||
|
||||
const deleteQueuedAttachment = `-- name: DeleteQueuedAttachment :execrows
|
||||
DELETE FROM attachments
|
||||
WHERE id = $1::uuid AND status = 'queued'
|
||||
`
|
||||
|
||||
func (q *Queries) DeleteQueuedAttachment(ctx context.Context, id uuid.UUID) (int64, error) {
|
||||
result, err := q.db.Exec(ctx, deleteQueuedAttachment, id)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.RowsAffected(), nil
|
||||
}
|
||||
|
||||
const failAttachmentJob = `-- name: FailAttachmentJob :execrows
|
||||
UPDATE attachments
|
||||
SET status = 'failed',
|
||||
@@ -278,7 +269,7 @@ func (q *Queries) FailExpiredAttachmentJob(ctx context.Context, id uuid.UUID) (i
|
||||
}
|
||||
|
||||
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
|
||||
`
|
||||
|
||||
@@ -302,6 +293,7 @@ func (q *Queries) GetAttachmentByID(ctx context.Context, dollar_1 uuid.UUID) (At
|
||||
&i.JobID,
|
||||
&i.PipelineVersion,
|
||||
&i.Attempts,
|
||||
&i.RetryBase,
|
||||
&i.Width,
|
||||
&i.Height,
|
||||
&i.LeaseUntil,
|
||||
@@ -342,26 +334,17 @@ func (q *Queries) ListAttachmentsByIDs(ctx context.Context, arg ListAttachmentsB
|
||||
}
|
||||
|
||||
const listAttachmentsForReconcile = `-- name: ListAttachmentsForReconcile :many
|
||||
SELECT
|
||||
a.id,
|
||||
a.s3_key,
|
||||
a.status,
|
||||
a.size_bytes,
|
||||
a.created_at,
|
||||
EXISTS (
|
||||
SELECT 1 FROM message_attachments ma
|
||||
WHERE ma.attachment_id = a.id
|
||||
) AS referenced
|
||||
FROM attachments a
|
||||
SELECT id, s3_key, staging_key, status, size_bytes, updated_at
|
||||
FROM attachments
|
||||
`
|
||||
|
||||
type ListAttachmentsForReconcileRow struct {
|
||||
ID uuid.UUID
|
||||
S3Key string
|
||||
StagingKey *string
|
||||
Status AttachmentStatus
|
||||
SizeBytes int
|
||||
CreatedAt time.Time
|
||||
Referenced bool
|
||||
UpdatedAt time.Time
|
||||
}
|
||||
|
||||
func (q *Queries) ListAttachmentsForReconcile(ctx context.Context) ([]ListAttachmentsForReconcileRow, error) {
|
||||
@@ -376,10 +359,52 @@ func (q *Queries) ListAttachmentsForReconcile(ctx context.Context) ([]ListAttach
|
||||
if err := rows.Scan(
|
||||
&i.ID,
|
||||
&i.S3Key,
|
||||
&i.StagingKey,
|
||||
&i.Status,
|
||||
&i.SizeBytes,
|
||||
&i.CreatedAt,
|
||||
&i.Referenced,
|
||||
&i.UpdatedAt,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
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
|
||||
}
|
||||
@@ -450,38 +475,79 @@ func (q *Queries) ListMessageAttachmentsByMessageIDs(ctx context.Context, messag
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const listStaleAttachmentUploads = `-- name: ListStaleAttachmentUploads :many
|
||||
SELECT id, s3_key FROM attachments
|
||||
WHERE status = 'queued' AND created_at < $1::timestamptz
|
||||
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, retry_base, width, height, lease_until FROM attachments
|
||||
WHERE staging_key = $1::text
|
||||
FOR UPDATE
|
||||
`
|
||||
|
||||
type ListStaleAttachmentUploadsRow struct {
|
||||
ID uuid.UUID
|
||||
S3Key string
|
||||
func (q *Queries) LockAttachmentByStagingKey(ctx context.Context, stagingKey string) (Attachment, error) {
|
||||
row := q.db.QueryRow(ctx, lockAttachmentByStagingKey, stagingKey)
|
||||
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
|
||||
}
|
||||
|
||||
func (q *Queries) ListStaleAttachmentUploads(ctx context.Context, cutoff time.Time) ([]ListStaleAttachmentUploadsRow, error) {
|
||||
rows, err := q.db.Query(ctx, listStaleAttachmentUploads, cutoff)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
items := []ListStaleAttachmentUploadsRow{}
|
||||
for rows.Next() {
|
||||
var i ListStaleAttachmentUploadsRow
|
||||
if err := rows.Scan(&i.ID, &i.S3Key); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
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.Height,
|
||||
&i.LeaseUntil,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
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
|
||||
AND status = 'processing'
|
||||
AND job_id = $2::uuid
|
||||
@@ -523,6 +589,7 @@ func (q *Queries) LockAttachmentJob(ctx context.Context, arg LockAttachmentJobPa
|
||||
&i.JobID,
|
||||
&i.PipelineVersion,
|
||||
&i.Attempts,
|
||||
&i.RetryBase,
|
||||
&i.Width,
|
||||
&i.Height,
|
||||
&i.LeaseUntil,
|
||||
@@ -531,7 +598,7 @@ func (q *Queries) LockAttachmentJob(ctx context.Context, arg LockAttachmentJobPa
|
||||
}
|
||||
|
||||
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'
|
||||
AND lease_until <= now()
|
||||
ORDER BY lease_until, id
|
||||
@@ -565,6 +632,7 @@ func (q *Queries) LockExpiredAttachmentJobs(ctx context.Context, batchSize int)
|
||||
&i.JobID,
|
||||
&i.PipelineVersion,
|
||||
&i.Attempts,
|
||||
&i.RetryBase,
|
||||
&i.Width,
|
||||
&i.Height,
|
||||
&i.LeaseUntil,
|
||||
@@ -579,6 +647,46 @@ func (q *Queries) LockExpiredAttachmentJobs(ctx context.Context, batchSize int)
|
||||
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
|
||||
UPDATE attachments
|
||||
SET status = 'failed',
|
||||
@@ -600,40 +708,6 @@ func (q *Queries) MarkAttachmentFailedIfReady(ctx context.Context, arg MarkAttac
|
||||
return result.RowsAffected(), nil
|
||||
}
|
||||
|
||||
const markAttachmentReady = `-- name: MarkAttachmentReady :one
|
||||
UPDATE attachments
|
||||
SET status = 'ready', updated_at = now()
|
||||
WHERE id = $1::uuid
|
||||
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
|
||||
`
|
||||
|
||||
func (q *Queries) MarkAttachmentReady(ctx context.Context, id uuid.UUID) (Attachment, error) {
|
||||
row := q.db.QueryRow(ctx, markAttachmentReady, 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.Width,
|
||||
&i.Height,
|
||||
&i.LeaseUntil,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const recoverExpiredAttachmentJob = `-- name: RecoverExpiredAttachmentJob :execrows
|
||||
UPDATE attachments
|
||||
SET status = 'queued',
|
||||
@@ -652,6 +726,30 @@ func (q *Queries) RecoverExpiredAttachmentJob(ctx context.Context, id uuid.UUID)
|
||||
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
|
||||
UPDATE attachments
|
||||
SET status = 'queued',
|
||||
@@ -677,3 +775,25 @@ func (q *Queries) RetryAttachmentJob(ctx context.Context, arg RetryAttachmentJob
|
||||
}
|
||||
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
|
||||
PipelineVersion int
|
||||
Attempts int
|
||||
RetryBase int
|
||||
Width *int32
|
||||
Height *int32
|
||||
LeaseUntil *time.Time
|
||||
}
|
||||
|
||||
type AttachmentReplay struct {
|
||||
AttachmentID uuid.UUID
|
||||
Attempt int
|
||||
PreviousErrorCode *string
|
||||
Operator string
|
||||
Reason string
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
type AttachmentVariant struct {
|
||||
AttachmentID uuid.UUID
|
||||
PipelineVersion int
|
||||
|
||||
+41
-22
@@ -19,27 +19,27 @@ type GetAttachmentContentRequest struct {
|
||||
}
|
||||
|
||||
type VariantResponse struct {
|
||||
Name string `json:"name"`
|
||||
ContentType string `json:"content_type"`
|
||||
SizeBytes int `json:"size_bytes"`
|
||||
Width int `json:"width"`
|
||||
Height int `json:"height"`
|
||||
Sha256 string `json:"sha256"`
|
||||
Name model.AttachmentVariantName `json:"name"`
|
||||
ContentType model.ContentType `json:"content_type"`
|
||||
SizeBytes int `json:"size_bytes"`
|
||||
Width int `json:"width"`
|
||||
Height int `json:"height"`
|
||||
Sha256 string `json:"sha256"`
|
||||
}
|
||||
|
||||
type AttachmentResponse struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
ChatID uuid.UUID `json:"chat_id"`
|
||||
OwnerID uuid.UUID `json:"owner_id"`
|
||||
Filename string `json:"filename"`
|
||||
ContentType string `json:"content_type"`
|
||||
SizeBytes int `json:"size_bytes"`
|
||||
Sha256 string `json:"sha256"`
|
||||
Status string `json:"status"`
|
||||
Variants []VariantResponse `json:"variants"`
|
||||
ErrorCode *string `json:"error_code"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
ID uuid.UUID `json:"id"`
|
||||
ChatID uuid.UUID `json:"chat_id"`
|
||||
OwnerID uuid.UUID `json:"owner_id"`
|
||||
Filename string `json:"filename"`
|
||||
ContentType model.ContentType `json:"content_type"`
|
||||
SizeBytes int `json:"size_bytes"`
|
||||
Sha256 string `json:"sha256"`
|
||||
Status model.AttachmentStatus `json:"status"`
|
||||
Variants []VariantResponse `json:"variants"`
|
||||
ErrorCode *string `json:"error_code"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
func (r CreateAttachmentRequest) Validate() bool {
|
||||
@@ -57,20 +57,39 @@ func (r CreateAttachmentRequest) Validate() bool {
|
||||
}
|
||||
|
||||
func (r GetAttachmentContentRequest) Validate() bool {
|
||||
return r.Variant == "" || r.Variant == "original"
|
||||
switch model.AttachmentVariantName(r.Variant) {
|
||||
case "",
|
||||
model.AttachmentContentOriginal,
|
||||
model.AttachmentVariantNameThumbnail,
|
||||
model.AttachmentVariantNameCrop,
|
||||
model.AttachmentVariantNameOptimized:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func ToAttachmentResponse(a model.Attachment) AttachmentResponse {
|
||||
variants := make([]VariantResponse, 0)
|
||||
variants := make([]VariantResponse, 0, len(a.Variants))
|
||||
for _, v := range a.Variants {
|
||||
variants = append(variants, VariantResponse{
|
||||
Name: v.Name,
|
||||
ContentType: v.ContentType,
|
||||
SizeBytes: v.SizeBytes,
|
||||
Width: v.Width,
|
||||
Height: v.Height,
|
||||
Sha256: v.Sha256,
|
||||
})
|
||||
}
|
||||
return AttachmentResponse{
|
||||
ID: a.ID,
|
||||
ChatID: a.ChatID,
|
||||
OwnerID: a.OwnerID,
|
||||
Filename: a.Filename,
|
||||
ContentType: string(a.ContentType),
|
||||
ContentType: a.ContentType,
|
||||
SizeBytes: a.SizeBytes,
|
||||
Sha256: a.Sha256,
|
||||
Status: string(a.Status),
|
||||
Status: a.Status,
|
||||
Variants: variants,
|
||||
ErrorCode: a.ErrorCode,
|
||||
CreatedAt: a.CreatedAt,
|
||||
|
||||
@@ -77,7 +77,7 @@ func (h *AttachmentHandler) Upload(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
httpx.WriteJSON(w, http.StatusCreated, dto.ToAttachmentResponse(att))
|
||||
httpx.WriteJSON(w, http.StatusAccepted, dto.ToAttachmentResponse(att))
|
||||
}
|
||||
|
||||
func (h *AttachmentHandler) Get(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -121,7 +121,7 @@ func (h *AttachmentHandler) GetContent(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
data, contentType, err := h.service.GetContent(r.Context(), userID, attachmentID)
|
||||
data, contentType, err := h.service.GetContent(r.Context(), userID, attachmentID, req.Variant)
|
||||
switch {
|
||||
case errors.Is(err, service.ErrAttachmentNotReady):
|
||||
httpx.WriteError(w, http.StatusConflict, dto.ErrorCodeConflict, "attachment not ready", requestID)
|
||||
|
||||
@@ -11,15 +11,39 @@ type ContentType string
|
||||
const (
|
||||
ContentTypePNG ContentType = "image/png"
|
||||
ContentTypeJPEG ContentType = "image/jpeg"
|
||||
ContentTypeWebP ContentType = "image/webp"
|
||||
)
|
||||
|
||||
type AttachmentStatus string
|
||||
|
||||
const (
|
||||
AttachmentStatusReady AttachmentStatus = "ready"
|
||||
AttachmentStatusQueued AttachmentStatus = "queued"
|
||||
AttachmentStatusProcessing AttachmentStatus = "processing"
|
||||
AttachmentStatusReady AttachmentStatus = "ready"
|
||||
AttachmentStatusFailed AttachmentStatus = "failed"
|
||||
)
|
||||
|
||||
const AttachmentContentOriginal = "original"
|
||||
|
||||
type AttachmentVariantName string
|
||||
|
||||
const (
|
||||
AttachmentVariantNameThumbnail AttachmentVariantName = "thumbnail"
|
||||
AttachmentVariantNameCrop AttachmentVariantName = "crop"
|
||||
AttachmentVariantNameOptimized AttachmentVariantName = "optimized"
|
||||
)
|
||||
|
||||
type AttachmentVariant struct {
|
||||
Name AttachmentVariantName
|
||||
ContentType ContentType
|
||||
SizeBytes int
|
||||
Width int
|
||||
Height int
|
||||
Sha256 string
|
||||
}
|
||||
|
||||
type Attachment struct {
|
||||
Variants []AttachmentVariant
|
||||
ID uuid.UUID
|
||||
ChatID uuid.UUID
|
||||
OwnerID uuid.UUID
|
||||
@@ -28,6 +52,8 @@ type Attachment struct {
|
||||
SizeBytes int
|
||||
Sha256 string
|
||||
Status AttachmentStatus
|
||||
Width *int32
|
||||
Height *int32
|
||||
ErrorCode *string
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type AttachmentJob struct {
|
||||
SchemaVersion int `json:"schema_version"`
|
||||
JobID uuid.UUID `json:"job_id"`
|
||||
Type string `json:"type"`
|
||||
AttachmentID uuid.UUID `json:"attachment_id"`
|
||||
PipelineVersion int `json:"pipeline_version"`
|
||||
Attempt int `json:"attempt"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
package outbox
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"mtusi2026-messenger/internal/db"
|
||||
"mtusi2026-messenger/internal/model"
|
||||
"mtusi2026-messenger/internal/rabbitmq"
|
||||
)
|
||||
|
||||
const (
|
||||
pollInterval = time.Second
|
||||
retryInterval = 2 * time.Second
|
||||
publishTimeout = 5 * time.Second
|
||||
)
|
||||
|
||||
type Publisher struct {
|
||||
pool *pgxpool.Pool
|
||||
url string
|
||||
log *slog.Logger
|
||||
}
|
||||
|
||||
func NewPublisher(pool *pgxpool.Pool, url string, log *slog.Logger) *Publisher {
|
||||
return &Publisher{
|
||||
pool: pool,
|
||||
url: url,
|
||||
log: log,
|
||||
}
|
||||
}
|
||||
|
||||
func (p *Publisher) Run(ctx context.Context) {
|
||||
for ctx.Err() == nil {
|
||||
client, err := rabbitmq.New(p.url)
|
||||
if err == nil {
|
||||
p.log.Info("outbox publisher connected")
|
||||
err = p.publish(ctx, client)
|
||||
_ = client.Close()
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
p.log.Error("outbox publisher retry", "error", err)
|
||||
if !wait(ctx, retryInterval) {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (p *Publisher) publish(ctx context.Context, client *rabbitmq.Client) error {
|
||||
for ctx.Err() == nil {
|
||||
published, err := p.publishOne(ctx, client)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !published && !wait(ctx, pollInterval) {
|
||||
return ctx.Err()
|
||||
}
|
||||
}
|
||||
return ctx.Err()
|
||||
}
|
||||
|
||||
func (p *Publisher) publishOne(ctx context.Context, client *rabbitmq.Client) (bool, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, publishTimeout)
|
||||
defer cancel()
|
||||
|
||||
tx, err := p.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
|
||||
q := db.New(tx)
|
||||
rows, err := q.LockPendingOutboxEntries(ctx, 1)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if len(rows) == 0 {
|
||||
return false, nil
|
||||
}
|
||||
row := rows[0]
|
||||
body, err := json.Marshal(model.AttachmentJob{
|
||||
SchemaVersion: 1,
|
||||
JobID: row.JobID,
|
||||
Type: "attachment.process.v1",
|
||||
AttachmentID: row.AttachmentID,
|
||||
PipelineVersion: row.PipelineVersion,
|
||||
Attempt: row.Attempt,
|
||||
CreatedAt: row.CreatedAt.UTC(),
|
||||
})
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if err := client.Publish(ctx, row.JobID.String(), body); err != nil {
|
||||
return false, err
|
||||
}
|
||||
if _, err := q.MarkOutboxPublished(ctx, row.ID); err != nil {
|
||||
return false, err
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return false, err
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func wait(ctx context.Context, delay time.Duration) bool {
|
||||
timer := time.NewTimer(delay)
|
||||
defer timer.Stop()
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return false
|
||||
case <-timer.C:
|
||||
return true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
package rabbitmq
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
amqp "github.com/rabbitmq/amqp091-go"
|
||||
)
|
||||
|
||||
const QueueName = "attachments.process.v1"
|
||||
|
||||
var (
|
||||
ErrConnect = errors.New("connect to rabbitmq")
|
||||
ErrNotRouted = errors.New("rabbitmq message not routed")
|
||||
ErrNack = errors.New("rabbitmq publish rejected")
|
||||
ErrPrefetch = errors.New("rabbitmq prefetch must be positive")
|
||||
)
|
||||
|
||||
type Client struct {
|
||||
conn *amqp.Connection
|
||||
channel *amqp.Channel
|
||||
returns <-chan amqp.Return
|
||||
}
|
||||
|
||||
func New(url string) (*Client, error) {
|
||||
conn, err := amqp.DialConfig(url, amqp.Config{
|
||||
Dial: amqp.DefaultDial(5 * time.Second),
|
||||
})
|
||||
if err != nil {
|
||||
return nil, ErrConnect
|
||||
}
|
||||
|
||||
channel, err := conn.Channel()
|
||||
if err != nil {
|
||||
_ = conn.CloseDeadline(time.Now().Add(time.Second))
|
||||
return nil, err
|
||||
}
|
||||
if _, err := channel.QueueDeclare(QueueName, true, false, false, false, nil); err != nil {
|
||||
_ = conn.CloseDeadline(time.Now().Add(time.Second))
|
||||
return nil, err
|
||||
}
|
||||
if err := channel.Confirm(false); err != nil {
|
||||
_ = conn.CloseDeadline(time.Now().Add(time.Second))
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &Client{
|
||||
conn: conn,
|
||||
channel: channel,
|
||||
returns: channel.NotifyReturn(make(chan amqp.Return, 1)),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Publish must not be called concurrently on the same client.
|
||||
func (c *Client) Publish(ctx context.Context, messageID string, body []byte) error {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
stop := context.AfterFunc(ctx, func() {
|
||||
_ = c.conn.CloseDeadline(time.Now())
|
||||
})
|
||||
defer stop()
|
||||
|
||||
confirmation, err := c.channel.PublishWithDeferredConfirm("", QueueName, true, false, amqp.Publishing{
|
||||
ContentType: "application/json",
|
||||
DeliveryMode: amqp.Persistent,
|
||||
MessageId: messageID,
|
||||
Body: body,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ack, err := confirmation.WaitContext(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !ack {
|
||||
return ErrNack
|
||||
}
|
||||
|
||||
select {
|
||||
case _, ok := <-c.returns:
|
||||
if !ok {
|
||||
return amqp.ErrClosed
|
||||
}
|
||||
return ErrNotRouted
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Client) Consume(ctx context.Context, prefetch int) (<-chan amqp.Delivery, error) {
|
||||
if prefetch < 1 {
|
||||
return nil, ErrPrefetch
|
||||
}
|
||||
if err := c.channel.Qos(prefetch, 0, false); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return c.channel.ConsumeWithContext(ctx, QueueName, "", false, false, false, false, nil)
|
||||
}
|
||||
|
||||
func (c *Client) Close() error {
|
||||
return c.conn.CloseDeadline(time.Now().Add(time.Second))
|
||||
}
|
||||
+100
-72
@@ -8,37 +8,40 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"mtusi2026-messenger/internal/db"
|
||||
s3store "mtusi2026-messenger/internal/s3"
|
||||
)
|
||||
|
||||
const (
|
||||
Prefix = "chats/"
|
||||
DefaultGrace = time.Hour
|
||||
DefaultMaxDeletes = 100
|
||||
ErrorCodeObjectMissing = "object_missing"
|
||||
Prefix = "chats/"
|
||||
StagingPrefix = "staging/"
|
||||
DefaultStagingRetention = 24 * time.Hour
|
||||
DefaultGrace = time.Hour
|
||||
DefaultMaxDeletes = 100
|
||||
ErrorCodeObjectMissing = "object_missing"
|
||||
)
|
||||
|
||||
type Options struct {
|
||||
DryRun bool
|
||||
Grace time.Duration
|
||||
MaxDeletes int
|
||||
DryRun bool
|
||||
Grace time.Duration
|
||||
MaxDeletes int
|
||||
StagingRetention time.Duration
|
||||
}
|
||||
|
||||
type Report struct {
|
||||
ScannedObjects int `json:"scanned_objects"`
|
||||
ScannedRows int `json:"scanned_rows"`
|
||||
ListPages int `json:"list_pages"`
|
||||
StagingObjects []string `json:"staging_objects"`
|
||||
OrphanObjects []string `json:"orphan_objects"`
|
||||
MissingAttachments []uuid.UUID `json:"missing_attachments"`
|
||||
StaleUploads []uuid.UUID `json:"stale_uploads"`
|
||||
CorruptObjects []string `json:"corrupt_objects"`
|
||||
SkippedFresh int `json:"skipped_fresh"`
|
||||
SkippedReferenced int `json:"skipped_referenced"`
|
||||
SkippedInactive int `json:"skipped_inactive"`
|
||||
DeletedObjects int `json:"deleted_objects"`
|
||||
DeletedRows int `json:"deleted_rows"`
|
||||
MarkedFailed int `json:"marked_failed"`
|
||||
DryRun bool `json:"dry_run"`
|
||||
Errors []string `json:"errors"`
|
||||
@@ -50,35 +53,50 @@ type ObjectClient interface {
|
||||
DeleteAdmin(ctx context.Context, key string) error
|
||||
}
|
||||
|
||||
type txBeginner interface {
|
||||
Begin(ctx context.Context) (pgx.Tx, error)
|
||||
}
|
||||
|
||||
type AttachmentQueries interface {
|
||||
LockAttachmentByStagingKey(ctx context.Context, stagingKey string) (db.Attachment, error)
|
||||
ClearAttachmentStagingKey(ctx context.Context, id uuid.UUID) error
|
||||
ListAttachmentsForReconcile(ctx context.Context) ([]db.ListAttachmentsForReconcileRow, error)
|
||||
DeleteQueuedAttachment(ctx context.Context, id uuid.UUID) (int64, error)
|
||||
MarkAttachmentFailedIfReady(ctx context.Context, arg db.MarkAttachmentFailedIfReadyParams) (int64, error)
|
||||
}
|
||||
|
||||
type Reconciler struct {
|
||||
q AttachmentQueries
|
||||
store ObjectClient
|
||||
log *slog.Logger
|
||||
now func() time.Time
|
||||
pool txBeginner
|
||||
q AttachmentQueries
|
||||
withTx func(pgx.Tx) AttachmentQueries
|
||||
store ObjectClient
|
||||
log *slog.Logger
|
||||
now func() time.Time
|
||||
}
|
||||
|
||||
type plan struct {
|
||||
orphans []s3store.ObjectInfo
|
||||
staleUploads []db.ListAttachmentsForReconcileRow
|
||||
missing []db.ListAttachmentsForReconcileRow
|
||||
corrupt []s3store.ObjectInfo
|
||||
skippedFresh int
|
||||
skippedReferenced int
|
||||
skippedInactive int
|
||||
orphans []s3store.ObjectInfo
|
||||
staging []s3store.ObjectInfo
|
||||
missing []db.ListAttachmentsForReconcileRow
|
||||
corrupt []s3store.ObjectInfo
|
||||
skippedFresh int
|
||||
skippedInactive int
|
||||
}
|
||||
|
||||
func New(store ObjectClient, queries AttachmentQueries, log *slog.Logger) *Reconciler {
|
||||
func New(
|
||||
pool *pgxpool.Pool,
|
||||
store ObjectClient,
|
||||
queries *db.Queries,
|
||||
log *slog.Logger,
|
||||
) *Reconciler {
|
||||
if log == nil {
|
||||
log = slog.Default()
|
||||
}
|
||||
|
||||
return &Reconciler{
|
||||
pool: pool,
|
||||
withTx: func(tx pgx.Tx) AttachmentQueries {
|
||||
return queries.WithTx(tx)
|
||||
},
|
||||
store: store,
|
||||
q: queries,
|
||||
log: log,
|
||||
@@ -92,8 +110,8 @@ func (r *Reconciler) Run(ctx context.Context, opts Options) (Report, error) {
|
||||
|
||||
report := Report{
|
||||
OrphanObjects: []string{},
|
||||
StagingObjects: []string{},
|
||||
MissingAttachments: []uuid.UUID{},
|
||||
StaleUploads: []uuid.UUID{},
|
||||
CorruptObjects: []string{},
|
||||
DryRun: opts.DryRun,
|
||||
Errors: []string{},
|
||||
@@ -104,32 +122,36 @@ func (r *Reconciler) Run(ctx context.Context, opts Options) (Report, error) {
|
||||
return report, err
|
||||
}
|
||||
|
||||
staging, err := r.store.ListAll(ctx, StagingPrefix)
|
||||
if err != nil {
|
||||
return report, err
|
||||
}
|
||||
|
||||
rows, err := r.q.ListAttachmentsForReconcile(ctx)
|
||||
if err != nil {
|
||||
return report, err
|
||||
}
|
||||
|
||||
report.ScannedObjects = len(listed.Objects)
|
||||
report.ScannedObjects = len(listed.Objects) + len(staging.Objects)
|
||||
report.ScannedRows = len(rows)
|
||||
report.ListPages = listed.Pages
|
||||
report.ListPages = listed.Pages + staging.Pages
|
||||
|
||||
p := buildPlan(listed.Objects, rows, started, opts.Grace)
|
||||
p := buildPlan(listed.Objects, staging.Objects, rows, started, opts)
|
||||
|
||||
for _, obj := range p.orphans {
|
||||
report.OrphanObjects = append(report.OrphanObjects, obj.Key)
|
||||
}
|
||||
for _, obj := range p.staging {
|
||||
report.StagingObjects = append(report.StagingObjects, obj.Key)
|
||||
}
|
||||
for _, obj := range p.corrupt {
|
||||
report.CorruptObjects = append(report.CorruptObjects, obj.Key)
|
||||
}
|
||||
for _, row := range p.staleUploads {
|
||||
report.StaleUploads = append(report.StaleUploads, row.ID)
|
||||
}
|
||||
for _, row := range p.missing {
|
||||
report.MissingAttachments = append(report.MissingAttachments, row.ID)
|
||||
}
|
||||
|
||||
report.SkippedFresh = p.skippedFresh
|
||||
report.SkippedReferenced = p.skippedReferenced
|
||||
report.SkippedInactive = p.skippedInactive
|
||||
|
||||
if !opts.DryRun {
|
||||
@@ -145,11 +167,10 @@ func (r *Reconciler) Run(ctx context.Context, opts Options) (Report, error) {
|
||||
"scanned_rows", report.ScannedRows,
|
||||
"list_pages", report.ListPages,
|
||||
"orphan_objects", len(report.OrphanObjects),
|
||||
"staging_objects", len(report.StagingObjects),
|
||||
"missing_attachments", len(report.MissingAttachments),
|
||||
"stale_uploads", len(report.StaleUploads),
|
||||
"corrupt_objects", len(report.CorruptObjects),
|
||||
"deleted_objects", report.DeletedObjects,
|
||||
"deleted_rows", report.DeletedRows,
|
||||
"marked_failed", report.MarkedFailed,
|
||||
"errors", len(report.Errors),
|
||||
)
|
||||
@@ -165,14 +186,19 @@ func (o Options) withDefaults() Options {
|
||||
o.MaxDeletes = DefaultMaxDeletes
|
||||
}
|
||||
|
||||
if o.StagingRetention <= 0 {
|
||||
o.StagingRetention = DefaultStagingRetention
|
||||
}
|
||||
|
||||
return o
|
||||
}
|
||||
|
||||
func buildPlan(
|
||||
objects []s3store.ObjectInfo,
|
||||
staging []s3store.ObjectInfo,
|
||||
rows []db.ListAttachmentsForReconcileRow,
|
||||
now time.Time,
|
||||
grace time.Duration,
|
||||
opts Options,
|
||||
) plan {
|
||||
var p plan
|
||||
|
||||
@@ -181,7 +207,12 @@ func buildPlan(
|
||||
byKey[obj.Key] = obj
|
||||
}
|
||||
|
||||
byStagingKey := make(map[string]db.ListAttachmentsForReconcileRow, len(rows))
|
||||
for _, row := range rows {
|
||||
if row.StagingKey != nil {
|
||||
byStagingKey[*row.StagingKey] = row
|
||||
}
|
||||
|
||||
obj, exists := byKey[row.S3Key]
|
||||
if exists {
|
||||
delete(byKey, row.S3Key)
|
||||
@@ -189,15 +220,7 @@ func buildPlan(
|
||||
|
||||
switch row.Status {
|
||||
case db.AttachmentStatusQueued:
|
||||
if now.Sub(row.CreatedAt) < grace {
|
||||
p.skippedFresh++
|
||||
continue
|
||||
}
|
||||
if row.Referenced {
|
||||
p.skippedReferenced++
|
||||
continue
|
||||
}
|
||||
p.staleUploads = append(p.staleUploads, row)
|
||||
p.skippedInactive++
|
||||
case db.AttachmentStatusReady:
|
||||
if !exists {
|
||||
p.missing = append(p.missing, row)
|
||||
@@ -214,22 +237,41 @@ func buildPlan(
|
||||
}
|
||||
|
||||
for _, obj := range byKey {
|
||||
if now.Sub(obj.LastModified) < grace {
|
||||
if now.Sub(obj.LastModified) < opts.Grace {
|
||||
p.skippedFresh++
|
||||
continue
|
||||
}
|
||||
p.orphans = append(p.orphans, obj)
|
||||
}
|
||||
|
||||
for _, obj := range staging {
|
||||
retainedSince := obj.LastModified
|
||||
if row, exists := byStagingKey[obj.Key]; exists {
|
||||
if row.Status != db.AttachmentStatusReady && row.Status != db.AttachmentStatusFailed {
|
||||
p.skippedInactive++
|
||||
continue
|
||||
}
|
||||
|
||||
retainedSince = row.UpdatedAt
|
||||
}
|
||||
|
||||
if now.Sub(retainedSince) < opts.StagingRetention {
|
||||
p.skippedFresh++
|
||||
continue
|
||||
}
|
||||
|
||||
p.staging = append(p.staging, obj)
|
||||
}
|
||||
|
||||
sort.Slice(p.staging, func(i, j int) bool {
|
||||
return p.staging[i].Key < p.staging[j].Key
|
||||
})
|
||||
sort.Slice(p.orphans, func(i, j int) bool {
|
||||
return p.orphans[i].Key < p.orphans[j].Key
|
||||
})
|
||||
sort.Slice(p.corrupt, func(i, j int) bool {
|
||||
return p.corrupt[i].Key < p.corrupt[j].Key
|
||||
})
|
||||
sort.Slice(p.staleUploads, func(i, j int) bool {
|
||||
return p.staleUploads[i].ID.String() < p.staleUploads[j].ID.String()
|
||||
})
|
||||
sort.Slice(p.missing, func(i, j int) bool {
|
||||
return p.missing[i].ID.String() < p.missing[j].ID.String()
|
||||
})
|
||||
@@ -240,31 +282,6 @@ func buildPlan(
|
||||
func (r *Reconciler) apply(ctx context.Context, opts Options, p plan, report *Report) {
|
||||
deletes := 0
|
||||
|
||||
for _, row := range p.staleUploads {
|
||||
if deletes >= opts.MaxDeletes {
|
||||
report.Errors = append(report.Errors, "max deletes reached")
|
||||
break
|
||||
}
|
||||
|
||||
removed, err := r.q.DeleteQueuedAttachment(ctx, row.ID)
|
||||
if err != nil {
|
||||
report.Errors = append(report.Errors, fmt.Sprintf("delete row %s: %v", row.ID, err))
|
||||
continue
|
||||
}
|
||||
if removed == 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
deletes++
|
||||
report.DeletedRows++
|
||||
|
||||
if err := r.store.DeleteAdmin(ctx, row.S3Key); err != nil {
|
||||
report.Errors = append(report.Errors, fmt.Sprintf("delete object %s: %v", row.S3Key, err))
|
||||
continue
|
||||
}
|
||||
report.DeletedObjects++
|
||||
}
|
||||
|
||||
for _, obj := range p.orphans {
|
||||
if deletes >= opts.MaxDeletes {
|
||||
report.Errors = append(report.Errors, "max deletes reached")
|
||||
@@ -292,4 +309,15 @@ func (r *Reconciler) apply(ctx context.Context, opts Options, p plan, report *Re
|
||||
|
||||
report.MarkedFailed += int(marked)
|
||||
}
|
||||
|
||||
for _, obj := range p.staging {
|
||||
if report.DeletedObjects >= opts.MaxDeletes {
|
||||
report.Errors = append(report.Errors, "max deletes reached")
|
||||
break
|
||||
}
|
||||
|
||||
if err := r.cleanupStagingObject(ctx, obj, opts, report); err != nil {
|
||||
report.Errors = append(report.Errors, fmt.Sprintf("cleanup staging %s: %v", obj.Key, err))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
package reconcile
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"mtusi2026-messenger/internal/db"
|
||||
s3store "mtusi2026-messenger/internal/s3"
|
||||
)
|
||||
|
||||
func (r *Reconciler) cleanupStagingObject(
|
||||
ctx context.Context,
|
||||
obj s3store.ObjectInfo,
|
||||
opts Options,
|
||||
report *Report,
|
||||
) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
tx, err := r.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback(context.Background())
|
||||
|
||||
q := r.withTx(tx)
|
||||
row, err := q.LockAttachmentByStagingKey(ctx, obj.Key)
|
||||
orphan := errors.Is(err, pgx.ErrNoRows)
|
||||
if err != nil && !orphan {
|
||||
return err
|
||||
}
|
||||
|
||||
if !orphan {
|
||||
if row.Status != db.AttachmentStatusReady && row.Status != db.AttachmentStatusFailed {
|
||||
report.SkippedInactive++
|
||||
return nil
|
||||
}
|
||||
|
||||
if r.now().Sub(row.UpdatedAt) < opts.StagingRetention {
|
||||
report.SkippedFresh++
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
if err := r.store.DeleteAdmin(ctx, obj.Key); err != nil {
|
||||
return err
|
||||
}
|
||||
report.DeletedObjects++
|
||||
|
||||
if !orphan {
|
||||
if err := q.ClearAttachmentStagingKey(ctx, row.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return tx.Commit(ctx)
|
||||
}
|
||||
+31
-15
@@ -50,15 +50,8 @@ type ListResult struct {
|
||||
}
|
||||
|
||||
func New(ctx context.Context, cfg appconfig.S3Config, log *slog.Logger) (*Client, error) {
|
||||
apiAccessKey, err := cfg.APIAccessKey()
|
||||
c, err := NewAPI(ctx, cfg, log)
|
||||
if err != nil {
|
||||
log.Error("read s3 api access key", "error", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
apiSecretKey, err := cfg.APISecretKey()
|
||||
if err != nil {
|
||||
log.Error("read s3 api secret key", "error", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -74,21 +67,36 @@ func New(ctx context.Context, cfg appconfig.S3Config, log *slog.Logger) (*Client
|
||||
return nil, err
|
||||
}
|
||||
|
||||
bootstrap, err := newS3Client(ctx, log, cfg.Endpoint, cfg.Region, bootstrapAccessKey, bootstrapSecretKey)
|
||||
c.bootstrap, err = newS3Client(ctx, log, cfg.Endpoint, cfg.Region, bootstrapAccessKey, bootstrapSecretKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func NewAPI(ctx context.Context, cfg appconfig.S3Config, log *slog.Logger) (*Client, error) {
|
||||
apiAccessKey, err := cfg.APIAccessKey()
|
||||
if err != nil {
|
||||
log.Error("read s3 api access key", "error", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
apiSecretKey, err := cfg.APISecretKey()
|
||||
if err != nil {
|
||||
log.Error("read s3 api secret key", "error", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
api, err := newS3Client(ctx, log, cfg.Endpoint, cfg.Region, apiAccessKey, apiSecretKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &Client{
|
||||
bucket: cfg.Bucket,
|
||||
bootstrap: bootstrap,
|
||||
api: api,
|
||||
log: log,
|
||||
bucket: cfg.Bucket,
|
||||
api: api,
|
||||
log: log,
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -198,7 +206,15 @@ func (c *Client) ListAll(ctx context.Context, prefix string) (ListResult, error)
|
||||
}
|
||||
|
||||
func (c *Client) DeleteAdmin(ctx context.Context, key string) error {
|
||||
_, err := c.bootstrap.DeleteObject(ctx, &awss3.DeleteObjectInput{
|
||||
return c.deleteObject(ctx, c.bootstrap, key)
|
||||
}
|
||||
|
||||
func (c *Client) Delete(ctx context.Context, key string) error {
|
||||
return c.deleteObject(ctx, c.api, key)
|
||||
}
|
||||
|
||||
func (c *Client) deleteObject(ctx context.Context, client *awss3.Client, key string) error {
|
||||
_, err := client.DeleteObject(ctx, &awss3.DeleteObjectInput{
|
||||
Bucket: aws.String(c.bucket),
|
||||
Key: aws.String(key),
|
||||
})
|
||||
@@ -206,7 +222,7 @@ func (c *Client) DeleteAdmin(ctx context.Context, key string) error {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
c.log.Error("delete admin object", "bucket", c.bucket, "key", key, "error", err)
|
||||
c.log.Error("delete object", "bucket", c.bucket, "key", key, "error", err)
|
||||
return ErrDeleteObject
|
||||
}
|
||||
|
||||
|
||||
@@ -14,6 +14,8 @@ import (
|
||||
"os"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"mtusi2026-messenger/internal/db"
|
||||
"mtusi2026-messenger/internal/model"
|
||||
@@ -31,13 +33,16 @@ var (
|
||||
|
||||
type attachmentQueries interface {
|
||||
CreateAttachment(ctx context.Context, arg db.CreateAttachmentParams) (db.Attachment, error)
|
||||
CreateOutboxEntry(ctx context.Context, arg db.CreateOutboxEntryParams) (db.Outbox, error)
|
||||
GetAttachmentByID(ctx context.Context, id uuid.UUID) (db.Attachment, error)
|
||||
ListAttachmentVariants(ctx context.Context, arg db.ListAttachmentVariantsParams) ([]db.AttachmentVariant, error)
|
||||
IsChatMember(ctx context.Context, arg db.IsChatMemberParams) (bool, error)
|
||||
MarkAttachmentReady(ctx context.Context, id uuid.UUID) (db.Attachment, error)
|
||||
}
|
||||
|
||||
type AttachmentService struct {
|
||||
pool txBeginner
|
||||
q attachmentQueries
|
||||
withTx func(pgx.Tx) attachmentQueries
|
||||
s3 *s3store.Client
|
||||
maxBytes int
|
||||
maxPixels int
|
||||
@@ -45,12 +50,17 @@ type AttachmentService struct {
|
||||
}
|
||||
|
||||
func NewAttachmentService(
|
||||
q attachmentQueries,
|
||||
pool *pgxpool.Pool,
|
||||
q *db.Queries,
|
||||
s3 *s3store.Client,
|
||||
maxBytes, maxPixels int,
|
||||
) *AttachmentService {
|
||||
return &AttachmentService{
|
||||
q: q,
|
||||
pool: pool,
|
||||
q: q,
|
||||
withTx: func(tx pgx.Tx) attachmentQueries {
|
||||
return q.WithTx(tx)
|
||||
},
|
||||
s3: s3,
|
||||
maxBytes: maxBytes,
|
||||
maxPixels: maxPixels,
|
||||
@@ -107,19 +117,37 @@ func (s *AttachmentService) Upload(
|
||||
if err != nil {
|
||||
return model.Attachment{}, err
|
||||
}
|
||||
jobID, err := uuid.NewV7()
|
||||
if err != nil {
|
||||
return model.Attachment{}, err
|
||||
}
|
||||
|
||||
hash := hex.EncodeToString(hasher.Sum(nil))
|
||||
key := "chats/" + chatID.String() + "/attachments/" + id.String()
|
||||
stagingKey := "staging/" + id.String()
|
||||
|
||||
if _, err := tmp.Seek(0, io.SeekStart); err != nil {
|
||||
return model.Attachment{}, err
|
||||
}
|
||||
|
||||
_, err = s.q.CreateAttachment(ctx, db.CreateAttachmentParams{
|
||||
if err := s.s3.Put(ctx, stagingKey, tmp, size, string(detectedType)); err != nil {
|
||||
return model.Attachment{}, err
|
||||
}
|
||||
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return model.Attachment{}, err
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
q := s.withTx(tx)
|
||||
|
||||
row, err := q.CreateAttachment(ctx, db.CreateAttachmentParams{
|
||||
ID: id,
|
||||
ChatID: chatID,
|
||||
OwnerID: userID,
|
||||
S3Key: key,
|
||||
StagingKey: stagingKey,
|
||||
JobID: jobID,
|
||||
Filename: filename,
|
||||
ContentType: db.AttachmentContentType(detectedType),
|
||||
SizeBytes: int(size),
|
||||
@@ -135,12 +163,15 @@ func (s *AttachmentService) Upload(
|
||||
return model.Attachment{}, err
|
||||
}
|
||||
|
||||
if err := s.s3.Put(ctx, key, tmp, size, string(detectedType)); err != nil {
|
||||
if _, err := q.CreateOutboxEntry(ctx, db.CreateOutboxEntryParams{
|
||||
AttachmentID: id,
|
||||
Attempt: 1,
|
||||
AvailableAt: row.CreatedAt,
|
||||
}); err != nil {
|
||||
return model.Attachment{}, err
|
||||
}
|
||||
|
||||
row, err := s.q.MarkAttachmentReady(ctx, id)
|
||||
if err != nil {
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return model.Attachment{}, err
|
||||
}
|
||||
|
||||
@@ -153,6 +184,8 @@ func (s *AttachmentService) Upload(
|
||||
SizeBytes: row.SizeBytes,
|
||||
Sha256: row.Sha256,
|
||||
Status: model.AttachmentStatus(row.Status),
|
||||
Width: row.Width,
|
||||
Height: row.Height,
|
||||
ErrorCode: row.ErrorCode,
|
||||
CreatedAt: row.CreatedAt,
|
||||
UpdatedAt: row.UpdatedAt,
|
||||
@@ -175,7 +208,24 @@ func (s *AttachmentService) Get(
|
||||
return model.Attachment{}, err
|
||||
}
|
||||
|
||||
rows, err := s.q.ListAttachmentVariants(ctx, db.ListAttachmentVariantsParams{AttachmentID: row.ID, PipelineVersion: row.PipelineVersion})
|
||||
if err != nil {
|
||||
return model.Attachment{}, err
|
||||
}
|
||||
variants := make([]model.AttachmentVariant, 0, len(rows))
|
||||
for _, v := range rows {
|
||||
variants = append(variants, model.AttachmentVariant{
|
||||
Name: model.AttachmentVariantName(v.Variant),
|
||||
ContentType: model.ContentType(v.ContentType),
|
||||
SizeBytes: v.SizeBytes,
|
||||
Width: v.Width,
|
||||
Height: v.Height,
|
||||
Sha256: v.Sha256,
|
||||
})
|
||||
}
|
||||
|
||||
return model.Attachment{
|
||||
Variants: variants,
|
||||
ID: row.ID,
|
||||
ChatID: row.ChatID,
|
||||
OwnerID: row.OwnerID,
|
||||
@@ -184,6 +234,8 @@ func (s *AttachmentService) Get(
|
||||
SizeBytes: row.SizeBytes,
|
||||
Sha256: row.Sha256,
|
||||
Status: model.AttachmentStatus(row.Status),
|
||||
Width: row.Width,
|
||||
Height: row.Height,
|
||||
ErrorCode: row.ErrorCode,
|
||||
CreatedAt: row.CreatedAt,
|
||||
UpdatedAt: row.UpdatedAt,
|
||||
@@ -193,6 +245,7 @@ func (s *AttachmentService) Get(
|
||||
func (s *AttachmentService) GetContent(
|
||||
ctx context.Context,
|
||||
userID, attachmentID uuid.UUID,
|
||||
variant string,
|
||||
) ([]byte, model.ContentType, error) {
|
||||
row, err := s.q.GetAttachmentByID(ctx, attachmentID)
|
||||
if postgres.IsNotFound(err) {
|
||||
@@ -210,7 +263,24 @@ func (s *AttachmentService) GetContent(
|
||||
return nil, "", ErrAttachmentNotReady
|
||||
}
|
||||
|
||||
out, err := s.s3.Get(ctx, row.S3Key)
|
||||
key, contentType := row.S3Key, model.ContentType(row.ContentType)
|
||||
if variant != "" && variant != model.AttachmentContentOriginal {
|
||||
rows, err := s.q.ListAttachmentVariants(ctx, db.ListAttachmentVariantsParams{AttachmentID: row.ID, PipelineVersion: row.PipelineVersion})
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
found := false
|
||||
for _, v := range rows {
|
||||
if string(v.Variant) == variant {
|
||||
key, contentType, found = v.S3Key, model.ContentType(v.ContentType), true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
return nil, "", ErrAttachmentNotFound
|
||||
}
|
||||
}
|
||||
out, err := s.s3.Get(ctx, key)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
@@ -221,7 +291,7 @@ func (s *AttachmentService) GetContent(
|
||||
return nil, "", err
|
||||
}
|
||||
|
||||
return data, model.ContentType(row.ContentType), nil
|
||||
return data, contentType, nil
|
||||
}
|
||||
|
||||
func (s *AttachmentService) checkImage(ctx context.Context, r io.ReadSeeker, contentType string) (model.ContentType, int, int, error) {
|
||||
|
||||
@@ -77,7 +77,7 @@ func (s *MessageService) Create(
|
||||
return model.Message{}, ErrAttachmentNotFound
|
||||
}
|
||||
for _, status := range statuses {
|
||||
if status != db.AttachmentStatusReady {
|
||||
if status == db.AttachmentStatusFailed {
|
||||
return model.Message{}, ErrAttachmentNotReady
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,225 @@
|
||||
package worker
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"image"
|
||||
"image/color"
|
||||
"image/draw"
|
||||
"image/jpeg"
|
||||
_ "image/png"
|
||||
"io"
|
||||
"os"
|
||||
"strconv"
|
||||
|
||||
"github.com/disintegration/imaging"
|
||||
"github.com/gen2brain/webp"
|
||||
|
||||
"mtusi2026-messenger/internal/db"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrInvalidSource = errors.New("invalid source image")
|
||||
ErrUnsupportedPipelineVersion = errors.New("unsupported pipeline version")
|
||||
)
|
||||
|
||||
type imageVariant struct {
|
||||
Name db.AttachmentVariantName
|
||||
Data []byte
|
||||
ContentType string
|
||||
Width, Height int
|
||||
}
|
||||
|
||||
func (w *Worker) process(ctx context.Context, row db.Attachment) ([]db.CreateAttachmentVariantParams, error) {
|
||||
if row.StagingKey == nil {
|
||||
return nil, ErrInvalidSource
|
||||
}
|
||||
|
||||
source, err := w.s3.Get(ctx, *row.StagingKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
defer source.Body.Close()
|
||||
|
||||
tmp, err := os.CreateTemp("", "attachment-job-*")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
defer func() {
|
||||
_ = tmp.Close()
|
||||
_ = os.Remove(tmp.Name())
|
||||
}()
|
||||
|
||||
hash := sha256.New()
|
||||
size, err := io.Copy(io.MultiWriter(tmp, hash), io.LimitReader(source.Body, int64(w.maxBytes)+1))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if size != int64(row.SizeBytes) ||
|
||||
hex.EncodeToString(hash.Sum(nil)) != row.Sha256 {
|
||||
return nil, ErrInvalidSource
|
||||
}
|
||||
|
||||
if _, err := tmp.Seek(0, io.SeekStart); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
select {
|
||||
case w.decodeSlot <- struct{}{}:
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
|
||||
if err := ctx.Err(); err != nil {
|
||||
<-w.decodeSlot
|
||||
return nil, err
|
||||
}
|
||||
|
||||
images, err := runImageProcess(ctx, tmp, w.maxPixels, row.PipelineVersion)
|
||||
<-w.decodeSlot
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if _, err := tmp.Seek(0, io.SeekStart); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := w.s3.Put(ctx, row.S3Key, tmp, size, string(row.ContentType)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
variants := make([]db.CreateAttachmentVariantParams, 0, len(images))
|
||||
for _, img := range images {
|
||||
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 {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
sum := sha256.Sum256(img.Data)
|
||||
variants = append(variants, db.CreateAttachmentVariantParams{
|
||||
AttachmentID: row.ID,
|
||||
PipelineVersion: row.PipelineVersion,
|
||||
Variant: img.Name,
|
||||
S3Key: key,
|
||||
ContentType: img.ContentType,
|
||||
SizeBytes: len(img.Data),
|
||||
Width: img.Width,
|
||||
Height: img.Height,
|
||||
Sha256: hex.EncodeToString(sum[:]),
|
||||
})
|
||||
}
|
||||
|
||||
return variants, nil
|
||||
}
|
||||
|
||||
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)
|
||||
if err != nil ||
|
||||
(format != "png" && format != "jpeg") ||
|
||||
cfg.Width <= 0 ||
|
||||
cfg.Height <= 0 ||
|
||||
cfg.Width > maxPixels/cfg.Height {
|
||||
return nil, ErrInvalidSource
|
||||
}
|
||||
|
||||
if _, err := r.Seek(0, io.SeekStart); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
src, err := imaging.Decode(r, imaging.AutoOrientation(true))
|
||||
if err != nil {
|
||||
return nil, ErrInvalidSource
|
||||
}
|
||||
|
||||
variants := make([]imageVariant, 0, 3)
|
||||
for _, item := range []struct {
|
||||
name db.AttachmentVariantName
|
||||
image image.Image
|
||||
}{
|
||||
{db.AttachmentVariantNameThumbnail, fitImage(src, 256)},
|
||||
{db.AttachmentVariantNameCrop, imaging.Fill(src, 128, 128, imaging.Center, imaging.Lanczos)},
|
||||
{db.AttachmentVariantNameOptimized, fitImage(src, 1280)},
|
||||
} {
|
||||
var data []byte
|
||||
contentType := "image/jpeg"
|
||||
if item.name == db.AttachmentVariantNameOptimized {
|
||||
contentType = "image/webp"
|
||||
data, err = encodeWebP(item.image, quality)
|
||||
} else {
|
||||
data, err = encodeJPEG(item.image, 85)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
variants = append(variants, imageVariant{
|
||||
Name: item.name,
|
||||
ContentType: contentType,
|
||||
Data: data,
|
||||
Width: item.image.Bounds().Dx(),
|
||||
Height: item.image.Bounds().Dy(),
|
||||
})
|
||||
}
|
||||
|
||||
return variants, nil
|
||||
}
|
||||
|
||||
func fitImage(src image.Image, maxSize int) image.Image {
|
||||
width, height := src.Bounds().Dx(), src.Bounds().Dy()
|
||||
if width > maxSize || height > maxSize {
|
||||
if width >= height {
|
||||
height = max(1, height*maxSize/width)
|
||||
width = maxSize
|
||||
} else {
|
||||
width = max(1, width*maxSize/height)
|
||||
height = maxSize
|
||||
}
|
||||
|
||||
return imaging.Resize(src, width, height, imaging.Lanczos)
|
||||
}
|
||||
|
||||
return src
|
||||
}
|
||||
|
||||
func encodeJPEG(src image.Image, quality int) ([]byte, error) {
|
||||
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(), src, src.Bounds().Min, draw.Over)
|
||||
|
||||
var out bytes.Buffer
|
||||
if err := jpeg.Encode(&out, dst, &jpeg.Options{Quality: quality}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return out.Bytes(), nil
|
||||
}
|
||||
|
||||
func encodeWebP(src image.Image, quality int) ([]byte, error) {
|
||||
var out bytes.Buffer
|
||||
if err := webp.Encode(&out, src, webp.Options{Quality: quality, Method: 4}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return out.Bytes(), nil
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -0,0 +1,219 @@
|
||||
package worker
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"io"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"mtusi2026-messenger/internal/db"
|
||||
"mtusi2026-messenger/internal/model"
|
||||
s3store "mtusi2026-messenger/internal/s3"
|
||||
)
|
||||
|
||||
var (
|
||||
errLeaseExpired = errors.New("attachment lease expired")
|
||||
errMissingThumbnail = errors.New("ready attachment has no thumbnail")
|
||||
errAttemptProcessing = errors.New("attachment attempt is still processing")
|
||||
errAttemptUnavailable = errors.New("attachment attempt is not yet available")
|
||||
errEffectChecksumMismatch = errors.New("attachment effect checksum mismatch")
|
||||
)
|
||||
|
||||
func (w *Worker) handle(ctx context.Context, job model.AttachmentJob) error {
|
||||
jobCtx, cancel := context.WithTimeout(ctx, w.cfg.Timeout)
|
||||
defer cancel()
|
||||
|
||||
row, err := w.q.ClaimAttachmentJob(jobCtx, db.ClaimAttachmentJobParams{
|
||||
ID: job.AttachmentID,
|
||||
JobID: job.JobID,
|
||||
PipelineVersion: job.PipelineVersion,
|
||||
Attempt: job.Attempt,
|
||||
LeaseUntil: time.Now().Add(w.cfg.Timeout),
|
||||
})
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return w.duplicate(jobCtx, job)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
w.log.Info("attachment processing", "job_id", job.JobID, "attachment_id", row.ID, "attempt", job.Attempt)
|
||||
variants, processErr := w.process(jobCtx, row)
|
||||
if processErr != nil {
|
||||
resultCtx, resultCancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
defer resultCancel()
|
||||
|
||||
return w.finishFailure(resultCtx, job, processErr)
|
||||
}
|
||||
|
||||
tx, err := w.pool.Begin(jobCtx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
defer tx.Rollback(context.Background())
|
||||
|
||||
q := w.q.WithTx(tx)
|
||||
_, err = q.LockAttachmentJob(jobCtx, db.LockAttachmentJobParams{
|
||||
ID: job.AttachmentID,
|
||||
JobID: job.JobID,
|
||||
PipelineVersion: job.PipelineVersion,
|
||||
Attempt: job.Attempt,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for _, variant := range variants {
|
||||
if err := q.CreateAttachmentVariant(jobCtx, variant); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
n, err := q.CompleteAttachmentJob(jobCtx, db.CompleteAttachmentJobParams{
|
||||
ID: row.ID,
|
||||
Attempt: job.Attempt,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if n != 1 {
|
||||
return errLeaseExpired
|
||||
}
|
||||
|
||||
if err := tx.Commit(jobCtx); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if row.StagingKey != nil {
|
||||
err := w.deleteStagingObject(ctx, *row.StagingKey)
|
||||
if err != nil && ctx.Err() == nil {
|
||||
w.log.Warn("delete ready attachment staging", "attachment_id", row.ID, "error", err)
|
||||
}
|
||||
}
|
||||
|
||||
w.log.Info("attachment ready", "job_id", job.JobID, "attachment_id", row.ID, "attempt", job.Attempt)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (w *Worker) duplicate(ctx context.Context, job model.AttachmentJob) error {
|
||||
row, err := w.q.GetAttachmentByID(ctx, job.AttachmentID)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if row.JobID == nil || *row.JobID != job.JobID || row.PipelineVersion != job.PipelineVersion {
|
||||
return nil
|
||||
}
|
||||
|
||||
if row.Status == db.AttachmentStatusFailed {
|
||||
return nil
|
||||
}
|
||||
|
||||
if row.Status == db.AttachmentStatusReady {
|
||||
variants, err := w.q.ListAttachmentVariants(ctx, db.ListAttachmentVariantsParams{
|
||||
AttachmentID: row.ID,
|
||||
PipelineVersion: row.PipelineVersion,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := verify(ctx, w.s3, row.S3Key, row.SizeBytes, row.Sha256); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
hasThumbnail := false
|
||||
for _, variant := range variants {
|
||||
if err := verify(ctx, w.s3, variant.S3Key, variant.SizeBytes, variant.Sha256); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if variant.Variant == db.AttachmentVariantNameThumbnail {
|
||||
hasThumbnail = true
|
||||
}
|
||||
}
|
||||
|
||||
if !hasThumbnail {
|
||||
return errMissingThumbnail
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
if row.Status == db.AttachmentStatusProcessing && row.Attempts == job.Attempt {
|
||||
return errAttemptProcessing
|
||||
}
|
||||
|
||||
if row.Attempts >= job.Attempt {
|
||||
return nil
|
||||
}
|
||||
|
||||
return errAttemptUnavailable
|
||||
}
|
||||
|
||||
func verify(ctx context.Context, storage *s3store.Client, key string, size int, checksum string) error {
|
||||
object, err := storage.Get(ctx, key)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
defer object.Body.Close()
|
||||
|
||||
hash := sha256.New()
|
||||
n, err := io.Copy(hash, io.LimitReader(object.Body, int64(size)+1))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if n != int64(size) || hex.EncodeToString(hash.Sum(nil)) != checksum {
|
||||
return errEffectChecksumMismatch
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (w *Worker) deleteStagingObject(ctx context.Context, key string) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
tx, err := w.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback(context.Background())
|
||||
|
||||
q := w.q.WithTx(tx)
|
||||
row, err := q.LockAttachmentByStagingKey(ctx, key)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if row.Status != db.AttachmentStatusReady {
|
||||
return nil
|
||||
}
|
||||
|
||||
if err := w.s3.Delete(ctx, key); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := q.ClearAttachmentStagingKey(ctx, row.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return tx.Commit(ctx)
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
package worker
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"math/rand/v2"
|
||||
"time"
|
||||
|
||||
"mtusi2026-messenger/internal/db"
|
||||
"mtusi2026-messenger/internal/model"
|
||||
s3store "mtusi2026-messenger/internal/s3"
|
||||
)
|
||||
|
||||
func (w *Worker) finishFailure(ctx context.Context, job model.AttachmentJob, cause error) error {
|
||||
tx, err := w.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
defer tx.Rollback(context.Background())
|
||||
|
||||
q := w.q.WithTx(tx)
|
||||
row, err := q.LockAttachmentJob(ctx, db.LockAttachmentJobParams{
|
||||
ID: job.AttachmentID,
|
||||
JobID: job.JobID,
|
||||
PipelineVersion: job.PipelineVersion,
|
||||
Attempt: job.Attempt,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
code := "processing_failed"
|
||||
permanent := errors.Is(cause, ErrInvalidSource) || errors.Is(cause, s3store.ErrObjectNotFound)
|
||||
if permanent {
|
||||
code = "invalid_source"
|
||||
} else if errors.Is(cause, context.DeadlineExceeded) {
|
||||
code = "job_timeout"
|
||||
}
|
||||
|
||||
var n int64
|
||||
if permanent || row.Attempts-row.RetryBase >= w.cfg.MaxAttempts {
|
||||
if !permanent {
|
||||
code = "retry_exhausted"
|
||||
}
|
||||
|
||||
n, err = q.FailAttachmentJob(ctx, db.FailAttachmentJobParams{
|
||||
ID: row.ID,
|
||||
Attempt: job.Attempt,
|
||||
ErrorCode: code,
|
||||
})
|
||||
} else {
|
||||
n, err = q.RetryAttachmentJob(ctx, db.RetryAttachmentJobParams{
|
||||
ID: row.ID,
|
||||
Attempt: job.Attempt,
|
||||
ErrorCode: code,
|
||||
})
|
||||
if err == nil && n == 1 {
|
||||
_, err = q.CreateOutboxEntry(ctx, db.CreateOutboxEntryParams{
|
||||
AttachmentID: row.ID,
|
||||
Attempt: row.Attempts + 1,
|
||||
AvailableAt: time.Now().Add(retryDelay(row.Attempts - row.RetryBase)),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if n != 1 {
|
||||
return errLeaseExpired
|
||||
}
|
||||
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
w.log.Warn(
|
||||
"attachment processing failed",
|
||||
"job_id",
|
||||
job.JobID,
|
||||
"attempt",
|
||||
job.Attempt,
|
||||
"error_code",
|
||||
code,
|
||||
)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (w *Worker) recoverLoop(ctx context.Context) {
|
||||
for ctx.Err() == nil {
|
||||
recovered, err := w.recoverOne(ctx)
|
||||
if err != nil && ctx.Err() == nil {
|
||||
w.log.Warn("recover attachment lease", "error", err)
|
||||
}
|
||||
|
||||
if (err != nil || !recovered) && !wait(ctx, time.Second) {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (w *Worker) recoverOne(ctx context.Context) (bool, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
tx, err := w.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
defer tx.Rollback(context.Background())
|
||||
|
||||
q := w.q.WithTx(tx)
|
||||
rows, err := q.LockExpiredAttachmentJobs(ctx, 1)
|
||||
if err != nil || len(rows) == 0 {
|
||||
return false, err
|
||||
}
|
||||
|
||||
row := rows[0]
|
||||
if row.Attempts-row.RetryBase >= w.cfg.MaxAttempts {
|
||||
_, err = q.FailExpiredAttachmentJob(ctx, row.ID)
|
||||
} else {
|
||||
_, err = q.RecoverExpiredAttachmentJob(ctx, row.ID)
|
||||
if err == nil {
|
||||
_, err = q.CreateOutboxEntry(ctx, db.CreateOutboxEntryParams{
|
||||
AttachmentID: row.ID,
|
||||
Attempt: row.Attempts + 1,
|
||||
AvailableAt: time.Now().Add(retryDelay(row.Attempts - row.RetryBase)),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
w.log.Info("attachment lease recovered", "attachment_id", row.ID, "attempt", row.Attempts)
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func retryDelay(attempt int) time.Duration {
|
||||
ceiling := time.Second * time.Duration(1<<min(max(attempt, 1), 6))
|
||||
return ceiling/2 + time.Duration(rand.Int64N(int64(ceiling/2)))
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
package worker
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"log/slog"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
amqp "github.com/rabbitmq/amqp091-go"
|
||||
|
||||
"mtusi2026-messenger/internal/config"
|
||||
"mtusi2026-messenger/internal/db"
|
||||
"mtusi2026-messenger/internal/model"
|
||||
"mtusi2026-messenger/internal/rabbitmq"
|
||||
s3store "mtusi2026-messenger/internal/s3"
|
||||
)
|
||||
|
||||
type Worker struct {
|
||||
pool *pgxpool.Pool
|
||||
q *db.Queries
|
||||
s3 *s3store.Client
|
||||
brokerURL string
|
||||
cfg config.WorkerConfig
|
||||
maxBytes, maxPixels int
|
||||
decodeSlot chan struct{}
|
||||
log *slog.Logger
|
||||
}
|
||||
|
||||
func New(
|
||||
pool *pgxpool.Pool,
|
||||
s3 *s3store.Client,
|
||||
brokerURL string,
|
||||
cfg config.WorkerConfig,
|
||||
maxBytes, maxPixels int,
|
||||
log *slog.Logger,
|
||||
) *Worker {
|
||||
return &Worker{
|
||||
pool: pool,
|
||||
q: db.New(pool),
|
||||
s3: s3,
|
||||
brokerURL: brokerURL,
|
||||
cfg: cfg,
|
||||
maxBytes: maxBytes,
|
||||
maxPixels: maxPixels,
|
||||
decodeSlot: make(chan struct{}, 1),
|
||||
log: log,
|
||||
}
|
||||
}
|
||||
|
||||
func (w *Worker) Run(ctx context.Context) {
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
|
||||
w.recoverLoop(ctx)
|
||||
}()
|
||||
|
||||
for range w.cfg.Concurrency {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
|
||||
w.consumeLoop(ctx)
|
||||
}()
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
}
|
||||
|
||||
func (w *Worker) consumeLoop(ctx context.Context) {
|
||||
for ctx.Err() == nil {
|
||||
client, err := rabbitmq.New(w.brokerURL)
|
||||
if err == nil {
|
||||
err = w.consume(ctx, client)
|
||||
_ = client.Close()
|
||||
}
|
||||
|
||||
if ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
|
||||
w.log.Warn("worker consumer reconnect", "error", err)
|
||||
if !wait(ctx, 2*time.Second) {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (w *Worker) consume(ctx context.Context, client *rabbitmq.Client) error {
|
||||
stop := context.AfterFunc(ctx, func() {
|
||||
_ = client.Close()
|
||||
})
|
||||
defer stop()
|
||||
|
||||
deliveries, err := client.Consume(ctx, 1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case delivery, ok := <-deliveries:
|
||||
if !ok {
|
||||
return amqp.ErrClosed
|
||||
}
|
||||
|
||||
var job model.AttachmentJob
|
||||
if json.Unmarshal(delivery.Body, &job) != nil ||
|
||||
job.SchemaVersion != 1 ||
|
||||
job.Type != "attachment.process.v1" ||
|
||||
job.JobID == uuid.Nil ||
|
||||
job.AttachmentID == uuid.Nil ||
|
||||
(job.PipelineVersion != 1 && job.PipelineVersion != 2) ||
|
||||
job.Attempt < 1 ||
|
||||
job.CreatedAt.IsZero() {
|
||||
if err := delivery.Reject(false); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
w.log.Warn("invalid attachment job rejected")
|
||||
continue
|
||||
}
|
||||
|
||||
err := w.handle(ctx, job)
|
||||
if err == nil {
|
||||
if err := delivery.Ack(false); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
if ctx.Err() != nil {
|
||||
return ctx.Err()
|
||||
}
|
||||
|
||||
w.log.Warn(
|
||||
"attachment job not acknowledged",
|
||||
"job_id",
|
||||
job.JobID,
|
||||
"attempt",
|
||||
job.Attempt,
|
||||
"error",
|
||||
err,
|
||||
)
|
||||
if !wait(ctx, time.Second) {
|
||||
return ctx.Err()
|
||||
}
|
||||
|
||||
if err := delivery.Nack(false, true); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func wait(ctx context.Context, duration time.Duration) bool {
|
||||
timer := time.NewTimer(duration)
|
||||
defer timer.Stop()
|
||||
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return false
|
||||
case <-timer.C:
|
||||
return true
|
||||
}
|
||||
}
|
||||
@@ -20,7 +20,7 @@ func TestAttachmentUploaderFailover(t *testing.T) {
|
||||
chat := createChat(t, user, user.ID)
|
||||
original := makePNG(t, 32, 32)
|
||||
resp := uploadAttachment(t, user, chat.ID, "failover.png", "image/png", original)
|
||||
requireStatus(t, resp, http.StatusCreated)
|
||||
requireStatus(t, resp, http.StatusAccepted)
|
||||
uploader := resp.Header.Get("X-Instance-Id")
|
||||
var att dto.AttachmentResponse
|
||||
mustDecode(t, resp, &att)
|
||||
@@ -82,7 +82,7 @@ func TestAttachmentUploaderFailover(t *testing.T) {
|
||||
}
|
||||
return
|
||||
}
|
||||
if response.StatusCode != http.StatusBadGateway && response.StatusCode != http.StatusServiceUnavailable && response.StatusCode != http.StatusGatewayTimeout {
|
||||
if response.StatusCode != http.StatusConflict && response.StatusCode != http.StatusBadGateway && response.StatusCode != http.StatusServiceUnavailable && response.StatusCode != http.StatusGatewayTimeout {
|
||||
t.Fatalf("unexpected download status: %d", response.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//go:build contract || reconcile || failure
|
||||
//go:build contract || reconcile || failure || worker || pipeline
|
||||
|
||||
package studenttests_test
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"net/http"
|
||||
"net/url"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
@@ -49,12 +50,12 @@ func uploadPNG(t *testing.T, actor testUser, chatID uuid.UUID) dto.AttachmentRes
|
||||
t.Helper()
|
||||
|
||||
resp := uploadAttachment(t, actor, chatID, "sample.png", "image/png", makePNG(t, 32, 32))
|
||||
requireStatus(t, resp, http.StatusCreated)
|
||||
requireStatus(t, resp, http.StatusAccepted)
|
||||
|
||||
var att dto.AttachmentResponse
|
||||
mustDecode(t, resp, &att)
|
||||
|
||||
return att
|
||||
return waitAttachment(t, actor, att.ID, "ready", time.Minute)
|
||||
}
|
||||
|
||||
func postMessage(
|
||||
@@ -104,3 +105,30 @@ func requireErrorCode(t *testing.T, resp *http.Response, code dto.ErrorCode) {
|
||||
t.Errorf("expected error code %q, got %q", code, apiErr.Error.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func waitAttachment(
|
||||
t *testing.T,
|
||||
actor testUser,
|
||||
id uuid.UUID,
|
||||
status string,
|
||||
timeout time.Duration,
|
||||
) dto.AttachmentResponse {
|
||||
t.Helper()
|
||||
|
||||
deadline := time.Now().Add(timeout)
|
||||
for time.Now().Before(deadline) {
|
||||
resp := doRequest(t, http.MethodGet, "/api/v1/attachments/"+id.String(), actor.Token, nil)
|
||||
requireStatus(t, resp, http.StatusOK)
|
||||
var att dto.AttachmentResponse
|
||||
mustDecode(t, resp, &att)
|
||||
if string(att.Status) == status {
|
||||
return att
|
||||
}
|
||||
if att.Status == "failed" {
|
||||
t.Fatalf("attachment failed: %v", att.ErrorCode)
|
||||
}
|
||||
time.Sleep(200 * time.Millisecond)
|
||||
}
|
||||
t.Fatalf("attachment did not reach %s within %s", status, timeout)
|
||||
return dto.AttachmentResponse{}
|
||||
}
|
||||
|
||||
@@ -118,7 +118,7 @@ func TestConcurrentUploads(t *testing.T) {
|
||||
|
||||
mu.Lock()
|
||||
statuses[resp.StatusCode]++
|
||||
if resp.StatusCode == http.StatusCreated {
|
||||
if resp.StatusCode == http.StatusAccepted {
|
||||
latencies = append(latencies, latency)
|
||||
}
|
||||
mu.Unlock()
|
||||
@@ -144,7 +144,7 @@ func TestConcurrentUploads(t *testing.T) {
|
||||
t.Logf("HTTP %d: %d", status, n)
|
||||
}
|
||||
|
||||
successful := statuses[http.StatusCreated]
|
||||
successful := statuses[http.StatusAccepted]
|
||||
t.Logf("successful RPS: %.2f", float64(successful)/elapsed.Seconds())
|
||||
|
||||
if len(latencies) > 0 {
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"io"
|
||||
"net/http"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
@@ -29,14 +30,16 @@ func TestAttachmentJPEG(t *testing.T) {
|
||||
}
|
||||
|
||||
resp := uploadAttachment(t, user, chat.ID, "sample.jpg", "image/jpeg", body.Bytes())
|
||||
requireStatus(t, resp, http.StatusCreated)
|
||||
requireStatus(t, resp, http.StatusAccepted)
|
||||
|
||||
var att dto.AttachmentResponse
|
||||
mustDecode(t, resp, &att)
|
||||
if att.Status != "ready" {
|
||||
t.Fatalf("expected ready attachment, got %q", att.Status)
|
||||
if att.Status != "queued" {
|
||||
t.Fatalf("expected queued attachment, got %q", att.Status)
|
||||
}
|
||||
|
||||
waitAttachment(t, user, att.ID, "ready", time.Minute)
|
||||
|
||||
resp = doRequest(t, http.MethodGet, "/api/v1/attachments/"+att.ID.String()+"/content", user.Token, nil)
|
||||
requireStatus(t, resp, http.StatusOK)
|
||||
defer resp.Body.Close()
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
//go:build failure || worker || pipeline
|
||||
|
||||
package studenttests_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"net/http"
|
||||
"os/exec"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"mtusi2026-messenger/internal/dto"
|
||||
)
|
||||
|
||||
func compose(t *testing.T, args ...string) {
|
||||
t.Helper()
|
||||
|
||||
cmd := exec.Command("docker", append([]string{"compose"}, args...)...)
|
||||
cmd.Dir = ".."
|
||||
if out, err := cmd.CombinedOutput(); err != nil {
|
||||
t.Fatalf("docker compose %v: %v\n%s", args, err, out)
|
||||
}
|
||||
}
|
||||
|
||||
func stopService(t *testing.T, name string) {
|
||||
t.Helper()
|
||||
|
||||
compose(t, "stop", name)
|
||||
t.Cleanup(func() {
|
||||
compose(t, "start", name)
|
||||
waitReady(t)
|
||||
})
|
||||
}
|
||||
|
||||
func waitReady(t *testing.T) {
|
||||
t.Helper()
|
||||
|
||||
deadline := time.Now().Add(60 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
resp, err := httpClient.Get(*baseURL + "/health/ready")
|
||||
if err == nil {
|
||||
resp.Body.Close()
|
||||
if resp.StatusCode == http.StatusOK {
|
||||
return
|
||||
}
|
||||
}
|
||||
time.Sleep(500 * time.Millisecond)
|
||||
}
|
||||
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
|
||||
}
|
||||
@@ -6,50 +6,12 @@ import (
|
||||
"bytes"
|
||||
"io"
|
||||
"net/http"
|
||||
"os/exec"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"mtusi2026-messenger/internal/dto"
|
||||
)
|
||||
|
||||
func compose(t *testing.T, args ...string) {
|
||||
t.Helper()
|
||||
|
||||
cmd := exec.Command("docker", append([]string{"compose"}, args...)...)
|
||||
cmd.Dir = ".."
|
||||
if out, err := cmd.CombinedOutput(); err != nil {
|
||||
t.Fatalf("docker compose %v: %v\n%s", args, err, out)
|
||||
}
|
||||
}
|
||||
|
||||
func stopService(t *testing.T, name string) {
|
||||
t.Helper()
|
||||
|
||||
compose(t, "stop", name)
|
||||
t.Cleanup(func() {
|
||||
compose(t, "start", name)
|
||||
waitReady(t)
|
||||
})
|
||||
}
|
||||
|
||||
func waitReady(t *testing.T) {
|
||||
t.Helper()
|
||||
|
||||
deadline := time.Now().Add(60 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
resp, err := httpClient.Get(*baseURL + "/health/ready")
|
||||
if err == nil {
|
||||
resp.Body.Close()
|
||||
if resp.StatusCode == http.StatusOK {
|
||||
return
|
||||
}
|
||||
}
|
||||
time.Sleep(500 * time.Millisecond)
|
||||
}
|
||||
t.Fatal("service did not become ready in 60s")
|
||||
}
|
||||
|
||||
func TestRedisDown(t *testing.T) {
|
||||
user := createUser(t)
|
||||
|
||||
@@ -140,7 +102,7 @@ func TestS3Down(t *testing.T) {
|
||||
response := uploadAttachment(t, user, chat.ID, "recovery.png", "image/png", original)
|
||||
status := response.StatusCode
|
||||
response.Body.Close()
|
||||
if status == http.StatusCreated {
|
||||
if status == http.StatusAccepted {
|
||||
uploaded = true
|
||||
} else if status != http.StatusServiceUnavailable {
|
||||
t.Fatalf("unexpected upload recovery status: %d", status)
|
||||
|
||||
@@ -0,0 +1,226 @@
|
||||
//go:build contract
|
||||
|
||||
package studenttests_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/sha256"
|
||||
"encoding/binary"
|
||||
"encoding/hex"
|
||||
"image"
|
||||
"image/color"
|
||||
"image/jpeg"
|
||||
"image/png"
|
||||
"io"
|
||||
"net/http"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"golang.org/x/image/webp"
|
||||
|
||||
"mtusi2026-messenger/internal/dto"
|
||||
)
|
||||
|
||||
func TestThumbnail(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
width, height, wantWidth, wantHeight int
|
||||
}{
|
||||
{"landscape", 320, 200, 256, 160}, {"portrait", 201, 321, 160, 256},
|
||||
{"small", 12, 7, 12, 7}, {"thin", 1, 1000, 1, 256},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
var source bytes.Buffer
|
||||
if err := png.Encode(&source, image.NewNRGBA(image.Rect(0, 0, tc.width, tc.height))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
data, width, height := processedVariant(t, source.Bytes(), "image/png", "thumbnail")
|
||||
|
||||
if width != tc.wantWidth || height != tc.wantHeight {
|
||||
t.Fatalf("got %dx%d", width, height)
|
||||
}
|
||||
|
||||
decoded, err := jpeg.Decode(bytes.NewReader(data))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if decoded.Bounds().Dx() != width || decoded.Bounds().Dy() != height {
|
||||
t.Fatal("JPEG dimensions disagree")
|
||||
}
|
||||
|
||||
r, g, b, _ := decoded.At(0, 0).RGBA()
|
||||
if r < 65000 || g < 65000 || b < 65000 {
|
||||
t.Fatal("transparent source was not composited on white")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestVariantsEXIF(t *testing.T) {
|
||||
src := image.NewRGBA(image.Rect(0, 0, 40, 20))
|
||||
|
||||
for y := 0; y < 20; y++ {
|
||||
for x := 0; x < 40; x++ {
|
||||
c := color.RGBA{255, 0, 0, 255}
|
||||
if x >= 20 {
|
||||
c = color.RGBA{0, 0, 255, 255}
|
||||
}
|
||||
|
||||
src.Set(x, y, c)
|
||||
}
|
||||
}
|
||||
|
||||
var original bytes.Buffer
|
||||
if err := jpeg.Encode(&original, src, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Little-endian TIFF, orientation=6 (90 degrees clockwise).
|
||||
exif := []byte{
|
||||
'E', 'x', 'i', 'f', 0, 0, 'I', 'I',
|
||||
42, 0, 8, 0, 0, 0, 1, 0,
|
||||
0x12, 1, 3, 0, 1, 0, 0, 0,
|
||||
6, 0, 0, 0, 0, 0, 0, 0,
|
||||
}
|
||||
segment := []byte{0xff, 0xe1, 0, 0}
|
||||
binary.BigEndian.PutUint16(segment[2:], uint16(len(exif)+2))
|
||||
data := append([]byte{}, original.Bytes()[:2]...)
|
||||
data = append(data, segment...)
|
||||
data = append(data, exif...)
|
||||
data = append(data, original.Bytes()[2:]...)
|
||||
for _, variant := range []string{"thumbnail", "optimized"} {
|
||||
t.Run(variant, func(t *testing.T) {
|
||||
result, width, height := processedVariant(t, data, "image/jpeg", variant)
|
||||
if width != 20 || height != 40 {
|
||||
t.Fatalf("orientation ignored: %dx%d", width, height)
|
||||
}
|
||||
|
||||
decoded, _, err := image.Decode(bytes.NewReader(result))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
r, _, b, _ := decoded.At(10, 5).RGBA()
|
||||
if r <= b {
|
||||
t.Fatal("incorrect EXIF rotation")
|
||||
}
|
||||
|
||||
if bytes.Contains(result, []byte("Exif")) || bytes.Contains(result, []byte("EXIF")) {
|
||||
t.Fatal("EXIF retained")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func processedVariant(t *testing.T, source []byte, contentType, variant string) ([]byte, int, int) {
|
||||
t.Helper()
|
||||
user := createUser(t)
|
||||
chat := createChat(t, user, user.ID)
|
||||
resp := uploadAttachment(t, user, chat.ID, "image", contentType, source)
|
||||
requireStatus(t, resp, http.StatusAccepted)
|
||||
var att dto.AttachmentResponse
|
||||
mustDecode(t, resp, &att)
|
||||
att = waitAttachment(t, user, att.ID, "ready", time.Minute)
|
||||
for _, v := range att.Variants {
|
||||
if string(v.Name) != variant {
|
||||
continue
|
||||
}
|
||||
resp = doRequest(t, http.MethodGet, "/api/v1/attachments/"+att.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)
|
||||
}
|
||||
|
||||
sum := sha256.Sum256(data)
|
||||
if len(data) != v.SizeBytes || hex.EncodeToString(sum[:]) != v.Sha256 ||
|
||||
resp.Header.Get("Content-Type") != string(v.ContentType) {
|
||||
t.Fatal("variant content disagrees with metadata")
|
||||
}
|
||||
|
||||
return data, v.Width, v.Height
|
||||
}
|
||||
t.Fatalf("ready attachment has no %s", variant)
|
||||
return nil, 0, 0
|
||||
}
|
||||
|
||||
func TestCrop(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
width, height int
|
||||
}{
|
||||
{"landscape", 384, 128},
|
||||
{"portrait", 128, 384},
|
||||
{"small", 24, 8},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
src := image.NewNRGBA(image.Rect(0, 0, tc.width, tc.height))
|
||||
// Only the central square is green; a stretched full image retains red edges.
|
||||
side := min(tc.width, tc.height)
|
||||
left, top := (tc.width-side)/2, (tc.height-side)/2
|
||||
for y := 0; y < tc.height; y++ {
|
||||
for x := 0; x < tc.width; x++ {
|
||||
c := color.NRGBA{R: 255, A: 255}
|
||||
if x >= left && x < left+side && y >= top && y < top+side {
|
||||
c = color.NRGBA{G: 255, A: 255}
|
||||
}
|
||||
src.SetNRGBA(x, y, c)
|
||||
}
|
||||
}
|
||||
|
||||
var source bytes.Buffer
|
||||
if err := png.Encode(&source, src); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
data, width, height := processedVariant(t, source.Bytes(), "image/png", "crop")
|
||||
decoded, err := jpeg.Decode(bytes.NewReader(data))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if width != 128 || height != 128 || decoded.Bounds() != image.Rect(0, 0, 128, 128) {
|
||||
t.Fatalf("expected crop 128x128, metadata=%dx%d, JPEG=%v", width, height, decoded.Bounds())
|
||||
}
|
||||
for _, point := range []image.Point{{8, 8}, {64, 64}, {119, 119}} {
|
||||
r, g, b, _ := decoded.At(point.X, point.Y).RGBA()
|
||||
if g < 50000 || r > 15000 || b > 15000 {
|
||||
t.Fatalf("crop is not centered at %v", point)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestOptimized(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
width, height, wantWidth, wantHeight int
|
||||
}{
|
||||
{"landscape", 1600, 1000, 1280, 800},
|
||||
{"portrait", 1000, 1600, 800, 1280},
|
||||
{"small", 12, 7, 12, 7},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
var source bytes.Buffer
|
||||
if err := png.Encode(&source, image.NewNRGBA(image.Rect(0, 0, tc.width, tc.height))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
data, width, height := processedVariant(t, source.Bytes(), "image/png", "optimized")
|
||||
decoded, err := webp.Decode(bytes.NewReader(data))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if width != tc.wantWidth || height != tc.wantHeight ||
|
||||
decoded.Bounds().Dx() != width || decoded.Bounds().Dy() != height {
|
||||
t.Fatalf("unexpected optimized dimensions: metadata=%dx%d, WebP=%v", width, height, decoded.Bounds())
|
||||
}
|
||||
_, _, _, alpha := decoded.At(0, 0).RGBA()
|
||||
if alpha != 0 {
|
||||
t.Fatal("optimized image lost transparency")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -6,7 +6,6 @@ import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/exec"
|
||||
@@ -62,7 +61,7 @@ func runReconcile(t *testing.T, dryRun bool, grace string) reconcile.Report {
|
||||
if err := json.Unmarshal(output, &report); err != nil {
|
||||
t.Fatalf("decode reconcile report: %v\n%s", err, output)
|
||||
}
|
||||
t.Logf("dry_run=%t objects=%d rows=%d list_pages=%d duration_ms=%d orphan=%d missing=%d stale=%d skipped_fresh=%d skipped_referenced=%d deleted_objects=%d deleted_rows=%d marked_failed=%d errors=%v", report.DryRun, report.ScannedObjects, report.ScannedRows, report.ListPages, report.DurationMS, len(report.OrphanObjects), len(report.MissingAttachments), len(report.StaleUploads), report.SkippedFresh, report.SkippedReferenced, report.DeletedObjects, report.DeletedRows, report.MarkedFailed, report.Errors)
|
||||
t.Logf("dry_run=%t objects=%d rows=%d list_pages=%d duration_ms=%d orphan=%d missing=%d skipped_fresh=%d skipped_inactive=%d deleted_objects=%d marked_failed=%d errors=%v", report.DryRun, report.ScannedObjects, report.ScannedRows, report.ListPages, report.DurationMS, len(report.OrphanObjects), len(report.MissingAttachments), report.SkippedFresh, report.SkippedInactive, report.DeletedObjects, report.MarkedFailed, report.Errors)
|
||||
if len(report.Errors) != 0 {
|
||||
t.Fatal("reconciler reported errors")
|
||||
}
|
||||
@@ -86,7 +85,7 @@ func TestReconcileRepair(t *testing.T) {
|
||||
if !slices.Contains(dry.OrphanObjects, originalKey) || !slices.Contains(dry.MissingAttachments, att.ID) {
|
||||
t.Fatal("dry-run did not detect both injected inconsistencies")
|
||||
}
|
||||
if dry.DeletedObjects != 0 || dry.DeletedRows != 0 || dry.MarkedFailed != 0 {
|
||||
if dry.DeletedObjects != 0 || dry.MarkedFailed != 0 {
|
||||
t.Fatal("dry-run changed data")
|
||||
}
|
||||
var status, code string
|
||||
@@ -110,7 +109,7 @@ func TestReconcileRepair(t *testing.T) {
|
||||
if slices.Contains(again.OrphanObjects, originalKey) || slices.Contains(again.MissingAttachments, att.ID) {
|
||||
t.Fatal("fixture still requires repair on repeat")
|
||||
}
|
||||
if again.DeletedObjects != 0 || again.DeletedRows != 0 || again.MarkedFailed != 0 {
|
||||
if again.DeletedObjects != 0 || again.MarkedFailed != 0 {
|
||||
t.Fatal("repeat repair changed data; run on an idle test stand")
|
||||
}
|
||||
t.Log("PASS: dry-run preserved data; orphan deleted; missing marked failed; repeat made no changes")
|
||||
@@ -125,7 +124,7 @@ func TestReconcileSafety(t *testing.T) {
|
||||
resp := postMessage(t, user, chat.ID, "", []uuid.UUID{used.ID})
|
||||
requireStatus(t, resp, http.StatusCreated)
|
||||
resp.Body.Close()
|
||||
// Exercise both grace-period protection and protection of referenced queued uploads.
|
||||
// Queued attachments must be preserved regardless of age or message references.
|
||||
reconcileSQL(t, conn, "UPDATE attachments SET status='queued' WHERE id=$1", fresh.ID)
|
||||
reconcileSQL(t, conn, "UPDATE attachments SET status='queued', created_at=now()-interval '2 hours' WHERE id=$1", used.ID)
|
||||
t.Cleanup(func() {
|
||||
@@ -135,8 +134,8 @@ func TestReconcileSafety(t *testing.T) {
|
||||
})
|
||||
for _, dryRun := range []bool{true, false} {
|
||||
report := runReconcile(t, dryRun, "1h")
|
||||
if report.SkippedFresh < 1 || report.SkippedReferenced < 1 {
|
||||
t.Fatal("fresh/referenced protection was not exercised")
|
||||
if report.SkippedInactive < 2 {
|
||||
t.Fatal("queued attachment protection was not exercised")
|
||||
}
|
||||
for _, att := range []uuid.UUID{fresh.ID, used.ID} {
|
||||
var status string
|
||||
@@ -147,18 +146,11 @@ func TestReconcileSafety(t *testing.T) {
|
||||
t.Fatalf("protected fixture changed status: %s", status)
|
||||
}
|
||||
resp := doRequest(t, http.MethodGet, "/api/v1/attachments/"+att.String()+"/content", user.Token, nil)
|
||||
requireStatus(t, resp, http.StatusOK)
|
||||
data, err := io.ReadAll(resp.Body)
|
||||
requireStatus(t, resp, http.StatusConflict)
|
||||
resp.Body.Close()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Equal(data, makePNG(t, 32, 32)) {
|
||||
t.Fatal("protected original changed")
|
||||
}
|
||||
}
|
||||
}
|
||||
t.Log("PASS: fresh and old referenced uploads preserved, originals unchanged")
|
||||
t.Log("PASS: queued uploads preserved regardless of age or references; content remains unavailable")
|
||||
}
|
||||
|
||||
func TestReconcileCost(t *testing.T) {
|
||||
|
||||
@@ -0,0 +1,426 @@
|
||||
//go:build worker
|
||||
|
||||
package studenttests_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"image/jpeg"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/exec"
|
||||
"reflect"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"golang.org/x/image/webp"
|
||||
|
||||
"mtusi2026-messenger/internal/dto"
|
||||
)
|
||||
|
||||
func TestWorkerPersistenceAndDuplicate(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)
|
||||
where := "attachment_id='" + att.ID.String() + "'"
|
||||
resp := postMessage(t, user, chat.ID, "", []uuid.UUID{att.ID})
|
||||
requireStatus(t, resp, http.StatusCreated)
|
||||
var message dto.MessageResponse
|
||||
mustDecode(t, resp, &message)
|
||||
resp = doRequest(t, http.MethodGet, "/api/v1/attachments/"+att.ID.String()+"/content", user.Token, nil)
|
||||
requireStatus(t, resp, http.StatusConflict)
|
||||
resp.Body.Close()
|
||||
resp = sendMessage(t, user, chat.ID, "worker is stopped")
|
||||
requireStatus(t, resp, http.StatusCreated)
|
||||
resp.Body.Close()
|
||||
workerWait(t, "confirmed publication", 15*time.Second, func() bool {
|
||||
return workerSQL(t, "SELECT published_at IS NOT NULL FROM outbox WHERE "+where) == "t"
|
||||
})
|
||||
stopService(t, "api")
|
||||
if workerQueue(t) != "1:0" {
|
||||
t.Fatal("accepted job is not pending in broker")
|
||||
}
|
||||
before := workerCommand(t, "compose", "ps", "-q", "rabbitmq")
|
||||
compose(t, "up", "-d", "--no-deps", "--force-recreate", "rabbitmq")
|
||||
after := workerCommand(t, "compose", "ps", "-q", "rabbitmq")
|
||||
if before == after {
|
||||
t.Fatal("broker was not recreated")
|
||||
}
|
||||
workerWait(t, "broker health", 30*time.Second, func() bool {
|
||||
return workerCommand(t, "inspect", "--format", "{{.State.Health.Status}}", after) == "healthy"
|
||||
})
|
||||
if workerQueue(t) != "1:0" {
|
||||
t.Fatal("job lost after broker recreation with existing volume")
|
||||
}
|
||||
compose(t, "start", "api")
|
||||
waitReady(t)
|
||||
att = waitAttachment(t, user, att.ID, "queued", 15*time.Second)
|
||||
resp = doRequest(t, http.MethodGet, "/api/v1/chats/"+chat.ID.String()+"/messages", user.Token, nil)
|
||||
requireStatus(t, resp, http.StatusOK)
|
||||
var page dto.MessagePageResponse
|
||||
mustDecode(t, resp, &page)
|
||||
found := false
|
||||
for _, item := range page.Items {
|
||||
if item.ID == message.ID && reflect.DeepEqual(item.AttachmentIDs, message.AttachmentIDs) {
|
||||
found = true
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Fatal("message with attachment lost after API restart")
|
||||
}
|
||||
compose(t, "start", "worker")
|
||||
ready := waitAttachment(t, user, att.ID, "ready", 30*time.Second)
|
||||
if !bytes.Equal(workerContent(t, user, att.ID, "original"), source) {
|
||||
t.Fatal("original changed")
|
||||
}
|
||||
thumb := workerContent(t, user, att.ID, "thumbnail")
|
||||
cfg, err := jpeg.DecodeConfig(bytes.NewReader(thumb))
|
||||
if err != nil || cfg.Width != 256 || cfg.Height != 160 {
|
||||
t.Fatal("invalid JPEG thumbnail")
|
||||
}
|
||||
crop := workerContent(t, user, att.ID, "crop")
|
||||
cfg, err = jpeg.DecodeConfig(bytes.NewReader(crop))
|
||||
if err != nil || cfg.Width != 128 || cfg.Height != 128 {
|
||||
t.Fatal("invalid JPEG crop")
|
||||
}
|
||||
optimized := workerContent(t, user, att.ID, "optimized")
|
||||
cfg, err = webp.DecodeConfig(bytes.NewReader(optimized))
|
||||
if err != nil || cfg.Width != 320 || cfg.Height != 200 {
|
||||
t.Fatal("invalid optimized WebP")
|
||||
}
|
||||
|
||||
workerSQL(t, "UPDATE outbox SET published_at=NULL WHERE "+where)
|
||||
workerWait(t, "duplicate publication", 15*time.Second, func() bool {
|
||||
return workerSQL(t, "SELECT published_at IS NOT NULL FROM outbox WHERE "+where) == "t"
|
||||
})
|
||||
workerWait(t, "duplicate acknowledgement", 15*time.Second, func() bool { return workerQueue(t) == "0:0" })
|
||||
duplicate := waitAttachment(t, user, att.ID, "ready", 30*time.Second)
|
||||
if !reflect.DeepEqual(ready, duplicate) || workerSQL(t, "SELECT count(*) FROM attachment_variants WHERE "+where) != "3" {
|
||||
t.Fatal("duplicate job changed metadata or duplicated variants")
|
||||
}
|
||||
if !bytes.Equal(workerContent(t, user, att.ID, "optimized"), optimized) ||
|
||||
!bytes.Equal(workerContent(t, user, att.ID, "crop"), crop) ||
|
||||
!bytes.Equal(workerContent(t, user, att.ID, "thumbnail"), thumb) ||
|
||||
!bytes.Equal(workerContent(t, user, att.ID, "original"), source) {
|
||||
t.Fatal("duplicate changed content")
|
||||
}
|
||||
t.Logf("PASS attachment=%s: queued survives API/broker restart; ready; duplicate acknowledged with unchanged result", att.ID)
|
||||
}
|
||||
|
||||
func TestWorkerRetryExhausted(t *testing.T) {
|
||||
user := createUser(t)
|
||||
chat := createChat(t, user, user.ID)
|
||||
stopService(t, "worker")
|
||||
att, _ := workerUpload(t, user, chat.ID)
|
||||
workerID := workerCommand(t, "compose", "ps", "-a", "-q", "worker")
|
||||
var env []string
|
||||
if err := json.Unmarshal([]byte(workerCommand(t, "inspect", "--format", "{{json .Config.Env}}", workerID)), &env); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
maxAttempts := 5
|
||||
for _, entry := range env {
|
||||
if value, ok := strings.CutPrefix(entry, "JOB_MAX_ATTEMPTS="); ok {
|
||||
n, err := strconv.Atoi(value)
|
||||
if err != nil || n < 1 {
|
||||
t.Fatal("invalid JOB_MAX_ATTEMPTS")
|
||||
}
|
||||
maxAttempts = n
|
||||
}
|
||||
}
|
||||
// A separate worker gets an unreachable S3 endpoint and a short attempt timeout.
|
||||
// Keep the configured attempt count and normal backoff; leave the shared S3 running.
|
||||
testWorker := "worker-retry-" + uuid.NewString()
|
||||
t.Cleanup(func() {
|
||||
workerCommand(t, "rm", "-f", testWorker)
|
||||
})
|
||||
workerCommand(t, "compose", "run", "-d", "--no-deps", "--name", testWorker,
|
||||
"-e", "JOB_TIMEOUT_SECONDS=3", "-e", "S3_ENDPOINT=http://127.0.0.1:1", "worker")
|
||||
failed := waitAttachment(t, user, att.ID, "failed", 90*time.Second)
|
||||
if failed.ErrorCode == nil || *failed.ErrorCode != "retry_exhausted" {
|
||||
t.Fatal("expected safe retry_exhausted error")
|
||||
}
|
||||
attempts := workerSQL(t, "SELECT attempts FROM attachments WHERE id='"+att.ID.String()+"'")
|
||||
if attempts != strconv.Itoa(maxAttempts) {
|
||||
t.Fatalf("expected %d attempts, got %s", maxAttempts, attempts)
|
||||
}
|
||||
resp := doRequest(t, http.MethodGet, "/api/v1/attachments/"+att.ID.String()+"/content", user.Token, nil)
|
||||
requireStatus(t, resp, http.StatusConflict)
|
||||
resp.Body.Close()
|
||||
resp = postMessage(t, user, chat.ID, "", []uuid.UUID{att.ID})
|
||||
requireStatus(t, resp, http.StatusConflict)
|
||||
resp.Body.Close()
|
||||
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)
|
||||
}
|
||||
+9
-1
@@ -8,14 +8,16 @@ ACTION ?= stop-one.sh
|
||||
ACTION_AT ?= 10s
|
||||
DRY_RUN ?= true
|
||||
|
||||
.PHONY: help-go contract-go race-go load-go failure-go load-action-go reconcile reconcile-test-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:
|
||||
@echo "contract-go: contract tests"
|
||||
@echo "worker-go: worker persistence, duplicate and bounded retry (stops shared services)"
|
||||
@echo "race-go: concurrency tests (-race)"
|
||||
@echo "load-go: load test"
|
||||
@echo "failure-go: dependency failure tests (stops redis/postgres/s3 containers)"
|
||||
@echo "reconcile: attachment audit; DRY_RUN=false to repair"
|
||||
@echo "pipeline-go: versioned pipeline tests (requires Compose; stops worker)"
|
||||
|
||||
contract-go:
|
||||
go test -tags=contract ./student-tests/... -v -args -base-url=$(BASE_URL)
|
||||
@@ -42,3 +44,9 @@ reconcile:
|
||||
reconcile-test-go:
|
||||
docker compose --env-file .env build reconcile
|
||||
go test -count=1 -tags=reconcile ./student-tests/... -v -args -base-url=$(BASE_URL)
|
||||
|
||||
worker-go:
|
||||
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