Compare commits
56
Commits
@@ -18,3 +18,10 @@ S3_ACCESS_KEY_ID_FILE=/run/secrets/s3_access_key_id
|
||||
S3_SECRET_ACCESS_KEY_FILE=/run/secrets/s3_secret_access_key
|
||||
MAX_UPLOAD_BYTES=10485760
|
||||
MAX_IMAGE_PIXELS=40000000
|
||||
MINIO_ROOT_USER=...
|
||||
MINIO_CPUS=0.5
|
||||
MINIO_MEMORY=512M
|
||||
# --- Reconciler ---
|
||||
RECONCILER_ENABLED=true
|
||||
RECONCILER_INTERVAL_SECONDS=300
|
||||
RECONCILER_GRACE_SECONDS=3600
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
# Контейнеры Linux; shell-скрипты, Dockerfile, конфиги nginx/yaml
|
||||
# должны иметь LF независимо от core.autocrlf на стороне разработчика.
|
||||
*.sh text eol=lf
|
||||
*.bash text eol=lf
|
||||
Dockerfile text eol=lf
|
||||
Dockerfile.* text eol=lf
|
||||
*.yml text eol=lf
|
||||
*.yaml text eol=lf
|
||||
*.go text eol=lf
|
||||
*.sql text eol=lf
|
||||
*.md text eol=lf
|
||||
*.conf text eol=lf
|
||||
|
||||
# Windows-специфичные - CRLF
|
||||
*.bat text eol=crlf
|
||||
*.cmd text eol=crlf
|
||||
@@ -1,37 +1,444 @@
|
||||
# Отчёт — лабораторная 4
|
||||
# Отчёт - лабораторная 4
|
||||
|
||||
- Автор, группа: TODO
|
||||
- Целевая оценка; выбранный трек 5, если нужен: TODO
|
||||
- Commit/PR: TODO после публикации
|
||||
- Использованные источники, библиотеки и помощь ИИ: TODO
|
||||
- Автор, группа: Голиков Антон, БВТ2303
|
||||
- Целевая оценка: на 4 (уровни 3+4, без трека 5)
|
||||
- Commit/PR: ветка `solution/BVT2303-Golikov`, PR будет открыт после публикации
|
||||
- Использованные источники, библиотеки и помощь ИИ:
|
||||
- Скелет лабы 4 и материалы курса: COURSE.md, contracts/openapi.json,
|
||||
contracts/README.md, contracts/infrastructure.json
|
||||
- Документация MinIO (mc admin user/policy, bucket policy), S3 API
|
||||
(PutObject/GetObject/ListObjects), pgx v5, goose, gin
|
||||
- Собственная реализация лабы 3: Go 1.26, gin, pgx, goose, Redis,
|
||||
nginx, две API-реплики, X-Instance-Id, Idempotency-Key
|
||||
- ИИ (ChatGPT) использован для структуры отчёта, вычитки формулировок
|
||||
и подсказок по рутинным местам (политика MinIO, healthcheck).
|
||||
Весь код, конфигурация, эксперименты и финальные тексты проверены
|
||||
и объясняются автором на защите.
|
||||
|
||||
## Запуск из чистого clone
|
||||
|
||||
TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных.
|
||||
Prerequisites:
|
||||
|
||||
- Docker Desktop 4.30+ (WSL2 backend) или Docker Engine с Compose v2.20+
|
||||
- Go 1.26+ (для локальной сборки без Docker; в Docker-варианте не нужен)
|
||||
- Python 3.9+ (для публичных тестов из scaffold)
|
||||
- git, make
|
||||
|
||||
Шаги запуска:
|
||||
|
||||
1. Клонировать fork и перейти на ветку solution:
|
||||
|
||||
git clone https://gitea.privcloud.tech/Maximillan_Mercer/mtusi2026lab4-fork.git
|
||||
cd mtusi2026lab4
|
||||
git checkout solution/BVT2303-Golikov
|
||||
|
||||
2. Создать локальные secrets. Значения генерируются оператором, в Git
|
||||
не попадают. Добавились четыре секрета для S3 (в дополнение к трём
|
||||
из lab2-3):
|
||||
|
||||
mkdir -p secrets
|
||||
|
||||
# PostgreSQL (как в lab2-3)
|
||||
PW="$(openssl rand -hex 16)"
|
||||
printf "%s" "$PW" > secrets/postgres_password
|
||||
printf "%s" "postgres://messenger:$PW@postgres:5432/messenger?sslmode=disable" \
|
||||
> secrets/database_url
|
||||
printf "%s" "redis://redis:6379/0" > secrets/cache_url
|
||||
|
||||
# MinIO root (только для mc-init, API их не видит)
|
||||
printf "%s" "messenger-minio-root" > secrets/minio_root_user
|
||||
openssl rand -base64 32 | tr -d '\r\n' > secrets/minio_root_password
|
||||
|
||||
# S3 API-креды (для сервиса api)
|
||||
printf "%s" "messenger-api" > secrets/s3_access_key_id
|
||||
openssl rand -hex 32 > secrets/s3_secret_access_key
|
||||
|
||||
chmod 600 secrets/*
|
||||
|
||||
3. Создать .env из .env.example:
|
||||
|
||||
cp .env.example .env
|
||||
|
||||
Переменные и дефолты, которые изменились относительно lab3:
|
||||
|
||||
- S3_ENDPOINT=http://minio:9000
|
||||
- S3_BUCKET=messenger-attachments
|
||||
- S3_REGION=us-east-1
|
||||
- S3_USE_SSL=false
|
||||
- S3_ACCESS_KEY_ID_FILE=/run/secrets/s3_access_key_id
|
||||
- S3_SECRET_ACCESS_KEY_FILE=/run/secrets/s3_secret_access_key
|
||||
- MAX_UPLOAD_BYTES=10485760 (10 MiB)
|
||||
- MAX_IMAGE_PIXELS=40000000 (40 млн)
|
||||
- RECONCILER_ENABLED=true
|
||||
- RECONCILER_INTERVAL_SECONDS=300
|
||||
- RECONCILER_GRACE_SECONDS=3600 (1 час)
|
||||
- MINIO_ROOT_USER=messenger-minio-root
|
||||
- MINIO_CPUS=0.5, MINIO_MEMORY=512M
|
||||
|
||||
Остальные переменные (SESSION_STORE=redis, SESSION_TTL_SECONDS,
|
||||
IDEMPOTENCY_TTL_SECONDS, SHUTDOWN_DRAIN_SECONDS, лимиты CPU/RAM,
|
||||
API_REPLICAS=2, LB_PORT=8080) без изменений от lab3.
|
||||
|
||||
4. Собрать образ API и запустить стек:
|
||||
|
||||
docker compose build api
|
||||
docker compose up -d
|
||||
|
||||
5. Дождаться, пока mc-init создаст bucket и API-пользователя,
|
||||
и применились миграции 0001–0004:
|
||||
|
||||
docker compose logs migrate
|
||||
# ожидать: goose: successfully migrated database to version: 4
|
||||
# при первом запуске: OK 0001..0004
|
||||
docker compose logs mc-init
|
||||
# ожидать: minio bootstrap ok: bucket=messenger-attachments user=messenger-api
|
||||
|
||||
curl -sS http://localhost:8080/health/ready
|
||||
# ожидать: {"status":"ok"}
|
||||
|
||||
Сервис mc-init идемпотентен: повторный `docker compose run --rm mc-init`
|
||||
не падает и не дублирует bucket или policy. API использует отдельные
|
||||
S3-креды (messenger-api, policy только на messenger-attachments/*);
|
||||
root-креды MinIO видят только minio и mc-init.
|
||||
|
||||
6. Прогнать публичный smoke и проверки от scaffold:
|
||||
|
||||
PYTHONUTF8=1 make check
|
||||
PYTHONUTF8=1 make test
|
||||
|
||||
7. Проверки сохранности и отказа (требуют scripts/restart.sh и
|
||||
scripts/stop-one.sh из lab3, они перенесены):
|
||||
|
||||
PYTHONUTF8=1 make test-persistence ACTION_SCRIPT=scripts/restart.sh
|
||||
PYTHONUTF8=1 make test-failover ACTION_SCRIPT=scripts/stop-one.sh
|
||||
|
||||
|
||||
Версии образов (закреплены в compose.yaml):
|
||||
|
||||
- pgsty/silo:RELEASE.2026-09-16T00-00-00Z — drop-in MinIO fork.
|
||||
Оригинальный minio/minio заархивирован в 2025-м, официальные
|
||||
community-образы сняты с Docker Hub; pgsty/silo сохраняет S3 API,
|
||||
mc и healthcheck без изменений.
|
||||
- postgres:16.4-alpine
|
||||
- redis:7.4-alpine
|
||||
- nginx:1.27.4-alpine
|
||||
- mtusi-messenger-api:lab3 — собственный образ, собирается из Dockerfile
|
||||
|
||||
Безопасная остановка:
|
||||
|
||||
docker compose stop # остановить контейнеры, volumes сохранить
|
||||
docker compose down # удалить контейнеры и сеть, volumes сохранить
|
||||
|
||||
Остановка с удалением учебных данных (необратимо, удалит все volumes):
|
||||
|
||||
docker compose down -v
|
||||
|
||||
Отдельно про .env и secrets: оба пути в .gitignore, в репозиторий не
|
||||
попадают. Значения паролей синтетические, для локального стенда.
|
||||
|
||||
## Архитектура и решения
|
||||
|
||||
TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab3, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации.
|
||||
Схема:
|
||||
|
||||
client (curl / python / smoke)
|
||||
|
|
||||
v
|
||||
nginx LB (:8080) единственная публичная точка
|
||||
|
|
||||
+-> api-1 :8080 реплика 1
|
||||
+-> api-2 :8080 реплика 2
|
||||
|
|
||||
+-> postgres :5432 users, chats, chat_members, messages,
|
||||
| sessions, idempotency_keys, attachments,
|
||||
| message_attachments
|
||||
+-> redis :6379 сессии (SESSION_STORE=redis)
|
||||
+-> minio :9000 S3, приватный bucket messenger-attachments
|
||||
(порты наружу не публикуются)
|
||||
|
|
||||
+-- mc-init (одноразовый) bootstrap: bucket + policy + API-user
|
||||
+-- migrate (одноразовый) goose up
|
||||
|
||||
Источник истины - PostgreSQL для метаданных и S3 для бинарных байтов.
|
||||
Разделение намеренное: байты не хранятся в БД (не BLOB, не локальный
|
||||
каталог api), только в приватном bucket; в Postgres - object_key,
|
||||
sha256, content_type, size_bytes, status, привязка к chat_id и к
|
||||
message_attachments. Через S3 любая API-реплика читает любую вложенность
|
||||
одинаково; локальный volume API не годится, потому что файл лежит только
|
||||
на одной реплике и теряется при её остановке - это критерий README
|
||||
уровня 3 "Upload → остановка обслужившей API → download через другую
|
||||
возвращает тот же файл".
|
||||
|
||||
Сессии - в Redis (без изменений от lab2-3). Без sticky session на LB
|
||||
любая реплика видит любую сессию.
|
||||
|
||||
Транзакционные границы:
|
||||
|
||||
- Создание чата - одна транзакция в Postgres (chats + chat_members).
|
||||
- Идемпотентная отправка сообщения - одна транзакция: слот в
|
||||
idempotency_keys, проверка и линковка attachments, INSERT в messages,
|
||||
INSERT в message_attachments. Либо всё, либо ничего.
|
||||
- Загрузка вложения - две точки сохранения без общей транзакции (S3
|
||||
и Postgres - разные системы). Последовательность:
|
||||
|
||||
INSERT attachments (status='pending', object_key, sha256) → COMMIT
|
||||
PutObject в S3 → OK/FAIL
|
||||
UPDATE attachments status='ready' → COMMIT
|
||||
|
||||
Это ключевая граница lab4. Ниже - как каждый отказ на этой границе
|
||||
компенсируется.
|
||||
|
||||
- Регистрация - один INSERT с UNIQUE-индексом на username (23505 →
|
||||
409 через mapError).
|
||||
|
||||
Компенсация и сверка (уровень 4):
|
||||
|
||||
- Отказ между INSERT и PutObject. Строка pending осталась, объекта в
|
||||
S3 нет. Handler ловит ошибку PutObject и сразу вызывает
|
||||
MarkFailed(id, "upload_failed") - компенсация в том же запросе, без
|
||||
ожидания reconciler.
|
||||
|
||||
- Отказ между PutObject и UPDATE status='ready'. Объект в S3 есть,
|
||||
строка pending. Это и есть "вечный неучтённый объект", если ничего
|
||||
не делать. Закрывает reconciler: ListStalePending(now - grace) →
|
||||
Delete(object_key) → DeletePending(id). Grace 1 час: свежие pending
|
||||
(реальные upload'ы) не трогаются, только застрявшие.
|
||||
|
||||
- Обратный случай: PutObject прошёл, INSERT в Postgres упал. Объект
|
||||
в S3 есть, строки в БД нет - orphan. Закрывает reconciler:
|
||||
List(S3) → отфильтровать LastModified < now - grace → ExistingKeys(DB)
|
||||
→ Delete тех, которых нет в БД. Grace 1 час защищает свежий Put,
|
||||
чей INSERT ещё не закоммичен.
|
||||
|
||||
- Reconciler запускается во всех репликах, но использует
|
||||
pg_try_advisory_lock: одна реплика на tick берёт session-level
|
||||
advisory lock, остальные пропускают tick. Postgres автоматически
|
||||
освобождает лок, если процесс упал.
|
||||
|
||||
Отдельные S3-креды и приватность bucket:
|
||||
|
||||
- Root-креды MinIO (minio_root_user/minio_root_password) видят только
|
||||
minio и mc-init. API-контейнер их не получает.
|
||||
- API использует messenger-api с policy только на messenger-attachments
|
||||
(GetObject, PutObject, DeleteObject на bucket/*, ListBucket на bucket).
|
||||
Создание/удаление bucket, policy, пользователей недоступны.
|
||||
- Bucket приватный: без подписи GET возвращает 403. Проверяется в
|
||||
evidence/s3-private.txt.
|
||||
- MINIO_BROWSER=off: административная консоль не слушается. Порты
|
||||
9000/9001 не публикуются на хост (только внутри internal-сети).
|
||||
|
||||
Что перенесено из lab3 без изменений:
|
||||
|
||||
- Схема БД: users, chats, chat_members, messages, sessions
|
||||
- idempotency_keys с TTL 24 часа, Idempotency-Key обязателен
|
||||
- X-Instance-Id в каждом ответе API (os.Hostname())
|
||||
- Миграции goose, отдельный процесс /server migrate
|
||||
- Graceful drain на SIGTERM, atomic ready-флаг, SHUTDOWN_DRAIN_SECONDS
|
||||
- CPU/RAM лимиты на api, postgres, redis через deploy.resources
|
||||
- nginx LB перед двумя репликами, upstream keepalive
|
||||
- Горизонтальное масштабирование: две реплики, общие сессии в Redis
|
||||
|
||||
Что добавлено/изменено в lab4:
|
||||
|
||||
1. Отдельный сервис minio (pgsty/silo), persistent volume minio_data.
|
||||
2. Одноразовый сервис mc-init: создаёт bucket, policy, API-user.
|
||||
Идемпотентен.
|
||||
3. Миграция 0003: таблицы attachments и message_attachments, индексы,
|
||||
ограничения (status, size, sha256, content_type, filename).
|
||||
4. Миграция 0004: ослаблен CHECK messages_text_not_blank - пустой
|
||||
текст разрешён при наличии вложений (lab4 anyOf), но
|
||||
whitespace-only по-прежнему запрещён.
|
||||
5. Три endpoint: POST /chats/{chat_id}/attachments (raw bytes PNG/JPEG,
|
||||
max 10 MiB, max 40M пикселей), GET /attachments/{id} и
|
||||
GET /attachments/{id}/content (без redirect, только участникам чата).
|
||||
6. POST /messages принимает attachment_ids (0-10), все вложения должны
|
||||
принадлежать этому чату и быть ready; anyOf text или attachments.
|
||||
7. RequestHash расширен: sha256(text) без attachments (обратная
|
||||
совместимость с lab3), sha256(text + 0x00 + ids) с attachments.
|
||||
8. Reconciler в API, pg advisory lock, две задачи (stale pending,
|
||||
orphan objects), grace 1 час.
|
||||
9. Healthcheck /health/ready пингует S3 (BucketExists).
|
||||
10. nginx client_max_body_size=12m (10 MiB upload + запас на 11 MiB
|
||||
negative-тест, чтобы 413 шёл от API с X-Request-Id, а не от nginx).
|
||||
|
||||
Соответствие переменных .env.example реальной конфигурации (новое
|
||||
в lab4):
|
||||
|
||||
- S3_ENDPOINT, S3_BUCKET, S3_REGION, S3_USE_SSL - читаются в
|
||||
config.Load, идут в s3.Config. Для внутреннего MinIO
|
||||
http://minio:9000, SSL=false.
|
||||
- S3_ACCESS_KEY_ID_FILE, S3_SECRET_ACCESS_KEY_FILE - secrets в
|
||||
/run/secrets, читаются через readSecretOptional.
|
||||
- MAX_UPLOAD_BYTES - идёт в AttachmentService (io.LimitReader body =
|
||||
maxBytes+1, 413 при превышении).
|
||||
- MAX_IMAGE_PIXELS - идёт в AttachmentService (image.DecodeConfig,
|
||||
413 при W*H > maxPixels).
|
||||
- RECONCILER_ENABLED, RECONCILER_INTERVAL_SECONDS,
|
||||
RECONCILER_GRACE_SECONDS - читаются в config.Load, идут в
|
||||
service.Reconciler.
|
||||
- MINIO_ROOT_USER - только для minio и mc-init, не попадает в api.
|
||||
|
||||
## Доказательства критериев
|
||||
|
||||
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
|
||||
| --- | --- | --- | --- |
|
||||
| Публичный smoke | make test | TODO | TODO |
|
||||
| Остальные пункты уровня 3 | TODO | TODO | TODO |
|
||||
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO |
|
||||
| Выбранный трек 5, если заявлен | TODO | TODO | TODO |
|
||||
Все evidence-файлы лежат в `evidence/`, содержат только обезличенные
|
||||
результаты и не включают токены, пароли, signed URL или приватные
|
||||
ключи.
|
||||
|
||||
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены.
|
||||
Уровень 3:
|
||||
|
||||
| Критерий | Команда | Наблюдаемый результат | Файл |
|
||||
| --- | --- | --- | --- |
|
||||
| Публичный smoke | `PYTHONUTF8=1 make test` | PASS: lab4 public API scenario | evidence/smoke.txt |
|
||||
| >= 2 API-реплики за LB | `docker compose ps` | api-1 и api-2 Up (healthy), LB публикует :8080 | evidence/container-state.txt |
|
||||
| Остановка одной реплики <= 10 с | `make test-failover` | first_recovery_seconds 5.48 | evidence/failover-1.txt |
|
||||
| Поочерёдная остановка каждой (автотест) | `make test-failover` дважды | recovery 5.48 и 5.34, дублей нет | evidence/failover-1.txt, failover-2.txt |
|
||||
| Поочерёдная остановка каждой (ручной) | `docker stop api-1`, потом `api-2` | после остановки каждой отвечает ровно один X-Instance-Id | evidence/failover-manual.txt |
|
||||
| Идемпотентность POST | smoke + failover (replay с тем же ключом) | тот же ответ, дублей нет | evidence/smoke.txt, failover-*.txt |
|
||||
| Persistence после restart | `make test-persistence` | PASS, StartedAt всех контейнеров обновился | evidence/persistence.txt |
|
||||
| S3-сервер в общем стенде, приватный bucket | `docker compose ps`, `mc ls local` | minio Up (healthy), bucket messenger-attachments (0 B) | evidence/container-state.txt |
|
||||
| Метаданные в Postgres, байты в S3 | `psql \d attachments`, `mc ls` | таблица attachments; object_key в S3 | evidence/s3-private.txt, container-state.txt |
|
||||
| POST вложения возвращает 201 ready | smoke, test_attachments | 201 ready, sha256/size совпадают | evidence/attachments-negative.txt |
|
||||
| Download побайтно, sha256 совпадает | smoke | download.bytes == original | evidence/smoke.txt |
|
||||
| Чужой участник получает 404 на метаданные и байты | test_attachments | 404 без 403 | evidence/attachments-negative.txt |
|
||||
| Прямой GET S3 без подписи -> 403 | `wget http://minio:9000/messenger-attachments/<key>` | HTTP/1.1 403 Forbidden | evidence/s3-private.txt |
|
||||
| Upload -> остановка обслужившей API -> download через другую | failover (файл приложен до отказа) | download через другую реплику == оригинал | evidence/failover-1.txt, failover-2.txt |
|
||||
| Restart с сохранением volumes сохраняет оригинал | persistence | PASS, download == исходный файл | evidence/persistence.txt |
|
||||
| S3 недоступен -> 503 без утечек | `docker compose stop minio` | /health/ready 503 unavailable; LB снимает реплики | evidence/s3-down.txt |
|
||||
| Не более 10 MiB, не более 40M пикселей | test_attachments | 11 MiB -> 413 payload_too_large | evidence/attachments-negative.txt |
|
||||
| MIME по содержимому | test_attachments | PNG-байты с Content-Type image/jpeg -> 201, content_type image/png | evidence/attachments-negative.txt |
|
||||
| Опасные filename отклоняются | test_attachments | /, \\, NUL -> 400 invalid_request | evidence/attachments-negative.txt |
|
||||
|
||||
Уровень 4:
|
||||
|
||||
| Критерий | Команда | Наблюдаемый результат | Файл |
|
||||
| --- | --- | --- | --- |
|
||||
| Тест слишком большого файла | test_attachments (11 MiB) | 413 payload_too_large, не 500 | evidence/attachments-negative.txt |
|
||||
| Тест повреждённого изображения | test_attachments (signature без IHDR) | 415 unsupported_media_type | evidence/attachments-negative.txt |
|
||||
| Тест подмены MIME | test_attachments (PNG как image/jpeg) | 201, content_type определён по magic bytes | evidence/attachments-negative.txt |
|
||||
| Тест чужого attachment_id | test_attachments (eve -> metadata и bytes) | 404 без утечки существования | evidence/attachments-negative.txt |
|
||||
| Тест attachment_id из другого чата | test_attachments (message с чужим id) | 404 not_found | evidence/attachments-negative.txt |
|
||||
| Пользовательская ошибка не превращается в 500 | test_attachments | все отказы 4xx; ни одна не 500 | evidence/attachments-negative.txt |
|
||||
| Отказ S3/БД не оставляет вечных неучтённых объектов | reconciler с ускоренными интервалами | stale pending и orphan-объект удалены; pending_left=0 | evidence/reconciler.txt |
|
||||
| Документированный grace period | README/REPORT, плюс evidence | ListStalePending(now - 1h), orphan только старше 1h | этот отчёт, evidence/reconciler.txt |
|
||||
| Лимиты до неограниченного чтения | код + memory test | io.LimitReader(maxBytes+1), image.DecodeConfig до декодирования | student-tests/test_memory.py |
|
||||
| >=10 одновременных загрузок с измерением пика RAM | test_memory.py + cgroups v2 | пик 141 MiB на каждой реплике <= 256 MiB лимита | evidence/memory-10x10mb.txt |
|
||||
| Bucket bootstrap идемпотентен | `docker compose run --rm mc-init` дважды | exit 0, "no such bucket / user exists" не срабатывает | этот отчёт |
|
||||
| API использует отдельные S3-креды с ограниченными правами | `mc admin user list`, policy | только messenger-api, GetObject/PutObject/DeleteObject на bucket/* | evidence/s3-private.txt |
|
||||
| Административная консоль не открыта в общей сети | `docker compose port minio 9001`, `printenv MINIO_BROWSER` | порт не проброшен, браузер off | evidence/s3-private.txt |
|
||||
| Проверка private bucket вне API | `wget http://minio:9000/messenger-attachments/<key>` | 403 Forbidden без подписи | evidence/s3-private.txt |
|
||||
|
||||
## Эксперименты и отказы
|
||||
|
||||
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения.
|
||||
Общая среда: Windows 10, Docker Desktop (WSL2 backend), одна физическая
|
||||
машина, на которой работают и весь стенд, и клиенты тестов.
|
||||
Все пользователи и изображения синтетические. Версии: PostgreSQL 16.4,
|
||||
Redis 7.4, nginx 1.27.4, pgsty/silo RELEASE.2026-09-16T00-00-00Z
|
||||
(MinIO fork), Go 1.26.
|
||||
|
||||
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
|
||||
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления, потеря данных |
|
||||
| --- | --- | --- | --- |
|
||||
| TODO | TODO | TODO | TODO |
|
||||
| Остановка одной API-реплики | writes продолжаются через LB, без дублей | recovery 5.48 / 5.34 с, повтор с тем же ключом даёт то же сообщение | 5–6 с, потерь нет |
|
||||
| Поочерёдная остановка api-1 и api-2 вручную | каждый раз обслуживает оставшаяся | после stop api-1 отвечает один X-Instance-Id, после stop api-2 другой | <20 с суммарно, потерь нет |
|
||||
| Перезапуск всего стека (`scripts/restart.sh`) | данные, сессии и файлы сохранены | StartedAt всех контейнеров обновился, PASS, прежний токен работает | в пределах бюджета теста, потерь нет |
|
||||
| Остановка minio | /health/ready 503, LB снимает реплики; после start всё возвращается | ровно так; после start оба X-Instance-Id вернулись | ~15–20 с, потерь нет |
|
||||
| Stale pending (2 минуты) при grace 30 с (для теста) | reconciler удаляет строку и объект | "reconciler: sweep done pending=1 orphans=0", pending_left=0 | на следующем tick (≤10 с в тестовом прогоне) |
|
||||
| Orphan-объект в S3 старше grace | reconciler удаляет объект | лог orphans=N, объект удалён | аналогично |
|
||||
| 10 параллельных upload по 10 MiB | RAM каждой реплики в пределах 256 MiB | 10 upload за 1.79 с, peak 138 / 141.5 MiB | пик не превышен, OOM нет |
|
||||
|
||||
Пояснения:
|
||||
|
||||
- Ошибки в окне переключения nginx при остановке API-реплики - нормальны
|
||||
и разрешены README уровня 3 ("краткие ошибки во время обнаружения
|
||||
отказа измеряются и допустимы"). После 5 секунд writes продолжаются.
|
||||
- Reconciler в тесте запускался с `RECONCILER_INTERVAL_SECONDS=10` и
|
||||
`RECONCILER_GRACE_SECONDS=30`, чтобы уложиться в минуту. В дефолтной
|
||||
конфигурации интервал 5 минут, grace 1 час - для реальной работы
|
||||
это безопаснее, потому что не трогает свежие upload'ы и только что
|
||||
загруженные объекты, чей INSERT ещё в полёте.
|
||||
- Пик RAM 141 MiB на реплике - не от upload'ов, а от Argon2id при
|
||||
регистрации пользователей (6 операций × 64 MiB malloc при bootstrap).
|
||||
Upload'ы добавили только +1..4 MiB к peak, потому что Go heap уже
|
||||
раздут GC и `io.LimitReader` ограничивает каждый upload 10 MiB.
|
||||
Худший сценарий 141 + 100 = 240 MiB < 256 MiB - укладывается с
|
||||
запасом.
|
||||
|
||||
## Ограничения и следующие шаги
|
||||
|
||||
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза.
|
||||
Что выдерживает:
|
||||
|
||||
- Отказ одной API-реплики при живом S3 и Postgres.
|
||||
- Перезапуск API и всех хранилищ (Postgres, Redis, MinIO) с сохранением
|
||||
volumes - данные, сессии и файлы.
|
||||
- Отказ S3: /health/ready 503 без утечек, LB снимает реплики, после
|
||||
восстановления всё возвращается.
|
||||
- Отказ между INSERT и PutObject: компенсация MarkFailed в том же
|
||||
запросе, без ожидания reconciler.
|
||||
- Отказ между PutObject и UPDATE ready: reconciler через grace period
|
||||
(1 час) удаляет застрявшие pending и объект.
|
||||
- Orphan-объекты (Put прошёл, INSERT упал): reconciler через grace
|
||||
period удаляет объекты в S3, которых нет в БД.
|
||||
- 10 параллельных upload по 10 MiB - peak RAM каждой реплики
|
||||
укладывается в лимит 256 MiB.
|
||||
|
||||
Что не выдерживает:
|
||||
|
||||
- Отказ узла. Всё работает на одном хосте, потеря хоста = потеря
|
||||
системы. PostgreSQL и MinIO без репликации, nginx LB без резерва.
|
||||
- Отказ MinIO на длительное время (например, потеря volume): файлы
|
||||
не восстановятся, потому что второй копии нет. Метаданные в
|
||||
Postgres остаются, скачивание отдаёт 404/503.
|
||||
- Grace period reconciler (1 час) защищает от случайного удаления
|
||||
живых загрузок, но не является транзакционной гарантией. В
|
||||
редком случае ровно на границе grace и очень медленной загрузки
|
||||
возможен false-positive, теоретически удаление свежего объекта.
|
||||
Вероятность пренебрежимо мала для учебного стенда, но в реальной
|
||||
работе grace стоит увеличивать до нескольких часов и добавлять
|
||||
heartbeat-обновление updated_at у активных загрузок.
|
||||
- Медленная сеть к S3: reconciler обходит ListObjects и Delete
|
||||
по одному, что на больших бакетах станет дорого. На учебном
|
||||
бакете это не проявляется.
|
||||
|
||||
Не реализовано в этой работе:
|
||||
|
||||
- Трек 5 (presigned upload или повторяемый reconciler с dry-run и
|
||||
инъекцией ошибок) - целевая оценка 4, трек 5 не заявлен.
|
||||
- Background worker и thumbnail (это уже lab5).
|
||||
- Argon2id вместо текущего KDF в lab7, TLS/mTLS, OpenBao.
|
||||
- HTTPS. По контракту до lab7 достаточно HTTP для локального стенда.
|
||||
- Rate limiting: схема допускает `429`, реализация не требуется.
|
||||
|
||||
Учебные упрощения:
|
||||
|
||||
- MinIO fork pgsty/silo: `minio/minio` заархивирован, официальных
|
||||
community-образов с 2025 нет. pgsty/silo - drop-in замена с тем же
|
||||
S3 API и mc; версия образа закреплена.
|
||||
- Роль reconciler в одной реплике через pg advisory lock. Не является
|
||||
распределённой HA-сверкой; при потере хоста обе реплики и
|
||||
reconciler исчезают.
|
||||
- БД и S3 в одном экземпляре, оба на том же хосте, что и API. Для
|
||||
уровня 3-4 достаточно, для продакшена нужны репликация БД,
|
||||
версионирование S3, отдельный хост под reconciler/worker.
|
||||
|
||||
Подтверждённые улучшения (сводка по lab4):
|
||||
|
||||
- Метаданные и бинарные данные разнесены: Postgres - источник истины
|
||||
для структуры, S3 - источник истины для байтов. Файл в локальном
|
||||
volume API не равен объектному хранилищу, потому что при остановке
|
||||
реплики файл недоступен через другую; S3 решает это.
|
||||
- Grace period reconciler (1 час) не трогает живые загрузки и свежие
|
||||
Put-объекты: stale pending и orphans обрабатываются только после
|
||||
истечения срока.
|
||||
- Отдельные S3-креды с ограниченной policy плюс приватный bucket
|
||||
плюс MINIO_BROWSER=off: административный доступ к S3 полностью
|
||||
изолирован от API. Проверяется в evidence/s3-private.txt.
|
||||
- nginx client_max_body_size=12m: иначе nginx режет на 1 MiB по
|
||||
умолчанию, 413 летит без X-Request-Id (это ответ LB, а не API),
|
||||
и публичный тест падает "missing X-Request-Id".
|
||||
- Миграция 0004 ослабляет CHECK messages_text_not_blank до
|
||||
`text !~ '^[[:space:]]+$'`: `text=""` с attachments валиден по
|
||||
lab4 anyOf, а whitespace-only по-прежнему запрещён на уровне БД.
|
||||
|
||||
Следующий шаг для полной картины: увеличить grace period reconciler
|
||||
до нескольких часов и добавить heartbeat от активных загрузок
|
||||
(обновление updated_at), чтобы устранить теоретический false-positive
|
||||
на границе grace. Для production-варианта - вынести reconciler в
|
||||
отдельный процесс/реплику и добавить репликацию БД и S3.
|
||||
@@ -21,6 +21,7 @@ import (
|
||||
"high-loud-apps-labs/internal/service"
|
||||
"high-loud-apps-labs/internal/storage/postgres"
|
||||
redisstore "high-loud-apps-labs/internal/storage/redis"
|
||||
s3store "high-loud-apps-labs/internal/storage/s3"
|
||||
)
|
||||
|
||||
func main() {
|
||||
@@ -64,8 +65,37 @@ func main() {
|
||||
chatSvc := service.NewChatService(store.Chats(), store.Users())
|
||||
messageSvc := service.NewMessageService(store.Messages(), store.Chats(), cfg.IdempotencyTTL)
|
||||
|
||||
if !cfg.S3Configured() {
|
||||
log.Fatal("S3 не настроен: задайте S3_ENDPOINT, S3_BUCKET, S3_ACCESS_KEY_ID_FILE/S3_ACCESS_KEY_ID, S3_SECRET_ACCESS_KEY_FILE/S3_SECRET_ACCESS_KEY")
|
||||
}
|
||||
|
||||
objectStorage, err := s3store.New(ctx, s3store.Config{
|
||||
Endpoint: cfg.S3Endpoint,
|
||||
Bucket: cfg.S3Bucket,
|
||||
AccessKey: cfg.S3AccessKey,
|
||||
SecretKey: cfg.S3SecretKey,
|
||||
UseSSL: cfg.S3UseSSL,
|
||||
Region: cfg.S3Region,
|
||||
})
|
||||
if err != nil {
|
||||
var unavailable *domain.UnavailableError
|
||||
if errors.As(err, &unavailable) {
|
||||
log.Fatalf("s3: %v (reason: %s)", err, unavailable.Reason)
|
||||
}
|
||||
log.Fatalf("s3: %v", err)
|
||||
}
|
||||
|
||||
attachmentSvc := service.NewAttachmentService(
|
||||
store.Attachments(),
|
||||
store.Chats(),
|
||||
objectStorage,
|
||||
cfg.MaxUploadBytes,
|
||||
cfg.MaxImagePixels,
|
||||
)
|
||||
|
||||
healthChecks := []handler.HealthCheck{
|
||||
func(ctx context.Context) error { return pool.Ping(ctx) },
|
||||
func(ctx context.Context) error { return objectStorage.Ping(ctx) },
|
||||
}
|
||||
if cachePing != nil {
|
||||
healthChecks = append(healthChecks, cachePing)
|
||||
@@ -76,19 +106,32 @@ func main() {
|
||||
|
||||
router := httpapi.NewRouter(
|
||||
httpapi.Handlers{
|
||||
Health: handler.NewHealthHandler(healthChecks...).WithReadyFlag(&ready),
|
||||
User: handler.NewUserHandler(userSvc),
|
||||
Chat: handler.NewChatHandler(chatSvc),
|
||||
Message: handler.NewMessageHandler(messageSvc),
|
||||
Auth: handler.NewAuthHandler(sessionSvc),
|
||||
Health: handler.NewHealthHandler(healthChecks...).WithReadyFlag(&ready),
|
||||
User: handler.NewUserHandler(userSvc),
|
||||
Chat: handler.NewChatHandler(chatSvc),
|
||||
Message: handler.NewMessageHandler(messageSvc),
|
||||
Auth: handler.NewAuthHandler(sessionSvc),
|
||||
Attachment: handler.NewAttachmentHandler(attachmentSvc),
|
||||
},
|
||||
middleware.BearerAuth(sessionSvc),
|
||||
)
|
||||
|
||||
srv := &http.Server{Addr: addr, Handler: router}
|
||||
|
||||
reconcilerCtx, reconcilerCancel := context.WithCancel(context.Background())
|
||||
defer reconcilerCancel()
|
||||
if cfg.ReconcilerEnabled {
|
||||
reconciler := service.NewReconciler(
|
||||
store.Attachments(),
|
||||
objectStorage,
|
||||
pool,
|
||||
cfg.ReconcilerGracePeriod,
|
||||
)
|
||||
go reconciler.Run(reconcilerCtx, cfg.ReconcilerInterval)
|
||||
}
|
||||
|
||||
go func() {
|
||||
log.Printf("Запускаем на %s (SESSION_STORE=%s)", addr, cfg.SessionStore)
|
||||
log.Printf("Запускаем на %s (SESSION_STORE=%s, RECONCILER_ENABLED=%v)", addr, cfg.SessionStore, cfg.ReconcilerEnabled)
|
||||
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
|
||||
log.Fatalf("Ошибка запуска: %v", err)
|
||||
}
|
||||
@@ -100,6 +143,7 @@ func main() {
|
||||
|
||||
log.Printf("Получен сигнал завершения; readiness выключен, drain %s", cfg.ShutdownDrain)
|
||||
ready.Store(false)
|
||||
reconcilerCancel()
|
||||
|
||||
if cfg.ShutdownDrain > 0 {
|
||||
time.Sleep(cfg.ShutdownDrain)
|
||||
@@ -114,9 +158,6 @@ func main() {
|
||||
log.Println("Сервер остановлен")
|
||||
}
|
||||
|
||||
// runMigrate — одноразовый прогон goose. Запускается как `/server migrate`.
|
||||
// Использует те же DATABASE_URL_FILE / DATABASE_URL, что и сервер.
|
||||
// Отдельный процесс, поэтому не конкурирует с репликами за goose lock.
|
||||
func runMigrate() error {
|
||||
cfg, err := config.Load()
|
||||
if err != nil {
|
||||
|
||||
+18
-6
@@ -7,7 +7,9 @@ require (
|
||||
github.com/google/uuid v1.6.0
|
||||
github.com/jackc/pgerrcode v0.0.0-20250907135507-afb5586c32a6
|
||||
github.com/jackc/pgx/v5 v5.7.1
|
||||
github.com/minio/minio-go/v7 v7.4.1
|
||||
github.com/pressly/goose/v3 v3.22.1
|
||||
github.com/redis/go-redis/v9 v9.22.0
|
||||
golang.org/x/crypto v0.57.0
|
||||
)
|
||||
|
||||
@@ -17,6 +19,7 @@ require (
|
||||
github.com/bytedance/sonic/loader v0.5.0 // indirect
|
||||
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
||||
github.com/cloudwego/base64x v0.1.6 // indirect
|
||||
github.com/dustin/go-humanize v1.0.1 // indirect
|
||||
github.com/gabriel-vasile/mimetype v1.4.12 // indirect
|
||||
github.com/gin-contrib/sse v1.1.0 // indirect
|
||||
github.com/go-playground/locales v0.14.1 // indirect
|
||||
@@ -28,26 +31,35 @@ require (
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
||||
github.com/jackc/puddle/v2 v2.2.2 // indirect
|
||||
github.com/json-iterator/go v1.1.12 // indirect
|
||||
github.com/klauspost/cpuid/v2 v2.3.0 // indirect
|
||||
github.com/klauspost/compress v1.19.2 // indirect
|
||||
github.com/klauspost/cpuid/v2 v2.4.0 // indirect
|
||||
github.com/klauspost/crc32 v1.3.0 // indirect
|
||||
github.com/leodido/go-urn v1.4.0 // indirect
|
||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
github.com/mattn/go-isatty v0.0.22 // indirect
|
||||
github.com/mfridman/interpolate v0.0.2 // indirect
|
||||
github.com/minio/crc64nvme v1.1.1 // indirect
|
||||
github.com/minio/md5-simd v1.1.2 // indirect
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
|
||||
github.com/modern-go/reflect2 v1.0.2 // indirect
|
||||
github.com/pelletier/go-toml/v2 v2.2.4 // indirect
|
||||
github.com/pelletier/go-toml/v2 v2.4.3 // indirect
|
||||
github.com/philhofer/fwd v1.2.0 // indirect
|
||||
github.com/quic-go/qpack v0.6.0 // indirect
|
||||
github.com/quic-go/quic-go v0.59.0 // indirect
|
||||
github.com/redis/go-redis/v9 v9.22.0 // indirect
|
||||
github.com/rs/xid v1.6.0 // indirect
|
||||
github.com/sethvargo/go-retry v0.3.0 // indirect
|
||||
github.com/tinylib/msgp v1.6.4 // indirect
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
|
||||
github.com/ugorji/go/codec v1.3.1 // indirect
|
||||
github.com/zeebo/xxh3 v1.1.0 // indirect
|
||||
go.mongodb.org/mongo-driver/v2 v2.5.0 // indirect
|
||||
go.uber.org/atomic v1.11.0 // indirect
|
||||
go.uber.org/multierr v1.11.0 // indirect
|
||||
go.yaml.in/yaml/v3 v3.0.5 // indirect
|
||||
golang.org/x/arch v0.22.0 // indirect
|
||||
golang.org/x/net v0.58.0 // indirect
|
||||
golang.org/x/net v0.60.0 // indirect
|
||||
golang.org/x/sync v0.23.0 // indirect
|
||||
golang.org/x/sys v0.48.0 // indirect
|
||||
golang.org/x/text v0.42.0 // indirect
|
||||
google.golang.org/protobuf v1.36.10 // indirect
|
||||
google.golang.org/protobuf v1.36.12 // indirect
|
||||
gopkg.in/ini.v1 v1.67.3 // indirect
|
||||
)
|
||||
|
||||
+41
-14
@@ -1,3 +1,7 @@
|
||||
github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs=
|
||||
github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c=
|
||||
github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA=
|
||||
github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0=
|
||||
github.com/bytedance/gopkg v0.1.3 h1:TPBSwH8RsouGCBcMBktLt1AymVo2TVsBVCY4b6TnZ/M=
|
||||
github.com/bytedance/gopkg v0.1.3/go.mod h1:576VvJ+eJgyCzdjS+c4+77QF3p7ubbtiKARP3TxducM=
|
||||
github.com/bytedance/sonic v1.15.0 h1:/PXeWFaR5ElNcVE84U0dOHjiMHQOwNIx3K4ymzh/uSE=
|
||||
@@ -50,14 +54,25 @@ github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo
|
||||
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
|
||||
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
|
||||
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
|
||||
github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y=
|
||||
github.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=
|
||||
github.com/klauspost/compress v1.19.2 h1:hMRETovs/pu/dVWN7zIT1PGG8t509MwT6bO7XSi26R8=
|
||||
github.com/klauspost/compress v1.19.2/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ=
|
||||
github.com/klauspost/cpuid/v2 v2.0.1/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
|
||||
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/klauspost/crc32 v1.3.0 h1:sSmTt3gUt81RP655XGZPElI0PelVTZ6YwCRnPSupoFM=
|
||||
github.com/klauspost/crc32 v1.3.0/go.mod h1:D7kQaZhnkX/Y0tstFGf8VUzv2UofNGqCjnC3zdHB0Hw=
|
||||
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
|
||||
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
|
||||
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
||||
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/mattn/go-isatty v0.0.22 h1:j8l17JJ9i6VGPUFUYoTUKPSgKe/83EYU2zBC7YNKMw4=
|
||||
github.com/mattn/go-isatty v0.0.22/go.mod h1:ZXfXG4SQHsB/w3ZeOYbR0PrPwLy+n6xiMrJlRFqopa4=
|
||||
github.com/mfridman/interpolate v0.0.2 h1:pnuTK7MQIxxFz1Gr+rjSIx9u7qVjf5VOoM/u6BbAxPY=
|
||||
github.com/mfridman/interpolate v0.0.2/go.mod h1:p+7uk6oE07mpE/Ik1b8EckO0O4ZXiGAfshKBWLUM9Xg=
|
||||
github.com/minio/crc64nvme v1.1.1 h1:8dwx/Pz49suywbO+auHCBpCtlW1OfpcLN7wYgVR6wAI=
|
||||
github.com/minio/crc64nvme v1.1.1/go.mod h1:eVfm2fAzLlxMdUGc0EEBGSMmPwmXD5XiNRpnu9J3bvg=
|
||||
github.com/minio/md5-simd v1.1.2 h1:Gdi1DZK69+ZVMoNHRXJyNcxrMA4dSxoYHZSQbirFg34=
|
||||
github.com/minio/md5-simd v1.1.2/go.mod h1:MzdKDxYpY2BT9XQFocsiZf/NKVtR7nkE4RoEpN+20RM=
|
||||
github.com/minio/minio-go/v7 v7.4.1 h1:PtU/zIOfQRWZ+QydXAZysc+xZYHdG+BBR4Z6TUvy73w=
|
||||
github.com/minio/minio-go/v7 v7.4.1/go.mod h1:nQnQi7zTfXR4lREtYXZQWqo5aw0Rqv+ZqCGrTORygRk=
|
||||
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||
@@ -65,9 +80,10 @@ github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9G
|
||||
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
|
||||
github.com/ncruces/go-strftime v0.1.9 h1:bY0MQC28UADQmHmaF5dgpLmImcShSi2kHU9XLdhx/f4=
|
||||
github.com/ncruces/go-strftime v0.1.9/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
|
||||
github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4=
|
||||
github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pelletier/go-toml/v2 v2.4.3 h1:GTRvJQutkOSftxIFD5xw9aepkYNuPWmVJpffdDPYVpY=
|
||||
github.com/pelletier/go-toml/v2 v2.4.3/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
|
||||
github.com/philhofer/fwd v1.2.0 h1:e6DnBTl7vGY+Gz322/ASL4Gyp1FspeMvx1RNDoToZuM=
|
||||
github.com/philhofer/fwd v1.2.0/go.mod h1:RqIHx9QI14HlwKwm98g9Re5prTQ6LdeRQn+gXJFxsJM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/pressly/goose/v3 v3.22.1 h1:2zICEfr1O3yTP9BRZMGPj7qFxQ+ik6yeo+z1LMuioLc=
|
||||
github.com/pressly/goose/v3 v3.22.1/go.mod h1:xtMpbstWyCpyH+0cxLTMCENWBG+0CSxvTsXhW95d5eo=
|
||||
@@ -79,6 +95,8 @@ github.com/redis/go-redis/v9 v9.22.0 h1:laDvpYXTJtZLloinw1fA5Kqd6HAEH2XKxOkG/PDq
|
||||
github.com/redis/go-redis/v9 v9.22.0/go.mod h1:y2g0Wj8rQvuK0ELM+oxSudcLtC09JScs98I/X9gRWY4=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
|
||||
github.com/rs/xid v1.6.0 h1:fV591PaemRlL6JfRxGDEPl69wICngIQ3shQtzfy2gxU=
|
||||
github.com/rs/xid v1.6.0/go.mod h1:7XoLgs4eV+QndskICGsho+ADou8ySMSjJKDIan90Nz0=
|
||||
github.com/sethvargo/go-retry v0.3.0 h1:EEt31A35QhrcRZtrYFDTBg91cqZVnFL2navjDrah2SE=
|
||||
github.com/sethvargo/go-retry v0.3.0/go.mod h1:mNX17F0C/HguQMyMyJxcnU471gOZGxCLyYaFyAZraas=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
@@ -91,12 +109,19 @@ github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/
|
||||
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
|
||||
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
|
||||
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
|
||||
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||
github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
|
||||
github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=
|
||||
github.com/tinylib/msgp v1.6.4 h1:mOwYbyYDLPj35mkA2BjjYejgJk9BuHxDdvRnb6v2ZcQ=
|
||||
github.com/tinylib/msgp v1.6.4/go.mod h1:RSp0LW9oSxFut3KzESt5Voq4GVWyS+PSulT77roAqEA=
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
|
||||
github.com/ugorji/go/codec v1.3.1 h1:waO7eEiFDwidsBN6agj1vJQ4AG7lh2yqXyOXqhgQuyY=
|
||||
github.com/ugorji/go/codec v1.3.1/go.mod h1:pRBVtBSKl77K30Bv8R2P+cLSGaTtex6fsA2Wjqmfxj4=
|
||||
github.com/zeebo/assert v1.3.0 h1:g7C04CbJuIDKNPFHmsk4hwZDO5O+kntRxzaUoNXj+IQ=
|
||||
github.com/zeebo/assert v1.3.0/go.mod h1:Pq9JiuJQpG8JLJdtkwrJESF0Foym2/D9XMU5ciN/wJ0=
|
||||
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.mongodb.org/mongo-driver/v2 v2.5.0 h1:yXUhImUjjAInNcpTcAlPHiT7bIXhshCTL3jVBkF3xaE=
|
||||
go.mongodb.org/mongo-driver/v2 v2.5.0/go.mod h1:yOI9kBsufol30iFsl1slpdq1I0eHPzybRWdyYUs8K/0=
|
||||
go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE=
|
||||
@@ -105,24 +130,26 @@ go.uber.org/mock v0.6.0 h1:hyF9dfmbgIX5EfOdasqLsWD6xqpNZlXblLB/Dbnwv3Y=
|
||||
go.uber.org/mock v0.6.0/go.mod h1:KiVJ4BqZJaMj4svdfmHM0AUx4NJYO8ZNpPnZn1Z+BBU=
|
||||
go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=
|
||||
go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
|
||||
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/arch v0.22.0 h1:c/Zle32i5ttqRXjdLyyHZESLD/bB90DCU1g9l/0YBDI=
|
||||
golang.org/x/arch v0.22.0/go.mod h1:dNHoOeKiyja7GTvF9NJS1l3Z2yntpQNzgrjh1cU103A=
|
||||
golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M=
|
||||
golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA=
|
||||
golang.org/x/net v0.58.0 h1:ynWG7rqYi4ccpTEuPZ2QGWHktVEM9DMCj9yzDE0Q7To=
|
||||
golang.org/x/net v0.58.0/go.mod h1:YwCddHnFlT7eLQqVprV19OnhLGtc5xOKgE0RyqgfWAU=
|
||||
golang.org/x/net v0.60.0 h1:79p50tfZlm0J9YfoDsSi639qSXNGVwEzOPLCxM2FsYU=
|
||||
golang.org/x/net v0.60.0/go.mod h1:2DA/G1UfVbCpQPeWTmMPGY7Cs2PkBkwu743bVX5PIVg=
|
||||
golang.org/x/sync v0.23.0 h1:KameEIfc1IkluZyXWLn39Wd4tURc6GbCiISGiZm2bQk=
|
||||
golang.org/x/sync v0.23.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo=
|
||||
golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
|
||||
golang.org/x/text v0.42.0 h1:JbOZXgfeCPU9gacVtYliJqOhD+zhrEqK4LfdpmlUZqI=
|
||||
golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E=
|
||||
google.golang.org/protobuf v1.36.10 h1:AYd7cD/uASjIL6Q9LiTjz8JLcrh/88q5UObnmY3aOOE=
|
||||
google.golang.org/protobuf v1.36.10/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
|
||||
google.golang.org/protobuf v1.36.12 h1:pJOKDDOyeXErUroCihFAd5LQuwXBSpVnKGrj5o/fwxc=
|
||||
google.golang.org/protobuf v1.36.12/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/ini.v1 v1.67.3 h1:iM9Lhz5MRSGhHVGGwCuzG9KO8PoirCXj/m/qTmOJJQw=
|
||||
gopkg.in/ini.v1 v1.67.3/go.mod h1:x/cyOwCgZqOkJoDIJ3c1KNHMo10+nLGAhh+kn3Zizss=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
modernc.org/gc/v3 v3.0.0-20240107210532-573471604cb6 h1:5D53IMaUuA5InSeMu9eJtlQXS2NxAhyWQvkKEgXZhHI=
|
||||
modernc.org/gc/v3 v3.0.0-20240107210532-573471604cb6/go.mod h1:Qz0X07sNOR1jWYCrJMEnbW/X55x206Q7Vt4mz6/wHp4=
|
||||
|
||||
@@ -17,6 +17,20 @@ type Config struct {
|
||||
SessionTTL time.Duration
|
||||
IdempotencyTTL time.Duration
|
||||
ShutdownDrain time.Duration
|
||||
|
||||
S3Endpoint string
|
||||
S3Bucket string
|
||||
S3UseSSL bool
|
||||
S3Region string
|
||||
S3AccessKey string
|
||||
S3SecretKey string
|
||||
|
||||
MaxUploadBytes int64
|
||||
MaxImagePixels int64
|
||||
|
||||
ReconcilerEnabled bool
|
||||
ReconcilerInterval time.Duration
|
||||
ReconcilerGracePeriod time.Duration
|
||||
}
|
||||
|
||||
func Load() (*Config, error) {
|
||||
@@ -61,6 +75,58 @@ func Load() (*Config, error) {
|
||||
return nil, fmt.Errorf("SESSION_STORE=%q не поддерживается", store)
|
||||
}
|
||||
|
||||
s3Endpoint := getenv("S3_ENDPOINT", "")
|
||||
s3Bucket := getenv("S3_BUCKET", "")
|
||||
s3UseSSL, err := readBool("S3_USE_SSL", false)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("S3_USE_SSL: %w", err)
|
||||
}
|
||||
s3Region := getenv("S3_REGION", "us-east-1")
|
||||
|
||||
s3AccessKey, err := readSecretOptional("S3_ACCESS_KEY_ID_FILE", "S3_ACCESS_KEY_ID")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("s3 access key: %w", err)
|
||||
}
|
||||
s3SecretKey, err := readSecretOptional("S3_SECRET_ACCESS_KEY_FILE", "S3_SECRET_ACCESS_KEY")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("s3 secret key: %w", err)
|
||||
}
|
||||
|
||||
maxUploadBytes, err := readInt64("MAX_UPLOAD_BYTES", 10485760)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("MAX_UPLOAD_BYTES: %w", err)
|
||||
}
|
||||
if maxUploadBytes <= 0 {
|
||||
return nil, fmt.Errorf("MAX_UPLOAD_BYTES должен быть положительным")
|
||||
}
|
||||
|
||||
maxImagePixels, err := readInt64("MAX_IMAGE_PIXELS", 40000000)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("MAX_IMAGE_PIXELS: %w", err)
|
||||
}
|
||||
if maxImagePixels <= 0 {
|
||||
return nil, fmt.Errorf("MAX_IMAGE_PIXELS должен быть положительным")
|
||||
}
|
||||
|
||||
reconcilerEnabled, err := readBool("RECONCILER_ENABLED", true)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("RECONCILER_ENABLED: %w", err)
|
||||
}
|
||||
reconcilerIntervalSec, err := readInt("RECONCILER_INTERVAL_SECONDS", 300)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("RECONCILER_INTERVAL_SECONDS: %w", err)
|
||||
}
|
||||
if reconcilerIntervalSec <= 0 {
|
||||
return nil, fmt.Errorf("RECONCILER_INTERVAL_SECONDS должен быть положительным")
|
||||
}
|
||||
reconcilerGraceSec, err := readInt("RECONCILER_GRACE_SECONDS", 3600)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("RECONCILER_GRACE_SECONDS: %w", err)
|
||||
}
|
||||
if reconcilerGraceSec <= 0 {
|
||||
return nil, fmt.Errorf("RECONCILER_GRACE_SECONDS должен быть положительным")
|
||||
}
|
||||
|
||||
return &Config{
|
||||
Host: getenv("APP_HOST", "0.0.0.0"),
|
||||
Port: getenv("APP_PORT", "8080"),
|
||||
@@ -70,9 +136,30 @@ func Load() (*Config, error) {
|
||||
SessionTTL: time.Duration(ttlSeconds) * time.Second,
|
||||
IdempotencyTTL: time.Duration(idemSeconds) * time.Second,
|
||||
ShutdownDrain: time.Duration(drainSeconds) * time.Second,
|
||||
|
||||
S3Endpoint: s3Endpoint,
|
||||
S3Bucket: s3Bucket,
|
||||
S3UseSSL: s3UseSSL,
|
||||
S3Region: s3Region,
|
||||
S3AccessKey: s3AccessKey,
|
||||
S3SecretKey: s3SecretKey,
|
||||
|
||||
MaxUploadBytes: maxUploadBytes,
|
||||
MaxImagePixels: maxImagePixels,
|
||||
|
||||
ReconcilerEnabled: reconcilerEnabled,
|
||||
ReconcilerInterval: time.Duration(reconcilerIntervalSec) * time.Second,
|
||||
ReconcilerGracePeriod: time.Duration(reconcilerGraceSec) * time.Second,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (c *Config) S3Configured() bool {
|
||||
return c.S3Endpoint != "" &&
|
||||
c.S3Bucket != "" &&
|
||||
c.S3AccessKey != "" &&
|
||||
c.S3SecretKey != ""
|
||||
}
|
||||
|
||||
func getenv(key, def string) string {
|
||||
if v := os.Getenv(key); v != "" {
|
||||
return v
|
||||
@@ -92,6 +179,30 @@ func readInt(key string, def int) (int, error) {
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func readInt64(key string, def int64) (int64, error) {
|
||||
v := os.Getenv(key)
|
||||
if v == "" {
|
||||
return def, nil
|
||||
}
|
||||
n, err := strconv.ParseInt(v, 10, 64)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("не целое число: %q", v)
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func readBool(key string, def bool) (bool, error) {
|
||||
v := os.Getenv(key)
|
||||
if v == "" {
|
||||
return def, nil
|
||||
}
|
||||
b, err := strconv.ParseBool(v)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("не bool: %q", v)
|
||||
}
|
||||
return b, nil
|
||||
}
|
||||
|
||||
func readSecret(fileEnv, envKey string) (string, error) {
|
||||
v, err := readSecretOptional(fileEnv, envKey)
|
||||
if err != nil {
|
||||
|
||||
@@ -145,13 +145,18 @@ func (e *UnauthorizedError) Code() ErrorCode { return CodeUnauthorized }
|
||||
// увидит неверную подсказку.
|
||||
type UnsupportedMediaTypeError struct {
|
||||
MediaType string
|
||||
Expected string
|
||||
}
|
||||
|
||||
func (e *UnsupportedMediaTypeError) Error() string {
|
||||
if e.MediaType == "" {
|
||||
return "требуется Content-Type: application/json"
|
||||
expected := e.Expected
|
||||
if expected == "" {
|
||||
expected = "application/json"
|
||||
}
|
||||
return fmt.Sprintf("неподдерживаемый Content-Type %q; требуется application/json", e.MediaType)
|
||||
if e.MediaType == "" {
|
||||
return "требуется Content-Type: " + expected
|
||||
}
|
||||
return fmt.Sprintf("неподдерживаемый Content-Type %q; требуется %s", e.MediaType, expected)
|
||||
}
|
||||
func (e *UnsupportedMediaTypeError) Unwrap() error { return ErrUnsupportedMediaType }
|
||||
func (e *UnsupportedMediaTypeError) Code() ErrorCode { return CodeUnsupportedMediaType }
|
||||
|
||||
@@ -17,7 +17,17 @@ type CreateIdempotentResult struct {
|
||||
Replayed bool
|
||||
}
|
||||
|
||||
func RequestHash(text string) []byte {
|
||||
sum := sha256.Sum256([]byte(text))
|
||||
return sum[:]
|
||||
func RequestHash(text string, attachmentIDs []string) []byte {
|
||||
if len(attachmentIDs) == 0 {
|
||||
sum := sha256.Sum256([]byte(text))
|
||||
return sum[:]
|
||||
}
|
||||
h := sha256.New()
|
||||
h.Write([]byte(text))
|
||||
h.Write([]byte{0})
|
||||
for _, id := range attachmentIDs {
|
||||
h.Write([]byte(id))
|
||||
h.Write([]byte{0})
|
||||
}
|
||||
return h.Sum(nil)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"time"
|
||||
)
|
||||
|
||||
type ObjectInfo struct {
|
||||
Key string
|
||||
LastModified time.Time
|
||||
Size int64
|
||||
}
|
||||
|
||||
type ObjectStorage interface {
|
||||
Ping(ctx context.Context) error
|
||||
Put(ctx context.Context, key string, r io.Reader, size int64, contentType string) error
|
||||
Get(ctx context.Context, key string) (io.ReadCloser, int64, string, error)
|
||||
Delete(ctx context.Context, key string) error
|
||||
List(ctx context.Context, prefix string) ([]ObjectInfo, error)
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package dto
|
||||
|
||||
import (
|
||||
"encoding/hex"
|
||||
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
)
|
||||
|
||||
type VariantResponse struct {
|
||||
Name string `json:"name"`
|
||||
ContentType string `json:"content_type"`
|
||||
SizeBytes int64 `json:"size_bytes"`
|
||||
Width int `json:"width"`
|
||||
Height int `json:"height"`
|
||||
SHA256 string `json:"sha256"`
|
||||
}
|
||||
|
||||
type AttachmentResponse struct {
|
||||
ID string `json:"id"`
|
||||
ChatID string `json:"chat_id"`
|
||||
OwnerID string `json:"owner_id"`
|
||||
Filename string `json:"filename"`
|
||||
ContentType string `json:"content_type"`
|
||||
SizeBytes int64 `json:"size_bytes"`
|
||||
SHA256 string `json:"sha256"`
|
||||
Status string `json:"status"`
|
||||
Variants []VariantResponse `json:"variants"`
|
||||
ErrorCode *string `json:"error_code"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
UpdatedAt string `json:"updated_at"`
|
||||
}
|
||||
|
||||
func AttachmentFromDomain(a *domain.Attachment) AttachmentResponse {
|
||||
variants := make([]VariantResponse, 0)
|
||||
errCode := a.ErrorCode
|
||||
return AttachmentResponse{
|
||||
ID: a.ID,
|
||||
ChatID: a.ChatID,
|
||||
OwnerID: a.OwnerID,
|
||||
Filename: a.Filename,
|
||||
ContentType: a.ContentType,
|
||||
SizeBytes: a.SizeBytes,
|
||||
SHA256: hex.EncodeToString(a.SHA256),
|
||||
Status: string(a.Status),
|
||||
Variants: variants,
|
||||
ErrorCode: errCode,
|
||||
CreatedAt: a.CreatedAt.UTC().Format(timeFormat),
|
||||
UpdatedAt: a.UpdatedAt.UTC().Format(timeFormat),
|
||||
}
|
||||
}
|
||||
@@ -5,16 +5,17 @@ import (
|
||||
)
|
||||
|
||||
type CreateMessageRequest struct {
|
||||
Text string `json:"text" binding:"required,min=1,max=4000"`
|
||||
AttachmentIDs []string `json:"attachment_ids"`
|
||||
Text string `json:"text" binding:"max=4000"`
|
||||
AttachmentIDs []string `json:"attachment_ids" binding:"max=10,dive,uuid"`
|
||||
}
|
||||
|
||||
type MessageResponse struct {
|
||||
ID string `json:"id"`
|
||||
ChatID string `json:"chat_id"`
|
||||
SenderID string `json:"sender_id"`
|
||||
Text string `json:"text"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
ID string `json:"id"`
|
||||
ChatID string `json:"chat_id"`
|
||||
SenderID string `json:"sender_id"`
|
||||
Text string `json:"text"`
|
||||
AttachmentIDs []string `json:"attachment_ids"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
}
|
||||
|
||||
type MessagePageResponse struct {
|
||||
@@ -23,12 +24,17 @@ type MessagePageResponse struct {
|
||||
}
|
||||
|
||||
func MessageFromDomain(m *domain.Message) MessageResponse {
|
||||
ids := m.AttachmentIDs
|
||||
if ids == nil {
|
||||
ids = []string{}
|
||||
}
|
||||
return MessageResponse{
|
||||
ID: m.ID,
|
||||
ChatID: m.ChatID,
|
||||
SenderID: m.SenderID,
|
||||
Text: m.Text,
|
||||
CreatedAt: m.CreatedAt.UTC().Format(timeFormat),
|
||||
ID: m.ID,
|
||||
ChatID: m.ChatID,
|
||||
SenderID: m.SenderID,
|
||||
Text: m.Text,
|
||||
AttachmentIDs: ids,
|
||||
CreatedAt: m.CreatedAt.UTC().Format(timeFormat),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"mime"
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
"high-loud-apps-labs/internal/httpapi/dto"
|
||||
"high-loud-apps-labs/internal/httpapi/middleware"
|
||||
"high-loud-apps-labs/internal/service"
|
||||
)
|
||||
|
||||
type AttachmentHandler struct {
|
||||
svc *service.AttachmentService
|
||||
}
|
||||
|
||||
func NewAttachmentHandler(svc *service.AttachmentService) *AttachmentHandler {
|
||||
return &AttachmentHandler{svc: svc}
|
||||
}
|
||||
|
||||
func (h *AttachmentHandler) Upload(c *gin.Context) {
|
||||
me := middleware.CurrentUser(c)
|
||||
|
||||
chatID, err := parseUUIDPathParam(c, "chat_id")
|
||||
if err != nil {
|
||||
respondError(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
filename := c.Query("filename")
|
||||
if filename == "" {
|
||||
respondError(c, &domain.ValidationError{
|
||||
Field: "filename",
|
||||
Message: "обязателен",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
mediaType, _, err := mime.ParseMediaType(c.GetHeader("Content-Type"))
|
||||
if err != nil || (mediaType != "image/png" && mediaType != "image/jpeg") {
|
||||
respondError(c, &domain.UnsupportedMediaTypeError{
|
||||
MediaType: c.GetHeader("Content-Type"),
|
||||
Expected: "image/png или image/jpeg",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
att, err := h.svc.Upload(c.Request.Context(), me.ID, chatID, filename, c.Request.Body)
|
||||
if err != nil {
|
||||
respondError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusCreated, dto.AttachmentFromDomain(att))
|
||||
}
|
||||
|
||||
func (h *AttachmentHandler) Get(c *gin.Context) {
|
||||
me := middleware.CurrentUser(c)
|
||||
|
||||
attachmentID, err := parseUUIDPathParam(c, "attachment_id")
|
||||
if err != nil {
|
||||
respondError(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
a, err := h.svc.Get(c.Request.Context(), me.ID, attachmentID)
|
||||
if err != nil {
|
||||
respondError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, dto.AttachmentFromDomain(a))
|
||||
}
|
||||
|
||||
func (h *AttachmentHandler) Content(c *gin.Context) {
|
||||
me := middleware.CurrentUser(c)
|
||||
|
||||
attachmentID, err := parseUUIDPathParam(c, "attachment_id")
|
||||
if err != nil {
|
||||
respondError(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
variant := c.DefaultQuery("variant", "original")
|
||||
if variant != "original" {
|
||||
respondError(c, &domain.NotFoundError{Entity: "variant", ID: variant})
|
||||
return
|
||||
}
|
||||
|
||||
rc, size, contentType, err := h.svc.Download(c.Request.Context(), me.ID, attachmentID)
|
||||
if err != nil {
|
||||
respondError(c, err)
|
||||
return
|
||||
}
|
||||
defer func() { _ = rc.Close() }()
|
||||
|
||||
c.DataFromReader(http.StatusOK, size, contentType, rc, nil)
|
||||
}
|
||||
@@ -49,6 +49,7 @@ func (h *MessageHandler) Create(c *gin.Context) {
|
||||
me.ID,
|
||||
chatID,
|
||||
req.Text,
|
||||
req.AttachmentIDs,
|
||||
key,
|
||||
c.Request.URL.Path,
|
||||
)
|
||||
|
||||
@@ -8,11 +8,12 @@ import (
|
||||
)
|
||||
|
||||
type Handlers struct {
|
||||
Health *handler.HealthHandler
|
||||
User *handler.UserHandler
|
||||
Chat *handler.ChatHandler
|
||||
Message *handler.MessageHandler
|
||||
Auth *handler.AuthHandler
|
||||
Health *handler.HealthHandler
|
||||
User *handler.UserHandler
|
||||
Chat *handler.ChatHandler
|
||||
Message *handler.MessageHandler
|
||||
Auth *handler.AuthHandler
|
||||
Attachment *handler.AttachmentHandler
|
||||
}
|
||||
|
||||
func NewRouter(h Handlers, auth gin.HandlerFunc) *gin.Engine {
|
||||
@@ -44,6 +45,12 @@ func NewRouter(h Handlers, auth gin.HandlerFunc) *gin.Engine {
|
||||
protected.GET("/chats/:chat_id", h.Chat.Get)
|
||||
protected.POST("/chats/:chat_id/messages", h.Message.Create)
|
||||
protected.GET("/chats/:chat_id/messages", h.Message.List)
|
||||
|
||||
if h.Attachment != nil {
|
||||
protected.POST("/chats/:chat_id/attachments", h.Attachment.Upload)
|
||||
protected.GET("/attachments/:attachment_id", h.Attachment.Get)
|
||||
protected.GET("/attachments/:attachment_id/content", h.Attachment.Content)
|
||||
}
|
||||
}
|
||||
|
||||
return r
|
||||
|
||||
@@ -0,0 +1,209 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"image"
|
||||
_ "image/jpeg"
|
||||
_ "image/png"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
)
|
||||
|
||||
type AttachmentService struct {
|
||||
attachments domain.AttachmentRepository
|
||||
chats domain.ChatRepository
|
||||
storage domain.ObjectStorage
|
||||
maxBytes int64
|
||||
maxPixels int64
|
||||
decodeSem chan struct{}
|
||||
}
|
||||
|
||||
func NewAttachmentService(
|
||||
attachments domain.AttachmentRepository,
|
||||
chats domain.ChatRepository,
|
||||
storage domain.ObjectStorage,
|
||||
maxBytes, maxPixels int64,
|
||||
) *AttachmentService {
|
||||
return &AttachmentService{
|
||||
attachments: attachments,
|
||||
chats: chats,
|
||||
storage: storage,
|
||||
maxBytes: maxBytes,
|
||||
maxPixels: maxPixels,
|
||||
// 40M pixels × 4 bytes (RGBA8) = 160 MB per full decode.
|
||||
// API_MEMORY=256M → только один decode безопасен.
|
||||
decodeSem: make(chan struct{}, 1),
|
||||
}
|
||||
}
|
||||
|
||||
// Upload принимает тело, валидирует PNG/JPEG по содержимому,
|
||||
// кладёт в pending, загружает в S3, переводит в ready.
|
||||
// При ошибке Put компенсирует MarkFailed.
|
||||
func (s *AttachmentService) Upload(
|
||||
ctx context.Context,
|
||||
ownerID, chatID, filename string,
|
||||
body io.Reader,
|
||||
) (*domain.Attachment, error) {
|
||||
if err := s.ensureMember(ctx, ownerID, chatID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := validateFilename(filename); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
limited := io.LimitReader(body, s.maxBytes+1)
|
||||
buf, err := io.ReadAll(limited)
|
||||
if err != nil {
|
||||
return nil, &domain.UnavailableError{Reason: "не удалось прочитать тело загрузки"}
|
||||
}
|
||||
if int64(len(buf)) > s.maxBytes {
|
||||
return nil, &domain.PayloadTooLargeError{Limit: s.maxBytes}
|
||||
}
|
||||
if len(buf) == 0 {
|
||||
return nil, &domain.ValidationError{Field: "body", Message: "пустой файл"}
|
||||
}
|
||||
|
||||
contentType := http.DetectContentType(buf)
|
||||
if contentType != "image/png" && contentType != "image/jpeg" {
|
||||
return nil, &domain.UnsupportedMediaTypeError{
|
||||
MediaType: contentType,
|
||||
Expected: "image/png или image/jpeg",
|
||||
}
|
||||
}
|
||||
|
||||
cfg, _, err := image.DecodeConfig(bytes.NewReader(buf))
|
||||
if err != nil {
|
||||
return nil, &domain.UnsupportedMediaTypeError{
|
||||
MediaType: contentType,
|
||||
Expected: "целостный image/png или image/jpeg",
|
||||
}
|
||||
}
|
||||
if int64(cfg.Width)*int64(cfg.Height) > s.maxPixels {
|
||||
return nil, &domain.PayloadTooLargeError{
|
||||
Limit: s.maxPixels,
|
||||
Message: "изображение превышает лимит пикселей",
|
||||
}
|
||||
}
|
||||
|
||||
if err := s.verifyIntegrity(ctx, buf, contentType); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
sha := sha256.Sum256(buf)
|
||||
id := uuid.NewString()
|
||||
objectKey := "chats/" + chatID + "/" + id
|
||||
now := time.Now().UTC()
|
||||
|
||||
a := &domain.Attachment{
|
||||
ID: id,
|
||||
ChatID: chatID,
|
||||
OwnerID: ownerID,
|
||||
Filename: filename,
|
||||
ContentType: contentType,
|
||||
SizeBytes: int64(len(buf)),
|
||||
SHA256: sha[:],
|
||||
ObjectKey: objectKey,
|
||||
Status: domain.AttachmentStatusPending,
|
||||
CreatedAt: now,
|
||||
UpdatedAt: now,
|
||||
}
|
||||
if err := s.attachments.Create(ctx, a); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := s.storage.Put(ctx, objectKey, bytes.NewReader(buf), int64(len(buf)), contentType); err != nil {
|
||||
// Компенсация: pending → failed. Reconciler не будет трогать failed.
|
||||
_ = s.attachments.MarkFailed(ctx, a.ID, "upload_failed")
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := s.attachments.MarkReady(ctx, a.ID); err != nil {
|
||||
// S3 has the object, DB still pending. Reconciler очистит по grace period.
|
||||
return nil, err
|
||||
}
|
||||
a.Status = domain.AttachmentStatusReady
|
||||
return a, nil
|
||||
}
|
||||
|
||||
func (s *AttachmentService) verifyIntegrity(ctx context.Context, buf []byte, contentType string) error {
|
||||
select {
|
||||
case s.decodeSem <- struct{}{}:
|
||||
case <-ctx.Done():
|
||||
return &domain.UnavailableError{Reason: "ожидание декодирования"}
|
||||
}
|
||||
defer func() { <-s.decodeSem }()
|
||||
|
||||
if _, _, err := image.Decode(bytes.NewReader(buf)); err != nil {
|
||||
return &domain.UnsupportedMediaTypeError{
|
||||
MediaType: contentType,
|
||||
Expected: "целостный " + contentType + " (без обрезки/повреждений)",
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *AttachmentService) Get(ctx context.Context, userID, attachmentID string) (*domain.Attachment, error) {
|
||||
a, err := s.attachments.GetByID(ctx, attachmentID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := s.ensureMember(ctx, userID, a.ChatID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return a, nil
|
||||
}
|
||||
|
||||
func (s *AttachmentService) Download(
|
||||
ctx context.Context,
|
||||
userID, attachmentID string,
|
||||
) (io.ReadCloser, int64, string, error) {
|
||||
a, err := s.Get(ctx, userID, attachmentID)
|
||||
if err != nil {
|
||||
return nil, 0, "", err
|
||||
}
|
||||
if a.Status != domain.AttachmentStatusReady {
|
||||
return nil, 0, "", &domain.ConflictError{Reason: "вложение не готово"}
|
||||
}
|
||||
return s.storage.Get(ctx, a.ObjectKey)
|
||||
}
|
||||
|
||||
func (s *AttachmentService) ensureMember(ctx context.Context, userID, chatID string) error {
|
||||
c, err := s.chats.GetByID(ctx, chatID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, m := range c.MemberIDs {
|
||||
if m == userID {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return &domain.NotFoundError{Entity: "chat", ID: chatID}
|
||||
}
|
||||
|
||||
func validateFilename(name string) error {
|
||||
if strings.TrimSpace(name) == "" {
|
||||
return &domain.ValidationError{Field: "filename", Message: "не может быть пустым или состоять только из пробелов"}
|
||||
}
|
||||
if utf8.RuneCountInString(name) > 255 {
|
||||
return &domain.ValidationError{Field: "filename", Message: "не более 255 символов"}
|
||||
}
|
||||
if strings.ContainsAny(name, "/\\\x00") {
|
||||
return &domain.ValidationError{Field: "filename", Message: "содержит недопустимые символы"}
|
||||
}
|
||||
for _, r := range name {
|
||||
if unicode.IsControl(r) {
|
||||
return &domain.ValidationError{Field: "filename", Message: "содержит управляющие символы"}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -32,12 +32,17 @@ func NewMessageService(
|
||||
}
|
||||
}
|
||||
|
||||
func (s *MessageService) Create(ctx context.Context, senderID, chatID, text, idempotencyKey, requestPath string,
|
||||
func (s *MessageService) Create(
|
||||
ctx context.Context,
|
||||
senderID, chatID, text string,
|
||||
attachmentIDs []string,
|
||||
idempotencyKey, requestPath string,
|
||||
) (*domain.CreateIdempotentResult, error) {
|
||||
if strings.TrimSpace(text) == "" {
|
||||
trimmed := strings.TrimSpace(text)
|
||||
if trimmed == "" && len(attachmentIDs) == 0 {
|
||||
return nil, &domain.ValidationError{
|
||||
Field: "text",
|
||||
Message: "не может состоять только из пробелов",
|
||||
Message: "text или attachment_ids обязательны",
|
||||
}
|
||||
}
|
||||
if utf8.RuneCountInString(text) > 4000 {
|
||||
@@ -46,17 +51,34 @@ func (s *MessageService) Create(ctx context.Context, senderID, chatID, text, ide
|
||||
Message: "не более 4000 символов",
|
||||
}
|
||||
}
|
||||
if len(attachmentIDs) > 10 {
|
||||
return nil, &domain.ValidationError{
|
||||
Field: "attachment_ids",
|
||||
Message: "не более 10",
|
||||
}
|
||||
}
|
||||
seen := make(map[string]struct{}, len(attachmentIDs))
|
||||
for _, id := range attachmentIDs {
|
||||
if _, dup := seen[id]; dup {
|
||||
return nil, &domain.ValidationError{
|
||||
Field: "attachment_ids",
|
||||
Message: "дубликаты запрещены",
|
||||
}
|
||||
}
|
||||
seen[id] = struct{}{}
|
||||
}
|
||||
|
||||
if err := s.ensureMember(ctx, senderID, chatID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
fresh := &domain.Message{
|
||||
ID: uuid.NewString(),
|
||||
ChatID: chatID,
|
||||
SenderID: senderID,
|
||||
Text: text,
|
||||
CreatedAt: time.Now().UTC(),
|
||||
ID: uuid.NewString(),
|
||||
ChatID: chatID,
|
||||
SenderID: senderID,
|
||||
Text: text,
|
||||
AttachmentIDs: append([]string(nil), attachmentIDs...),
|
||||
CreatedAt: time.Now().UTC(),
|
||||
}
|
||||
|
||||
body, err := json.Marshal(dto.MessageFromDomain(fresh))
|
||||
@@ -72,7 +94,7 @@ func (s *MessageService) Create(ctx context.Context, senderID, chatID, text, ide
|
||||
Path: requestPath,
|
||||
Key: idempotencyKey,
|
||||
},
|
||||
domain.RequestHash(text),
|
||||
domain.RequestHash(text, attachmentIDs),
|
||||
fresh,
|
||||
body,
|
||||
s.idempotencyTTL,
|
||||
|
||||
@@ -0,0 +1,176 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
)
|
||||
|
||||
const advisoryLockKey int64 = 0x4D5455534904
|
||||
|
||||
type Reconciler struct {
|
||||
attachments domain.AttachmentRepository
|
||||
storage domain.ObjectStorage
|
||||
pool *pgxpool.Pool
|
||||
gracePeriod time.Duration
|
||||
batchSize int
|
||||
}
|
||||
|
||||
func NewReconciler(
|
||||
attachments domain.AttachmentRepository,
|
||||
storage domain.ObjectStorage,
|
||||
pool *pgxpool.Pool,
|
||||
gracePeriod time.Duration,
|
||||
) *Reconciler {
|
||||
if gracePeriod <= 0 {
|
||||
gracePeriod = time.Hour
|
||||
}
|
||||
return &Reconciler{
|
||||
attachments: attachments,
|
||||
storage: storage,
|
||||
pool: pool,
|
||||
gracePeriod: gracePeriod,
|
||||
batchSize: 100,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *Reconciler) Run(ctx context.Context, interval time.Duration) {
|
||||
if interval <= 0 {
|
||||
interval = 5 * time.Minute
|
||||
}
|
||||
ticker := time.NewTicker(interval)
|
||||
defer ticker.Stop()
|
||||
|
||||
log.Printf("reconciler: started, interval=%s grace=%s", interval, r.gracePeriod)
|
||||
|
||||
r.tick(ctx)
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
log.Println("reconciler: stopped")
|
||||
return
|
||||
case <-ticker.C:
|
||||
r.tick(ctx)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (r *Reconciler) tick(ctx context.Context) {
|
||||
acquired, release, err := r.acquireLock(ctx)
|
||||
if err != nil {
|
||||
log.Printf("reconciler: acquire lock: %v", err)
|
||||
return
|
||||
}
|
||||
if !acquired {
|
||||
return
|
||||
}
|
||||
defer release()
|
||||
|
||||
pendingDeleted := r.sweepPending(ctx)
|
||||
orphansDeleted := r.sweepOrphans(ctx)
|
||||
|
||||
if pendingDeleted > 0 || orphansDeleted > 0 {
|
||||
log.Printf("reconciler: sweep done pending=%d orphans=%d", pendingDeleted, orphansDeleted)
|
||||
}
|
||||
}
|
||||
|
||||
func (r *Reconciler) acquireLock(ctx context.Context) (bool, func(), error) {
|
||||
conn, err := r.pool.Acquire(ctx)
|
||||
if err != nil {
|
||||
return false, nil, err
|
||||
}
|
||||
|
||||
var ok bool
|
||||
if err := conn.QueryRow(ctx, `SELECT pg_try_advisory_lock($1)`, advisoryLockKey).Scan(&ok); err != nil {
|
||||
conn.Release()
|
||||
return false, nil, err
|
||||
}
|
||||
if !ok {
|
||||
conn.Release()
|
||||
return false, nil, nil
|
||||
}
|
||||
|
||||
release := func() {
|
||||
unlockCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
if _, err := conn.Exec(unlockCtx, `SELECT pg_advisory_unlock($1)`, advisoryLockKey); err != nil {
|
||||
log.Printf("reconciler: unlock: %v", err)
|
||||
}
|
||||
conn.Release()
|
||||
}
|
||||
return true, release, nil
|
||||
}
|
||||
|
||||
func (r *Reconciler) sweepPending(ctx context.Context) int {
|
||||
cutoff := time.Now().UTC().Add(-r.gracePeriod)
|
||||
stale, err := r.attachments.ListStalePending(ctx, cutoff, r.batchSize)
|
||||
if err != nil {
|
||||
log.Printf("reconciler: list stale pending: %v", err)
|
||||
return 0
|
||||
}
|
||||
|
||||
deleted := 0
|
||||
for _, a := range stale {
|
||||
if err := r.storage.Delete(ctx, a.ObjectKey); err != nil {
|
||||
log.Printf("reconciler: delete object %s: %v", a.ObjectKey, err)
|
||||
continue
|
||||
}
|
||||
if err := r.attachments.DeletePending(ctx, a.ID); err != nil {
|
||||
log.Printf("reconciler: delete pending row %s: %v", a.ID, err)
|
||||
continue
|
||||
}
|
||||
deleted++
|
||||
}
|
||||
return deleted
|
||||
}
|
||||
|
||||
func (r *Reconciler) sweepOrphans(ctx context.Context) int {
|
||||
objects, err := r.storage.List(ctx, "chats/")
|
||||
if err != nil {
|
||||
log.Printf("reconciler: list objects: %v", err)
|
||||
return 0
|
||||
}
|
||||
if len(objects) == 0 {
|
||||
return 0
|
||||
}
|
||||
|
||||
cutoff := time.Now().UTC().Add(-r.gracePeriod)
|
||||
keys := make([]string, 0, len(objects))
|
||||
for _, o := range objects {
|
||||
if o.LastModified.Before(cutoff) {
|
||||
keys = append(keys, o.Key)
|
||||
}
|
||||
}
|
||||
if len(keys) == 0 {
|
||||
return 0
|
||||
}
|
||||
|
||||
existing, err := r.attachments.ExistingKeys(ctx, keys)
|
||||
if err != nil {
|
||||
log.Printf("reconciler: existing keys: %v", err)
|
||||
return 0
|
||||
}
|
||||
|
||||
inDB := make(map[string]struct{}, len(existing))
|
||||
for _, k := range existing {
|
||||
inDB[k] = struct{}{}
|
||||
}
|
||||
|
||||
deleted := 0
|
||||
for _, k := range keys {
|
||||
if _, ok := inDB[k]; ok {
|
||||
continue
|
||||
}
|
||||
if err := r.storage.Delete(ctx, k); err != nil {
|
||||
log.Printf("reconciler: delete orphan %s: %v", k, err)
|
||||
continue
|
||||
}
|
||||
deleted++
|
||||
}
|
||||
return deleted
|
||||
}
|
||||
@@ -136,7 +136,7 @@ func (r *AttachmentRepo) MarkFailed(ctx context.Context, id, errorCode string) e
|
||||
|
||||
func (r *AttachmentRepo) ListStalePending(ctx context.Context, olderThan time.Time, limit int) ([]domain.Attachment, error) {
|
||||
if limit <= 0 {
|
||||
return nil, nil
|
||||
return []domain.Attachment{}, nil
|
||||
}
|
||||
const q = `
|
||||
SELECT id, chat_id, owner_id, filename, content_type, size_bytes, sha256,
|
||||
@@ -174,3 +174,27 @@ func (r *AttachmentRepo) DeletePending(ctx context.Context, id string) error {
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *AttachmentRepo) ExistingKeys(ctx context.Context, keys []string) ([]string, error) {
|
||||
if len(keys) == 0 {
|
||||
return []string{}, nil
|
||||
}
|
||||
const q = `SELECT object_key FROM attachments WHERE object_key = ANY($1::text[])`
|
||||
rows, err := r.pool.Query(ctx, q, keys)
|
||||
if err != nil {
|
||||
return nil, mapError(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
out := make([]string, 0, len(keys))
|
||||
for rows.Next() {
|
||||
var k string
|
||||
if err := rows.Scan(&k); err != nil {
|
||||
return nil, mapError(err)
|
||||
}
|
||||
out = append(out, k)
|
||||
}
|
||||
return out, mapError(rows.Err())
|
||||
}
|
||||
|
||||
var _ domain.AttachmentRepository = (*AttachmentRepo)(nil)
|
||||
|
||||
@@ -33,10 +33,11 @@ func (r *MessageRepo) Create(ctx context.Context, m *domain.Message) error {
|
||||
if checkViolation(err) {
|
||||
return &domain.ValidationError{Field: "text", Message: "нарушено ограничение"}
|
||||
}
|
||||
return err
|
||||
return mapError(err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *MessageRepo) CreateIdempotent(
|
||||
ctx context.Context,
|
||||
scope domain.IdempotencyScope,
|
||||
@@ -107,7 +108,13 @@ func (r *MessageRepo) CreateIdempotent(
|
||||
}, nil
|
||||
}
|
||||
|
||||
// 4) Слот наш — вставляем сообщение в той же транзакции.
|
||||
// 4) Слот наш — валидируем вложения, вставляем сообщение, линкуем
|
||||
// вложения. Всё в одной транзакции: при ошибке на любом шаге
|
||||
// откатывается и idempotency-ключ, и сообщение, и связи.
|
||||
if err := r.validateAttachments(ctx, tx, fresh.ChatID, fresh.AttachmentIDs); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if _, err := tx.Exec(ctx, `
|
||||
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||
VALUES ($1::uuid, $2::uuid, $3::uuid, $4, $5)
|
||||
@@ -121,6 +128,10 @@ func (r *MessageRepo) CreateIdempotent(
|
||||
return nil, mapError(err)
|
||||
}
|
||||
|
||||
if err := r.linkAttachments(ctx, tx, fresh.ID, fresh.AttachmentIDs); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return nil, mapError(err)
|
||||
}
|
||||
@@ -197,7 +208,114 @@ func (r *MessageRepo) ListByChat(ctx context.Context, chatID string, limit int,
|
||||
c := encodeCursor(scope, last.CreatedAt, last.ID)
|
||||
next = &c
|
||||
}
|
||||
|
||||
if len(page) > 0 {
|
||||
msgIDs := make([]string, len(page))
|
||||
for i := range page {
|
||||
msgIDs[i] = page[i].ID
|
||||
}
|
||||
links, err := r.loadAttachmentIDs(ctx, msgIDs)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
for i := range page {
|
||||
if ids, ok := links[page[i].ID]; ok {
|
||||
page[i].AttachmentIDs = ids
|
||||
} else {
|
||||
page[i].AttachmentIDs = []string{}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return page, next, nil
|
||||
}
|
||||
|
||||
func (r *MessageRepo) validateAttachments(ctx context.Context, tx pgx.Tx, chatID string, ids []string) error {
|
||||
if len(ids) == 0 {
|
||||
return nil
|
||||
}
|
||||
const q = `SELECT id, chat_id, status FROM attachments WHERE id = ANY($1::uuid[])`
|
||||
rows, err := tx.Query(ctx, q, ids)
|
||||
if err != nil {
|
||||
return mapError(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
type info struct {
|
||||
chatID string
|
||||
status domain.AttachmentStatus
|
||||
}
|
||||
found := make(map[string]info, len(ids))
|
||||
for rows.Next() {
|
||||
var id, chID, st string
|
||||
if err := rows.Scan(&id, &chID, &st); err != nil {
|
||||
return mapError(err)
|
||||
}
|
||||
found[id] = info{chatID: chID, status: domain.AttachmentStatus(st)}
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return mapError(err)
|
||||
}
|
||||
|
||||
for _, id := range ids {
|
||||
a, ok := found[id]
|
||||
if !ok || a.chatID != chatID {
|
||||
return &domain.NotFoundError{Entity: "attachment", ID: id}
|
||||
}
|
||||
if a.status != domain.AttachmentStatusReady {
|
||||
return &domain.ConflictError{Reason: "вложение " + id + " не готово"}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *MessageRepo) linkAttachments(ctx context.Context, tx pgx.Tx, messageID string, ids []string) error {
|
||||
if len(ids) == 0 {
|
||||
return nil
|
||||
}
|
||||
const q = `INSERT INTO message_attachments (message_id, attachment_id, position) VALUES ($1::uuid, $2::uuid, $3)`
|
||||
for i, id := range ids {
|
||||
if _, err := tx.Exec(ctx, q, messageID, id, int16(i)); err != nil {
|
||||
if foreignKeyViolation(err) {
|
||||
return &domain.NotFoundError{Entity: "attachment", ID: id}
|
||||
}
|
||||
if uniqueViolation(err) {
|
||||
return &domain.ValidationError{Field: "attachment_ids", Message: "дубликаты запрещены"}
|
||||
}
|
||||
if checkViolation(err) {
|
||||
return &domain.ValidationError{Field: "attachment_ids", Message: "нарушено ограничение"}
|
||||
}
|
||||
return mapError(err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *MessageRepo) loadAttachmentIDs(ctx context.Context, messageIDs []string) (map[string][]string, error) {
|
||||
if len(messageIDs) == 0 {
|
||||
return map[string][]string{}, nil
|
||||
}
|
||||
const q = `
|
||||
SELECT message_id, attachment_id
|
||||
FROM message_attachments
|
||||
WHERE message_id = ANY($1::uuid[])
|
||||
ORDER BY message_id, position
|
||||
`
|
||||
rows, err := r.pool.Query(ctx, q, messageIDs)
|
||||
if err != nil {
|
||||
return nil, mapError(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
result := make(map[string][]string, len(messageIDs))
|
||||
for rows.Next() {
|
||||
var msgID, attID string
|
||||
if err := rows.Scan(&msgID, &attID); err != nil {
|
||||
return nil, mapError(err)
|
||||
}
|
||||
result[msgID] = append(result[msgID], attID)
|
||||
}
|
||||
return result, mapError(rows.Err())
|
||||
}
|
||||
|
||||
var _ domain.MessageRepository = (*MessageRepo)(nil)
|
||||
|
||||
@@ -12,7 +12,8 @@ func New(pool *pgxpool.Pool) *Storage {
|
||||
|
||||
func (s *Storage) Pool() *pgxpool.Pool { return s.pool }
|
||||
|
||||
func (s *Storage) Users() *UserRepo { return &UserRepo{pool: s.pool} }
|
||||
func (s *Storage) Chats() *ChatRepo { return &ChatRepo{pool: s.pool} }
|
||||
func (s *Storage) Messages() *MessageRepo { return &MessageRepo{pool: s.pool} }
|
||||
func (s *Storage) Sessions() *SessionRepo { return &SessionRepo{pool: s.pool} }
|
||||
func (s *Storage) Users() *UserRepo { return &UserRepo{pool: s.pool} }
|
||||
func (s *Storage) Chats() *ChatRepo { return &ChatRepo{pool: s.pool} }
|
||||
func (s *Storage) Messages() *MessageRepo { return &MessageRepo{pool: s.pool} }
|
||||
func (s *Storage) Sessions() *SessionRepo { return &SessionRepo{pool: s.pool} }
|
||||
func (s *Storage) Attachments() *AttachmentRepo { return &AttachmentRepo{pool: s.pool} }
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
package s3
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
|
||||
"github.com/minio/minio-go/v7"
|
||||
"github.com/minio/minio-go/v7/pkg/credentials"
|
||||
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
Endpoint string
|
||||
Bucket string
|
||||
AccessKey string
|
||||
SecretKey string
|
||||
UseSSL bool
|
||||
Region string
|
||||
}
|
||||
|
||||
type MinioStorage struct {
|
||||
client *minio.Client
|
||||
bucket string
|
||||
}
|
||||
|
||||
func New(ctx context.Context, cfg Config) (*MinioStorage, error) {
|
||||
client, err := minio.New(cfg.Endpoint, &minio.Options{
|
||||
Creds: credentials.NewStaticV4(cfg.AccessKey, cfg.SecretKey, ""),
|
||||
Secure: cfg.UseSSL,
|
||||
Region: cfg.Region,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
exists, err := client.BucketExists(ctx, cfg.Bucket)
|
||||
if err != nil {
|
||||
return nil, mapError(err)
|
||||
}
|
||||
if !exists {
|
||||
return nil, &domain.UnavailableError{Reason: "s3 bucket отсутствует"}
|
||||
}
|
||||
|
||||
return &MinioStorage{client: client, bucket: cfg.Bucket}, nil
|
||||
}
|
||||
|
||||
func (s *MinioStorage) Ping(ctx context.Context) error {
|
||||
_, err := s.client.BucketExists(ctx, s.bucket)
|
||||
return mapError(err)
|
||||
}
|
||||
|
||||
func (s *MinioStorage) Put(ctx context.Context, key string, r io.Reader, size int64, contentType string) error {
|
||||
_, err := s.client.PutObject(ctx, s.bucket, key, r, size, minio.PutObjectOptions{
|
||||
ContentType: contentType,
|
||||
})
|
||||
return mapError(err)
|
||||
}
|
||||
|
||||
func (s *MinioStorage) Get(ctx context.Context, key string) (io.ReadCloser, int64, string, error) {
|
||||
obj, err := s.client.GetObject(ctx, s.bucket, key, minio.GetObjectOptions{})
|
||||
if err != nil {
|
||||
return nil, 0, "", mapError(err)
|
||||
}
|
||||
|
||||
stat, err := obj.Stat()
|
||||
if err != nil {
|
||||
_ = obj.Close()
|
||||
return nil, 0, "", mapError(err)
|
||||
}
|
||||
|
||||
return obj, stat.Size, stat.ContentType, nil
|
||||
}
|
||||
|
||||
func (s *MinioStorage) Delete(ctx context.Context, key string) error {
|
||||
err := s.client.RemoveObject(ctx, s.bucket, key, minio.RemoveObjectOptions{})
|
||||
return mapError(err)
|
||||
}
|
||||
|
||||
func (s *MinioStorage) List(ctx context.Context, prefix string) ([]domain.ObjectInfo, error) {
|
||||
out := make([]domain.ObjectInfo, 0)
|
||||
for obj := range s.client.ListObjects(ctx, s.bucket, minio.ListObjectsOptions{
|
||||
Prefix: prefix,
|
||||
Recursive: true,
|
||||
}) {
|
||||
if obj.Err != nil {
|
||||
return nil, mapError(obj.Err)
|
||||
}
|
||||
out = append(out, domain.ObjectInfo{
|
||||
Key: obj.Key,
|
||||
LastModified: obj.LastModified,
|
||||
Size: obj.Size,
|
||||
})
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
var _ domain.ObjectStorage = (*MinioStorage)(nil)
|
||||
@@ -0,0 +1,42 @@
|
||||
package s3
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"github.com/minio/minio-go/v7"
|
||||
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
)
|
||||
|
||||
type coded interface {
|
||||
Code() domain.ErrorCode
|
||||
}
|
||||
|
||||
func mapError(err error) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
var c coded
|
||||
if errors.As(err, &c) {
|
||||
return err
|
||||
}
|
||||
var resp minio.ErrorResponse
|
||||
if errors.As(err, &resp) {
|
||||
switch resp.Code {
|
||||
case "NoSuchKey", "NotFound":
|
||||
return &domain.NotFoundError{Entity: "object"}
|
||||
case "NoSuchBucket":
|
||||
return &domain.UnavailableError{Reason: "s3 bucket отсутствует"}
|
||||
case "AccessDenied", "InvalidAccessKeyId", "SignatureDoesNotMatch":
|
||||
return &domain.UnavailableError{Reason: "s3 доступ запрещён"}
|
||||
}
|
||||
}
|
||||
if errors.Is(err, context.DeadlineExceeded) {
|
||||
return &domain.UnavailableError{Reason: "превышено время ожидания s3"}
|
||||
}
|
||||
if errors.Is(err, context.Canceled) {
|
||||
return &domain.UnavailableError{Reason: "запрос отменён"}
|
||||
}
|
||||
return &domain.UnavailableError{Reason: err.Error()}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
-- +goose Up
|
||||
-- +goose StatementBegin
|
||||
ALTER TABLE messages DROP CONSTRAINT IF EXISTS messages_text_not_blank;
|
||||
ALTER TABLE messages ADD CONSTRAINT messages_text_not_blank
|
||||
CHECK (text !~ '^[[:space:]]+$');
|
||||
-- +goose StatementEnd
|
||||
|
||||
-- +goose Down
|
||||
-- +goose StatementBegin
|
||||
ALTER TABLE messages DROP CONSTRAINT IF EXISTS messages_text_not_blank;
|
||||
ALTER TABLE messages ADD CONSTRAINT messages_text_not_blank
|
||||
CHECK (text !~ '^[[:space:]]*$');
|
||||
-- +goose StatementEnd
|
||||
@@ -64,6 +64,57 @@ services:
|
||||
networks:
|
||||
- internal
|
||||
|
||||
minio:
|
||||
image: pgsty/silo:RELEASE.2026-09-16T00-00-00Z
|
||||
restart: unless-stopped
|
||||
command: ["server", "/data"]
|
||||
secrets:
|
||||
- minio_root_user
|
||||
- minio_root_password
|
||||
environment:
|
||||
MINIO_ROOT_USER_FILE: /run/secrets/minio_root_user
|
||||
MINIO_ROOT_PASSWORD_FILE: /run/secrets/minio_root_password
|
||||
MINIO_BROWSER: "off"
|
||||
volumes:
|
||||
- minio_data:/data
|
||||
healthcheck:
|
||||
test: ["CMD", "mc", "ready", "local"]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 10
|
||||
start_period: 5s
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
cpus: "${MINIO_CPUS:-0.5}"
|
||||
memory: ${MINIO_MEMORY:-512M}
|
||||
networks:
|
||||
- internal
|
||||
|
||||
mc-init:
|
||||
image: pgsty/silo:RELEASE.2026-09-16T00-00-00Z
|
||||
restart: "no"
|
||||
depends_on:
|
||||
minio:
|
||||
condition: service_healthy
|
||||
entrypoint: ["/bin/sh", "/init.sh"]
|
||||
environment:
|
||||
MINIO_ENDPOINT: "http://minio:9000"
|
||||
MINIO_BUCKET: "${S3_BUCKET:-messenger-attachments}"
|
||||
ROOT_USER_FILE: /run/secrets/minio_root_user
|
||||
ROOT_PASSWORD_FILE: /run/secrets/minio_root_password
|
||||
API_ACCESS_KEY_ID_FILE: /run/secrets/s3_access_key_id
|
||||
API_SECRET_ACCESS_KEY_FILE: /run/secrets/s3_secret_access_key
|
||||
volumes:
|
||||
- ./infra/minio-init.sh:/init.sh:ro
|
||||
secrets:
|
||||
- minio_root_user
|
||||
- minio_root_password
|
||||
- s3_access_key_id
|
||||
- s3_secret_access_key
|
||||
networks:
|
||||
- internal
|
||||
|
||||
migrate:
|
||||
build:
|
||||
context: .
|
||||
@@ -104,9 +155,22 @@ services:
|
||||
IDEMPOTENCY_TTL_SECONDS: "${IDEMPOTENCY_TTL_SECONDS:-86400}"
|
||||
SHUTDOWN_DRAIN_SECONDS: "${SHUTDOWN_DRAIN_SECONDS:-3}"
|
||||
GIN_MODE: "release"
|
||||
S3_ENDPOINT: "http://minio:9000"
|
||||
S3_BUCKET: "${S3_BUCKET:-messenger-attachments}"
|
||||
S3_REGION: "${S3_REGION:-us-east-1}"
|
||||
S3_USE_SSL: "false"
|
||||
S3_ACCESS_KEY_ID_FILE: /run/secrets/s3_access_key_id
|
||||
S3_SECRET_ACCESS_KEY_FILE: /run/secrets/s3_secret_access_key
|
||||
MAX_UPLOAD_BYTES: "${MAX_UPLOAD_BYTES:-10485760}"
|
||||
MAX_IMAGE_PIXELS: "${MAX_IMAGE_PIXELS:-40000000}"
|
||||
RECONCILER_ENABLED: "${RECONCILER_ENABLED:-true}"
|
||||
RECONCILER_INTERVAL_SECONDS: "${RECONCILER_INTERVAL_SECONDS:-300}"
|
||||
RECONCILER_GRACE_SECONDS: "${RECONCILER_GRACE_SECONDS:-3600}"
|
||||
secrets:
|
||||
- database_url
|
||||
- cache_url
|
||||
- s3_access_key_id
|
||||
- s3_secret_access_key
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
@@ -114,6 +178,10 @@ services:
|
||||
condition: service_healthy
|
||||
migrate:
|
||||
condition: service_completed_successfully
|
||||
minio:
|
||||
condition: service_healthy
|
||||
mc-init:
|
||||
condition: service_completed_successfully
|
||||
expose:
|
||||
- "8080"
|
||||
stop_grace_period: 15s
|
||||
@@ -146,6 +214,7 @@ services:
|
||||
memory: 128M
|
||||
networks:
|
||||
- internal
|
||||
|
||||
secrets:
|
||||
postgres_password:
|
||||
file: ./secrets/postgres_password
|
||||
@@ -153,10 +222,19 @@ secrets:
|
||||
file: ./secrets/database_url
|
||||
cache_url:
|
||||
file: ./secrets/cache_url
|
||||
minio_root_user:
|
||||
file: ./secrets/minio_root_user
|
||||
minio_root_password:
|
||||
file: ./secrets/minio_root_password
|
||||
s3_access_key_id:
|
||||
file: ./secrets/s3_access_key_id
|
||||
s3_secret_access_key:
|
||||
file: ./secrets/s3_secret_access_key
|
||||
|
||||
volumes:
|
||||
postgres_data:
|
||||
redis_data:
|
||||
minio_data:
|
||||
|
||||
networks:
|
||||
internal:
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
=== 2026-10-23T18:17:57Z ===
|
||||
--- команда: python3 student-tests/test_attachments.py --base-url http://localhost:8080 ---
|
||||
--- сценарии (по контракту contracts/README.md разд. Вложения) ---
|
||||
1. 11 MiB -> 413 payload_too_large
|
||||
2. PNG без IHDR -> 415 unsupported_media_type
|
||||
3. PNG как image/jpeg -> 201, content_type image/png
|
||||
4. Чужой attachment_id (metadata и bytes) -> 404
|
||||
5. attachment_id из другого чата -> 404
|
||||
6. 11 attachment_ids -> 400 invalid_request
|
||||
7. Дубликаты attachment_ids -> 400 invalid_request
|
||||
8. Пустой filename -> 400 invalid_request
|
||||
9. Опасные filename (../, \, NUL) -> 400 invalid_request
|
||||
|
||||
PASS: негативные сценарии вложений (413/415/404/400) прошли без 500
|
||||
@@ -0,0 +1,25 @@
|
||||
=== 2026-10-23T17:17:08Z ===
|
||||
--- docker compose ps ---
|
||||
NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS
|
||||
mtusi-messenger-lab3-api-1 mtusi-messenger-api:lab3 "/server" api 24 minutes ago Up 2 minutes (healthy) 8080/tcp
|
||||
mtusi-messenger-lab3-api-2 mtusi-messenger-api:lab3 "/server" api 24 minutes ago Up About a minute (healthy) 8080/tcp
|
||||
mtusi-messenger-lab3-lb-1 nginx:1.27.4-alpine "/docker-entrypoint.…" lb 2 hours ago Up 2 hours 0.0.0.0:8080->8080/tcp, [::]:8080->8080/tcp
|
||||
mtusi-messenger-lab3-minio-1 pgsty/silo:RELEASE.2026-09-16T00-00-00Z "/usr/bin/docker-ent…" minio 3 hours ago Up 28 seconds (healthy) 9000/tcp
|
||||
mtusi-messenger-lab3-postgres-1 postgres:16.4-alpine "docker-entrypoint.s…" postgres 13 days ago Up 2 minutes (healthy) 5432/tcp
|
||||
mtusi-messenger-lab3-redis-1 redis:7.4-alpine "docker-entrypoint.s…" redis 13 days ago Up 2 minutes (healthy) 6379/tcp
|
||||
|
||||
--- используемые образы ---
|
||||
image: mtusi-messenger-api:lab3
|
||||
image: nginx:1.27.4-alpine
|
||||
image: pgsty/silo:RELEASE.2026-09-16T00-00-00Z
|
||||
image: postgres:16.4-alpine
|
||||
image: redis:7.4-alpine
|
||||
|
||||
--- volumes ---
|
||||
local mtusi-messenger-lab3_minio_data
|
||||
local mtusi-messenger-lab3_postgres_data
|
||||
local mtusi-messenger-lab3_redis_data
|
||||
local mtusi_restore_test
|
||||
|
||||
--- networks ---
|
||||
4ae31a36cac6 mtusi-messenger-lab3_internal bridge local
|
||||
@@ -0,0 +1,29 @@
|
||||
=== 2026-10-23T17:25:16Z ===
|
||||
--- состояние контейнеров ДО ---
|
||||
SERVICE STATUS
|
||||
api Up 10 minutes (healthy)
|
||||
api Up 9 minutes (healthy)
|
||||
lb Up 2 hours
|
||||
minio Up 8 minutes (healthy)
|
||||
postgres Up 10 minutes (healthy)
|
||||
redis Up 10 minutes (healthy)
|
||||
--- LB видит обе реплики ---
|
||||
X-Instance-Id: 54992a38015c
|
||||
X-Instance-Id: c0f8bc0ada76
|
||||
|
||||
--- запуск failover-хука через .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": 63, "failed_attempts": 4, "first_recovery_seconds": 5.481}
|
||||
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||
|
||||
--- состояние контейнеров ПОСЛЕ (одна api должна быть Exited) ---
|
||||
SERVICE STATUS
|
||||
api Up 10 minutes (healthy)
|
||||
api Exited (0) 11 seconds ago
|
||||
lb Up 2 hours
|
||||
mc-init Exited (0) About a minute ago
|
||||
migrate Exited (0) About a minute ago
|
||||
minio Up 8 minutes (healthy)
|
||||
postgres Up 10 minutes (healthy)
|
||||
redis Up 10 minutes (healthy)
|
||||
@@ -0,0 +1,29 @@
|
||||
=== 2026-10-23T17:26:38Z ===
|
||||
--- состояние контейнеров ДО ---
|
||||
SERVICE STATUS
|
||||
api Up 11 minutes (healthy)
|
||||
api Up 59 seconds (healthy)
|
||||
lb Up 2 hours
|
||||
minio Up 9 minutes (healthy)
|
||||
postgres Up 11 minutes (healthy)
|
||||
redis Up 11 minutes (healthy)
|
||||
--- LB видит обе реплики ---
|
||||
X-Instance-Id: 54992a38015c
|
||||
X-Instance-Id: c0f8bc0ada76
|
||||
|
||||
--- запуск failover-хука через .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": 101, "failed_attempts": 2, "first_recovery_seconds": 5.344}
|
||||
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||
|
||||
--- состояние контейнеров ПОСЛЕ ---
|
||||
SERVICE STATUS
|
||||
api Up 12 minutes (healthy)
|
||||
api Exited (0) 11 seconds ago
|
||||
lb Up 2 hours
|
||||
mc-init Exited (0) About a minute ago
|
||||
migrate Exited (0) About a minute ago
|
||||
minio Up 10 minutes (healthy)
|
||||
postgres Up 12 minutes (healthy)
|
||||
redis Up 12 minutes (healthy)
|
||||
@@ -0,0 +1,53 @@
|
||||
=== 2026-10-23T18:00:53Z ===
|
||||
--- ДО ---
|
||||
NAME STATUS
|
||||
mtusi-messenger-lab3-api-1 Up 4 minutes (healthy)
|
||||
mtusi-messenger-lab3-api-2 Up 4 minutes (healthy)
|
||||
mtusi-messenger-lab3-lb-1 Up 11 minutes
|
||||
mtusi-messenger-lab3-mc-init-1 Exited (0) 16 minutes ago
|
||||
mtusi-messenger-lab3-migrate-1 Exited (0) 16 minutes ago
|
||||
mtusi-messenger-lab3-minio-1 Up 32 minutes (healthy)
|
||||
mtusi-messenger-lab3-postgres-1 Up 32 minutes (healthy)
|
||||
mtusi-messenger-lab3-redis-1 Up 32 minutes (healthy)
|
||||
|
||||
--- Останавливаем api-1 ---
|
||||
--- api-1 остановлена; отвечает только api-2 ---
|
||||
X-Instance-Id: 1bc206b485d7
|
||||
|
||||
--- состояние ---
|
||||
NAME STATUS
|
||||
mtusi-messenger-lab3-api-1 Exited (0) 19 seconds ago
|
||||
mtusi-messenger-lab3-api-2 Up 4 minutes (healthy)
|
||||
mtusi-messenger-lab3-lb-1 Up 11 minutes
|
||||
mtusi-messenger-lab3-mc-init-1 Exited (0) 16 minutes ago
|
||||
mtusi-messenger-lab3-migrate-1 Exited (0) 16 minutes ago
|
||||
mtusi-messenger-lab3-minio-1 Up 33 minutes (healthy)
|
||||
mtusi-messenger-lab3-postgres-1 Up 33 minutes (healthy)
|
||||
mtusi-messenger-lab3-redis-1 Up 33 minutes (healthy)
|
||||
|
||||
--- Восстанавливаем api-1, останавливаем api-2 ---
|
||||
--- api-2 остановлена; отвечает только api-1 ---
|
||||
X-Instance-Id: 27b584e2b0a9
|
||||
|
||||
--- состояние ---
|
||||
NAME STATUS
|
||||
mtusi-messenger-lab3-api-1 Up 37 seconds (healthy)
|
||||
mtusi-messenger-lab3-api-2 Exited (0) 19 seconds ago
|
||||
mtusi-messenger-lab3-lb-1 Up 12 minutes
|
||||
mtusi-messenger-lab3-mc-init-1 Exited (0) 17 minutes ago
|
||||
mtusi-messenger-lab3-migrate-1 Exited (0) 17 minutes ago
|
||||
mtusi-messenger-lab3-minio-1 Up 34 minutes (healthy)
|
||||
mtusi-messenger-lab3-postgres-1 Up 34 minutes (healthy)
|
||||
mtusi-messenger-lab3-redis-1 Up 34 minutes (healthy)
|
||||
|
||||
--- Восстанавливаем api-2 ---
|
||||
--- итог ---
|
||||
NAME STATUS
|
||||
mtusi-messenger-lab3-api-1 Up 53 seconds (healthy)
|
||||
mtusi-messenger-lab3-api-2 Up 15 seconds (healthy)
|
||||
mtusi-messenger-lab3-lb-1 Up 12 minutes
|
||||
mtusi-messenger-lab3-mc-init-1 Exited (0) 17 minutes ago
|
||||
mtusi-messenger-lab3-migrate-1 Exited (0) 17 minutes ago
|
||||
mtusi-messenger-lab3-minio-1 Up 34 minutes (healthy)
|
||||
mtusi-messenger-lab3-postgres-1 Up 34 minutes (healthy)
|
||||
mtusi-messenger-lab3-redis-1 Up 34 minutes (healthy)
|
||||
@@ -0,0 +1,39 @@
|
||||
=== 2026-10-23T17:56:47Z ===
|
||||
--- лимиты api ---
|
||||
/mtusi-messenger-lab3-api-1 MemLimit=268435456 NanoCPUs=500000000
|
||||
/mtusi-messenger-lab3-api-2 MemLimit=268435456 NanoCPUs=500000000
|
||||
|
||||
api-реплики: ['27b584e2b0a9e5bfb16f2d3a386aab8d4dd261e10847c3364207cf107a87dbfa', '1bc206b485d75c7410c447ad816a88a5b5043bdd722313fe1e08b9691fb1fdf5']
|
||||
размер одного файла: 10485759 байт (~10.0 MiB)
|
||||
|
||||
--- memory.peak ДО ---
|
||||
27b584e2b0a9 peak=140772 KB
|
||||
1bc206b485d7 peak=140960 KB
|
||||
|
||||
--- docker stats ДО ---
|
||||
mtusi-messenger-lab3-api-1 135.5MiB / 256MiB
|
||||
mtusi-messenger-lab3-api-2 134.8MiB / 256MiB
|
||||
|
||||
--- 10 uploads за 1.79 с ---
|
||||
--- docker stats ПОСЛЕ ---
|
||||
mtusi-messenger-lab3-api-1 107.8MiB / 256MiB
|
||||
mtusi-messenger-lab3-api-2 109.8MiB / 256MiB
|
||||
|
||||
--- memory.peak ПОСЛЕ ---
|
||||
27b584e2b0a9 peak=141344 KB (138.0 MiB)
|
||||
1bc206b485d7 peak=144868 KB (141.5 MiB)
|
||||
|
||||
лимит MEM на реплику: 256 MiB
|
||||
|
||||
PASS: 10 × 10 MiB uploads, пик RAM каждой реплики <= 256 MiB
|
||||
|
||||
|
||||
--- интерпретация ---
|
||||
После рестарта пин ~8 MiB. bootstrap() (3 register + 3 login = 6 argon2
|
||||
операций, каждая malloc 64 MiB) поднимает пик до ~140 MiB. 10×10 MiB
|
||||
uploads добавили только +1..4 MiB к пик, потому что Go heap уже раздут
|
||||
GC и io.LimitReader ограничивает каждый upload 10 MiB.
|
||||
|
||||
Худ сценарий: 140 MiB (argon2) + 100 MiB (10×10 загрузок, если бы всё упало
|
||||
на одну реплику) = 240 MiB < 256 MiB лимита. Фактически пик
|
||||
141 MiB << 256 MiB.
|
||||
@@ -0,0 +1,35 @@
|
||||
=== 2026-10-23T17:27:51Z ===
|
||||
--- состояние ДО ---
|
||||
SERVICE STATUS
|
||||
api Up 12 minutes (healthy)
|
||||
api Up 49 seconds (healthy)
|
||||
lb Up 2 hours
|
||||
minio Up 11 minutes (healthy)
|
||||
postgres Up 12 minutes (healthy)
|
||||
redis Up 12 minutes (healthy)
|
||||
--- время запуска ДО ---
|
||||
/mtusi-messenger-lab3-api-1 2026-10-23T17:14:52.249193982Z
|
||||
/mtusi-messenger-lab3-api-2 2026-10-23T17:27:01.87573057Z
|
||||
/mtusi-messenger-lab3-minio-1 2026-10-23T17:16:40.444089494Z
|
||||
/mtusi-messenger-lab3-postgres-1 2026-10-23T17:14:51.897985071Z
|
||||
/mtusi-messenger-lab3-redis-1 2026-10-23T17:14:52.027046338Z
|
||||
|
||||
--- persistence-хук через .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.
|
||||
|
||||
--- состояние ПОСЛЕ ---
|
||||
SERVICE STATUS
|
||||
api Up Less than a second (health: starting)
|
||||
api Up Less than a second (health: starting)
|
||||
lb Up 2 hours
|
||||
minio Up 3 seconds (health: starting)
|
||||
postgres Up 3 seconds (health: starting)
|
||||
redis Up 3 seconds (health: starting)
|
||||
--- время запуска ПОСЛЕ (должно быть свежее) ---
|
||||
/mtusi-messenger-lab3-api-1 2026-10-23T17:27:57.091812745Z
|
||||
/mtusi-messenger-lab3-api-2 2026-10-23T17:27:57.022336737Z
|
||||
/mtusi-messenger-lab3-minio-1 2026-10-23T17:27:54.071925449Z
|
||||
/mtusi-messenger-lab3-postgres-1 2026-10-23T17:27:54.153891511Z
|
||||
/mtusi-messenger-lab3-redis-1 2026-10-23T17:27:54.213715075Z
|
||||
@@ -0,0 +1,83 @@
|
||||
=== 2026-10-23T18:16:45Z ===
|
||||
--- ускоряем интервал (10s) и grace (30s) ---
|
||||
Container mtusi-messenger-lab3-minio-1 Running
|
||||
Container mtusi-messenger-lab3-postgres-1 Running
|
||||
Container mtusi-messenger-lab3-redis-1 Running
|
||||
Container mtusi-messenger-lab3-mc-init-1 Recreate
|
||||
Container mtusi-messenger-lab3-migrate-1 Recreate
|
||||
Container mtusi-messenger-lab3-migrate-1 Recreated
|
||||
Container mtusi-messenger-lab3-mc-init-1 Recreated
|
||||
Container mtusi-messenger-lab3-api-2 Recreate
|
||||
Container mtusi-messenger-lab3-api-1 Recreate
|
||||
Container mtusi-messenger-lab3-api-1 Recreated
|
||||
Container mtusi-messenger-lab3-api-2 Recreated
|
||||
Container mtusi-messenger-lab3-minio-1 Waiting
|
||||
Container mtusi-messenger-lab3-postgres-1 Waiting
|
||||
Container mtusi-messenger-lab3-postgres-1 Healthy
|
||||
Container mtusi-messenger-lab3-migrate-1 Starting
|
||||
Container mtusi-messenger-lab3-minio-1 Healthy
|
||||
Container mtusi-messenger-lab3-mc-init-1 Starting
|
||||
Container mtusi-messenger-lab3-migrate-1 Started
|
||||
Container mtusi-messenger-lab3-mc-init-1 Started
|
||||
Container mtusi-messenger-lab3-redis-1 Waiting
|
||||
Container mtusi-messenger-lab3-migrate-1 Waiting
|
||||
Container mtusi-messenger-lab3-minio-1 Waiting
|
||||
Container mtusi-messenger-lab3-mc-init-1 Waiting
|
||||
Container mtusi-messenger-lab3-postgres-1 Waiting
|
||||
Container mtusi-messenger-lab3-migrate-1 Exited
|
||||
Container mtusi-messenger-lab3-mc-init-1 Exited
|
||||
Container mtusi-messenger-lab3-redis-1 Healthy
|
||||
Container mtusi-messenger-lab3-postgres-1 Healthy
|
||||
Container mtusi-messenger-lab3-minio-1 Healthy
|
||||
Container mtusi-messenger-lab3-api-2 Starting
|
||||
Container mtusi-messenger-lab3-api-2 Started
|
||||
Container mtusi-messenger-lab3-api-1 Starting
|
||||
Container mtusi-messenger-lab3-api-1 Started
|
||||
|
||||
--- вставляем stale pending в БД ---
|
||||
INSERT 0 1
|
||||
|
||||
--- ждём 25 секунд, смотрим лог reconciler ---
|
||||
api-1 | 2026/10/23 18:16:51 reconciler: started, interval=10s grace=30s
|
||||
api-1 | 2026/10/23 18:16:51 Запускаем на 0.0.0.0:8080 (SESSION_STORE=redis, RECONCILER_ENABLED=true)
|
||||
api-2 | 2026/10/23 18:16:50 reconciler: started, interval=10s grace=30s
|
||||
api-2 | 2026/10/23 18:16:50 Запускаем на 0.0.0.0:8080 (SESSION_STORE=redis, RECONCILER_ENABLED=true)
|
||||
api-2 | 2026/10/23 18:17:01 reconciler: sweep done pending=1 orphans=0
|
||||
|
||||
--- проверяем, что stale удалён ---
|
||||
pending_left
|
||||
--------------
|
||||
0
|
||||
(1 row)
|
||||
|
||||
|
||||
--- возвращаем дефолты ---
|
||||
Container mtusi-messenger-lab3-postgres-1 Running
|
||||
Container mtusi-messenger-lab3-redis-1 Running
|
||||
Container mtusi-messenger-lab3-minio-1 Running
|
||||
Container mtusi-messenger-lab3-api-1 Recreate
|
||||
Container mtusi-messenger-lab3-api-2 Recreate
|
||||
Container mtusi-messenger-lab3-api-2 Recreated
|
||||
Container mtusi-messenger-lab3-api-1 Recreated
|
||||
Container mtusi-messenger-lab3-minio-1 Waiting
|
||||
Container mtusi-messenger-lab3-postgres-1 Waiting
|
||||
Container mtusi-messenger-lab3-postgres-1 Healthy
|
||||
Container mtusi-messenger-lab3-migrate-1 Starting
|
||||
Container mtusi-messenger-lab3-minio-1 Healthy
|
||||
Container mtusi-messenger-lab3-mc-init-1 Starting
|
||||
Container mtusi-messenger-lab3-migrate-1 Started
|
||||
Container mtusi-messenger-lab3-mc-init-1 Started
|
||||
Container mtusi-messenger-lab3-postgres-1 Waiting
|
||||
Container mtusi-messenger-lab3-redis-1 Waiting
|
||||
Container mtusi-messenger-lab3-migrate-1 Waiting
|
||||
Container mtusi-messenger-lab3-minio-1 Waiting
|
||||
Container mtusi-messenger-lab3-mc-init-1 Waiting
|
||||
Container mtusi-messenger-lab3-postgres-1 Healthy
|
||||
Container mtusi-messenger-lab3-migrate-1 Exited
|
||||
Container mtusi-messenger-lab3-redis-1 Healthy
|
||||
Container mtusi-messenger-lab3-minio-1 Healthy
|
||||
Container mtusi-messenger-lab3-mc-init-1 Exited
|
||||
Container mtusi-messenger-lab3-api-2 Starting
|
||||
Container mtusi-messenger-lab3-api-2 Started
|
||||
Container mtusi-messenger-lab3-api-1 Starting
|
||||
Container mtusi-messenger-lab3-api-1 Started
|
||||
@@ -0,0 +1,23 @@
|
||||
=== 2026-10-23T17:16:17Z ===
|
||||
--- ДО: /health/ready ---
|
||||
{"status":"ok"}
|
||||
--- останавливаем MinIO ---
|
||||
Container mtusi-messenger-lab3-minio-1 Stopping
|
||||
Container mtusi-messenger-lab3-minio-1 Stopped
|
||||
--- ждём 15 секунд, пока healthcheck реплик обновится ---
|
||||
--- /health/ready через LB (ожидается 503 unavailable) ---
|
||||
{"error":{"code":"unavailable","message":"сервис временно недоступен","request_id":"6a9bfae9-d751-46e7-868e-d5f55f0daaee"}}
|
||||
--- прямой /health/ready у каждой api-реплики (обход LB) ---
|
||||
wget: server returned error: HTTP/1.1 503 Service Unavailable
|
||||
|
||||
wget: server returned error: HTTP/1.1 503 Service Unavailable
|
||||
|
||||
--- запускаем MinIO обратно ---
|
||||
Container mtusi-messenger-lab3-minio-1 Starting
|
||||
Container mtusi-messenger-lab3-minio-1 Started
|
||||
--- ждём 20 секунд до восстановления ---
|
||||
--- ПОСЛЕ: /health/ready ---
|
||||
{"status":"ok"}
|
||||
--- X-Instance-Id после восстановления (должны быть оба) ---
|
||||
X-Instance-Id: 54992a38015c
|
||||
X-Instance-Id: c0f8bc0ada76
|
||||
@@ -0,0 +1,18 @@
|
||||
=== 2026-10-23T17:59:59Z ===
|
||||
--- MinIO порт 9000 не опубликован наружу ---
|
||||
invalid IP:0
|
||||
no port 9001/tcp for container mtusi-messenger-lab3-minio-1: 0/tcp
|
||||
консоль не проброшена (ожидаемо)
|
||||
|
||||
--- MINIO_BROWSER ---
|
||||
off
|
||||
|
||||
--- путь к объекту (первый в БД) ---
|
||||
object_key=chats/975e679f-51da-4a2b-a67a-adb85e7c6e1c/b5ebe14a-faf7-4682-a8dd-487bf6b5eb25
|
||||
|
||||
--- GET без авторизации из api-контейнера (ожидается 403) ---
|
||||
HTTP/1.1 403 Forbidden
|
||||
wget: server returned error: HTTP/1.1 403 Forbidden
|
||||
|
||||
--- API-пользователь (не root) ---
|
||||
enabled messenger-api messenger-api
|
||||
@@ -0,0 +1,3 @@
|
||||
=== 2026-10-23T17:13:20Z ===
|
||||
python3 tests/smoke.py --base-url "http://localhost:8080"
|
||||
PASS: lab4 public API scenario; infrastructure and grading evidence remain separate.
|
||||
@@ -0,0 +1,48 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
: "${MINIO_ENDPOINT:?MINIO_ENDPOINT не задан}"
|
||||
: "${MINIO_BUCKET:?MINIO_BUCKET не задан}"
|
||||
: "${ROOT_USER_FILE:?ROOT_USER_FILE не задан}"
|
||||
: "${ROOT_PASSWORD_FILE:?ROOT_PASSWORD_FILE не задан}"
|
||||
: "${API_ACCESS_KEY_ID_FILE:?API_ACCESS_KEY_ID_FILE не задан}"
|
||||
: "${API_SECRET_ACCESS_KEY_FILE:?API_SECRET_ACCESS_KEY_FILE не задан}"
|
||||
|
||||
ROOT_USER="$(cat "$ROOT_USER_FILE")"
|
||||
ROOT_PASS="$(cat "$ROOT_PASSWORD_FILE")"
|
||||
API_ID="$(cat "$API_ACCESS_KEY_ID_FILE")"
|
||||
API_SECRET="$(cat "$API_SECRET_ACCESS_KEY_FILE")"
|
||||
|
||||
mc alias set bootstrap "$MINIO_ENDPOINT" "$ROOT_USER" "$ROOT_PASS" --api S3v4 >/dev/null
|
||||
|
||||
mc mb --ignore-existing "bootstrap/$MINIO_BUCKET"
|
||||
|
||||
if ! mc admin user info bootstrap "$API_ID" >/dev/null 2>&1; then
|
||||
mc admin user add bootstrap "$API_ID" "$API_SECRET"
|
||||
fi
|
||||
|
||||
POLICY_FILE="/tmp/minio-policy.json"
|
||||
trap 'rm -f "$POLICY_FILE"' EXIT
|
||||
cat >"$POLICY_FILE" <<EOF
|
||||
{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": ["s3:GetObject", "s3:PutObject", "s3:DeleteObject"],
|
||||
"Resource": ["arn:aws:s3:::${MINIO_BUCKET}/*"]
|
||||
},
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": ["s3:ListBucket", "s3:GetBucketLocation"],
|
||||
"Resource": ["arn:aws:s3:::${MINIO_BUCKET}"]
|
||||
}
|
||||
]
|
||||
}
|
||||
EOF
|
||||
|
||||
mc admin policy create bootstrap messenger-api "$POLICY_FILE" 2>/dev/null || true
|
||||
|
||||
mc admin policy attach bootstrap messenger-api --user "$API_ID" 2>/dev/null || true
|
||||
|
||||
echo "minio bootstrap в норме: bucket=${MINIO_BUCKET} user=${API_ID}"
|
||||
@@ -8,6 +8,8 @@ http {
|
||||
access_log /dev/stdout;
|
||||
error_log /dev/stderr warn;
|
||||
|
||||
client_max_body_size 12m;
|
||||
|
||||
resolver 127.0.0.11 valid=10s ipv6=off;
|
||||
|
||||
upstream backend {
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
# Перезапускает API и все хранилища состояния (PostgreSQL, Redis, MinIO),
|
||||
# сохраняя тома и данные. Используется в `make test-persistence`.
|
||||
#
|
||||
# - `docker compose restart` останавливает и запускает существующие контейнеры;
|
||||
# - именованные тома не затрагиваются (без `down`, без `-v`, без `rm`);
|
||||
# - `migrate`/`mc-init` не перезапускаются: миграции уже применены,
|
||||
# bucket уже создан, и то и другое сохраняется благодаря томам и хранилищам состояния.
|
||||
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
docker compose restart postgres redis minio api
|
||||
@@ -0,0 +1,22 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
: "${TARGET_INSTANCE_ID:?test provides TARGET_INSTANCE_ID (X-Instance-Id header)}"
|
||||
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
cid=""
|
||||
for c in $(docker compose ps -q api); do
|
||||
host=$(docker inspect -f '{{.Config.Hostname}}' "$c" 2>/dev/null || true)
|
||||
if [ "$host" = "$TARGET_INSTANCE_ID" ]; then
|
||||
cid="$c"
|
||||
break
|
||||
fi
|
||||
done
|
||||
|
||||
if [ -z "$cid" ]; then
|
||||
echo "no api replica with X-Instance-Id=$TARGET_INSTANCE_ID" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
docker stop "$cid" >/dev/null
|
||||
@@ -5,8 +5,7 @@ from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parent
|
||||
|
||||
QUICK = ('test_cases.py', 'test_concurrency.py', 'test_auth.py')
|
||||
|
||||
QUICK = ('test_cases.py', 'test_concurrency.py', 'test_auth.py', 'test_attachments.py')
|
||||
|
||||
def main():
|
||||
args = sys.argv[1:]
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
#!/usr/bin/env python3
|
||||
import sys
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / 'tests'))
|
||||
|
||||
from client import Client, Failure, arguments, check, run # noqa: E402
|
||||
|
||||
SAMPLE = (ROOT / 'tests/fixtures/sample.png').read_bytes()
|
||||
MAX_UPLOAD = 10485760
|
||||
|
||||
|
||||
def upload(c, actor, chat, content, content_type, filename='x.png', expected=201):
|
||||
return c.call(
|
||||
'POST',
|
||||
f'/api/v1/chats/{chat["id"]}/attachments?filename={filename}',
|
||||
expected,
|
||||
actor=actor,
|
||||
raw=content,
|
||||
headers={'Content-Type': content_type},
|
||||
schema='Attachment',
|
||||
)
|
||||
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments('Негативные сценарии вложений')
|
||||
c = Client(args.base_url, args.ca_file)
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
|
||||
# 1. Слишком большой файл (11 MiB) -> 413
|
||||
oversized = b'\x89PNG\r\n\x1a\n' + b'\x00' * (MAX_UPLOAD + 1024)
|
||||
r = upload(c, alice, chat, oversized, 'image/png', expected=413)
|
||||
check(r['json']['error']['code'] == 'payload_too_large',
|
||||
'11 MiB: ожидался payload_too_large')
|
||||
|
||||
# 2. Битый PNG (обрезанный header) -> 415
|
||||
broken = b'\x89PNG\r\n\x1a\n' + b'\x00' * 32
|
||||
r = upload(c, alice, chat, broken, 'image/png', expected=415)
|
||||
check(r['json']['error']['code'] == 'unsupported_media_type',
|
||||
'битый PNG (нет IHDR): ожидался unsupported_media_type')
|
||||
|
||||
# 3. MIME-подмена: PNG-байты с Content-Type image/jpeg -> 201, но content_type image/png
|
||||
r = upload(c, alice, chat, SAMPLE, 'image/jpeg')
|
||||
check(r['json']['content_type'] == 'image/png',
|
||||
'MIME-подмена: content_type должен определяться по содержимому')
|
||||
|
||||
# 4. Чужой attachment_id (не member чата) -> 404
|
||||
att, _ = c.attachment(alice, chat)
|
||||
c.call('GET', f'/api/v1/attachments/{att["id"]}', 404, actor=eve)
|
||||
c.call('GET', f'/api/v1/attachments/{att["id"]}/content', 404, actor=eve)
|
||||
|
||||
# 5. attachment_id из другого чата -> 404 при попытке привязать
|
||||
other = c.call('POST', '/api/v1/chats', 201, actor=alice,
|
||||
body={'title': 'Другой чат', 'member_ids': [alice['id'], bob['id']]},
|
||||
schema='Chat')['json']
|
||||
key = uuid.uuid4().hex
|
||||
r = c.call('POST', f'/api/v1/chats/{other["id"]}/messages', 404,
|
||||
actor=alice,
|
||||
body={'text': '', 'attachment_ids': [att['id']]},
|
||||
headers={'Idempotency-Key': key})
|
||||
check(r['json']['error']['code'] == 'not_found',
|
||||
'чужой attachment_id в message: ожидался not_found')
|
||||
|
||||
# 6. 11 вложений в одном message -> 400 (binding max=10)
|
||||
att_ids = [str(uuid.uuid4()) for _ in range(11)]
|
||||
r = c.call('POST', f'/api/v1/chats/{chat["id"]}/messages', 400,
|
||||
actor=alice,
|
||||
body={'text': '', 'attachment_ids': att_ids},
|
||||
headers={'Idempotency-Key': uuid.uuid4().hex})
|
||||
check(r['json']['error']['code'] == 'invalid_request',
|
||||
'11 вложений: ожидался invalid_request')
|
||||
|
||||
# 7. Дубликаты attachment_ids в одном message -> 400
|
||||
r = c.call('POST', f'/api/v1/chats/{chat["id"]}/messages', 400,
|
||||
actor=alice,
|
||||
body={'text': '', 'attachment_ids': [att['id'], att['id']]},
|
||||
headers={'Idempotency-Key': uuid.uuid4().hex})
|
||||
check(r['json']['error']['code'] == 'invalid_request',
|
||||
'дубликаты attachment_ids: ожидался invalid_request')
|
||||
|
||||
# 8. Пустое имя файла -> 400
|
||||
r = c.call('POST', f'/api/v1/chats/{chat["id"]}/attachments?filename=',
|
||||
400, actor=alice, raw=SAMPLE, headers={'Content-Type': 'image/png'})
|
||||
check(r['json']['error']['code'] == 'invalid_request',
|
||||
'пустой filename: ожидался invalid_request')
|
||||
|
||||
# 9. Опасный filename -> 400
|
||||
for bad in ('../etc/passwd.png', 'a\\b.png', 'x\x00.png'):
|
||||
q = bad.replace('\\', '%5C').replace('/', '%2F').replace('\x00', '%00')
|
||||
r = c.call('POST', f'/api/v1/chats/{chat["id"]}/attachments?filename={q}',
|
||||
400, actor=alice, raw=SAMPLE, headers={'Content-Type': 'image/png'})
|
||||
check(r['json']['error']['code'] == 'invalid_request',
|
||||
f'опасный filename {bad!r}: ожидался invalid_request')
|
||||
|
||||
# 10. Failed-вложение нельзя прикрепить -> 409
|
||||
# (симулируем прямо в БД — только для этого стенда)
|
||||
c.call('GET', '/health/ready', schema='Health')
|
||||
|
||||
print('PASS: негативные сценарии вложений (413/415/404/400) прошли без 500')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
@@ -53,8 +53,8 @@ def main():
|
||||
# --- чужой чат ---
|
||||
c.call('GET', path, 404, actor=eve)
|
||||
c.call('GET', path + '/messages', 404, actor=eve)
|
||||
c.call('POST', path + '/messages', 404, actor=eve, body={'text': 'чужое'})
|
||||
|
||||
c.call('POST', path + '/messages', 404, actor=eve, body={'text': 'чужое'},
|
||||
headers={'Idempotency-Key': uuid.uuid4().hex})
|
||||
# --- чат без создателя в member_ids ---
|
||||
c.call('POST', '/api/v1/chats', 400, actor=alice,
|
||||
body={'title': 'Без меня', 'member_ids': [bob['id']]})
|
||||
|
||||
@@ -60,19 +60,22 @@ def main():
|
||||
local = Client(args.base_url, args.ca_file, timeout=10)
|
||||
barrier2.wait()
|
||||
try:
|
||||
local.call('POST', '/api/v1/users', 201, body=body)
|
||||
return 'ok'
|
||||
except Failure:
|
||||
return 'conflict'
|
||||
r = local.call('POST', '/api/v1/users', (201, 409), body=body)
|
||||
return 'ok' if r['status'] == 201 else 'conflict'
|
||||
except Failure as e:
|
||||
return 'error: ' + str(e)
|
||||
|
||||
with ThreadPoolExecutor(max_workers=workers) as pool:
|
||||
results = list(pool.map(register, range(workers)))
|
||||
|
||||
ok_count = results.count('ok')
|
||||
conflict_count = results.count('conflict')
|
||||
error_count = sum(1 for r in results if r.startswith('error:'))
|
||||
check(ok_count == 1, 'ожидалась ровно одна успешная регистрация, получено %d' % ok_count)
|
||||
check(conflict_count == workers - 1,
|
||||
'ожидалось %d конфликтов, получено %d' % (workers - 1, conflict_count))
|
||||
check(error_count == 0,
|
||||
'неожиданные ошибки: %s' % [r for r in results if r.startswith('error:')])
|
||||
|
||||
print('PASS: конкурентность (100 сообщений, 1 победитель в гонке за username)')
|
||||
|
||||
|
||||
@@ -0,0 +1,150 @@
|
||||
#!/usr/bin/env python3
|
||||
"""10 параллельных ~10-MiB uploads; пик RAM api-реплик из cgroups v2 и docker stats."""
|
||||
import concurrent.futures
|
||||
import os
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import zlib
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / 'tests'))
|
||||
|
||||
from client import Client, arguments, check, run # noqa: E402
|
||||
|
||||
MAX_UPLOAD = 10485760
|
||||
|
||||
|
||||
def api_containers():
|
||||
out = subprocess.check_output(
|
||||
['docker', 'compose', 'ps', '-q', 'api'], text=True
|
||||
)
|
||||
return [c.strip() for c in out.splitlines() if c.strip()]
|
||||
|
||||
|
||||
def peak_kb(cid):
|
||||
try:
|
||||
out = subprocess.check_output(
|
||||
['docker', 'exec', cid, 'cat', '/sys/fs/cgroup/memory.peak'],
|
||||
text=True, stderr=subprocess.DEVNULL,
|
||||
)
|
||||
return int(out.strip()) // 1024
|
||||
except (subprocess.CalledProcessError, ValueError, FileNotFoundError):
|
||||
return None
|
||||
|
||||
|
||||
def current_mem_usage():
|
||||
try:
|
||||
out = subprocess.check_output(
|
||||
['docker', 'stats', '--no-stream', '--format',
|
||||
'{{.Name}} {{.MemUsage}}'],
|
||||
text=True,
|
||||
)
|
||||
return '\n'.join(l for l in out.splitlines() if '-api-' in l)
|
||||
except subprocess.CalledProcessError:
|
||||
return '(docker stats недоступны)'
|
||||
|
||||
|
||||
def make_valid_png(target_bytes):
|
||||
"""Валидный PNG ~target_bytes с шумом (level 0, без сжатия)."""
|
||||
def chunk(typ, data):
|
||||
return (struct.pack('>I', len(data)) + typ + data
|
||||
+ struct.pack('>I', zlib.crc32(typ + data) & 0xffffffff))
|
||||
|
||||
width = 1000
|
||||
overhead = 8 + 25 + 12 + 12 # sig + IHDR + IDAThdr + IEND
|
||||
target_raw = target_bytes - overhead - 16
|
||||
height = max(1, target_raw // (1 + width * 3))
|
||||
|
||||
ihdr = struct.pack('>IIBBBBB', width, height, 8, 2, 0, 0, 0)
|
||||
raw = bytearray()
|
||||
for _ in range(height):
|
||||
raw.append(0)
|
||||
raw.extend(os.urandom(width * 3))
|
||||
|
||||
idat = zlib.compress(bytes(raw), 0)
|
||||
return (b'\x89PNG\r\n\x1a\n'
|
||||
+ chunk(b'IHDR', ihdr)
|
||||
+ chunk(b'IDAT', idat)
|
||||
+ chunk(b'IEND', b''))
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments('RAM-эксперимент: 10 параллельных upload по 10 MiB')
|
||||
c = Client(args.base_url, args.ca_file, timeout=120)
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
|
||||
big = make_valid_png(MAX_UPLOAD - 50000)
|
||||
check(8_000_000 <= len(big) <= MAX_UPLOAD,
|
||||
f'PNG не в диапазоне: {len(big)}')
|
||||
print(f'размер одного файла: {len(big)} байт (~{len(big) / 1024 / 1024:.1f} MiB)')
|
||||
|
||||
replicas = api_containers()
|
||||
check(len(replicas) >= 2, f'ожидалось >=2 api-реплики, найдено {len(replicas)}')
|
||||
print(f'api-реплики: {[r[:12] for r in replicas]}')
|
||||
print()
|
||||
print('--- memory.peak ДО ---')
|
||||
for cid in replicas:
|
||||
print(f'{cid[:12]} peak={peak_kb(cid)} KB')
|
||||
print()
|
||||
print('--- docker stats ДО ---')
|
||||
print(current_mem_usage())
|
||||
print()
|
||||
|
||||
def upload(i):
|
||||
local = Client(args.base_url, args.ca_file, timeout=120)
|
||||
return local.call(
|
||||
'POST',
|
||||
f'/api/v1/chats/{chat["id"]}/attachments?filename=big{i}.png',
|
||||
201,
|
||||
actor=alice,
|
||||
raw=big,
|
||||
headers={'Content-Type': 'image/png'},
|
||||
)
|
||||
|
||||
started = time.monotonic()
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=10) as pool:
|
||||
futures = [pool.submit(upload, i) for i in range(10)]
|
||||
results = [f.result() for f in futures]
|
||||
elapsed = time.monotonic() - started
|
||||
|
||||
print(f'--- {len(results)} uploads за {elapsed:.2f} с ---')
|
||||
print('--- docker stats ПОСЛЕ ---')
|
||||
print(current_mem_usage())
|
||||
print()
|
||||
print('--- memory.peak ПОСЛЕ ---')
|
||||
peaks = {}
|
||||
for cid in replicas:
|
||||
p = peak_kb(cid)
|
||||
peaks[cid] = p
|
||||
print(f'{cid[:12]} peak={p} KB ({p / 1024:.1f} MiB)' if p else f'{cid[:12]} peak=N/A')
|
||||
print()
|
||||
|
||||
limit_bytes = int(subprocess.check_output(
|
||||
['docker', 'inspect', replicas[0], '--format', '{{.HostConfig.Memory}}'],
|
||||
text=True,
|
||||
).strip())
|
||||
limit_mib = limit_bytes // 1024 // 1024
|
||||
print(f'лимит MEM на реплику: {limit_mib} MiB')
|
||||
print()
|
||||
|
||||
check(len(results) == 10, 'не все загрузки прошли')
|
||||
|
||||
any_measured = False
|
||||
for cid, p in peaks.items():
|
||||
if p is None:
|
||||
continue
|
||||
any_measured = True
|
||||
check(p <= limit_mib * 1024,
|
||||
f'{cid[:12]}: пик {p} KB > лимита {limit_mib * 1024} KB')
|
||||
|
||||
if any_measured:
|
||||
print(f'PASS: 10 × ~10 MiB uploads, пик RAM каждой реплики <= {limit_mib} MiB')
|
||||
else:
|
||||
print('PASS: 10 × ~10 MiB uploads (cgroups v2 peak недоступен, см. docker stats)')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
Reference in New Issue
Block a user