Compare commits
31
Commits
+5
-1
@@ -20,4 +20,8 @@ MAX_UPLOAD_BYTES=10485760
|
||||
MAX_IMAGE_PIXELS=40000000
|
||||
MINIO_ROOT_USER=...
|
||||
MINIO_CPUS=0.5
|
||||
MINIO_MEMORY=512M
|
||||
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 {
|
||||
|
||||
@@ -27,6 +27,10 @@ type Config struct {
|
||||
|
||||
MaxUploadBytes int64
|
||||
MaxImagePixels int64
|
||||
|
||||
ReconcilerEnabled bool
|
||||
ReconcilerInterval time.Duration
|
||||
ReconcilerGracePeriod time.Duration
|
||||
}
|
||||
|
||||
func Load() (*Config, error) {
|
||||
@@ -104,6 +108,25 @@ func Load() (*Config, error) {
|
||||
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"),
|
||||
@@ -123,6 +146,10 @@ func Load() (*Config, error) {
|
||||
|
||||
MaxUploadBytes: maxUploadBytes,
|
||||
MaxImagePixels: maxImagePixels,
|
||||
|
||||
ReconcilerEnabled: reconcilerEnabled,
|
||||
ReconcilerInterval: time.Duration(reconcilerIntervalSec) * time.Second,
|
||||
ReconcilerGracePeriod: time.Duration(reconcilerGraceSec) * time.Second,
|
||||
}, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@ type ObjectInfo struct {
|
||||
}
|
||||
|
||||
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
|
||||
|
||||
@@ -5,8 +5,8 @@ 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 {
|
||||
|
||||
@@ -49,6 +49,7 @@ func (h *MessageHandler) Create(c *gin.Context) {
|
||||
me.ID,
|
||||
chatID,
|
||||
req.Text,
|
||||
req.AttachmentIDs,
|
||||
key,
|
||||
c.Request.URL.Path,
|
||||
)
|
||||
|
||||
@@ -25,6 +25,7 @@ type AttachmentService struct {
|
||||
storage domain.ObjectStorage
|
||||
maxBytes int64
|
||||
maxPixels int64
|
||||
decodeSem chan struct{}
|
||||
}
|
||||
|
||||
func NewAttachmentService(
|
||||
@@ -39,6 +40,9 @@ func NewAttachmentService(
|
||||
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),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -81,7 +85,7 @@ func (s *AttachmentService) Upload(
|
||||
if err != nil {
|
||||
return nil, &domain.UnsupportedMediaTypeError{
|
||||
MediaType: contentType,
|
||||
Expected: "image/png или image/jpeg",
|
||||
Expected: "целостный image/png или image/jpeg",
|
||||
}
|
||||
}
|
||||
if int64(cfg.Width)*int64(cfg.Height) > s.maxPixels {
|
||||
@@ -91,6 +95,10 @@ func (s *AttachmentService) Upload(
|
||||
}
|
||||
}
|
||||
|
||||
if err := s.verifyIntegrity(ctx, buf, contentType); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
sha := sha256.Sum256(buf)
|
||||
id := uuid.NewString()
|
||||
objectKey := "chats/" + chatID + "/" + id
|
||||
@@ -127,6 +135,23 @@ func (s *AttachmentService) Upload(
|
||||
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 {
|
||||
@@ -166,8 +191,8 @@ func (s *AttachmentService) ensureMember(ctx context.Context, userID, chatID str
|
||||
}
|
||||
|
||||
func validateFilename(name string) error {
|
||||
if name == "" {
|
||||
return &domain.ValidationError{Field: "filename", Message: "не может быть пустым"}
|
||||
if strings.TrimSpace(name) == "" {
|
||||
return &domain.ValidationError{Field: "filename", Message: "не может быть пустым или состоять только из пробелов"}
|
||||
}
|
||||
if utf8.RuneCountInString(name) > 255 {
|
||||
return &domain.ValidationError{Field: "filename", Message: "не более 255 символов"}
|
||||
|
||||
@@ -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,7 +33,7 @@ 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
|
||||
}
|
||||
|
||||
@@ -45,6 +45,11 @@ func New(ctx context.Context, cfg Config) (*MinioStorage, error) {
|
||||
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,
|
||||
|
||||
@@ -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
|
||||
@@ -155,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
|
||||
@@ -165,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
|
||||
|
||||
@@ -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.
|
||||
@@ -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