32 changed files with 906 additions and 140 deletions
+1 -1
View File
@@ -15,7 +15,7 @@ API_REPLICAS=2
IDEMPOTENCY_TTL_SECONDS=86400
API_CPUS=0.5
API_MEM=256M
API_MEM=512M
LB_CPUS=0.5
S3_ENDPOINT=http://s3:9000
+1 -1
View File
@@ -1,4 +1,4 @@
FROM golang:1.27.1-alpine3.24 AS build
FROM golang:1.27.1 AS build
ENV CGO_ENABLED=0
RUN go install github.com/pressly/goose/v3/cmd/goose@v3.28.0
+2 -2
View File
@@ -1,4 +1,4 @@
FROM golang:1.27.1-alpine3.24 AS build
FROM golang:1.27.1 AS build
ENV CGO_ENABLED=0
WORKDIR /src
@@ -8,6 +8,6 @@ RUN go mod download
COPY . .
RUN go build -o /out/s3config ./cmd/s3config
FROM alpine:3.24
FROM gcr.io/distroless/static-debian12:nonroot
COPY --from=build /out/s3config /usr/local/bin/s3config
ENTRYPOINT ["/usr/local/bin/s3config"]
+103 -17
View File
@@ -1,37 +1,123 @@
# Отчёт — лабораторная 4
- Автор, группа: TODO
- Целевая оценка; выбранный трек 5, если нужен: TODO
- Commit/PR: TODO после публикации
- Использованные источники, библиотеки и помощь ИИ: TODO
- Автор, группа: Каменски Лин, БПИ2301
- Целевая оценка; выбранный трек 5, если нужен: 5; трек 2
- Commit/PR: [Pull Request 58](https://gitea.privcloud.tech/mtusi2026/mtusi2026lab4/pulls/58)
- Использованные источники, библиотеки и помощь ИИ: материалы лабораторной; Go 1.27.1, chi v5, pgx v5, sqlc, goose, PostgreSQL 18.6, Redis 8.8.3, Nginx 1.31.7, Docker Compose, SeaweedFS 4.51; OpenCode - для ускорения работы и оформления отчёта
## Запуск из чистого 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`.
Создать локальные секреты - файлы в `secrets/`, в каждый записать значение без лишних символов:
- `database_url.txt` - URL PostgreSQL для API;
- `cache_url.txt` - URL Redis;
- `postgres_password.txt` - пароль пользователя `messenger`;
- `test_database_url.txt` - URL БД для тестов;
- `s3_access_key_id.txt` - S3 access key ID для API;
- `s3_secret_access_key.txt` - S3 secret access key для API;
- `s3_bootstrap_access_key_id.txt` - bootstrap access key ID;
- `s3_bootstrap_secret_access_key.txt` - bootstrap secret access key.
Пример (значения заменить своими):
```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/.
Безопасная остановка (данные в volume `pgdata` сохраняются):
```bash
docker compose down
```
Намеренное удаление учебных данных:
```bash
docker compose down -v
```
## Архитектура и решения
TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab3, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации.
**Процессы/хранилища:** `api` (Go, chi, pgxpool, sqlc, goose, s3-client) × `API_REPLICAS` (≥2) → PostgreSQL (источник истины метаданных) + Redis (кэш сессий с fallback) → SeaweedFS S3 (байты вложений, приватный bucket `messenger-attachments`). Единственная публичная точка входа - nginx на `127.0.0.1:8080`.
**Источник истины** - PostgreSQL. API не хранит локального состояния: сессии доступны всем репликам через общее хранилище, режим выбирается переменной `SESSION_STORE` (`postgres` | `redis`). При недоступности Redis API обходит кэш и читает сессию из PostgreSQL.
**Что перенесено из lab3:** Go-приложение и PostgreSQL, аутентификация, сессии, чаты, сообщения, идемпотентность и `X-Instance-Id`, Redis-кэш сессий, `compose.yaml`, `deploy/nginx.conf`, `Dockerfile`, `Dockerfile.migrate`, `scripts/restart.sh`, `scripts/stop-one.sh`, `student-tests`, `student.mk`, `Makefile`, `web/swagger`, `contracts`.
**Что изменено в lab4:** Добавлен S3-совместимое объектное хранилище (SeaweedFS) в compose.yaml с приватным bucket `messenger-attachments`, политика доступа и bootstrap-конфигурация; таблица/миграция `attachments` + типы `attachment_content_type` и `attachment_status`; sqlc-запросы и DTO для вложений; `attachment_ids` в сообщениях (0-10 уникальных ID, по умолчанию `[]`); `POST /api/v1/chats/{chat_id}/attachments` - загрузка raw PNG/JPEG с ограничениями (10 MiB, 40 млн пикселей, MIME по содержимому); эндпоинты `GET /api/v1/attachments/{id}` и `GET /api/v1/attachments/{id}/content`; поле `attachment_ids` в ответах сообщений; механизм `queued → ready` (upload пишет `queued`, после успешного S3 Put переводит в `ready`); Nginx `client_max_body_size 11m`; очистка orphan-объектов через reconciler с индексом `idx_attachments_queued_created_at`; отдельные S3 credentials: bootstrap (Admin) и API (Read/Write/List/Tagging, без Admin/Delete).
**Загрузка и память.** Тело запроса ограничено 10 MiB и потоково записывается во временный файл с одновременным подсчётом SHA-256. По заголовку изображения проверяются формат, MIME и лимит 40 млн пикселей до распаковки. Затем выполняется полное декодирование для проверки целостности; на одной API-реплике одновременно работает не более одного декодера. Тело сохраняется потоково, но декодер держит распакованные пиксели в RAM. Затем файл передаётся в S3; временный файл удаляется при завершении запроса. Контекст запроса и чтение тела на стороне API ограничены 5 с; таймаут чтения возвращает `408 invalid_request`. Локальный файл нужен только на время загрузки, оригинал хранится в S3.
**Очистка незавершённых загрузок.** До записи в S3 создаётся строка `queued`, после успеха - `ready`. Фоновая очистка каждые 10 минут обрабатывает брошенные `queued` старше 1 часа. Полную сверку объектов и метаданных выполняет отдельный reconciler; часовой grace period защищает свежие загрузки.
**Готовность и недоступность S3.** `GET /health/ready` теперь помимо PostgreSQL проверяет доступ к S3 bucket через `HeadBucket` с общим таймаутом 2 с. При недоступности S3 загрузка и скачивание возвращают `503 unavailable`. Повторы Nginx при `503` отключены: PostgreSQL и S3 общие для всех API-реплик, поэтому переход на другую реплику при их недоступности не помогает. После рестарта S3 доступ к bucket может восстановиться раньше загрузки и скачивания - тест дополнительно ждёт их восстановления.
**Bootstrap и доступ к S3.** Bucket создаётся только при отсутствии; повторный запуск и одновременное создание несколькими репликами допустимы. API и bootstrap используют разные credentials. Порты S3 и административных интерфейсов не публикуются на хост, HTTP-интерфейс filer отключён. Прямой анонимный доступ к объекту возвращает `403 Forbidden`.
**Переменные `.env.example`:** `APP_HOST`, `APP_PORT` - адрес и порт API; `SESSION_TTL_SECONDS` - срок жизни сессии; `LOG_LEVEL` - уровень логов; `DATABASE_URL_FILE`, `CACHE_URL_FILE` - пути к secrets с URL PostgreSQL и Redis; `SESSION_STORE` - режим хранения сессий, `postgres` или `redis`; `IDEMPOTENCY_TTL_SECONDS` - срок хранения ключей идемпотентности; `API_REPLICAS` - число реплик `api`; `API_CPUS`, `API_MEM` - лимиты CPU и памяти каждой реплики; `LB_CPUS` - лимит CPU Nginx; `S3_ENDPOINT`, `S3_REGION`, `S3_BUCKET` - настройки S3; `MAX_UPLOAD_BYTES`, `MAX_IMAGE_PIXELS` - лимиты загрузок; `S3_ACCESS_KEY_ID_FILE`, `S3_SECRET_ACCESS_KEY_FILE`, `S3_BOOTSTRAP_ACCESS_KEY_ID_FILE`, `S3_BOOTSTRAP_SECRET_ACCESS_KEY_FILE` - пути к secrets.
## Доказательства критериев
| Критерий 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 |
| Загрузка, ready, checksum и сообщение с вложением | `make test` | `PASS` | `evidence/make-test.txt` |
| Запрет доступа постороннему | `make test` | `404` для метаданных и содержимого | `evidence/make-test.txt` |
| PNG/JPEG, MIME, лимиты размера и пикселей, безопасный filename | `make test`; `make contract-go`: `TestAttachmentJPEG`, `TestAttachmentTooLarge`, `TestAttachmentTooManyPixels`, `TestAttachmentCorruptedImage`, `TestAttachmentMimeSubstitution`, `TestAttachmentUnsafeFilename` | `PASS` | `evidence/make-test.txt`, `evidence/contract-go.txt` |
| Запрет прямого доступа к объекту S3 | `docker compose exec -T s3 wget -S -O /dev/null "http://127.0.0.1:9000/messenger-attachments/${OBJECT_KEY}"` | `403 Forbidden` | `evidence/s3-private.txt` |
| Скачивание после остановки загрузившей реплики | `make failure-go`: `TestAttachmentUploaderFailover` | `PASS` | `evidence/failure-go.txt` |
| Сохранность метаданных и оригинала после restart | `make test-persistence ACTION_SCRIPT=scripts/restart.sh`; `docker compose ps -a` до и после | `PASS` | `evidence/test-persistence.txt` |
| Отказ S3 и восстановление | `make s3-failure-go`: `TestS3Down` | `PASS` | `evidence/s3-failure-go.txt` |
| Уровень 4 |
| Негативные тесты вложений без 500 | `make contract-go`: `TestAttachmentTooLarge`, `TestAttachmentCorruptedImage`, `TestAttachmentMimeSubstitution`, `TestAttachmentForeignID`, `TestAttachmentFromAnotherChat` | `PASS` | `evidence/contract-go.txt` |
| ≥10 одновременных загрузок и пик памяти | `make load-go LOAD_WORKERS=10 LOAD_DURATION=30s` | `PASS`: 10 загрузчиков, 30,4 с, 632 ответа 201, ошибок 0; 20,82 загрузки/с; память API-1: 12,2 → 50,9 MiB, API-2: 13,3 → 56,7 MiB | `evidence/load-go.txt` |
| Уровень 5, трек 2 |
| Обнаружение и исправление orphan/missing при моделировании рассогласования S3/БД | `make reconcile-test-go`: `TestReconcileRepair` | `PASS`: dry-run нашёл 1 orphan и 1 missing без изменений; исправление удалило объект и пометило вложение failed; повторный запуск без изменений | `evidence/reconcile-test-go.txt` |
| Свежие и используемые вложения сохраняются | `make reconcile-test-go`: `TestReconcileSafety` | `PASS`: пропущены 1 свежее и 1 используемое вложение; строки и оригиналы сохранены | `evidence/reconcile-test-go.txt` |
| Стоимость обхода объектов и метаданных | `make reconcile-test-go`: `TestReconcileCost` (3 обхода, объекты, строки, страницы, время) | `PASS`: 14 607 объектов, 14 614 строк, 15 страниц S3; время обходов: 1609 / 1721 / 1587 мс | `evidence/reconcile-test-go.txt` |
## Эксперименты и отказы
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения.
### Трек 2: согласованность двух хранилищ
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
| --- | --- | --- | --- |
| TODO | TODO | TODO | TODO |
**Гипотеза:** сверка S3 и PostgreSQL обнаруживает объекты без метаданных и метаданные без оригинала; исправление повторяемо, а свежие и используемые вложения сохраняются.
Методика: `make reconcile-test-go` создаёт вложения через API и подменяет S3-ключ одного из них в БД. Исходный объект становится orphan, строка указывает на отсутствующий объект (missing). Затем выполняются dry-run, исправление и повторное исправление. В этом сценарии grace period сокращён до 1 с; в проверке безопасности используется штатный 1 час. Команда запускается на стенде без параллельных загрузок.
| Проверка | Что ожидаем | Что наблюдали |
| --- | --- | --- |
| Dry-run после рассогласования | Найти orphan/missing без изменения данных | Обнаружены 1 orphan и 1 missing; изменений нет |
| Исправление | Удалить orphan и отметить missing как ошибку | Orphan удалён; missing переведён в `failed` с `object_missing` |
| Повторное исправление | Не менять уже исправленные данные | Расхождения устранены, новых изменений нет |
| Защита вложений | Сохранить свежие и используемые вложения | Свежий `queued` и привязанный к сообщению `queued` старше 2 часов пропущены; строки сохранены, скачанные оригиналы совпадают побайтно |
Стоимость полного обхода измерена тремя последовательными dry-run: 14 607 объектов S3, 14 614 строк PostgreSQL, 15 страниц списка S3. Время: 1609 / 1721 / 1587 мс, медиана 1609 мс. Доказательство: `evidence/reconcile-test-go.txt`.
Ограничения: моделируются последствия рассогласования через SQL, а не реальные сетевые отказы или падение процесса между операциями. Сверка не восстанавливает утраченные байты: missing помечается ошибкой. Списки объектов и строк загружаются в память целиком; стоимость растёт с объёмом данных. Измерен один объём, поэтому масштабируемость не доказана. Время трёх обходов составило 1,59-1,72 с.
**Вывод**: Гипотеза подтверждена на подготовленных сценариях: reconciler обнаружил и исправил orphan/missing, повторный запуск не внёс изменений, свежие и используемые вложения сохранились. Обход 14,6 тыс. объектов занял 1,59-1,72 с. Утраченный оригинал не восстанавливается, а отмечается ошибкой.
## Ограничения и следующие шаги
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза.
- Nginx, PostgreSQL и SeaweedFS работают в одном экземпляре на одном хосте. Реплики API не защищают от отказа этих компонентов или самого хоста.
- Если удалить сессию из Redis не удалось, logout возвращает `503 unavailable`: сессия уже удалена из PostgreSQL, но старый токен может приниматься из кэша до 60 с. Несмотря на `503`, может потребоваться повторный вход. Пока Redis недоступен, получить `204` нельзя, хотя сессия в БД уже удалена; после восстановления повторный logout вернёт `401`.
- Полное декодирование требует памяти под распакованное изображение. Для ограничения расхода RAM на каждой API-реплике работает один декодер, поэтому параллельные загрузки ожидают своей очереди.
- Общей транзакции PostgreSQL и S3 нет: расхождения исправляются последующей сверкой. Reconciler отмечает отсутствие оригинала, но не восстанавливает байты. Сохранность volumes не заменяет резервные копии обоих хранилищ.
- Фоновая очистка сначала удаляет строку БД, затем объект S3. Если удаление из S3 не удалось, объект останется без метаданных до запуска reconciler.
- Reconciler загружает списки объектов и метаданных целиком в память, поэтому расход памяти растёт с объёмом хранилища.
+2 -2
View File
@@ -18,7 +18,7 @@ services:
resources:
limits:
cpus: "${API_CPUS:-0.5}"
memory: ${API_MEM:-256M}
memory: ${API_MEM:-512M}
depends_on:
migrate:
condition: service_completed_successfully
@@ -134,7 +134,7 @@ services:
resources:
limits:
cpus: "0.5"
memory: 256M
memory: 512M
restart: unless-stopped
load_balancer:
+2 -2
View File
@@ -16,7 +16,7 @@ http {
proxy_connect_timeout 1s;
proxy_read_timeout 6s;
proxy_next_upstream error timeout http_500 http_502 http_503 non_idempotent;
proxy_next_upstream error timeout http_500 http_502 non_idempotent;
proxy_next_upstream_tries 2;
}
@@ -26,7 +26,7 @@ http {
proxy_connect_timeout 1s;
proxy_read_timeout 6s;
proxy_next_upstream error timeout http_500 http_502 http_503;
proxy_next_upstream error timeout http_500 http_502;
proxy_next_upstream_tries 2;
}
}
+36
View File
@@ -0,0 +1,36 @@
> make contract-go
go test -tags=contract ./student-tests/... -v -args -base-url=http://localhost:8080
=== RUN TestAttachmentJPEG
--- PASS: TestAttachmentJPEG (0.23s)
=== RUN TestAttachmentTooManyPixels
--- PASS: TestAttachmentTooManyPixels (1.83s)
=== RUN TestAttachmentUnsafeFilename
--- PASS: TestAttachmentUnsafeFilename (0.12s)
=== RUN TestAttachmentTooLarge
--- PASS: TestAttachmentTooLarge (0.22s)
=== RUN TestAttachmentCorruptedImage
--- PASS: TestAttachmentCorruptedImage (0.14s)
=== RUN TestAttachmentMimeSubstitution
--- PASS: TestAttachmentMimeSubstitution (0.12s)
=== RUN TestAttachmentForeignID
--- PASS: TestAttachmentForeignID (0.26s)
=== RUN TestAttachmentFromAnotherChat
--- PASS: TestAttachmentFromAnotherChat (0.41s)
=== RUN TestCreateChatRollback
--- PASS: TestCreateChatRollback (0.16s)
=== RUN TestInvalidJSON
--- PASS: TestInvalidJSON (0.00s)
=== RUN TestForeignChat
--- PASS: TestForeignChat (0.57s)
=== RUN TestEmptyMessage
--- PASS: TestEmptyMessage (0.21s)
=== RUN TestDuplicateUsername
--- PASS: TestDuplicateUsername (0.28s)
=== RUN TestPagination
--- PASS: TestPagination (0.36s)
=== RUN TestLoginWrongPassword
--- PASS: TestLoginWrongPassword (0.34s)
=== RUN TestLogout
--- PASS: TestLogout (0.17s)
PASS
ok mtusi2026-messenger/student-tests 5.442s
+14
View File
@@ -0,0 +1,14 @@
> make failure-go
go test -tags=failure ./student-tests/... -v -args -base-url=http://localhost:8080
=== RUN TestAttachmentUploaderFailover
--- PASS: TestAttachmentUploaderFailover (1.53s)
=== RUN TestRedisDown
--- PASS: TestRedisDown (2.81s)
=== RUN TestDatabaseDown
--- PASS: TestDatabaseDown (7.67s)
=== RUN TestS3Down
--- PASS: TestS3Down (47.30s)
=== RUN TestSessionExpiry
--- PASS: TestSessionExpiry (6.05s)
PASS
ok mtusi2026-messenger/student-tests 65.376s
+27
View File
@@ -0,0 +1,27 @@
> make load-go LOAD_WORKERS=10 LOAD_DURATION=30s
go test -count=1 -tags=load ./student-tests/... -v -args -base-url=http://localhost:8080 -workers=10 -duration=30s
=== RUN TestConcurrentUploads
attachment_load_test.go:141: workers=10 duration=30.0s elapsed=30.4s
attachment_load_test.go:142: total uploads=632 transport_errors=0
attachment_load_test.go:144: HTTP 201: 632
attachment_load_test.go:148: successful RPS: 20.82
attachment_load_test.go:152: latency p50=449.961ms p95=691.7505ms p99=807.8037ms
attachment_load_test.go:176: memory per container (idle -> peak):
attachment_load_test.go:178: mtusi2026lab4-api-1: 12.2MiB -> 50.9MiB
attachment_load_test.go:178: mtusi2026lab4-api-2: 13.3MiB -> 56.7MiB
--- PASS: TestConcurrentUploads (32.69s)
=== RUN TestLoad
load_test.go:109: duration: 30.000s
load_test.go:110: workers: 10
load_test.go:111: rate per worker: 20 req/s
load_test.go:112: target rate: 200 req/s
load_test.go:113: total requests: 5990
load_test.go:116: HTTP 201: 5990
load_test.go:119: request errors: 0
load_test.go:123: successful RPS: 199.66
load_test.go:132: successful latency p50: 8.1287ms
load_test.go:133: successful latency p95: 9.4585ms
load_test.go:134: successful latency p99: 16.4092ms
--- PASS: TestLoad (30.58s)
PASS
ok mtusi2026-messenger/student-tests 63.302s
+3
View File
@@ -0,0 +1,3 @@
> make test
python3 tests/smoke.py --base-url "http://localhost:8080"
PASS: lab4 public API scenario; infrastructure and grading evidence remain separate.
+52
View File
@@ -0,0 +1,52 @@
> make reconcile-test-go
docker compose --env-file .env build reconcile
[+] Building 13.8s (18/18) FINISHED
=> [internal] load local bake definitions 0.0s
=> => reading from stdin 600B 0.0s
=> [internal] load build definition from Dockerfile.reconcile 0.0s
=> => transferring dockerfile: 342B 0.0s
=> [internal] load metadata for gcr.io/distroless/static-debian12:nonroot 1.4s
=> [internal] load metadata for docker.io/library/golang:1.27.1 1.3s
=> [auth] library/golang:pull token for registry-1.docker.io 0.0s
=> [internal] load .dockerignore 0.0s
=> => transferring context: 203B 0.0s
=> [build 1/6] FROM docker.io/library/golang:1.27.1@sha256:162be5298a40ed317005c8339c6de4d10d3eef336d66dc8e9259b03ab9d3a6d2 0.0s
=> [internal] load build context 0.0s
=> => transferring context: 11.25kB 0.0s
=> [stage-1 1/3] FROM gcr.io/distroless/static-debian12:nonroot@sha256:afa5c872c891853ca7fcf1f12c3edb23f7eeef36189728842dd51042ff57f7ab 0.0s
=> CACHED [build 2/6] WORKDIR /src 0.0s
=> CACHED [build 3/6] COPY go.mod go.sum ./ 0.0s
=> CACHED [build 4/6] RUN go mod download 0.0s
=> [build 5/6] COPY . . 0.1s
=> [build 6/6] RUN CGO_ENABLED=0 GOOS=linux go build -o /out/reconcile ./cmd/reconcile 11.9s
=> CACHED [stage-1 2/3] WORKDIR /app 0.0s
=> CACHED [stage-1 3/3] COPY --from=build /out/reconcile . 0.0s
=> exporting to image 0.0s
=> => exporting layers 0.0s
=> => writing image sha256:0a06bc3c0229755a92090161a0913af4d053556c4934087af6539b95c1d9b1cd 0.0s
=> => naming to docker.io/library/mtusi-messenger-reconcile:lab4 0.0s
=> resolving provenance for metadata file 0.0s
[+] build 1/1
✔ Image mtusi-messenger-reconcile:lab4 Built 13.9s
go test -count=1 -tags=reconcile ./student-tests/... -v -args -base-url=http://localhost:8080
=== RUN TestReconcileRepair
reconcile_test.go:85: dry_run=true objects=14606 rows=14612 list_pages=15 duration_ms=1813 orphan=1 missing=1 stale=0 skipped_fresh=0 skipped_referenced=0 deleted_objects=0 deleted_rows=0 marked_failed=0 errors=[]
reconcile_test.go:99: dry_run=false objects=14606 rows=14612 list_pages=15 duration_ms=1557 orphan=1 missing=1 stale=0 skipped_fresh=0 skipped_referenced=0 deleted_objects=1 deleted_rows=0 marked_failed=1 errors=[]
reconcile_test.go:109: dry_run=false objects=14605 rows=14612 list_pages=15 duration_ms=1836 orphan=0 missing=0 stale=0 skipped_fresh=0 skipped_referenced=0 deleted_objects=0 deleted_rows=0 marked_failed=0 errors=[]
reconcile_test.go:116: PASS: dry-run preserved data; orphan deleted; missing marked failed; repeat made no changes
--- PASS: TestReconcileRepair (8.81s)
=== RUN TestReconcileSafety
reconcile_test.go:137: dry_run=true objects=14607 rows=14614 list_pages=15 duration_ms=1630 orphan=0 missing=0 stale=0 skipped_fresh=1 skipped_referenced=1 deleted_objects=0 deleted_rows=0 marked_failed=0 errors=[]
reconcile_test.go:137: dry_run=false objects=14607 rows=14614 list_pages=15 duration_ms=1560 orphan=0 missing=0 stale=0 skipped_fresh=1 skipped_referenced=1 deleted_objects=0 deleted_rows=0 marked_failed=0 errors=[]
reconcile_test.go:161: PASS: fresh and old referenced uploads preserved, originals unchanged
--- PASS: TestReconcileSafety (5.03s)
=== RUN TestReconcileCost
reconcile_test.go:166: scan 1/3
reconcile_test.go:167: dry_run=true objects=14607 rows=14614 list_pages=15 duration_ms=1609 orphan=0 missing=0 stale=0 skipped_fresh=0 skipped_referenced=0 deleted_objects=0 deleted_rows=0 marked_failed=0 errors=[]
reconcile_test.go:166: scan 2/3
reconcile_test.go:167: dry_run=true objects=14607 rows=14614 list_pages=15 duration_ms=1721 orphan=0 missing=0 stale=0 skipped_fresh=0 skipped_referenced=0 deleted_objects=0 deleted_rows=0 marked_failed=0 errors=[]
reconcile_test.go:166: scan 3/3
reconcile_test.go:167: dry_run=true objects=14607 rows=14614 list_pages=15 duration_ms=1587 orphan=0 missing=0 stale=0 skipped_fresh=0 skipped_referenced=0 deleted_objects=0 deleted_rows=0 marked_failed=0 errors=[]
--- PASS: TestReconcileCost (6.92s)
PASS
ok mtusi2026-messenger/student-tests 20.784s
+7
View File
@@ -0,0 +1,7 @@
> OBJECT_KEY=$(docker compose exec -T postgres psql -U messenger -d messenger -Atc "SELECT s3_key FROM attachments WHERE status = 'ready' ORDER BY created_at DESC LIMIT 1;")
> echo "$OBJECT_KEY"
chats/01a1a6df-35b7-786f-aa90-f7155218d5b0/attachments/01a1a6df-35ca-7a29-9fa7-fb30a52fbed0
> docker compose exec -T s3 wget -S -O /dev/null "http://127.0.0.1:9000/messenger-attachments/${OBJECT_KEY}"
Connecting to 127.0.0.1:9000 (127.0.0.1:9000)
HTTP/1.1 403 Forbidden
wget: server returned error: HTTP/1.1 403 Forbidden
+5
View File
@@ -0,0 +1,5 @@
> make test-failover ACTION_SCRIPT=scripts/stop-one.sh
python3 tests/resilience.py --mode failover --action-script "scripts/stop-one.sh" --base-url "http://localhost:8080"
Executing explicit failover hook; hook output suppressed to avoid leaking secrets.
{"observed_instances_before": 2, "successful_writes": 122, "failed_attempts": 0, "first_recovery_seconds": 2.441}
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
+24
View File
@@ -0,0 +1,24 @@
> docker compose ps -a
NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS
mtusi2026lab4-api-1 mtusi-messenger:lab4 "/app/server" api 2 hours ago Up 2 hours (healthy) 8080/tcp
mtusi2026lab4-api-2 mtusi-messenger:lab4 "/app/server" api 2 hours ago Up 21 seconds (healthy) 8080/tcp
mtusi2026lab4-load_balancer-1 nginx:1.31.7-alpine3.24 "/docker-entrypoint.…" load_balancer 2 hours ago Up 2 hours 127.0.0.1:8080->8080/tcp
mtusi2026lab4-migrate-1 mtusi2026lab4-migrate "sh -c 'goose -dir /…" migrate 26 hours ago Exited (0) 2 hours ago
mtusi2026lab4-postgres-1 postgres:18.6 "docker-entrypoint.s…" postgres 26 hours ago Up 2 hours (healthy) 127.0.0.1:5432->5432/tcp
mtusi2026lab4-redis-1 redis:8.8.3-alpine3.23 "docker-entrypoint.s…" redis 26 hours ago Up 2 hours (healthy) 6379/tcp
mtusi2026lab4-s3-1 chrislusf/seaweedfs:4.51 "/entrypoint.sh serv…" s3 26 hours ago Up 2 hours (healthy) 7333/tcp, 8080/tcp, 8333/tcp, 8888/tcp, 9333/tcp, 18080/tcp, 18888/tcp, 19333/tcp
mtusi2026lab4-s3-config-init-1 mtusi-messenger-s3config:lab4 "/usr/local/bin/s3co…" s3-config-init 2 hours ago Exited (0) 2 hours ago
> make test-persistence ACTION_SCRIPT=scripts/restart.sh
python3 tests/resilience.py --mode persistence --action-script "scripts/restart.sh" --base-url "http://localhost:8080"
Executing explicit persistence hook; hook output suppressed to avoid leaking secrets.
PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence.
> docker compose ps -a
NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS
mtusi2026lab4-api-1 mtusi-messenger:lab4 "/app/server" api 31 seconds ago Up 9 seconds (healthy) 8080/tcp
mtusi2026lab4-api-2 mtusi-messenger:lab4 "/app/server" api 31 seconds ago Up 9 seconds (healthy) 8080/tcp
mtusi2026lab4-load_balancer-1 nginx:1.31.7-alpine3.24 "/docker-entrypoint.…" load_balancer 31 seconds ago Up 3 seconds 127.0.0.1:8080->8080/tcp
mtusi2026lab4-migrate-1 mtusi2026lab4-migrate "sh -c 'goose -dir /…" migrate 31 seconds ago Exited (0) 24 seconds ago
mtusi2026lab4-postgres-1 postgres:18.6 "docker-entrypoint.s…" postgres 31 seconds ago Up 30 seconds (healthy) 127.0.0.1:5432->5432/tcp
mtusi2026lab4-redis-1 redis:8.8.3-alpine3.23 "docker-entrypoint.s…" redis 31 seconds ago Up 29 seconds (healthy) 6379/tcp
mtusi2026lab4-s3-1 chrislusf/seaweedfs:4.51 "/entrypoint.sh serv…" s3 31 seconds ago Up 29 seconds (healthy) 7333/tcp, 8080/tcp, 8333/tcp, 8888/tcp, 9333/tcp, 18080/tcp, 18888/tcp, 19333/tcp
mtusi2026lab4-s3-config-init-1 mtusi-messenger-s3config:lab4 "/usr/local/bin/s3co…" s3-config-init 31 seconds ago Exited (0) 30 seconds ago
+1
View File
@@ -115,6 +115,7 @@ func Run() error {
cfg.Server.MaxInflightRequests,
cfg.S3.MaxUploadBytes,
pool,
s3Client,
authService,
userService,
chatService,
+2 -1
View File
@@ -18,6 +18,7 @@ func NewRouter(
maxInflightRequests int,
maxUploadBytes int,
db handler.Pinger,
storage handler.Pinger,
authService *service.AuthService,
userService *service.UserService,
chatService *service.ChatService,
@@ -26,7 +27,7 @@ func NewRouter(
) http.Handler {
router := chi.NewRouter()
healthHandler := handler.NewHealthHandler(log, db)
healthHandler := handler.NewHealthHandler(log, db, storage)
authHandler := handler.NewAuthHandler(authService)
userHandler := handler.NewUserHandler(userService)
chatHandler := handler.NewChatHandler(chatService)
+8
View File
@@ -14,6 +14,10 @@ type CreateAttachmentRequest struct {
Filename string
}
type GetAttachmentContentRequest struct {
Variant string
}
type VariantResponse struct {
Name string `json:"name"`
ContentType string `json:"content_type"`
@@ -52,6 +56,10 @@ func (r CreateAttachmentRequest) Validate() bool {
return true
}
func (r GetAttachmentContentRequest) Validate() bool {
return r.Variant == "" || r.Variant == "original"
}
func ToAttachmentResponse(a model.Attachment) AttachmentResponse {
variants := make([]VariantResponse, 0)
return AttachmentResponse{
+26
View File
@@ -3,6 +3,7 @@ package handler
import (
"errors"
"net/http"
"time"
"github.com/go-chi/chi/v5"
"github.com/google/uuid"
@@ -43,11 +44,25 @@ func (h *AttachmentHandler) Upload(w http.ResponseWriter, r *http.Request) {
return
}
if deadline, ok := r.Context().Deadline(); ok {
controller := http.NewResponseController(w)
if err := controller.SetReadDeadline(deadline); err != nil {
httpx.WriteInternalError(w, requestID, err)
return
}
defer func() { _ = controller.SetReadDeadline(time.Time{}) }()
}
contentType := r.Header.Get("Content-Type")
r.Body = http.MaxBytesReader(w, r.Body, int64(h.maxBytes))
att, err := h.service.Upload(r.Context(), userID, chatID, req.Filename, r.Body, contentType)
switch {
case errors.Is(err, service.ErrUploadReadTimeout):
r.Close = true
w.Header().Set("Connection", "close")
httpx.WriteError(w, http.StatusRequestTimeout, dto.ErrorCodeInvalidRequest, "upload body read timed out", requestID)
return
case errors.Is(err, service.ErrInvalidSize):
httpx.WriteError(w, http.StatusRequestEntityTooLarge, dto.ErrorCodePayloadTooLarge, "file too large", requestID)
return
@@ -98,8 +113,19 @@ func (h *AttachmentHandler) GetContent(w http.ResponseWriter, r *http.Request) {
return
}
req := dto.GetAttachmentContentRequest{
Variant: r.URL.Query().Get("variant"),
}
if !req.Validate() {
httpx.WriteError(w, http.StatusNotFound, dto.ErrorCodeNotFound, "not found", requestID)
return
}
data, contentType, err := h.service.GetContent(r.Context(), userID, attachmentID)
switch {
case errors.Is(err, service.ErrAttachmentNotReady):
httpx.WriteError(w, http.StatusConflict, dto.ErrorCodeConflict, "attachment not ready", requestID)
return
case errors.Is(err, service.ErrAttachmentNotFound):
httpx.WriteError(w, http.StatusNotFound, dto.ErrorCodeNotFound, "not found", requestID)
return
+6 -3
View File
@@ -64,11 +64,14 @@ func (h *AuthHandler) RevokeSession(w http.ResponseWriter, r *http.Request) {
}
err := h.service.Logout(r.Context(), token)
if errors.Is(err, service.ErrUnauthorized) {
switch {
case errors.Is(err, service.ErrSessionCacheUnavailable):
httpx.WriteError(w, http.StatusServiceUnavailable, dto.ErrorCodeUnavailable, "session cache unavailable", requestID)
return
case errors.Is(err, service.ErrUnauthorized):
httpx.WriteUnauthorized(w, httpx.BearerChallenge, requestID)
return
}
if err != nil {
case err != nil:
httpx.WriteInternalError(w, requestID, err)
return
}
+16 -14
View File
@@ -18,12 +18,12 @@ type Pinger interface {
}
type HealthHandler struct {
log *slog.Logger
db Pinger
log *slog.Logger
dependencies []Pinger
}
func NewHealthHandler(log *slog.Logger, db Pinger) *HealthHandler {
return &HealthHandler{log: log, db: db}
func NewHealthHandler(log *slog.Logger, dependencies ...Pinger) *HealthHandler {
return &HealthHandler{log: log, dependencies: dependencies}
}
func (h *HealthHandler) Live(w http.ResponseWriter, r *http.Request) {
@@ -39,16 +39,18 @@ func (h *HealthHandler) Ready(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), readyPingTimeout)
defer cancel()
if err := h.db.Ping(ctx); err != nil {
h.log.ErrorContext(r.Context(), "readiness check failed", "error", err)
httpx.WriteError(
w,
http.StatusServiceUnavailable,
dto.ErrorCodeUnavailable,
"service unavailable",
w.Header().Get("X-Request-Id"),
)
return
for _, dependency := range h.dependencies {
if err := dependency.Ping(ctx); err != nil {
h.log.ErrorContext(r.Context(), "readiness check failed", "error", err)
httpx.WriteError(
w,
http.StatusServiceUnavailable,
dto.ErrorCodeUnavailable,
"service unavailable",
w.Header().Get("X-Request-Id"),
)
return
}
}
w.Header().Set("Content-Type", "application/json")
+2 -1
View File
@@ -11,6 +11,7 @@ import (
"github.com/jackc/pgx/v5/pgconn"
"mtusi2026-messenger/internal/dto"
s3store "mtusi2026-messenger/internal/s3"
)
func WriteJSON(w http.ResponseWriter, status int, body any) {
@@ -51,7 +52,7 @@ func WriteInternalError(w http.ResponseWriter, requestID string, err error) {
}
func isUnavailable(err error) bool {
if errors.Is(err, context.DeadlineExceeded) {
if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, s3store.ErrUnavailable) {
return true
}
+4
View File
@@ -11,6 +11,10 @@ type responseWriter struct {
status int
}
func (w *responseWriter) Unwrap() http.ResponseWriter {
return w.ResponseWriter
}
func (w *responseWriter) WriteHeader(status int) {
w.status = status
w.ResponseWriter.WriteHeader(status)
+23 -2
View File
@@ -5,6 +5,7 @@ import (
"errors"
"io"
"log/slog"
"net"
"net/http"
"time"
@@ -19,6 +20,7 @@ import (
)
var (
ErrUnavailable = errors.New("s3 unavailable")
ErrLoadConfig = errors.New("load aws config")
ErrHeadBucket = errors.New("head bucket")
ErrCreateBucket = errors.New("create bucket")
@@ -118,6 +120,15 @@ func (c *Client) EnsureBucket(ctx context.Context) error {
return ErrCreateBucket
}
func (c *Client) Ping(ctx context.Context) error {
_, err := c.api.HeadBucket(ctx, &awss3.HeadBucketInput{Bucket: aws.String(c.bucket)})
if err != nil {
c.log.Error("head bucket", "bucket", c.bucket, "error", err)
return operationError(ErrHeadBucket, err)
}
return nil
}
func (c *Client) Put(
ctx context.Context,
key string,
@@ -134,7 +145,7 @@ func (c *Client) Put(
})
if err != nil {
c.log.Error("put object", "bucket", c.bucket, "key", key, "error", err)
return ErrPutObject
return operationError(ErrPutObject, err)
}
return nil
@@ -151,7 +162,7 @@ func (c *Client) Get(ctx context.Context, key string) (*awss3.GetObjectOutput, e
}
if err != nil {
c.log.Error("get object", "bucket", c.bucket, "key", key, "error", err)
return nil, ErrGetObject
return nil, operationError(ErrGetObject, err)
}
return out, nil
@@ -228,6 +239,16 @@ func newS3Client(
}), nil
}
func operationError(operation, err error) error {
var networkError net.Error
var responseError *awshttp.ResponseError
if errors.Is(err, context.DeadlineExceeded) || errors.As(err, &networkError) ||
(errors.As(err, &responseError) && responseError.HTTPStatusCode() >= 500) {
return ErrUnavailable
}
return operation
}
func isNotFound(err error) bool {
var responseErr *awshttp.ResponseError
if errors.As(err, &responseErr) && responseErr.HTTPStatusCode() == http.StatusNotFound {
+48 -13
View File
@@ -9,6 +9,7 @@ import (
_ "image/jpeg"
_ "image/png"
"io"
"net"
"net/http"
"os"
@@ -22,8 +23,10 @@ import (
var (
ErrAttachmentNotFound = errors.New("attachment not found")
ErrAttachmentNotReady = errors.New("attachment not ready")
ErrInvalidImage = errors.New("invalid image")
ErrInvalidSize = errors.New("invalid size")
ErrUploadReadTimeout = errors.New("upload body read timed out")
)
type attachmentQueries interface {
@@ -34,10 +37,11 @@ type attachmentQueries interface {
}
type AttachmentService struct {
q attachmentQueries
s3 *s3store.Client
maxBytes int
maxPixels int
q attachmentQueries
s3 *s3store.Client
maxBytes int
maxPixels int
decodeSlot chan struct{}
}
func NewAttachmentService(
@@ -46,10 +50,11 @@ func NewAttachmentService(
maxBytes, maxPixels int,
) *AttachmentService {
return &AttachmentService{
q: q,
s3: s3,
maxBytes: maxBytes,
maxPixels: maxPixels,
q: q,
s3: s3,
maxBytes: maxBytes,
maxPixels: maxPixels,
decodeSlot: make(chan struct{}, 1),
}
}
@@ -80,6 +85,10 @@ func (s *AttachmentService) Upload(
if errors.As(err, &maxBytesErr) {
return model.Attachment{}, ErrInvalidSize
}
var networkErr net.Error
if errors.As(err, &networkErr) && networkErr.Timeout() {
return model.Attachment{}, ErrUploadReadTimeout
}
return model.Attachment{}, err
}
if size > int64(s.maxBytes) {
@@ -89,7 +98,7 @@ func (s *AttachmentService) Upload(
if _, err := tmp.Seek(0, io.SeekStart); err != nil {
return model.Attachment{}, err
}
detectedType, err := s.checkImage(tmp, contentType)
detectedType, err := s.checkImage(ctx, tmp, contentType)
if err != nil {
return model.Attachment{}, err
}
@@ -195,6 +204,10 @@ func (s *AttachmentService) GetContent(
return nil, "", err
}
if model.AttachmentStatus(row.Status) != model.AttachmentStatusReady {
return nil, "", ErrAttachmentNotReady
}
out, err := s.s3.Get(ctx, row.S3Key)
if err != nil {
return nil, "", err
@@ -209,30 +222,52 @@ func (s *AttachmentService) GetContent(
return data, model.ContentType(row.ContentType), nil
}
func (s *AttachmentService) checkImage(r io.Reader, contentType string) (model.ContentType, error) {
func (s *AttachmentService) checkImage(ctx context.Context, r io.ReadSeeker, contentType string) (model.ContentType, error) {
cfg, format, err := image.DecodeConfig(r)
if err != nil {
return "", ErrInvalidImage
}
if cfg.Width*cfg.Height > s.maxPixels {
if cfg.Width <= 0 || cfg.Height <= 0 {
return "", ErrInvalidImage
}
if cfg.Width > s.maxPixels/cfg.Height {
return "", ErrInvalidSize
}
var detectedType model.ContentType
switch format {
case "png":
if contentType != string(model.ContentTypePNG) {
return "", ErrInvalidImage
}
return model.ContentTypePNG, nil
detectedType = model.ContentTypePNG
case "jpeg":
if contentType != string(model.ContentTypeJPEG) {
return "", ErrInvalidImage
}
return model.ContentTypeJPEG, nil
detectedType = model.ContentTypeJPEG
default:
return "", ErrInvalidImage
}
select {
case s.decodeSlot <- struct{}{}:
defer func() { <-s.decodeSlot }()
case <-ctx.Done():
return "", ctx.Err()
}
if err := ctx.Err(); err != nil {
return "", err
}
if _, err := r.Seek(0, io.SeekStart); err != nil {
return "", err
}
if _, _, err := image.Decode(r); err != nil {
return "", ErrInvalidImage
}
return detectedType, nil
}
func (s *AttachmentService) ensureMember(ctx context.Context, userID, chatID uuid.UUID) error {
+10 -5
View File
@@ -19,8 +19,9 @@ const sessionCacheTTL = 60 * time.Second
const cacheOpTimeout = 300 * time.Millisecond
var (
ErrInvalidCredentials = errors.New("invalid credentials")
ErrUnauthorized = errors.New("unauthorized")
ErrInvalidCredentials = errors.New("invalid credentials")
ErrUnauthorized = errors.New("unauthorized")
ErrSessionCacheUnavailable = errors.New("session cache unavailable")
)
type authQueries interface {
@@ -118,7 +119,9 @@ func (s *AuthService) Logout(ctx context.Context, token string) error {
return err
}
s.cacheDel(ctx, cacheKey(tokenHash))
if err := s.cacheDel(ctx, cacheKey(tokenHash)); err != nil {
return ErrSessionCacheUnavailable
}
if n == 0 {
return ErrUnauthorized
@@ -169,9 +172,9 @@ func (s *AuthService) cacheSet(ctx context.Context, key string, id uuid.UUID, tt
}
}
func (s *AuthService) cacheDel(ctx context.Context, key string) {
func (s *AuthService) cacheDel(ctx context.Context, key string) error {
if s.cache == nil {
return
return nil
}
cctx, cancel := context.WithTimeout(ctx, cacheOpTimeout)
@@ -179,5 +182,7 @@ func (s *AuthService) cacheDel(ctx context.Context, key string) {
if err := s.cache.Del(cctx, key).Err(); err != nil {
s.log.Warn("session cache delete failed", "error", err)
return err
}
return nil
}
-1
View File
@@ -20,7 +20,6 @@ import (
var (
ErrMessageChatNotFound = errors.New("chat not found")
ErrAttachmentNotReady = errors.New("attachment not ready")
ErrIdempotencyKeyConflict = errors.New("idempotency key reused with different request")
)
+92
View File
@@ -0,0 +1,92 @@
//go:build failure
package studenttests_test
import (
"bytes"
"context"
"io"
"net/http"
"os/exec"
"strings"
"testing"
"time"
"mtusi2026-messenger/internal/dto"
)
func TestAttachmentUploaderFailover(t *testing.T) {
user := createUser(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)
uploader := resp.Header.Get("X-Instance-Id")
var att dto.AttachmentResponse
mustDecode(t, resp, &att)
if uploader == "" {
t.Fatal("upload response has no X-Instance-Id")
}
cmd := exec.Command("docker", "compose", "ps", "-q", "api")
cmd.Dir = ".."
out, err := cmd.Output()
if err != nil {
t.Fatalf("list API replicas: %v", err)
}
replicas := strings.Fields(string(out))
if len(replicas) < 2 {
t.Fatal("at least two running API replicas required")
}
var target string
for _, id := range replicas {
if strings.HasPrefix(id, uploader) {
target = id
break
}
}
if target == "" {
t.Fatal("upload instance is not an API container in this Compose project")
}
t.Cleanup(func() {
if err := exec.Command("docker", "start", target).Run(); err != nil {
t.Errorf("restart uploader replica: %v", err)
}
})
if err := exec.Command("docker", "stop", "-t", "5", target).Run(); err != nil {
t.Fatalf("stop uploader replica: %v", err)
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
for ctx.Err() == nil {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, *baseURL+"/api/v1/attachments/"+att.ID.String()+"/content", nil)
if err != nil {
t.Fatal(err)
}
req.Header.Set("Authorization", "Bearer "+user.Token)
response, err := httpClient.Do(req)
if err == nil {
data, readErr := io.ReadAll(response.Body)
response.Body.Close()
if response.StatusCode == http.StatusOK {
downloader := response.Header.Get("X-Instance-Id")
if downloader == "" || downloader == uploader {
t.Fatal("download was not served by another replica")
}
if readErr != nil {
t.Fatal(readErr)
}
if !bytes.Equal(data, original) {
t.Fatal("downloaded original differs from uploaded file")
}
return
}
if response.StatusCode != http.StatusBadGateway && response.StatusCode != http.StatusServiceUnavailable && response.StatusCode != http.StatusGatewayTimeout {
t.Fatalf("unexpected download status: %d", response.StatusCode)
}
}
time.Sleep(200 * time.Millisecond)
}
t.Fatal("download through another replica did not recover within 10s")
}
+106
View File
@@ -0,0 +1,106 @@
//go:build contract || reconcile || failure
package studenttests_test
import (
"bytes"
"encoding/json"
"net/http"
"net/url"
"testing"
"github.com/google/uuid"
"mtusi2026-messenger/internal/dto"
)
const maxUploadBytes = 10 * 1024 * 1024
func uploadAttachment(
t *testing.T,
actor testUser,
chatID uuid.UUID,
filename string,
contentType string,
body []byte,
) *http.Response {
t.Helper()
req, err := http.NewRequest(
http.MethodPost,
*baseURL+"/api/v1/chats/"+chatID.String()+"/attachments?filename="+url.QueryEscape(filename),
bytes.NewReader(body),
)
if err != nil {
t.Fatalf("build upload request: %v", err)
}
req.Header.Set("Content-Type", contentType)
req.Header.Set("Authorization", "Bearer "+actor.Token)
resp, err := httpClient.Do(req)
if err != nil {
t.Fatalf("upload request failed: %v", err)
}
return resp
}
func uploadPNG(t *testing.T, actor testUser, chatID uuid.UUID) dto.AttachmentResponse {
t.Helper()
resp := uploadAttachment(t, actor, chatID, "sample.png", "image/png", makePNG(t, 32, 32))
requireStatus(t, resp, http.StatusCreated)
var att dto.AttachmentResponse
mustDecode(t, resp, &att)
return att
}
func postMessage(
t *testing.T,
actor testUser,
chatID uuid.UUID,
text string,
attachmentIDs []uuid.UUID,
) *http.Response {
t.Helper()
body, err := json.Marshal(map[string]any{
"text": text,
"attachment_ids": attachmentIDs,
})
if err != nil {
t.Fatalf("marshal message: %v", err)
}
req, err := http.NewRequest(
http.MethodPost,
*baseURL+"/api/v1/chats/"+chatID.String()+"/messages",
bytes.NewReader(body),
)
if err != nil {
t.Fatalf("build message request: %v", err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+actor.Token)
req.Header.Set("Idempotency-Key", uuid.NewString())
resp, err := httpClient.Do(req)
if err != nil {
t.Fatalf("message request failed: %v", err)
}
return resp
}
func requireErrorCode(t *testing.T, resp *http.Response, code dto.ErrorCode) {
t.Helper()
var apiErr dto.ErrorResponse
mustDecode(t, resp, &apiErr)
if apiErr.Error.Code != code {
t.Errorf("expected error code %q, got %q", code, apiErr.Error.Code)
}
}
+41 -73
View File
@@ -4,9 +4,10 @@ package studenttests_test
import (
"bytes"
"encoding/json"
"image/jpeg"
"image/png"
"io"
"net/http"
"net/url"
"testing"
"github.com/google/uuid"
@@ -14,95 +15,62 @@ import (
"mtusi2026-messenger/internal/dto"
)
const maxUploadBytes = 10 * 1024 * 1024
func TestAttachmentJPEG(t *testing.T) {
user := createUser(t)
chat := createChat(t, user, user.ID)
func uploadAttachment(
t *testing.T,
actor testUser,
chatID uuid.UUID,
filename string,
contentType string,
body []byte,
) *http.Response {
t.Helper()
req, err := http.NewRequest(
http.MethodPost,
*baseURL+"/api/v1/chats/"+chatID.String()+"/attachments?filename="+url.QueryEscape(filename),
bytes.NewReader(body),
)
img, err := png.Decode(bytes.NewReader(makePNG(t, 32, 32)))
if err != nil {
t.Fatalf("build upload request: %v", err)
t.Fatalf("decode png: %v", err)
}
req.Header.Set("Content-Type", contentType)
req.Header.Set("Authorization", "Bearer "+actor.Token)
resp, err := httpClient.Do(req)
if err != nil {
t.Fatalf("upload request failed: %v", err)
var body bytes.Buffer
if err := jpeg.Encode(&body, img, nil); err != nil {
t.Fatalf("encode jpeg: %v", err)
}
return resp
}
func uploadPNG(t *testing.T, actor testUser, chatID uuid.UUID) dto.AttachmentResponse {
t.Helper()
resp := uploadAttachment(t, actor, chatID, "sample.png", "image/png", makePNG(t, 32, 32))
resp := uploadAttachment(t, user, chat.ID, "sample.jpg", "image/jpeg", body.Bytes())
requireStatus(t, resp, http.StatusCreated)
var att dto.AttachmentResponse
mustDecode(t, resp, &att)
if att.Status != "ready" {
t.Fatalf("expected ready attachment, got %q", att.Status)
}
return att
resp = doRequest(t, http.MethodGet, "/api/v1/attachments/"+att.ID.String()+"/content", user.Token, nil)
requireStatus(t, resp, http.StatusOK)
defer resp.Body.Close()
original, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatalf("read original: %v", err)
}
if !bytes.Equal(original, body.Bytes()) {
t.Error("downloaded JPEG differs from uploaded original")
}
}
func postMessage(
t *testing.T,
actor testUser,
chatID uuid.UUID,
text string,
attachmentIDs []uuid.UUID,
) *http.Response {
t.Helper()
func TestAttachmentTooManyPixels(t *testing.T) {
user := createUser(t)
chat := createChat(t, user, user.ID)
body, err := json.Marshal(map[string]any{
"text": text,
"attachment_ids": attachmentIDs,
})
if err != nil {
t.Fatalf("marshal message: %v", err)
body := makePNG(t, 8000, 5001)
if len(body) > maxUploadBytes {
t.Fatal("pixel-limit fixture exceeds upload byte limit")
}
req, err := http.NewRequest(
http.MethodPost,
*baseURL+"/api/v1/chats/"+chatID.String()+"/messages",
bytes.NewReader(body),
)
if err != nil {
t.Fatalf("build message request: %v", err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+actor.Token)
req.Header.Set("Idempotency-Key", uuid.NewString())
resp, err := httpClient.Do(req)
if err != nil {
t.Fatalf("message request failed: %v", err)
}
return resp
resp := uploadAttachment(t, user, chat.ID, "large.png", "image/png", body)
requireStatus(t, resp, http.StatusRequestEntityTooLarge)
requireErrorCode(t, resp, dto.ErrorCodePayloadTooLarge)
}
func requireErrorCode(t *testing.T, resp *http.Response, code dto.ErrorCode) {
t.Helper()
func TestAttachmentUnsafeFilename(t *testing.T) {
user := createUser(t)
chat := createChat(t, user, user.ID)
var apiErr dto.ErrorResponse
mustDecode(t, resp, &apiErr)
if apiErr.Error.Code != code {
t.Errorf("expected error code %q, got %q", code, apiErr.Error.Code)
}
resp := uploadAttachment(t, user, chat.ID, "../image.png", "image/png", makePNG(t, 32, 32))
requireStatus(t, resp, http.StatusBadRequest)
requireErrorCode(t, resp, dto.ErrorCodeInvalidRequest)
}
func TestAttachmentTooLarge(t *testing.T) {
+67
View File
@@ -3,10 +3,14 @@
package studenttests_test
import (
"bytes"
"io"
"net/http"
"os/exec"
"testing"
"time"
"mtusi2026-messenger/internal/dto"
)
func compose(t *testing.T, args ...string) {
@@ -87,3 +91,66 @@ func TestDatabaseDown(t *testing.T) {
requireStatus(t, resp, http.StatusUnauthorized)
resp.Body.Close()
}
func TestS3Down(t *testing.T) {
user := createUser(t)
chat := createChat(t, user, user.ID)
original := makePNG(t, 32, 32)
att := uploadPNG(t, user, chat.ID)
stopService(t, "s3")
for _, path := range []string{"/health/ready", "/api/v1/attachments/" + att.ID.String() + "/content"} {
resp := doRequest(t, http.MethodGet, path, user.Token, nil)
requireStatus(t, resp, http.StatusServiceUnavailable)
requireErrorCode(t, resp, dto.ErrorCodeUnavailable)
}
resp := uploadAttachment(t, user, chat.ID, "outage.png", "image/png", original)
requireStatus(t, resp, http.StatusServiceUnavailable)
requireErrorCode(t, resp, dto.ErrorCodeUnavailable)
resp = doRequest(t, http.MethodGet, "/health/live", "", nil)
requireStatus(t, resp, http.StatusOK)
resp.Body.Close()
compose(t, "start", "s3")
waitReady(t)
deadline := time.Now().Add(60 * time.Second)
downloaded, uploaded := false, false
for time.Now().Before(deadline) && (!downloaded || !uploaded) {
if !downloaded {
req, err := http.NewRequest(http.MethodGet, *baseURL+"/api/v1/attachments/"+att.ID.String()+"/content", nil)
if err != nil {
t.Fatal(err)
}
req.Header.Set("Authorization", "Bearer "+user.Token)
response, err := httpClient.Do(req)
if err == nil {
data, readErr := io.ReadAll(response.Body)
response.Body.Close()
if response.StatusCode == http.StatusOK && readErr == nil {
if !bytes.Equal(data, original) {
t.Fatal("original changed across S3 outage")
}
downloaded = true
} else if response.StatusCode != http.StatusServiceUnavailable && response.StatusCode != http.StatusBadGateway && response.StatusCode != http.StatusGatewayTimeout {
t.Fatalf("unexpected download recovery status: %d", response.StatusCode)
}
}
}
if !uploaded {
response := uploadAttachment(t, user, chat.ID, "recovery.png", "image/png", original)
status := response.StatusCode
response.Body.Close()
if status == http.StatusCreated {
uploaded = true
} else if status != http.StatusServiceUnavailable {
t.Fatalf("unexpected upload recovery status: %d", status)
}
}
if !downloaded || !uploaded {
time.Sleep(500 * time.Millisecond)
}
}
if !downloaded || !uploaded {
t.Fatalf("S3 did not recover in 60s: download=%t upload=%t", downloaded, uploaded)
}
}
+169
View File
@@ -0,0 +1,169 @@
//go:build reconcile
package studenttests_test
import (
"bytes"
"context"
"encoding/json"
"io"
"net/http"
"os"
"os/exec"
"slices"
"strings"
"testing"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"mtusi2026-messenger/internal/reconcile"
)
func reconcileDB(t *testing.T) *pgx.Conn {
t.Helper()
secret, err := os.ReadFile("../secrets/test_database_url.txt")
if err != nil {
t.Fatalf("read test database URL: %v", err)
}
conn, err := pgx.Connect(context.Background(), strings.TrimSpace(string(secret)))
if err != nil {
t.Fatalf("connect to test database: %v", err)
}
t.Cleanup(func() { conn.Close(context.Background()) })
return conn
}
func reconcileSQL(t *testing.T, conn *pgx.Conn, query string, args ...any) {
t.Helper()
if _, err := conn.Exec(context.Background(), query, args...); err != nil {
t.Fatalf("prepare/check reconcile fixture: %v", err)
}
}
func runReconcile(t *testing.T, dryRun bool, grace string) reconcile.Report {
t.Helper()
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
defer cancel()
dry := "false"
if dryRun {
dry = "true"
}
cmd := exec.CommandContext(ctx, "docker", "compose", "--env-file", ".env", "run", "--rm", "--no-deps", "reconcile", "-json", "-dry-run="+dry, "-grace="+grace)
cmd.Dir = ".."
var stderr bytes.Buffer
cmd.Stderr = &stderr
output, err := cmd.Output()
if err != nil {
t.Fatalf("run reconciler: %v\n%s", err, stderr.String())
}
var report 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)
if len(report.Errors) != 0 {
t.Fatal("reconciler reported errors")
}
return report
}
func TestReconcileRepair(t *testing.T) {
conn := reconcileDB(t)
user := createUser(t)
chat := createChat(t, user, user.ID)
att := uploadPNG(t, user, chat.ID)
var originalKey string
if err := conn.QueryRow(context.Background(), "SELECT s3_key FROM attachments WHERE id=$1", att.ID).Scan(&originalKey); err != nil {
t.Fatal(err)
}
// Simulate lost metadata for the original object and metadata pointing at a missing object.
reconcileSQL(t, conn, "UPDATE attachments SET s3_key=$2 WHERE id=$1", att.ID, "chats/reconcile-missing/"+uuid.NewString())
// Only this experiment uses a shortened grace period, to avoid waiting an hour.
time.Sleep(1100 * time.Millisecond)
dry := runReconcile(t, true, "1s")
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 {
t.Fatal("dry-run changed data")
}
var status, code string
if err := conn.QueryRow(context.Background(), "SELECT status::text FROM attachments WHERE id=$1", att.ID).Scan(&status); err != nil {
t.Fatal(err)
}
if status != "ready" {
t.Fatalf("dry-run changed status: %s", status)
}
repair := runReconcile(t, false, "1s")
if repair.DeletedObjects < 1 || repair.MarkedFailed < 1 {
t.Fatal("repair did not apply fixes")
}
if err := conn.QueryRow(context.Background(), "SELECT status::text, error_code FROM attachments WHERE id=$1", att.ID).Scan(&status, &code); err != nil {
t.Fatal(err)
}
if status != "failed" || code != "object_missing" {
t.Fatalf("unexpected repaired state: %s %s", status, code)
}
again := runReconcile(t, false, "1s")
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 {
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")
}
func TestReconcileSafety(t *testing.T) {
conn := reconcileDB(t)
user := createUser(t)
chat := createChat(t, user, user.ID)
fresh := uploadPNG(t, user, chat.ID)
used := uploadPNG(t, user, chat.ID)
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.
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() {
if _, err := conn.Exec(context.Background(), "UPDATE attachments SET status='ready' WHERE id=ANY($1::uuid[])", []uuid.UUID{fresh.ID, used.ID}); err != nil {
t.Errorf("restore fixture status: %v", err)
}
})
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")
}
for _, att := range []uuid.UUID{fresh.ID, used.ID} {
var status string
if err := conn.QueryRow(context.Background(), "SELECT status::text FROM attachments WHERE id=$1", att).Scan(&status); err != nil {
t.Fatal(err)
}
if status != "queued" {
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)
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")
}
func TestReconcileCost(t *testing.T) {
for i := 1; i <= 3; i++ {
t.Logf("scan %d/3", i)
runReconcile(t, true, "1h")
}
}
+6 -2
View File
@@ -8,13 +8,13 @@ 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
.PHONY: help-go contract-go race-go load-go failure-go load-action-go reconcile reconcile-test-go
help-go:
@echo "contract-go: contract tests"
@echo "race-go: concurrency tests (-race)"
@echo "load-go: load test"
@echo "failure-go: dependency failure tests (stops redis/postgres containers)"
@echo "failure-go: dependency failure tests (stops redis/postgres/s3 containers)"
@echo "reconcile: attachment audit; DRY_RUN=false to repair"
contract-go:
@@ -38,3 +38,7 @@ load-action-go:
reconcile:
docker compose --env-file .env run --rm --no-deps reconcile -dry-run=$(DRY_RUN)
reconcile-test-go:
docker compose --env-file .env build reconcile
go test -count=1 -tags=reconcile ./student-tests/... -v -args -base-url=$(BASE_URL)