From 0b4a21a83fbcb63bc2ebee475490cb362e0b8563 Mon Sep 17 00:00:00 2001 From: Vladislav Gavrilenko <178+sxdees@noreply.gitea.privcloud.tech> Date: Tue, 1 Dec 2026 22:01:52 +0300 Subject: [PATCH] =?UTF-8?q?=D0=9B=D0=A04=20=D0=BD=D0=B0=204:=20MinIO-?= =?UTF-8?q?=D0=B2=D0=BB=D0=BE=D0=B6=D0=B5=D0=BD=D0=B8=D1=8F=20=D0=BF=D0=BE?= =?UTF-8?q?=D0=B2=D0=B5=D1=80=D1=85=20LB,=20=D0=B8=D0=B4=D0=B5=D0=BC=D0=BF?= =?UTF-8?q?=D0=BE=D1=82=D0=B5=D0=BD=D1=82=D0=BD=D0=BE=D1=81=D1=82=D0=B8=20?= =?UTF-8?q?=D0=B8=20failover.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PNG/JPEG через API, student-tests, REPORT и DEFENSE. --- .env.example | 47 +- DEFENSE.md | 71 ++ Dockerfile | 20 + Makefile | 45 +- REPORT.md | 66 +- cmd/server/main.go | 262 +++++ compose.yaml | 236 +++++ evidence/check.txt | 2 + evidence/failover.txt | 4 + evidence/persistence.txt | 3 + evidence/private-bucket.txt | 21 + evidence/smoke.txt | 2 + evidence/student-tests.txt | 419 ++++++++ evidence/upload-memory/limit_4.stats | 446 ++++++++ evidence/upload-memory/limit_64.stats | 971 ++++++++++++++++++ evidence/upload-memory/summary.txt | 14 + go.mod | 33 + go.sum | 66 ++ infra/haproxy/haproxy.cfg | 52 + internal/api/attachments.go | 391 +++++++ internal/api/imagecheck.go | 181 ++++ internal/api/server.go | 767 ++++++++++++++ internal/auth/password.go | 110 ++ internal/config/config.go | 188 ++++ internal/objectstore/s3.go | 304 ++++++ internal/reconcile/reconcile.go | 377 +++++++ internal/session/redis.go | 135 +++ internal/store/attachments.go | 301 ++++++ internal/store/migrate.go | 84 ++ internal/store/migrations/001_init.sql | 49 + internal/store/migrations/002_idempotency.sql | 23 + internal/store/migrations/003_attachments.sql | 47 + internal/store/migrations/attachments.go | 301 ++++++ internal/store/migrations/store.go | 693 +++++++++++++ internal/store/store.go | 693 +++++++++++++ scripts/_lib.sh | 44 + scripts/check_private_bucket.sh | 73 ++ scripts/restart.sh | 6 + scripts/restore-one.sh | 27 + scripts/stop-one.sh | 39 + scripts/up.sh | 40 + scripts/upload_mem_experiment.sh | 120 +++ student-tests/api_test.go | 673 ++++++++++++ student-tests/attachments_test.go | 743 ++++++++++++++ 44 files changed, 9152 insertions(+), 37 deletions(-) create mode 100644 DEFENSE.md create mode 100644 Dockerfile create mode 100644 cmd/server/main.go create mode 100644 compose.yaml create mode 100644 evidence/check.txt create mode 100644 evidence/failover.txt create mode 100644 evidence/persistence.txt create mode 100644 evidence/private-bucket.txt create mode 100644 evidence/smoke.txt create mode 100644 evidence/student-tests.txt create mode 100644 evidence/upload-memory/limit_4.stats create mode 100644 evidence/upload-memory/limit_64.stats create mode 100644 evidence/upload-memory/summary.txt create mode 100644 go.mod create mode 100644 go.sum create mode 100644 infra/haproxy/haproxy.cfg create mode 100644 internal/api/attachments.go create mode 100644 internal/api/imagecheck.go create mode 100644 internal/api/server.go create mode 100644 internal/auth/password.go create mode 100644 internal/config/config.go create mode 100644 internal/objectstore/s3.go create mode 100644 internal/reconcile/reconcile.go create mode 100644 internal/session/redis.go create mode 100644 internal/store/attachments.go create mode 100644 internal/store/migrate.go create mode 100644 internal/store/migrations/001_init.sql create mode 100644 internal/store/migrations/002_idempotency.sql create mode 100644 internal/store/migrations/003_attachments.sql create mode 100644 internal/store/migrations/attachments.go create mode 100644 internal/store/migrations/store.go create mode 100644 internal/store/store.go create mode 100755 scripts/_lib.sh create mode 100755 scripts/check_private_bucket.sh create mode 100755 scripts/restart.sh create mode 100755 scripts/restore-one.sh create mode 100755 scripts/stop-one.sh create mode 100755 scripts/up.sh create mode 100755 scripts/upload_mem_experiment.sh create mode 100644 student-tests/api_test.go create mode 100644 student-tests/attachments_test.go diff --git a/.env.example b/.env.example index d99d26a2..ae63d43f 100644 --- a/.env.example +++ b/.env.example @@ -1,20 +1,41 @@ # Copy to .env for your LOCAL synthetic test environment; never commit .env. -# These are logical interface suggestions; map actual framework names in REPORT.md. APP_HOST=0.0.0.0 APP_PORT=8080 APP_ENV=lab +APP_ACCESS_LOG=1 SESSION_TTL_SECONDS=3600 -# Choose credentials locally. File paths contain no secret values. -DATABASE_URL_FILE=/run/secrets/database_url -# Optional on 3, required use on 4 in lab2; Redis OR Valkey: -SESSION_STORE=postgres -CACHE_URL_FILE=/run/secrets/cache_url -API_REPLICAS=2 IDEMPOTENCY_TTL_SECONDS=86400 -S3_ENDPOINT=http://s3:9000 + +POSTGRES_USER=messenger +POSTGRES_PASSWORD=messenger +POSTGRES_DB=messenger + +DATABASE_URL=postgres://messenger:messenger@postgres:5432/messenger?sslmode=disable +REDIS_URL=redis://redis:6379/0 +SESSION_STORE=redis + +API_REPLICAS=2 +API_CPUS=0.50 +API_MEMORY=256M +API_GOMEMLIMIT=200MiB +DB_MAX_CONNS=5 + +MINIO_ROOT_USER=minio-root +MINIO_ROOT_PASSWORD=minio-root-secret-change-me +S3_ENDPOINT=http://minio:9000 S3_REGION=us-east-1 -S3_BUCKET=messenger-attachments -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 +S3_BUCKET=messenger +S3_ACCESS_KEY=messenger-api +S3_SECRET_KEY=messenger-api-secret-change-me +S3_FORCE_PATH_STYLE=1 +S3_ORPHAN_GRACE_SECONDS=300 +UPLOAD_MAX_CONCURRENCY=4 + +# Порты хоста (127.0.0.1). По умолчанию смещены от lab3 (5432/6379/8080/9000). +LB_HOST_PORT=8081 +POSTGRES_HOST_PORT=5433 +REDIS_HOST_PORT=6380 +MINIO_HOST_PORT=9002 + +MINIO_IMAGE=ghcr.io/coollabsio/minio:RELEASE.2025-10-15T17-29-55Z +MC_IMAGE=cgr.dev/chainguard/minio-client:latest-dev \ No newline at end of file diff --git a/DEFENSE.md b/DEFENSE.md new file mode 100644 index 00000000..9e869233 --- /dev/null +++ b/DEFENSE.md @@ -0,0 +1,71 @@ +# Шпаргалка к защите ЛР4 + +**Автор:** Гавриленко Владислав, БПИ2303 · **Цель:** оценка **4** (трек 5 не заявляется) +**Стенд:** `http://127.0.0.1:8081` (через HAProxy; порты смещены от lab3) · **Ветка:** `solution/bpi2303-gavrilenko` + +--- + +## Быстрый старт + +```bash +cd lab4 +cp -n .env.example .env +bash scripts/up.sh +make test BASE_URL=http://127.0.0.1:8081 +make student-test +make private-bucket +make test-persistence ACTION_SCRIPT=scripts/restart.sh BASE_URL=http://127.0.0.1:8081 +make test-failover ACTION_SCRIPT=scripts/stop-one.sh BASE_URL=http://127.0.0.1:8081 +``` + +--- + +## Архитектура + +| Компонент | Роль | +|-----------|------| +| **HAProxy** | Единственная точка входа; round-robin; health `/health/ready` | +| **API × 2+** | Stateless; **X-Instance-Id** = hostname; скачивание вложений из общего S3 | +| **PostgreSQL** | Метаданные чатов, сообщений, **attachments**, idempotency | +| **Redis (AOF)** | Сессии Bearer | +| **MinIO** | Приватный bucket; байты вложений; консоль отключена | + +Порядок загрузки: **S3 PUT → INSERT в БД → 201 ready**. Ошибка БД → `compensateOrphan` (Delete объекта). «Зависший» orphan после grace убирает `docker compose run --rm reconcile` (`-reconcile` / `-reconcile-dry-run`). + +--- + +## Ключевые механизмы lab4 + +- **Ключ объекта:** `attachments/{chat_id}/{attachment_id}`; `filename` только для отображения. +- **MIME** проверяется по содержимому; лимиты **10 MiB** и **40M пикселей** до полного декодирования больших картинок. +- **Download** — proxy через API, без redirect на S3; посторонний пользователь — **404**. +- **Слоты `UPLOAD_MAX_CONCURRENCY`** ограничивают пик RAM на реплику (≈ слоты × 10 MiB). +- **`minio-init`:** идемпотентный bootstrap bucket + пользователь `messenger-api` с узкой политикой. + +Сохранено из **lab3:** Idempotency-Key, Redis-сессии, failover hooks, drain на SIGTERM. + +--- + +## Что показать на защите + +1. Загрузить `tests/fixtures/sample.png`, сообщение с `attachment_ids`, скачать вторым участником, сверить SHA-256. +2. Третий пользователь — 404 на метаданные и bytes; анонимный GET в MinIO — 403 (`make private-bucket`). +3. Failover: остановить реплику, скачать файл через другую. +4. Persistence: `restart.sh` перезапускает postgres/redis/minio/api/lb, файл и сессия на месте. +5. Уровень 4: негативы в `make student-test`; эксперимент `make upload-mem`. + +--- + +## Типовые вопросы + +1. **Файл в volume API ≠ объектное хранилище:** реплики эфемерны; общий S3 переживает stop реплики. +2. **Честный 201:** только после PUT и COMMIT метаданных. +3. **PUT ok, COMMIT fail:** компенсация Delete; иначе orphan + reconciler после grace. +4. **Приватный bucket ≠ ACL приложения:** API всё равно проверяет членство в чате. +5. **Почему S3 в readiness:** lab4 не может честно отдавать вложения без хранилища. + +--- + +## Ограничения + +SPOF: LB, Postgres, Redis, MinIO, один хост. Presigned upload (трек 5.1) и полный track2-evidence не делались. Reconciler — страховка orphan/missing, не восстановление потерянных used-вложений. \ No newline at end of file diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 00000000..dae1065e --- /dev/null +++ b/Dockerfile @@ -0,0 +1,20 @@ +# syntax=docker/dockerfile:1.7 +FROM golang:1.23.8-bookworm AS build +WORKDIR /src +COPY go.mod go.sum ./ +RUN go mod download +COPY cmd ./cmd +COPY internal ./internal +RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags="-s -w" -o /out/server ./cmd/server + +FROM gcr.io/distroless/static-debian12:nonroot +COPY --from=build /out/server /server +USER nonroot:nonroot +EXPOSE 8080 +ENV APP_HOST=0.0.0.0 \ + APP_PORT=8080 \ + APP_ENV=lab \ + SESSION_TTL_SECONDS=3600 +HEALTHCHECK --interval=5s --timeout=3s --start-period=15s --retries=5 \ + CMD ["/server", "-healthcheck"] +ENTRYPOINT ["/server"] diff --git a/Makefile b/Makefile index 5d86d171..f771bf18 100644 --- a/Makefile +++ b/Makefile @@ -1,13 +1,30 @@ PYTHON ?= python3 -BASE_URL ?= http://localhost:8080 +BASE_URL ?= http://127.0.0.1:8081 CA_FILE ?= ACTION_SCRIPT ?= TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",) +COMPOSE ?= docker compose -p gavrilenko-lab4 --env-file .env +GO ?= go -.PHONY: help check validate test load test-persistence test-failover +ENV_FILE ?= .env +env_val = $(shell grep -E '^$(1)=' $(ENV_FILE) 2>/dev/null | tail -n1 | cut -d= -f2-) +PG_PORT := $(or $(call env_val,POSTGRES_HOST_PORT),5433) +REDIS_PORT := $(or $(call env_val,REDIS_HOST_PORT),6380) +MINIO_PORT := $(or $(call env_val,MINIO_HOST_PORT),9002) +PG_USER := $(or $(call env_val,POSTGRES_USER),messenger) +PG_PASS := $(or $(call env_val,POSTGRES_PASSWORD),messenger) +PG_DB := $(or $(call env_val,POSTGRES_DB),messenger) + +.PHONY: help check validate test load test-persistence test-failover up down student-test private-bucket upload-mem reconcile-dry help: - @echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes" + @echo "up/down: стенд; test BASE_URL=...; student-test; private-bucket; upload-mem" + +up: + bash scripts/up.sh + +down: + $(COMPOSE) down check: $(PYTHON) scripts/check_contract.py @@ -22,9 +39,27 @@ load: $(PYTHON) tests/load.py --base-url "$(BASE_URL)" $(TLS_ARGS) test-persistence: - @test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable restart hook"; exit 2) + @test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT"; exit 2) $(PYTHON) tests/resilience.py --mode persistence --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS) test-failover: - @test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable stop-one hook"; exit 2) + @test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT"; exit 2) $(PYTHON) tests/resilience.py --mode failover --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS) + +student-test: + DATABASE_URL="$${DATABASE_URL:-postgres://$(PG_USER):$(PG_PASS)@127.0.0.1:$(PG_PORT)/$(PG_DB)?sslmode=disable}" \ + REDIS_URL="$${REDIS_URL:-redis://127.0.0.1:$(REDIS_PORT)/0}" \ + S3_ENDPOINT="$${S3_ENDPOINT:-http://127.0.0.1:$(MINIO_PORT)}" \ + S3_ACCESS_KEY="$${S3_ACCESS_KEY:-$(or $(call env_val,S3_ACCESS_KEY),messenger-api)}" \ + S3_SECRET_KEY="$${S3_SECRET_KEY:-$(or $(call env_val,S3_SECRET_KEY),messenger-api-secret-change-me)}" \ + S3_BUCKET="$${S3_BUCKET:-$(or $(call env_val,S3_BUCKET),messenger)}" \ + $(GO) test ./student-tests/ -v -count=1 -timeout 300s + +private-bucket: + bash scripts/check_private_bucket.sh | tee evidence/private-bucket.txt + +upload-mem: + bash scripts/upload_mem_experiment.sh + +reconcile-dry: + $(COMPOSE) run --rm reconcile -reconcile-dry-run \ No newline at end of file diff --git a/REPORT.md b/REPORT.md index 9ad2b84f..e9efb532 100644 --- a/REPORT.md +++ b/REPORT.md @@ -1,37 +1,65 @@ # Отчёт — лабораторная 4 -- Автор, группа: TODO -- Целевая оценка; выбранный трек 5, если нужен: TODO -- Commit/PR: TODO после публикации -- Использованные источники, библиотеки и помощь ИИ: TODO +- Автор, группа: **Гавриленко Владислав**, БПИ2303 +- Целевая оценка; трек 5: **4** (трек 5 не заявляется) +- Commit/PR: ветка `solution/bpi2303-gavrilenko` (fork `gavrilenko-sxdees/mtusi2026lab4`) +- Использованные источники: публичный контракт lab4; перенос реализации lab3 (Go, HAProxy, Redis, idempotency); образец архитектуры вложений/MinIO (Belousov lab4, без дословного копирования); `aws-sdk-go-v2` (S3); Cursor/Composer. ## Запуск из чистого clone -TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных. +Требуются Docker, Go 1.23+, Python 3.9+. + +```sh +cp .env.example .env +bash scripts/up.sh +# LB по умолчанию http://127.0.0.1:8081; если порты заняты (lab3), сдвиньте в `.env` (локально: 8082/5434/6381/9003) +make check +make test BASE_URL=http://127.0.0.1:8081 +make student-test +make private-bucket +make upload-mem +make test-persistence ACTION_SCRIPT=scripts/restart.sh BASE_URL=http://127.0.0.1:8081 +make test-failover ACTION_SCRIPT=scripts/stop-one.sh BASE_URL=http://127.0.0.1:8081 +bash scripts/restore-one.sh +make reconcile-dry +``` + +Остановка: `docker compose -p gavrilenko-lab4 --env-file .env stop`. +Сброс данных: `docker compose -p gavrilenko-lab4 --env-file .env down -v`. + +Образы: `golang:1.23.8-bookworm` → `gcr.io/distroless/static-debian12:nonroot`; `postgres:16.6`; `redis:7.4.1` (AOF); `haproxy:2.9.14-alpine`; MinIO `ghcr.io/coollabsio/minio:RELEASE.2025-10-15T17-29-55Z`; mc `cgr.dev/chainguard/minio-client:latest-dev`. Консоль MinIO выключена (`MINIO_BROWSER=off`). + +Хостовые порты по умолчанию: LB **8081**, Postgres **5433**, Redis **6380**, MinIO **9002** — чтобы lab3 и lab4 могли работать на одной машине. ## Архитектура и решения -TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab3, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации. +Клиент → HAProxy → API×N → PostgreSQL (метаданные) + Redis (сессии) + MinIO (байты вложений). + +Вложения: серверный ключ `attachments/{chat_id}/{attachment_id}`; загрузка синхронная PNG/JPEG; скачивание через API без redirect. Порядок записи S3 → PostgreSQL; компенсация при ошибке INSERT; для «зависших» orphan — reconciler с grace `S3_ORPHAN_GRACE_SECONDS` (профиль `tools`, не трек 5). + +Из lab3 перенесены: маршруты чатов/сообщений, Idempotency-Key, drain, скрипты failover/persistence (дополнен restart для MinIO). ## Доказательства критериев | Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства | | --- | --- | --- | --- | -| Публичный smoke | make test | TODO | TODO | -| Остальные пункты уровня 3 | TODO | TODO | TODO | -| Все пункты уровня 4, если заявлен | TODO | TODO | TODO | -| Выбранный трек 5, если заявлен | TODO | TODO | TODO | - -TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены. +| Offline contract | `make check` | PASS | `evidence/check.txt` | +| Публичный smoke + файл | `make test BASE_URL=http://127.0.0.1:8082` | PASS | `evidence/smoke.txt` | +| Student-tests уровня 4 | `make student-test` | PASS (~13s) | `evidence/student-tests.txt` | +| Private bucket | `make private-bucket` | PASS | `evidence/private-bucket.txt` | +| Persistence + файл | `make test-persistence …` | PASS | `evidence/persistence.txt` | +| Failover API + файл | `make test-failover …` | PASS (recovery ~3.2s) | `evidence/failover.txt` | +| ≥10 uploads + RAM | `make upload-mem` | 80×201; peak ~176 MiB @64 vs ~93 MiB @4 | `evidence/upload-memory/` | ## Эксперименты и отказы -TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения. +| Воздействие | Ожидание | Наблюдение | +| --- | --- | --- | +| stop одной API | download с другой реплики | failover PASS | +| restart хранилищ | та же сессия и файл | persistence PASS | +| S3 down | upload/ready 503 | student-tests | +| PG fail после PUT | компенсация, не 500 | student-tests | -| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных | -| --- | --- | --- | --- | -| TODO | TODO | TODO | TODO | +## Ограничения -## Ограничения и следующие шаги - -TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза. +Один Docker-host; official `minio/minio` с Hub может быть недоступен — зафиксирован community-образ. Трек 5 (presigned upload / полный reconciler research) не выполнялся. Reconciler не восстанавливает байты у used-missing. \ No newline at end of file diff --git a/cmd/server/main.go b/cmd/server/main.go new file mode 100644 index 00000000..1c36678b --- /dev/null +++ b/cmd/server/main.go @@ -0,0 +1,262 @@ +// Точка входа HTTP API, одноразового мигратора и reconciler (lab4). +// +// Режимы: +// +// (по умолчанию) — API-реплика: ждёт Postgres/Redis/S3, слушает порт, миграции НЕ +// применяет (их гоняет отдельный сервис migrate, чтобы реплики не гонялись); +// -migrate — применить встроенные SQL, проверить наличие bucket, выйти с кодом 0/1; +// -healthcheck — локальный probe /health/ready для Docker HEALTHCHECK; +// -reconcile — сверка S3 и PostgreSQL: удалить orphan-объекты старше grace, +// отчитаться о missing-объектах (трек 2). Печатает JSON-отчёт; +// -reconcile-dry-run — то же, но ничего не удаляет (подразумевает -reconcile); +// -reconcile-prune-missing — дополнительно удалять СТАРЫЕ НЕИСПОЛЬЗУЕМЫЕ строки без объекта. +// +// Коды выхода -reconcile: 0 — успех, 1 — ошибка (S3/PG недоступны), 2 — найдены +// используемые вложения без объекта (потеря данных, нужен человек). +// +// SIGTERM: /health/ready → 503 (LB снимает реплику) и Shutdown до 10 секунд. +package main + +import ( + "context" + "encoding/json" + "flag" + "fmt" + "io" + "log" + "net/http" + "os" + "os/signal" + "syscall" + "time" + + "gavrilenko-sxdees/lab4/internal/api" + "gavrilenko-sxdees/lab4/internal/auth" + "gavrilenko-sxdees/lab4/internal/config" + "gavrilenko-sxdees/lab4/internal/objectstore" + "gavrilenko-sxdees/lab4/internal/reconcile" + "gavrilenko-sxdees/lab4/internal/session" + "gavrilenko-sxdees/lab4/internal/store" +) + +func main() { + healthcheck := flag.Bool("healthcheck", false, "probe local /health/ready and exit") + migrateOnly := flag.Bool("migrate", false, "apply SQL migrations, ensure bucket and exit") + doReconcile := flag.Bool("reconcile", false, "reconcile S3 objects with PostgreSQL attachments and exit") + reconcileDry := flag.Bool("reconcile-dry-run", false, "reconcile without deleting anything (implies -reconcile)") + reconcilePrune := flag.Bool("reconcile-prune-missing", false, "reconcile: also delete stale UNUSED rows whose object is missing") + flag.Parse() + if *healthcheck { + os.Exit(runHealthcheck()) + } + + cfg, err := config.Load() + if err != nil { + log.Fatalf("config: %v", err) + } + hasher, err := auth.NewHasher() + if err != nil { + log.Fatalf("password hasher: %v", err) + } + + rootCtx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, syscall.SIGINT) + defer stop() + + st, err := waitPostgres(rootCtx, cfg.DatabaseURL, hasher, cfg.MaxConns) + if err != nil { + log.Fatalf("postgres: %v", err) + } + defer st.Close() + + objects, err := objectstore.New(objectstore.Config{ + Endpoint: cfg.S3Endpoint, + Region: cfg.S3Region, + Bucket: cfg.S3Bucket, + AccessKey: cfg.S3AccessKey, + SecretKey: cfg.S3SecretKey, + ForcePathStyle: cfg.S3ForcePathStyle, + }) + if err != nil { + log.Fatalf("object store: %v", err) + } + + if *migrateOnly || cfg.RunMigrations { + if err := st.Migrate(rootCtx); err != nil { + log.Fatalf("migrate: %v", err) + } + log.Printf("migrations applied") + // Bucket создаёт minio-init (root-учётка). Здесь только идемпотентная проверка: + // мигратор падает с понятной причиной, если стенд поднят без minio-init. + if err := waitBucket(rootCtx, objects); err != nil { + log.Fatalf("bucket: %v", err) + } + log.Printf("bucket %q is available", objects.Bucket()) + if *migrateOnly { + return + } + } + + if *doReconcile || *reconcileDry { + os.Exit(runReconcile(rootCtx, st, objects, cfg, *reconcileDry, *reconcilePrune)) + } + + sessions, err := waitRedis(rootCtx, cfg.RedisURL, cfg.SessionTTL) + if err != nil { + log.Fatalf("redis: %v", err) + } + defer sessions.Close() + + // API стартует только при доступном S3 и существующем bucket; затем доступность + // контролирует /health/ready (недоступный S3 → 503). + if err := waitBucket(rootCtx, objects); err != nil { + log.Fatalf("bucket: %v", err) + } + + srvAPI := api.New(st, sessions, objects, cfg.InstanceID).WithUploadConcurrency(cfg.UploadMaxConcurrency) + httpServer := &http.Server{ + Addr: cfg.Addr(), + Handler: srvAPI.Handler(), + ReadHeaderTimeout: 5 * time.Second, + // 10 MiB загрузка/скачивание по медленному клиенту дольше обычного JSON-запроса. + // Лимиты размера и семафор слотов не дают этому стать способом занять RAM. + ReadTimeout: 30 * time.Second, + WriteTimeout: 30 * time.Second, + IdleTimeout: 60 * time.Second, + } + + errCh := make(chan error, 1) + go func() { + log.Printf("listening on %s env=%s instance=%s session_ttl=%s db_max_conns=%d", + cfg.Addr(), cfg.Env, cfg.InstanceID, cfg.SessionTTL, cfg.MaxConns) + if err := httpServer.ListenAndServe(); err != nil && err != http.ErrServerClosed { + errCh <- err + } + }() + + select { + case err := <-errCh: + log.Fatalf("listen: %v", err) + case <-rootCtx.Done(): + } + log.Printf("shutting down instance=%s", cfg.InstanceID) + srvAPI.BeginDrain() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + if err := httpServer.Shutdown(ctx); err != nil { + log.Printf("shutdown error: %v", err) + os.Exit(1) + } + log.Printf("shutdown complete") +} + +// waitBucket ждёт S3 и идемпотентно проверяет bucket (до 45 с, как и для Postgres/Redis). +func waitBucket(ctx context.Context, objects *objectstore.Store) error { + deadline := time.Now().Add(45 * time.Second) + var last error + for { + last = objects.EnsureBucket(ctx) + if last == nil { + return nil + } + if ctx.Err() != nil || time.Now().After(deadline) { + return last + } + log.Printf("object store not ready, retrying") + select { + case <-ctx.Done(): + return ctx.Err() + case <-time.After(time.Second): + } + } +} + +// runReconcile — режим трека 2. Отчёт JSON — в stdout (годится для evidence), подробности — в лог. +func runReconcile(ctx context.Context, st *store.Store, objects *objectstore.Store, cfg config.Config, dry, prune bool) int { + rc := &reconcile.Reconciler{ + DB: st, + Objects: objects, + Opts: reconcile.Options{ + DryRun: dry, + Grace: cfg.S3OrphanGrace, + PruneMissing: prune, + Logf: log.Printf, + }, + } + log.Printf("reconcile start dry_run=%t grace=%s prune_missing=%t", dry, cfg.S3OrphanGrace, prune) + rep, err := rc.Run(ctx) + out, _ := json.MarshalIndent(rep, "", " ") + fmt.Println(string(out)) + if err != nil { + log.Printf("reconcile failed: %v", err) + return 1 + } + if rep.MissingUsed > 0 { + log.Printf("reconcile: %d used attachment(s) lost their object, manual action required", rep.MissingUsed) + return 2 + } + return 0 +} + +func waitPostgres(ctx context.Context, dsn string, hasher *auth.Hasher, maxConns int32) (*store.Store, error) { + deadline := time.Now().Add(45 * time.Second) + var last error + for { + st, err := store.Open(ctx, dsn, hasher, maxConns) + if err == nil { + return st, nil + } + last = err + if ctx.Err() != nil || time.Now().After(deadline) { + return nil, last + } + log.Printf("postgres not ready, retrying") + select { + case <-ctx.Done(): + return nil, ctx.Err() + case <-time.After(time.Second): + } + } +} + +func waitRedis(ctx context.Context, redisURL string, ttl time.Duration) (*session.Store, error) { + deadline := time.Now().Add(45 * time.Second) + var last error + for { + st, err := session.Open(redisURL, ttl) + if err == nil { + return st, nil + } + last = err + if ctx.Err() != nil || time.Now().After(deadline) { + return nil, last + } + log.Printf("redis not ready, retrying") + select { + case <-ctx.Done(): + return nil, ctx.Err() + case <-time.After(time.Second): + } + } +} + +func runHealthcheck() int { + cfg, err := config.Load() + if err != nil { + return 1 + } + host := cfg.Host + if host == "0.0.0.0" || host == "::" { + host = "127.0.0.1" + } + client := &http.Client{Timeout: 2 * time.Second} + resp, err := client.Get(fmt.Sprintf("http://%s:%d/health/ready", host, cfg.Port)) + if err != nil { + return 1 + } + defer resp.Body.Close() + _, _ = io.Copy(io.Discard, resp.Body) + if resp.StatusCode != http.StatusOK { + return 1 + } + return 0 +} diff --git a/compose.yaml b/compose.yaml new file mode 100644 index 00000000..95d2dacc --- /dev/null +++ b/compose.yaml @@ -0,0 +1,236 @@ +# Локальный стенд lab4 (Гавриленко): Клиент → HAProxy → API×N → PostgreSQL, Redis, MinIO. +# Проект Compose: gavrilenko-lab4 (скрипты задают -p). Публикуется LB и S3 только на loopback. +# Консоль MinIO отключена (MINIO_BROWSER=off); порт 9001 не публикуется. +name: gavrilenko-lab4 + +x-api-env: &api-env + APP_HOST: 0.0.0.0 + APP_PORT: 8080 + APP_ENV: ${APP_ENV:-lab} + APP_ACCESS_LOG: ${APP_ACCESS_LOG:-1} + SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600} + IDEMPOTENCY_TTL_SECONDS: ${IDEMPOTENCY_TTL_SECONDS:-86400} + DB_MAX_CONNS: ${DB_MAX_CONNS:-5} + DATABASE_URL: postgres://${POSTGRES_USER:-messenger}:${POSTGRES_PASSWORD:-messenger}@postgres:5432/${POSTGRES_DB:-messenger}?sslmode=disable + REDIS_URL: redis://redis:6379/0 + S3_ENDPOINT: http://minio:9000 + S3_REGION: ${S3_REGION:-us-east-1} + S3_BUCKET: ${S3_BUCKET:-messenger} + S3_ACCESS_KEY: ${S3_ACCESS_KEY:-messenger-api} + S3_SECRET_KEY: ${S3_SECRET_KEY:-messenger-api-secret-change-me} + S3_FORCE_PATH_STYLE: ${S3_FORCE_PATH_STYLE:-1} + S3_ORPHAN_GRACE_SECONDS: ${S3_ORPHAN_GRACE_SECONDS:-300} + UPLOAD_MAX_CONCURRENCY: ${UPLOAD_MAX_CONCURRENCY:-4} + GOMEMLIMIT: ${API_GOMEMLIMIT:-200MiB} + +services: + postgres: + image: postgres:16.6 + environment: + POSTGRES_USER: ${POSTGRES_USER:-messenger} + POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-messenger} + POSTGRES_DB: ${POSTGRES_DB:-messenger} + volumes: + - pgdata:/var/lib/postgresql/data + ports: + - "127.0.0.1:${POSTGRES_HOST_PORT:-5433}:5432" + healthcheck: + test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER:-messenger} -d ${POSTGRES_DB:-messenger}"] + interval: 5s + timeout: 3s + retries: 20 + stop_grace_period: 10s + deploy: + resources: + limits: + cpus: "1.0" + memory: 512M + + redis: + image: redis:7.4.1 + command: ["redis-server", "--appendonly", "yes", "--appendfsync", "everysec"] + volumes: + - redisdata:/data + ports: + - "127.0.0.1:${REDIS_HOST_PORT:-6380}:6379" + healthcheck: + test: ["CMD", "redis-cli", "ping"] + interval: 5s + timeout: 3s + retries: 20 + stop_grace_period: 10s + deploy: + resources: + limits: + cpus: "0.50" + memory: 256M + + minio: + image: ${MINIO_IMAGE:-ghcr.io/coollabsio/minio:RELEASE.2025-10-15T17-29-55Z} + command: ["server", "/data", "--address", ":9000"] + environment: + MINIO_ROOT_USER: ${MINIO_ROOT_USER:-minio-root} + MINIO_ROOT_PASSWORD: ${MINIO_ROOT_PASSWORD:-minio-root-secret-change-me} + MINIO_BROWSER: "off" + volumes: + - mindata:/data + ports: + - "127.0.0.1:${MINIO_HOST_PORT:-9002}:9000" + healthcheck: + test: ["CMD-SHELL", "mc ready local >/dev/null 2>&1 || curl -fsS http://127.0.0.1:9000/minio/health/ready >/dev/null 2>&1 || wget -q -O /dev/null http://127.0.0.1:9000/minio/health/ready"] + interval: 3s + timeout: 3s + retries: 20 + start_period: 5s + stop_grace_period: 10s + deploy: + resources: + limits: + cpus: "1.0" + memory: 512M + + minio-init: + image: ${MC_IMAGE:-cgr.dev/chainguard/minio-client:latest-dev} + entrypoint: ["/bin/sh", "-c"] + environment: + MINIO_ROOT_USER: ${MINIO_ROOT_USER:-minio-root} + MINIO_ROOT_PASSWORD: ${MINIO_ROOT_PASSWORD:-minio-root-secret-change-me} + S3_BUCKET: ${S3_BUCKET:-messenger} + S3_ACCESS_KEY: ${S3_ACCESS_KEY:-messenger-api} + S3_SECRET_KEY: ${S3_SECRET_KEY:-messenger-api-secret-change-me} + command: + - | + set -eu + POLICY=messenger-api-rw + until mc alias set local http://minio:9000 "$$MINIO_ROOT_USER" "$$MINIO_ROOT_PASSWORD" >/dev/null 2>&1; do + echo "minio-init: waiting for minio..."; sleep 1 + done + mc mb --ignore-existing "local/$$S3_BUCKET" + mc anonymous set none "local/$$S3_BUCKET" + cat > /tmp/policy.json </dev/null 2>&1 || true + mc admin user info local "$$S3_ACCESS_KEY" | grep -q "$$POLICY" \ + || { echo "minio-init: policy $$POLICY is not attached to $$S3_ACCESS_KEY" >&2; exit 1; } + echo "minio-init: bucket=$$S3_BUCKET user=$$S3_ACCESS_KEY policy=$$POLICY ok" + depends_on: + minio: + condition: service_healthy + restart: "no" + deploy: + resources: + limits: + memory: 128M + + migrate: + build: . + command: ["-migrate"] + environment: + <<: *api-env + depends_on: + postgres: + condition: service_healthy + minio-init: + condition: service_completed_successfully + restart: "no" + healthcheck: + disable: true + deploy: + resources: + limits: + cpus: "0.50" + memory: 256M + + reconcile: + build: . + command: ["-reconcile"] + environment: + <<: *api-env + depends_on: + postgres: + condition: service_healthy + minio: + condition: service_healthy + profiles: ["tools"] + restart: "no" + healthcheck: + disable: true + deploy: + resources: + limits: + cpus: "0.50" + memory: 256M + + api: + build: . + environment: + <<: *api-env + expose: + - "8080" + depends_on: + redis: + condition: service_healthy + postgres: + condition: service_healthy + minio: + condition: service_healthy + minio-init: + condition: service_completed_successfully + healthcheck: + test: ["CMD", "/server", "-healthcheck"] + interval: 2s + timeout: 2s + retries: 10 + start_period: 15s + stop_grace_period: 10s + restart: "no" + deploy: + resources: + limits: + cpus: ${API_CPUS:-0.50} + memory: ${API_MEMORY:-256M} + + lb: + image: haproxy:2.9.14-alpine + volumes: + - ./infra/haproxy/haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro + ports: + - "127.0.0.1:${LB_HOST_PORT:-8081}:8080" + depends_on: + api: + condition: service_healthy + healthcheck: + test: ["CMD", "haproxy", "-c", "-f", "/usr/local/etc/haproxy/haproxy.cfg"] + interval: 10s + timeout: 3s + retries: 5 + start_period: 5s + stop_grace_period: 10s + deploy: + resources: + limits: + cpus: "0.50" + memory: 128M + +volumes: + pgdata: + redisdata: + mindata: \ No newline at end of file diff --git a/evidence/check.txt b/evidence/check.txt new file mode 100644 index 00000000..9a553306 --- /dev/null +++ b/evidence/check.txt @@ -0,0 +1,2 @@ +python3 scripts/check_contract.py +PASS: offline skeleton structure, local refs and Python syntax; application NOT tested. diff --git a/evidence/failover.txt b/evidence/failover.txt new file mode 100644 index 00000000..91a1be5e --- /dev/null +++ b/evidence/failover.txt @@ -0,0 +1,4 @@ +python3 tests/resilience.py --mode failover --action-script "scripts/stop-one.sh" --base-url "http://127.0.0.1:8082" +Executing explicit failover hook; hook output suppressed to avoid leaking secrets. +{"observed_instances_before": 2, "successful_writes": 104, "failed_attempts": 1, "first_recovery_seconds": 3.169} +PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence. diff --git a/evidence/persistence.txt b/evidence/persistence.txt new file mode 100644 index 00000000..7b748522 --- /dev/null +++ b/evidence/persistence.txt @@ -0,0 +1,3 @@ +python3 tests/resilience.py --mode persistence --action-script "scripts/restart.sh" --base-url "http://127.0.0.1:8082" +Executing explicit persistence hook; hook output suppressed to avoid leaking secrets. +PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence. diff --git a/evidence/private-bucket.txt b/evidence/private-bucket.txt new file mode 100644 index 00000000..bc7fe20a --- /dev/null +++ b/evidence/private-bucket.txt @@ -0,0 +1,21 @@ +== подготовка: загрузить реальное вложение через API и узнать его object_key +attachment=5db75133-2002-41fc-943d-6e9062f34d2a (ключ в S3 внутренний, в ответах API его нет) +== 1. анонимный доступ +PASS анонимный GET объекта → 403 +PASS анонимный листинг bucket → 403 +PASS анонимный PUT → 403 +== 2. контроль: подписанный запрос учётки messenger-api +PASS GET с подписью messenger-api → 200 (объект существует) +== 3. права учётки API ограничены bucket-ом +PASS ListBuckets не раскрывает чужие buckets +PASS чтение объекта в чужом bucket → 403 +PASS листинг чужого bucket → 403 +PASS запись в чужой bucket → 403 +PASS CreateBucket → 403 +== 4. консоль MinIO не опубликована +PASS 127.0.0.1:9001 не отвечает консолью (000) +PASS порт 9001 сервиса minio не опубликован +публикуемые порты minio: [{127.0.0.1 9000 9003 tcp}] +PASS в Publishers нет 9001 +PASS S3 API только на 127.0.0.1 +ИТОГ: bucket приватный diff --git a/evidence/smoke.txt b/evidence/smoke.txt new file mode 100644 index 00000000..915aa06f --- /dev/null +++ b/evidence/smoke.txt @@ -0,0 +1,2 @@ +python3 tests/smoke.py --base-url "http://127.0.0.1:8082" +PASS: lab4 public API scenario; infrastructure and grading evidence remain separate. diff --git a/evidence/student-tests.txt b/evidence/student-tests.txt new file mode 100644 index 00000000..7e5f1d5b --- /dev/null +++ b/evidence/student-tests.txt @@ -0,0 +1,419 @@ +DATABASE_URL="${DATABASE_URL:-postgres://messenger:messenger@127.0.0.1:5434/messenger?sslmode=disable}" \ + REDIS_URL="${REDIS_URL:-redis://127.0.0.1:6381/0}" \ + S3_ENDPOINT="${S3_ENDPOINT:-http://127.0.0.1:9003}" \ + S3_ACCESS_KEY="${S3_ACCESS_KEY:-messenger-api}" \ + S3_SECRET_KEY="${S3_SECRET_KEY:-messenger-api-secret-change-me}" \ + S3_BUCKET="${S3_BUCKET:-messenger}" \ + go test ./student-tests/ -v -count=1 -timeout 300s +=== RUN TestMalformedJSONAndValidation + api_test.go:96: → битый JSON, хвост после объекта, лишнее поле, пустой текст, чужой чат +2026/12/01 21:58:20 method=POST path=/api/v1/users status=400 request_id=01afd54c-3d79-44a4-b0ee-372be57ebc6f duration_ms=0 + api_test.go:99: status=400 body={"error":{"code":"invalid_request","message":"malformed json","request_id":"01afd54c-3d79-44a4-b0ee-372be57ebc6f"}} +2026/12/01 21:58:20 method=POST path=/api/v1/users status=400 request_id=3762a883-eec9-4e8b-bd40-5b1d13e0dbe5 duration_ms=0 + api_test.go:106: status=400 body={"error":{"code":"invalid_request","message":"malformed json","request_id":"3762a883-eec9-4e8b-bd40-5b1d13e0dbe5"}} +2026/12/01 21:58:20 method=POST path=/api/v1/users status=201 request_id=94c38c2f-5e6f-47a7-8e1a-cbc6adf8719b duration_ms=65 + api_test.go:111: создан ok_user_67a97ae5 id=326efb60-10c6-480a-b6cb-f0f4a0a50e41 +2026/12/01 21:58:20 method=POST path=/api/v1/auth/sessions status=201 request_id=04ff26a0-e778-4f21-9711-466bf7da5ead duration_ms=51 + api_test.go:112: сессия выпущена, длина токена=64 (значение не печатаем) +2026/12/01 21:58:20 method=POST path=/api/v1/chats status=201 request_id=71b4f183-b13c-4533-b9c0-ae87e70b1a04 duration_ms=10 +2026/12/01 21:58:20 method=POST path=/api/v1/chats/239a7816-a704-4d6c-9029-89df22bd194c/messages status=400 request_id=3925d0b1-52ea-4285-bede-afed2a0fe206 duration_ms=1 + api_test.go:119: status=400 body={"error":{"code":"invalid_request","message":"malformed json","request_id":"3925d0b1-52ea-4285-bede-afed2a0fe206"}} +2026/12/01 21:58:20 method=POST path=/api/v1/chats/239a7816-a704-4d6c-9029-89df22bd194c/messages status=400 request_id=b10068a5-769e-42d3-add1-cbd41d028402 duration_ms=1 + api_test.go:119: status=400 body={"error":{"code":"invalid_request","message":"malformed json","request_id":"b10068a5-769e-42d3-add1-cbd41d028402"}} +2026/12/01 21:58:20 method=POST path=/api/v1/chats/239a7816-a704-4d6c-9029-89df22bd194c/messages status=400 request_id=a5efa1ee-cff1-4566-975e-0b0c73a00796 duration_ms=1 + api_test.go:126: status=400 body={"error":{"code":"invalid_request","message":"invalid text","request_id":"a5efa1ee-cff1-4566-975e-0b0c73a00796"}} +2026/12/01 21:58:20 method=POST path=/api/v1/users status=201 request_id=f4708ea7-86c9-43d2-9ac4-dfe61767beee duration_ms=38 + api_test.go:131: создан outsider_37688b02 id=aa88cb70-1a95-48f2-ab09-3ab86bca5291 +2026/12/01 21:58:20 method=POST path=/api/v1/auth/sessions status=201 request_id=b5f53907-1b8f-4827-bfee-7de0405c1909 duration_ms=53 + api_test.go:132: сессия выпущена, длина токена=64 (значение не печатаем) +2026/12/01 21:58:20 method=POST path=/api/v1/chats/239a7816-a704-4d6c-9029-89df22bd194c/messages status=404 request_id=911eadc5-7016-4a7d-b42a-940f020b8b7f duration_ms=13 + api_test.go:134: status=404 body={"error":{"code":"not_found","message":"object not found","request_id":"911eadc5-7016-4a7d-b42a-940f020b8b7f"}} + api_test.go:138: ✓ валидация JSON, хвоста, пустого текста и чужого чата +--- PASS: TestMalformedJSONAndValidation (0.25s) +=== RUN TestMessageTextPreservedAndLengthOnOriginal + api_test.go:144: → пробелы по краям сохраняются; длина считается по исходному тексту +2026/12/01 21:58:20 method=POST path=/api/v1/users status=201 request_id=261ab52e-3db2-443a-b98c-ba51f794705f duration_ms=67 + api_test.go:145: создан text_user_9eb6cc3d id=6b83b904-828c-4332-b2c5-4c64db22c9bb +2026/12/01 21:58:20 method=POST path=/api/v1/auth/sessions status=201 request_id=0080807c-8e34-4c2f-815d-6b4ba46ce245 duration_ms=46 + api_test.go:146: сессия выпущена, длина токена=64 (значение не печатаем) +2026/12/01 21:58:20 method=POST path=/api/v1/chats status=201 request_id=4e3f73c9-1f7d-4d28-b0c3-dda4aeb963ee duration_ms=6 +2026/12/01 21:58:20 method=POST path=/api/v1/chats/a770fe64-a4b9-49cd-9e3b-e03aa057b60a/messages status=201 request_id=7432aef4-4ea3-43fe-92e0-d2e3250be14c duration_ms=8 + api_test.go:153: status=201 body={"attachment_ids":[],"chat_id":"a770fe64-a4b9-49cd-9e3b-e03aa057b60a","created_at":"2026-12-01T18:58:20.688Z","id":"ed09cba4-8870-40a1-9025-66da3ee0fd58","sender_id":"6b83b904-828c-4332-b2c5-4c64db22c9bb","text":" строка\nс пробелами "} +2026/12/01 21:58:20 method=POST path=/api/v1/chats/a770fe64-a4b9-49cd-9e3b-e03aa057b60a/messages status=400 request_id=488be3a5-4456-4088-b211-893977910ae8 duration_ms=0 + api_test.go:165: status=400 body={"error":{"code":"invalid_request","message":"invalid text","request_id":"488be3a5-4456-4088-b211-893977910ae8"}} + api_test.go:169: ✓ текст сохранён целиком, обход лимита через TrimSpace закрыт +--- PASS: TestMessageTextPreservedAndLengthOnOriginal (0.13s) +=== RUN TestSessionRejectsJSONBody + api_test.go:175: → POST /auth/sessions с телом должен быть 400 даже при верном Basic +2026/12/01 21:58:20 method=POST path=/api/v1/users status=201 request_id=4702c48c-ae62-4d8b-9459-aa7f93354c99 duration_ms=41 + api_test.go:176: создан body_user_47c84eb3 id=259cf23e-b500-45c6-a4a4-fd9ad627d635 +2026/12/01 21:58:20 method=POST path=/api/v1/auth/sessions status=400 request_id=db4fe7a3-692a-4a42-9ae2-db59eb3812c3 duration_ms=0 + api_test.go:180: status=400 body={"error":{"code":"invalid_request","message":"session create must not have a body","request_id":"db4fe7a3-692a-4a42-9ae2-db59eb3812c3"}} + api_test.go:184: ✓ вход без JSON body +--- PASS: TestSessionRejectsJSONBody (0.04s) +=== RUN TestWrongPasswordLogoutAndIgnoredUserHeader + api_test.go:190: → неверный пароль, Basic на бизнес-методе, X-User-Id, logout +2026/12/01 21:58:20 method=POST path=/api/v1/users status=201 request_id=0e24ac2c-0c6e-47ab-a915-a57c98b5e4d3 duration_ms=39 + api_test.go:191: создан auth_user_60120960 id=955239fa-f3a5-4737-8e3f-c00c40b32077 +2026/12/01 21:58:20 method=POST path=/api/v1/users status=201 request_id=59e9dcc2-22f6-4280-a109-a74ba7070b0e duration_ms=46 + api_test.go:192: создан auth_other_ff97a54b id=8009bbd5-046d-4702-9844-2be9733a9a8e +2026/12/01 21:58:20 method=POST path=/api/v1/auth/sessions status=401 request_id=795f78de-89b2-4542-8f6c-192574eaf557 duration_ms=40 + api_test.go:197: status=401 body={"error":{"code":"unauthorized","message":"authentication required","request_id":"795f78de-89b2-4542-8f6c-192574eaf557"}} +2026/12/01 21:58:20 method=POST path=/api/v1/auth/sessions status=201 request_id=5c396ef7-e7e6-4cc8-8c8e-abb36124e26c duration_ms=44 + api_test.go:202: сессия выпущена, длина токена=64 (значение не печатаем) +2026/12/01 21:58:20 method=GET path=/api/v1/users/me status=401 request_id=d37ca73f-f190-4e96-b8b6-a37c6e0c8ec3 duration_ms=0 + api_test.go:206: status=401 body={"error":{"code":"unauthorized","message":"authentication required","request_id":"d37ca73f-f190-4e96-b8b6-a37c6e0c8ec3"}} +2026/12/01 21:58:20 method=GET path=/api/v1/users/me status=401 request_id=9d4f3028-4329-4c23-a026-c0e4f83069b8 duration_ms=0 + api_test.go:212: status=401 body={"error":{"code":"unauthorized","message":"authentication required","request_id":"9d4f3028-4329-4c23-a026-c0e4f83069b8"}} +2026/12/01 21:58:20 method=GET path=/api/v1/users/me status=200 request_id=344cc38a-abc2-41ef-8101-1bc7fc6da90c duration_ms=3 + api_test.go:221: status=200 body={"created_at":"2026-12-01T18:58:20.782Z","display_name":"Студент","id":"955239fa-f3a5-4737-8e3f-c00c40b32077","username":"auth_user_60120960"} +2026/12/01 21:58:20 method=DELETE path=/api/v1/auth/sessions/current status=204 request_id=4dea947a-4a64-42e6-8865-016f2730e0a1 duration_ms=1 + api_test.go:227: logout status=204 +2026/12/01 21:58:20 method=GET path=/api/v1/users/me status=401 request_id=bcee10b4-ce00-44bb-a6f4-6e13abcde533 duration_ms=0 +2026/12/01 21:58:20 method=DELETE path=/api/v1/auth/sessions/current status=401 request_id=83f18ace-154b-44a9-b51c-69f1f1c0b33f duration_ms=0 + api_test.go:239: ✓ пароль, заголовки и отзыв сессии +--- PASS: TestWrongPasswordLogoutAndIgnoredUserHeader (0.18s) +=== RUN TestSessionExpiry + api_test.go:245: → SESSION_TTL=2s: тот же токен после паузы должен стать 401, TTL рестартом API не продлевается +2026/12/01 21:58:20 method=POST path=/api/v1/users status=201 request_id=92390952-2a6e-4535-844d-b3a942cf7cac duration_ms=46 + api_test.go:246: создан ttl_user_a50e6a08 id=842a69d2-df63-42b9-b2cc-c8e2e40c6694 +2026/12/01 21:58:21 method=POST path=/api/v1/auth/sessions status=201 request_id=e2bcf62f-497d-4d92-bb34-5c7eed7448c5 duration_ms=38 + api_test.go:247: сессия выпущена, длина токена=64 (значение не печатаем) +2026/12/01 21:58:23 method=GET path=/api/v1/users/me status=401 request_id=5ca7186d-cda1-4ac5-b69b-150f053b6f50 duration_ms=8 + api_test.go:250: status=401 body={"error":{"code":"unauthorized","message":"authentication required","request_id":"5ca7186d-cda1-4ac5-b69b-150f053b6f50"}} + api_test.go:254: ✓ истёкшая сессия отклонена +--- PASS: TestSessionExpiry (2.60s) +=== RUN TestDuplicateUsernameRace + api_test.go:261: → 8 параллельных регистраций username=race_0c6a2408 +2026/12/01 21:58:23 method=POST path=/api/v1/users status=201 request_id=c5464434-7861-48bf-96ea-8b44de41b8a1 duration_ms=161 +2026/12/01 21:58:23 method=POST path=/api/v1/users status=409 request_id=4e786af4-a6ed-49e2-9165-485a8374a646 duration_ms=164 +2026/12/01 21:58:23 method=POST path=/api/v1/users status=409 request_id=cd3f721f-8d9d-4a2e-9505-7fd8730d0271 duration_ms=170 +2026/12/01 21:58:23 method=POST path=/api/v1/users status=409 request_id=ef1567c4-546a-4769-911e-84798b799fde duration_ms=174 +2026/12/01 21:58:23 method=POST path=/api/v1/users status=409 request_id=de488d01-7201-4bee-8d06-526a4103da49 duration_ms=184 +2026/12/01 21:58:23 method=POST path=/api/v1/users status=409 request_id=92859392-a110-40f8-97f0-5743d85cc259 duration_ms=190 +2026/12/01 21:58:23 method=POST path=/api/v1/users status=409 request_id=10b3529e-cf19-42c1-9fcb-70ff09dc15a2 duration_ms=193 +2026/12/01 21:58:23 method=POST path=/api/v1/users status=409 request_id=b32b8951-a848-4da2-b7c3-19edd6785dcc duration_ms=192 + api_test.go:286: created=1 conflict=7 + api_test.go:290: ✓ UNIQUE username выдержал гонку +--- PASS: TestDuplicateUsernameRace (0.21s) +=== RUN TestChatCreateRollsBack +2026/12/01 21:58:23 method=POST path=/api/v1/users status=201 request_id=ed124d67-9de6-4347-a6a7-090b7f054f97 duration_ms=95 + api_test.go:296: создан roll_user_23809c71 id=e59c6c39-205f-4e63-94bb-a994c652a6e1 +2026/12/01 21:58:23 method=POST path=/api/v1/auth/sessions status=201 request_id=19f51a3a-39d3-4de6-a3e0-5e1b5b810ac1 duration_ms=125 + api_test.go:297: сессия выпущена, длина токена=64 (значение не печатаем) + api_test.go:300: → создание чата с несуществующим участником должно откатиться, title=rollback-40fe1ea5-338d-4677-842f-64d46c961c7a +2026/12/01 21:58:24 method=POST path=/api/v1/chats status=400 request_id=4d905396-ea54-41e3-99f1-7fc4e466730a duration_ms=74 + api_test.go:303: status=400 body={"error":{"code":"invalid_request","message":"unknown member","request_id":"4d905396-ea54-41e3-99f1-7fc4e466730a"}} + api_test.go:311: строк chats с этим title после ошибки: 0 + api_test.go:315: ✓ транзакция создания чата откатилась +--- PASS: TestChatCreateRollsBack (0.35s) +=== RUN TestPaginationPages + api_test.go:321: → три сообщения, две страницы limit=2, затем последняя +2026/12/01 21:58:24 method=POST path=/api/v1/users status=201 request_id=50fb4eb0-83d9-41f4-9e57-678e9b7f8929 duration_ms=118 + api_test.go:322: создан page_user_a4e05751 id=065d6c5c-8bc3-41a8-b243-69b13b8b41fb +2026/12/01 21:58:24 method=POST path=/api/v1/auth/sessions status=201 request_id=ebcb85ea-9ea5-4154-8994-ff87da181d46 duration_ms=105 + api_test.go:323: сессия выпущена, длина токена=64 (значение не печатаем) +2026/12/01 21:58:24 method=POST path=/api/v1/chats status=201 request_id=d6deb008-4673-4ed7-a2b6-910129fc0999 duration_ms=64 +2026/12/01 21:58:25 method=POST path=/api/v1/chats/e9b883c6-23dc-4852-af0b-a13e98e471d3/messages status=201 request_id=37e33cf8-db6d-4d2a-b88b-157bb728701f duration_ms=840 +2026/12/01 21:58:25 method=POST path=/api/v1/chats/e9b883c6-23dc-4852-af0b-a13e98e471d3/messages status=201 request_id=056b77b1-5ab0-4901-aaad-e925ee12b110 duration_ms=53 +2026/12/01 21:58:25 method=POST path=/api/v1/chats/e9b883c6-23dc-4852-af0b-a13e98e471d3/messages status=201 request_id=181d1090-5444-49e6-9141-5949f5a56ddb duration_ms=51 +2026/12/01 21:58:25 method=GET path=/api/v1/chats/e9b883c6-23dc-4852-af0b-a13e98e471d3/messages status=200 request_id=ea4699d4-fff3-4974-bac6-6f1e37248473 duration_ms=20 + api_test.go:333: status=200 body={"items":[{"attachment_ids":[],"chat_id":"e9b883c6-23dc-4852-af0b-a13e98e471d3","created_at":"2026-12-01T18:58:25.213Z","id":"1b705c14-1605-4081-a2b5-8ad8456780b1","sender_id":"065d6c5c-8bc3-41a8-b243-69b13b8b41fb","text":"раз"},{"attachment_ids":[],"chat_id":"e9b883c6-23dc-4852-af0b-a13e98e471d3","created_at":"2026-12-01T18:58:25.295Z","id":"8b9de1d1-ba76-467a-82d7-180e232bcad3","sender_id":"0... +2026/12/01 21:58:25 method=GET path=/api/v1/chats/e9b883c6-23dc-4852-af0b-a13e98e471d3/messages status=200 request_id=860e674e-b6be-49c7-9aac-e5c9cc784f79 duration_ms=15 + api_test.go:341: status=200 body={"items":[{"attachment_ids":[],"chat_id":"e9b883c6-23dc-4852-af0b-a13e98e471d3","created_at":"2026-12-01T18:58:25.350Z","id":"c5cbcf53-1283-44ab-9c76-544a2fb45ffa","sender_id":"065d6c5c-8bc3-41a8-b243-69b13b8b41fb","text":"три"}],"next_cursor":null} + api_test.go:347: ✓ keyset обошёл историю без зависания cursor +--- PASS: TestPaginationPages (1.33s) +=== RUN TestRedisDownIsNotAnonymous + api_test.go:351: → закрытый клиент Redis: вход и Bearer дают 503, а не 200 от анонима +2026/12/01 21:58:25 method=POST path=/api/v1/users status=201 request_id=de10c4ef-991c-41b3-96d1-bf42593b2ca2 duration_ms=91 + api_test.go:363: создан redis_down_7d513082 id=090460d5-7c4e-4b88-b503-e5a9d3226f7e +2026/12/01 21:58:25 method=POST path=/api/v1/auth/sessions status=503 request_id=7c510476-9042-427a-9b25-e16e6e856e1f duration_ms=55 + api_test.go:367: status=503 body={"error":{"code":"unavailable","message":"dependency unavailable","request_id":"7c510476-9042-427a-9b25-e16e6e856e1f"}} +2026/12/01 21:58:25 method=GET path=/api/v1/users/me status=503 request_id=c1078896-8c33-49ed-9ef0-a002cac5ee1b duration_ms=0 + api_test.go:374: status=503 body={"error":{"code":"unavailable","message":"dependency unavailable","request_id":"c1078896-8c33-49ed-9ef0-a002cac5ee1b"}} + api_test.go:378: ✓ сбой Redis не стал анонимным доступом +--- PASS: TestRedisDownIsNotAnonymous (0.18s) +=== RUN TestPostgresDownIsNotAnonymous + api_test.go:382: → закрытый пул PostgreSQL: ready/me/login дают 503, без тела пользователя +2026/12/01 21:58:25 method=POST path=/api/v1/users status=201 request_id=dd446fea-3f11-42ba-af0d-0d6ef95a4ac7 duration_ms=92 + api_test.go:385: создан pg_down_6890d887 id=f354397a-9f92-4f72-bfd0-954dcc89620d +2026/12/01 21:58:25 method=POST path=/api/v1/auth/sessions status=201 request_id=b86f6d6a-65f8-4a66-9d92-db8d4b3c19d5 duration_ms=80 + api_test.go:386: сессия выпущена, длина токена=64 (значение не печатаем) +2026/12/01 21:58:25 method=GET path=/health/ready status=503 request_id=dcf2de7b-cd42-40a8-a8d7-043e27dcacf8 duration_ms=0 + api_test.go:407: status=503 body={"error":{"code":"unavailable","message":"dependency unavailable","request_id":"dcf2de7b-cd42-40a8-a8d7-043e27dcacf8"}} +2026/12/01 21:58:25 method=GET path=/api/v1/users/me status=503 request_id=bf2b58b4-ab13-4ece-9ce9-b969bdd10011 duration_ms=6 + api_test.go:414: status=503 body={"error":{"code":"unavailable","message":"dependency unavailable","request_id":"bf2b58b4-ab13-4ece-9ce9-b969bdd10011"}} +2026/12/01 21:58:25 method=POST path=/api/v1/auth/sessions status=503 request_id=2ac57497-134b-4d79-b8c0-3af19b8c0318 duration_ms=0 + api_test.go:421: status=503 body={"error":{"code":"unavailable","message":"dependency unavailable","request_id":"2ac57497-134b-4d79-b8c0-3af19b8c0318"}} + api_test.go:425: ✓ сбой PostgreSQL не стал анонимным доступом +--- PASS: TestPostgresDownIsNotAnonymous (0.35s) +=== RUN TestIdempotencyReplayAndConflict + api_test.go:431: → повтор того же Idempotency-Key возвращает то же сообщение; другой body — 409 +2026/12/01 21:58:26 method=POST path=/api/v1/users status=201 request_id=b6d52aa5-57de-499a-819e-2acc9893ad12 duration_ms=93 + api_test.go:432: создан idem_user_bb1be8da id=438e4803-1ef9-4231-9a73-81f09683491d +2026/12/01 21:58:26 method=POST path=/api/v1/auth/sessions status=201 request_id=e5ebf5ae-1868-43a0-88ce-14f295b43cc1 duration_ms=94 + api_test.go:433: сессия выпущена, длина токена=64 (значение не печатаем) +2026/12/01 21:58:26 method=POST path=/api/v1/chats status=201 request_id=2d15ae62-70b5-497e-8993-d372f10aa325 duration_ms=18 +2026/12/01 21:58:26 method=POST path=/api/v1/chats/f32bc877-b405-46f1-92fc-bc98071d6d46/messages status=201 request_id=7ce1c18c-53ae-4cbb-81f8-d2ce9e84dcfb duration_ms=76 + api_test.go:441: status=201 body={"attachment_ids":[],"chat_id":"f32bc877-b405-46f1-92fc-bc98071d6d46","created_at":"2026-12-01T18:58:26.177Z","id":"7fdf9b0f-e773-4f46-9931-7148077033f9","sender_id":"438e4803-1ef9-4231-9a73-81f09683491d","text":"один раз"} +2026/12/01 21:58:26 method=POST path=/api/v1/chats/f32bc877-b405-46f1-92fc-bc98071d6d46/messages status=201 request_id=6bb81834-8f2c-4a70-aec7-baf076765e76 duration_ms=48 + api_test.go:447: status=201 body={"attachment_ids":[],"chat_id":"f32bc877-b405-46f1-92fc-bc98071d6d46","created_at":"2026-12-01T18:58:26.177Z","id":"7fdf9b0f-e773-4f46-9931-7148077033f9","sender_id":"438e4803-1ef9-4231-9a73-81f09683491d","text":"один раз"} +2026/12/01 21:58:26 method=POST path=/api/v1/chats/f32bc877-b405-46f1-92fc-bc98071d6d46/messages status=409 request_id=07971910-e817-4d7a-841e-36d066644e59 duration_ms=16 + api_test.go:456: status=409 body={"error":{"code":"conflict","message":"idempotency key reused with different body","request_id":"07971910-e817-4d7a-841e-36d066644e59"}} + api_test.go:460: ✓ replay и conflict по Idempotency-Key +--- PASS: TestIdempotencyReplayAndConflict (0.36s) +=== RUN TestIdempotencyKeyRequiredAndConcurrent + api_test.go:466: → нет ключа → 400; 8 параллельных POST с одним ключом → ровно одно сообщение +2026/12/01 21:58:26 method=POST path=/api/v1/users status=201 request_id=247fa258-dcba-4cfa-adf5-c0f0a26ff240 duration_ms=68 + api_test.go:467: создан idem_race_f933771c id=0eeffbb0-7628-42b6-9636-0510df2804e6 +2026/12/01 21:58:26 method=POST path=/api/v1/auth/sessions status=201 request_id=f6052d41-121f-4b49-a6b6-7481cf47bd99 duration_ms=91 + api_test.go:468: сессия выпущена, длина токена=64 (значение не печатаем) +2026/12/01 21:58:26 method=POST path=/api/v1/chats status=201 request_id=d7c99c26-deec-44d0-aff8-66d4823889f4 duration_ms=36 +2026/12/01 21:58:26 method=POST path=/api/v1/chats/bd337ceb-3dd7-4e88-801c-55542cc480ae/messages status=400 request_id=7c6f8ca2-f6ef-48c0-9b04-969eb6be75a6 duration_ms=3 + api_test.go:486: status=400 body={"error":{"code":"invalid_request","message":"invalid or missing Idempotency-Key","request_id":"7c6f8ca2-f6ef-48c0-9b04-969eb6be75a6"}} +2026/12/01 21:58:26 method=POST path=/api/v1/chats/bd337ceb-3dd7-4e88-801c-55542cc480ae/messages status=201 request_id=b62c8e15-6573-4bd7-91d4-6c644c9f179b duration_ms=35 +2026/12/01 21:58:26 method=POST path=/api/v1/chats/bd337ceb-3dd7-4e88-801c-55542cc480ae/messages status=201 request_id=14beadb8-5085-48d6-949d-7f4a3867b9f1 duration_ms=115 +2026/12/01 21:58:26 method=POST path=/api/v1/chats/bd337ceb-3dd7-4e88-801c-55542cc480ae/messages status=201 request_id=2d165347-5e21-428e-ae4a-90594088f938 duration_ms=124 +2026/12/01 21:58:26 method=POST path=/api/v1/chats/bd337ceb-3dd7-4e88-801c-55542cc480ae/messages status=201 request_id=38fc339c-db82-4f11-a4d6-f38d1dd13687 duration_ms=165 +2026/12/01 21:58:26 method=POST path=/api/v1/chats/bd337ceb-3dd7-4e88-801c-55542cc480ae/messages status=201 request_id=28e7a700-c5dc-48fc-af18-e5d95ed9a522 duration_ms=206 +2026/12/01 21:58:26 method=POST path=/api/v1/chats/bd337ceb-3dd7-4e88-801c-55542cc480ae/messages status=201 request_id=5035a00a-e588-44d2-9c1d-97af983a33fc duration_ms=235 +2026/12/01 21:58:26 method=POST path=/api/v1/chats/bd337ceb-3dd7-4e88-801c-55542cc480ae/messages status=201 request_id=61baef3e-7844-4e29-9b31-b2ca16daffa7 duration_ms=263 +2026/12/01 21:58:26 method=POST path=/api/v1/chats/bd337ceb-3dd7-4e88-801c-55542cc480ae/messages status=201 request_id=8ca65086-ec39-41a4-adcb-eadf8599ac99 duration_ms=284 + api_test.go:518: unique message ids=1 + api_test.go:522: ✓ ключ обязателен; конкурентный повтор не плодит дубли +--- PASS: TestIdempotencyKeyRequiredAndConcurrent (0.50s) +=== RUN TestInstanceIDHeaderPresent + api_test.go:528: → каждый ответ содержит непустой X-Instance-Id + api_test.go:530: status=200 body={"status":"ok"} + api_test.go:534: ✓ X-Instance-Id=test-instance +--- PASS: TestInstanceIDHeaderPresent (0.01s) +=== RUN TestAttachmentRoundTripAndAccessControl + attachments_test.go:203: → PNG и JPEG: 201 ready, sha256/size, download без redirect, доступ только участникам +2026/12/01 21:58:26 method=POST path=/api/v1/users status=201 request_id=4cac634f-6bcd-4e1b-a2bf-675fb5ac4dc0 duration_ms=119 + attachments_test.go:206: создан att_alice_beba8c7a id=52f047c5-76bf-4994-a75c-97692db69ebe +2026/12/01 21:58:27 method=POST path=/api/v1/users status=201 request_id=59ca935b-347d-4699-9a78-35f1155798b7 duration_ms=81 + attachments_test.go:207: создан att_bob_a197f321 id=10a0d1f1-155c-4c77-8339-13943e287693 +2026/12/01 21:58:27 method=POST path=/api/v1/users status=201 request_id=c23d2232-acc3-461e-800b-1e10cabefeba duration_ms=94 + attachments_test.go:208: создан att_eve_56c7c11f id=344e75bd-61ba-455c-a733-0a56b0d518f1 +2026/12/01 21:58:27 method=POST path=/api/v1/auth/sessions status=201 request_id=4be591eb-25c3-406a-87c1-606e566c0638 duration_ms=83 + attachments_test.go:209: сессия выпущена, длина токена=64 (значение не печатаем) +2026/12/01 21:58:27 method=POST path=/api/v1/auth/sessions status=201 request_id=2cf32395-d229-4a6f-b63b-6c2886868e6f duration_ms=75 + attachments_test.go:210: сессия выпущена, длина токена=64 (значение не печатаем) +2026/12/01 21:58:27 method=POST path=/api/v1/auth/sessions status=201 request_id=6a516cdf-e480-47b1-b80f-c5c2743d94bd duration_ms=72 + attachments_test.go:211: сессия выпущена, длина токена=64 (значение не печатаем) +2026/12/01 21:58:27 method=POST path=/api/v1/chats status=201 request_id=2ac75104-39d3-426f-9e4b-a3dce45fe6f4 duration_ms=26 +2026/12/01 21:58:27 method=POST path=/api/v1/chats/fc640630-c6c2-4f88-83af-1bf15dbf47e8/attachments status=201 request_id=0727cea8-ea30-43a6-a8ed-b5a819b5c9dd duration_ms=106 +2026/12/01 21:58:27 method=GET path=/api/v1/attachments/92a7bc63-a93e-4d70-983b-c9de531dd51f status=200 request_id=53f5c019-6ffa-4e19-8b48-b0038fb99751 duration_ms=35 +2026/12/01 21:58:27 method=GET path=/api/v1/attachments/92a7bc63-a93e-4d70-983b-c9de531dd51f/content status=200 request_id=e436dba5-325d-4436-838e-7ecf778ac224 duration_ms=17 +2026/12/01 21:58:27 method=POST path=/api/v1/chats/fc640630-c6c2-4f88-83af-1bf15dbf47e8/attachments status=201 request_id=72f981e9-1c37-423d-a78b-c2bf0de9f6db duration_ms=23 +2026/12/01 21:58:27 method=GET path=/api/v1/attachments/92a7bc63-a93e-4d70-983b-c9de531dd51f status=404 request_id=c8eb1d0d-5715-4a46-acab-c6f21f3c31b5 duration_ms=5 + attachments_test.go:259: status=404 body={"error":{"code":"not_found","message":"object not found","request_id":"c8eb1d0d-5715-4a46-acab-c6f21f3c31b5"}} +2026/12/01 21:58:27 method=GET path=/api/v1/attachments/92a7bc63-a93e-4d70-983b-c9de531dd51f/content status=404 request_id=1c9f04dc-2e31-4201-a4bd-b919060acd41 duration_ms=6 + attachments_test.go:259: status=404 body={"error":{"code":"not_found","message":"object not found","request_id":"1c9f04dc-2e31-4201-a4bd-b919060acd41"}} +2026/12/01 21:58:27 method=POST path=/api/v1/chats/fc640630-c6c2-4f88-83af-1bf15dbf47e8/attachments status=404 request_id=d17e8504-270a-4b02-83ea-d4fa9f53d871 duration_ms=5 +2026/12/01 21:58:27 method=POST path=/api/v1/chats/fc640630-c6c2-4f88-83af-1bf15dbf47e8/attachments status=401 request_id=46290ebd-eb92-4455-8fa9-a90fb3ed3a40 duration_ms=0 +2026/12/01 21:58:27 method=GET path=/api/v1/attachments/92a7bc63-a93e-4d70-983b-c9de531dd51f/content status=404 request_id=c235c189-f690-4c2f-913e-9fd9687f606f duration_ms=4 +2026/12/01 21:58:27 method=GET path=/api/v1/attachments/d976811c-5091-47fd-a36d-415a1fbf9135 status=404 request_id=660db267-9c77-4daf-a438-34439be0cf37 duration_ms=4 +2026/12/01 21:58:27 method=POST path=/api/v1/chats/fc640630-c6c2-4f88-83af-1bf15dbf47e8/messages status=201 request_id=848301d0-1274-4d17-9f3f-93711f213809 duration_ms=42 + attachments_test.go:288: status=201 body={"attachment_ids":["4fc0786e-181b-42bf-a57c-132e907ec9d9","92a7bc63-a93e-4d70-983b-c9de531dd51f"],"chat_id":"fc640630-c6c2-4f88-83af-1bf15dbf47e8","created_at":"2026-12-01T18:58:27.620Z","id":"dd3fec40-8719-46b3-a7c6-4925989a2816","sender_id":"52f047c5-76bf-4994-a75c-97692db69ebe","text":"смотри"} +2026/12/01 21:58:27 method=POST path=/api/v1/chats/fc640630-c6c2-4f88-83af-1bf15dbf47e8/messages status=201 request_id=c77748ec-3cba-4025-a8af-6694fd88314b duration_ms=73 +2026/12/01 21:58:27 method=POST path=/api/v1/chats/fc640630-c6c2-4f88-83af-1bf15dbf47e8/messages status=409 request_id=17a61b62-52b0-4f4f-b145-09b416c0a477 duration_ms=154 +2026/12/01 21:58:27 method=GET path=/api/v1/chats/fc640630-c6c2-4f88-83af-1bf15dbf47e8/messages status=200 request_id=4a559191-04ba-48c1-aa1c-02705f563dc1 duration_ms=10 +2026/12/01 21:58:27 method=GET path=/api/v1/chats/fc640630-c6c2-4f88-83af-1bf15dbf47e8/messages status=404 request_id=2e497bc2-98ff-48da-99b9-81c69f7ec277 duration_ms=4 + attachments_test.go:319: ✓ upload/download/доступ/replay работают, внутренние ключи не раскрываются +--- PASS: TestAttachmentRoundTripAndAccessControl (1.08s) +=== RUN TestAttachmentTooLarge + attachments_test.go:324: → ровно 10 MiB проходит лимит размера (дальше 415 как не-картинка), 10 MiB+1 → 413 +2026/12/01 21:58:27 method=POST path=/api/v1/users status=201 request_id=7ddf73ed-7547-4fa9-a3d8-03e9465a116c duration_ms=79 + attachments_test.go:325: создан att_big_4daf86e1 id=5c53a092-69eb-4ff5-aad4-a3c6ee32e54b +2026/12/01 21:58:28 method=POST path=/api/v1/auth/sessions status=201 request_id=c2637bf9-fef7-4d7a-8bf1-52f714c2a2e9 duration_ms=109 + attachments_test.go:325: сессия выпущена, длина токена=64 (значение не печатаем) +2026/12/01 21:58:28 method=POST path=/api/v1/chats status=201 request_id=86de037b-8e29-445d-bf39-76f1379ea800 duration_ms=65 +2026/12/01 21:58:28 method=POST path=/api/v1/chats/590943e6-2f84-4949-9693-e9f7491d0caa/attachments status=415 request_id=c8bbd92c-04d4-4c60-b651-5d4f985c4cec duration_ms=12 + attachments_test.go:330: status=415 body={"error":{"code":"unsupported_media_type","message":"file is not a valid png/jpeg image","request_id":"c8bbd92c-04d4-4c60-b651-5d4f985c4cec"}} +2026/12/01 21:58:28 method=POST path=/api/v1/chats/590943e6-2f84-4949-9693-e9f7491d0caa/attachments status=413 request_id=41339836-1f40-4b44-a378-c3a99a00bd7e duration_ms=23 + attachments_test.go:337: status=413 body={"error":{"code":"payload_too_large","message":"file is too large","request_id":"41339836-1f40-4b44-a378-c3a99a00bd7e"}} +2026/12/01 21:58:28 method=POST path=/api/v1/chats/590943e6-2f84-4949-9693-e9f7491d0caa/attachments status=413 request_id=26981107-e12b-4837-b792-b66507780156 duration_ms=13 +2026/12/01 21:58:28 method=POST path=/api/v1/chats/590943e6-2f84-4949-9693-e9f7491d0caa/attachments status=413 request_id=63e28e6e-8647-4c32-b818-a87a34c2414a duration_ms=13 + attachments_test.go:364: ✓ лимит байтов: граница точная, работает и для chunked +--- PASS: TestAttachmentTooLarge (0.35s) +=== RUN TestAttachmentPixelLimit + attachments_test.go:369: → 8000x5000 (=40 млн) принимается, 8000x5001 → 413 +2026/12/01 21:58:28 method=POST path=/api/v1/users status=201 request_id=7977b741-beeb-4148-a60d-c93c8ba2e4eb duration_ms=113 + attachments_test.go:370: создан att_px_bdccb3ce id=266b62fa-b97d-4ffe-9202-249d4588811d +2026/12/01 21:58:28 method=POST path=/api/v1/auth/sessions status=201 request_id=7d10af1a-c3e8-45af-a0b0-4f464f1e7478 duration_ms=77 + attachments_test.go:370: сессия выпущена, длина токена=64 (значение не печатаем) +2026/12/01 21:58:28 method=POST path=/api/v1/chats status=201 request_id=813271a0-a99a-4640-94e4-a754c7175c00 duration_ms=21 + attachments_test.go:373: PNG 8000x5000 занимает 9860 байт на проводе +2026/12/01 21:58:28 method=POST path=/api/v1/chats/7a1cc0b4-8d4f-42a3-8300-424040002866/attachments status=201 request_id=4236df5b-99a6-4123-a959-69c730da1b9f duration_ms=34 +2026/12/01 21:58:28 method=POST path=/api/v1/chats/7a1cc0b4-8d4f-42a3-8300-424040002866/attachments status=413 request_id=5025a303-9fef-45df-861d-caf5912ec300 duration_ms=1 + attachments_test.go:381: status=413 body={"error":{"code":"payload_too_large","message":"image has too many pixels","request_id":"5025a303-9fef-45df-861d-caf5912ec300"}} + attachments_test.go:385: ✓ лимит пикселей по заголовку, без полного декода +--- PASS: TestAttachmentPixelLimit (0.30s) +=== RUN TestAttachmentCorruptAndMimeSpoof + attachments_test.go:390: → мусор, усечённые PNG/JPEG, битый CRC, GIF под видом PNG, подмена Content-Type +2026/12/01 21:58:28 method=POST path=/api/v1/users status=201 request_id=66ac9f5a-7066-4be2-b19c-f83795e84866 duration_ms=58 + attachments_test.go:391: создан att_bad_a481e386 id=1cc1f865-5c4a-496a-96ae-c9cac266be6f +2026/12/01 21:58:28 method=POST path=/api/v1/auth/sessions status=201 request_id=6f9c2986-fb7e-4a7f-9c94-89c3cfcdd16b duration_ms=66 + attachments_test.go:391: сессия выпущена, длина токена=64 (значение не печатаем) +2026/12/01 21:58:28 method=POST path=/api/v1/chats status=201 request_id=36f7eaf7-2703-4a2d-b032-8aca09670074 duration_ms=13 +2026/12/01 21:58:28 method=POST path=/api/v1/chats/9eea2ac0-9591-4857-b412-3ff3c13f874d/attachments status=415 request_id=bf76714c-b8de-41e0-84aa-fc31aae1484e duration_ms=1 + attachments_test.go:419: случайные байты как png → 415 +2026/12/01 21:58:28 method=POST path=/api/v1/chats/9eea2ac0-9591-4857-b412-3ff3c13f874d/attachments status=415 request_id=5edb8ff9-3701-4f03-ab14-a278cbec3536 duration_ms=3 + attachments_test.go:419: пустое тело → 415 +2026/12/01 21:58:28 method=POST path=/api/v1/chats/9eea2ac0-9591-4857-b412-3ff3c13f874d/attachments status=415 request_id=9ce7f04f-9843-4e1a-aa7e-2ad30e67876c duration_ms=2 + attachments_test.go:419: усечённый PNG → 415 +2026/12/01 21:58:28 method=POST path=/api/v1/chats/9eea2ac0-9591-4857-b412-3ff3c13f874d/attachments status=415 request_id=08835f47-f805-45b4-b59c-9351a2d67756 duration_ms=2 + attachments_test.go:419: усечённый JPEG → 415 +2026/12/01 21:58:28 method=POST path=/api/v1/chats/9eea2ac0-9591-4857-b412-3ff3c13f874d/attachments status=415 request_id=2aeb65a6-7105-45d1-bcde-168f34398f93 duration_ms=4 + attachments_test.go:419: PNG с битым CRC → 415 +2026/12/01 21:58:28 method=POST path=/api/v1/chats/9eea2ac0-9591-4857-b412-3ff3c13f874d/attachments status=415 request_id=88f84fd9-0199-4186-9ba8-2f0359178163 duration_ms=4 + attachments_test.go:419: GIF под видом PNG → 415 +2026/12/01 21:58:28 method=POST path=/api/v1/chats/9eea2ac0-9591-4857-b412-3ff3c13f874d/attachments status=415 request_id=28d1a37a-6741-45df-a5d6-9bfbb8c0487a duration_ms=4 + attachments_test.go:419: PNG под видом JPEG (спуфинг) → 415 +2026/12/01 21:58:28 method=POST path=/api/v1/chats/9eea2ac0-9591-4857-b412-3ff3c13f874d/attachments status=415 request_id=eb181878-746c-4f6e-8f43-b4880f63871c duration_ms=5 + attachments_test.go:419: JPEG под видом PNG (спуфинг) → 415 +2026/12/01 21:58:28 method=POST path=/api/v1/chats/9eea2ac0-9591-4857-b412-3ff3c13f874d/attachments status=415 request_id=e4e4ed50-c1db-45e5-8df0-cca87f425598 duration_ms=2 + attachments_test.go:419: валидный PNG, но Content-Type text/plain → 415 +2026/12/01 21:58:28 method=POST path=/api/v1/chats/9eea2ac0-9591-4857-b412-3ff3c13f874d/attachments status=415 request_id=a3710935-96cf-43f2-9a86-46abe7c3bfe5 duration_ms=4 + attachments_test.go:419: валидный PNG без Content-Type → 415 +2026/12/01 21:58:28 method=POST path=/api/v1/chats/9eea2ac0-9591-4857-b412-3ff3c13f874d/attachments status=415 request_id=83018bb6-5829-41fe-8899-ed9059c31595 duration_ms=2 + attachments_test.go:419: валидный PNG, Content-Type image/gif → 415 +2026/12/01 21:58:28 method=POST path=/api/v1/chats/9eea2ac0-9591-4857-b412-3ff3c13f874d/attachments status=201 request_id=8a1d010b-4bb9-4735-a135-a19f214c57eb duration_ms=18 + attachments_test.go:437: ✓ все повреждённые/подменённые файлы → 415, строки в БД не создаются +--- PASS: TestAttachmentCorruptAndMimeSpoof (0.22s) +=== RUN TestAttachmentFilenameValidation + attachments_test.go:441: → filename: '/', '\', NUL, управляющие, пустое, >255 → 400; unicode и пробелы допустимы +2026/12/01 21:58:28 method=POST path=/api/v1/users status=201 request_id=b6b1cb24-14d3-45b4-934b-8a006871e950 duration_ms=69 + attachments_test.go:442: создан att_name_9df1d75b id=c8d128d9-fbc0-40df-9bd8-12670b7302c0 +2026/12/01 21:58:28 method=POST path=/api/v1/auth/sessions status=201 request_id=8179cd47-c2f9-4009-9c7d-39b1b67315bd duration_ms=78 + attachments_test.go:442: сессия выпущена, длина токена=64 (значение не печатаем) +2026/12/01 21:58:28 method=POST path=/api/v1/chats status=201 request_id=e1565082-23ea-4e6a-a4a6-de15d3580ceb duration_ms=21 +2026/12/01 21:58:28 method=POST path=/api/v1/chats/f7573d23-efef-4737-a87d-f1df80895ea2/attachments status=400 request_id=a7250d4d-d76d-47a4-b08d-a6f937cef85d duration_ms=6 +2026/12/01 21:58:28 method=POST path=/api/v1/chats/f7573d23-efef-4737-a87d-f1df80895ea2/attachments status=400 request_id=4de33619-7269-4b1d-a7c9-852adc070070 duration_ms=4 +2026/12/01 21:58:28 method=POST path=/api/v1/chats/f7573d23-efef-4737-a87d-f1df80895ea2/attachments status=400 request_id=9252b043-2b3e-4c88-ad8b-559f33e5516c duration_ms=5 +2026/12/01 21:58:28 method=POST path=/api/v1/chats/f7573d23-efef-4737-a87d-f1df80895ea2/attachments status=400 request_id=d38cbb64-8eb6-406b-9032-8fbaa61ca02c duration_ms=3 +2026/12/01 21:58:28 method=POST path=/api/v1/chats/f7573d23-efef-4737-a87d-f1df80895ea2/attachments status=400 request_id=6fe424c9-30fb-4b8b-895f-71c26717f549 duration_ms=4 +2026/12/01 21:58:28 method=POST path=/api/v1/chats/f7573d23-efef-4737-a87d-f1df80895ea2/attachments status=400 request_id=0301271b-874d-4e4e-881e-31b44e2ffaa7 duration_ms=6 +2026/12/01 21:58:28 method=POST path=/api/v1/chats/f7573d23-efef-4737-a87d-f1df80895ea2/attachments status=400 request_id=c8afc6a1-205f-439e-90d3-8a9d3eafd4f4 duration_ms=4 +2026/12/01 21:58:29 method=POST path=/api/v1/chats/f7573d23-efef-4737-a87d-f1df80895ea2/attachments status=400 request_id=8ec00a28-c791-4a1c-8025-884e061060c1 duration_ms=5 +2026/12/01 21:58:29 method=POST path=/api/v1/chats/f7573d23-efef-4737-a87d-f1df80895ea2/attachments status=400 request_id=044e7764-dfb5-49e9-b0d9-511d6be71873 duration_ms=4 +2026/12/01 21:58:29 method=POST path=/api/v1/chats/f7573d23-efef-4737-a87d-f1df80895ea2/attachments status=400 request_id=b4690595-c901-43d5-8d1a-7d49c64cafb7 duration_ms=3 +2026/12/01 21:58:29 method=POST path=/api/v1/chats/f7573d23-efef-4737-a87d-f1df80895ea2/attachments status=400 request_id=d3a06ad0-b41e-4761-9411-c12a399dca2f duration_ms=2 +2026/12/01 21:58:29 method=POST path=/api/v1/chats/f7573d23-efef-4737-a87d-f1df80895ea2/attachments status=201 request_id=7e3ac971-0b03-4f6d-997e-6832d2741084 duration_ms=25 +2026/12/01 21:58:29 method=POST path=/api/v1/chats/f7573d23-efef-4737-a87d-f1df80895ea2/attachments status=201 request_id=d36b3f2b-4b57-454b-ace9-ff5287a9a609 duration_ms=28 +2026/12/01 21:58:29 method=POST path=/api/v1/chats/f7573d23-efef-4737-a87d-f1df80895ea2/attachments status=201 request_id=42167528-fb9c-493e-8606-a7b4c6a53979 duration_ms=48 + attachments_test.go:472: ✓ опасные имена отклоняются, обычные Unicode-имена сохраняются как есть +--- PASS: TestAttachmentFilenameValidation (0.36s) +=== RUN TestMessageAttachmentRules + attachments_test.go:478: → foreign attachment_id, вложение другого чата, неизвестный id, лимиты и пустой текст +2026/12/01 21:58:29 method=POST path=/api/v1/users status=201 request_id=8e8e0095-2b8c-4f2d-9b3d-305c6147b0df duration_ms=113 + attachments_test.go:481: создан rule_alice_2d2d808f id=a67c47d3-22bc-4087-bae4-8e83a820a6cf +2026/12/01 21:58:29 method=POST path=/api/v1/users status=201 request_id=d5781525-6dfe-4926-bc7a-e761673c1e17 duration_ms=84 + attachments_test.go:482: создан rule_mal_84aad169 id=9e7c51c4-60c2-4dd5-8fba-58471ba1ab7d +2026/12/01 21:58:29 method=POST path=/api/v1/auth/sessions status=201 request_id=d2902ce2-f94d-40d4-ba83-d24d67b5152c duration_ms=44 + attachments_test.go:483: сессия выпущена, длина токена=64 (значение не печатаем) +2026/12/01 21:58:29 method=POST path=/api/v1/auth/sessions status=201 request_id=c84e6ef6-0209-4471-bfab-38a5c95345ea duration_ms=40 + attachments_test.go:484: сессия выпущена, длина токена=64 (значение не печатаем) +2026/12/01 21:58:29 method=POST path=/api/v1/chats status=201 request_id=15e28a73-d0c4-47b7-8296-8c47944234cf duration_ms=3 +2026/12/01 21:58:29 method=POST path=/api/v1/chats status=201 request_id=c39dbc33-fa72-4c35-bfb7-3be3c8f1069f duration_ms=4 +2026/12/01 21:58:29 method=POST path=/api/v1/chats status=201 request_id=f43ee995-6ebe-42ac-9fa0-ade5d47615ab duration_ms=4 +2026/12/01 21:58:29 method=POST path=/api/v1/chats/d06577ab-a895-422d-9d52-dac6f1a03c8c/attachments status=201 request_id=066126fb-b2dc-49f5-b687-a15b1a19933e duration_ms=16 +2026/12/01 21:58:29 method=POST path=/api/v1/chats/bf63182a-abdc-494b-bf4d-694807d6e416/attachments status=201 request_id=97246851-0ba5-424f-acd5-7d0a3f195144 duration_ms=16 +2026/12/01 21:58:29 method=POST path=/api/v1/chats/d06577ab-a895-422d-9d52-dac6f1a03c8c/messages status=404 request_id=b3ce92ba-259d-44e1-988c-7b17e582be99 duration_ms=24 + attachments_test.go:499: status=404 body={"error":{"code":"not_found","message":"object not found","request_id":"b3ce92ba-259d-44e1-988c-7b17e582be99"}} +2026/12/01 21:58:29 method=POST path=/api/v1/chats/339a4757-ac97-40e7-a5e4-8f434d2c2f67/messages status=404 request_id=78b3b2db-ff0d-4669-805f-bfdb1046fa24 duration_ms=7 + attachments_test.go:505: status=404 body={"error":{"code":"not_found","message":"object not found","request_id":"78b3b2db-ff0d-4669-805f-bfdb1046fa24"}} +2026/12/01 21:58:29 method=POST path=/api/v1/chats/d06577ab-a895-422d-9d52-dac6f1a03c8c/messages status=404 request_id=9598d50b-cf00-4477-9d47-41712665b6d7 duration_ms=4 +2026/12/01 21:58:29 method=POST path=/api/v1/chats/d06577ab-a895-422d-9d52-dac6f1a03c8c/messages status=404 request_id=238574b1-c495-40b3-9a8e-cda6ce5d6481 duration_ms=4 +2026/12/01 21:58:29 method=GET path=/api/v1/chats/d06577ab-a895-422d-9d52-dac6f1a03c8c/messages status=200 request_id=b03d7207-96c1-4c41-a835-e80cb5c29364 duration_ms=2 +2026/12/01 21:58:29 method=POST path=/api/v1/chats/d06577ab-a895-422d-9d52-dac6f1a03c8c/messages status=400 request_id=82d0a6dd-a779-46dc-926a-5694082c6a14 duration_ms=0 +2026/12/01 21:58:29 method=POST path=/api/v1/chats/d06577ab-a895-422d-9d52-dac6f1a03c8c/messages status=400 request_id=82131a11-f938-455b-a064-0a4c03b3d7b3 duration_ms=0 +2026/12/01 21:58:29 method=POST path=/api/v1/chats/d06577ab-a895-422d-9d52-dac6f1a03c8c/messages status=400 request_id=bf7f0b83-9906-4e24-b2e1-a3727d976409 duration_ms=0 +2026/12/01 21:58:29 method=POST path=/api/v1/chats/d06577ab-a895-422d-9d52-dac6f1a03c8c/messages status=400 request_id=75c74a2a-cfb2-4f00-b32a-bc6d05da3591 duration_ms=0 +2026/12/01 21:58:29 method=POST path=/api/v1/chats/d06577ab-a895-422d-9d52-dac6f1a03c8c/messages status=201 request_id=b904c6ba-872c-481d-bc59-8b21566a7730 duration_ms=10 +2026/12/01 21:58:29 method=POST path=/api/v1/chats/d06577ab-a895-422d-9d52-dac6f1a03c8c/attachments status=201 request_id=296431a9-422f-4ebe-a331-4dbaaeaca62e duration_ms=12 +2026/12/01 21:58:29 method=POST path=/api/v1/chats/d06577ab-a895-422d-9d52-dac6f1a03c8c/attachments status=201 request_id=689372ca-14d6-4beb-88b8-e76256c78e91 duration_ms=13 +2026/12/01 21:58:29 method=POST path=/api/v1/chats/d06577ab-a895-422d-9d52-dac6f1a03c8c/attachments status=201 request_id=cb5d495b-1376-47da-8738-03129f7540d7 duration_ms=28 +2026/12/01 21:58:29 method=POST path=/api/v1/chats/d06577ab-a895-422d-9d52-dac6f1a03c8c/attachments status=201 request_id=a625301e-4457-4f63-ac66-d41ab621be2e duration_ms=9 +2026/12/01 21:58:29 method=POST path=/api/v1/chats/d06577ab-a895-422d-9d52-dac6f1a03c8c/attachments status=201 request_id=df98dbf4-2b78-4f18-8b94-44f389b39a50 duration_ms=8 +2026/12/01 21:58:29 method=POST path=/api/v1/chats/d06577ab-a895-422d-9d52-dac6f1a03c8c/attachments status=201 request_id=eb5ace50-5bc6-410b-9ae2-ce6450fe33c1 duration_ms=6 +2026/12/01 21:58:29 method=POST path=/api/v1/chats/d06577ab-a895-422d-9d52-dac6f1a03c8c/attachments status=201 request_id=e19c3fda-00b0-450f-ae9b-f577664635f9 duration_ms=16 +2026/12/01 21:58:29 method=POST path=/api/v1/chats/d06577ab-a895-422d-9d52-dac6f1a03c8c/attachments status=201 request_id=2bac7d09-f774-413a-849f-5715485d058e duration_ms=10 +2026/12/01 21:58:29 method=POST path=/api/v1/chats/d06577ab-a895-422d-9d52-dac6f1a03c8c/attachments status=201 request_id=46652804-bddd-4f08-85a3-763f25644c89 duration_ms=16 +2026/12/01 21:58:29 method=POST path=/api/v1/chats/d06577ab-a895-422d-9d52-dac6f1a03c8c/attachments status=201 request_id=a36c77bd-8f19-4894-97b2-98d9100e817c duration_ms=30 +2026/12/01 21:58:29 method=POST path=/api/v1/chats/d06577ab-a895-422d-9d52-dac6f1a03c8c/messages status=201 request_id=0e077bd7-b102-4a1b-a116-039c3adfab07 duration_ms=45 +2026/12/01 21:58:29 method=POST path=/api/v1/chats/d06577ab-a895-422d-9d52-dac6f1a03c8c/messages status=201 request_id=a6be3265-5d54-4ce2-ad99-07ecc7ee1c68 duration_ms=33 + attachments_test.go:565: ✓ чужое/другой чат/неизвестное → 404, лимиты → 400, пустой текст только с вложением +--- PASS: TestMessageAttachmentRules (0.64s) +=== RUN TestS3DownGivesLimitedError + attachments_test.go:571: → API с недоступным S3: upload/ready → 503, без утечек и полуфабрикатов в БД +2026/12/01 21:58:29 method=POST path=/api/v1/users status=201 request_id=7a6cccf3-47d2-490d-8e87-fc530fde19c8 duration_ms=66 + attachments_test.go:580: создан att_down_25eeb87b id=5f2b6d44-5c30-44ec-b566-81fbe27fe220 +2026/12/01 21:58:29 method=POST path=/api/v1/auth/sessions status=201 request_id=f41dcf59-4c9f-4fc9-8ec4-87bda5964e45 duration_ms=48 + attachments_test.go:580: сессия выпущена, длина токена=64 (значение не печатаем) +2026/12/01 21:58:29 method=POST path=/api/v1/chats status=201 request_id=d972f16f-0c5f-45d5-a65b-c781e0ae62c6 duration_ms=5 +2026/12/01 21:58:31 request_id=a805df0d-e338-45e2-9c1d-d943d429b426 attachment_put_failed err=object store unavailable +2026/12/01 21:58:31 method=POST path=/api/v1/chats/8a6d80a2-dd26-4056-8a77-6a73968b8239/attachments status=503 request_id=a805df0d-e338-45e2-9c1d-d943d429b426 duration_ms=1515 + attachments_test.go:591: upload при лежащем S3: status=503 за 1.516s body={"error":{"code":"unavailable","message":"dependency unavailable","request_id":"a805df0d-e338-45e2-9c1d-d943d429b426"}} +2026/12/01 21:58:32 method=GET path=/health/ready status=503 request_id=9bf4e6dd-96f5-41cd-809a-84f1861a2734 duration_ms=703 + attachments_test.go:616: ✓ лежащий S3 → 503 без деталей, ready=503, live=200, БД чиста +--- PASS: TestS3DownGivesLimitedError (2.37s) +=== RUN TestCompensationWhenPostgresFailsAfterPut + attachments_test.go:633: → отказ PG после успешного PUT: объект удаляется компенсацией +2026/12/01 21:58:32 method=POST path=/api/v1/users status=201 request_id=2d3d9918-2a1f-4a50-9b6f-f3b95d45dbb0 duration_ms=82 + attachments_test.go:635: создан att_comp_4b586851 id=b35bceff-ae42-4556-aa6e-d0f6e1df1938 +2026/12/01 21:58:32 method=POST path=/api/v1/auth/sessions status=201 request_id=c72adeeb-9085-439c-a8e4-63e053d75a28 duration_ms=50 + attachments_test.go:635: сессия выпущена, длина токена=64 (значение не печатаем) +2026/12/01 21:58:32 method=POST path=/api/v1/chats status=201 request_id=8d71c20a-b369-4c8c-ad88-b6e9d013a4f5 duration_ms=5 +2026/12/01 21:58:32 request_id=dd2b5886-12a1-4baf-babf-0493879c2c90 attachment_compensated key=attachments/84fc1350-72dc-4ebc-8356-59a9a6844213/3f6af15f-0a5f-4cf8-adf6-5751acce28d4 (PG insert не удался, объект удалён) +2026/12/01 21:58:32 method=POST path=/api/v1/chats/84fc1350-72dc-4ebc-8356-59a9a6844213/attachments status=503 request_id=dd2b5886-12a1-4baf-babf-0493879c2c90 duration_ms=17 + attachments_test.go:668: status=503 body={"error":{"code":"unavailable","message":"dependency unavailable","request_id":"dd2b5886-12a1-4baf-babf-0493879c2c90"}} + key=attachments/84fc1350-72dc-4ebc-8356-59a9a6844213/3f6af15f-0a5f-4cf8-adf6-5751acce28d4 + attachments_test.go:682: ✓ orphan после отказа PG удалён сразу; если бы удаление не удалось — его уберёт reconciler +--- PASS: TestCompensationWhenPostgresFailsAfterPut (0.22s) +=== RUN TestConcurrentUploads + attachments_test.go:687: → 12 параллельных загрузок: все 201, уникальные id, sha256 совпадает +2026/12/01 21:58:32 method=POST path=/api/v1/users status=201 request_id=b5a93c03-7b3d-4e9b-addb-7635ab6b8b86 duration_ms=39 + attachments_test.go:688: создан att_conc_85e68ede id=68ffe16b-f50a-499f-b480-41d6aecd49ec +2026/12/01 21:58:32 method=POST path=/api/v1/auth/sessions status=201 request_id=2c659ceb-212a-4304-8b36-69630965b3dc duration_ms=32 + attachments_test.go:688: сессия выпущена, длина токена=64 (значение не печатаем) +2026/12/01 21:58:32 method=POST path=/api/v1/chats status=201 request_id=b6a5f0d7-1e78-480b-89af-a63f638b1932 duration_ms=1 +2026/12/01 21:58:32 method=POST path=/api/v1/chats/8633cf35-0472-4270-b41f-ca967df21189/attachments status=201 request_id=133c62e2-0a7e-4f36-a70c-e8729cbba6dd duration_ms=42 +2026/12/01 21:58:32 method=POST path=/api/v1/chats/8633cf35-0472-4270-b41f-ca967df21189/attachments status=201 request_id=6a06818b-94c5-4606-a808-2f2dc258a3c1 duration_ms=41 +2026/12/01 21:58:32 method=POST path=/api/v1/chats/8633cf35-0472-4270-b41f-ca967df21189/attachments status=201 request_id=74a535e6-9a97-4612-9408-08556a195ce3 duration_ms=45 +2026/12/01 21:58:32 method=POST path=/api/v1/chats/8633cf35-0472-4270-b41f-ca967df21189/attachments status=201 request_id=bcbc44c9-0d4e-43d4-9888-da300d444777 duration_ms=50 +2026/12/01 21:58:32 method=POST path=/api/v1/chats/8633cf35-0472-4270-b41f-ca967df21189/attachments status=201 request_id=ddef005c-4035-4892-a33b-457382986bd8 duration_ms=58 +2026/12/01 21:58:32 method=POST path=/api/v1/chats/8633cf35-0472-4270-b41f-ca967df21189/attachments status=201 request_id=6abe3e08-5493-4e00-bec0-45f11410bffa duration_ms=62 +2026/12/01 21:58:32 method=POST path=/api/v1/chats/8633cf35-0472-4270-b41f-ca967df21189/attachments status=201 request_id=55edd557-90c7-4a23-a6f8-6236bce19c8a duration_ms=66 +2026/12/01 21:58:32 method=POST path=/api/v1/chats/8633cf35-0472-4270-b41f-ca967df21189/attachments status=201 request_id=12827294-8fc6-44b7-9705-a3b7b57484a1 duration_ms=68 +2026/12/01 21:58:32 method=POST path=/api/v1/chats/8633cf35-0472-4270-b41f-ca967df21189/attachments status=201 request_id=dbcd6ff5-e984-4404-9244-82fde35fb20d duration_ms=75 +2026/12/01 21:58:32 method=POST path=/api/v1/chats/8633cf35-0472-4270-b41f-ca967df21189/attachments status=201 request_id=64efc355-998c-40ba-8cee-159280bbb56d duration_ms=78 +2026/12/01 21:58:32 method=POST path=/api/v1/chats/8633cf35-0472-4270-b41f-ca967df21189/attachments status=201 request_id=8e78f9f4-3775-4de5-a5db-39a8175c77f7 duration_ms=74 +2026/12/01 21:58:32 method=POST path=/api/v1/chats/8633cf35-0472-4270-b41f-ca967df21189/attachments status=201 request_id=c959d8e8-f0a8-43e7-830d-dd6d30343702 duration_ms=77 +2026/12/01 21:58:32 method=GET path=/api/v1/attachments/d7dc21a4-a15f-4aad-a596-e3f4e0b645a9/content status=200 request_id=49ddad0a-4318-4467-9f01-f6533f9b010b duration_ms=24 +2026/12/01 21:58:32 method=GET path=/api/v1/attachments/46cc28c2-6b00-4961-ad8a-0cfd678d04b7/content status=200 request_id=90f23104-cb67-4945-9262-00bcf108b97b duration_ms=32 +2026/12/01 21:58:32 method=GET path=/api/v1/attachments/66f80456-6c14-4538-89a7-2359fc13bb4b/content status=200 request_id=dbc51978-1977-49a4-8ca8-d47fdc5fc5dc duration_ms=6 +2026/12/01 21:58:32 method=GET path=/api/v1/attachments/4e6536c7-550f-4ad0-8259-0da355cb40c1/content status=200 request_id=e67435e0-b036-425e-be71-b5b432eba508 duration_ms=3 +2026/12/01 21:58:32 method=GET path=/api/v1/attachments/13bb5198-4505-4d1a-a889-b50445970f61/content status=200 request_id=d66d5f55-4067-4f5e-a069-3bda2aab1d53 duration_ms=4 +2026/12/01 21:58:32 method=GET path=/api/v1/attachments/9c36ddcd-1b64-49a8-8578-0fb3b70f70a5/content status=200 request_id=022ddf3a-b2a7-4294-a140-ea19c1b071fe duration_ms=7 +2026/12/01 21:58:32 method=GET path=/api/v1/attachments/9608e69f-275c-443a-8400-f167aad7abf4/content status=200 request_id=916e2848-0c5c-4335-8f4c-4b386ea3c565 duration_ms=8 +2026/12/01 21:58:32 method=GET path=/api/v1/attachments/c77839fd-d7f5-4b8c-9757-52bd0a22c624/content status=200 request_id=9367eaae-c5ed-4170-8463-8b1a44de72b3 duration_ms=8 +2026/12/01 21:58:32 method=GET path=/api/v1/attachments/3b07eb6e-96a6-4a7b-976d-d1a5b727a6b7/content status=200 request_id=ab82c88e-7a45-498b-acea-0735e5a6df98 duration_ms=5 +2026/12/01 21:58:32 method=GET path=/api/v1/attachments/8a97b163-ab17-4f16-8217-c67d55d4c5f9/content status=200 request_id=a12c7567-4c5f-4f63-9b78-ac76585b6177 duration_ms=8 +2026/12/01 21:58:32 method=GET path=/api/v1/attachments/2dd2df8b-2a62-48b3-8714-58d456528644/content status=200 request_id=ff00108e-4e98-4713-bc5a-25d59fbea2b9 duration_ms=6 +2026/12/01 21:58:32 method=GET path=/api/v1/attachments/a2fa0804-5e6f-4d1b-9740-66e7aa8d9613/content status=200 request_id=ae20b934-4cc7-478a-86e8-9eb0e62bf36e duration_ms=3 + attachments_test.go:722: ✓ параллельные загрузки целы +--- PASS: TestConcurrentUploads (0.29s) +=== RUN TestObjectKeyIsServerAssigned + attachments_test.go:727: → ключ объекта = attachments/{chat}/{id}; filename в ключ не попадает +2026/12/01 21:58:32 method=POST path=/api/v1/users status=201 request_id=6477b5e5-fc58-4df9-b421-e79013b0c792 duration_ms=50 + attachments_test.go:728: создан att_key_e09ba1ad id=a638e6af-0a06-4131-8b42-87ad79599f15 +2026/12/01 21:58:32 method=POST path=/api/v1/auth/sessions status=201 request_id=53303bcb-9119-40aa-90b4-76c97b180702 duration_ms=38 + attachments_test.go:728: сессия выпущена, длина токена=64 (значение не печатаем) +2026/12/01 21:58:32 method=POST path=/api/v1/chats status=201 request_id=37a65e64-d59e-4a19-87aa-0c3b35e7d423 duration_ms=4 +2026/12/01 21:58:32 method=POST path=/api/v1/chats/7bb6c813-d438-4e05-bff5-076d254f1d65/attachments status=201 request_id=deb0513a-a897-45a0-91e5-25a4b92ff65c duration_ms=5 + attachments_test.go:742: ✓ ключ серверный: attachments/7bb6c813-d438-4e05-bff5-076d254f1d65/9af53ef4-05d3-4842-923c-de3c10dc9068 +--- PASS: TestObjectKeyIsServerAssigned (0.11s) +PASS +ok gavrilenko-sxdees/lab4/student-tests 12.953s diff --git a/evidence/upload-memory/limit_4.stats b/evidence/upload-memory/limit_4.stats new file mode 100644 index 00000000..6f4f9155 --- /dev/null +++ b/evidence/upload-memory/limit_4.stats @@ -0,0 +1,446 @@ +gavrilenko-lab4-api-1 25.59MiB / 256MiB +gavrilenko-lab4-api-2 24.79MiB / 256MiB +gavrilenko-lab4-api-1 25.59MiB / 256MiB  +gavrilenko-lab4-api-2 24.79MiB / 256MiB  +  +gavrilenko-lab4-api-1 25.59MiB / 256MiB +gavrilenko-lab4-api-2 24.79MiB / 256MiB +gavrilenko-lab4-api-1 25.59MiB / 256MiB  +gavrilenko-lab4-api-2 24.79MiB / 256MiB  +  +gavrilenko-lab4-api-1 25.66MiB / 256MiB +gavrilenko-lab4-api-2 24.78MiB / 256MiB +gavrilenko-lab4-api-1 25.66MiB / 256MiB  +gavrilenko-lab4-api-2 24.78MiB / 256MiB  +  +gavrilenko-lab4-api-1 25.66MiB / 256MiB +gavrilenko-lab4-api-2 24.78MiB / 256MiB +gavrilenko-lab4-api-1 25.66MiB / 256MiB  +gavrilenko-lab4-api-2 24.78MiB / 256MiB  +  +gavrilenko-lab4-api-1 50.47MiB / 256MiB +gavrilenko-lab4-api-2 46.67MiB / 256MiB +gavrilenko-lab4-api-1 50.47MiB / 256MiB  +gavrilenko-lab4-api-2 46.67MiB / 256MiB  +  +gavrilenko-lab4-api-1 50.47MiB / 256MiB +gavrilenko-lab4-api-2 46.67MiB / 256MiB +gavrilenko-lab4-api-1 50.47MiB / 256MiB  +gavrilenko-lab4-api-2 46.67MiB / 256MiB  +  +gavrilenko-lab4-api-1 50.47MiB / 256MiB +gavrilenko-lab4-api-2 46.67MiB / 256MiB +gavrilenko-lab4-api-1 50.47MiB / 256MiB  +gavrilenko-lab4-api-2 46.67MiB / 256MiB  +  +gavrilenko-lab4-api-1 51.91MiB / 256MiB +gavrilenko-lab4-api-2 49.57MiB / 256MiB +gavrilenko-lab4-api-1 51.91MiB / 256MiB  +gavrilenko-lab4-api-2 49.57MiB / 256MiB  +  +gavrilenko-lab4-api-1 51.91MiB / 256MiB +gavrilenko-lab4-api-2 49.57MiB / 256MiB +gavrilenko-lab4-api-1 51.91MiB / 256MiB  +gavrilenko-lab4-api-2 49.57MiB / 256MiB  +  +gavrilenko-lab4-api-1 51.75MiB / 256MiB +gavrilenko-lab4-api-2 49.58MiB / 256MiB +gavrilenko-lab4-api-1 51.75MiB / 256MiB  +gavrilenko-lab4-api-2 49.58MiB / 256MiB  +  +gavrilenko-lab4-api-1 51.75MiB / 256MiB +gavrilenko-lab4-api-2 49.58MiB / 256MiB +gavrilenko-lab4-api-1 51.75MiB / 256MiB  +gavrilenko-lab4-api-2 49.58MiB / 256MiB  +  +gavrilenko-lab4-api-1 61.09MiB / 256MiB +gavrilenko-lab4-api-2 49.79MiB / 256MiB +gavrilenko-lab4-api-1 61.09MiB / 256MiB  +gavrilenko-lab4-api-2 49.79MiB / 256MiB  +  +gavrilenko-lab4-api-1 61.09MiB / 256MiB +gavrilenko-lab4-api-2 49.79MiB / 256MiB +gavrilenko-lab4-api-1 61.09MiB / 256MiB  +gavrilenko-lab4-api-2 49.79MiB / 256MiB  +  +gavrilenko-lab4-api-1 71.21MiB / 256MiB +gavrilenko-lab4-api-2 53.85MiB / 256MiB +gavrilenko-lab4-api-1 71.21MiB / 256MiB  +gavrilenko-lab4-api-2 53.85MiB / 256MiB  +  +gavrilenko-lab4-api-1 71.21MiB / 256MiB +gavrilenko-lab4-api-2 53.85MiB / 256MiB +gavrilenko-lab4-api-1 71.21MiB / 256MiB  +gavrilenko-lab4-api-2 53.85MiB / 256MiB  +  +gavrilenko-lab4-api-1 80.43MiB / 256MiB +gavrilenko-lab4-api-2 66.15MiB / 256MiB +gavrilenko-lab4-api-1 80.43MiB / 256MiB  +gavrilenko-lab4-api-2 66.15MiB / 256MiB  +  +gavrilenko-lab4-api-1 80.43MiB / 256MiB +gavrilenko-lab4-api-2 66.15MiB / 256MiB +gavrilenko-lab4-api-1 80.43MiB / 256MiB  +gavrilenko-lab4-api-2 66.15MiB / 256MiB  +  +gavrilenko-lab4-api-1 80.43MiB / 256MiB +gavrilenko-lab4-api-2 66.15MiB / 256MiB +gavrilenko-lab4-api-1 80.43MiB / 256MiB  +gavrilenko-lab4-api-2 66.15MiB / 256MiB  +  +gavrilenko-lab4-api-1 88.55MiB / 256MiB +gavrilenko-lab4-api-2 76.77MiB / 256MiB +gavrilenko-lab4-api-1 88.55MiB / 256MiB  +gavrilenko-lab4-api-2 76.77MiB / 256MiB  +  +gavrilenko-lab4-api-1 88.55MiB / 256MiB +gavrilenko-lab4-api-2 76.77MiB / 256MiB +gavrilenko-lab4-api-1 88.55MiB / 256MiB  +gavrilenko-lab4-api-2 76.77MiB / 256MiB  +  +gavrilenko-lab4-api-1 88.55MiB / 256MiB +gavrilenko-lab4-api-2 76.76MiB / 256MiB +gavrilenko-lab4-api-1 88.55MiB / 256MiB  +gavrilenko-lab4-api-2 76.76MiB / 256MiB  +  +gavrilenko-lab4-api-1 89.86MiB / 256MiB +gavrilenko-lab4-api-2 76.76MiB / 256MiB +gavrilenko-lab4-api-1 89.86MiB / 256MiB  +gavrilenko-lab4-api-2 76.76MiB / 256MiB  +  +gavrilenko-lab4-api-1 89.86MiB / 256MiB +gavrilenko-lab4-api-2 76.76MiB / 256MiB +gavrilenko-lab4-api-1 89.86MiB / 256MiB  +gavrilenko-lab4-api-2 76.76MiB / 256MiB  +  +gavrilenko-lab4-api-1 90.44MiB / 256MiB +gavrilenko-lab4-api-2 76.09MiB / 256MiB +gavrilenko-lab4-api-1 90.44MiB / 256MiB  +gavrilenko-lab4-api-2 76.09MiB / 256MiB  +  +gavrilenko-lab4-api-1 90.44MiB / 256MiB +gavrilenko-lab4-api-2 76.09MiB / 256MiB +gavrilenko-lab4-api-1 90.44MiB / 256MiB  +gavrilenko-lab4-api-2 76.09MiB / 256MiB  +  +gavrilenko-lab4-api-1 89.55MiB / 256MiB +gavrilenko-lab4-api-2 87.55MiB / 256MiB +gavrilenko-lab4-api-1 89.55MiB / 256MiB  +gavrilenko-lab4-api-2 87.55MiB / 256MiB  +  +gavrilenko-lab4-api-1 89.55MiB / 256MiB +gavrilenko-lab4-api-2 87.55MiB / 256MiB +gavrilenko-lab4-api-1 89.55MiB / 256MiB  +gavrilenko-lab4-api-2 87.55MiB / 256MiB  +  +gavrilenko-lab4-api-1 83.08MiB / 256MiB +gavrilenko-lab4-api-2 86.71MiB / 256MiB +gavrilenko-lab4-api-1 83.08MiB / 256MiB  +gavrilenko-lab4-api-2 86.71MiB / 256MiB  +  +gavrilenko-lab4-api-1 83.08MiB / 256MiB +gavrilenko-lab4-api-2 86.71MiB / 256MiB +gavrilenko-lab4-api-1 83.08MiB / 256MiB  +gavrilenko-lab4-api-2 86.71MiB / 256MiB  +  +gavrilenko-lab4-api-1 86.06MiB / 256MiB +gavrilenko-lab4-api-2 87.36MiB / 256MiB +gavrilenko-lab4-api-1 86.06MiB / 256MiB  +gavrilenko-lab4-api-2 87.36MiB / 256MiB  +  +gavrilenko-lab4-api-1 86.06MiB / 256MiB +gavrilenko-lab4-api-2 87.36MiB / 256MiB +gavrilenko-lab4-api-1 86.06MiB / 256MiB  +gavrilenko-lab4-api-2 87.36MiB / 256MiB  +  +gavrilenko-lab4-api-1 86.06MiB / 256MiB +gavrilenko-lab4-api-2 87.36MiB / 256MiB +gavrilenko-lab4-api-1 86.06MiB / 256MiB  +gavrilenko-lab4-api-2 87.36MiB / 256MiB  +  +gavrilenko-lab4-api-1 86.06MiB / 256MiB +gavrilenko-lab4-api-2 88.5MiB / 256MiB +gavrilenko-lab4-api-1 86.06MiB / 256MiB  +gavrilenko-lab4-api-2 88.5MiB / 256MiB  +  +gavrilenko-lab4-api-1 93.39MiB / 256MiB +gavrilenko-lab4-api-2 88.5MiB / 256MiB +gavrilenko-lab4-api-1 93.39MiB / 256MiB  +gavrilenko-lab4-api-2 88.5MiB / 256MiB  +  +gavrilenko-lab4-api-1 93.39MiB / 256MiB +gavrilenko-lab4-api-2 88.5MiB / 256MiB +gavrilenko-lab4-api-1 93.39MiB / 256MiB  +gavrilenko-lab4-api-2 88.5MiB / 256MiB  +  +gavrilenko-lab4-api-1 89.27MiB / 256MiB +gavrilenko-lab4-api-2 81.14MiB / 256MiB +gavrilenko-lab4-api-1 89.27MiB / 256MiB  +gavrilenko-lab4-api-2 81.14MiB / 256MiB  +  +gavrilenko-lab4-api-1 89.27MiB / 256MiB +gavrilenko-lab4-api-2 81.14MiB / 256MiB +gavrilenko-lab4-api-1 89.27MiB / 256MiB  +gavrilenko-lab4-api-2 81.14MiB / 256MiB  +  +gavrilenko-lab4-api-1 87.07MiB / 256MiB +gavrilenko-lab4-api-2 87.77MiB / 256MiB +gavrilenko-lab4-api-1 87.07MiB / 256MiB  +gavrilenko-lab4-api-2 87.77MiB / 256MiB  +  +gavrilenko-lab4-api-1 87.07MiB / 256MiB +gavrilenko-lab4-api-2 87.77MiB / 256MiB +gavrilenko-lab4-api-1 87.07MiB / 256MiB  +gavrilenko-lab4-api-2 87.77MiB / 256MiB  +  +gavrilenko-lab4-api-1 82.66MiB / 256MiB +gavrilenko-lab4-api-2 87.45MiB / 256MiB +gavrilenko-lab4-api-1 82.66MiB / 256MiB  +gavrilenko-lab4-api-2 87.45MiB / 256MiB  +  +gavrilenko-lab4-api-1 82.66MiB / 256MiB +gavrilenko-lab4-api-2 87.45MiB / 256MiB +gavrilenko-lab4-api-1 82.66MiB / 256MiB  +gavrilenko-lab4-api-2 87.45MiB / 256MiB  +  +gavrilenko-lab4-api-1 83.25MiB / 256MiB +gavrilenko-lab4-api-2 79.75MiB / 256MiB +gavrilenko-lab4-api-1 83.25MiB / 256MiB  +gavrilenko-lab4-api-2 79.75MiB / 256MiB  +  +gavrilenko-lab4-api-1 83.25MiB / 256MiB +gavrilenko-lab4-api-2 79.75MiB / 256MiB +gavrilenko-lab4-api-1 83.25MiB / 256MiB  +gavrilenko-lab4-api-2 79.75MiB / 256MiB  +  +gavrilenko-lab4-api-1 79.81MiB / 256MiB +gavrilenko-lab4-api-2 73.23MiB / 256MiB +gavrilenko-lab4-api-1 79.81MiB / 256MiB  +gavrilenko-lab4-api-2 73.23MiB / 256MiB  +  +gavrilenko-lab4-api-1 79.81MiB / 256MiB +gavrilenko-lab4-api-2 73.23MiB / 256MiB +gavrilenko-lab4-api-1 79.81MiB / 256MiB  +gavrilenko-lab4-api-2 73.23MiB / 256MiB  +  +gavrilenko-lab4-api-1 80.15MiB / 256MiB +gavrilenko-lab4-api-2 77.82MiB / 256MiB +gavrilenko-lab4-api-1 80.15MiB / 256MiB  +gavrilenko-lab4-api-2 77.82MiB / 256MiB  +  +gavrilenko-lab4-api-1 80.15MiB / 256MiB +gavrilenko-lab4-api-2 77.82MiB / 256MiB +gavrilenko-lab4-api-1 80.15MiB / 256MiB  +gavrilenko-lab4-api-2 77.82MiB / 256MiB  +  +gavrilenko-lab4-api-1 81.5MiB / 256MiB +gavrilenko-lab4-api-2 78.96MiB / 256MiB +gavrilenko-lab4-api-1 81.5MiB / 256MiB  +gavrilenko-lab4-api-2 78.96MiB / 256MiB  +  +gavrilenko-lab4-api-1 81.5MiB / 256MiB +gavrilenko-lab4-api-2 78.96MiB / 256MiB +gavrilenko-lab4-api-1 81.5MiB / 256MiB  +gavrilenko-lab4-api-2 78.96MiB / 256MiB  +  +gavrilenko-lab4-api-1 81.5MiB / 256MiB +gavrilenko-lab4-api-2 78.96MiB / 256MiB +gavrilenko-lab4-api-1 81.5MiB / 256MiB  +gavrilenko-lab4-api-2 78.96MiB / 256MiB  +  +gavrilenko-lab4-api-1 89.75MiB / 256MiB +gavrilenko-lab4-api-2 79.74MiB / 256MiB +gavrilenko-lab4-api-1 89.75MiB / 256MiB  +gavrilenko-lab4-api-2 79.74MiB / 256MiB  +  +gavrilenko-lab4-api-1 89.75MiB / 256MiB +gavrilenko-lab4-api-2 79.74MiB / 256MiB +gavrilenko-lab4-api-1 89.75MiB / 256MiB  +gavrilenko-lab4-api-2 79.74MiB / 256MiB  +  +gavrilenko-lab4-api-1 79.91MiB / 256MiB +gavrilenko-lab4-api-2 76.18MiB / 256MiB +gavrilenko-lab4-api-1 79.91MiB / 256MiB  +gavrilenko-lab4-api-2 76.18MiB / 256MiB  +  +gavrilenko-lab4-api-1 79.91MiB / 256MiB +gavrilenko-lab4-api-2 76.18MiB / 256MiB +gavrilenko-lab4-api-1 79.91MiB / 256MiB  +gavrilenko-lab4-api-2 76.18MiB / 256MiB  +  +gavrilenko-lab4-api-1 75.64MiB / 256MiB +gavrilenko-lab4-api-2 72.28MiB / 256MiB +gavrilenko-lab4-api-1 75.64MiB / 256MiB  +gavrilenko-lab4-api-2 72.28MiB / 256MiB  +  +gavrilenko-lab4-api-1 75.64MiB / 256MiB +gavrilenko-lab4-api-2 72.28MiB / 256MiB +gavrilenko-lab4-api-1 75.64MiB / 256MiB  +gavrilenko-lab4-api-2 72.28MiB / 256MiB  +  +gavrilenko-lab4-api-1 74.77MiB / 256MiB +gavrilenko-lab4-api-2 72.34MiB / 256MiB +gavrilenko-lab4-api-1 74.77MiB / 256MiB  +gavrilenko-lab4-api-2 72.34MiB / 256MiB  +  +gavrilenko-lab4-api-1 74.77MiB / 256MiB +gavrilenko-lab4-api-2 72.34MiB / 256MiB +gavrilenko-lab4-api-1 74.77MiB / 256MiB  +gavrilenko-lab4-api-2 72.34MiB / 256MiB  +  +gavrilenko-lab4-api-1 74.78MiB / 256MiB +gavrilenko-lab4-api-2 72.34MiB / 256MiB +gavrilenko-lab4-api-1 74.78MiB / 256MiB  +gavrilenko-lab4-api-2 72.34MiB / 256MiB  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  + \ No newline at end of file diff --git a/evidence/upload-memory/limit_64.stats b/evidence/upload-memory/limit_64.stats new file mode 100644 index 00000000..ebae7cc7 --- /dev/null +++ b/evidence/upload-memory/limit_64.stats @@ -0,0 +1,971 @@ +gavrilenko-lab4-api-1 23.96MiB / 256MiB +gavrilenko-lab4-api-2 25.01MiB / 256MiB +gavrilenko-lab4-api-1 23.96MiB / 256MiB  +gavrilenko-lab4-api-2 25.01MiB / 256MiB  +  +gavrilenko-lab4-api-1 23.96MiB / 256MiB +gavrilenko-lab4-api-2 25.01MiB / 256MiB +gavrilenko-lab4-api-1 23.96MiB / 256MiB  +gavrilenko-lab4-api-2 25.01MiB / 256MiB  +  +gavrilenko-lab4-api-1 23.98MiB / 256MiB +gavrilenko-lab4-api-2 25.02MiB / 256MiB +gavrilenko-lab4-api-1 23.98MiB / 256MiB  +gavrilenko-lab4-api-2 25.02MiB / 256MiB  +  +gavrilenko-lab4-api-1 23.98MiB / 256MiB +gavrilenko-lab4-api-2 25.02MiB / 256MiB +gavrilenko-lab4-api-1 23.98MiB / 256MiB  +gavrilenko-lab4-api-2 25.02MiB / 256MiB  +  +gavrilenko-lab4-api-1 50.04MiB / 256MiB +gavrilenko-lab4-api-2 50.81MiB / 256MiB +gavrilenko-lab4-api-1 50.04MiB / 256MiB  +gavrilenko-lab4-api-2 50.81MiB / 256MiB  +  +gavrilenko-lab4-api-1 50.04MiB / 256MiB +gavrilenko-lab4-api-2 50.81MiB / 256MiB +gavrilenko-lab4-api-1 50.04MiB / 256MiB  +gavrilenko-lab4-api-2 50.81MiB / 256MiB  +  +gavrilenko-lab4-api-1 50.04MiB / 256MiB +gavrilenko-lab4-api-2 88.16MiB / 256MiB +gavrilenko-lab4-api-1 50.04MiB / 256MiB  +gavrilenko-lab4-api-2 88.16MiB / 256MiB  +  +gavrilenko-lab4-api-1 86.7MiB / 256MiB +gavrilenko-lab4-api-2 88.16MiB / 256MiB +gavrilenko-lab4-api-1 86.7MiB / 256MiB  +gavrilenko-lab4-api-2 88.16MiB / 256MiB  +  +gavrilenko-lab4-api-1 86.7MiB / 256MiB +gavrilenko-lab4-api-2 88.16MiB / 256MiB +gavrilenko-lab4-api-1 86.7MiB / 256MiB  +gavrilenko-lab4-api-2 88.16MiB / 256MiB  +  +gavrilenko-lab4-api-1 86.69MiB / 256MiB +gavrilenko-lab4-api-2 86.83MiB / 256MiB +gavrilenko-lab4-api-1 86.69MiB / 256MiB  +gavrilenko-lab4-api-2 86.83MiB / 256MiB  +  +gavrilenko-lab4-api-1 86.69MiB / 256MiB +gavrilenko-lab4-api-2 86.83MiB / 256MiB +gavrilenko-lab4-api-1 86.69MiB / 256MiB  +gavrilenko-lab4-api-2 86.83MiB / 256MiB  +  +gavrilenko-lab4-api-1 86.68MiB / 256MiB +gavrilenko-lab4-api-2 86.84MiB / 256MiB +gavrilenko-lab4-api-1 86.68MiB / 256MiB  +gavrilenko-lab4-api-2 86.84MiB / 256MiB  +  +gavrilenko-lab4-api-1 86.68MiB / 256MiB +gavrilenko-lab4-api-2 86.84MiB / 256MiB +gavrilenko-lab4-api-1 86.68MiB / 256MiB  +gavrilenko-lab4-api-2 86.84MiB / 256MiB  +  +gavrilenko-lab4-api-1 86.99MiB / 256MiB +gavrilenko-lab4-api-2 86.92MiB / 256MiB +gavrilenko-lab4-api-1 86.99MiB / 256MiB  +gavrilenko-lab4-api-2 86.92MiB / 256MiB  +  +gavrilenko-lab4-api-1 86.99MiB / 256MiB +gavrilenko-lab4-api-2 86.92MiB / 256MiB +gavrilenko-lab4-api-1 86.99MiB / 256MiB  +gavrilenko-lab4-api-2 86.92MiB / 256MiB  +  +gavrilenko-lab4-api-1 102.9MiB / 256MiB +gavrilenko-lab4-api-2 94.54MiB / 256MiB +gavrilenko-lab4-api-1 102.9MiB / 256MiB  +gavrilenko-lab4-api-2 94.54MiB / 256MiB  +  +gavrilenko-lab4-api-1 102.9MiB / 256MiB +gavrilenko-lab4-api-2 94.54MiB / 256MiB +gavrilenko-lab4-api-1 102.9MiB / 256MiB  +gavrilenko-lab4-api-2 94.54MiB / 256MiB  +  +gavrilenko-lab4-api-1 102.9MiB / 256MiB +gavrilenko-lab4-api-2 94.54MiB / 256MiB +gavrilenko-lab4-api-1 102.9MiB / 256MiB  +gavrilenko-lab4-api-2 94.54MiB / 256MiB  +  +gavrilenko-lab4-api-1 113.9MiB / 256MiB +gavrilenko-lab4-api-2 106.1MiB / 256MiB +gavrilenko-lab4-api-1 113.9MiB / 256MiB  +gavrilenko-lab4-api-2 106.1MiB / 256MiB  +  +gavrilenko-lab4-api-1 113.9MiB / 256MiB +gavrilenko-lab4-api-2 106.1MiB / 256MiB +gavrilenko-lab4-api-1 113.9MiB / 256MiB  +gavrilenko-lab4-api-2 106.1MiB / 256MiB  +  +gavrilenko-lab4-api-1 113.9MiB / 256MiB +gavrilenko-lab4-api-2 106.1MiB / 256MiB +gavrilenko-lab4-api-1 113.9MiB / 256MiB  +gavrilenko-lab4-api-2 106.1MiB / 256MiB  +  +gavrilenko-lab4-api-1 119.4MiB / 256MiB +gavrilenko-lab4-api-2 110.3MiB / 256MiB +gavrilenko-lab4-api-1 119.4MiB / 256MiB  +gavrilenko-lab4-api-2 110.3MiB / 256MiB  +  +gavrilenko-lab4-api-1 119.4MiB / 256MiB +gavrilenko-lab4-api-2 110.3MiB / 256MiB +gavrilenko-lab4-api-1 119.4MiB / 256MiB  +gavrilenko-lab4-api-2 110.3MiB / 256MiB  +  +gavrilenko-lab4-api-1 112.1MiB / 256MiB +gavrilenko-lab4-api-2 110.2MiB / 256MiB +gavrilenko-lab4-api-1 112.1MiB / 256MiB  +gavrilenko-lab4-api-2 110.2MiB / 256MiB  +  +gavrilenko-lab4-api-1 112.1MiB / 256MiB +gavrilenko-lab4-api-2 110.2MiB / 256MiB +gavrilenko-lab4-api-1 112.1MiB / 256MiB  +gavrilenko-lab4-api-2 110.2MiB / 256MiB  +  +gavrilenko-lab4-api-1 138.5MiB / 256MiB +gavrilenko-lab4-api-2 146.3MiB / 256MiB +gavrilenko-lab4-api-1 138.5MiB / 256MiB  +gavrilenko-lab4-api-2 146.3MiB / 256MiB  +  +gavrilenko-lab4-api-1 138.5MiB / 256MiB +gavrilenko-lab4-api-2 146.3MiB / 256MiB +gavrilenko-lab4-api-1 138.5MiB / 256MiB  +gavrilenko-lab4-api-2 146.3MiB / 256MiB  +  +gavrilenko-lab4-api-1 153.5MiB / 256MiB +gavrilenko-lab4-api-2 159.3MiB / 256MiB +gavrilenko-lab4-api-1 153.5MiB / 256MiB  +gavrilenko-lab4-api-2 159.3MiB / 256MiB  +  +gavrilenko-lab4-api-1 153.5MiB / 256MiB +gavrilenko-lab4-api-2 159.3MiB / 256MiB +gavrilenko-lab4-api-1 153.5MiB / 256MiB  +gavrilenko-lab4-api-2 159.3MiB / 256MiB  +  +gavrilenko-lab4-api-1 153.3MiB / 256MiB +gavrilenko-lab4-api-2 161.3MiB / 256MiB +gavrilenko-lab4-api-1 153.3MiB / 256MiB  +gavrilenko-lab4-api-2 161.3MiB / 256MiB  +  +gavrilenko-lab4-api-1 153.3MiB / 256MiB +gavrilenko-lab4-api-2 161.3MiB / 256MiB +gavrilenko-lab4-api-1 153.3MiB / 256MiB  +gavrilenko-lab4-api-2 161.3MiB / 256MiB  +  +gavrilenko-lab4-api-1 153.7MiB / 256MiB +gavrilenko-lab4-api-2 161.3MiB / 256MiB +gavrilenko-lab4-api-1 153.7MiB / 256MiB  +gavrilenko-lab4-api-2 161.3MiB / 256MiB  +  +gavrilenko-lab4-api-1 153.7MiB / 256MiB +gavrilenko-lab4-api-2 161.3MiB / 256MiB +gavrilenko-lab4-api-1 153.7MiB / 256MiB  +gavrilenko-lab4-api-2 161.3MiB / 256MiB  +  +gavrilenko-lab4-api-1 153.7MiB / 256MiB +gavrilenko-lab4-api-2 161.3MiB / 256MiB +gavrilenko-lab4-api-1 153.7MiB / 256MiB  +gavrilenko-lab4-api-2 161.3MiB / 256MiB  +  +gavrilenko-lab4-api-1 155.9MiB / 256MiB +gavrilenko-lab4-api-2 161.7MiB / 256MiB +gavrilenko-lab4-api-1 155.9MiB / 256MiB  +gavrilenko-lab4-api-2 161.7MiB / 256MiB  +  +gavrilenko-lab4-api-1 155.9MiB / 256MiB +gavrilenko-lab4-api-2 161.7MiB / 256MiB +gavrilenko-lab4-api-1 155.9MiB / 256MiB  +gavrilenko-lab4-api-2 161.7MiB / 256MiB  +  +gavrilenko-lab4-api-1 153.3MiB / 256MiB +gavrilenko-lab4-api-2 161.1MiB / 256MiB +gavrilenko-lab4-api-1 153.3MiB / 256MiB  +gavrilenko-lab4-api-2 161.1MiB / 256MiB  +  +gavrilenko-lab4-api-1 153.3MiB / 256MiB +gavrilenko-lab4-api-2 161.1MiB / 256MiB +gavrilenko-lab4-api-1 153.3MiB / 256MiB  +gavrilenko-lab4-api-2 161.1MiB / 256MiB  +  +gavrilenko-lab4-api-1 156.7MiB / 256MiB +gavrilenko-lab4-api-2 167.6MiB / 256MiB +gavrilenko-lab4-api-1 156.7MiB / 256MiB  +gavrilenko-lab4-api-2 167.6MiB / 256MiB  +  +gavrilenko-lab4-api-1 156.7MiB / 256MiB +gavrilenko-lab4-api-2 167.6MiB / 256MiB +gavrilenko-lab4-api-1 156.7MiB / 256MiB  +gavrilenko-lab4-api-2 167.6MiB / 256MiB  +  +gavrilenko-lab4-api-1 156.7MiB / 256MiB +gavrilenko-lab4-api-2 167.8MiB / 256MiB +gavrilenko-lab4-api-1 156.7MiB / 256MiB  +gavrilenko-lab4-api-2 167.8MiB / 256MiB  +  +gavrilenko-lab4-api-1 160.9MiB / 256MiB +gavrilenko-lab4-api-2 167.8MiB / 256MiB +gavrilenko-lab4-api-1 160.9MiB / 256MiB  +gavrilenko-lab4-api-2 167.8MiB / 256MiB  +  +gavrilenko-lab4-api-1 160.9MiB / 256MiB +gavrilenko-lab4-api-2 167.8MiB / 256MiB +gavrilenko-lab4-api-1 160.9MiB / 256MiB  +gavrilenko-lab4-api-2 167.8MiB / 256MiB  +  +gavrilenko-lab4-api-1 159.9MiB / 256MiB +gavrilenko-lab4-api-2 167.5MiB / 256MiB +gavrilenko-lab4-api-1 159.9MiB / 256MiB  +gavrilenko-lab4-api-2 167.5MiB / 256MiB  +  +gavrilenko-lab4-api-1 159.9MiB / 256MiB +gavrilenko-lab4-api-2 167.5MiB / 256MiB +gavrilenko-lab4-api-1 159.9MiB / 256MiB  +gavrilenko-lab4-api-2 167.5MiB / 256MiB  +  +gavrilenko-lab4-api-1 157.1MiB / 256MiB +gavrilenko-lab4-api-2 167MiB / 256MiB +gavrilenko-lab4-api-1 157.1MiB / 256MiB  +gavrilenko-lab4-api-2 167MiB / 256MiB  +  +gavrilenko-lab4-api-1 157.1MiB / 256MiB +gavrilenko-lab4-api-2 167MiB / 256MiB +gavrilenko-lab4-api-1 157.1MiB / 256MiB  +gavrilenko-lab4-api-2 167MiB / 256MiB  +  +gavrilenko-lab4-api-1 157.8MiB / 256MiB +gavrilenko-lab4-api-2 168.3MiB / 256MiB +gavrilenko-lab4-api-1 157.8MiB / 256MiB  +gavrilenko-lab4-api-2 168.3MiB / 256MiB  +  +gavrilenko-lab4-api-1 157.8MiB / 256MiB +gavrilenko-lab4-api-2 168.3MiB / 256MiB +gavrilenko-lab4-api-1 157.8MiB / 256MiB  +gavrilenko-lab4-api-2 168.3MiB / 256MiB  +  +gavrilenko-lab4-api-1 157.8MiB / 256MiB +gavrilenko-lab4-api-2 168.3MiB / 256MiB +gavrilenko-lab4-api-1 157.8MiB / 256MiB  +gavrilenko-lab4-api-2 168.3MiB / 256MiB  +  +gavrilenko-lab4-api-1 160.9MiB / 256MiB +gavrilenko-lab4-api-2 169.4MiB / 256MiB +gavrilenko-lab4-api-1 160.9MiB / 256MiB  +gavrilenko-lab4-api-2 169.4MiB / 256MiB  +  +gavrilenko-lab4-api-1 160.9MiB / 256MiB +gavrilenko-lab4-api-2 169.4MiB / 256MiB +gavrilenko-lab4-api-1 160.9MiB / 256MiB  +gavrilenko-lab4-api-2 169.4MiB / 256MiB  +  +gavrilenko-lab4-api-1 162.6MiB / 256MiB +gavrilenko-lab4-api-2 168.5MiB / 256MiB +gavrilenko-lab4-api-1 162.6MiB / 256MiB  +gavrilenko-lab4-api-2 168.5MiB / 256MiB  +  +gavrilenko-lab4-api-1 162.6MiB / 256MiB +gavrilenko-lab4-api-2 168.5MiB / 256MiB +gavrilenko-lab4-api-1 162.6MiB / 256MiB  +gavrilenko-lab4-api-2 168.5MiB / 256MiB  +  +gavrilenko-lab4-api-1 160.9MiB / 256MiB +gavrilenko-lab4-api-2 168.5MiB / 256MiB +gavrilenko-lab4-api-1 160.9MiB / 256MiB  +gavrilenko-lab4-api-2 168.5MiB / 256MiB  +  +gavrilenko-lab4-api-1 160.9MiB / 256MiB +gavrilenko-lab4-api-2 168.5MiB / 256MiB +gavrilenko-lab4-api-1 160.9MiB / 256MiB  +gavrilenko-lab4-api-2 168.5MiB / 256MiB  +  +gavrilenko-lab4-api-1 160.9MiB / 256MiB +gavrilenko-lab4-api-2 169.2MiB / 256MiB +gavrilenko-lab4-api-1 160.9MiB / 256MiB  +gavrilenko-lab4-api-2 169.2MiB / 256MiB  +  +gavrilenko-lab4-api-1 162.6MiB / 256MiB +gavrilenko-lab4-api-2 169.2MiB / 256MiB +gavrilenko-lab4-api-1 162.6MiB / 256MiB  +gavrilenko-lab4-api-2 169.2MiB / 256MiB  +  +gavrilenko-lab4-api-1 162.6MiB / 256MiB +gavrilenko-lab4-api-2 169.2MiB / 256MiB +gavrilenko-lab4-api-1 162.6MiB / 256MiB  +gavrilenko-lab4-api-2 169.2MiB / 256MiB  +  +gavrilenko-lab4-api-1 160.9MiB / 256MiB +gavrilenko-lab4-api-2 170.3MiB / 256MiB +gavrilenko-lab4-api-1 160.9MiB / 256MiB  +gavrilenko-lab4-api-2 170.3MiB / 256MiB  +  +gavrilenko-lab4-api-1 160.9MiB / 256MiB +gavrilenko-lab4-api-2 170.3MiB / 256MiB +gavrilenko-lab4-api-1 160.9MiB / 256MiB  +gavrilenko-lab4-api-2 170.3MiB / 256MiB  +  +gavrilenko-lab4-api-1 161.4MiB / 256MiB +gavrilenko-lab4-api-2 168.5MiB / 256MiB +gavrilenko-lab4-api-1 161.4MiB / 256MiB  +gavrilenko-lab4-api-2 168.5MiB / 256MiB  +  +gavrilenko-lab4-api-1 161.4MiB / 256MiB +gavrilenko-lab4-api-2 168.5MiB / 256MiB +gavrilenko-lab4-api-1 161.4MiB / 256MiB  +gavrilenko-lab4-api-2 168.5MiB / 256MiB  +  +gavrilenko-lab4-api-1 165.2MiB / 256MiB +gavrilenko-lab4-api-2 173.8MiB / 256MiB +gavrilenko-lab4-api-1 165.2MiB / 256MiB  +gavrilenko-lab4-api-2 173.8MiB / 256MiB  +  +gavrilenko-lab4-api-1 165.2MiB / 256MiB +gavrilenko-lab4-api-2 173.8MiB / 256MiB +gavrilenko-lab4-api-1 165.2MiB / 256MiB  +gavrilenko-lab4-api-2 173.8MiB / 256MiB  +  +gavrilenko-lab4-api-1 166.1MiB / 256MiB +gavrilenko-lab4-api-2 176.3MiB / 256MiB +gavrilenko-lab4-api-1 166.1MiB / 256MiB  +gavrilenko-lab4-api-2 176.3MiB / 256MiB  +  +gavrilenko-lab4-api-1 166.1MiB / 256MiB +gavrilenko-lab4-api-2 176.3MiB / 256MiB +gavrilenko-lab4-api-1 166.1MiB / 256MiB  +gavrilenko-lab4-api-2 176.3MiB / 256MiB  +  +gavrilenko-lab4-api-1 161.1MiB / 256MiB +gavrilenko-lab4-api-2 168.5MiB / 256MiB +gavrilenko-lab4-api-1 161.1MiB / 256MiB  +gavrilenko-lab4-api-2 168.5MiB / 256MiB  +  +gavrilenko-lab4-api-1 161.1MiB / 256MiB +gavrilenko-lab4-api-2 168.5MiB / 256MiB +gavrilenko-lab4-api-1 161.1MiB / 256MiB  +gavrilenko-lab4-api-2 168.5MiB / 256MiB  +  +gavrilenko-lab4-api-1 161.1MiB / 256MiB +gavrilenko-lab4-api-2 168.5MiB / 256MiB +gavrilenko-lab4-api-1 161.1MiB / 256MiB  +gavrilenko-lab4-api-2 168.5MiB / 256MiB  +  +gavrilenko-lab4-api-1 161.1MiB / 256MiB +gavrilenko-lab4-api-2 168.5MiB / 256MiB +gavrilenko-lab4-api-1 161.1MiB / 256MiB  +gavrilenko-lab4-api-2 168.5MiB / 256MiB  +  +gavrilenko-lab4-api-1 161.1MiB / 256MiB +gavrilenko-lab4-api-2 168.5MiB / 256MiB +gavrilenko-lab4-api-1 161.1MiB / 256MiB  +gavrilenko-lab4-api-2 168.5MiB / 256MiB  +  +gavrilenko-lab4-api-1 161.1MiB / 256MiB +gavrilenko-lab4-api-2 168.5MiB / 256MiB +gavrilenko-lab4-api-1 161.1MiB / 256MiB  +gavrilenko-lab4-api-2 168.5MiB / 256MiB  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  +gavrilenko-lab4-api-1 -- / -- +gavrilenko-lab4-api-2 -- / -- +gavrilenko-lab4-api-1 -- / --  +gavrilenko-lab4-api-2 -- / --  +  + \ No newline at end of file diff --git a/evidence/upload-memory/summary.txt b/evidence/upload-memory/summary.txt new file mode 100644 index 00000000..0efe67d0 --- /dev/null +++ b/evidence/upload-memory/summary.txt @@ -0,0 +1,14 @@ +# Эксперимент пика памяти при одновременных загрузках +# дата: 2026-12-01T18:59:25Z, реплик API: 2, commit: ec540a1 +--- UPLOAD_MAX_CONCURRENCY=64 (параллельных клиентов=20, повторов=4, файл=7684003 байт, длительность=32s) +статусы HTTP: 80 201 +время ответа: min=3.11s p50=7.60s max=11.20s +пик памяти реплик, MiB (лимит контейнера 256M): + gavrilenko-lab4-api-1: idle=24.0 peak=166.1 + gavrilenko-lab4-api-2: idle=25.0 peak=176.3 +--- UPLOAD_MAX_CONCURRENCY=4 (параллельных клиентов=20, повторов=4, файл=7684003 байт, длительность=25s) +статусы HTTP: 80 201 +время ответа: min=3.00s p50=5.68s max=9.74s +пик памяти реплик, MiB (лимит контейнера 256M): + gavrilenko-lab4-api-1: idle=25.6 peak=93.4 + gavrilenko-lab4-api-2: idle=24.8 peak=88.5 diff --git a/go.mod b/go.mod new file mode 100644 index 00000000..e42eeaa2 --- /dev/null +++ b/go.mod @@ -0,0 +1,33 @@ +module gavrilenko-sxdees/lab4 + +go 1.23.0 + +require ( + github.com/aws/aws-sdk-go-v2 v1.36.3 + github.com/aws/aws-sdk-go-v2/credentials v1.17.62 + github.com/aws/aws-sdk-go-v2/service/s3 v1.78.2 + github.com/aws/smithy-go v1.22.2 + github.com/google/uuid v1.6.0 + github.com/jackc/pgx/v5 v5.7.4 + github.com/redis/go-redis/v9 v9.7.3 + golang.org/x/crypto v0.36.0 +) + +require ( + github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.6.10 // indirect + github.com/aws/aws-sdk-go-v2/internal/configsources v1.3.34 // indirect + github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.6.34 // indirect + github.com/aws/aws-sdk-go-v2/internal/v4a v1.3.34 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.12.3 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.7.0 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.12.15 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.18.15 // indirect + github.com/cespare/xxhash/v2 v2.2.0 // indirect + github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect + github.com/jackc/pgpassfile v1.0.0 // indirect + github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect + github.com/jackc/puddle/v2 v2.2.2 // indirect + golang.org/x/sync v0.12.0 // indirect + golang.org/x/sys v0.31.0 // indirect + golang.org/x/text v0.23.0 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 00000000..99cec08c --- /dev/null +++ b/go.sum @@ -0,0 +1,66 @@ +github.com/aws/aws-sdk-go-v2 v1.36.3 h1:mJoei2CxPutQVxaATCzDUjcZEjVRdpsiiXi2o38yqWM= +github.com/aws/aws-sdk-go-v2 v1.36.3/go.mod h1:LLXuLpgzEbD766Z5ECcRmi8AzSwfZItDtmABVkRLGzg= +github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.6.10 h1:zAybnyUQXIZ5mok5Jqwlf58/TFE7uvd3IAsa1aF9cXs= +github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.6.10/go.mod h1:qqvMj6gHLR/EXWZw4ZbqlPbQUyenf4h82UQUlKc+l14= +github.com/aws/aws-sdk-go-v2/credentials v1.17.62 h1:fvtQY3zFzYJ9CfixuAQ96IxDrBajbBWGqjNTCa79ocU= +github.com/aws/aws-sdk-go-v2/credentials v1.17.62/go.mod h1:ElETBxIQqcxej++Cs8GyPBbgMys5DgQPTwo7cUPDKt8= +github.com/aws/aws-sdk-go-v2/internal/configsources v1.3.34 h1:ZK5jHhnrioRkUNOc+hOgQKlUL5JeC3S6JgLxtQ+Rm0Q= +github.com/aws/aws-sdk-go-v2/internal/configsources v1.3.34/go.mod h1:p4VfIceZokChbA9FzMbRGz5OV+lekcVtHlPKEO0gSZY= +github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.6.34 h1:SZwFm17ZUNNg5Np0ioo/gq8Mn6u9w19Mri8DnJ15Jf0= +github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.6.34/go.mod h1:dFZsC0BLo346mvKQLWmoJxT+Sjp+qcVR1tRVHQGOH9Q= +github.com/aws/aws-sdk-go-v2/internal/v4a v1.3.34 h1:ZNTqv4nIdE/DiBfUUfXcLZ/Spcuz+RjeziUtNJackkM= +github.com/aws/aws-sdk-go-v2/internal/v4a v1.3.34/go.mod h1:zf7Vcd1ViW7cPqYWEHLHJkS50X0JS2IKz9Cgaj6ugrs= +github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.12.3 h1:eAh2A4b5IzM/lum78bZ590jy36+d/aFLgKF/4Vd1xPE= +github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.12.3/go.mod h1:0yKJC/kb8sAnmlYa6Zs3QVYqaC8ug2AbnNChv5Ox3uA= +github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.7.0 h1:lguz0bmOoGzozP9XfRJR1QIayEYo+2vP/No3OfLF0pU= +github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.7.0/go.mod h1:iu6FSzgt+M2/x3Dk8zhycdIcHjEFb36IS8HVUVFoMg0= +github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.12.15 h1:dM9/92u2F1JbDaGooxTq18wmmFzbJRfXfVfy96/1CXM= +github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.12.15/go.mod h1:SwFBy2vjtA0vZbjjaFtfN045boopadnoVPhu4Fv66vY= +github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.18.15 h1:moLQUoVq91LiqT1nbvzDukyqAlCv89ZmwaHw/ZFlFZg= +github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.18.15/go.mod h1:ZH34PJUc8ApjBIfgQCFvkWcUDBtl/WTD+uiYHjd8igA= +github.com/aws/aws-sdk-go-v2/service/s3 v1.78.2 h1:jIiopHEV22b4yQP2q36Y0OmwLbsxNWdWwfZRR5QRRO4= +github.com/aws/aws-sdk-go-v2/service/s3 v1.78.2/go.mod h1:U5SNqwhXB3Xe6F47kXvWihPl/ilGaEDe8HD/50Z9wxc= +github.com/aws/smithy-go v1.22.2 h1:6D9hW43xKFrRx/tXXfAlIZc4JI+yQe6snnWcQyxSyLQ= +github.com/aws/smithy-go v1.22.2/go.mod h1:irrKGvNn1InZwb2d7fkIRNucdfwR8R+Ts3wxYa/cJHg= +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/cespare/xxhash/v2 v2.2.0 h1:DC2CZ1Ep5Y4k3ZQ899DldepgrayRUGE6BBZ/cd9Cj44= +github.com/cespare/xxhash/v2 v2.2.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78= +github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= +github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg= +github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo= +github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM= +github.com/jackc/pgx/v5 v5.7.4 h1:9wKznZrhWa2QiHL+NjTSPP6yjl3451BX3imWDnokYlg= +github.com/jackc/pgx/v5 v5.7.4/go.mod h1:ncY89UGWxg82EykZUwSpUKEfccBGGYq1xjrOpsbsfGQ= +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/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/redis/go-redis/v9 v9.7.3 h1:YpPyAayJV+XErNsatSElgRZZVCwXX9QzkKYNvO7x0wM= +github.com/redis/go-redis/v9 v9.7.3/go.mod h1:bGUrSggJ9X9GUmZpZNEOQKaANxSGgOEBRltRTZHSvrA= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk= +github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= +golang.org/x/crypto v0.36.0 h1:AnAEvhDddvBdpY+uR+MyHmuZzzNqXSe/GvuDeob5L34= +golang.org/x/crypto v0.36.0/go.mod h1:Y4J0ReaxCR1IMaabaSMugxJES1EpwhBHhv2bDHklZvc= +golang.org/x/sync v0.12.0 h1:MHc5BpPuC30uJk597Ri8TV3CNZcTLu6B6z4lJy+g6Jw= +golang.org/x/sync v0.12.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA= +golang.org/x/sys v0.31.0 h1:ioabZlmFYtWhL+TRYpcnNlLwhyxaM9kWTDEmfnprqik= +golang.org/x/sys v0.31.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= +golang.org/x/text v0.23.0 h1:D71I7dUrlY+VX0gQShAThNGHFxZ13dGLBHQLVl1mJlY= +golang.org/x/text v0.23.0/go.mod h1:/BLNzu4aZCJ1+kcD0DNRotWKage4q2rGVAg4o22unh4= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/infra/haproxy/haproxy.cfg b/infra/haproxy/haproxy.cfg new file mode 100644 index 00000000..4782bd3e --- /dev/null +++ b/infra/haproxy/haproxy.cfg @@ -0,0 +1,52 @@ +# HAProxy — единственная публичная точка входа lab3. +# +# Backend-адреса берутся из Docker DNS имени сервиса `api` (A-записи всех реплик). +# server-template + resolvers перечитывает DNS; option httpchk снимает реплику, +# у которой /health/ready != 200 (в т.ч. после BeginDrain на SIGTERM). +# +# Оценка обнаружения отказа: +# inter 1s * fall 2 = ~2s по healthcheck + hold valid 2s у DNS ≈ до ~4s. +# Краткие 502/503 в это окно допустимы контрактом failover-теста. + +global + log stdout format raw local0 + maxconn 512 + +defaults + log global + mode http + option httplog + option dontlognull + timeout connect 2s + timeout client 15s + timeout server 15s + timeout check 1s + timeout http-keep-alive 10s + retries 2 + +resolvers docker + nameserver dns 127.0.0.11:53 + resolve_retries 3 + timeout resolve 1s + timeout retry 1s + hold valid 2s + hold other 2s + hold refused 2s + hold nx 2s + hold timeout 2s + hold obsolete 2s + +frontend fe_http + bind *:8080 + default_backend be_api + +backend be_api + balance roundrobin + option httpchk + option redispatch + retry-on conn-failure empty-response response-timeout + http-check send meth GET uri /health/ready + http-check expect status 200 + # До 8 слотов под --scale api=N. init-addr last,libc,none ждёт DNS при старте. + # fall 3: чуть терпимее к краткому DNS-мерцанию при docker stop одной реплики. + server-template api 8 api:8080 check inter 1s fall 3 rise 1 resolvers docker resolve-prefer ipv4 init-addr last,libc,none diff --git a/internal/api/attachments.go b/internal/api/attachments.go new file mode 100644 index 00000000..b7bbfac5 --- /dev/null +++ b/internal/api/attachments.go @@ -0,0 +1,391 @@ +package api + +// HTTP-слой вложений lab4. +// +// Модель согласованности двух хранилищ (S3 + PostgreSQL), т.к. общей транзакции у них нет: +// +// 1. проверяем всё, что можно, ДО записи (доступ, имя, тип, размер, содержимое); +// 2. PUT оригинала в S3 по ключу attachments/{chat}/{id}; +// 3. INSERT метаданных в PostgreSQL; +// 4. только после этого — 201 ready. +// +// Что если процесс/сеть упали между 2 и 3, или INSERT вернул ошибку? +// - Остаётся лишний ОБЪЕКТ без строки (orphan). Строки без файла не бывает — +// ради этого PUT делается ПЕРВЫМ. Пользователь не увидит «битое» вложение, +// а лишний объект безвреден: на него никто не ссылается. +// - При ошибке INSERT мы сразу пытаемся удалить объект (компенсация, compensateOrphan). +// - Если и удаление не удалось (процесс убит, S3 моргнул) — объект подберёт reconciler +// (`/server -reconcile`): он удаляет объекты без строки старше S3_ORPHAN_GRACE_SECONDS. +// Grace нужен, чтобы не снести объект, у которого INSERT ещё «в полёте». +// - Обрыв соединения клиентом во время передачи тела: до PUT мы ничего не пишем, +// а PUT/INSERT привязаны к контексту запроса и отменяются. + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/hex" + "errors" + "io" + "log" + "mime" + "net/http" + "strconv" + "strings" + "time" + "unicode" + "unicode/utf8" + + "github.com/google/uuid" + + "gavrilenko-sxdees/lab4/internal/objectstore" + "gavrilenko-sxdees/lab4/internal/store" +) + +const ( + // drainLimit — сколько байт «лишнего» тела дочитываем при раннем отказе (413/415/400). + // Если сервер ответил и закрыл соединение, пока клиент ещё пишет, клиент получит + // RST вместо читаемого 413. Дочитывание ограничено, чтобы это не стало каналом + // для бесплатной траты трафика. + drainLimit = 16 << 20 + // slotWait — сколько загрузка ждёт свободный слот буферизации, прежде чем получить 429. + // Меньше таймаутов HAProxy (15 с), чтобы клиент получил осмысленный ответ. + slotWait = 8 * time.Second +) + +// WithUploadConcurrency задаёт, сколько загрузок реплика обрабатывает одновременно. +// +// Зачем: тело загрузки целиком буферизуется в RAM (оно нужно для проверки содержимого и +// SHA-256 ДО записи в S3, иначе мусор попадал бы в bucket). Без ограничения N клиентов +// заняли бы N*10 MiB. Со слотами пик ≈ n*10 MiB (+ декод маленьких картинок), +// остальные загрузки ждут в очереди, не читая тело. +func (s *Server) WithUploadConcurrency(n int) *Server { + if n < 1 { + n = 1 + } + s.uploadSlots = make(chan struct{}, n) + return s +} + +// handleUploadAttachment — POST /api/v1/chats/{chat_id}/attachments?filename=... +func (s *Server) handleUploadAttachment(w http.ResponseWriter, r *http.Request) { + chatID, err := uuid.Parse(r.PathValue("chat_id")) + if err != nil { + s.rejectUpload(w, r, http.StatusBadRequest, "invalid_request", "invalid chat id") + return + } + uid := userFrom(r) + + // 1. Сначала доступ к ресурсу (контракт: аутентификация → доступ → остальное). + // Посторонний получает 404 до того, как мы потратим на него RAM и трафик. + if err := s.Store.IsChatMember(r.Context(), chatID, uid); err != nil { + if errors.Is(err, store.ErrNotFound) { + s.rejectUpload(w, r, http.StatusNotFound, "not_found", "object not found") + return + } + s.writeStoreErr(w, r, err, 0, "", "") + return + } + + // 2. filename — только для отображения. Опасные символы отклоняем сразу (400): + // даже зная, что в путь/ключ он не попадает, не храним то, что опасно показывать. + filename, ok := validFilename(r.URL.Query().Get("filename")) + if !ok { + s.rejectUpload(w, r, http.StatusBadRequest, "invalid_request", "invalid filename") + return + } + + // 3. Заголовок Content-Type должен быть image/png или image/jpeg. Это лишь заявка + // клиента: настоящий тип определяется по содержимому (шаг 6) и должен с ней совпасть. + declared, _, err := mime.ParseMediaType(r.Header.Get("Content-Type")) + if err != nil || (declared != "image/png" && declared != "image/jpeg") { + s.rejectUpload(w, r, http.StatusUnsupportedMediaType, "unsupported_media_type", "content type must be image/png or image/jpeg") + return + } + + // 4. Лимит размера до чтения тела: честный Content-Length > 10 MiB отвергаем сразу. + if r.ContentLength > maxUploadBytes { + s.rejectUpload(w, r, http.StatusRequestEntityTooLarge, "payload_too_large", "file is too large") + return + } + + // 5. Слот буферизации. Ждём не дольше slotWait, иначе 429 (контракт его допускает). + release, ok := s.acquireUploadSlot(r.Context()) + if !ok { + if r.Context().Err() != nil { + return // клиент ушёл + } + w.Header().Set("Retry-After", "1") + s.rejectUpload(w, r, http.StatusTooManyRequests, "rate_limited", "too many concurrent uploads") + return + } + defer release() + + // 6. Ограниченное чтение тела. MaxBytesReader гарантирует, что и при chunked-запросе + // без Content-Length (где честную длину проверить нельзя) мы не прочитаем больше 10 MiB. + origBody := r.Body + data, err := readLimitedBody(w, r, maxUploadBytes) + if err != nil { + var tooBig *http.MaxBytesError + if errors.As(err, &tooBig) { + // Дочитываем (ограниченно) ИСХОДНОЕ тело: обёртка MaxBytesReader после + // превышения лимита читать уже не даёт. + r.Body = origBody + s.rejectUpload(w, r, http.StatusRequestEntityTooLarge, "payload_too_large", "file is too large") + return + } + // Обрыв загрузки клиентом/таймаут чтения: ничего ещё не записано ни в S3, ни в БД. + writeError(w, r, http.StatusBadRequest, "invalid_request", "upload interrupted") + return + } + + // 7. Проверка СОДЕРЖИМОГО: формат, пиксели, целостность. Пользовательская ошибка + // здесь — всегда 4xx, никогда 500. + info, err := inspectImage(data) + switch { + case errors.Is(err, errTooManyPixels): + writeError(w, r, http.StatusRequestEntityTooLarge, "payload_too_large", "image has too many pixels") + return + case err != nil: + writeError(w, r, http.StatusUnsupportedMediaType, "unsupported_media_type", "file is not a valid png/jpeg image") + return + case info.ContentType != declared: + // «Подмена MIME»: заголовок говорит jpeg, а внутри png (или наоборот). + writeError(w, r, http.StatusUnsupportedMediaType, "unsupported_media_type", "content does not match declared content type") + return + } + + // 8. SHA-256 и ключ. Ключ полностью серверный: filename в нём не участвует. + sum := sha256.Sum256(data) + attID := uuid.New() + key := store.AttachmentObjectKey(chatID, attID) + + // 9. Оригинал в S3. Ошибка хранилища — 503 без подробностей. + if err := s.Objects.Put(r.Context(), key, bytes.NewReader(data), int64(len(data)), info.ContentType); err != nil { + log.Printf("request_id=%s attachment_put_failed err=%v", requestID(r), err) + writeError(w, r, http.StatusServiceUnavailable, "unavailable", "dependency unavailable") + return + } + // Точка отказа «между S3 и PG» — для тестов компенсации. В проде hook == nil. + if s.AfterObjectPut != nil { + s.AfterObjectPut(key) + } + + // 10. Метаданные в PostgreSQL. Дальше data больше не нужна — освобождаем RAM как можно раньше. + att := &store.Attachment{ + ID: attID, + ChatID: chatID, + OwnerID: uid, + Filename: filename, + ContentType: info.ContentType, + SizeBytes: int64(len(data)), + SHA256: hex.EncodeToString(sum[:]), + ObjectKey: key, + Status: store.StatusReady, + Width: info.Width, + Height: info.Height, + } + data = nil + if err := s.Store.CreateAttachment(r.Context(), att); err != nil { + // Компенсация: строки нет → объект бесполезен. Удаляем сразу и независимо от + // контекста запроса (он мог быть отменён — как раз из-за этого INSERT и упал). + s.compensateOrphan(r, key) + if errors.Is(err, store.ErrNotFound) { + writeError(w, r, http.StatusNotFound, "not_found", "object not found") + return + } + s.writeStoreErr(w, r, err, 0, "", "") + return + } + + // 11. Теперь честно: и байты, и метаданные сохранены. + writeJSON(w, http.StatusCreated, attachmentDTO(att)) +} + +// compensateOrphan убирает объект, для которого не удалось записать метаданные. +// Контекст новый и короткий. Если удаление не прошло — это не ошибка запроса: +// объект станет orphan и будет удалён reconciler'ом после grace-периода. +func (s *Server) compensateOrphan(r *http.Request, key string) { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + if err := s.Objects.Delete(ctx, key); err != nil { + log.Printf("request_id=%s attachment_compensation_failed key=%s (reconciler удалит orphan после grace) err=%v", + requestID(r), key, err) + return + } + log.Printf("request_id=%s attachment_compensated key=%s (PG insert не удался, объект удалён)", requestID(r), key) +} + +// handleGetAttachment — GET /api/v1/attachments/{id}: метаданные участнику чата. +func (s *Server) handleGetAttachment(w http.ResponseWriter, r *http.Request) { + att, ok := s.loadAttachmentForRequest(w, r) + if !ok { + return + } + writeJSON(w, http.StatusOK, attachmentDTO(att)) +} + +// handleDownloadAttachment — GET /api/v1/attachments/{id}/content: байты через API, без redirect. +// Прямой доступ к bucket не нужен ни клиенту, ни другой реплике: любая реплика читает +// из общего S3, поэтому остановка загрузившей реплики ничего не ломает. +func (s *Server) handleDownloadAttachment(w http.ResponseWriter, r *http.Request) { + att, ok := s.loadAttachmentForRequest(w, r) + if !ok { + return + } + // variant: в lab4 есть только original. Известные имена вариантов lab5+ у ready-объекта + // отсутствуют → 404, неизвестное имя → 400. + switch v := r.URL.Query().Get("variant"); v { + case "", "original": + case "thumbnail", "crop", "optimized": + writeError(w, r, http.StatusNotFound, "not_found", "object not found") + return + default: + writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid variant") + return + } + if att.Status != store.StatusReady { + writeError(w, r, http.StatusConflict, "conflict", "attachment is not ready") + return + } + + body, _, err := s.Objects.Get(r.Context(), att.ObjectKey) + if err != nil { + if errors.Is(err, objectstore.ErrNotFound) { + // Строка есть, объекта нет — расхождение БД/S3 (его ловит reconciler). + // Это не ошибка пользователя; наружу — общий 500 без деталей. + log.Printf("request_id=%s attachment_object_missing attachment_id=%s", requestID(r), att.ID) + writeError(w, r, http.StatusInternalServerError, "internal_error", "internal error") + return + } + log.Printf("request_id=%s attachment_get_failed err=%v", requestID(r), err) + writeError(w, r, http.StatusServiceUnavailable, "unavailable", "dependency unavailable") + return + } + defer body.Close() + + h := w.Header() + // Тип берём из БД (определён по содержимому при загрузке), а не из S3 и не из имени. + h.Set("Content-Type", att.ContentType) + h.Set("Content-Length", strconv.FormatInt(att.SizeBytes, 10)) + // nosniff: браузер не должен «угадывать» иной тип у отданных байт. + h.Set("X-Content-Type-Options", "nosniff") + h.Set("Cache-Control", "private, no-store") + h.Set("ETag", `"`+att.SHA256+`"`) + // filename показываем только в заголовке, закодированным по RFC 5987 (FormatMediaType). + if cd := mime.FormatMediaType("inline", map[string]string{"filename": att.Filename}); cd != "" { + h.Set("Content-Disposition", cd) + } + w.WriteHeader(http.StatusOK) + // Потоково: в памяти реплики лежит только буфер копирования, не весь файл. + if _, err := io.Copy(w, body); err != nil { + // Заголовки уже отправлены, статус не изменить; клиент увидит обрыв. + log.Printf("request_id=%s attachment_stream_interrupted", requestID(r)) + } +} + +// loadAttachmentForRequest разбирает {attachment_id} и проверяет доступ участника. +// Невалидный UUID — 400; чужое/несуществующее — 404. +func (s *Server) loadAttachmentForRequest(w http.ResponseWriter, r *http.Request) (*store.Attachment, bool) { + id, err := uuid.Parse(r.PathValue("attachment_id")) + if err != nil { + writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid attachment id") + return nil, false + } + att, err := s.Store.GetAttachmentForUser(r.Context(), id, userFrom(r)) + if errors.Is(err, store.ErrNotFound) { + writeError(w, r, http.StatusNotFound, "not_found", "object not found") + return nil, false + } + if err != nil { + s.writeStoreErr(w, r, err, 0, "", "") + return nil, false + } + return att, true +} + +// attachmentDTO — публичное представление. object_key и bucket НЕ раскрываются. +func attachmentDTO(a *store.Attachment) map[string]any { + return map[string]any{ + "id": a.ID.String(), + "chat_id": a.ChatID.String(), + "owner_id": a.OwnerID.String(), + "filename": a.Filename, + "content_type": a.ContentType, + "size_bytes": a.SizeBytes, + "sha256": a.SHA256, + "status": a.Status, + // lab4: производных вариантов нет (они появятся с воркером в lab5+). + "variants": []any{}, + "error_code": a.ErrorCode, + "created_at": formatTime(a.CreatedAt), + "updated_at": formatTime(a.UpdatedAt), + } +} + +// acquireUploadSlot занимает место в очереди буферизации. Возвращает функцию освобождения. +func (s *Server) acquireUploadSlot(ctx context.Context) (func(), bool) { + timer := time.NewTimer(slotWait) + defer timer.Stop() + select { + case s.uploadSlots <- struct{}{}: + return func() { <-s.uploadSlots }, true + case <-ctx.Done(): + return nil, false + case <-timer.C: + return nil, false + } +} + +// rejectUpload отвечает ошибкой на запрос с ещё не прочитанным телом. +// Перед ответом ограниченно дочитываем тело (см. drainLimit): иначе клиент, который +// ещё пишет большой файл, получит сброс соединения вместо понятного статуса. +func (s *Server) rejectUpload(w http.ResponseWriter, r *http.Request, status int, code, msg string) { + _, _ = io.Copy(io.Discard, io.LimitReader(r.Body, drainLimit)) + writeError(w, r, status, code, msg) +} + +// readLimitedBody читает тело не больше limit байт. +// +// Если клиент заявил Content-Length, буфер выделяется ОДИН раз нужного размера +// (+MinRead, чтобы bytes.Buffer не удваивал ёмкость перед самым EOF и не копировал +// 10 MiB в 20 MiB). Для chunked-тела размер неизвестен — буфер растёт, но лимит +// MaxBytesReader всё равно ограничивает его сверху. +func readLimitedBody(w http.ResponseWriter, r *http.Request, limit int64) ([]byte, error) { + r.Body = http.MaxBytesReader(w, r.Body, limit) + var buf bytes.Buffer + if cl := r.ContentLength; cl > 0 && cl <= limit { + buf.Grow(int(cl) + bytes.MinRead) + } + if _, err := buf.ReadFrom(r.Body); err != nil { + return nil, err + } + return buf.Bytes(), nil +} + +// validFilename проверяет отображаемое имя: 1–255 code points, валидный UTF-8, +// не пустое/не пробельное, без '/', '\', NUL и управляющих символов. +// Дополнительно отвергаем разделители строк и bidi-переопределения (U+202A–202E, +// U+2066–2069): через них имя «photo‮gnp.exe» выглядит иначе, чем записано. +func validFilename(raw string) (string, bool) { + if raw == "" || !utf8.ValidString(raw) { + return "", false + } + if n := utf8.RuneCountInString(raw); n < 1 || n > 255 { + return "", false + } + if strings.TrimSpace(raw) == "" { + return "", false + } + for _, c := range raw { + switch { + case c == '/', c == '\\', c == 0, unicode.IsControl(c): + return "", false + case c == 0x2028, c == 0x2029: + return "", false + case c >= 0x202A && c <= 0x202E, c >= 0x2066 && c <= 0x2069: + return "", false + } + } + return raw, true +} diff --git a/internal/api/imagecheck.go b/internal/api/imagecheck.go new file mode 100644 index 00000000..aa90aa0b --- /dev/null +++ b/internal/api/imagecheck.go @@ -0,0 +1,181 @@ +package api + +import ( + "bytes" + "encoding/binary" + "errors" + "hash/crc32" + "image" + _ "image/jpeg" // регистрирует декодер JPEG для image.DecodeConfig / image.Decode + _ "image/png" // регистрирует декодер PNG +) + +// Лимиты контракта lab4. +const ( + // maxUploadBytes = 10 MiB = 10 485 760 байт. Превышение — 413. + maxUploadBytes = 10 << 20 + // maxImagePixels — 40 млн декодированных пикселей. Превышение — 413. + // Проверяется по заголовку (image.DecodeConfig) ДО любой распаковки: PNG размером + // в несколько КБ может «раскрыться» в гигабайты (decompression bomb). + maxImagePixels = 40_000_000 + // fullDecodeMaxPixels — до этого размера дополнительно делаем ПОЛНЫЙ декод, чтобы + // поймать повреждённые данные внутри потока (битый zlib/Huffman при целых заголовках). + // Для больших картинок полный декод стоил бы сотни МБ RAM на одну загрузку + // (40 Мпикс * 4–8 байт) — это ровно то, что запрещает требование про ограниченную RAM, + // поэтому там остаются дешёвые структурные проверки (CRC всех чанков PNG, маркеры/EOI JPEG). + fullDecodeMaxPixels = 2_000_000 +) + +var ( + // errNotImage — не PNG/JPEG или файл повреждён → 415. + errNotImage = errors.New("not a valid png/jpeg image") + // errTooManyPixels — больше 40 млн пикселей → 413. + errTooManyPixels = errors.New("too many pixels") +) + +// imageInfo — результат проверки содержимого. +type imageInfo struct { + ContentType string // image/png | image/jpeg — по СОДЕРЖИМОМУ, не по заголовку запроса + Width, Height int +} + +// inspectImage определяет формат и размеры и отвергает повреждённые файлы. +// +// Порядок важен: +// 1. image.DecodeConfig читает только заголовок: формат + width/height без выделения +// пиксельного буфера. Не PNG/JPEG (в т.ч. GIF, WebP, текст, нули) → errNotImage. +// 2. Лимит пикселей проверяется сразу и ДО структурной проверки и декода. +// 3. Структурная проверка (дёшево, O(n) по байтам, без распаковки). +// 4. Полный декод только для небольших изображений (см. fullDecodeMaxPixels). +func inspectImage(data []byte) (imageInfo, error) { + cfg, format, err := image.DecodeConfig(bytes.NewReader(data)) + if err != nil || cfg.Width <= 0 || cfg.Height <= 0 { + return imageInfo{}, errNotImage + } + var info imageInfo + switch format { + case "png": + info.ContentType = "image/png" + case "jpeg": + info.ContentType = "image/jpeg" + default: + return imageInfo{}, errNotImage + } + info.Width, info.Height = cfg.Width, cfg.Height + + pixels := int64(cfg.Width) * int64(cfg.Height) + if pixels > maxImagePixels { + return imageInfo{}, errTooManyPixels + } + + switch format { + case "png": + if !validPNGStructure(data) { + return imageInfo{}, errNotImage + } + case "jpeg": + if !validJPEGStructure(data) { + return imageInfo{}, errNotImage + } + } + + if pixels <= fullDecodeMaxPixels { + if _, _, err := image.Decode(bytes.NewReader(data)); err != nil { + return imageInfo{}, errNotImage + } + } + return info, nil +} + +// validPNGStructure обходит чанки PNG, не распаковывая данные: +// сигнатура, первым IHDR (13 байт), у каждого чанка верный CRC-32, есть хотя бы один IDAT, +// последний чанк — пустой IEND, после него ничего нет. Усечённый или «склеенный» +// файл этой проверки не проходит. +func validPNGStructure(data []byte) bool { + const signature = "\x89PNG\r\n\x1a\n" + if len(data) < len(signature)+12 || string(data[:len(signature)]) != signature { + return false + } + pos := len(signature) + first, sawIDAT := true, false + for { + if pos+8 > len(data) { + return false // обрыв внутри заголовка чанка + } + length := int64(binary.BigEndian.Uint32(data[pos:])) + if length > 0x7fffffff { + return false // по спецификации длина < 2^31 + } + end := int64(pos) + 8 + length + 4 // длина + тип + данные + CRC + if end > int64(len(data)) { + return false // обрыв внутри данных/CRC + } + chunkType := string(data[pos+4 : pos+8]) + // CRC считается по типу и данным, без поля длины. + if crc32.ChecksumIEEE(data[pos+4:end-4]) != binary.BigEndian.Uint32(data[end-4:end]) { + return false + } + if first { + if chunkType != "IHDR" || length != 13 { + return false + } + first = false + } + switch chunkType { + case "IDAT": + sawIDAT = true + case "IEND": + return sawIDAT && length == 0 && end == int64(len(data)) + } + pos = int(end) + } +} + +// validJPEGStructure — дешёвая проверка целостности JPEG без декода: +// файл начинается с SOI (FFD8), заканчивается EOI (FFD9; нулевой «паддинг» в хвосте +// допускается), и до SOS (начало данных скана) все сегменты имеют корректную длину. +// Усечённый JPEG (потерян хвост) не проходит из-за отсутствия EOI. +func validJPEGStructure(data []byte) bool { + if len(data) < 4 || data[0] != 0xFF || data[1] != 0xD8 { + return false + } + end := len(data) + for end > 0 && data[end-1] == 0x00 { + end-- + } + if end < 2 || data[end-2] != 0xFF || data[end-1] != 0xD9 { + return false + } + i := 2 + for i < len(data) { + if data[i] != 0xFF { + return false + } + for i < len(data) && data[i] == 0xFF { // fill-байты 0xFF перед маркером + i++ + } + if i >= len(data) { + return false + } + marker := data[i] + i++ + switch { + case marker == 0xDA: // SOS: дальше энтропийно-кодированные данные, маркеры не идут подряд + return true + case marker == 0xD9: // EOI до SOS — в файле нет изображения + return false + case marker == 0x01 || (marker >= 0xD0 && marker <= 0xD8): // маркеры без длины + continue + default: + if i+2 > len(data) { + return false + } + segLen := int(binary.BigEndian.Uint16(data[i:])) + if segLen < 2 || i+segLen > len(data) { + return false + } + i += segLen + } + } + return false +} diff --git a/internal/api/server.go b/internal/api/server.go new file mode 100644 index 00000000..d1af0167 --- /dev/null +++ b/internal/api/server.go @@ -0,0 +1,767 @@ +// Package api — HTTP-слой lab4 (lab3 + вложения в S3). +// +// Порядок обработки запроса: +// 1. X-Request-Id и X-Instance-Id на каждый ответ, включая ошибки; +// 2. журнал method/path/status без текста сообщений и без токена; +// 3. маршрут; +// 4. для защищённых маршрутов — только Bearer. Basic и X-User-Id доступ не дают. +// +// /health/live отвечает, пока процесс жив. /health/ready ещё проверяет PostgreSQL, Redis +// и S3: без них нельзя честно принять запись, узнать, кто делает запрос, или принять/отдать +// вложение (lab4: недоступный S3 → 503, балансировщик снимает реплику). +// +// POST сообщения требует Idempotency-Key; результат хранится в общей БД, а не в памяти реплики. +package api + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/base64" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "io" + "log" + "net/http" + "os" + "strconv" + "strings" + "sync/atomic" + "time" + "unicode/utf8" + + "github.com/google/uuid" + + "gavrilenko-sxdees/lab4/internal/objectstore" + "gavrilenko-sxdees/lab4/internal/session" + "gavrilenko-sxdees/lab4/internal/store" +) + +type ctxKey int + +const ( + userKey ctxKey = iota + tokenKey + requestIDKey +) + +const ( + challengeBasic = `Basic realm="messenger", charset="UTF-8"` + challengeBearer = `Bearer realm="messenger"` +) + +// Server связывает HTTP с PostgreSQL и Redis. +type Server struct { + Store *store.Store + Sessions *session.Store + Objects *objectstore.Store // приватный S3-bucket с оригиналами вложений + InstanceID string + ready atomic.Bool + + // uploadSlots — семафор одновременных загрузок (ограничивает пик RAM, см. attachments.go). + uploadSlots chan struct{} + + // AfterObjectPut — тестовый hook: вызывается после успешного PUT в S3 и до INSERT в PG. + // Позволяет в тестах смоделировать отказ «между S3 и БД». В проде всегда nil. + AfterObjectPut func(key string) +} + +// New помечает процесс готовым. Реальная зависимость всё равно проверяется в /health/ready. +// instanceID попадает в X-Instance-Id каждого ответа и стабилен на жизнь процесса. +func New(st *store.Store, sessions *session.Store, objects *objectstore.Store, instanceID string) *Server { + s := &Server{Store: st, Sessions: sessions, Objects: objects, InstanceID: instanceID} + s.uploadSlots = make(chan struct{}, 4) // значение по умолчанию; main задаёт UPLOAD_MAX_CONCURRENCY + s.ready.Store(true) + return s +} + +// BeginDrain вызывается на SIGTERM: новые клиенты видят 503 на /health/ready. +// HAProxy/Traefik с httpchk на /health/ready перестаёт слать трафик на эту реплику. +func (s *Server) BeginDrain() { s.ready.Store(false) } + +// Handler собирает маршруты lab4. +func (s *Server) Handler() http.Handler { + mux := http.NewServeMux() + mux.HandleFunc("GET /health/live", s.handleLive) + mux.HandleFunc("GET /health/ready", s.handleReady) + mux.HandleFunc("POST /api/v1/users", s.handleCreateUser) + mux.HandleFunc("POST /api/v1/auth/sessions", s.handleCreateSession) + mux.HandleFunc("DELETE /api/v1/auth/sessions/current", s.requireUser(s.handleRevokeSession)) + mux.HandleFunc("GET /api/v1/users/me", s.requireUser(s.handleMe)) + mux.HandleFunc("POST /api/v1/chats", s.requireUser(s.handleCreateChat)) + mux.HandleFunc("GET /api/v1/chats", s.requireUser(s.handleListChats)) + mux.HandleFunc("GET /api/v1/chats/{chat_id}", s.requireUser(s.handleGetChat)) + mux.HandleFunc("POST /api/v1/chats/{chat_id}/messages", s.requireUser(s.handleCreateMessage)) + mux.HandleFunc("GET /api/v1/chats/{chat_id}/messages", s.requireUser(s.handleListMessages)) + // lab4: вложения. Загрузка — сырой binary (не multipart), метаданные и байты — через API. + mux.HandleFunc("POST /api/v1/chats/{chat_id}/attachments", s.requireUser(s.handleUploadAttachment)) + mux.HandleFunc("GET /api/v1/attachments/{attachment_id}", s.requireUser(s.handleGetAttachment)) + mux.HandleFunc("GET /api/v1/attachments/{attachment_id}/content", s.requireUser(s.handleDownloadAttachment)) + return s.withInstanceID(s.withRequestID(s.withAccessLog(mux))) +} + +func (s *Server) handleLive(w http.ResponseWriter, r *http.Request) { + writeJSON(w, http.StatusOK, map[string]string{"status": "ok"}) +} + +func (s *Server) handleReady(w http.ResponseWriter, r *http.Request) { + if !s.ready.Load() { + writeError(w, r, http.StatusServiceUnavailable, "unavailable", "service is shutting down") + return + } + // lab4: S3 — критичная зависимость обязательного синхронного пути (загрузка/скачивание). + // Недоступное хранилище → 503, чтобы LB не слал трафик на реплику, которая не может + // выполнить контракт; сообщения без вложений при этом тоже временно недоступны + // (осознанное упрощение: readiness один на реплику, см. REPORT). + if err := s.Store.Ping(r.Context()); err != nil || s.Sessions.Ping(r.Context()) != nil || s.Objects.Ping(r.Context()) != nil { + writeError(w, r, http.StatusServiceUnavailable, "unavailable", "dependency unavailable") + return + } + writeJSON(w, http.StatusOK, map[string]string{"status": "ok"}) +} + +func (s *Server) handleCreateUser(w http.ResponseWriter, r *http.Request) { + var body struct { + Username string `json:"username"` + DisplayName string `json:"display_name"` + Password string `json:"password"` + } + if err := decodeStrict(r, &body); err != nil { + writeDecodeErr(w, r, err) + return + } + if !validUsername(body.Username) { + writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid username") + return + } + display := strings.TrimSpace(body.DisplayName) + if display == "" || utf8.RuneCountInString(display) > 100 { + writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid display_name") + return + } + if n := utf8.RuneCountInString(body.Password); n < 12 || n > 128 { + writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid password") + return + } + u, err := s.Store.CreateUser(r.Context(), body.Username, display, body.Password) + if err != nil { + s.writeStoreErr(w, r, err, http.StatusConflict, "conflict", "username already taken") + return + } + writeJSON(w, http.StatusCreated, userDTO(u)) +} + +func (s *Server) handleCreateSession(w http.ResponseWriter, r *http.Request) { + // Контракт: только Basic, без JSON body. Любые байты в теле — 400, не тихий игнор. + rawBody, err := io.ReadAll(io.LimitReader(r.Body, 4096)) + if err != nil { + writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid body") + return + } + if len(bytes.TrimSpace(rawBody)) != 0 { + writeError(w, r, http.StatusBadRequest, "invalid_request", "session create must not have a body") + return + } + username, password, ok := parseBasic(r.Header.Get("Authorization")) + if !ok || !validUsername(username) { + writeAuthError(w, r, challengeBasic) + return + } + if n := utf8.RuneCountInString(password); n < 12 || n > 128 { + writeAuthError(w, r, challengeBasic) + return + } + u, err := s.Store.Authenticate(r.Context(), username, password) + if errors.Is(err, store.ErrNotFound) { + writeAuthError(w, r, challengeBasic) + return + } + if err != nil { + s.writeStoreErr(w, r, err, 0, "", "") + return + } + token, exp, err := s.Sessions.Issue(r.Context(), u.ID) + if err != nil { + writeError(w, r, http.StatusServiceUnavailable, "unavailable", "dependency unavailable") + return + } + writeJSON(w, http.StatusCreated, map[string]any{ + "token": token, + "token_type": "Bearer", + "expires_at": formatTime(exp), + "user": userDTO(u), + }) +} + +func (s *Server) handleRevokeSession(w http.ResponseWriter, r *http.Request) { + token, _ := r.Context().Value(tokenKey).(string) + if err := s.Sessions.Revoke(r.Context(), token); err != nil { + if errors.Is(err, session.ErrUnauthorized) { + writeAuthError(w, r, challengeBearer) + return + } + writeError(w, r, http.StatusServiceUnavailable, "unavailable", "dependency unavailable") + return + } + w.WriteHeader(http.StatusNoContent) +} + +func (s *Server) handleMe(w http.ResponseWriter, r *http.Request) { + u, err := s.Store.GetUser(r.Context(), userFrom(r)) + if err != nil { + s.writeStoreErr(w, r, err, http.StatusUnauthorized, "unauthorized", "authentication required") + return + } + writeJSON(w, http.StatusOK, userDTO(u)) +} + +func (s *Server) handleCreateChat(w http.ResponseWriter, r *http.Request) { + var body struct { + Title string `json:"title"` + MemberIDs []string `json:"member_ids"` + } + if err := decodeStrict(r, &body); err != nil { + writeDecodeErr(w, r, err) + return + } + title := strings.TrimSpace(body.Title) + if title == "" || utf8.RuneCountInString(title) > 100 { + writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid title") + return + } + if len(body.MemberIDs) < 1 || len(body.MemberIDs) > 100 { + writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid member_ids") + return + } + uid := userFrom(r) + seen := make(map[uuid.UUID]struct{}, len(body.MemberIDs)) + ids := make([]uuid.UUID, 0, len(body.MemberIDs)) + callerPresent := false + for _, raw := range body.MemberIDs { + id, err := uuid.Parse(raw) + if err != nil { + writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid member id") + return + } + if _, dup := seen[id]; dup { + writeError(w, r, http.StatusBadRequest, "invalid_request", "duplicate member id") + return + } + seen[id] = struct{}{} + if id == uid { + callerPresent = true + } + ids = append(ids, id) + } + if !callerPresent { + writeError(w, r, http.StatusBadRequest, "invalid_request", "caller must be a member") + return + } + chat, err := s.Store.CreateChat(r.Context(), title, ids) + if errors.Is(err, store.ErrNotFound) { + writeError(w, r, http.StatusBadRequest, "invalid_request", "unknown member") + return + } + if err != nil { + s.writeStoreErr(w, r, err, 0, "", "") + return + } + writeJSON(w, http.StatusCreated, chatDTO(chat)) +} + +func (s *Server) handleListChats(w http.ResponseWriter, r *http.Request) { + uid := userFrom(r) + limit, after, err := parsePage(r, "chats:"+uid.String()) + if err != nil { + writeError(w, r, http.StatusBadRequest, "invalid_request", err.Error()) + return + } + items, next, err := s.Store.ListChats(r.Context(), uid, limit, after) + if err != nil { + s.writeStoreErr(w, r, err, http.StatusBadRequest, "invalid_request", "invalid cursor") + return + } + out := make([]any, len(items)) + for i := range items { + out[i] = chatDTO(&items[i]) + } + var cursor *store.PageCursor + if next != nil { + cursor = &store.PageCursor{Scope: "chats:" + uid.String(), CreatedAt: next.CreatedAt, ID: next.ID} + } + writeJSON(w, http.StatusOK, pageDTO(out, cursor)) +} + +func (s *Server) handleGetChat(w http.ResponseWriter, r *http.Request) { + chatID, err := uuid.Parse(r.PathValue("chat_id")) + if err != nil { + writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid chat id") + return + } + chat, err := s.Store.GetChat(r.Context(), chatID, userFrom(r)) + if errors.Is(err, store.ErrNotFound) { + writeError(w, r, http.StatusNotFound, "not_found", "object not found") + return + } + if err != nil { + s.writeStoreErr(w, r, err, 0, "", "") + return + } + writeJSON(w, http.StatusOK, chatDTO(chat)) +} + +func (s *Server) handleCreateMessage(w http.ResponseWriter, r *http.Request) { + chatID, err := uuid.Parse(r.PathValue("chat_id")) + if err != nil { + writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid chat id") + return + } + idemKey := r.Header.Get("Idempotency-Key") + if !validIdempotencyKey(idemKey) { + writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid or missing Idempotency-Key") + return + } + var body struct { + Text string `json:"text"` + AttachmentIDs []string `json:"attachment_ids"` + } + if err := decodeStrict(r, &body); err != nil { + writeDecodeErr(w, r, err) + return + } + // attachment_ids: 0–10 уникальных UUID, по умолчанию []. Отсутствующий ключ, null и [] + // равны. UUID нормализуем (нижний регистр, канонический вид): иначе «ABC…» и «abc…» + // давали бы разные хэши идемпотентности и дубль в uniqueItems. + if len(body.AttachmentIDs) > 10 { + writeError(w, r, http.StatusBadRequest, "invalid_request", "too many attachment_ids") + return + } + attachmentIDs := make([]uuid.UUID, 0, len(body.AttachmentIDs)) + canonicalIDs := make([]string, 0, len(body.AttachmentIDs)) + seenAtt := make(map[uuid.UUID]struct{}, len(body.AttachmentIDs)) + for _, raw := range body.AttachmentIDs { + id, err := uuid.Parse(raw) + if err != nil { + writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid attachment id") + return + } + if _, dup := seenAtt[id]; dup { + writeError(w, r, http.StatusBadRequest, "invalid_request", "duplicate attachment id") + return + } + seenAtt[id] = struct{}{} + attachmentIDs = append(attachmentIDs, id) + canonicalIDs = append(canonicalIDs, id.String()) + } + // Непустота — по TrimSpace; длина и сохранение — по исходному тексту. + // Иначе пробелы по краям пропадают, а строка «пробел + 4000 букв» проходит как 4000. + // lab4: пустой текст допустим, если есть хотя бы одно вложение (сообщение «только файл»). + if utf8.RuneCountInString(body.Text) > 4000 || + (strings.TrimSpace(body.Text) == "" && len(attachmentIDs) == 0) { + writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid text") + return + } + path := "/api/v1/chats/" + chatID.String() + "/messages" + reqHash := idempotencyRequestHash(body.Text, canonicalIDs) + result, err := s.Store.CreateMessageIdempotent( + r.Context(), chatID, userFrom(r), body.Text, attachmentIDs, + http.MethodPost, path, idemKey, reqHash, + ) + if errors.Is(err, store.ErrNotFound) { + writeError(w, r, http.StatusNotFound, "not_found", "object not found") + return + } + if errors.Is(err, store.ErrIdempotencyConflict) { + writeError(w, r, http.StatusConflict, "conflict", "idempotency key reused with different body") + return + } + if errors.Is(err, store.ErrAttachmentNotReady) { + writeError(w, r, http.StatusConflict, "conflict", "attachment is not ready") + return + } + if err != nil { + s.writeStoreErr(w, r, err, 0, "", "") + return + } + writeJSON(w, http.StatusCreated, messageDTO(result.Message)) +} + +func (s *Server) handleListMessages(w http.ResponseWriter, r *http.Request) { + chatID, err := uuid.Parse(r.PathValue("chat_id")) + if err != nil { + writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid chat id") + return + } + scope := "chat:" + chatID.String() + limit, after, err := parsePage(r, scope) + if err != nil { + writeError(w, r, http.StatusBadRequest, "invalid_request", err.Error()) + return + } + items, next, err := s.Store.ListMessages(r.Context(), chatID, userFrom(r), limit, after) + if errors.Is(err, store.ErrNotFound) { + writeError(w, r, http.StatusNotFound, "not_found", "object not found") + return + } + if err != nil { + s.writeStoreErr(w, r, err, http.StatusBadRequest, "invalid_request", "invalid cursor") + return + } + out := make([]any, len(items)) + for i := range items { + out[i] = messageDTO(&items[i]) + } + var cursor *store.PageCursor + if next != nil { + cursor = &store.PageCursor{Scope: scope, CreatedAt: next.CreatedAt, ID: next.ID} + } + writeJSON(w, http.StatusOK, pageDTO(out, cursor)) +} + +// requireUser принимает только Authorization: Bearer. X-User-Id не читается. +// Basic на бизнес-методе — тот же 401, но с Bearer-challenge, не с Basic. +func (s *Server) requireUser(next http.HandlerFunc) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + header := r.Header.Get("Authorization") + if strings.HasPrefix(strings.ToLower(header), "basic ") { + writeAuthError(w, r, challengeBearer) + return + } + token, ok := parseBearer(header) + if !ok { + writeAuthError(w, r, challengeBearer) + return + } + uid, err := s.Sessions.Lookup(r.Context(), token) + if errors.Is(err, session.ErrUnauthorized) { + writeAuthError(w, r, challengeBearer) + return + } + if err != nil { + writeError(w, r, http.StatusServiceUnavailable, "unavailable", "dependency unavailable") + return + } + ctx := context.WithValue(r.Context(), userKey, uid) + ctx = context.WithValue(ctx, tokenKey, token) + next(w, r.WithContext(ctx)) + } +} + +func userFrom(r *http.Request) uuid.UUID { + id, _ := r.Context().Value(userKey).(uuid.UUID) + return id +} + +func (s *Server) withRequestID(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + rid := r.Header.Get("X-Request-Id") + if rid == "" { + rid = uuid.NewString() + } + w.Header().Set("X-Request-Id", rid) + next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), requestIDKey, rid))) + }) +} + +func (s *Server) withInstanceID(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("X-Instance-Id", s.InstanceID) + next.ServeHTTP(w, r) + }) +} + +// validIdempotencyKey — ASCII [A-Za-z0-9._:-]{1,128}. +func validIdempotencyKey(key string) bool { + if len(key) < 1 || len(key) > 128 { + return false + } + for i := 0; i < len(key); i++ { + c := key[i] + switch { + case c >= 'A' && c <= 'Z', c >= 'a' && c <= 'z', c >= '0' && c <= '9': + case c == '.', c == '_', c == ':', c == '-': + default: + return false + } + } + return true +} + +// idempotencyRequestHash канонизирует тело: порядок ключей JSON не важен, +// отсутствующий attachment_ids равен []. Хэш — SHA-256 hex. +func idempotencyRequestHash(text string, attachmentIDs []string) string { + if attachmentIDs == nil { + attachmentIDs = []string{} + } + payload, _ := json.Marshal(struct { + Text string `json:"text"` + AttachmentIDs []string `json:"attachment_ids"` + }{Text: text, AttachmentIDs: attachmentIDs}) + sum := sha256.Sum256(payload) + return hex.EncodeToString(sum[:]) +} + +type statusRecorder struct { + http.ResponseWriter + status int +} + +func (s *statusRecorder) WriteHeader(code int) { + s.status = code + s.ResponseWriter.WriteHeader(code) +} + +func (s *Server) withAccessLog(next http.Handler) http.Handler { + quiet := strings.EqualFold(os.Getenv("APP_ACCESS_LOG"), "0") || strings.EqualFold(os.Getenv("APP_ACCESS_LOG"), "false") + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + start := time.Now() + rec := &statusRecorder{ResponseWriter: w, status: http.StatusOK} + next.ServeHTTP(rec, r) + if quiet && rec.status < 400 { + return + } + if strings.HasPrefix(r.URL.Path, "/health/") && rec.status == http.StatusOK { + return + } + rid, _ := r.Context().Value(requestIDKey).(string) + // path без query: в cursor нет секрета, но и текста сообщения в логе быть не должно. + log.Printf("method=%s path=%s status=%d request_id=%s duration_ms=%d", + r.Method, r.URL.Path, rec.status, rid, time.Since(start).Milliseconds()) + }) +} + +func parsePage(r *http.Request, expectedScope string) (int, *store.PageCursor, error) { + limit := 50 + if raw := r.URL.Query().Get("limit"); raw != "" { + n, err := strconv.Atoi(raw) + if err != nil || n < 1 || n > 100 { + return 0, nil, fmt.Errorf("invalid limit") + } + limit = n + } + rawCursor := r.URL.Query().Get("cursor") + if rawCursor == "" { + return limit, nil, nil + } + cur, err := decodeCursor(rawCursor) + if err != nil || cur.Scope != expectedScope { + return 0, nil, fmt.Errorf("invalid cursor") + } + return limit, cur, nil +} + +func encodeCursor(c *store.PageCursor) string { + payload := fmt.Sprintf("%s|%s|%s", c.Scope, c.CreatedAt.UTC().Format(time.RFC3339Nano), c.ID.String()) + return base64.RawURLEncoding.EncodeToString([]byte(payload)) +} + +func decodeCursor(raw string) (*store.PageCursor, error) { + b, err := base64.RawURLEncoding.DecodeString(raw) + if err != nil { + return nil, err + } + parts := strings.SplitN(string(b), "|", 3) + if len(parts) != 3 { + return nil, fmt.Errorf("bad cursor") + } + ts, err := time.Parse(time.RFC3339Nano, parts[1]) + if err != nil { + return nil, err + } + id, err := uuid.Parse(parts[2]) + if err != nil { + return nil, err + } + return &store.PageCursor{Scope: parts[0], CreatedAt: ts.UTC(), ID: id}, nil +} + +func validUsername(s string) bool { + if len(s) < 3 || len(s) > 32 { + return false + } + for _, c := range s { + if (c < 'a' || c > 'z') && (c < '0' || c > '9') && c != '_' { + return false + } + } + return true +} + +func decodeStrict(r *http.Request, dst any) error { + ct := r.Header.Get("Content-Type") + if ct != "" && !strings.HasPrefix(strings.ToLower(strings.TrimSpace(ct)), "application/json") { + return errUnsupported + } + // Читаем тело целиком: Decoder.More() не ловит хвост вида {"text":"x"}} — + // после одного объекта More()=false, а лишняя скобка всё равно остаётся. + raw, err := io.ReadAll(io.LimitReader(r.Body, 1<<20)) + if err != nil { + return errMalformed + } + dec := json.NewDecoder(bytes.NewReader(raw)) + dec.DisallowUnknownFields() + if err := dec.Decode(dst); err != nil { + return errMalformed + } + rest := bytes.TrimSpace(raw[dec.InputOffset():]) + if len(rest) != 0 { + return errMalformed + } + return nil +} + +var ( + errUnsupported = errors.New("unsupported media type") + errMalformed = errors.New("malformed json") +) + +func writeDecodeErr(w http.ResponseWriter, r *http.Request, err error) { + if errors.Is(err, errUnsupported) { + writeError(w, r, http.StatusUnsupportedMediaType, "unsupported_media_type", "unsupported media type") + return + } + writeError(w, r, http.StatusBadRequest, "invalid_request", "malformed json") +} + +func parseBasic(header string) (string, string, bool) { + const prefix = "basic " + if len(header) < len(prefix) || strings.ToLower(header[:len(prefix)]) != prefix { + return "", "", false + } + raw, err := base64.StdEncoding.DecodeString(strings.TrimSpace(header[len(prefix):])) + if err != nil || !utf8.Valid(raw) { + return "", "", false + } + user, pass, ok := strings.Cut(string(raw), ":") + if !ok || user == "" { + return "", "", false + } + return user, pass, true +} + +func parseBearer(header string) (string, bool) { + const prefix = "bearer " + if len(header) < len(prefix) || strings.ToLower(header[:len(prefix)]) != prefix { + return "", false + } + token := strings.TrimSpace(header[len(prefix):]) + if token == "" || strings.Contains(token, " ") { + return "", false + } + return token, true +} + +func userDTO(u *store.User) map[string]any { + return map[string]any{ + "id": u.ID.String(), + "username": u.Username, + "display_name": u.DisplayName, + "created_at": formatTime(u.CreatedAt), + } +} + +func chatDTO(c *store.Chat) map[string]any { + ids := make([]string, len(c.MemberIDs)) + for i, id := range c.MemberIDs { + ids[i] = id.String() + } + return map[string]any{ + "id": c.ID.String(), + "title": c.Title, + "member_ids": ids, + "created_at": formatTime(c.CreatedAt), + } +} + +func messageDTO(m *store.Message) map[string]any { + // attachment_ids обязателен в ответе (контракт 1.4.0): всегда массив, не null. + ids := make([]string, len(m.AttachmentIDs)) + for i, id := range m.AttachmentIDs { + ids[i] = id.String() + } + return map[string]any{ + "id": m.ID.String(), + "chat_id": m.ChatID.String(), + "sender_id": m.SenderID.String(), + "text": m.Text, + "created_at": formatTime(m.CreatedAt), + "attachment_ids": ids, + } +} + +func pageDTO(items []any, next *store.PageCursor) map[string]any { + var cursor any + if next != nil { + cursor = encodeCursor(next) + } + if items == nil { + items = []any{} + } + return map[string]any{"items": items, "next_cursor": cursor} +} + +func formatTime(t time.Time) string { + return t.UTC().Truncate(time.Millisecond).Format("2006-01-02T15:04:05.000Z") +} + +func writeJSON(w http.ResponseWriter, status int, v any) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(status) + enc := json.NewEncoder(w) + enc.SetEscapeHTML(false) + _ = enc.Encode(v) +} + +func writeError(w http.ResponseWriter, r *http.Request, status int, code, message string) { + rid, _ := r.Context().Value(requestIDKey).(string) + if rid == "" { + rid = w.Header().Get("X-Request-Id") + } + writeJSON(w, status, map[string]any{ + "error": map[string]any{ + "code": code, + "message": message, + "request_id": rid, + }, + }) +} + +func writeAuthError(w http.ResponseWriter, r *http.Request, challenge string) { + w.Header().Set("WWW-Authenticate", challenge) + writeError(w, r, http.StatusUnauthorized, "unauthorized", "authentication required") +} + +// writeStoreErr прячет текст драйвера. fallbackStatus используется для ожидаемой доменной ошибки. +func (s *Server) writeStoreErr(w http.ResponseWriter, r *http.Request, err error, fallbackStatus int, fallbackCode, fallbackMessage string) { + switch { + case errors.Is(err, store.ErrUnavailable): + writeError(w, r, http.StatusServiceUnavailable, "unavailable", "dependency unavailable") + case errors.Is(err, store.ErrIdempotencyConflict): + writeError(w, r, http.StatusConflict, "conflict", "idempotency key reused with different body") + case errors.Is(err, store.ErrConflict) && fallbackStatus != 0: + writeError(w, r, fallbackStatus, fallbackCode, fallbackMessage) + case errors.Is(err, store.ErrNotFound) && fallbackStatus != 0: + if fallbackCode == "unauthorized" { + writeAuthError(w, r, challengeBearer) + return + } + writeError(w, r, fallbackStatus, fallbackCode, fallbackMessage) + case errors.Is(err, store.ErrInvalidCursor): + writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid cursor") + default: + if errors.Is(err, store.ErrConflict) { + writeError(w, r, http.StatusConflict, "conflict", "username already taken") + return + } + // В лог — только тип, без SQL и без текста, который драйвер мог вложить в ошибку. + log.Printf("request_id=%s store_error_type=%T", requestID(r), err) + writeError(w, r, http.StatusInternalServerError, "internal_error", "internal error") + } +} + +func requestID(r *http.Request) string { + rid, _ := r.Context().Value(requestIDKey).(string) + return rid +} diff --git a/internal/auth/password.go b/internal/auth/password.go new file mode 100644 index 00000000..fb798dba --- /dev/null +++ b/internal/auth/password.go @@ -0,0 +1,110 @@ +// Package auth хранит пароли через Argon2id. +// +// bcrypt отвергнут: библиотека молча режет пароль на 72 байта, а контракт +// разрешает до 128 Unicode code points, включая символы вне ASCII. +// Argon2id принимает пароль целиком. Параметры — интерактивные, не «серверные» +// на сотни миллисекунд: smoke создаёт несколько пользователей подряд. +package auth + +import ( + "crypto/rand" + "crypto/subtle" + "encoding/base64" + "fmt" + "strings" + + "golang.org/x/crypto/argon2" +) + +const ( + argonTime = 2 + argonMemory = 19 * 1024 // KiB, около 19 MiB + argonThreads = 1 + argonKeyLen = 32 + argonSaltLen = 16 +) + +// Hasher умеет хешировать и проверять. dummy — хеш случайного пароля, +// чтобы отсутствующий username занимал примерно столько же CPU, сколько неверный пароль. +type Hasher struct { + dummy string +} + +// NewHasher готовит dummy-хеш один раз на процесс. +func NewHasher() (*Hasher, error) { + dummy, err := Hash(randomPassword()) + if err != nil { + return nil, err + } + return &Hasher{dummy: dummy}, nil +} + +// Hash возвращает PHC-строку. Её пишем в users.password_hash. +func Hash(password string) (string, error) { + salt := make([]byte, argonSaltLen) + if _, err := rand.Read(salt); err != nil { + return "", err + } + sum := argon2.IDKey([]byte(password), salt, argonTime, argonMemory, argonThreads, argonKeyLen) + return fmt.Sprintf("$argon2id$v=19$m=%d,t=%d,p=%d$%s$%s", + argonMemory, argonTime, argonThreads, + base64.RawStdEncoding.EncodeToString(salt), + base64.RawStdEncoding.EncodeToString(sum), + ), nil +} + +// Verify сравнивает пароль с PHC-строкой. При битой строке возвращает false, не панику. +func (h *Hasher) Verify(encoded, password string) bool { + if encoded == "" { + encoded = h.dummy + } + ok, err := verify(encoded, password) + if err != nil { + // Всё равно тратим время dummy-проверки, чтобы ветка ошибки не была мгновенной. + _, _ = verify(h.dummy, password) + return false + } + return ok +} + +// Burn тратит время проверки, когда пользователя нет. Результат всегда false. +func (h *Hasher) Burn(password string) { + _, _ = verify(h.dummy, password) +} + +func verify(encoded, password string) (bool, error) { + parts := strings.Split(encoded, "$") + // ["", "argon2id", "v=19", "m=..,t=..,p=..", salt, hash] + if len(parts) != 6 || parts[1] != "argon2id" || parts[2] != "v=19" { + return false, fmt.Errorf("bad hash") + } + var memory uint32 + var timeCost uint32 + var threads uint8 + if _, err := fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d", &memory, &timeCost, &threads); err != nil { + return false, err + } + if memory != argonMemory || timeCost != argonTime || threads != argonThreads { + return false, fmt.Errorf("unexpected argon2 parameters") + } + salt, err := base64.RawStdEncoding.DecodeString(parts[4]) + if err != nil { + return false, err + } + want, err := base64.RawStdEncoding.DecodeString(parts[5]) + if err != nil { + return false, err + } + got := argon2.IDKey([]byte(password), salt, timeCost, memory, threads, uint32(len(want))) + // ConstantTimeCompare не даёт выйти на первом несовпавшем байте. + if subtle.ConstantTimeCompare(got, want) != 1 { + return false, nil + } + return true, nil +} + +func randomPassword() string { + buf := make([]byte, 24) + _, _ = rand.Read(buf) + return base64.RawStdEncoding.EncodeToString(buf) +} diff --git a/internal/config/config.go b/internal/config/config.go new file mode 100644 index 00000000..ea55e4ad --- /dev/null +++ b/internal/config/config.go @@ -0,0 +1,188 @@ +// Package config читает настройки процесса из окружения. +// +// Прямые URL (DATABASE_URL, REDIS_URL) удобны в Compose. +// Вариант *_FILE из .env.example нужен, если секрет смонтирован файлом: +// тогда в переменной лежит путь, а не сам секрет. +package config + +import ( + "fmt" + "os" + "strconv" + "strings" + "time" +) + +// Config — всё, что процесс обязан знать до открытия соединений. +type Config struct { + Host string + Port int + Env string + DatabaseURL string + RedisURL string + SessionTTL time.Duration + InstanceID string + MaxConns int32 + RunMigrations bool + IdempotencyTTL time.Duration + + // --- lab4: объектное хранилище (S3-совместимое, MinIO) --- + + // S3Endpoint — URL S3 API внутри сети Compose (http://minio:9000). + S3Endpoint string + // S3Region — для SigV4 нужен любой регион; у MinIO по умолчанию us-east-1. + S3Region string + // S3Bucket — приватный bucket с оригиналами вложений. + S3Bucket string + // S3AccessKey/S3SecretKey — НЕ root MinIO, а отдельный пользователь messenger-api + // с политикой только на этот bucket (создаётся сервисом minio-init). + S3AccessKey string + S3SecretKey string + // S3ForcePathStyle — path-style адресация (http://minio:9000/bucket/key). + // У MinIO в Compose нет wildcard-DNS для bucket.minio, поэтому virtual-hosted не работает. + S3ForcePathStyle bool + // S3OrphanGrace — «льготный период» reconciler: объект без строки в БД младше этого + // возраста считается ещё загружаемым (PUT уже был, INSERT ещё не успел) и не трогается. + S3OrphanGrace time.Duration + // UploadMaxConcurrency — сколько загрузок одна реплика буферизует в RAM одновременно. + // Остальные ждут в очереди (см. api.Server.uploadSlots), поэтому пик памяти ограничен + // сверху UploadMaxConcurrency * 10 MiB, а не числом клиентов. + UploadMaxConcurrency int +} + +// Load собирает Config. Пустой URL без файла — ошибка запуска, а не тихий дефолт на чужой хост. +func Load() (Config, error) { + cfg := Config{ + Host: getenv("APP_HOST", "0.0.0.0"), + Env: getenv("APP_ENV", "lab"), + } + port, err := strconv.Atoi(getenv("APP_PORT", "8080")) + if err != nil || port < 1 || port > 65535 { + return cfg, fmt.Errorf("invalid APP_PORT") + } + cfg.Port = port + + ttlSec, err := strconv.Atoi(getenv("SESSION_TTL_SECONDS", "3600")) + if err != nil || ttlSec < 1 || ttlSec > 7*24*3600 { + return cfg, fmt.Errorf("invalid SESSION_TTL_SECONDS") + } + cfg.SessionTTL = time.Duration(ttlSec) * time.Second + + idemTTL, err := strconv.Atoi(getenv("IDEMPOTENCY_TTL_SECONDS", "86400")) + if err != nil || idemTTL < 60 || idemTTL > 7*24*3600 { + return cfg, fmt.Errorf("invalid IDEMPOTENCY_TTL_SECONDS") + } + cfg.IdempotencyTTL = time.Duration(idemTTL) * time.Second + + maxConns, err := strconv.Atoi(getenv("DB_MAX_CONNS", "5")) + if err != nil || maxConns < 1 || maxConns > 50 { + return cfg, fmt.Errorf("invalid DB_MAX_CONNS") + } + cfg.MaxConns = int32(maxConns) + + cfg.DatabaseURL, err = getenvOrFile("DATABASE_URL", "DATABASE_URL_FILE") + if err != nil { + return cfg, err + } + cfg.RedisURL, err = getenvOrFile("REDIS_URL", "CACHE_URL_FILE") + if err != nil { + return cfg, err + } + + if err := loadS3(&cfg); err != nil { + return cfg, err + } + + // X-Instance-Id стабилен на жизнь процесса. В Compose hostname = id контейнера, + // поэтому stop-one.sh сопоставляет TARGET_INSTANCE_ID с Config.Hostname. + cfg.InstanceID = strings.TrimSpace(os.Getenv("INSTANCE_ID")) + if cfg.InstanceID == "" { + host, herr := os.Hostname() + if herr != nil || strings.TrimSpace(host) == "" { + return cfg, fmt.Errorf("set INSTANCE_ID or ensure hostname is available") + } + cfg.InstanceID = host + } + + // Миграции по умолчанию выключены у API-реплик: их гоняет одноразовый сервис migrate. + // Для локальных тестов и -migrate флага включается явно. + cfg.RunMigrations = truthy(os.Getenv("RUN_MIGRATIONS")) + return cfg, nil +} + +// loadS3 читает S3_* переменные. Ключи, как и DATABASE_URL, можно передать файлом +// (S3_ACCESS_KEY_FILE / S3_SECRET_KEY_FILE): так секрет не попадает в `docker inspect`. +// Пустой endpoint/ключ — ошибка запуска: тихий дефолт на «какой-нибудь» S3 опаснее падения. +func loadS3(cfg *Config) error { + var err error + cfg.S3Endpoint = strings.TrimSpace(os.Getenv("S3_ENDPOINT")) + if cfg.S3Endpoint == "" { + return fmt.Errorf("set S3_ENDPOINT") + } + cfg.S3Region = getenv("S3_REGION", "us-east-1") + cfg.S3Bucket = getenv("S3_BUCKET", "messenger") + cfg.S3AccessKey, err = getenvOrFile("S3_ACCESS_KEY", "S3_ACCESS_KEY_FILE") + if err != nil { + return err + } + cfg.S3SecretKey, err = getenvOrFile("S3_SECRET_KEY", "S3_SECRET_KEY_FILE") + if err != nil { + return err + } + // По умолчанию path-style включён: для MinIO в Compose это единственный рабочий вариант. + cfg.S3ForcePathStyle = truthy(getenv("S3_FORCE_PATH_STYLE", "1")) + + // Grace по умолчанию 300 с: с запасом больше любой реальной загрузки (таймаут PUT 10 с) + // и задержки между PUT и COMMIT. 0 допустим (удалять сразу) — нужен только тестам. + graceSec, err := strconv.Atoi(getenv("S3_ORPHAN_GRACE_SECONDS", "300")) + if err != nil || graceSec < 0 || graceSec > 7*24*3600 { + return fmt.Errorf("invalid S3_ORPHAN_GRACE_SECONDS") + } + cfg.S3OrphanGrace = time.Duration(graceSec) * time.Second + + cfg.UploadMaxConcurrency, err = strconv.Atoi(getenv("UPLOAD_MAX_CONCURRENCY", "4")) + if err != nil || cfg.UploadMaxConcurrency < 1 || cfg.UploadMaxConcurrency > 64 { + return fmt.Errorf("invalid UPLOAD_MAX_CONCURRENCY") + } + return nil +} + +// Addr — адрес Listen, обычно 0.0.0.0:8080 внутри контейнера. +func (c Config) Addr() string { + return fmt.Sprintf("%s:%d", c.Host, c.Port) +} + +func getenv(key, fallback string) string { + if v := strings.TrimSpace(os.Getenv(key)); v != "" { + return v + } + return fallback +} + +func getenvOrFile(directKey, fileKey string) (string, error) { + if v := strings.TrimSpace(os.Getenv(directKey)); v != "" { + return v, nil + } + path := strings.TrimSpace(os.Getenv(fileKey)) + if path == "" { + return "", fmt.Errorf("set %s or %s", directKey, fileKey) + } + b, err := os.ReadFile(path) + if err != nil { + return "", fmt.Errorf("read %s: %w", fileKey, err) + } + v := strings.TrimSpace(string(b)) + if v == "" { + return "", fmt.Errorf("%s is empty", fileKey) + } + return v, nil +} + +func truthy(v string) bool { + switch strings.ToLower(strings.TrimSpace(v)) { + case "1", "true", "yes", "on": + return true + default: + return false + } +} diff --git a/internal/objectstore/s3.go b/internal/objectstore/s3.go new file mode 100644 index 00000000..55444d97 --- /dev/null +++ b/internal/objectstore/s3.go @@ -0,0 +1,304 @@ +// Package objectstore — тонкая обёртка над aws-sdk-go-v2 для приватного S3-bucket (MinIO). +// +// Зачем отдельный пакет: +// - HTTP-слой и reconciler работают с узким набором операций (Put/Get/Delete/Head/List/ +// EnsureBucket/Ping) и с двумя доменными ошибками, а не с типами SDK; +// - все таймауты и настройки «совместимости с MinIO» собраны в одном месте; +// - наружу (в ответ клиенту, в лог) не уходят тексты ошибок SDK: в них бывают +// endpoint, имя bucket и фрагменты запроса. +// +// Байты вложений живут ТОЛЬКО здесь. Ни локальный диск API-реплики, ни PostgreSQL +// оригиналов не хранят: любая реплика после остановки соседней отдаёт тот же файл. +package objectstore + +import ( + "context" + "errors" + "fmt" + "io" + "net" + "net/http" + "time" + + "github.com/aws/aws-sdk-go-v2/aws" + awshttp "github.com/aws/aws-sdk-go-v2/aws/transport/http" + "github.com/aws/aws-sdk-go-v2/credentials" + "github.com/aws/aws-sdk-go-v2/service/s3" + "github.com/aws/aws-sdk-go-v2/service/s3/types" + "github.com/aws/smithy-go" +) + +// Доменные ошибки. HTTP-слой различает «нет объекта» и «хранилище недоступно». +var ( + // ErrNotFound — объекта (или bucket) нет. + ErrNotFound = errors.New("object not found") + // ErrUnavailable — S3 недоступен, таймаут, отказ в доступе или любая иная ошибка + // транспорта. Клиенту это всегда 503: он не должен видеть подробности. + ErrUnavailable = errors.New("object store unavailable") +) + +// Таймауты операций. Подобраны под HAProxy (timeout server 15s): S3-запрос обязан +// закончиться раньше, чем балансировщик оборвёт клиента, иначе получим 504 вместо +// управляемого 503. +const ( + pingTimeout = 700 * time.Millisecond // /health/ready опрашивается раз в секунду + putTimeout = 10 * time.Second // до 10 MiB по локальной сети + smallOpTimeout = 3 * time.Second // Head/Delete + listTimeout = 10 * time.Second // страница List до 1000 ключей +) + +// Config — параметры подключения. Секреты приходят из окружения, в лог не пишутся. +type Config struct { + Endpoint string + Region string + Bucket string + AccessKey string + SecretKey string + ForcePathStyle bool +} + +// Store — клиент одного bucket. Безопасен для конкурентного использования. +type Store struct { + client *s3.Client + bucket string +} + +// ObjectInfo — метаданные объекта (из Head или List). +type ObjectInfo struct { + Key string + Size int64 + ContentType string // пусто для List: он тип не возвращает + LastModified time.Time + ETag string +} + +// ListPage — одна страница List. NextToken пуст, когда страниц больше нет. +type ListPage struct { + Objects []ObjectInfo + NextToken string +} + +// New создаёт клиента. Сетевых вызовов не делает: доступность проверяют Ping/EnsureBucket. +func New(cfg Config) (*Store, error) { + if cfg.Endpoint == "" || cfg.Bucket == "" || cfg.AccessKey == "" || cfg.SecretKey == "" { + return nil, fmt.Errorf("objectstore: endpoint, bucket and credentials are required") + } + region := cfg.Region + if region == "" { + region = "us-east-1" + } + + // Собственный HTTP-клиент: короткий dial-таймаут нужен, чтобы остановленный MinIO + // давал отказ за ~2 с, а не за системные минуты. ResponseHeaderTimeout защищает от + // «подвисшего» сервера, который принял соединение, но не отвечает. + httpClient := awshttp.NewBuildableClient(). + WithDialerOptions(func(d *net.Dialer) { + d.Timeout = 2 * time.Second + d.KeepAlive = 30 * time.Second + }). + WithTransportOptions(func(tr *http.Transport) { + tr.ResponseHeaderTimeout = 8 * time.Second + tr.MaxIdleConnsPerHost = 16 + tr.IdleConnTimeout = 60 * time.Second + }) + + awsCfg := aws.Config{ + Region: region, + Credentials: credentials.NewStaticCredentialsProvider(cfg.AccessKey, cfg.SecretKey, ""), + HTTPClient: httpClient, + // Две попытки вместо трёх по умолчанию: повтор нужен для редких обрывов, + // но при лежащем S3 мы хотим быстро ответить 503, а не копить backoff. + RetryMaxAttempts: 2, + } + client := s3.NewFromConfig(awsCfg, func(o *s3.Options) { + o.BaseEndpoint = aws.String(cfg.Endpoint) + // MinIO в Compose доступен только по имени хоста minio — bucket в имени хоста + // (virtual-hosted) невозможен, поэтому path-style. + o.UsePathStyle = cfg.ForcePathStyle + // Свежие версии SDK по умолчанию добавляют CRC32-trailer ко всем PUT. Для + // не-AWS бэкендов это источник несовместимостей; нам достаточно обычной SigV4 + // подписи полезной нагрузки (тело — seekable bytes.Reader). + o.RequestChecksumCalculation = aws.RequestChecksumCalculationWhenRequired + o.ResponseChecksumValidation = aws.ResponseChecksumValidationWhenRequired + }) + return &Store{client: client, bucket: cfg.Bucket}, nil +} + +// Bucket возвращает имя bucket (для логов bootstrap; клиенту не отдаётся). +func (s *Store) Bucket() string { return s.bucket } + +// Ping — проверка для /health/ready: HeadBucket. Требует s3:ListBucket, которое +// есть в политике messenger-api. Короткий таймаут: readiness не должен висеть. +func (s *Store) Ping(ctx context.Context) error { + ctx, cancel := context.WithTimeout(ctx, pingTimeout) + defer cancel() + if _, err := s.client.HeadBucket(ctx, &s3.HeadBucketInput{Bucket: aws.String(s.bucket)}); err != nil { + return ErrUnavailable + } + return nil +} + +// EnsureBucket идемпотентно гарантирует существование bucket. +// +// Основной путь создания — сервис minio-init (root-учётка). API-пользователь по политике +// НЕ может создавать buckets, поэтому здесь: HeadBucket → если нет, пробуем CreateBucket +// (сработает на S3-бэкендах с более широкими правами, например в локальном dev) и +// «уже существует/уже наш» считаем успехом. Повторный вызов безопасен. +func (s *Store) EnsureBucket(ctx context.Context) error { + ctx, cancel := context.WithTimeout(ctx, smallOpTimeout) + defer cancel() + _, err := s.client.HeadBucket(ctx, &s3.HeadBucketInput{Bucket: aws.String(s.bucket)}) + if err == nil { + return nil + } + if !isNotFound(err) { + return fmt.Errorf("head bucket: %w", classify(err)) + } + _, err = s.client.CreateBucket(ctx, &s3.CreateBucketInput{Bucket: aws.String(s.bucket)}) + if err != nil { + var owned *types.BucketAlreadyOwnedByYou + var exists *types.BucketAlreadyExists + if errors.As(err, &owned) || errors.As(err, &exists) { + return nil // гонка с другой репликой/minio-init: bucket уже есть + } + return fmt.Errorf("create bucket (запустите minio-init): %w", classify(err)) + } + return nil +} + +// Put кладёт объект целиком. body должен быть seekable (bytes.Reader): SDK тогда сам +// считает хеш полезной нагрузки для SigV4 и умеет перечитать тело при retry. +// Объект без ACL: bucket приватный, анонимный доступ запрещён политикой. +func (s *Store) Put(ctx context.Context, key string, body io.ReadSeeker, size int64, contentType string) error { + ctx, cancel := context.WithTimeout(ctx, putTimeout) + defer cancel() + _, err := s.client.PutObject(ctx, &s3.PutObjectInput{ + Bucket: aws.String(s.bucket), + Key: aws.String(key), + Body: body, + ContentLength: aws.Int64(size), + ContentType: aws.String(contentType), + }) + return classify(err) +} + +// Get открывает поток объекта. Вызывающий ОБЯЗАН закрыть ReadCloser. +// Таймаут здесь не навешиваем: контекст живёт, пока тело стримится клиенту +// (его ограничивает ctx запроса и WriteTimeout HTTP-сервера). +func (s *Store) Get(ctx context.Context, key string) (io.ReadCloser, ObjectInfo, error) { + out, err := s.client.GetObject(ctx, &s3.GetObjectInput{ + Bucket: aws.String(s.bucket), + Key: aws.String(key), + }) + if err != nil { + return nil, ObjectInfo{}, classify(err) + } + info := ObjectInfo{ + Key: key, + Size: aws.ToInt64(out.ContentLength), + ContentType: aws.ToString(out.ContentType), + LastModified: aws.ToTime(out.LastModified), + ETag: aws.ToString(out.ETag), + } + return out.Body, info, nil +} + +// Head возвращает метаданные без тела. ErrNotFound — объекта нет. +func (s *Store) Head(ctx context.Context, key string) (ObjectInfo, error) { + ctx, cancel := context.WithTimeout(ctx, smallOpTimeout) + defer cancel() + out, err := s.client.HeadObject(ctx, &s3.HeadObjectInput{ + Bucket: aws.String(s.bucket), + Key: aws.String(key), + }) + if err != nil { + return ObjectInfo{}, classify(err) + } + return ObjectInfo{ + Key: key, + Size: aws.ToInt64(out.ContentLength), + ContentType: aws.ToString(out.ContentType), + LastModified: aws.ToTime(out.LastModified), + ETag: aws.ToString(out.ETag), + }, nil +} + +// Delete удаляет объект. Отсутствующий объект — не ошибка (S3 DeleteObject идемпотентен), +// что важно и для компенсации после сбоя PG, и для повторных запусков reconciler. +func (s *Store) Delete(ctx context.Context, key string) error { + ctx, cancel := context.WithTimeout(ctx, smallOpTimeout) + defer cancel() + _, err := s.client.DeleteObject(ctx, &s3.DeleteObjectInput{ + Bucket: aws.String(s.bucket), + Key: aws.String(key), + }) + if err != nil && isNotFound(err) { + return nil + } + return classify(err) +} + +// List возвращает одну страницу ключей с префиксом prefix в лексикографическом порядке +// (так S3 отдаёт ListObjectsV2). token — из предыдущей страницы, пустой для первой. +// Именно порядок позволяет reconciler сливать листинг с отсортированной выборкой из БД +// (merge-join) без загрузки всех ключей в память. +func (s *Store) List(ctx context.Context, prefix, token string, maxKeys int32) (ListPage, error) { + ctx, cancel := context.WithTimeout(ctx, listTimeout) + defer cancel() + in := &s3.ListObjectsV2Input{ + Bucket: aws.String(s.bucket), + Prefix: aws.String(prefix), + MaxKeys: aws.Int32(maxKeys), + } + if token != "" { + in.ContinuationToken = aws.String(token) + } + out, err := s.client.ListObjectsV2(ctx, in) + if err != nil { + return ListPage{}, classify(err) + } + page := ListPage{Objects: make([]ObjectInfo, 0, len(out.Contents))} + for _, o := range out.Contents { + page.Objects = append(page.Objects, ObjectInfo{ + Key: aws.ToString(o.Key), + Size: aws.ToInt64(o.Size), + LastModified: aws.ToTime(o.LastModified), + ETag: aws.ToString(o.ETag), + }) + } + if aws.ToBool(out.IsTruncated) { + page.NextToken = aws.ToString(out.NextContinuationToken) + } + return page, nil +} + +// classify сводит ошибки SDK к двум доменным. Исходный текст не пробрасываем. +func classify(err error) error { + switch { + case err == nil: + return nil + case isNotFound(err): + return ErrNotFound + default: + return ErrUnavailable + } +} + +// isNotFound распознаёт «нет объекта/bucket» по типам и кодам ответа S3. +// HeadObject отдаёт безымянный 404 (types.NotFound), GetObject — NoSuchKey. +func isNotFound(err error) bool { + var noKey *types.NoSuchKey + var notFound *types.NotFound + var noBucket *types.NoSuchBucket + if errors.As(err, &noKey) || errors.As(err, ¬Found) || errors.As(err, &noBucket) { + return true + } + var apiErr smithy.APIError + if errors.As(err, &apiErr) { + switch apiErr.ErrorCode() { + case "NoSuchKey", "NotFound", "NoSuchBucket": + return true + } + } + return false +} diff --git a/internal/reconcile/reconcile.go b/internal/reconcile/reconcile.go new file mode 100644 index 00000000..57bdf276 --- /dev/null +++ b/internal/reconcile/reconcile.go @@ -0,0 +1,377 @@ +// Package reconcile — сверка двух хранилищ вложений: S3 (байты) и PostgreSQL (метаданные). +// +// Почему сверка нужна вообще. Общей транзакции у S3 и PostgreSQL нет. Загрузка делает +// PUT в S3, затем INSERT в БД (см. internal/api/attachments.go). Между шагами процесс может +// умереть, а компенсирующее удаление — не сработать. Получаются два вида расхождений: +// +// orphan — объект в S3 есть, строки в БД нет. Безвредно для пользователя, но это вечный +// мусор и расход места. Лечение: удалить объект, НО только старше grace-периода +// (иначе можно снести объект, у которого INSERT ещё «в полёте»). +// missing — строка в БД есть, объекта в S3 нет (удалён руками, потерян, сбой диска). +// Пользователь получит ошибку при скачивании. Автоматически данные не вернуть, +// поэтому по умолчанию только ОТЧЁТ. Опционально (PruneMissing) удаляется строка, +// которая одновременно старая И неиспользуемая; «свежие» и «используемые» +// сообщениями вложения не удаляются никогда. +// +// Алгоритм — merge-join двух ОТСОРТИРОВАННЫХ потоков (ключи S3 в лексикографическом порядке +// и attachments.object_key COLLATE "C" в БД). Обе стороны читаются страницами, поэтому память +// O(размер страницы), а не O(число объектов), а стоимость — O(n) по числу объектов +// плюс HEAD только для редких кандидатов в missing. +// +// Безопасность: +// - dry-run (DryRun) ничего не удаляет и не изменяет: только лог и отчёт; +// - повторный запуск идемпотентен (после исправления расхождений находит 0); +// - ключи вне схемы attachments/{uuid}/{uuid} никогда не удаляются; +// - перед удалением orphan — повторная проверка строки в БД (сужает окно гонки); +// - строки, на которые ссылаются сообщения, защищены ещё и внешним ключом PostgreSQL. +package reconcile + +import ( + "context" + "errors" + "fmt" + "time" + + "github.com/google/uuid" + + "gavrilenko-sxdees/lab4/internal/objectstore" + "gavrilenko-sxdees/lab4/internal/store" +) + +// KeyPrefix — единственный префикс, который обходит reconciler. +const KeyPrefix = "attachments/" + +// pageSize — размер страницы и для S3 (максимум ListObjectsV2 — 1000), и для БД. +const defaultPageSize = 1000 + +// maxSamples ограничивает число ключей-примеров в отчёте, чтобы вывод не разрастался. +const maxSamples = 50 + +// Options — параметры запуска. +type Options struct { + // DryRun — ничего не менять, только сообщить, что было бы сделано. + DryRun bool + // Grace — минимальный возраст orphan-объекта (по LastModified в S3) и «неиспользуемой» + // строки (по created_at), после которого их можно трогать. Берётся из S3_ORPHAN_GRACE_SECONDS. + Grace time.Duration + // PruneMissing — удалять строки без объекта, если они старше Grace и не прикреплены + // ни к одному сообщению. Без флага missing только отчётность. + PruneMissing bool + // PageSize — для тестов; по умолчанию 1000. + PageSize int + // Now — для тестов; по умолчанию time.Now. + Now func() time.Time + // Logf — построчный лог (по умолчанию молчит). В main — log.Printf. + Logf func(format string, args ...any) +} + +// Report — итог запуска. Печатается в JSON и годится как evidence. +type Report struct { + DryRun bool `json:"dry_run"` + GraceSeconds float64 `json:"grace_seconds"` + PruneMissing bool `json:"prune_missing"` + + // Стоимость обхода. + S3ObjectsScanned int `json:"s3_objects_scanned"` + DBRowsScanned int `json:"db_rows_scanned"` + S3ListCalls int `json:"s3_list_calls"` + DBPages int `json:"db_pages"` + HeadCalls int `json:"s3_head_calls"` + DeleteCalls int `json:"s3_delete_calls"` + DurationMs int64 `json:"duration_ms"` + + Matched int `json:"matched"` // и объект, и строка + + // Orphan: объект без строки. + OrphansFound int `json:"orphans_found"` // старше grace, подлежат удалению + OrphansDeleted int `json:"orphans_deleted"` // реально удалено (0 в dry-run) + OrphansFresh int `json:"orphans_fresh"` // моложе grace — не тронуты + OrphansRaced int `json:"orphans_raced"` // перед удалением строка появилась — не тронуты + UnknownKeys int `json:"unknown_keys"` // ключ вне схемы attachments/{uuid}/{uuid} — не тронуты + OrphanSampleKey []string `json:"orphan_sample_keys,omitempty"` + + // Missing: строка без объекта. + MissingFound int `json:"missing_found"` // подтверждено HEAD + MissingUsed int `json:"missing_used"` // прикреплено к сообщению — ТРЕБУЕТ внимания, не удаляется + MissingFresh int `json:"missing_fresh"` // моложе grace — не тронуты + MissingStale int `json:"missing_stale"` // старые и неиспользуемые — кандидаты на prune + MissingPruned int `json:"missing_pruned"` // строк удалено (0 в dry-run и без PruneMissing) + MissingRaced int `json:"missing_raced"` // HEAD нашёл объект — ложная тревога из-за гонки + MissingSample []string `json:"missing_sample_keys,omitempty"` + + Errors int `json:"errors"` +} + +// Reconciler — зависимости. +type Reconciler struct { + DB *store.Store + Objects *objectstore.Store + Opts Options +} + +// Run выполняет один проход. Ошибка хранилища (S3/PG недоступны) прерывает проход: +// частичный результат без явной причины хуже честной остановки; отчёт возвращается всегда. +func (rc *Reconciler) Run(ctx context.Context) (*Report, error) { + opts := rc.Opts + if opts.PageSize <= 0 || opts.PageSize > defaultPageSize { + opts.PageSize = defaultPageSize + } + if opts.Now == nil { + opts.Now = time.Now + } + if opts.Logf == nil { + opts.Logf = func(string, ...any) {} + } + rep := &Report{ + DryRun: opts.DryRun, + GraceSeconds: opts.Grace.Seconds(), + PruneMissing: opts.PruneMissing, + } + start := time.Now() + defer func() { rep.DurationMs = time.Since(start).Milliseconds() }() + + run := &run{rc: rc, opts: opts, rep: rep} + err := run.mergeJoin(ctx) + return rep, err +} + +type run struct { + rc *Reconciler + opts Options + rep *Report +} + +// s3Cursor / dbCursor — «ленивые» итераторы по страницам с peek/advance. +type s3Cursor struct { + page []objectstore.ObjectInfo + idx int + token string + begun bool + done bool +} + +type dbCursor struct { + page []store.AttachmentRef + idx int + after string + done bool +} + +func (r *run) peekS3(ctx context.Context, c *s3Cursor) (*objectstore.ObjectInfo, error) { + for c.idx >= len(c.page) { + if c.done { + return nil, nil + } + if c.begun && c.token == "" { + c.done = true + return nil, nil + } + p, err := r.rc.Objects.List(ctx, KeyPrefix, c.token, int32(r.opts.PageSize)) + if err != nil { + return nil, fmt.Errorf("list s3: %w", err) + } + r.rep.S3ListCalls++ + c.begun, c.page, c.idx, c.token = true, p.Objects, 0, p.NextToken + if len(p.Objects) == 0 && p.NextToken == "" { + c.done = true + return nil, nil + } + } + return &c.page[c.idx], nil +} + +func (r *run) peekDB(ctx context.Context, c *dbCursor) (*store.AttachmentRef, error) { + for c.idx >= len(c.page) { + if c.done { + return nil, nil + } + rows, err := r.rc.DB.ListAttachmentRefsAfter(ctx, c.after, r.opts.PageSize) + if err != nil { + return nil, fmt.Errorf("list db: %w", err) + } + r.rep.DBPages++ + if len(rows) == 0 { + c.done = true + return nil, nil + } + c.page, c.idx = rows, 0 + c.after = rows[len(rows)-1].ObjectKey + } + return &c.page[c.idx], nil +} + +func (r *run) mergeJoin(ctx context.Context) error { + s3c, dbc := &s3Cursor{}, &dbCursor{} + for { + if err := ctx.Err(); err != nil { + return err + } + o, err := r.peekS3(ctx, s3c) + if err != nil { + r.rep.Errors++ + return err + } + d, err := r.peekDB(ctx, dbc) + if err != nil { + r.rep.Errors++ + return err + } + if o == nil && d == nil { + return nil + } + switch { + case d == nil || (o != nil && o.Key < d.ObjectKey): + // Ключ есть в S3, а в БД его нет → кандидат в orphan. + r.rep.S3ObjectsScanned++ + if err := r.handleOrphanCandidate(ctx, *o); err != nil { + r.rep.Errors++ + return err + } + s3c.idx++ + case o == nil || d.ObjectKey < o.Key: + // Строка есть, объекта нет → кандидат в missing. + r.rep.DBRowsScanned++ + if err := r.handleMissingCandidate(ctx, *d); err != nil { + r.rep.Errors++ + return err + } + dbc.idx++ + default: + // Ключи равны: всё согласовано. + r.rep.S3ObjectsScanned++ + r.rep.DBRowsScanned++ + r.rep.Matched++ + s3c.idx++ + dbc.idx++ + } + } +} + +func (r *run) handleOrphanCandidate(ctx context.Context, o objectstore.ObjectInfo) error { + // Чужие/неожиданные ключи не трогаем вообще: reconciler знает только свою схему ключей. + if !validAttachmentKey(o.Key) { + r.rep.UnknownKeys++ + r.opts.Logf("SKIP unknown key (вне схемы attachments/{uuid}/{uuid}): %s", o.Key) + return nil + } + age := r.opts.Now().Sub(o.LastModified) + if age < r.opts.Grace { + // PUT был недавно: INSERT мог ещё не закоммититься. Не трогаем. + r.rep.OrphansFresh++ + r.opts.Logf("SKIP fresh orphan (age=%s < grace=%s): %s", age.Round(time.Second), r.opts.Grace, o.Key) + return nil + } + // Повторная проверка непосредственно перед удалением: за время прохода строка + // могла появиться (долгая загрузка, медленный INSERT). + exists, err := r.rc.DB.AttachmentKeyExists(ctx, o.Key) + if err != nil { + return fmt.Errorf("recheck db: %w", err) + } + if exists { + r.rep.OrphansRaced++ + return nil + } + r.rep.OrphansFound++ + r.sample(&r.rep.OrphanSampleKey, o.Key) + if r.opts.DryRun { + r.opts.Logf("DRY-RUN would delete orphan (age=%s, size=%d): %s", age.Round(time.Second), o.Size, o.Key) + return nil + } + r.rep.DeleteCalls++ + if err := r.rc.Objects.Delete(ctx, o.Key); err != nil { + return fmt.Errorf("delete orphan: %w", err) + } + r.rep.OrphansDeleted++ + r.opts.Logf("DELETED orphan (age=%s, size=%d): %s", age.Round(time.Second), o.Size, o.Key) + return nil +} + +func (r *run) handleMissingCandidate(ctx context.Context, d store.AttachmentRef) error { + // Подтверждаем HEAD: листинг S3 и страница БД читались в разные моменты, поэтому + // «нет в листинге» ещё не значит «нет в S3» (загрузка могла завершиться между ними). + r.rep.HeadCalls++ + _, err := r.rc.Objects.Head(ctx, d.ObjectKey) + switch { + case err == nil: + r.rep.MissingRaced++ + return nil + case errors.Is(err, objectstore.ErrNotFound): + // действительно отсутствует — идём дальше + default: + return fmt.Errorf("head: %w", err) + } + + r.rep.MissingFound++ + r.sample(&r.rep.MissingSample, d.ObjectKey) + age := r.opts.Now().Sub(d.CreatedAt) + switch { + case d.Used: + // Вложение прикреплено к сообщению, а байт нет: потеря данных. Автоматически не чиним + // и не удаляем строку (иначе сообщение осталось бы со ссылкой в никуда). + r.rep.MissingUsed++ + r.opts.Logf("ALERT used attachment lost its object (id=%s, не удаляется): %s", d.ID, d.ObjectKey) + case age < r.opts.Grace: + r.rep.MissingFresh++ + r.opts.Logf("SKIP fresh missing (age=%s < grace=%s): %s", age.Round(time.Second), r.opts.Grace, d.ObjectKey) + default: + r.rep.MissingStale++ + switch { + case r.opts.DryRun: + r.opts.Logf("DRY-RUN missing object, unused stale row (id=%s)%s: %s", d.ID, pruneHint(r.opts.PruneMissing), d.ObjectKey) + case !r.opts.PruneMissing: + r.opts.Logf("REPORT missing object, unused stale row (id=%s), prune выключен: %s", d.ID, d.ObjectKey) + default: + // Удаление защищено условиями created_at < cutoff и NOT EXISTS ссылок в SQL. + deleted, err := r.rc.DB.DeleteUnusedAttachment(ctx, d.ID, r.opts.Now().Add(-r.opts.Grace)) + if err != nil { + return fmt.Errorf("prune row: %w", err) + } + if deleted { + r.rep.MissingPruned++ + r.opts.Logf("PRUNED row without object (id=%s): %s", d.ID, d.ObjectKey) + } + } + } + return nil +} + +func pruneHint(prune bool) string { + if prune { + return " would be pruned" + } + return " (prune off, report only)" +} + +func (r *run) sample(dst *[]string, key string) { + if len(*dst) < maxSamples { + *dst = append(*dst, key) + } +} + +// validAttachmentKey — ключ строго вида attachments/{uuid}/{uuid} в каноническом написании. +func validAttachmentKey(key string) bool { + rest, ok := cutPrefix(key, KeyPrefix) + if !ok { + return false + } + var chat, att string + for i := 0; i < len(rest); i++ { + if rest[i] == '/' { + chat, att = rest[:i], rest[i+1:] + break + } + } + if chat == "" || att == "" { + return false + } + c, err1 := uuid.Parse(chat) + a, err2 := uuid.Parse(att) + return err1 == nil && err2 == nil && c.String() == chat && a.String() == att +} + +func cutPrefix(s, prefix string) (string, bool) { + if len(s) >= len(prefix) && s[:len(prefix)] == prefix { + return s[len(prefix):], true + } + return s, false +} diff --git a/internal/session/redis.go b/internal/session/redis.go new file mode 100644 index 00000000..ee6d98d2 --- /dev/null +++ b/internal/session/redis.go @@ -0,0 +1,135 @@ +// Package session хранит opaque Bearer-сессии в Redis. +// +// PostgreSQL остаётся источником истины для пользователей и сообщений. +// Сессия — отдельная роль: случайный токен, срок жизни SESSION_TTL_SECONDS и отзыв. +// В Redis лежит не сам токен, а его SHA-256: дамп AOF не содержит значение, +// которое клиент предъявляет в Authorization. +// +// TTL ключа равен оставшемуся сроку сессии. Рестарт API его не продлевает. +// Рестарт Redis сессию сохраняет только потому, что включён AOF на volume. +package session + +import ( + "context" + "crypto/rand" + "crypto/sha256" + "encoding/hex" + "errors" + "fmt" + "strings" + "time" + + "github.com/google/uuid" + "github.com/redis/go-redis/v9" +) + +var ( + ErrUnauthorized = errors.New("unauthorized") + ErrUnavailable = errors.New("unavailable") +) + +// Store — клиент Redis с короткими таймаутами. +type Store struct { + client *redis.Client + ttl time.Duration +} + +// Open разбирает redis:// URL. Пароль в лог не пишется. +func Open(redisURL string, ttl time.Duration) (*Store, error) { + opt, err := redis.ParseURL(redisURL) + if err != nil { + return nil, fmt.Errorf("parse redis url: %w", err) + } + opt.DialTimeout = 500 * time.Millisecond + opt.ReadTimeout = 500 * time.Millisecond + opt.WriteTimeout = 500 * time.Millisecond + opt.PoolSize = 20 + client := redis.NewClient(opt) + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + if err := client.Ping(ctx).Err(); err != nil { + _ = client.Close() + return nil, err + } + return &Store{client: client, ttl: ttl}, nil +} + +// Close закрывает пул при остановке процесса. +func (s *Store) Close() error { + return s.client.Close() +} + +// Ping — готовность кэша сессий. Недоступный Redis не означает «анонимный доступ». +func (s *Store) Ping(ctx context.Context) error { + ctx, cancel := context.WithTimeout(ctx, 300*time.Millisecond) + defer cancel() + if err := s.client.Ping(ctx).Err(); err != nil { + return ErrUnavailable + } + return nil +} + +// Issue выпускает 256 бит случайности (32 байта) и кладёт сессию с TTL. +// Наружу уходит hex (64 символа). В Redis — только хеш. +func (s *Store) Issue(ctx context.Context, userID uuid.UUID) (token string, expiresAt time.Time, err error) { + buf := make([]byte, 32) + if _, err = rand.Read(buf); err != nil { + return "", time.Time{}, err + } + token = hex.EncodeToString(buf) + expiresAt = time.Now().UTC().Add(s.ttl).Truncate(time.Millisecond) + value := userID.String() + "|" + expiresAt.Format(time.RFC3339Nano) + ctx, cancel := context.WithTimeout(ctx, time.Second) + defer cancel() + if err = s.client.Set(ctx, key(token), value, time.Until(expiresAt)).Err(); err != nil { + return "", time.Time{}, ErrUnavailable + } + return token, expiresAt, nil +} + +// Lookup возвращает владельца живой сессии. +// Промах и истёкший срок — ErrUnauthorized. Сбой Redis — ErrUnavailable (HTTP 503). +func (s *Store) Lookup(ctx context.Context, token string) (uuid.UUID, error) { + ctx, cancel := context.WithTimeout(ctx, time.Second) + defer cancel() + raw, err := s.client.Get(ctx, key(token)).Result() + if errors.Is(err, redis.Nil) { + return uuid.Nil, ErrUnauthorized + } + if err != nil { + return uuid.Nil, ErrUnavailable + } + userPart, expPart, ok := strings.Cut(raw, "|") + if !ok { + return uuid.Nil, ErrUnauthorized + } + exp, err := time.Parse(time.RFC3339Nano, expPart) + if err != nil || !exp.After(time.Now()) { + _ = s.client.Del(ctx, key(token)).Err() + return uuid.Nil, ErrUnauthorized + } + id, err := uuid.Parse(userPart) + if err != nil { + return uuid.Nil, ErrUnauthorized + } + return id, nil +} + +// Revoke удаляет текущую сессию. Повторный отзыв — это уже отсутствие ключа. +func (s *Store) Revoke(ctx context.Context, token string) error { + ctx, cancel := context.WithTimeout(ctx, time.Second) + defer cancel() + n, err := s.client.Del(ctx, key(token)).Result() + if err != nil { + return ErrUnavailable + } + if n == 0 { + return ErrUnauthorized + } + return nil +} + +func key(token string) string { + sum := sha256.Sum256([]byte(token)) + return "sess:" + hex.EncodeToString(sum[:]) +} diff --git a/internal/store/attachments.go b/internal/store/attachments.go new file mode 100644 index 00000000..2bbf6851 --- /dev/null +++ b/internal/store/attachments.go @@ -0,0 +1,301 @@ +// Метаданные вложений (lab4): таблицы attachments и message_attachments. +// +// Разделение ответственности: +// - байты оригинала лежат в приватном S3-bucket по ключу attachments/{chat}/{id}; +// - здесь — всё остальное: чат, владелец, имя для показа, тип, размер, sha256, ключ. +// +// Порядок «PUT в S3, потом INSERT здесь» выбран намеренно (см. api/attachments.go): +// при сбое между шагами остаётся лишний ОБЪЕКТ (его безопасно убирает reconciler), +// а не строка без файла (она бы отдавала пользователю ошибку при скачивании). +package store + +import ( + "context" + "errors" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5" +) + +// StatusReady — единственный статус lab4: 201 возвращается только после сохранения +// и оригинала в S3, и метаданных в PostgreSQL. +const StatusReady = "ready" + +// Attachment — строка таблицы attachments. +type Attachment struct { + ID uuid.UUID + ChatID uuid.UUID + OwnerID uuid.UUID + Filename string + ContentType string // image/png | image/jpeg, определён по содержимому + SizeBytes int64 + SHA256 string // lowercase hex + ObjectKey string // внутренний, клиенту не отдаётся + Status string + ErrorCode *string + Width int + Height int + CreatedAt time.Time + UpdatedAt time.Time +} + +// AttachmentObjectKey строит ключ объекта. Ключ целиком определяется сервером: +// имя файла клиента в нём не участвует (нет path traversal и коллизий имён), +// а префикс chat-id группирует объекты чата для будущей очистки. +func AttachmentObjectKey(chatID, attachmentID uuid.UUID) string { + return "attachments/" + chatID.String() + "/" + attachmentID.String() +} + +// CreateAttachment вставляет метаданные уже загруженного в S3 объекта. +// +// INSERT ... SELECT ... WHERE EXISTS проверяет членство атомарно с вставкой: +// между «проверили участие» в HTTP-слое и записью строки состав чата мог бы измениться, +// а так условие и запись — один оператор. 0 строк → ErrNotFound (404). +func (s *Store) CreateAttachment(ctx context.Context, a *Attachment) error { + if a.CreatedAt.IsZero() { + // Миллисекундная точность — та же, что печатается в JSON. + a.CreatedAt = nowUTC() + } + if a.Status == "" { + a.Status = StatusReady + } + ctx, cancel := context.WithTimeout(ctx, queryTimeout) + defer cancel() + tag, err := s.pool.Exec(ctx, ` + INSERT INTO attachments ( + id, chat_id, owner_id, filename, content_type, size_bytes, sha256, + object_key, status, error_code, width, height, created_at, updated_at) + SELECT $1, $2, $3, $4, $5, $6, $7, $8, $9, NULL, $10, $11, $12, $12 + WHERE EXISTS (SELECT 1 FROM chat_members WHERE chat_id = $2 AND user_id = $3)`, + a.ID, a.ChatID, a.OwnerID, a.Filename, a.ContentType, a.SizeBytes, a.SHA256, + a.ObjectKey, a.Status, a.Width, a.Height, a.CreatedAt) + if err != nil { + return mapWriteErr(err) + } + if tag.RowsAffected() != 1 { + return ErrNotFound + } + a.UpdatedAt = a.CreatedAt + return nil +} + +// GetAttachmentForUser возвращает вложение ТОЛЬКО участнику его чата. +// Чужое и несуществующее неразличимы (ErrNotFound → 404, не 403): иначе можно было +// бы по коду ответа проверять, существует ли чужой файл. +func (s *Store) GetAttachmentForUser(ctx context.Context, id, userID uuid.UUID) (*Attachment, error) { + ctx, cancel := context.WithTimeout(ctx, queryTimeout) + defer cancel() + var a Attachment + err := s.pool.QueryRow(ctx, ` + SELECT a.id, a.chat_id, a.owner_id, a.filename, a.content_type, a.size_bytes, + a.sha256, a.object_key, a.status, a.error_code, a.width, a.height, + a.created_at, a.updated_at + FROM attachments a + JOIN chat_members m ON m.chat_id = a.chat_id AND m.user_id = $2 + WHERE a.id = $1`, id, userID).Scan( + &a.ID, &a.ChatID, &a.OwnerID, &a.Filename, &a.ContentType, &a.SizeBytes, + &a.SHA256, &a.ObjectKey, &a.Status, &a.ErrorCode, &a.Width, &a.Height, + &a.CreatedAt, &a.UpdatedAt) + if errors.Is(err, pgx.ErrNoRows) { + return nil, ErrNotFound + } + if err != nil { + return nil, mapWriteErr(err) + } + return &a, nil +} + +// CountAttachmentsInChat нужен тестам: после отказа S3/PG в чате не должно оставаться +// «полуфабрикатов» (строк метаданных без успешной загрузки). +func (s *Store) CountAttachmentsInChat(ctx context.Context, chatID uuid.UUID) (int, error) { + ctx, cancel := context.WithTimeout(ctx, queryTimeout) + defer cancel() + var n int + if err := s.pool.QueryRow(ctx, `SELECT count(*) FROM attachments WHERE chat_id = $1`, chatID).Scan(&n); err != nil { + return 0, mapWriteErr(err) + } + return n, nil +} + +// querier — общая часть pgx.Tx и pgxpool.Pool: так одни и те же функции читают +// связи сообщений и внутри транзакции (идемпотентный replay), и вне её (история). +type querier interface { + Query(ctx context.Context, sql string, args ...any) (pgx.Rows, error) +} + +// lockMessageAttachments проверяет вложения будущего сообщения внутри его транзакции. +// +// - WHERE id = ANY($1) AND chat_id = $2: вложение другого чата и несуществующее +// одинаково «не находятся» → ErrNotFound (404). Это и есть привязка файла к чату. +// - FOR SHARE блокирует найденные строки до COMMIT: параллельное удаление +// (reconciler) подождёт и затем упрётся в внешний ключ message_attachments. +// - Если нашлось меньше строк, чем запрошено, — хотя бы одно чужое/неизвестное. +// - Любой статус, кроме ready, → ErrAttachmentNotReady (409). +// +// ids уже проверены HTTP-слоем на уникальность и количество (≤10). +func lockMessageAttachments(ctx context.Context, tx pgx.Tx, chatID uuid.UUID, ids []uuid.UUID) error { + if len(ids) == 0 { + return nil + } + rows, err := tx.Query(ctx, ` + SELECT id, status FROM attachments + WHERE id = ANY($1) AND chat_id = $2 + ORDER BY id + FOR SHARE`, ids, chatID) + if err != nil { + return mapWriteErr(err) + } + defer rows.Close() + found, notReady := 0, false + for rows.Next() { + var id uuid.UUID + var status string + if err := rows.Scan(&id, &status); err != nil { + return mapWriteErr(err) + } + found++ + if status != StatusReady { + notReady = true + } + } + if err := rows.Err(); err != nil { + return mapWriteErr(err) + } + rows.Close() + if found != len(ids) { + return ErrNotFound + } + if notReady { + return ErrAttachmentNotReady + } + return nil +} + +// loadMessageAttachmentIDs — вложения одного сообщения в исходном порядке (position). +// Никогда не возвращает nil: пустой срез сериализуется в [], а не в null. +func loadMessageAttachmentIDs(ctx context.Context, q querier, messageID uuid.UUID) ([]uuid.UUID, error) { + byMsg, err := attachmentIDsByMessage(ctx, q, []uuid.UUID{messageID}) + if err != nil { + return nil, err + } + return byMsg[messageID], nil +} + +// attachmentIDsByMessage одним запросом читает связи для набора сообщений. +// Для сообщений без вложений вернётся пустой (не nil) срез. +func attachmentIDsByMessage(ctx context.Context, q querier, messageIDs []uuid.UUID) (map[uuid.UUID][]uuid.UUID, error) { + out := make(map[uuid.UUID][]uuid.UUID, len(messageIDs)) + for _, id := range messageIDs { + out[id] = []uuid.UUID{} + } + if len(messageIDs) == 0 { + return out, nil + } + rows, err := q.Query(ctx, ` + SELECT message_id, attachment_id + FROM message_attachments + WHERE message_id = ANY($1) + ORDER BY message_id, position`, messageIDs) + if err != nil { + return nil, mapWriteErr(err) + } + defer rows.Close() + for rows.Next() { + var mid, aid uuid.UUID + if err := rows.Scan(&mid, &aid); err != nil { + return nil, mapWriteErr(err) + } + out[mid] = append(out[mid], aid) + } + return out, mapWriteErr(rows.Err()) +} + +// attachMessageAttachments дозаполняет AttachmentIDs у страницы сообщений (ListMessages). +func (s *Store) attachMessageAttachments(ctx context.Context, items []Message) error { + if len(items) == 0 { + return nil + } + ids := make([]uuid.UUID, len(items)) + for i := range items { + ids[i] = items[i].ID + } + byMsg, err := attachmentIDsByMessage(ctx, s.pool, ids) + if err != nil { + return err + } + for i := range items { + items[i].AttachmentIDs = byMsg[items[i].ID] + } + return nil +} + +// --------------------------------------------------------------------------- +// Методы для reconciler (internal/reconcile). Они здесь, а не в reconcile, потому +// что SQL и работа с пулом принадлежат пакету store. +// --------------------------------------------------------------------------- + +// AttachmentRef — минимальная информация о строке для сверки с S3. +type AttachmentRef struct { + ID uuid.UUID + ObjectKey string + CreatedAt time.Time + // Used — на вложение ссылается хотя бы одно сообщение. Такое вложение удалять нельзя. + Used bool +} + +// ListAttachmentRefsAfter — keyset-страница строк в байтовом порядке object_key +// (колонка COLLATE "C" — порядок совпадает с листингом S3). afterKey="" — с начала. +func (s *Store) ListAttachmentRefsAfter(ctx context.Context, afterKey string, limit int) ([]AttachmentRef, error) { + ctx, cancel := context.WithTimeout(ctx, queryTimeout) + defer cancel() + rows, err := s.pool.Query(ctx, ` + SELECT a.id, a.object_key, a.created_at, + EXISTS (SELECT 1 FROM message_attachments ma WHERE ma.attachment_id = a.id) + FROM attachments a + WHERE a.object_key > $1 + ORDER BY a.object_key + LIMIT $2`, afterKey, limit) + if err != nil { + return nil, mapWriteErr(err) + } + defer rows.Close() + var out []AttachmentRef + for rows.Next() { + var r AttachmentRef + if err := rows.Scan(&r.ID, &r.ObjectKey, &r.CreatedAt, &r.Used); err != nil { + return nil, mapWriteErr(err) + } + out = append(out, r) + } + return out, mapWriteErr(rows.Err()) +} + +// AttachmentKeyExists — повторная проверка непосредственно перед удалением orphan-объекта: +// сужает окно гонки «reconciler решил, что строки нет, а загрузка как раз сделала INSERT». +func (s *Store) AttachmentKeyExists(ctx context.Context, key string) (bool, error) { + ctx, cancel := context.WithTimeout(ctx, queryTimeout) + defer cancel() + var ok bool + err := s.pool.QueryRow(ctx, `SELECT EXISTS (SELECT 1 FROM attachments WHERE object_key = $1)`, key).Scan(&ok) + return ok, mapWriteErr(err) +} + +// DeleteUnusedAttachment удаляет строку вложения, только если выполнены ОБА условия: +// она старше olderThan (не «свежая») и на неё нет ссылок из сообщений (не «используемая»). +// Возвращает true, если строка удалена. Внешний ключ message_attachments страхует +// от гонки с параллельной отправкой сообщения: такой DELETE упадёт, а не потеряет данные. +func (s *Store) DeleteUnusedAttachment(ctx context.Context, id uuid.UUID, olderThan time.Time) (bool, error) { + ctx, cancel := context.WithTimeout(ctx, queryTimeout) + defer cancel() + tag, err := s.pool.Exec(ctx, ` + DELETE FROM attachments a + WHERE a.id = $1 + AND a.created_at < $2 + AND NOT EXISTS (SELECT 1 FROM message_attachments ma WHERE ma.attachment_id = a.id)`, + id, olderThan) + if err != nil { + return false, mapWriteErr(err) + } + return tag.RowsAffected() == 1, nil +} diff --git a/internal/store/migrate.go b/internal/store/migrate.go new file mode 100644 index 00000000..bbeeb2a7 --- /dev/null +++ b/internal/store/migrate.go @@ -0,0 +1,84 @@ +package store + +import ( + "context" + "embed" + "fmt" + "sort" + "strings" + "time" +) + +//go:embed migrations/*.sql +var migrationFS embed.FS + +// Migrate применяет встроенные SQL-файлы по одному разу. +// Повторный старт процесса не создаёт вторую копию строк: версия пишется в schema_migrations. +func (s *Store) Migrate(ctx context.Context) error { + ctx, cancel := context.WithTimeout(ctx, 30*time.Second) + defer cancel() + if _, err := s.pool.Exec(ctx, ` + CREATE TABLE IF NOT EXISTS schema_migrations ( + version text PRIMARY KEY, + applied_at timestamptz NOT NULL DEFAULT now() + )`); err != nil { + return fmt.Errorf("schema_migrations: %w", err) + } + entries, err := migrationFS.ReadDir("migrations") + if err != nil { + return err + } + names := make([]string, 0, len(entries)) + for _, e := range entries { + if !e.IsDir() && strings.HasSuffix(e.Name(), ".sql") { + names = append(names, e.Name()) + } + } + sort.Strings(names) + for _, name := range names { + var exists bool + if err := s.pool.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM schema_migrations WHERE version = $1)`, name).Scan(&exists); err != nil { + return err + } + if exists { + continue + } + body, err := migrationFS.ReadFile("migrations/" + name) + if err != nil { + return err + } + tx, err := s.pool.Begin(ctx) + if err != nil { + return err + } + // pgx в extended protocol не выполняет несколько команд одним Exec. + for _, stmt := range splitSQL(string(body)) { + if _, err := tx.Exec(ctx, stmt); err != nil { + _ = tx.Rollback(ctx) + return fmt.Errorf("migrate %s: %w", name, err) + } + } + if _, err := tx.Exec(ctx, `INSERT INTO schema_migrations (version) VALUES ($1)`, name); err != nil { + _ = tx.Rollback(ctx) + return err + } + if err := tx.Commit(ctx); err != nil { + return err + } + } + return nil +} + +// splitSQL делит файл миграции по ';'. В этих файлах нет строк с точкой с запятой внутри литералов. +func splitSQL(body string) []string { + parts := strings.Split(body, ";") + out := make([]string, 0, len(parts)) + for _, part := range parts { + stmt := strings.TrimSpace(part) + if stmt == "" { + continue + } + out = append(out, stmt) + } + return out +} diff --git a/internal/store/migrations/001_init.sql b/internal/store/migrations/001_init.sql new file mode 100644 index 00000000..205bc6a7 --- /dev/null +++ b/internal/store/migrations/001_init.sql @@ -0,0 +1,49 @@ +-- Схема lab2. PostgreSQL — источник истины для пользователей, чатов и сообщений. +-- Сессии здесь намеренно нет: их держит Redis с AOF, TTL не продлевается рестартом API. +-- Повторный запуск безопасен: все объекты создаются через IF NOT EXISTS. + +CREATE TABLE IF NOT EXISTS schema_migrations ( + version text PRIMARY KEY, + applied_at timestamptz NOT NULL DEFAULT now() +); + +CREATE TABLE IF NOT EXISTS users ( + id uuid PRIMARY KEY, + username text NOT NULL, + display_name text NOT NULL, + -- Argon2id PHC-строка. Не SHA-256 и не plaintext. Наружу не отдаётся. + password_hash text NOT NULL, + created_at timestamptz NOT NULL, + CONSTRAINT users_username_unique UNIQUE (username) +); + +CREATE TABLE IF NOT EXISTS chats ( + id uuid PRIMARY KEY, + title text NOT NULL, + created_at timestamptz NOT NULL +); + +-- Составной первичный ключ не даёт вставить участника дважды. +-- Внешние ключи не дают сослаться на несуществующего пользователя или чат. +CREATE TABLE IF NOT EXISTS chat_members ( + chat_id uuid NOT NULL REFERENCES chats (id), + user_id uuid NOT NULL REFERENCES users (id), + PRIMARY KEY (chat_id, user_id) +); + +-- Список чатов пользователя начинается с фильтра «где я участник». +CREATE INDEX IF NOT EXISTS chat_members_user_idx ON chat_members (user_id); + +CREATE TABLE IF NOT EXISTS messages ( + id uuid PRIMARY KEY, + chat_id uuid NOT NULL REFERENCES chats (id), + sender_id uuid NOT NULL REFERENCES users (id), + text text NOT NULL, + created_at timestamptz NOT NULL +); + +-- Keyset истории: WHERE chat_id = ? AND (created_at, id) > (?, ?) ORDER BY created_at, id. +-- Составной индекс покрывает и фильтр, и порядок. Слабый индекс только по chat_id +-- заставил бы сортировать историю чата. Его нет в продовой схеме, он появляется +-- лишь на время эксперимента трека 2. +CREATE INDEX IF NOT EXISTS messages_history_idx ON messages (chat_id, created_at, id); diff --git a/internal/store/migrations/002_idempotency.sql b/internal/store/migrations/002_idempotency.sql new file mode 100644 index 00000000..b03c86a5 --- /dev/null +++ b/internal/store/migrations/002_idempotency.sql @@ -0,0 +1,23 @@ +-- Идемпотентность POST сообщения (lab3). +-- Область ключа: (user_id, method, path, key). +-- Разные пользователи и чаты могут независимо использовать одну строку Idempotency-Key. +-- request_hash — SHA-256 канонического тела. +-- Другой body при том же ключе даёт HTTP 409. +-- response_* фиксируются только для успешного 201 в той же транзакции, что и INSERT messages. +-- Транзиентный 5xx не сохраняется как окончательный результат. + +CREATE TABLE IF NOT EXISTS idempotency_keys ( + user_id uuid NOT NULL REFERENCES users (id), + method text NOT NULL, + path text NOT NULL, + key text NOT NULL, + request_hash text NOT NULL, + response_status integer NOT NULL, + response_body jsonb NOT NULL, + message_id uuid NOT NULL REFERENCES messages (id), + created_at timestamptz NOT NULL, + PRIMARY KEY (user_id, method, path, key) +); + +-- Индекс по времени — для будущей очистки хвоста старше 24 часов. +CREATE INDEX IF NOT EXISTS idempotency_keys_created_idx ON idempotency_keys (created_at); diff --git a/internal/store/migrations/003_attachments.sql b/internal/store/migrations/003_attachments.sql new file mode 100644 index 00000000..818319fd --- /dev/null +++ b/internal/store/migrations/003_attachments.sql @@ -0,0 +1,47 @@ +-- Вложения lab4. Метаданные - в PostgreSQL, байты - в приватном S3-bucket (MinIO). +-- Ключ объекта назначает сервер: attachments/{chat_id}/{attachment_id}. +-- filename - только отображаемое имя, в ключ и в путь не попадает. +-- +-- ВНИМАНИЕ: файл режется по символу точки с запятой (см. splitSQL в migrate.go), +-- поэтому в комментариях и литералах здесь нет этого символа. + +CREATE TABLE IF NOT EXISTS attachments ( + id uuid PRIMARY KEY, + -- Файл заранее привязан к чату: доступ к нему определяется членством в этом чате. + chat_id uuid NOT NULL REFERENCES chats (id), + owner_id uuid NOT NULL REFERENCES users (id), + filename text NOT NULL, + -- Тип определён по СОДЕРЖИМОМУ файла, а не по заголовку запроса. + content_type text NOT NULL CHECK (content_type IN ('image/png', 'image/jpeg')), + size_bytes bigint NOT NULL CHECK (size_bytes BETWEEN 1 AND 10485760), + -- lowercase hex SHA-256 оригинала. + sha256 text NOT NULL CHECK (sha256 ~ '^[a-f0-9]{64}$'), + -- COLLATE "C": байтовый порядок совпадает с лексикографическим порядком ListObjectsV2. + -- Reconciler сливает два отсортированных потока (S3 и эта колонка) без загрузки в память. + object_key text COLLATE "C" NOT NULL, + -- lab4 знает только ready (201 после сохранения байтов и метаданных). + -- Состояния queued/processing/failed появятся в lab5+ расширением CHECK. + status text NOT NULL DEFAULT 'ready' CHECK (status IN ('ready')), + error_code text, + width integer NOT NULL CHECK (width > 0), + height integer NOT NULL CHECK (height > 0), + created_at timestamptz NOT NULL, + updated_at timestamptz NOT NULL, + CONSTRAINT attachments_object_key_unique UNIQUE (object_key) +); + +-- Проверка вложений сообщения идёт по PK, индекс по чату нужен списку и будущей очистке. +CREATE INDEX IF NOT EXISTS attachments_chat_idx ON attachments (chat_id); + +-- Связь сообщение - вложение. position хранит порядок attachment_ids из запроса. +-- Одно вложение можно прикрепить к нескольким сообщениям своего чата (контракт не запрещает). +-- Внешние ключи не дают удалить вложение, на которое ссылается сообщение: reconciler +-- физически не может снести «используемое» вложение даже при ошибке в его логике. +CREATE TABLE IF NOT EXISTS message_attachments ( + message_id uuid NOT NULL REFERENCES messages (id), + attachment_id uuid NOT NULL REFERENCES attachments (id), + position smallint NOT NULL CHECK (position >= 0), + PRIMARY KEY (message_id, attachment_id) +); + +CREATE INDEX IF NOT EXISTS message_attachments_attachment_idx ON message_attachments (attachment_id) diff --git a/internal/store/migrations/attachments.go b/internal/store/migrations/attachments.go new file mode 100644 index 00000000..2bbf6851 --- /dev/null +++ b/internal/store/migrations/attachments.go @@ -0,0 +1,301 @@ +// Метаданные вложений (lab4): таблицы attachments и message_attachments. +// +// Разделение ответственности: +// - байты оригинала лежат в приватном S3-bucket по ключу attachments/{chat}/{id}; +// - здесь — всё остальное: чат, владелец, имя для показа, тип, размер, sha256, ключ. +// +// Порядок «PUT в S3, потом INSERT здесь» выбран намеренно (см. api/attachments.go): +// при сбое между шагами остаётся лишний ОБЪЕКТ (его безопасно убирает reconciler), +// а не строка без файла (она бы отдавала пользователю ошибку при скачивании). +package store + +import ( + "context" + "errors" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5" +) + +// StatusReady — единственный статус lab4: 201 возвращается только после сохранения +// и оригинала в S3, и метаданных в PostgreSQL. +const StatusReady = "ready" + +// Attachment — строка таблицы attachments. +type Attachment struct { + ID uuid.UUID + ChatID uuid.UUID + OwnerID uuid.UUID + Filename string + ContentType string // image/png | image/jpeg, определён по содержимому + SizeBytes int64 + SHA256 string // lowercase hex + ObjectKey string // внутренний, клиенту не отдаётся + Status string + ErrorCode *string + Width int + Height int + CreatedAt time.Time + UpdatedAt time.Time +} + +// AttachmentObjectKey строит ключ объекта. Ключ целиком определяется сервером: +// имя файла клиента в нём не участвует (нет path traversal и коллизий имён), +// а префикс chat-id группирует объекты чата для будущей очистки. +func AttachmentObjectKey(chatID, attachmentID uuid.UUID) string { + return "attachments/" + chatID.String() + "/" + attachmentID.String() +} + +// CreateAttachment вставляет метаданные уже загруженного в S3 объекта. +// +// INSERT ... SELECT ... WHERE EXISTS проверяет членство атомарно с вставкой: +// между «проверили участие» в HTTP-слое и записью строки состав чата мог бы измениться, +// а так условие и запись — один оператор. 0 строк → ErrNotFound (404). +func (s *Store) CreateAttachment(ctx context.Context, a *Attachment) error { + if a.CreatedAt.IsZero() { + // Миллисекундная точность — та же, что печатается в JSON. + a.CreatedAt = nowUTC() + } + if a.Status == "" { + a.Status = StatusReady + } + ctx, cancel := context.WithTimeout(ctx, queryTimeout) + defer cancel() + tag, err := s.pool.Exec(ctx, ` + INSERT INTO attachments ( + id, chat_id, owner_id, filename, content_type, size_bytes, sha256, + object_key, status, error_code, width, height, created_at, updated_at) + SELECT $1, $2, $3, $4, $5, $6, $7, $8, $9, NULL, $10, $11, $12, $12 + WHERE EXISTS (SELECT 1 FROM chat_members WHERE chat_id = $2 AND user_id = $3)`, + a.ID, a.ChatID, a.OwnerID, a.Filename, a.ContentType, a.SizeBytes, a.SHA256, + a.ObjectKey, a.Status, a.Width, a.Height, a.CreatedAt) + if err != nil { + return mapWriteErr(err) + } + if tag.RowsAffected() != 1 { + return ErrNotFound + } + a.UpdatedAt = a.CreatedAt + return nil +} + +// GetAttachmentForUser возвращает вложение ТОЛЬКО участнику его чата. +// Чужое и несуществующее неразличимы (ErrNotFound → 404, не 403): иначе можно было +// бы по коду ответа проверять, существует ли чужой файл. +func (s *Store) GetAttachmentForUser(ctx context.Context, id, userID uuid.UUID) (*Attachment, error) { + ctx, cancel := context.WithTimeout(ctx, queryTimeout) + defer cancel() + var a Attachment + err := s.pool.QueryRow(ctx, ` + SELECT a.id, a.chat_id, a.owner_id, a.filename, a.content_type, a.size_bytes, + a.sha256, a.object_key, a.status, a.error_code, a.width, a.height, + a.created_at, a.updated_at + FROM attachments a + JOIN chat_members m ON m.chat_id = a.chat_id AND m.user_id = $2 + WHERE a.id = $1`, id, userID).Scan( + &a.ID, &a.ChatID, &a.OwnerID, &a.Filename, &a.ContentType, &a.SizeBytes, + &a.SHA256, &a.ObjectKey, &a.Status, &a.ErrorCode, &a.Width, &a.Height, + &a.CreatedAt, &a.UpdatedAt) + if errors.Is(err, pgx.ErrNoRows) { + return nil, ErrNotFound + } + if err != nil { + return nil, mapWriteErr(err) + } + return &a, nil +} + +// CountAttachmentsInChat нужен тестам: после отказа S3/PG в чате не должно оставаться +// «полуфабрикатов» (строк метаданных без успешной загрузки). +func (s *Store) CountAttachmentsInChat(ctx context.Context, chatID uuid.UUID) (int, error) { + ctx, cancel := context.WithTimeout(ctx, queryTimeout) + defer cancel() + var n int + if err := s.pool.QueryRow(ctx, `SELECT count(*) FROM attachments WHERE chat_id = $1`, chatID).Scan(&n); err != nil { + return 0, mapWriteErr(err) + } + return n, nil +} + +// querier — общая часть pgx.Tx и pgxpool.Pool: так одни и те же функции читают +// связи сообщений и внутри транзакции (идемпотентный replay), и вне её (история). +type querier interface { + Query(ctx context.Context, sql string, args ...any) (pgx.Rows, error) +} + +// lockMessageAttachments проверяет вложения будущего сообщения внутри его транзакции. +// +// - WHERE id = ANY($1) AND chat_id = $2: вложение другого чата и несуществующее +// одинаково «не находятся» → ErrNotFound (404). Это и есть привязка файла к чату. +// - FOR SHARE блокирует найденные строки до COMMIT: параллельное удаление +// (reconciler) подождёт и затем упрётся в внешний ключ message_attachments. +// - Если нашлось меньше строк, чем запрошено, — хотя бы одно чужое/неизвестное. +// - Любой статус, кроме ready, → ErrAttachmentNotReady (409). +// +// ids уже проверены HTTP-слоем на уникальность и количество (≤10). +func lockMessageAttachments(ctx context.Context, tx pgx.Tx, chatID uuid.UUID, ids []uuid.UUID) error { + if len(ids) == 0 { + return nil + } + rows, err := tx.Query(ctx, ` + SELECT id, status FROM attachments + WHERE id = ANY($1) AND chat_id = $2 + ORDER BY id + FOR SHARE`, ids, chatID) + if err != nil { + return mapWriteErr(err) + } + defer rows.Close() + found, notReady := 0, false + for rows.Next() { + var id uuid.UUID + var status string + if err := rows.Scan(&id, &status); err != nil { + return mapWriteErr(err) + } + found++ + if status != StatusReady { + notReady = true + } + } + if err := rows.Err(); err != nil { + return mapWriteErr(err) + } + rows.Close() + if found != len(ids) { + return ErrNotFound + } + if notReady { + return ErrAttachmentNotReady + } + return nil +} + +// loadMessageAttachmentIDs — вложения одного сообщения в исходном порядке (position). +// Никогда не возвращает nil: пустой срез сериализуется в [], а не в null. +func loadMessageAttachmentIDs(ctx context.Context, q querier, messageID uuid.UUID) ([]uuid.UUID, error) { + byMsg, err := attachmentIDsByMessage(ctx, q, []uuid.UUID{messageID}) + if err != nil { + return nil, err + } + return byMsg[messageID], nil +} + +// attachmentIDsByMessage одним запросом читает связи для набора сообщений. +// Для сообщений без вложений вернётся пустой (не nil) срез. +func attachmentIDsByMessage(ctx context.Context, q querier, messageIDs []uuid.UUID) (map[uuid.UUID][]uuid.UUID, error) { + out := make(map[uuid.UUID][]uuid.UUID, len(messageIDs)) + for _, id := range messageIDs { + out[id] = []uuid.UUID{} + } + if len(messageIDs) == 0 { + return out, nil + } + rows, err := q.Query(ctx, ` + SELECT message_id, attachment_id + FROM message_attachments + WHERE message_id = ANY($1) + ORDER BY message_id, position`, messageIDs) + if err != nil { + return nil, mapWriteErr(err) + } + defer rows.Close() + for rows.Next() { + var mid, aid uuid.UUID + if err := rows.Scan(&mid, &aid); err != nil { + return nil, mapWriteErr(err) + } + out[mid] = append(out[mid], aid) + } + return out, mapWriteErr(rows.Err()) +} + +// attachMessageAttachments дозаполняет AttachmentIDs у страницы сообщений (ListMessages). +func (s *Store) attachMessageAttachments(ctx context.Context, items []Message) error { + if len(items) == 0 { + return nil + } + ids := make([]uuid.UUID, len(items)) + for i := range items { + ids[i] = items[i].ID + } + byMsg, err := attachmentIDsByMessage(ctx, s.pool, ids) + if err != nil { + return err + } + for i := range items { + items[i].AttachmentIDs = byMsg[items[i].ID] + } + return nil +} + +// --------------------------------------------------------------------------- +// Методы для reconciler (internal/reconcile). Они здесь, а не в reconcile, потому +// что SQL и работа с пулом принадлежат пакету store. +// --------------------------------------------------------------------------- + +// AttachmentRef — минимальная информация о строке для сверки с S3. +type AttachmentRef struct { + ID uuid.UUID + ObjectKey string + CreatedAt time.Time + // Used — на вложение ссылается хотя бы одно сообщение. Такое вложение удалять нельзя. + Used bool +} + +// ListAttachmentRefsAfter — keyset-страница строк в байтовом порядке object_key +// (колонка COLLATE "C" — порядок совпадает с листингом S3). afterKey="" — с начала. +func (s *Store) ListAttachmentRefsAfter(ctx context.Context, afterKey string, limit int) ([]AttachmentRef, error) { + ctx, cancel := context.WithTimeout(ctx, queryTimeout) + defer cancel() + rows, err := s.pool.Query(ctx, ` + SELECT a.id, a.object_key, a.created_at, + EXISTS (SELECT 1 FROM message_attachments ma WHERE ma.attachment_id = a.id) + FROM attachments a + WHERE a.object_key > $1 + ORDER BY a.object_key + LIMIT $2`, afterKey, limit) + if err != nil { + return nil, mapWriteErr(err) + } + defer rows.Close() + var out []AttachmentRef + for rows.Next() { + var r AttachmentRef + if err := rows.Scan(&r.ID, &r.ObjectKey, &r.CreatedAt, &r.Used); err != nil { + return nil, mapWriteErr(err) + } + out = append(out, r) + } + return out, mapWriteErr(rows.Err()) +} + +// AttachmentKeyExists — повторная проверка непосредственно перед удалением orphan-объекта: +// сужает окно гонки «reconciler решил, что строки нет, а загрузка как раз сделала INSERT». +func (s *Store) AttachmentKeyExists(ctx context.Context, key string) (bool, error) { + ctx, cancel := context.WithTimeout(ctx, queryTimeout) + defer cancel() + var ok bool + err := s.pool.QueryRow(ctx, `SELECT EXISTS (SELECT 1 FROM attachments WHERE object_key = $1)`, key).Scan(&ok) + return ok, mapWriteErr(err) +} + +// DeleteUnusedAttachment удаляет строку вложения, только если выполнены ОБА условия: +// она старше olderThan (не «свежая») и на неё нет ссылок из сообщений (не «используемая»). +// Возвращает true, если строка удалена. Внешний ключ message_attachments страхует +// от гонки с параллельной отправкой сообщения: такой DELETE упадёт, а не потеряет данные. +func (s *Store) DeleteUnusedAttachment(ctx context.Context, id uuid.UUID, olderThan time.Time) (bool, error) { + ctx, cancel := context.WithTimeout(ctx, queryTimeout) + defer cancel() + tag, err := s.pool.Exec(ctx, ` + DELETE FROM attachments a + WHERE a.id = $1 + AND a.created_at < $2 + AND NOT EXISTS (SELECT 1 FROM message_attachments ma WHERE ma.attachment_id = a.id)`, + id, olderThan) + if err != nil { + return false, mapWriteErr(err) + } + return tag.RowsAffected() == 1, nil +} diff --git a/internal/store/migrations/store.go b/internal/store/migrations/store.go new file mode 100644 index 00000000..d6461063 --- /dev/null +++ b/internal/store/migrations/store.go @@ -0,0 +1,693 @@ +// Package store — пользователи, чаты, сообщения и ключи идемпотентности в PostgreSQL. +// +// Источник истины — только эти таблицы. Память процесса после рестарта пуста, +// поэтому ни одного map с данными здесь нет. Каждый запрос параметризован ($1, $2): +// текст сообщения не склеивается в SQL. +// +// Создание чата — одна транзакция: строка чата и все участники фиксируются вместе +// либо не фиксируются вообще. Уникальность username обеспечивает UNIQUE, а не проверка +// «сначала SELECT, потом INSERT» (та проверка проигрывает гонке). +// +// Идемпотентность сообщения тоже живёт в PostgreSQL, а не в памяти реплики: +// два параллельных POST с одним ключом через разные API-контейнеры видят один PK. +package store + +import ( + "context" + "crypto/sha256" + "encoding/binary" + "encoding/json" + "errors" + "fmt" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgconn" + "github.com/jackc/pgx/v5/pgxpool" + + "gavrilenko-sxdees/lab4/internal/auth" +) + +const queryTimeout = 3 * time.Second + +// Ошибки домена. HTTP-слой переводит их в коды контракта и не показывает SQL. +var ( + ErrConflict = errors.New("conflict") + ErrNotFound = errors.New("not found") + ErrInvalidCursor = errors.New("invalid cursor") + ErrUnavailable = errors.New("unavailable") + // ErrIdempotencyConflict — тот же ключ, но другое тело запроса. + ErrIdempotencyConflict = errors.New("idempotency conflict") + // ErrAttachmentNotReady — вложение существует, но ещё не ready (409 по контракту). + // В lab4 все вложения создаются сразу ready; проверка нужна для lab5+ и защищает + // от прикрепления недообработанного файла. + ErrAttachmentNotReady = errors.New("attachment not ready") +) + +// User — публичные поля пользователя. Hash пароля в эту структуру не попадает. +type User struct { + ID uuid.UUID + Username string + DisplayName string + CreatedAt time.Time +} + +// Chat — чат и явный состав участников. +type Chat struct { + ID uuid.UUID + Title string + MemberIDs []uuid.UUID + CreatedAt time.Time +} + +// Message — одно подтверждённое сообщение. sender_id назначает сервер. +type Message struct { + ID uuid.UUID + ChatID uuid.UUID + SenderID uuid.UUID + Text string + CreatedAt time.Time + // AttachmentIDs — вложения в порядке, заданном клиентом. Никогда nil в ответах API + // (контракт: attachment_ids обязателен, по умолчанию []). + AttachmentIDs []uuid.UUID +} + +// PageCursor — позиция keyset. Клиент видит только opaque-строку в пакете api. +type PageCursor struct { + CreatedAt time.Time + ID uuid.UUID + Scope string +} + +// Store — пул соединений. Пул ограничен, у каждого запроса свой таймаут. +type Store struct { + pool *pgxpool.Pool + hasher *auth.Hasher +} + +// Open поднимает пул. ConnectTimeout короткий, чтобы недоступная БД быстро стала 503, +// а не висела до клиентского таймаута теста. +// maxConns — на одну реплику; при N репликах суммарный пул ≈ N*maxConns. +func Open(ctx context.Context, databaseURL string, hasher *auth.Hasher, maxConns int32) (*Store, error) { + if maxConns < 1 { + maxConns = 5 + } + cfg, err := pgxpool.ParseConfig(databaseURL) + if err != nil { + return nil, fmt.Errorf("parse database url: %w", err) + } + cfg.MaxConns = maxConns + cfg.MinConns = 1 + cfg.MaxConnLifetime = 30 * time.Minute + cfg.MaxConnIdleTime = 5 * time.Minute + cfg.HealthCheckPeriod = 30 * time.Second + cfg.ConnConfig.ConnectTimeout = 2 * time.Second + cfg.AfterConnect = func(ctx context.Context, conn *pgx.Conn) error { + // UTC, чтобы timestamptz читался так же, как мы его записали. + // statement_timeout обрывает запрос, который внезапно решил сканировать всё. + _, err := conn.Exec(ctx, `SET TIME ZONE 'UTC'; SET statement_timeout = '3s'`) + return err + } + pool, err := pgxpool.NewWithConfig(ctx, cfg) + if err != nil { + return nil, err + } + pingCtx, cancel := context.WithTimeout(ctx, 3*time.Second) + defer cancel() + if err := pool.Ping(pingCtx); err != nil { + pool.Close() + return nil, err + } + return &Store{pool: pool, hasher: hasher}, nil +} + +// Close освобождает соединения при остановке процесса. +func (s *Store) Close() { + s.pool.Close() +} + +// Ping — проверка для /health/ready. Ошибка здесь значит «не готов», не «жив». +func (s *Store) Ping(ctx context.Context) error { + ctx, cancel := context.WithTimeout(ctx, 300*time.Millisecond) + defer cancel() + if err := s.pool.Ping(ctx); err != nil { + return ErrUnavailable + } + return nil +} + +// CreateUser пишет пользователя. Повтор username → ErrConflict благодаря UNIQUE. +func (s *Store) CreateUser(ctx context.Context, username, displayName, password string) (*User, error) { + hash, err := auth.Hash(password) + if err != nil { + return nil, err + } + u := &User{ + ID: uuid.New(), + Username: username, + DisplayName: displayName, + CreatedAt: nowUTC(), + } + ctx, cancel := context.WithTimeout(ctx, queryTimeout) + defer cancel() + _, err = s.pool.Exec(ctx, ` + INSERT INTO users (id, username, display_name, password_hash, created_at) + VALUES ($1, $2, $3, $4, $5)`, + u.ID, u.Username, u.DisplayName, hash, u.CreatedAt) + if err != nil { + return nil, mapWriteErr(err) + } + return u, nil +} + +// Authenticate проверяет Basic-логин. Нет пользователя и неверный пароль +// выглядят одинаково: оба дают false без отдельной ошибки «такого логина нет». +func (s *Store) Authenticate(ctx context.Context, username, password string) (*User, error) { + ctx, cancel := context.WithTimeout(ctx, queryTimeout) + defer cancel() + var u User + var hash string + err := s.pool.QueryRow(ctx, ` + SELECT id, username, display_name, created_at, password_hash + FROM users WHERE username = $1`, username).Scan(&u.ID, &u.Username, &u.DisplayName, &u.CreatedAt, &hash) + if errors.Is(err, pgx.ErrNoRows) { + s.hasher.Burn(password) + return nil, ErrNotFound + } + if err != nil { + return nil, mapWriteErr(err) + } + if !s.hasher.Verify(hash, password) { + return nil, ErrNotFound + } + return &u, nil +} + +// GetUser нужен, чтобы ответ /users/me совпал с объектом из регистрации. +func (s *Store) GetUser(ctx context.Context, id uuid.UUID) (*User, error) { + ctx, cancel := context.WithTimeout(ctx, queryTimeout) + defer cancel() + var u User + err := s.pool.QueryRow(ctx, ` + SELECT id, username, display_name, created_at FROM users WHERE id = $1`, id). + Scan(&u.ID, &u.Username, &u.DisplayName, &u.CreatedAt) + if errors.Is(err, pgx.ErrNoRows) { + return nil, ErrNotFound + } + if err != nil { + return nil, mapWriteErr(err) + } + return &u, nil +} + +// CreateChat атомарно создаёт чат и состав. Неизвестный участник откатывает всё: +// в таблице chats не остаётся «пустой» строки без полного состава. +func (s *Store) CreateChat(ctx context.Context, title string, memberIDs []uuid.UUID) (*Chat, error) { + ctx, cancel := context.WithTimeout(ctx, queryTimeout) + defer cancel() + tx, err := s.pool.Begin(ctx) + if err != nil { + return nil, mapWriteErr(err) + } + defer func() { _ = tx.Rollback(ctx) }() + + chat := &Chat{ + ID: uuid.New(), + Title: title, + MemberIDs: append([]uuid.UUID(nil), memberIDs...), + CreatedAt: nowUTC(), + } + if _, err := tx.Exec(ctx, `INSERT INTO chats (id, title, created_at) VALUES ($1, $2, $3)`, + chat.ID, chat.Title, chat.CreatedAt); err != nil { + return nil, mapWriteErr(err) + } + for _, uid := range memberIDs { + // INSERT ... SELECT вставит 0 строк, если пользователя нет, и не нарушит FK. + tag, err := tx.Exec(ctx, ` + INSERT INTO chat_members (chat_id, user_id) + SELECT $1, id FROM users WHERE id = $2`, chat.ID, uid) + if err != nil { + return nil, mapWriteErr(err) + } + if tag.RowsAffected() != 1 { + return nil, ErrNotFound + } + } + if err := tx.Commit(ctx); err != nil { + return nil, mapWriteErr(err) + } + return chat, nil +} + +// GetChat возвращает чат только участнику. Чужому — ErrNotFound (HTTP 404, не 403). +func (s *Store) GetChat(ctx context.Context, chatID, userID uuid.UUID) (*Chat, error) { + if err := s.ensureMember(ctx, chatID, userID); err != nil { + return nil, err + } + return s.loadChat(ctx, chatID) +} + +// ListChats — keyset по (created_at, id) только среди чатов этого пользователя. +func (s *Store) ListChats(ctx context.Context, userID uuid.UUID, limit int, after *PageCursor) ([]Chat, *PageCursor, error) { + ctx, cancel := context.WithTimeout(ctx, queryTimeout) + defer cancel() + var ( + rows pgx.Rows + err error + ) + if after == nil { + rows, err = s.pool.Query(ctx, ` + SELECT c.id, c.title, c.created_at + FROM chats c + JOIN chat_members m ON m.chat_id = c.id + WHERE m.user_id = $1 + ORDER BY c.created_at, c.id + LIMIT $2`, userID, limit+1) + } else { + rows, err = s.pool.Query(ctx, ` + SELECT c.id, c.title, c.created_at + FROM chats c + JOIN chat_members m ON m.chat_id = c.id + WHERE m.user_id = $1 + AND (c.created_at, c.id) > ($2, $3) + ORDER BY c.created_at, c.id + LIMIT $4`, userID, after.CreatedAt, after.ID, limit+1) + } + if err != nil { + return nil, nil, mapWriteErr(err) + } + defer rows.Close() + + var items []Chat + for rows.Next() { + var c Chat + if err := rows.Scan(&c.ID, &c.Title, &c.CreatedAt); err != nil { + return nil, nil, mapWriteErr(err) + } + items = append(items, c) + } + if err := rows.Err(); err != nil { + return nil, nil, mapWriteErr(err) + } + next, items := trimPage(items, limit, func(c Chat) (time.Time, uuid.UUID) { + return c.CreatedAt, c.ID + }) + for i := range items { + members, err := s.memberIDs(ctx, items[i].ID) + if err != nil { + return nil, nil, err + } + items[i].MemberIDs = members + } + var cursor *PageCursor + if next { + last := items[len(items)-1] + cursor = &PageCursor{CreatedAt: last.CreatedAt, ID: last.ID} + } + return items, cursor, nil +} + +// CreateMessage пишет сообщение только если отправитель состоит в чате. +// Подтверждение — это COMMIT строки. Следующее чтение видит её без кэша истории. +// Без идемпотентности — только для внутренних/тестовых случаев; HTTP использует CreateMessageIdempotent. +func (s *Store) CreateMessage(ctx context.Context, chatID, senderID uuid.UUID, text string) (*Message, error) { + ctx, cancel := context.WithTimeout(ctx, queryTimeout) + defer cancel() + msg := &Message{ + ID: uuid.New(), + ChatID: chatID, + SenderID: senderID, + Text: text, + CreatedAt: nowUTC(), + // Внутренний путь без вложений; поле не nil, чтобы JSON дал [], а не null. + AttachmentIDs: []uuid.UUID{}, + } + tag, err := s.pool.Exec(ctx, ` + INSERT INTO messages (id, chat_id, sender_id, text, created_at) + SELECT $1, $2, $3, $4, $5 + WHERE EXISTS ( + SELECT 1 FROM chat_members WHERE chat_id = $2 AND user_id = $3 + )`, msg.ID, msg.ChatID, msg.SenderID, msg.Text, msg.CreatedAt) + if err != nil { + return nil, mapWriteErr(err) + } + if tag.RowsAffected() != 1 { + return nil, ErrNotFound + } + return msg, nil +} + +// IdempotentMessage — либо только что созданное, либо ранее сохранённое по ключу сообщение. +type IdempotentMessage struct { + Message *Message + Replayed bool +} + +// CreateMessageIdempotent атомарно создаёт сообщение и запоминает ответ по ключу. +// +// Алгоритм (общая БД, любые реплики): +// 1. BEGIN; +// 2. pg_advisory_xact_lock по хешу (user, method, path, key) — сериализует конкурентов +// ещё до INSERT messages, иначе два победителя гонки успели бы создать два сообщения; +// 3. SELECT сохранённого ключа — если есть, сравнить hash и вернуть Message; +// 4. иначе проверить членство, затем вложения (lab4): все принадлежат ЭТОМУ чату и ready, +// строки блокируются FOR SHARE, чтобы удаление (reconciler) не вклинилось до COMMIT; +// 5. INSERT message + INSERT message_attachments + INSERT idempotency_keys в той же +// транзакции: сообщение либо видно целиком вместе со ссылками на вложения, либо нет; +// 6. COMMIT (advisory lock снимается вместе с транзакцией). +// +// Чужое и неизвестное вложение (в т.ч. из другого чата) неразличимы: оба дают ErrNotFound +// (HTTP 404), чтобы нельзя было перебором выяснить, существует ли чужой файл. +// +// Другой request_hash → ErrIdempotencyConflict. Транзиентный 5xx сюда не попадает: +// запись ключа только после успешной подготовки 201. +func (s *Store) CreateMessageIdempotent( + ctx context.Context, + chatID, senderID uuid.UUID, + text string, + attachmentIDs []uuid.UUID, + method, path, idemKey, requestHash string, +) (*IdempotentMessage, error) { + ctx, cancel := context.WithTimeout(ctx, queryTimeout) + defer cancel() + + tx, err := s.pool.Begin(ctx) + if err != nil { + return nil, mapWriteErr(err) + } + defer func() { _ = tx.Rollback(ctx) }() + + lockKey := idempotencyLockKey(senderID, method, path, idemKey) + if _, err := tx.Exec(ctx, `SELECT pg_advisory_xact_lock($1)`, lockKey); err != nil { + return nil, mapWriteErr(err) + } + + var ( + storedHash string + msgID uuid.UUID + msgChat uuid.UUID + msgSender uuid.UUID + msgText string + msgCreated time.Time + ) + err = tx.QueryRow(ctx, ` + SELECT i.request_hash, m.id, m.chat_id, m.sender_id, m.text, m.created_at + FROM idempotency_keys i + JOIN messages m ON m.id = i.message_id + WHERE i.user_id = $1 AND i.method = $2 AND i.path = $3 AND i.key = $4`, + senderID, method, path, idemKey, + ).Scan(&storedHash, &msgID, &msgChat, &msgSender, &msgText, &msgCreated) + if err == nil { + if storedHash != requestHash { + return nil, ErrIdempotencyConflict + } + // Replay обязан вернуть ТОТ ЖЕ набор вложений, что и первый ответ. + replayIDs, err := loadMessageAttachmentIDs(ctx, tx, msgID) + if err != nil { + return nil, err + } + if err := tx.Commit(ctx); err != nil { + return nil, mapWriteErr(err) + } + return &IdempotentMessage{ + Message: &Message{ + ID: msgID, + ChatID: msgChat, + SenderID: msgSender, + Text: msgText, + CreatedAt: msgCreated, + AttachmentIDs: replayIDs, + }, + Replayed: true, + }, nil + } + if !errors.Is(err, pgx.ErrNoRows) { + return nil, mapWriteErr(err) + } + + var member int + if err := tx.QueryRow(ctx, ` + SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2`, chatID, senderID).Scan(&member); err != nil { + if errors.Is(err, pgx.ErrNoRows) { + return nil, ErrNotFound + } + return nil, mapWriteErr(err) + } + + // Вложения проверяем ПОСЛЕ членства: посторонний в чат получает 404 по чату, + // а не информацию о существовании файлов. + if err := lockMessageAttachments(ctx, tx, chatID, attachmentIDs); err != nil { + return nil, err + } + + msg := &Message{ + ID: uuid.New(), + ChatID: chatID, + SenderID: senderID, + Text: text, + CreatedAt: nowUTC(), + AttachmentIDs: append([]uuid.UUID{}, attachmentIDs...), + } + if _, err := tx.Exec(ctx, ` + INSERT INTO messages (id, chat_id, sender_id, text, created_at) + VALUES ($1, $2, $3, $4, $5)`, + msg.ID, msg.ChatID, msg.SenderID, msg.Text, msg.CreatedAt); err != nil { + return nil, mapWriteErr(err) + } + // Порядок attachment_ids клиента сохраняется в position. + for i, aid := range attachmentIDs { + if _, err := tx.Exec(ctx, ` + INSERT INTO message_attachments (message_id, attachment_id, position) + VALUES ($1, $2, $3)`, msg.ID, aid, i); err != nil { + return nil, mapWriteErr(err) + } + } + + // response_body заполняем каноническим Message JSON уже здесь, чтобы replay + // не зависел от повторной сериализации в HTTP-слое с другим порядком полей. + attachmentStrs := make([]string, len(msg.AttachmentIDs)) + for i, aid := range msg.AttachmentIDs { + attachmentStrs[i] = aid.String() + } + bodyJSON, err := json.Marshal(map[string]any{ + "id": msg.ID.String(), + "chat_id": msg.ChatID.String(), + "sender_id": msg.SenderID.String(), + "text": msg.Text, + "created_at": msg.CreatedAt.UTC().Truncate(time.Millisecond).Format("2006-01-02T15:04:05.000Z"), + "attachment_ids": attachmentStrs, + }) + if err != nil { + return nil, err + } + if _, err = tx.Exec(ctx, ` + INSERT INTO idempotency_keys ( + user_id, method, path, key, request_hash, + response_status, response_body, message_id, created_at + ) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9)`, + senderID, method, path, idemKey, requestHash, + 201, bodyJSON, msg.ID, msg.CreatedAt); err != nil { + return nil, mapWriteErr(err) + } + if err := tx.Commit(ctx); err != nil { + return nil, mapWriteErr(err) + } + return &IdempotentMessage{Message: msg, Replayed: false}, nil +} + +// idempotencyLockKey — стабильный int64 для pg_advisory_xact_lock из области ключа. +func idempotencyLockKey(userID uuid.UUID, method, path, key string) int64 { + sum := sha256.Sum256([]byte(userID.String() + "|" + method + "|" + path + "|" + key)) + return int64(binary.BigEndian.Uint64(sum[:8])) +} + +// ListMessages — keyset по индексу messages_history_idx. Берём limit+1 строку, +// чтобы next_cursor был null, когда следующей записи уже нет. +func (s *Store) ListMessages(ctx context.Context, chatID, userID uuid.UUID, limit int, after *PageCursor) ([]Message, *PageCursor, error) { + if err := s.ensureMember(ctx, chatID, userID); err != nil { + return nil, nil, err + } + ctx, cancel := context.WithTimeout(ctx, queryTimeout) + defer cancel() + var ( + rows pgx.Rows + err error + ) + if after == nil { + rows, err = s.pool.Query(ctx, ` + SELECT id, chat_id, sender_id, text, created_at + FROM messages + WHERE chat_id = $1 + ORDER BY created_at, id + LIMIT $2`, chatID, limit+1) + } else { + rows, err = s.pool.Query(ctx, ` + SELECT id, chat_id, sender_id, text, created_at + FROM messages + WHERE chat_id = $1 + AND (created_at, id) > ($2, $3) + ORDER BY created_at, id + LIMIT $4`, chatID, after.CreatedAt, after.ID, limit+1) + } + if err != nil { + return nil, nil, mapWriteErr(err) + } + defer rows.Close() + var items []Message + for rows.Next() { + var m Message + if err := rows.Scan(&m.ID, &m.ChatID, &m.SenderID, &m.Text, &m.CreatedAt); err != nil { + return nil, nil, mapWriteErr(err) + } + items = append(items, m) + } + if err := rows.Err(); err != nil { + return nil, nil, mapWriteErr(err) + } + hasNext, items := trimPage(items, limit, func(m Message) (time.Time, uuid.UUID) { + return m.CreatedAt, m.ID + }) + // Вложения страницы одним запросом (а не N+1): WHERE message_id = ANY(id страницы). + if err := s.attachMessageAttachments(ctx, items); err != nil { + return nil, nil, err + } + var cursor *PageCursor + if hasNext { + last := items[len(items)-1] + cursor = &PageCursor{CreatedAt: last.CreatedAt, ID: last.ID} + } + return items, cursor, nil +} + +// ChatExistsForTitle помогает тесту отката: после ошибки создания чата строки нет. +func (s *Store) CountChatsByTitle(ctx context.Context, title string) (int, error) { + ctx, cancel := context.WithTimeout(ctx, queryTimeout) + defer cancel() + var n int + err := s.pool.QueryRow(ctx, `SELECT count(*) FROM chats WHERE title = $1`, title).Scan(&n) + if err != nil { + return 0, mapWriteErr(err) + } + return n, nil +} + +// IsChatMember — проверка членства для HTTP-слоя (например, до чтения тела загрузки: +// постороннему не нужно тратить на себя RAM и трафик). ErrNotFound — не участник. +func (s *Store) IsChatMember(ctx context.Context, chatID, userID uuid.UUID) error { + return s.ensureMember(ctx, chatID, userID) +} + +func (s *Store) ensureMember(ctx context.Context, chatID, userID uuid.UUID) error { + ctx, cancel := context.WithTimeout(ctx, queryTimeout) + defer cancel() + var one int + err := s.pool.QueryRow(ctx, ` + SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2`, chatID, userID).Scan(&one) + if errors.Is(err, pgx.ErrNoRows) { + return ErrNotFound + } + if err != nil { + return mapWriteErr(err) + } + return nil +} + +func (s *Store) loadChat(ctx context.Context, chatID uuid.UUID) (*Chat, error) { + ctx, cancel := context.WithTimeout(ctx, queryTimeout) + defer cancel() + var c Chat + err := s.pool.QueryRow(ctx, `SELECT id, title, created_at FROM chats WHERE id = $1`, chatID). + Scan(&c.ID, &c.Title, &c.CreatedAt) + if errors.Is(err, pgx.ErrNoRows) { + return nil, ErrNotFound + } + if err != nil { + return nil, mapWriteErr(err) + } + c.MemberIDs, err = s.memberIDs(ctx, chatID) + if err != nil { + return nil, err + } + return &c, nil +} + +func (s *Store) memberIDs(ctx context.Context, chatID uuid.UUID) ([]uuid.UUID, error) { + rows, err := s.pool.Query(ctx, ` + SELECT user_id FROM chat_members WHERE chat_id = $1 ORDER BY user_id`, chatID) + if err != nil { + return nil, mapWriteErr(err) + } + defer rows.Close() + var ids []uuid.UUID + for rows.Next() { + var id uuid.UUID + if err := rows.Scan(&id); err != nil { + return nil, mapWriteErr(err) + } + ids = append(ids, id) + } + return ids, mapWriteErr(rows.Err()) +} + +func trimPage[T any](items []T, limit int, _ func(T) (time.Time, uuid.UUID)) (bool, []T) { + if len(items) > limit { + return true, items[:limit] + } + return false, items +} + +func nowUTC() time.Time { + // Миллисекунда — точность, которую мы же и печатаем в JSON. + return time.Now().UTC().Truncate(time.Millisecond) +} + +func mapWriteErr(err error) error { + if err == nil { + return nil + } + var pgErr *pgconn.PgError + if errors.As(err, &pgErr) && pgErr.Code == "23505" { + return ErrConflict + } + if errors.Is(err, context.DeadlineExceeded) || isConn(err) { + return ErrUnavailable + } + return err +} + +func isConn(err error) bool { + msg := err.Error() + // Не логируем и не возвращаем клиенту эту строку. Здесь только классификация. + switch { + case errors.Is(err, pgx.ErrNoRows): + return false + default: + if stringsContains(msg, "connection refused") || + stringsContains(msg, "failed to connect") || + stringsContains(msg, "conn closed") || + stringsContains(msg, "closed pool") || + stringsContains(msg, "broken pipe") || + stringsContains(msg, "connection reset") || + stringsContains(msg, "SQLSTATE 57P01") || + stringsContains(msg, "SQLSTATE 08006") || + stringsContains(msg, "SQLSTATE 08001") { + return true + } + } + return false +} + +func stringsContains(s, sub string) bool { + return len(s) >= len(sub) && (s == sub || len(sub) == 0 || + (func() bool { return contains(s, sub) })()) +} + +func contains(s, sub string) bool { + for i := 0; i+len(sub) <= len(s); i++ { + if s[i:i+len(sub)] == sub { + return true + } + } + return false +} diff --git a/internal/store/store.go b/internal/store/store.go new file mode 100644 index 00000000..d6461063 --- /dev/null +++ b/internal/store/store.go @@ -0,0 +1,693 @@ +// Package store — пользователи, чаты, сообщения и ключи идемпотентности в PostgreSQL. +// +// Источник истины — только эти таблицы. Память процесса после рестарта пуста, +// поэтому ни одного map с данными здесь нет. Каждый запрос параметризован ($1, $2): +// текст сообщения не склеивается в SQL. +// +// Создание чата — одна транзакция: строка чата и все участники фиксируются вместе +// либо не фиксируются вообще. Уникальность username обеспечивает UNIQUE, а не проверка +// «сначала SELECT, потом INSERT» (та проверка проигрывает гонке). +// +// Идемпотентность сообщения тоже живёт в PostgreSQL, а не в памяти реплики: +// два параллельных POST с одним ключом через разные API-контейнеры видят один PK. +package store + +import ( + "context" + "crypto/sha256" + "encoding/binary" + "encoding/json" + "errors" + "fmt" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgconn" + "github.com/jackc/pgx/v5/pgxpool" + + "gavrilenko-sxdees/lab4/internal/auth" +) + +const queryTimeout = 3 * time.Second + +// Ошибки домена. HTTP-слой переводит их в коды контракта и не показывает SQL. +var ( + ErrConflict = errors.New("conflict") + ErrNotFound = errors.New("not found") + ErrInvalidCursor = errors.New("invalid cursor") + ErrUnavailable = errors.New("unavailable") + // ErrIdempotencyConflict — тот же ключ, но другое тело запроса. + ErrIdempotencyConflict = errors.New("idempotency conflict") + // ErrAttachmentNotReady — вложение существует, но ещё не ready (409 по контракту). + // В lab4 все вложения создаются сразу ready; проверка нужна для lab5+ и защищает + // от прикрепления недообработанного файла. + ErrAttachmentNotReady = errors.New("attachment not ready") +) + +// User — публичные поля пользователя. Hash пароля в эту структуру не попадает. +type User struct { + ID uuid.UUID + Username string + DisplayName string + CreatedAt time.Time +} + +// Chat — чат и явный состав участников. +type Chat struct { + ID uuid.UUID + Title string + MemberIDs []uuid.UUID + CreatedAt time.Time +} + +// Message — одно подтверждённое сообщение. sender_id назначает сервер. +type Message struct { + ID uuid.UUID + ChatID uuid.UUID + SenderID uuid.UUID + Text string + CreatedAt time.Time + // AttachmentIDs — вложения в порядке, заданном клиентом. Никогда nil в ответах API + // (контракт: attachment_ids обязателен, по умолчанию []). + AttachmentIDs []uuid.UUID +} + +// PageCursor — позиция keyset. Клиент видит только opaque-строку в пакете api. +type PageCursor struct { + CreatedAt time.Time + ID uuid.UUID + Scope string +} + +// Store — пул соединений. Пул ограничен, у каждого запроса свой таймаут. +type Store struct { + pool *pgxpool.Pool + hasher *auth.Hasher +} + +// Open поднимает пул. ConnectTimeout короткий, чтобы недоступная БД быстро стала 503, +// а не висела до клиентского таймаута теста. +// maxConns — на одну реплику; при N репликах суммарный пул ≈ N*maxConns. +func Open(ctx context.Context, databaseURL string, hasher *auth.Hasher, maxConns int32) (*Store, error) { + if maxConns < 1 { + maxConns = 5 + } + cfg, err := pgxpool.ParseConfig(databaseURL) + if err != nil { + return nil, fmt.Errorf("parse database url: %w", err) + } + cfg.MaxConns = maxConns + cfg.MinConns = 1 + cfg.MaxConnLifetime = 30 * time.Minute + cfg.MaxConnIdleTime = 5 * time.Minute + cfg.HealthCheckPeriod = 30 * time.Second + cfg.ConnConfig.ConnectTimeout = 2 * time.Second + cfg.AfterConnect = func(ctx context.Context, conn *pgx.Conn) error { + // UTC, чтобы timestamptz читался так же, как мы его записали. + // statement_timeout обрывает запрос, который внезапно решил сканировать всё. + _, err := conn.Exec(ctx, `SET TIME ZONE 'UTC'; SET statement_timeout = '3s'`) + return err + } + pool, err := pgxpool.NewWithConfig(ctx, cfg) + if err != nil { + return nil, err + } + pingCtx, cancel := context.WithTimeout(ctx, 3*time.Second) + defer cancel() + if err := pool.Ping(pingCtx); err != nil { + pool.Close() + return nil, err + } + return &Store{pool: pool, hasher: hasher}, nil +} + +// Close освобождает соединения при остановке процесса. +func (s *Store) Close() { + s.pool.Close() +} + +// Ping — проверка для /health/ready. Ошибка здесь значит «не готов», не «жив». +func (s *Store) Ping(ctx context.Context) error { + ctx, cancel := context.WithTimeout(ctx, 300*time.Millisecond) + defer cancel() + if err := s.pool.Ping(ctx); err != nil { + return ErrUnavailable + } + return nil +} + +// CreateUser пишет пользователя. Повтор username → ErrConflict благодаря UNIQUE. +func (s *Store) CreateUser(ctx context.Context, username, displayName, password string) (*User, error) { + hash, err := auth.Hash(password) + if err != nil { + return nil, err + } + u := &User{ + ID: uuid.New(), + Username: username, + DisplayName: displayName, + CreatedAt: nowUTC(), + } + ctx, cancel := context.WithTimeout(ctx, queryTimeout) + defer cancel() + _, err = s.pool.Exec(ctx, ` + INSERT INTO users (id, username, display_name, password_hash, created_at) + VALUES ($1, $2, $3, $4, $5)`, + u.ID, u.Username, u.DisplayName, hash, u.CreatedAt) + if err != nil { + return nil, mapWriteErr(err) + } + return u, nil +} + +// Authenticate проверяет Basic-логин. Нет пользователя и неверный пароль +// выглядят одинаково: оба дают false без отдельной ошибки «такого логина нет». +func (s *Store) Authenticate(ctx context.Context, username, password string) (*User, error) { + ctx, cancel := context.WithTimeout(ctx, queryTimeout) + defer cancel() + var u User + var hash string + err := s.pool.QueryRow(ctx, ` + SELECT id, username, display_name, created_at, password_hash + FROM users WHERE username = $1`, username).Scan(&u.ID, &u.Username, &u.DisplayName, &u.CreatedAt, &hash) + if errors.Is(err, pgx.ErrNoRows) { + s.hasher.Burn(password) + return nil, ErrNotFound + } + if err != nil { + return nil, mapWriteErr(err) + } + if !s.hasher.Verify(hash, password) { + return nil, ErrNotFound + } + return &u, nil +} + +// GetUser нужен, чтобы ответ /users/me совпал с объектом из регистрации. +func (s *Store) GetUser(ctx context.Context, id uuid.UUID) (*User, error) { + ctx, cancel := context.WithTimeout(ctx, queryTimeout) + defer cancel() + var u User + err := s.pool.QueryRow(ctx, ` + SELECT id, username, display_name, created_at FROM users WHERE id = $1`, id). + Scan(&u.ID, &u.Username, &u.DisplayName, &u.CreatedAt) + if errors.Is(err, pgx.ErrNoRows) { + return nil, ErrNotFound + } + if err != nil { + return nil, mapWriteErr(err) + } + return &u, nil +} + +// CreateChat атомарно создаёт чат и состав. Неизвестный участник откатывает всё: +// в таблице chats не остаётся «пустой» строки без полного состава. +func (s *Store) CreateChat(ctx context.Context, title string, memberIDs []uuid.UUID) (*Chat, error) { + ctx, cancel := context.WithTimeout(ctx, queryTimeout) + defer cancel() + tx, err := s.pool.Begin(ctx) + if err != nil { + return nil, mapWriteErr(err) + } + defer func() { _ = tx.Rollback(ctx) }() + + chat := &Chat{ + ID: uuid.New(), + Title: title, + MemberIDs: append([]uuid.UUID(nil), memberIDs...), + CreatedAt: nowUTC(), + } + if _, err := tx.Exec(ctx, `INSERT INTO chats (id, title, created_at) VALUES ($1, $2, $3)`, + chat.ID, chat.Title, chat.CreatedAt); err != nil { + return nil, mapWriteErr(err) + } + for _, uid := range memberIDs { + // INSERT ... SELECT вставит 0 строк, если пользователя нет, и не нарушит FK. + tag, err := tx.Exec(ctx, ` + INSERT INTO chat_members (chat_id, user_id) + SELECT $1, id FROM users WHERE id = $2`, chat.ID, uid) + if err != nil { + return nil, mapWriteErr(err) + } + if tag.RowsAffected() != 1 { + return nil, ErrNotFound + } + } + if err := tx.Commit(ctx); err != nil { + return nil, mapWriteErr(err) + } + return chat, nil +} + +// GetChat возвращает чат только участнику. Чужому — ErrNotFound (HTTP 404, не 403). +func (s *Store) GetChat(ctx context.Context, chatID, userID uuid.UUID) (*Chat, error) { + if err := s.ensureMember(ctx, chatID, userID); err != nil { + return nil, err + } + return s.loadChat(ctx, chatID) +} + +// ListChats — keyset по (created_at, id) только среди чатов этого пользователя. +func (s *Store) ListChats(ctx context.Context, userID uuid.UUID, limit int, after *PageCursor) ([]Chat, *PageCursor, error) { + ctx, cancel := context.WithTimeout(ctx, queryTimeout) + defer cancel() + var ( + rows pgx.Rows + err error + ) + if after == nil { + rows, err = s.pool.Query(ctx, ` + SELECT c.id, c.title, c.created_at + FROM chats c + JOIN chat_members m ON m.chat_id = c.id + WHERE m.user_id = $1 + ORDER BY c.created_at, c.id + LIMIT $2`, userID, limit+1) + } else { + rows, err = s.pool.Query(ctx, ` + SELECT c.id, c.title, c.created_at + FROM chats c + JOIN chat_members m ON m.chat_id = c.id + WHERE m.user_id = $1 + AND (c.created_at, c.id) > ($2, $3) + ORDER BY c.created_at, c.id + LIMIT $4`, userID, after.CreatedAt, after.ID, limit+1) + } + if err != nil { + return nil, nil, mapWriteErr(err) + } + defer rows.Close() + + var items []Chat + for rows.Next() { + var c Chat + if err := rows.Scan(&c.ID, &c.Title, &c.CreatedAt); err != nil { + return nil, nil, mapWriteErr(err) + } + items = append(items, c) + } + if err := rows.Err(); err != nil { + return nil, nil, mapWriteErr(err) + } + next, items := trimPage(items, limit, func(c Chat) (time.Time, uuid.UUID) { + return c.CreatedAt, c.ID + }) + for i := range items { + members, err := s.memberIDs(ctx, items[i].ID) + if err != nil { + return nil, nil, err + } + items[i].MemberIDs = members + } + var cursor *PageCursor + if next { + last := items[len(items)-1] + cursor = &PageCursor{CreatedAt: last.CreatedAt, ID: last.ID} + } + return items, cursor, nil +} + +// CreateMessage пишет сообщение только если отправитель состоит в чате. +// Подтверждение — это COMMIT строки. Следующее чтение видит её без кэша истории. +// Без идемпотентности — только для внутренних/тестовых случаев; HTTP использует CreateMessageIdempotent. +func (s *Store) CreateMessage(ctx context.Context, chatID, senderID uuid.UUID, text string) (*Message, error) { + ctx, cancel := context.WithTimeout(ctx, queryTimeout) + defer cancel() + msg := &Message{ + ID: uuid.New(), + ChatID: chatID, + SenderID: senderID, + Text: text, + CreatedAt: nowUTC(), + // Внутренний путь без вложений; поле не nil, чтобы JSON дал [], а не null. + AttachmentIDs: []uuid.UUID{}, + } + tag, err := s.pool.Exec(ctx, ` + INSERT INTO messages (id, chat_id, sender_id, text, created_at) + SELECT $1, $2, $3, $4, $5 + WHERE EXISTS ( + SELECT 1 FROM chat_members WHERE chat_id = $2 AND user_id = $3 + )`, msg.ID, msg.ChatID, msg.SenderID, msg.Text, msg.CreatedAt) + if err != nil { + return nil, mapWriteErr(err) + } + if tag.RowsAffected() != 1 { + return nil, ErrNotFound + } + return msg, nil +} + +// IdempotentMessage — либо только что созданное, либо ранее сохранённое по ключу сообщение. +type IdempotentMessage struct { + Message *Message + Replayed bool +} + +// CreateMessageIdempotent атомарно создаёт сообщение и запоминает ответ по ключу. +// +// Алгоритм (общая БД, любые реплики): +// 1. BEGIN; +// 2. pg_advisory_xact_lock по хешу (user, method, path, key) — сериализует конкурентов +// ещё до INSERT messages, иначе два победителя гонки успели бы создать два сообщения; +// 3. SELECT сохранённого ключа — если есть, сравнить hash и вернуть Message; +// 4. иначе проверить членство, затем вложения (lab4): все принадлежат ЭТОМУ чату и ready, +// строки блокируются FOR SHARE, чтобы удаление (reconciler) не вклинилось до COMMIT; +// 5. INSERT message + INSERT message_attachments + INSERT idempotency_keys в той же +// транзакции: сообщение либо видно целиком вместе со ссылками на вложения, либо нет; +// 6. COMMIT (advisory lock снимается вместе с транзакцией). +// +// Чужое и неизвестное вложение (в т.ч. из другого чата) неразличимы: оба дают ErrNotFound +// (HTTP 404), чтобы нельзя было перебором выяснить, существует ли чужой файл. +// +// Другой request_hash → ErrIdempotencyConflict. Транзиентный 5xx сюда не попадает: +// запись ключа только после успешной подготовки 201. +func (s *Store) CreateMessageIdempotent( + ctx context.Context, + chatID, senderID uuid.UUID, + text string, + attachmentIDs []uuid.UUID, + method, path, idemKey, requestHash string, +) (*IdempotentMessage, error) { + ctx, cancel := context.WithTimeout(ctx, queryTimeout) + defer cancel() + + tx, err := s.pool.Begin(ctx) + if err != nil { + return nil, mapWriteErr(err) + } + defer func() { _ = tx.Rollback(ctx) }() + + lockKey := idempotencyLockKey(senderID, method, path, idemKey) + if _, err := tx.Exec(ctx, `SELECT pg_advisory_xact_lock($1)`, lockKey); err != nil { + return nil, mapWriteErr(err) + } + + var ( + storedHash string + msgID uuid.UUID + msgChat uuid.UUID + msgSender uuid.UUID + msgText string + msgCreated time.Time + ) + err = tx.QueryRow(ctx, ` + SELECT i.request_hash, m.id, m.chat_id, m.sender_id, m.text, m.created_at + FROM idempotency_keys i + JOIN messages m ON m.id = i.message_id + WHERE i.user_id = $1 AND i.method = $2 AND i.path = $3 AND i.key = $4`, + senderID, method, path, idemKey, + ).Scan(&storedHash, &msgID, &msgChat, &msgSender, &msgText, &msgCreated) + if err == nil { + if storedHash != requestHash { + return nil, ErrIdempotencyConflict + } + // Replay обязан вернуть ТОТ ЖЕ набор вложений, что и первый ответ. + replayIDs, err := loadMessageAttachmentIDs(ctx, tx, msgID) + if err != nil { + return nil, err + } + if err := tx.Commit(ctx); err != nil { + return nil, mapWriteErr(err) + } + return &IdempotentMessage{ + Message: &Message{ + ID: msgID, + ChatID: msgChat, + SenderID: msgSender, + Text: msgText, + CreatedAt: msgCreated, + AttachmentIDs: replayIDs, + }, + Replayed: true, + }, nil + } + if !errors.Is(err, pgx.ErrNoRows) { + return nil, mapWriteErr(err) + } + + var member int + if err := tx.QueryRow(ctx, ` + SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2`, chatID, senderID).Scan(&member); err != nil { + if errors.Is(err, pgx.ErrNoRows) { + return nil, ErrNotFound + } + return nil, mapWriteErr(err) + } + + // Вложения проверяем ПОСЛЕ членства: посторонний в чат получает 404 по чату, + // а не информацию о существовании файлов. + if err := lockMessageAttachments(ctx, tx, chatID, attachmentIDs); err != nil { + return nil, err + } + + msg := &Message{ + ID: uuid.New(), + ChatID: chatID, + SenderID: senderID, + Text: text, + CreatedAt: nowUTC(), + AttachmentIDs: append([]uuid.UUID{}, attachmentIDs...), + } + if _, err := tx.Exec(ctx, ` + INSERT INTO messages (id, chat_id, sender_id, text, created_at) + VALUES ($1, $2, $3, $4, $5)`, + msg.ID, msg.ChatID, msg.SenderID, msg.Text, msg.CreatedAt); err != nil { + return nil, mapWriteErr(err) + } + // Порядок attachment_ids клиента сохраняется в position. + for i, aid := range attachmentIDs { + if _, err := tx.Exec(ctx, ` + INSERT INTO message_attachments (message_id, attachment_id, position) + VALUES ($1, $2, $3)`, msg.ID, aid, i); err != nil { + return nil, mapWriteErr(err) + } + } + + // response_body заполняем каноническим Message JSON уже здесь, чтобы replay + // не зависел от повторной сериализации в HTTP-слое с другим порядком полей. + attachmentStrs := make([]string, len(msg.AttachmentIDs)) + for i, aid := range msg.AttachmentIDs { + attachmentStrs[i] = aid.String() + } + bodyJSON, err := json.Marshal(map[string]any{ + "id": msg.ID.String(), + "chat_id": msg.ChatID.String(), + "sender_id": msg.SenderID.String(), + "text": msg.Text, + "created_at": msg.CreatedAt.UTC().Truncate(time.Millisecond).Format("2006-01-02T15:04:05.000Z"), + "attachment_ids": attachmentStrs, + }) + if err != nil { + return nil, err + } + if _, err = tx.Exec(ctx, ` + INSERT INTO idempotency_keys ( + user_id, method, path, key, request_hash, + response_status, response_body, message_id, created_at + ) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9)`, + senderID, method, path, idemKey, requestHash, + 201, bodyJSON, msg.ID, msg.CreatedAt); err != nil { + return nil, mapWriteErr(err) + } + if err := tx.Commit(ctx); err != nil { + return nil, mapWriteErr(err) + } + return &IdempotentMessage{Message: msg, Replayed: false}, nil +} + +// idempotencyLockKey — стабильный int64 для pg_advisory_xact_lock из области ключа. +func idempotencyLockKey(userID uuid.UUID, method, path, key string) int64 { + sum := sha256.Sum256([]byte(userID.String() + "|" + method + "|" + path + "|" + key)) + return int64(binary.BigEndian.Uint64(sum[:8])) +} + +// ListMessages — keyset по индексу messages_history_idx. Берём limit+1 строку, +// чтобы next_cursor был null, когда следующей записи уже нет. +func (s *Store) ListMessages(ctx context.Context, chatID, userID uuid.UUID, limit int, after *PageCursor) ([]Message, *PageCursor, error) { + if err := s.ensureMember(ctx, chatID, userID); err != nil { + return nil, nil, err + } + ctx, cancel := context.WithTimeout(ctx, queryTimeout) + defer cancel() + var ( + rows pgx.Rows + err error + ) + if after == nil { + rows, err = s.pool.Query(ctx, ` + SELECT id, chat_id, sender_id, text, created_at + FROM messages + WHERE chat_id = $1 + ORDER BY created_at, id + LIMIT $2`, chatID, limit+1) + } else { + rows, err = s.pool.Query(ctx, ` + SELECT id, chat_id, sender_id, text, created_at + FROM messages + WHERE chat_id = $1 + AND (created_at, id) > ($2, $3) + ORDER BY created_at, id + LIMIT $4`, chatID, after.CreatedAt, after.ID, limit+1) + } + if err != nil { + return nil, nil, mapWriteErr(err) + } + defer rows.Close() + var items []Message + for rows.Next() { + var m Message + if err := rows.Scan(&m.ID, &m.ChatID, &m.SenderID, &m.Text, &m.CreatedAt); err != nil { + return nil, nil, mapWriteErr(err) + } + items = append(items, m) + } + if err := rows.Err(); err != nil { + return nil, nil, mapWriteErr(err) + } + hasNext, items := trimPage(items, limit, func(m Message) (time.Time, uuid.UUID) { + return m.CreatedAt, m.ID + }) + // Вложения страницы одним запросом (а не N+1): WHERE message_id = ANY(id страницы). + if err := s.attachMessageAttachments(ctx, items); err != nil { + return nil, nil, err + } + var cursor *PageCursor + if hasNext { + last := items[len(items)-1] + cursor = &PageCursor{CreatedAt: last.CreatedAt, ID: last.ID} + } + return items, cursor, nil +} + +// ChatExistsForTitle помогает тесту отката: после ошибки создания чата строки нет. +func (s *Store) CountChatsByTitle(ctx context.Context, title string) (int, error) { + ctx, cancel := context.WithTimeout(ctx, queryTimeout) + defer cancel() + var n int + err := s.pool.QueryRow(ctx, `SELECT count(*) FROM chats WHERE title = $1`, title).Scan(&n) + if err != nil { + return 0, mapWriteErr(err) + } + return n, nil +} + +// IsChatMember — проверка членства для HTTP-слоя (например, до чтения тела загрузки: +// постороннему не нужно тратить на себя RAM и трафик). ErrNotFound — не участник. +func (s *Store) IsChatMember(ctx context.Context, chatID, userID uuid.UUID) error { + return s.ensureMember(ctx, chatID, userID) +} + +func (s *Store) ensureMember(ctx context.Context, chatID, userID uuid.UUID) error { + ctx, cancel := context.WithTimeout(ctx, queryTimeout) + defer cancel() + var one int + err := s.pool.QueryRow(ctx, ` + SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2`, chatID, userID).Scan(&one) + if errors.Is(err, pgx.ErrNoRows) { + return ErrNotFound + } + if err != nil { + return mapWriteErr(err) + } + return nil +} + +func (s *Store) loadChat(ctx context.Context, chatID uuid.UUID) (*Chat, error) { + ctx, cancel := context.WithTimeout(ctx, queryTimeout) + defer cancel() + var c Chat + err := s.pool.QueryRow(ctx, `SELECT id, title, created_at FROM chats WHERE id = $1`, chatID). + Scan(&c.ID, &c.Title, &c.CreatedAt) + if errors.Is(err, pgx.ErrNoRows) { + return nil, ErrNotFound + } + if err != nil { + return nil, mapWriteErr(err) + } + c.MemberIDs, err = s.memberIDs(ctx, chatID) + if err != nil { + return nil, err + } + return &c, nil +} + +func (s *Store) memberIDs(ctx context.Context, chatID uuid.UUID) ([]uuid.UUID, error) { + rows, err := s.pool.Query(ctx, ` + SELECT user_id FROM chat_members WHERE chat_id = $1 ORDER BY user_id`, chatID) + if err != nil { + return nil, mapWriteErr(err) + } + defer rows.Close() + var ids []uuid.UUID + for rows.Next() { + var id uuid.UUID + if err := rows.Scan(&id); err != nil { + return nil, mapWriteErr(err) + } + ids = append(ids, id) + } + return ids, mapWriteErr(rows.Err()) +} + +func trimPage[T any](items []T, limit int, _ func(T) (time.Time, uuid.UUID)) (bool, []T) { + if len(items) > limit { + return true, items[:limit] + } + return false, items +} + +func nowUTC() time.Time { + // Миллисекунда — точность, которую мы же и печатаем в JSON. + return time.Now().UTC().Truncate(time.Millisecond) +} + +func mapWriteErr(err error) error { + if err == nil { + return nil + } + var pgErr *pgconn.PgError + if errors.As(err, &pgErr) && pgErr.Code == "23505" { + return ErrConflict + } + if errors.Is(err, context.DeadlineExceeded) || isConn(err) { + return ErrUnavailable + } + return err +} + +func isConn(err error) bool { + msg := err.Error() + // Не логируем и не возвращаем клиенту эту строку. Здесь только классификация. + switch { + case errors.Is(err, pgx.ErrNoRows): + return false + default: + if stringsContains(msg, "connection refused") || + stringsContains(msg, "failed to connect") || + stringsContains(msg, "conn closed") || + stringsContains(msg, "closed pool") || + stringsContains(msg, "broken pipe") || + stringsContains(msg, "connection reset") || + stringsContains(msg, "SQLSTATE 57P01") || + stringsContains(msg, "SQLSTATE 08006") || + stringsContains(msg, "SQLSTATE 08001") { + return true + } + } + return false +} + +func stringsContains(s, sub string) bool { + return len(s) >= len(sub) && (s == sub || len(sub) == 0 || + (func() bool { return contains(s, sub) })()) +} + +func contains(s, sub string) bool { + for i := 0; i+len(sub) <= len(s); i++ { + if s[i:i+len(sub)] == sub { + return true + } + } + return false +} diff --git a/scripts/_lib.sh b/scripts/_lib.sh new file mode 100755 index 00000000..059a10fa --- /dev/null +++ b/scripts/_lib.sh @@ -0,0 +1,44 @@ +# Общие функции для скриптов lab4 (подключается через `. scripts/_lib.sh`). + +env_get() { + v=$(grep -E "^$1=" .env 2>/dev/null | tail -n1 | cut -d= -f2- || true) + if [ -n "$v" ]; then printf '%s' "$v"; else printf '%s' "$2"; fi +} + +DC="docker compose -p gavrilenko-lab4 --env-file .env" +LB_PORT=$(env_get LB_HOST_PORT 8081) +MINIO_PORT=$(env_get MINIO_HOST_PORT 9002) +S3_BUCKET=$(env_get S3_BUCKET messenger) +BASE_URL=${BASE_URL:-http://127.0.0.1:${LB_PORT}} + +json_get() { python3 -c 'import json,sys; print(json.load(sys.stdin)[sys.argv[1]])' "$1"; } + +register_and_login() { + name="u$(date +%s)$$$(awk 'BEGIN{srand(); printf "%05d", rand()*99999}')" + pw="correct-horse-1" + uid=$(curl -fsS -X POST "$BASE_URL/api/v1/users" -H 'Content-Type: application/json' \ + -d "{\"username\":\"$name\",\"display_name\":\"Script\",\"password\":\"$pw\"}" | json_get id) + tok=$(curl -fsS -X POST "$BASE_URL/api/v1/auth/sessions" -u "$name:$pw" | json_get token) + printf '%s %s' "$tok" "$uid" +} + +create_chat() { + curl -fsS -X POST "$BASE_URL/api/v1/chats" -H "Authorization: Bearer $1" -H 'Content-Type: application/json' \ + -d "{\"title\":\"script\",\"member_ids\":[\"$2\"]}" | json_get id +} + +upload_file() { + curl -fsS -X POST "$BASE_URL/api/v1/chats/$2/attachments?filename=$(basename "$3")" \ + -H "Authorization: Bearer $1" -H "Content-Type: ${4:-image/png}" --data-binary "@$3" +} + +psql_q() { + $DC exec -T postgres sh -c 'psql -U "$POSTGRES_USER" -d "$POSTGRES_DB" -Atc "$1"' _ "$1" +} + +s3sh() { + $DC run --rm -T --no-deps --entrypoint /bin/sh minio-init -c \ + "mc alias set local http://minio:9000 \"\$MINIO_ROOT_USER\" \"\$MINIO_ROOT_PASSWORD\" >/dev/null && $1" +} + +uuid() { python3 -c 'import uuid; print(uuid.uuid4())'; } \ No newline at end of file diff --git a/scripts/check_private_bucket.sh b/scripts/check_private_bucket.sh new file mode 100755 index 00000000..284826d3 --- /dev/null +++ b/scripts/check_private_bucket.sh @@ -0,0 +1,73 @@ +#!/bin/sh +# Проверка «приватный bucket вне API» (критерий уровня 4): +# 1) анонимный GET объекта → 403, анонимный листинг и PUT → отказ; +# 2) контроль: тот же объект с SigV4-подписью учётки messenger-api читается (значит +# отказ в п.1 — из-за приватности, а не из-за отсутствия файла); +# 3) учётка API ограничена bucket-ом: ListBuckets и другой bucket запрещены; +# 4) консоль MinIO наружу не опубликована (порт 9001 не слушает на хосте). +# Требует поднятого стенда (scripts/up.sh), curl >= 7.75 (--aws-sigv4), python3. +set -eu +ROOT=$(CDPATH= cd -- "$(dirname "$0")/.." && pwd) +cd "$ROOT" +. scripts/_lib.sh + +S3_URL="http://127.0.0.1:${MINIO_PORT}" +AK=$(env_get S3_ACCESS_KEY messenger-api) +SK=$(env_get S3_SECRET_KEY messenger-api-secret-change-me) +REGION=$(env_get S3_REGION us-east-1) +fail=0 +pass() { echo "PASS $*"; } +bad() { echo "FAIL $*"; fail=1; } + +# code URL [curl args...] → HTTP-код (000 при отказе соединения) +code() { u=$1; shift; curl -s -o /dev/null -w '%{http_code}' --max-time 5 "$@" "$u" || true; } + +echo "== подготовка: загрузить реальное вложение через API и узнать его object_key" +set -- $(register_and_login); TOK=$1; UID_=$2 +CHAT=$(create_chat "$TOK" "$UID_") +SAMPLE=tests/fixtures/sample.png +ATT=$(upload_file "$TOK" "$CHAT" "$SAMPLE" | json_get id) +KEY=$(psql_q "SELECT object_key FROM attachments WHERE id='$ATT'") +[ -n "$KEY" ] || { echo "не нашли object_key в БД" >&2; exit 2; } +echo "attachment=$ATT (ключ в S3 внутренний, в ответах API его нет)" + +echo "== 1. анонимный доступ" +c=$(code "$S3_URL/$S3_BUCKET/$KEY"); [ "$c" = 403 ] && pass "анонимный GET объекта → $c" || bad "анонимный GET объекта → $c (ждали 403)" +c=$(code "$S3_URL/$S3_BUCKET/"); [ "$c" = 403 ] && pass "анонимный листинг bucket → $c" || bad "анонимный листинг bucket → $c (ждали 403)" +c=$(code "$S3_URL/$S3_BUCKET/anon-probe.txt" -X PUT --data x); [ "$c" = 403 ] && pass "анонимный PUT → $c" || bad "анонимный PUT → $c (ждали 403)" + +echo "== 2. контроль: подписанный запрос учётки messenger-api" +c=$(code "$S3_URL/$S3_BUCKET/$KEY" --user "$AK:$SK" --aws-sigv4 "aws:amz:$REGION:s3") +[ "$c" = 200 ] && pass "GET с подписью messenger-api → $c (объект существует)" || bad "GET с подписью → $c (ждали 200; нужен curl >= 7.75)" + +echo "== 3. права учётки API ограничены bucket-ом" +# Второй bucket создаёт root (только для проверки). MinIO отвечает на ListBuckets 200 любому +# аутентифицированному пользователю, но показывает лишь доступные ему buckets. +OTHER="other-probe-$(date +%s)" +s3sh "mc mb --ignore-existing local/$OTHER >/dev/null && echo secret | mc pipe local/$OTHER/x >/dev/null" +cleanup_other() { s3sh "mc rb --force local/$OTHER >/dev/null 2>&1" >/dev/null 2>&1 || true; } +trap cleanup_other EXIT +list=$(curl -s --max-time 5 --user "$AK:$SK" --aws-sigv4 "aws:amz:$REGION:s3" "$S3_URL/" || true) +case "$list" in + *"$OTHER"*) bad "ListBuckets показывает чужой bucket $OTHER";; + *) pass "ListBuckets не раскрывает чужие buckets";; +esac +c=$(code "$S3_URL/$OTHER/x" --user "$AK:$SK" --aws-sigv4 "aws:amz:$REGION:s3") +[ "$c" = 403 ] && pass "чтение объекта в чужом bucket → $c" || bad "чтение объекта в чужом bucket → $c (ждали 403)" +c=$(code "$S3_URL/$OTHER/" --user "$AK:$SK" --aws-sigv4 "aws:amz:$REGION:s3") +[ "$c" = 403 ] && pass "листинг чужого bucket → $c" || bad "листинг чужого bucket → $c (ждали 403)" +c=$(code "$S3_URL/$OTHER/y" -X PUT --data x --user "$AK:$SK" --aws-sigv4 "aws:amz:$REGION:s3") +[ "$c" = 403 ] && pass "запись в чужой bucket → $c" || bad "запись в чужой bucket → $c (ждали 403)" +c=$(code "$S3_URL/new-bucket-probe-$(date +%s)" -X PUT --user "$AK:$SK" --aws-sigv4 "aws:amz:$REGION:s3") +[ "$c" = 403 ] && pass "CreateBucket → $c" || bad "CreateBucket → $c (ждали 403)" + +echo "== 4. консоль MinIO не опубликована" +c=$(code "http://127.0.0.1:9001/") +{ [ "$c" = 000 ] || [ "$c" = 404 ]; } && pass "127.0.0.1:9001 не отвечает консолью ($c)" || bad "127.0.0.1:9001 отвечает: $c" +if $DC port minio 9001 2>/dev/null | grep -q .; then bad "docker compose port minio 9001 → опубликован"; else pass "порт 9001 сервиса minio не опубликован"; fi +pub=$($DC ps minio --format '{{.Publishers}}' 2>/dev/null || true) +echo "публикуемые порты minio: $pub" +case "$pub" in *9001*) bad "в Publishers есть 9001";; *) pass "в Publishers нет 9001";; esac +case "$pub" in *0.0.0.0:9000*|*"[::]:9000"*) bad "S3 API опубликован на все интерфейсы";; *) pass "S3 API только на 127.0.0.1";; esac + +[ "$fail" = 0 ] && echo "ИТОГ: bucket приватный" || { echo "ИТОГ: ЕСТЬ ОШИБКИ"; exit 1; } diff --git a/scripts/restart.sh b/scripts/restart.sh new file mode 100755 index 00000000..38f048ed --- /dev/null +++ b/scripts/restart.sh @@ -0,0 +1,6 @@ +#!/bin/sh +# Перезапуск API (всех реплик), LB и хранилищ (postgres, redis, minio) без удаления volumes. +set -eu +ROOT=$(CDPATH= cd -- "$(dirname "$0")/.." && pwd) +cd "$ROOT" +docker compose -p gavrilenko-lab4 --env-file .env restart postgres redis minio api lb \ No newline at end of file diff --git a/scripts/restore-one.sh b/scripts/restore-one.sh new file mode 100755 index 00000000..0dace002 --- /dev/null +++ b/scripts/restore-one.sh @@ -0,0 +1,27 @@ +#!/bin/sh +# Восстанавливает остановленную API-реплику после failover-теста. +set -eu +ROOT=$(CDPATH= cd -- "$(dirname "$0")/.." && pwd) +cd "$ROOT" +COMPOSE="docker compose -p gavrilenko-lab4 --env-file .env" + +API_REPLICAS=$(grep -E '^API_REPLICAS=' .env | cut -d= -f2- || true) +API_REPLICAS=${API_REPLICAS:-2} +LB_PORT=$(grep -E '^LB_HOST_PORT=' .env | cut -d= -f2- || true) +LB_PORT=${LB_PORT:-8081} + +$COMPOSE start api 2>/dev/null || true +$COMPOSE up -d --no-deps --scale "api=${API_REPLICAS}" api + +deadline=$(( $(date +%s) + 90 )) +while :; do + if curl -fsS "http://127.0.0.1:${LB_PORT}/health/ready" >/dev/null 2>&1; then + exit 0 + fi + if [ "$(date +%s)" -ge "$deadline" ]; then + echo "timeout waiting for api recovery" >&2 + $COMPOSE ps >&2 || true + exit 1 + fi + sleep 1 +done \ No newline at end of file diff --git a/scripts/stop-one.sh b/scripts/stop-one.sh new file mode 100755 index 00000000..44916cc7 --- /dev/null +++ b/scripts/stop-one.sh @@ -0,0 +1,39 @@ +#!/bin/sh +# Останавливает одну API-реплику с X-Instance-Id = TARGET_INSTANCE_ID. +set -eu +: "${TARGET_INSTANCE_ID:?test provides target API instance alias}" + +ROOT=$(CDPATH= cd -- "$(dirname "$0")/.." && pwd) +cd "$ROOT" + +ids=$(docker compose -p gavrilenko-lab4 --env-file .env ps -q api) +if [ -z "$ids" ]; then + echo "no api containers" >&2 + exit 1 +fi + +found=0 +for id in $ids; do + hostname=$(docker inspect -f '{{.Config.Hostname}}' "$id") + env_id=$(docker inspect -f '{{range .Config.Env}}{{println .}}{{end}}' "$id" | sed -n 's/^INSTANCE_ID=//p' | head -n1) + match=$hostname + if [ -n "$env_id" ]; then + match=$env_id + fi + if [ "$match" = "$TARGET_INSTANCE_ID" ]; then + docker stop -t 8 "$id" >/dev/null + state=$(docker inspect -f '{{.State.Running}}' "$id") + if [ "$state" = "true" ]; then + echo "container still running after stop" >&2 + exit 1 + fi + found=1 + break + fi +done + +if [ "$found" -ne 1 ]; then + echo "TARGET_INSTANCE_ID not found among api replicas" >&2 + exit 1 +fi +exit 0 \ No newline at end of file diff --git a/scripts/up.sh b/scripts/up.sh new file mode 100755 index 00000000..796349aa --- /dev/null +++ b/scripts/up.sh @@ -0,0 +1,40 @@ +#!/bin/sh +# Единая последовательность запуска стенда lab4 (postgres, redis, minio, minio-init, migrate, api×N, lb). +set -eu +ROOT=$(CDPATH= cd -- "$(dirname "$0")/.." && pwd) +cd "$ROOT" +COMPOSE="docker compose -p gavrilenko-lab4 --env-file .env" + +if [ ! -f .env ]; then + cp .env.example .env + echo "created .env from .env.example" >&2 +fi + +API_REPLICAS=$(grep -E '^API_REPLICAS=' .env | tail -n1 | cut -d= -f2- || true) +API_REPLICAS=${API_REPLICAS:-2} +LB_PORT=$(grep -E '^LB_HOST_PORT=' .env | tail -n1 | cut -d= -f2- || true) +LB_PORT=${LB_PORT:-8081} + +$COMPOSE config --quiet +$COMPOSE up -d --build --wait postgres redis minio +$COMPOSE run --rm minio-init +$COMPOSE run --rm --build migrate +$COMPOSE up -d --build --scale "api=${API_REPLICAS}" --no-deps api +$COMPOSE up -d --no-deps lb + +echo "waiting for http://127.0.0.1:${LB_PORT}/health/ready via LB..." +deadline=$(( $(date +%s) + 120 )) +while :; do + if curl -fsS "http://127.0.0.1:${LB_PORT}/health/ready" >/dev/null 2>&1; then + echo "ready" + $COMPOSE ps + exit 0 + fi + if [ "$(date +%s)" -ge "$deadline" ]; then + echo "timeout waiting for readiness" >&2 + $COMPOSE ps >&2 || true + $COMPOSE logs --tail=80 api lb minio >&2 || true + exit 1 + fi + sleep 1 +done \ No newline at end of file diff --git a/scripts/upload_mem_experiment.sh b/scripts/upload_mem_experiment.sh new file mode 100755 index 00000000..a86f2157 --- /dev/null +++ b/scripts/upload_mem_experiment.sh @@ -0,0 +1,120 @@ +#!/bin/sh +# Эксперимент «≥10 одновременных загрузок → пик памяти API» (критерий уровня 4). +# +# Гипотеза: тело загрузки буферизуется целиком (нужно проверить содержимое и SHA-256 до записи +# в S3), поэтому БЕЗ ограничения пик RAM растёт как N * размер файла и упирается в лимит +# контейнера (OOM). Семафор UPLOAD_MAX_CONCURRENCY держит пик около слоты * 10 MiB, а лишние +# загрузки ждут в очереди, не читая тело. +# +# Методика: N одновременных curl, каждый ROUNDS раз подряд шлёт файл ~8 MB (PNG-шум 1600x1600, +# 2,56 Мпикс > порога полного декода) через LB. Пока идёт нагрузка, `docker stats` в потоковом +# режиме пишет потребление памяти каждой реплики API; берётся максимум. Сравниваются +# UPLOAD_MAX_CONCURRENCY=64 («без ограничения») и значение из .env (по умолчанию 4). +# +# Параметры (env): CONCURRENCY=20 ROUNDS=4 COMPARE_LIMITS="64 4" SIZE_PX=1600 +# Результат: evidence/upload-memory/{summary.txt,*.stats}. Токены и тела файлов не сохраняются. +set -eu +ROOT=$(CDPATH= cd -- "$(dirname "$0")/.." && pwd) +cd "$ROOT" +. scripts/_lib.sh + +CONCURRENCY=${CONCURRENCY:-20} +ROUNDS=${ROUNDS:-4} +SIZE_PX=${SIZE_PX:-1600} +COMPARE_LIMITS=${COMPARE_LIMITS:-"64 $(env_get UPLOAD_MAX_CONCURRENCY 4)"} +REPLICAS=$(env_get API_REPLICAS 2) +OUT=evidence/upload-memory +TMP=$(mktemp -d) +trap 'rm -rf "$TMP"; kill $(cat "$TMP/stats.pid" 2>/dev/null) 2>/dev/null || true' EXIT +mkdir -p "$OUT"; rm -f "$OUT"/*.stats "$OUT/summary.txt" + +echo "== генерация PNG-шума ${SIZE_PX}x${SIZE_PX}" +python3 - "$TMP/big.png" "$SIZE_PX" <<'PY' +import os, struct, sys, zlib +path, n = sys.argv[1], int(sys.argv[2]) +raw = b"".join(b"\x00" + os.urandom(n * 3) for _ in range(n)) # фильтр 0 + RGB-шум, не сжимается +def chunk(t, d): + c = struct.pack(">I", len(d)) + t + d + return c + struct.pack(">I", zlib.crc32(t + d) & 0xFFFFFFFF) +png = b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", n, n, 8, 2, 0, 0, 0)) \ + + chunk(b"IDAT", zlib.compress(raw, 1)) + chunk(b"IEND", b"") +open(path, "wb").write(png) +print("размер файла: %.2f MiB" % (len(png) / 1048576)) +PY +FILE_BYTES=$(wc -c < "$TMP/big.png" | tr -d ' ') +[ "$FILE_BYTES" -le 10485760 ] || { echo "файл больше 10 MiB, уменьшите SIZE_PX" >&2; exit 1; } + +set -- $(register_and_login); TOK=$1; UID_=$2 +CHAT=$(create_chat "$TOK" "$UID_") + +# Пиковая память: разбираем строки `docker stats --format '{{.Name}} {{.MemUsage}}'`. +peak_mib() { # peak_mib FILE → "имя: idle=… peak=…" на каждую реплику + python3 - "$1" <<'PY' +import re, sys +unit = {"B": 1/1048576, "KiB": 1/1024, "MiB": 1, "GiB": 1024, "kB": 1/1048.576, "MB": 0.9537, "GB": 976.6} +first, peak = {}, {} +ansi = re.compile(r"\x1b\[[0-9;?]*[A-Za-z]") +for line in open(sys.argv[1], errors="ignore"): + line = ansi.sub("", line) # docker stats рисует поток с escape-последовательностями + m = re.search(r"(\S*api\S*)\s+([\d.]+)\s*([KMG]i?B|B)\s*/", line) + if m: + v = float(m.group(2)) * unit[m.group(3)] + first.setdefault(m.group(1), v) # первый замер — до нагрузки + peak[m.group(1)] = max(peak.get(m.group(1), 0), v) +for k in sorted(peak): + print("%s: idle=%.1f peak=%.1f" % (k, first[k], peak[k])) +PY +} + +run_case() { # run_case LIMIT + limit=$1 + echo "== случай UPLOAD_MAX_CONCURRENCY=$limit: пересоздаём API (replicas=$REPLICAS)" + UPLOAD_MAX_CONCURRENCY=$limit $DC up -d --no-deps --force-recreate --scale "api=$REPLICAS" api >/dev/null 2>&1 + i=0; until curl -fsS "$BASE_URL/health/ready" >/dev/null 2>&1; do i=$((i+1)); [ $i -lt 90 ] || { echo "API не поднялся" >&2; exit 1; }; sleep 1; done + sleep 5 # дать прогреться и снять «базовую» память до нагрузки + + stats="$OUT/limit_${limit}.stats" + : > "$stats" + docker stats --format '{{.Name}} {{.MemUsage}}' $($DC ps -q api) >> "$stats" 2>/dev/null & + echo $! > "$TMP/stats.pid" + sleep 3 + + : > "$TMP/codes" + start=$(date +%s) + w=0; pids="" + while [ $w -lt "$CONCURRENCY" ]; do + ( + r=0 + while [ $r -lt "$ROUNDS" ]; do + curl -s -o /dev/null -w '%{http_code} %{time_total}\n' --max-time 60 -X POST \ + "$BASE_URL/api/v1/chats/$CHAT/attachments?filename=load.png" \ + -H "Authorization: Bearer $TOK" -H 'Content-Type: image/png' --data-binary "@$TMP/big.png" >> "$TMP/codes" || echo "000 0" >> "$TMP/codes" + r=$((r+1)) + done + ) & + pids="$pids $!" + w=$((w+1)) + done + wait $pids 2>/dev/null || true + elapsed=$(( $(date +%s) - start )) + sleep 3 + kill "$(cat "$TMP/stats.pid")" 2>/dev/null || true + + { + echo "--- UPLOAD_MAX_CONCURRENCY=$limit (параллельных клиентов=$CONCURRENCY, повторов=$ROUNDS, файл=$FILE_BYTES байт, длительность=${elapsed}s)" + echo "статусы HTTP: $(awk '{print $1}' "$TMP/codes" | sort | uniq -c | tr '\n' ' ')" + python3 -c 'import sys; t=sorted(float(l.split()[1]) for l in open(sys.argv[1]) if l.strip()); print("время ответа: min=%.2fs p50=%.2fs max=%.2fs" % (t[0], t[len(t)//2], t[-1])) if t else None' "$TMP/codes" + echo "пик памяти реплик, MiB (лимит контейнера $(env_get API_MEMORY 256M)):" + peak_mib "$stats" | sed 's/^/ /' + } | tee -a "$OUT/summary.txt" +} + +{ + echo "# Эксперимент пика памяти при одновременных загрузках" + echo "# дата: $(date -u +%Y-%m-%dT%H:%M:%SZ), реплик API: $REPLICAS, commit: $(git rev-parse --short HEAD 2>/dev/null || echo n/a)" +} > "$OUT/summary.txt" +for l in $COMPARE_LIMITS; do run_case "$l"; done + +# Вернуть стенд к значению из .env. +$DC up -d --no-deps --force-recreate --scale "api=$REPLICAS" api >/dev/null 2>&1 +echo "готово: $OUT/summary.txt" diff --git a/student-tests/api_test.go b/student-tests/api_test.go new file mode 100644 index 00000000..1288b159 --- /dev/null +++ b/student-tests/api_test.go @@ -0,0 +1,673 @@ +// Собственные проверки lab3 (плюс регрессия lab2) и lab4 (см. attachments_test.go, +// reconcile_test.go). Им нужен уже поднятый PostgreSQL, Redis и MinIO +// (docker compose up / scripts/up.sh): контракт требует настоящую БД и настоящий S3, +// а не sqlmock. HTTP бьём в httptest.Server поверх того же Store, +// что и реплики — идемпотентность и гонки видны без обхода LB. +// +// Каждый тест пишет в лог, что именно проверяет и какой статус получил. +package studenttests + +import ( + "bytes" + "context" + "encoding/base64" + "encoding/json" + "fmt" + "io" + "net/http" + "net/http/httptest" + "os" + "strings" + "sync" + "testing" + "time" + + "github.com/google/uuid" + + "gavrilenko-sxdees/lab4/internal/api" + "gavrilenko-sxdees/lab4/internal/auth" + "gavrilenko-sxdees/lab4/internal/objectstore" + "gavrilenko-sxdees/lab4/internal/session" + "gavrilenko-sxdees/lab4/internal/store" +) + +var ( + sharedStore *store.Store + sharedSessions *session.Store + sharedRedisURL string + // sharedObjects — клиент к тому же MinIO, что и реплики (учётка messenger-api, не root). + sharedObjects *objectstore.Store +) + +func TestMain(m *testing.M) { + ctx := context.Background() + dsn := getenv("DATABASE_URL", "postgres://messenger:messenger@127.0.0.1:5432/messenger?sslmode=disable") + sharedRedisURL = getenv("REDIS_URL", "redis://127.0.0.1:6379/0") + hasher, err := auth.NewHasher() + if err != nil { + fmt.Fprintln(os.Stderr, "hasher:", err) + os.Exit(1) + } + sharedStore, err = store.Open(ctx, dsn, hasher, 5) + if err != nil { + fmt.Fprintln(os.Stderr, "postgres:", err) + fmt.Fprintln(os.Stderr, "подсказка: docker compose --env-file .env up -d --build") + os.Exit(1) + } + defer sharedStore.Close() + if err := sharedStore.Migrate(ctx); err != nil { + fmt.Fprintln(os.Stderr, "migrate:", err) + os.Exit(1) + } + // Повтор миграции не должен падать и не должен дублировать данные. + if err := sharedStore.Migrate(ctx); err != nil { + fmt.Fprintln(os.Stderr, "migrate second:", err) + os.Exit(1) + } + sharedObjects, err = objectstore.New(objectstore.Config{ + Endpoint: getenv("S3_ENDPOINT", "http://127.0.0.1:9000"), + Region: getenv("S3_REGION", "us-east-1"), + Bucket: getenv("S3_BUCKET", "messenger"), + AccessKey: getenv("S3_ACCESS_KEY", "messenger-api"), + SecretKey: getenv("S3_SECRET_KEY", "messenger-api-secret-change-me"), + ForcePathStyle: true, + }) + if err != nil { + fmt.Fprintln(os.Stderr, "objectstore:", err) + os.Exit(1) + } + if err := sharedObjects.EnsureBucket(ctx); err != nil { + fmt.Fprintln(os.Stderr, "s3:", err) + fmt.Fprintln(os.Stderr, "подсказка: bash scripts/up.sh (MinIO на 127.0.0.1:${MINIO_HOST_PORT}); для нестандартных портов задайте S3_ENDPOINT") + os.Exit(1) + } + sharedSessions, err = session.Open(sharedRedisURL, time.Hour) + if err != nil { + fmt.Fprintln(os.Stderr, "redis:", err) + os.Exit(1) + } + defer sharedSessions.Close() + os.Exit(m.Run()) +} + +func TestMalformedJSONAndValidation(t *testing.T) { + srv := newAPI(t, time.Hour) + defer srv.Close() + logStep(t, "битый JSON, хвост после объекта, лишнее поле, пустой текст, чужой чат") + + status, body := do(t, srv, http.MethodPost, "/api/v1/users", nil, "{") + logResult(t, status, body) + if status != http.StatusBadRequest || !strings.Contains(body, "invalid_request") { + t.Fatalf("malformed json: status=%d body=%s", status, body) + } + + status, body = do(t, srv, http.MethodPost, "/api/v1/users", nil, + `{"username":"abc","display_name":"Имя","password":"correct-horse-1","extra":1}`) + logResult(t, status, body) + if status != http.StatusBadRequest { + t.Fatalf("extra field: status=%d", status) + } + + user := register(t, srv, "ok_user") + token := login(t, srv, user.username, user.password) + chat := createChat(t, srv, token, user.id, "Чат проверки") + auth := map[string]string{"Authorization": "Bearer " + token} + + // Decoder.More() это не ловит: один объект декодируется, лишняя скобка остаётся. + for _, raw := range []string{`{"text":"valid"}}`, `{"text":"valid"}]`} { + status, body = do(t, srv, http.MethodPost, "/api/v1/chats/"+chat+"/messages", auth, raw) + logResult(t, status, body) + if status != http.StatusBadRequest { + t.Fatalf("trailing garbage %q: status=%d body=%s", raw, status, body) + } + } + + status, body = do(t, srv, http.MethodPost, "/api/v1/chats/"+chat+"/messages", auth, `{"text":" "}`) + logResult(t, status, body) + if status != http.StatusBadRequest { + t.Fatalf("blank message: status=%d", status) + } + + outsider := register(t, srv, "outsider") + outTok := login(t, srv, outsider.username, outsider.password) + status, body = do(t, srv, http.MethodPost, "/api/v1/chats/"+chat+"/messages", map[string]string{"Authorization": "Bearer " + outTok}, `{"text":"чужое"}`) + logResult(t, status, body) + if status != http.StatusNotFound { + t.Fatalf("foreign chat: status=%d body=%s", status, body) + } + logOK(t, "валидация JSON, хвоста, пустого текста и чужого чата") +} + +func TestMessageTextPreservedAndLengthOnOriginal(t *testing.T) { + srv := newAPI(t, time.Hour) + defer srv.Close() + logStep(t, "пробелы по краям сохраняются; длина считается по исходному тексту") + user := register(t, srv, "text_user") + token := login(t, srv, user.username, user.password) + chat := createChat(t, srv, token, user.id, "Текст") + auth := map[string]string{"Authorization": "Bearer " + token} + + original := " строка\nс пробелами " + status, body := do(t, srv, http.MethodPost, "/api/v1/chats/"+chat+"/messages", auth, + fmt.Sprintf(`{"text":%q}`, original)) + logResult(t, status, body) + if status != http.StatusCreated { + t.Fatalf("preserve spaces: status=%d", status) + } + got := decode(t, body) + if got["text"] != original { + t.Fatalf("text mutated: got %q want %q", got["text"], original) + } + + tooLong := " " + strings.Repeat("a", 4000) // 4001 code points + status, body = do(t, srv, http.MethodPost, "/api/v1/chats/"+chat+"/messages", auth, + fmt.Sprintf(`{"text":%q}`, tooLong)) + logResult(t, status, body) + if status != http.StatusBadRequest { + t.Fatalf("length after trim bypass: status=%d body=%s", status, body) + } + logOK(t, "текст сохранён целиком, обход лимита через TrimSpace закрыт") +} + +func TestSessionRejectsJSONBody(t *testing.T) { + srv := newAPI(t, time.Hour) + defer srv.Close() + logStep(t, "POST /auth/sessions с телом должен быть 400 даже при верном Basic") + user := register(t, srv, "body_user") + status, body := do(t, srv, http.MethodPost, "/api/v1/auth/sessions", map[string]string{ + "Authorization": "Basic " + basic(user.username, user.password), + }, `{"extra":1}`) + logResult(t, status, body) + if status != http.StatusBadRequest { + t.Fatalf("session with body: status=%d body=%s", status, body) + } + logOK(t, "вход без JSON body") +} + +func TestWrongPasswordLogoutAndIgnoredUserHeader(t *testing.T) { + srv := newAPI(t, time.Hour) + defer srv.Close() + logStep(t, "неверный пароль, Basic на бизнес-методе, X-User-Id, logout") + user := register(t, srv, "auth_user") + other := register(t, srv, "auth_other") + + status, body, hdr := doRaw(t, srv, http.MethodPost, "/api/v1/auth/sessions", map[string]string{ + "Authorization": "Basic " + basic(user.username, "wrong-password-1"), + }, "") + logResult(t, status, body) + if status != http.StatusUnauthorized || !strings.HasPrefix(hdr.Get("WWW-Authenticate"), "Basic") { + t.Fatalf("wrong password: status=%d www=%q", status, hdr.Get("WWW-Authenticate")) + } + + token := login(t, srv, user.username, user.password) + status, body, hdr = doRaw(t, srv, http.MethodGet, "/api/v1/users/me", map[string]string{ + "Authorization": "Basic " + basic(user.username, user.password), + }, "") + logResult(t, status, body) + if status != http.StatusUnauthorized || !strings.HasPrefix(hdr.Get("WWW-Authenticate"), "Bearer") { + t.Fatalf("basic on business endpoint: status=%d www=%q", status, hdr.Get("WWW-Authenticate")) + } + + status, body = do(t, srv, http.MethodGet, "/api/v1/users/me", map[string]string{"X-User-Id": user.id}, "") + logResult(t, status, body) + if status != http.StatusUnauthorized { + t.Fatalf("X-User-Id alone: status=%d", status) + } + + status, body = do(t, srv, http.MethodGet, "/api/v1/users/me", map[string]string{ + "Authorization": "Bearer " + token, + "X-User-Id": other.id, + }, "") + logResult(t, status, body) + if status != http.StatusOK || !strings.Contains(body, user.id) || strings.Contains(body, other.id) { + t.Fatalf("X-User-Id overrode bearer: status=%d body=%s", status, body) + } + + status, _ = do(t, srv, http.MethodDelete, "/api/v1/auth/sessions/current", map[string]string{"Authorization": "Bearer " + token}, "") + t.Logf("logout status=%d", status) + if status != http.StatusNoContent { + t.Fatalf("logout status=%d", status) + } + status, _ = do(t, srv, http.MethodGet, "/api/v1/users/me", map[string]string{"Authorization": "Bearer " + token}, "") + if status != http.StatusUnauthorized { + t.Fatalf("token still valid after logout: %d", status) + } + status, _ = do(t, srv, http.MethodDelete, "/api/v1/auth/sessions/current", map[string]string{"Authorization": "Bearer " + token}, "") + if status != http.StatusUnauthorized { + t.Fatalf("second logout status=%d", status) + } + logOK(t, "пароль, заголовки и отзыв сессии") +} + +func TestSessionExpiry(t *testing.T) { + srv := newAPI(t, 2*time.Second) + defer srv.Close() + logStep(t, "SESSION_TTL=2s: тот же токен после паузы должен стать 401, TTL рестартом API не продлевается") + user := register(t, srv, "ttl_user") + token := login(t, srv, user.username, user.password) + time.Sleep(2500 * time.Millisecond) + status, body := do(t, srv, http.MethodGet, "/api/v1/users/me", map[string]string{"Authorization": "Bearer " + token}, "") + logResult(t, status, body) + if status != http.StatusUnauthorized { + t.Fatalf("expired token status=%d body=%s", status, body) + } + logOK(t, "истёкшая сессия отклонена") +} + +func TestDuplicateUsernameRace(t *testing.T) { + srv := newAPI(t, time.Hour) + defer srv.Close() + name := "race_" + uuid.NewString()[:8] + logStep(t, "8 параллельных регистраций username="+name) + const n = 8 + codes := make([]int, n) + var wg sync.WaitGroup + body := fmt.Sprintf(`{"username":%q,"display_name":"Гонка","password":"correct-horse-1"}`, name) + for i := 0; i < n; i++ { + wg.Add(1) + go func(i int) { + defer wg.Done() + status, _ := do(t, srv, http.MethodPost, "/api/v1/users", nil, body) + codes[i] = status + }(i) + } + wg.Wait() + ok, conflict := 0, 0 + for _, c := range codes { + switch c { + case http.StatusCreated: + ok++ + case http.StatusConflict: + conflict++ + default: + t.Errorf("unexpected status %d", c) + } + } + t.Logf("created=%d conflict=%d", ok, conflict) + if ok != 1 || conflict != n-1 { + t.Fatalf("race result created=%d conflict=%d", ok, conflict) + } + logOK(t, "UNIQUE username выдержал гонку") +} + +func TestChatCreateRollsBack(t *testing.T) { + srv := newAPI(t, time.Hour) + defer srv.Close() + user := register(t, srv, "roll_user") + token := login(t, srv, user.username, user.password) + title := "rollback-" + uuid.NewString() + missing := uuid.NewString() + logStep(t, "создание чата с несуществующим участником должно откатиться, title="+title) + raw := fmt.Sprintf(`{"title":%q,"member_ids":[%q,%q]}`, title, user.id, missing) + status, body := do(t, srv, http.MethodPost, "/api/v1/chats", map[string]string{"Authorization": "Bearer " + token}, raw) + logResult(t, status, body) + if status != http.StatusBadRequest { + t.Fatalf("status=%d", status) + } + n, err := sharedStore.CountChatsByTitle(context.Background(), title) + if err != nil { + t.Fatal(err) + } + t.Logf("строк chats с этим title после ошибки: %d", n) + if n != 0 { + t.Fatalf("chat row survived rollback: %d", n) + } + logOK(t, "транзакция создания чата откатилась") +} + +func TestPaginationPages(t *testing.T) { + srv := newAPI(t, time.Hour) + defer srv.Close() + logStep(t, "три сообщения, две страницы limit=2, затем последняя") + user := register(t, srv, "page_user") + token := login(t, srv, user.username, user.password) + chat := createChat(t, srv, token, user.id, "Страницы") + auth := map[string]string{"Authorization": "Bearer " + token} + for _, text := range []string{"раз", "два", "три"} { + status, body := do(t, srv, http.MethodPost, "/api/v1/chats/"+chat+"/messages", auth, fmt.Sprintf(`{"text":%q}`, text)) + if status != http.StatusCreated { + t.Fatalf("post message %s: %d %s", text, status, body) + } + } + status, body := do(t, srv, http.MethodGet, "/api/v1/chats/"+chat+"/messages?limit=2", auth, "") + logResult(t, status, body) + page := decode(t, body) + items, _ := page["items"].([]any) + if status != http.StatusOK || len(items) != 2 || page["next_cursor"] == nil { + t.Fatalf("page1: %+v", page) + } + cursor, _ := page["next_cursor"].(string) + status, body = do(t, srv, http.MethodGet, "/api/v1/chats/"+chat+"/messages?limit=2&cursor="+cursor, auth, "") + logResult(t, status, body) + page = decode(t, body) + items, _ = page["items"].([]any) + if len(items) != 1 || page["next_cursor"] != nil { + t.Fatalf("page2: %+v", page) + } + logOK(t, "keyset обошёл историю без зависания cursor") +} + +func TestRedisDownIsNotAnonymous(t *testing.T) { + logStep(t, "закрытый клиент Redis: вход и Bearer дают 503, а не 200 от анонима") + closed, err := session.Open(sharedRedisURL, time.Hour) + if err != nil { + t.Fatal(err) + } + if err := closed.Close(); err != nil { + t.Fatal(err) + } + srv := httptest.NewServer(api.New(sharedStore, closed, sharedObjects, "test-closed-redis").Handler()) + defer srv.Close() + regSrv := newAPI(t, time.Hour) + defer regSrv.Close() + user := register(t, regSrv, "redis_down") + status, body := do(t, srv, http.MethodPost, "/api/v1/auth/sessions", map[string]string{ + "Authorization": "Basic " + basic(user.username, user.password), + }, "") + logResult(t, status, body) + if status != http.StatusServiceUnavailable { + t.Fatalf("login with dead redis: status=%d body=%s", status, body) + } + status, body = do(t, srv, http.MethodGet, "/api/v1/users/me", map[string]string{ + "Authorization": "Bearer " + strings.Repeat("ab", 32), + }, "") + logResult(t, status, body) + if status != http.StatusServiceUnavailable { + t.Fatalf("bearer with dead redis: status=%d body=%s", status, body) + } + logOK(t, "сбой Redis не стал анонимным доступом") +} + +func TestPostgresDownIsNotAnonymous(t *testing.T) { + logStep(t, "закрытый пул PostgreSQL: ready/me/login дают 503, без тела пользователя") + regSrv := newAPI(t, time.Hour) + defer regSrv.Close() + user := register(t, regSrv, "pg_down") + token := login(t, regSrv, user.username, user.password) + + hasher, err := auth.NewHasher() + if err != nil { + t.Fatal(err) + } + dsn := getenv("DATABASE_URL", "postgres://messenger:messenger@127.0.0.1:5432/messenger?sslmode=disable") + broken, err := store.Open(context.Background(), dsn, hasher, 5) + if err != nil { + t.Fatal(err) + } + broken.Close() + sessions, err := session.Open(sharedRedisURL, time.Hour) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = sessions.Close() }) + srv := httptest.NewServer(api.New(broken, sessions, sharedObjects, "test-broken-pg").Handler()) + defer srv.Close() + + status, body := do(t, srv, http.MethodGet, "/health/ready", nil, "") + logResult(t, status, body) + if status != http.StatusServiceUnavailable { + t.Fatalf("ready with dead postgres: %d", status) + } + status, body = do(t, srv, http.MethodGet, "/api/v1/users/me", map[string]string{ + "Authorization": "Bearer " + token, + }, "") + logResult(t, status, body) + if status != http.StatusServiceUnavailable || strings.Contains(body, `"username"`) { + t.Fatalf("me with dead postgres: status=%d body=%s", status, body) + } + status, body = do(t, srv, http.MethodPost, "/api/v1/auth/sessions", map[string]string{ + "Authorization": "Basic " + basic(user.username, user.password), + }, "") + logResult(t, status, body) + if status != http.StatusServiceUnavailable { + t.Fatalf("login with dead postgres: status=%d body=%s", status, body) + } + logOK(t, "сбой PostgreSQL не стал анонимным доступом") +} + +func TestIdempotencyReplayAndConflict(t *testing.T) { + srv := newAPI(t, time.Hour) + defer srv.Close() + logStep(t, "повтор того же Idempotency-Key возвращает то же сообщение; другой body — 409") + user := register(t, srv, "idem_user") + token := login(t, srv, user.username, user.password) + chat := createChat(t, srv, token, user.id, "Идемпотентность") + key := "key-" + uuid.NewString() + auth := map[string]string{ + "Authorization": "Bearer " + token, + "Idempotency-Key": key, + } + status, body := do(t, srv, http.MethodPost, "/api/v1/chats/"+chat+"/messages", auth, `{"text":"один раз"}`) + logResult(t, status, body) + if status != http.StatusCreated { + t.Fatalf("first: %d %s", status, body) + } + first := decode(t, body) + status, body = do(t, srv, http.MethodPost, "/api/v1/chats/"+chat+"/messages", auth, `{"text":"один раз"}`) + logResult(t, status, body) + if status != http.StatusCreated { + t.Fatalf("replay: %d %s", status, body) + } + second := decode(t, body) + if first["id"] != second["id"] || first["text"] != second["text"] { + t.Fatalf("replay differs: first=%v second=%v", first, second) + } + status, body = do(t, srv, http.MethodPost, "/api/v1/chats/"+chat+"/messages", auth, `{"text":"другой body"}`) + logResult(t, status, body) + if status != http.StatusConflict { + t.Fatalf("conflict: %d %s", status, body) + } + logOK(t, "replay и conflict по Idempotency-Key") +} + +func TestIdempotencyKeyRequiredAndConcurrent(t *testing.T) { + srv := newAPI(t, time.Hour) + defer srv.Close() + logStep(t, "нет ключа → 400; 8 параллельных POST с одним ключом → ровно одно сообщение") + user := register(t, srv, "idem_race") + token := login(t, srv, user.username, user.password) + chat := createChat(t, srv, token, user.id, "Гонка ключа") + + // Явно без ключа: хелпер doRaw подставляет ключ только если заголовок пуст — + // поэтому бьём в doRaw с пустым Idempotency-Key, переопределив после... + // Проще: отдельный raw-запрос. + req, err := http.NewRequest(http.MethodPost, srv.URL+"/api/v1/chats/"+chat+"/messages", strings.NewReader(`{"text":"без ключа"}`)) + if err != nil { + t.Fatal(err) + } + req.Header.Set("Authorization", "Bearer "+token) + req.Header.Set("Content-Type", "application/json") + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatal(err) + } + b, _ := io.ReadAll(resp.Body) + resp.Body.Close() + logResult(t, resp.StatusCode, string(b)) + if resp.StatusCode != http.StatusBadRequest { + t.Fatalf("missing key: %d", resp.StatusCode) + } + + key := "race-" + uuid.NewString() + const n = 8 + ids := make([]string, n) + var wg sync.WaitGroup + for i := 0; i < n; i++ { + wg.Add(1) + go func(i int) { + defer wg.Done() + status, body := do(t, srv, http.MethodPost, "/api/v1/chats/"+chat+"/messages", map[string]string{ + "Authorization": "Bearer " + token, + "Idempotency-Key": key, + }, `{"text":"параллельно"}`) + if status != http.StatusCreated { + t.Errorf("worker %d status=%d body=%s", i, status, body) + return + } + ids[i] = decode(t, body)["id"].(string) + }(i) + } + wg.Wait() + uniq := map[string]struct{}{} + for _, id := range ids { + if id == "" { + t.Fatalf("empty id in race") + } + uniq[id] = struct{}{} + } + t.Logf("unique message ids=%d", len(uniq)) + if len(uniq) != 1 { + t.Fatalf("expected 1 message, got %d ids=%v", len(uniq), ids) + } + logOK(t, "ключ обязателен; конкурентный повтор не плодит дубли") +} + +func TestInstanceIDHeaderPresent(t *testing.T) { + srv := newAPI(t, time.Hour) + defer srv.Close() + logStep(t, "каждый ответ содержит непустой X-Instance-Id") + status, body, hdr := doRaw(t, srv, http.MethodGet, "/health/live", nil, "") + logResult(t, status, body) + if status != http.StatusOK || hdr.Get("X-Instance-Id") == "" { + t.Fatalf("live instance header missing: %q status=%d", hdr.Get("X-Instance-Id"), status) + } + logOK(t, "X-Instance-Id="+hdr.Get("X-Instance-Id")) +} + +type account struct { + id string + username string + password string +} + +func newAPI(t *testing.T, ttl time.Duration) *httptest.Server { + t.Helper() + sessions, err := session.Open(sharedRedisURL, ttl) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = sessions.Close() }) + return httptest.NewServer(api.New(sharedStore, sessions, sharedObjects, "test-instance").Handler()) +} + +func register(t *testing.T, srv *httptest.Server, prefix string) account { + t.Helper() + username := prefix + "_" + uuid.NewString()[:8] + password := "correct-horse-1" + raw := fmt.Sprintf(`{"username":%q,"display_name":"Студент","password":%q}`, username, password) + status, body := do(t, srv, http.MethodPost, "/api/v1/users", nil, raw) + if status != http.StatusCreated { + t.Fatalf("register %s: %d %s", username, status, body) + } + var u struct { + ID string `json:"id"` + } + if err := json.Unmarshal([]byte(body), &u); err != nil { + t.Fatal(err) + } + t.Logf("создан %s id=%s", username, u.ID) + return account{id: u.ID, username: username, password: password} +} + +func login(t *testing.T, srv *httptest.Server, username, password string) string { + t.Helper() + status, body := do(t, srv, http.MethodPost, "/api/v1/auth/sessions", map[string]string{ + "Authorization": "Basic " + basic(username, password), + }, "") + if status != http.StatusCreated { + t.Fatalf("login %s: %d %s", username, status, body) + } + var s struct { + Token string `json:"token"` + } + if err := json.Unmarshal([]byte(body), &s); err != nil { + t.Fatal(err) + } + if len(s.Token) < 32 { + t.Fatalf("token too short: %d", len(s.Token)) + } + t.Logf("сессия выпущена, длина токена=%d (значение не печатаем)", len(s.Token)) + return s.Token +} + +func createChat(t *testing.T, srv *httptest.Server, token, userID, title string) string { + t.Helper() + raw := fmt.Sprintf(`{"title":%q,"member_ids":[%q]}`, title, userID) + status, body := do(t, srv, http.MethodPost, "/api/v1/chats", map[string]string{"Authorization": "Bearer " + token}, raw) + if status != http.StatusCreated { + t.Fatalf("chat: %d %s", status, body) + } + var c struct { + ID string `json:"id"` + } + if err := json.Unmarshal([]byte(body), &c); err != nil { + t.Fatal(err) + } + return c.ID +} + +func do(t *testing.T, srv *httptest.Server, method, path string, headers map[string]string, raw string) (int, string) { + t.Helper() + status, body, _ := doRaw(t, srv, method, path, headers, raw) + return status, body +} + +func doRaw(t *testing.T, srv *httptest.Server, method, path string, headers map[string]string, raw string) (int, string, http.Header) { + t.Helper() + var rdr io.Reader + if raw != "" { + rdr = bytes.NewBufferString(raw) + } + req, err := http.NewRequest(method, srv.URL+path, rdr) + if err != nil { + t.Fatal(err) + } + if raw != "" && method != http.MethodGet { + req.Header.Set("Content-Type", "application/json") + } + for k, v := range headers { + req.Header.Set(k, v) + } + // Lab3: POST сообщений без ключа — 400. В хелперах подставляем уникальный ключ, + // если тест сам его не задал (негативные проверки ключа делают это явно). + if method == http.MethodPost && strings.Contains(path, "/messages") && req.Header.Get("Idempotency-Key") == "" { + req.Header.Set("Idempotency-Key", uuid.NewString()) + } + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + b, _ := io.ReadAll(resp.Body) + return resp.StatusCode, string(b), resp.Header +} + +func decode(t *testing.T, body string) map[string]any { + t.Helper() + var m map[string]any + if err := json.Unmarshal([]byte(body), &m); err != nil { + t.Fatal(err) + } + return m +} + +func basic(user, pass string) string { + return base64.StdEncoding.EncodeToString([]byte(user + ":" + pass)) +} + +func logStep(t *testing.T, msg string) { t.Helper(); t.Logf("→ %s", msg) } +func logOK(t *testing.T, msg string) { t.Helper(); t.Logf("✓ %s", msg) } +func logResult(t *testing.T, status int, body string) { + t.Helper() + if len(body) > 400 { + body = body[:400] + "..." + } + t.Logf("status=%d body=%s", status, body) +} + +func getenv(k, def string) string { + if v := os.Getenv(k); v != "" { + return v + } + return def +} diff --git a/student-tests/attachments_test.go b/student-tests/attachments_test.go new file mode 100644 index 00000000..75a48d18 --- /dev/null +++ b/student-tests/attachments_test.go @@ -0,0 +1,743 @@ +// Собственные проверки lab4: вложения (S3 + PostgreSQL). +// +// Покрыто (требования уровня «4»): слишком большой файл, повреждённое изображение, +// подмена MIME, чужое attachment_id, вложение другого чата, недоступный S3, +// компенсация при отказе PG после PUT, параллельные загрузки. +// Реальные PNG/JPEG генерируются на лету (стандартная библиотека), внешних фикстур нет. +package studenttests + +import ( + "bytes" + "compress/zlib" + "context" + "crypto/sha256" + "encoding/binary" + "encoding/hex" + "errors" + "fmt" + "hash/crc32" + "image" + "image/color" + "image/jpeg" + "image/png" + "io" + "math/rand" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "sync" + "testing" + "time" + + "github.com/google/uuid" + + "gavrilenko-sxdees/lab4/internal/api" + "gavrilenko-sxdees/lab4/internal/auth" + "gavrilenko-sxdees/lab4/internal/objectstore" + "gavrilenko-sxdees/lab4/internal/session" + "gavrilenko-sxdees/lab4/internal/store" +) + +const maxUpload = 10 << 20 // 10 MiB — лимит контракта + +// ---------------------------------------------------------------- генераторы файлов + +// noisePNG — настоящий PNG из псевдослучайного шума (плохо сжимается → размер ≈ w*h*4). +func noisePNG(t *testing.T, w, h int) []byte { + t.Helper() + rng := rand.New(rand.NewSource(int64(w*100003 + h))) + img := image.NewNRGBA(image.Rect(0, 0, w, h)) + rng.Read(img.Pix) + var buf bytes.Buffer + if err := png.Encode(&buf, img); err != nil { + t.Fatal(err) + } + return buf.Bytes() +} + +// smallJPEG — настоящий JPEG. +func smallJPEG(t *testing.T, w, h int) []byte { + t.Helper() + img := image.NewRGBA(image.Rect(0, 0, w, h)) + for y := 0; y < h; y++ { + for x := 0; x < w; x++ { + img.Set(x, y, color.RGBA{uint8(x * 3), uint8(y * 5), uint8(x ^ y), 255}) + } + } + var buf bytes.Buffer + if err := jpeg.Encode(&buf, img, &jpeg.Options{Quality: 80}); err != nil { + t.Fatal(err) + } + return buf.Bytes() +} + +// craftPNG собирает ВАЛИДНЫЙ 1-битный серый PNG заданных размеров вручную: данные — +// нули, сжимаются до пары КБ даже для десятков миллионов пикселей. Нужен для проверки +// лимита пикселей без гигабайтных буферов в тесте. +func craftPNG(w, h int) []byte { + var idat bytes.Buffer + zw := zlib.NewWriter(&idat) + row := make([]byte, 1+(w+7)/8) // фильтр 0 + биты строки + for y := 0; y < h; y++ { + _, _ = zw.Write(row) + } + _ = zw.Close() + + var out bytes.Buffer + out.WriteString("\x89PNG\r\n\x1a\n") + chunk := func(typ string, data []byte) { + var l [4]byte + binary.BigEndian.PutUint32(l[:], uint32(len(data))) + out.Write(l[:]) + out.WriteString(typ) + out.Write(data) + var c [4]byte + binary.BigEndian.PutUint32(c[:], crc32.ChecksumIEEE(append([]byte(typ), data...))) + out.Write(c[:]) + } + ihdr := make([]byte, 13) + binary.BigEndian.PutUint32(ihdr[0:], uint32(w)) + binary.BigEndian.PutUint32(ihdr[4:], uint32(h)) + ihdr[8], ihdr[9] = 1, 0 // глубина 1 бит, grayscale + chunk("IHDR", ihdr) + chunk("IDAT", idat.Bytes()) + chunk("IEND", nil) + return out.Bytes() +} + +// ---------------------------------------------------------------- HTTP-хелперы + +type chatCtx struct { + srv *httptest.Server + owner account + token string + chat string +} + +func newChatCtx(t *testing.T, prefix string) chatCtx { + t.Helper() + srv := newAPI(t, time.Hour) + t.Cleanup(srv.Close) + u := register(t, srv, prefix) + tok := login(t, srv, u.username, u.password) + return chatCtx{srv: srv, owner: u, token: tok, chat: createChat(t, srv, tok, u.id, "Вложения "+prefix)} +} + +// upload отправляет сырой binary. contentType "" → заголовок не ставится. +func upload(t *testing.T, srv *httptest.Server, token, chat, filename, contentType string, body []byte) (int, []byte, http.Header) { + t.Helper() + u := srv.URL + "/api/v1/chats/" + chat + "/attachments?filename=" + url.QueryEscape(filename) + req, err := http.NewRequest(http.MethodPost, u, bytes.NewReader(body)) + if err != nil { + t.Fatal(err) + } + if token != "" { + req.Header.Set("Authorization", "Bearer "+token) + } + if contentType != "" { + req.Header.Set("Content-Type", contentType) + } + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatalf("upload transport error (ждали HTTP-ответ): %v", err) + } + defer resp.Body.Close() + b, _ := io.ReadAll(resp.Body) + return resp.StatusCode, b, resp.Header +} + +func mustUpload(t *testing.T, c chatCtx, filename, ctype string, body []byte) map[string]any { + t.Helper() + status, b, _ := upload(t, c.srv, c.token, c.chat, filename, ctype, body) + if status != http.StatusCreated { + t.Fatalf("upload %s: status=%d body=%s", filename, status, string(b)) + } + return decode(t, string(b)) +} + +// get без следования редиректам: контракт требует отдавать байты самим API. +func getNoRedirect(t *testing.T, srv *httptest.Server, token, path string) (int, []byte, http.Header) { + t.Helper() + client := &http.Client{CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }} + req, _ := http.NewRequest(http.MethodGet, srv.URL+path, nil) + req.Header.Set("Authorization", "Bearer "+token) + resp, err := client.Do(req) + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + b, _ := io.ReadAll(resp.Body) + return resp.StatusCode, b, resp.Header +} + +func createChatWith(t *testing.T, srv *httptest.Server, token, title string, ids ...string) string { + t.Helper() + quoted := make([]string, len(ids)) + for i, id := range ids { + quoted[i] = fmt.Sprintf("%q", id) + } + raw := fmt.Sprintf(`{"title":%q,"member_ids":[%s]}`, title, strings.Join(quoted, ",")) + status, body := do(t, srv, http.MethodPost, "/api/v1/chats", map[string]string{"Authorization": "Bearer " + token}, raw) + if status != http.StatusCreated { + t.Fatalf("chat: %d %s", status, body) + } + return decode(t, body)["id"].(string) +} + +func postMessage(t *testing.T, srv *httptest.Server, token, chat, key, rawJSON string) (int, string) { + t.Helper() + return do(t, srv, http.MethodPost, "/api/v1/chats/"+chat+"/messages", map[string]string{ + "Authorization": "Bearer " + token, + "Idempotency-Key": key, + }, rawJSON) +} + +func hexSHA(b []byte) string { s := sha256.Sum256(b); return hex.EncodeToString(s[:]) } + +// ---------------------------------------------------------------- тесты + +// Полный путь: upload → метаданные → байты → сообщение с вложением → чтение вторым +// участником → 404 постороннему. Заодно: идемпотентный replay сохраняет attachment_ids. +func TestAttachmentRoundTripAndAccessControl(t *testing.T) { + logStep(t, "PNG и JPEG: 201 ready, sha256/size, download без redirect, доступ только участникам") + srv := newAPI(t, time.Hour) + defer srv.Close() + alice := register(t, srv, "att_alice") + bob := register(t, srv, "att_bob") + eve := register(t, srv, "att_eve") + tokA := login(t, srv, alice.username, alice.password) + tokB := login(t, srv, bob.username, bob.password) + tokE := login(t, srv, eve.username, eve.password) + chat := createChatWith(t, srv, tokA, "Общий", alice.id, bob.id) + c := chatCtx{srv: srv, owner: alice, token: tokA, chat: chat} + + pngData := noisePNG(t, 120, 90) + meta := mustUpload(t, c, "фото.png", "image/png", pngData) + if meta["status"] != "ready" || meta["error_code"] != nil || meta["content_type"] != "image/png" { + t.Fatalf("метаданные: %v", meta) + } + if v, ok := meta["variants"].([]any); !ok || len(v) != 0 { + t.Fatalf("variants должен быть []: %v", meta["variants"]) + } + if meta["sha256"] != hexSHA(pngData) || int(meta["size_bytes"].(float64)) != len(pngData) { + t.Fatalf("sha256/size не совпали: %v", meta) + } + if meta["owner_id"] != alice.id || meta["chat_id"] != chat || meta["filename"] != "фото.png" { + t.Fatalf("owner/chat/filename: %v", meta) + } + for _, k := range []string{"object_key", "bucket", "key"} { + if _, leaked := meta[k]; leaked { + t.Fatalf("в публичном ответе утёк внутренний ключ %q", k) + } + } + id := meta["id"].(string) + + // Метаданные и байты — участнику Bob (не загрузившему). + status, body, _ := getNoRedirect(t, srv, tokB, "/api/v1/attachments/"+id) + if status != http.StatusOK || decode(t, string(body))["sha256"] != hexSHA(pngData) { + t.Fatalf("meta by bob: %d %s", status, body) + } + status, got, hdr := getNoRedirect(t, srv, tokB, "/api/v1/attachments/"+id+"/content") + if status != http.StatusOK || hdr.Get("Content-Type") != "image/png" || hexSHA(got) != hexSHA(pngData) { + t.Fatalf("download: status=%d ct=%q sha=%s", status, hdr.Get("Content-Type"), hexSHA(got)) + } + if hdr.Get("Location") != "" { + t.Fatal("download не должен быть redirect") + } + + // JPEG тем же путём. + jpgData := smallJPEG(t, 64, 48) + jmeta := mustUpload(t, c, "pic.jpg", "image/jpeg", jpgData) + if jmeta["content_type"] != "image/jpeg" || jmeta["sha256"] != hexSHA(jpgData) { + t.Fatalf("jpeg meta: %v", jmeta) + } + + // Посторонний: метаданные, байты, загрузка — всё 404 (не 403, не раскрываем существование). + for _, path := range []string{"/api/v1/attachments/" + id, "/api/v1/attachments/" + id + "/content"} { + status, body, _ := getNoRedirect(t, srv, tokE, path) + logResult(t, status, string(body)) + if status != http.StatusNotFound { + t.Fatalf("outsider GET %s: %d", path, status) + } + } + status, body, _ = upload(t, srv, tokE, chat, "x.png", "image/png", pngData) + if status != http.StatusNotFound { + t.Fatalf("outsider upload: %d %s", status, body) + } + // Без токена — 401. + status, _, _ = upload(t, srv, "", chat, "x.png", "image/png", pngData) + if status != http.StatusUnauthorized { + t.Fatalf("upload без токена: %d", status) + } + // Неизвестный вариант и несуществующее вложение. + status, _, _ = getNoRedirect(t, srv, tokB, "/api/v1/attachments/"+id+"/content?variant=thumbnail") + if status != http.StatusNotFound { + t.Fatalf("variant=thumbnail у ready-объекта: %d", status) + } + status, _, _ = getNoRedirect(t, srv, tokB, "/api/v1/attachments/"+uuid.NewString()) + if status != http.StatusNotFound { + t.Fatalf("unknown attachment: %d", status) + } + + // Сообщение с двумя вложениями (порядок сохраняется), затем чтение Bob'ом. + jid := jmeta["id"].(string) + key := "msg-" + uuid.NewString() + raw := fmt.Sprintf(`{"text":"смотри","attachment_ids":[%q,%q]}`, jid, id) + status, mbody := postMessage(t, srv, tokA, chat, key, raw) + logResult(t, status, mbody) + if status != http.StatusCreated { + t.Fatalf("message with attachments: %d %s", status, mbody) + } + msg := decode(t, mbody) + ids := msg["attachment_ids"].([]any) + if len(ids) != 2 || ids[0] != jid || ids[1] != id { + t.Fatalf("порядок/состав attachment_ids: %v", ids) + } + // Replay с тем же ключом → то же сообщение И те же attachment_ids. + status, body2 := postMessage(t, srv, tokA, chat, key, raw) + if status != http.StatusCreated || decode(t, body2)["id"] != msg["id"] { + t.Fatalf("replay: %d %s", status, body2) + } + if rid := decode(t, body2)["attachment_ids"].([]any); len(rid) != 2 || rid[0] != jid { + t.Fatalf("replay потерял attachment_ids: %v", rid) + } + // Тот же ключ, другой набор вложений → 409. + status, _ = postMessage(t, srv, tokA, chat, key, fmt.Sprintf(`{"text":"смотри","attachment_ids":[%q]}`, id)) + if status != http.StatusConflict { + t.Fatalf("тот же ключ, другие вложения: %d", status) + } + + status, body, _ = getNoRedirect(t, srv, tokB, "/api/v1/chats/"+chat+"/messages") + if status != http.StatusOK || !strings.Contains(string(body), jid) { + t.Fatalf("история Bob: %d %s", status, body) + } + status, _, _ = getNoRedirect(t, srv, tokE, "/api/v1/chats/"+chat+"/messages") + if status != http.StatusNotFound { + t.Fatalf("история постороннего: %d", status) + } + logOK(t, "upload/download/доступ/replay работают, внутренние ключи не раскрываются") +} + +// Слишком большой файл → 413 (границу проверяем с точностью до байта). +func TestAttachmentTooLarge(t *testing.T) { + logStep(t, "ровно 10 MiB проходит лимит размера (дальше 415 как не-картинка), 10 MiB+1 → 413") + c := newChatCtx(t, "att_big") + header := noisePNG(t, 8, 8)[:8] // валидная сигнатура PNG, чтобы тело «похоже» на картинку + + atLimit := append(append([]byte{}, header...), make([]byte, maxUpload-len(header))...) + status, b, _ := upload(t, c.srv, c.token, c.chat, "limit.png", "image/png", atLimit) + logResult(t, status, string(b)) + if status != http.StatusUnsupportedMediaType { + t.Fatalf("ровно 10 MiB мусора: ждали 415 (размер допустим), got %d", status) + } + + over := append(append([]byte{}, header...), make([]byte, maxUpload-len(header)+1)...) + status, b, _ = upload(t, c.srv, c.token, c.chat, "big.png", "image/png", over) + logResult(t, status, string(b)) + if status != http.StatusRequestEntityTooLarge || !strings.Contains(string(b), "payload_too_large") { + t.Fatalf("10 MiB+1: ждали 413, got %d %s", status, b) + } + + // Заметно больше лимита: клиент должен получить именно 413, а не сброс соединения. + huge := make([]byte, 14<<20) + copy(huge, header) + status, b, _ = upload(t, c.srv, c.token, c.chat, "huge.png", "image/png", huge) + if status != http.StatusRequestEntityTooLarge { + t.Fatalf("14 MiB: ждали 413, got %d %s", status, b) + } + + // chunked без Content-Length: лимит всё равно обязан сработать (MaxBytesReader). + req, _ := http.NewRequest(http.MethodPost, c.srv.URL+"/api/v1/chats/"+c.chat+"/attachments?filename=chunked.png", + io.NopCloser(bytes.NewReader(over))) + req.ContentLength = -1 + req.Header.Set("Authorization", "Bearer "+c.token) + req.Header.Set("Content-Type", "image/png") + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatal(err) + } + resp.Body.Close() + if resp.StatusCode != http.StatusRequestEntityTooLarge { + t.Fatalf("chunked >10 MiB: ждали 413, got %d", resp.StatusCode) + } + logOK(t, "лимит байтов: граница точная, работает и для chunked") +} + +// Лимит пикселей: ровно 40 млн можно, на один ряд больше — 413 (до распаковки). +func TestAttachmentPixelLimit(t *testing.T) { + logStep(t, "8000x5000 (=40 млн) принимается, 8000x5001 → 413") + c := newChatCtx(t, "att_px") + + ok := craftPNG(8000, 5000) + t.Logf("PNG 8000x5000 занимает %d байт на проводе", len(ok)) + meta := mustUpload(t, c, "forty-million.png", "image/png", ok) + if meta["status"] != "ready" { + t.Fatalf("40 Мпикс: %v", meta) + } + + tooMany := craftPNG(8000, 5001) + status, b, _ := upload(t, c.srv, c.token, c.chat, "bomb.png", "image/png", tooMany) + logResult(t, status, string(b)) + if status != http.StatusRequestEntityTooLarge { + t.Fatalf("40 Мпикс + 1 ряд: ждали 413, got %d %s", status, b) + } + logOK(t, "лимит пикселей по заголовку, без полного декода") +} + +// Повреждённые файлы, чужие форматы и подмена MIME → 415, никогда не 500. +func TestAttachmentCorruptAndMimeSpoof(t *testing.T) { + logStep(t, "мусор, усечённые PNG/JPEG, битый CRC, GIF под видом PNG, подмена Content-Type") + c := newChatCtx(t, "att_bad") + validPNG := noisePNG(t, 40, 40) + validJPG := smallJPEG(t, 40, 40) + + flipped := append([]byte{}, validPNG...) + flipped[len(flipped)/2] ^= 0xFF // портим данные IDAT → не сойдётся CRC + + gif := []byte("GIF89a\x01\x00\x01\x00\x80\x00\x00\x00\x00\x00\xff\xff\xff!\xf9\x04\x01\x00\x00\x00\x00,\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02D\x01\x00;") + + cases := []struct { + name string + ctype string + body []byte + }{ + {"случайные байты как png", "image/png", bytes.Repeat([]byte("не картинка "), 500)}, + {"пустое тело", "image/png", nil}, + {"усечённый PNG", "image/png", validPNG[:len(validPNG)-20]}, + {"усечённый JPEG", "image/jpeg", validJPG[:len(validJPG)-30]}, + {"PNG с битым CRC", "image/png", flipped}, + {"GIF под видом PNG", "image/png", gif}, + {"PNG под видом JPEG (спуфинг)", "image/jpeg", validPNG}, + {"JPEG под видом PNG (спуфинг)", "image/png", validJPG}, + {"валидный PNG, но Content-Type text/plain", "text/plain", validPNG}, + {"валидный PNG без Content-Type", "", validPNG}, + {"валидный PNG, Content-Type image/gif", "image/gif", validPNG}, + } + for _, tc := range cases { + status, b, _ := upload(t, c.srv, c.token, c.chat, "bad.bin", tc.ctype, tc.body) + t.Logf("%-45s → %d", tc.name, status) + if status != http.StatusUnsupportedMediaType { + t.Fatalf("%s: ждали 415, got %d body=%s", tc.name, status, b) + } + if !strings.Contains(string(b), "unsupported_media_type") { + t.Fatalf("%s: код ошибки: %s", tc.name, b) + } + } + // После всех отказов в чате не появилось ни одной строки вложения. + n, err := sharedStore.CountAttachmentsInChat(context.Background(), uuid.MustParse(c.chat)) + if err != nil || n != 0 { + t.Fatalf("после отказов в БД осталось %d вложений (err=%v)", n, err) + } + // Контрольный: Content-Type с параметрами и в другом регистре допустим. + meta := mustUpload(t, c, "ok.png", "Image/PNG; charset=binary", validPNG) + if meta["content_type"] != "image/png" { + t.Fatalf("content_type по содержимому: %v", meta) + } + logOK(t, "все повреждённые/подменённые файлы → 415, строки в БД не создаются") +} + +func TestAttachmentFilenameValidation(t *testing.T) { + logStep(t, "filename: '/', '\\', NUL, управляющие, пустое, >255 → 400; unicode и пробелы допустимы") + c := newChatCtx(t, "att_name") + data := noisePNG(t, 16, 16) + bad := []string{ + "a/b.png", "..\\evil.png", "nul\x00byte.png", "line\nbreak.png", "tab\tname.png", + "del\x7f.png", "", " ", strings.Repeat("я", 256), "bidi\u202eexe.png", + } + for _, name := range bad { + status, b, _ := upload(t, c.srv, c.token, c.chat, name, "image/png", data) + if status != http.StatusBadRequest { + t.Fatalf("filename %q: ждали 400, got %d %s", name, status, b) + } + } + // Без параметра filename вообще. + req, _ := http.NewRequest(http.MethodPost, c.srv.URL+"/api/v1/chats/"+c.chat+"/attachments", bytes.NewReader(data)) + req.Header.Set("Authorization", "Bearer "+c.token) + req.Header.Set("Content-Type", "image/png") + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatal(err) + } + resp.Body.Close() + if resp.StatusCode != http.StatusBadRequest { + t.Fatalf("без filename: %d", resp.StatusCode) + } + for _, name := range []string{"отчёт 2026 (финал).png", strings.Repeat("я", 255), "a b.png"} { + meta := mustUpload(t, c, name, "image/png", data) + if meta["filename"] != name { + t.Fatalf("filename искажён: %q vs %q", meta["filename"], name) + } + } + logOK(t, "опасные имена отклоняются, обычные Unicode-имена сохраняются как есть") +} + +// Правила attachment_ids в сообщениях: чужое/неизвестное/другой чат → 404, +// >10 и дубли → 400, пустой текст допустим только с вложением. +func TestMessageAttachmentRules(t *testing.T) { + logStep(t, "foreign attachment_id, вложение другого чата, неизвестный id, лимиты и пустой текст") + srv := newAPI(t, time.Hour) + defer srv.Close() + alice := register(t, srv, "rule_alice") + mallory := register(t, srv, "rule_mal") + tokA := login(t, srv, alice.username, alice.password) + tokM := login(t, srv, mallory.username, mallory.password) + + chatA1 := createChat(t, srv, tokA, alice.id, "A1") + chatA2 := createChat(t, srv, tokA, alice.id, "A2") + chatM := createChat(t, srv, tokM, mallory.id, "M") + data := noisePNG(t, 20, 20) + a1 := mustUpload(t, chatCtx{srv: srv, token: tokA, chat: chatA1}, "a1.png", "image/png", data)["id"].(string) + mine := mustUpload(t, chatCtx{srv: srv, token: tokM, chat: chatM}, "m.png", "image/png", data)["id"].(string) + + post := func(chat, tok, raw string) (int, string) { + return postMessage(t, srv, tok, chat, "k-"+uuid.NewString(), raw) + } + + // 1. Вложение ЧУЖОГО пользователя (другой чат, Alice не участник) → 404. + status, body := post(chatA1, tokA, fmt.Sprintf(`{"text":"x","attachment_ids":[%q]}`, mine)) + logResult(t, status, body) + if status != http.StatusNotFound { + t.Fatalf("чужое attachment_id: %d %s", status, body) + } + // 2. Своё вложение, но из ДРУГОГО чата того же пользователя → 404 (файл привязан к чату). + status, body = post(chatA2, tokA, fmt.Sprintf(`{"text":"x","attachment_ids":[%q]}`, a1)) + logResult(t, status, body) + if status != http.StatusNotFound { + t.Fatalf("вложение другого чата: %d %s", status, body) + } + // 3. Неизвестный UUID → 404; одно плохое среди хороших портит весь запрос атомарно. + status, _ = post(chatA1, tokA, fmt.Sprintf(`{"text":"x","attachment_ids":[%q]}`, uuid.NewString())) + if status != http.StatusNotFound { + t.Fatalf("неизвестный id: %d", status) + } + status, _ = post(chatA1, tokA, fmt.Sprintf(`{"text":"x","attachment_ids":[%q,%q]}`, a1, uuid.NewString())) + if status != http.StatusNotFound { + t.Fatalf("хороший+неизвестный: %d", status) + } + // Ни одно из сообщений выше не должно было записаться. + status, body = do(t, srv, http.MethodGet, "/api/v1/chats/"+chatA1+"/messages", map[string]string{"Authorization": "Bearer " + tokA}, "") + if status != http.StatusOK || strings.Contains(body, `"text":"x"`) { + t.Fatalf("отклонённое сообщение просочилось в историю: %s", body) + } + // 4. Не UUID → 400, дубли → 400, больше 10 → 400. + status, _ = post(chatA1, tokA, `{"text":"x","attachment_ids":["not-a-uuid"]}`) + if status != http.StatusBadRequest { + t.Fatalf("не uuid: %d", status) + } + status, _ = post(chatA1, tokA, fmt.Sprintf(`{"text":"x","attachment_ids":[%q,%q]}`, a1, a1)) + if status != http.StatusBadRequest { + t.Fatalf("дубли: %d", status) + } + eleven := make([]string, 11) + for i := range eleven { + eleven[i] = fmt.Sprintf("%q", uuid.NewString()) + } + status, _ = post(chatA1, tokA, fmt.Sprintf(`{"text":"x","attachment_ids":[%s]}`, strings.Join(eleven, ","))) + if status != http.StatusBadRequest { + t.Fatalf("11 вложений: %d", status) + } + // 5. Пустой текст: без вложений 400, с вложением 201; ровно 10 вложений допустимо. + status, _ = post(chatA1, tokA, `{"text":"","attachment_ids":[]}`) + if status != http.StatusBadRequest { + t.Fatalf("пусто без вложений: %d", status) + } + status, body = post(chatA1, tokA, fmt.Sprintf(`{"text":"","attachment_ids":[%q]}`, a1)) + if status != http.StatusCreated { + t.Fatalf("пустой текст с вложением: %d %s", status, body) + } + if m := decode(t, body); m["text"] != "" { + t.Fatalf("text: %v", m["text"]) + } + ten := make([]string, 10) + for i := range ten { + ten[i] = fmt.Sprintf("%q", mustUpload(t, chatCtx{srv: srv, token: tokA, chat: chatA1}, fmt.Sprintf("t%d.png", i), "image/png", data)["id"].(string)) + } + status, body = post(chatA1, tokA, fmt.Sprintf(`{"text":"ровно десять","attachment_ids":[%s]}`, strings.Join(ten, ","))) + if status != http.StatusCreated || len(decode(t, body)["attachment_ids"].([]any)) != 10 { + t.Fatalf("10 вложений: %d %s", status, body) + } + // 6. Обычное сообщение без attachment_ids → в ответе attachment_ids == []. + status, body = post(chatA1, tokA, `{"text":"просто текст"}`) + if status != http.StatusCreated || !strings.Contains(body, `"attachment_ids":[]`) { + t.Fatalf("attachment_ids по умолчанию []: %d %s", status, body) + } + logOK(t, "чужое/другой чат/неизвестное → 404, лимиты → 400, пустой текст только с вложением") +} + +// S3 недоступен: загрузка → контролируемый 503 (не 500, без деталей), readiness → 503, +// в БД не остаётся строки метаданных. +func TestS3DownGivesLimitedError(t *testing.T) { + logStep(t, "API с недоступным S3: upload/ready → 503, без утечек и полуфабрикатов в БД") + dead, err := objectstore.New(objectstore.Config{ + Endpoint: "http://127.0.0.1:1", Region: "us-east-1", Bucket: "messenger", + AccessKey: "x", SecretKey: "yyyyyyyy", ForcePathStyle: true, + }) + if err != nil { + t.Fatal(err) + } + // Пользователь и чат — через нормальный API; недоступный S3 подсовываем второй реплике. + good := newChatCtx(t, "att_down") + sessions, err := session.Open(sharedRedisURL, time.Hour) + if err != nil { + t.Fatal(err) + } + defer sessions.Close() + srv := httptest.NewServer(api.New(sharedStore, sessions, dead, "dead-s3").Handler()) + defer srv.Close() + + start := time.Now() + status, b, _ := upload(t, srv, good.token, good.chat, "p.png", "image/png", noisePNG(t, 16, 16)) + t.Logf("upload при лежащем S3: status=%d за %s body=%s", status, time.Since(start).Round(time.Millisecond), b) + if status != http.StatusServiceUnavailable || !strings.Contains(string(b), `"unavailable"`) { + t.Fatalf("ждали 503 unavailable, got %d %s", status, b) + } + for _, leak := range []string{"127.0.0.1", "messenger", "dial", "connection refused", "amazonaws"} { + if strings.Contains(strings.ToLower(string(b)), leak) { + t.Fatalf("ответ раскрывает внутренние детали (%q): %s", leak, b) + } + } + if time.Since(start) > 10*time.Second { + t.Fatalf("отказ должен быть быстрым, занял %s", time.Since(start)) + } + + status, b, _ = doRaw2(t, srv, "/health/ready") + if status != http.StatusServiceUnavailable { + t.Fatalf("/health/ready при лежащем S3: %d %s", status, b) + } + status, _, _ = doRaw2(t, srv, "/health/live") + if status != http.StatusOK { + t.Fatalf("/health/live обязан оставаться 200: %d", status) + } + n, err := sharedStore.CountAttachmentsInChat(context.Background(), uuid.MustParse(good.chat)) + if err != nil || n != 0 { + t.Fatalf("в БД осталось %d строк вложений после отказа S3 (err=%v)", n, err) + } + logOK(t, "лежащий S3 → 503 без деталей, ready=503, live=200, БД чиста") +} + +func doRaw2(t *testing.T, srv *httptest.Server, path string) (int, []byte, http.Header) { + t.Helper() + resp, err := http.Get(srv.URL + path) + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + b, _ := io.ReadAll(resp.Body) + return resp.StatusCode, b, resp.Header +} + +// Компенсация: PUT в S3 прошёл, INSERT в PG не удался → объект удаляется сразу, +// клиент получает ошибку, строки нет. +func TestCompensationWhenPostgresFailsAfterPut(t *testing.T) { + logStep(t, "отказ PG после успешного PUT: объект удаляется компенсацией") + ctx := context.Background() + good := newChatCtx(t, "att_comp") + + hasher, err := auth.NewHasher() + if err != nil { + t.Fatal(err) + } + // Отдельный пул, который «умрёт» ровно между PUT и INSERT. + dsn := getenv("DATABASE_URL", "postgres://messenger:messenger@127.0.0.1:5432/messenger?sslmode=disable") + doomed, err := store.Open(ctx, dsn, hasher, 2) + if err != nil { + t.Fatal(err) + } + defer doomed.Close() + sessions, err := session.Open(sharedRedisURL, time.Hour) + if err != nil { + t.Fatal(err) + } + defer sessions.Close() + + server := api.New(doomed, sessions, sharedObjects, "compensation") + var putKey string + server.AfterObjectPut = func(key string) { + putKey = key + // До компенсации убеждаемся, что объект РЕАЛЬНО лежит в S3. + if _, err := sharedObjects.Head(ctx, key); err != nil { + t.Errorf("после PUT объекта нет в S3: %v", err) + } + doomed.Close() // INSERT дальше упадёт: пул закрыт + } + srv := httptest.NewServer(server.Handler()) + defer srv.Close() + + status, b, _ := upload(t, srv, good.token, good.chat, "doomed.png", "image/png", noisePNG(t, 24, 24)) + t.Logf("status=%d body=%s key=%s", status, b, putKey) + if status < 500 || status > 503 { + t.Fatalf("ждали ошибку сервера (отказ PG), got %d %s", status, b) + } + if putKey == "" { + t.Fatal("hook не вызывался: PUT не был выполнен") + } + if _, err := sharedObjects.Head(ctx, putKey); !errors.Is(err, objectstore.ErrNotFound) { + t.Fatalf("объект должен быть удалён компенсацией, Head err=%v", err) + } + n, err := sharedStore.CountAttachmentsInChat(ctx, uuid.MustParse(good.chat)) + if err != nil || n != 0 { + t.Fatalf("строк вложений: %d (err=%v)", n, err) + } + logOK(t, "orphan после отказа PG удалён сразу; если бы удаление не удалось — его уберёт reconciler") +} + +// ≥10 одновременных загрузок: все 201 (лишние ждут слот), все объекты разные и читаются. +func TestConcurrentUploads(t *testing.T) { + logStep(t, "12 параллельных загрузок: все 201, уникальные id, sha256 совпадает") + c := newChatCtx(t, "att_conc") + const n = 12 + type res struct { + id, sha string + data []byte + } + results := make([]res, n) + var wg sync.WaitGroup + for i := 0; i < n; i++ { + wg.Add(1) + go func(i int) { + defer wg.Done() + data := noisePNG(t, 150+i, 150) // разные байты у каждой загрузки + status, b, _ := upload(t, c.srv, c.token, c.chat, fmt.Sprintf("c%d.png", i), "image/png", data) + if status != http.StatusCreated { + t.Errorf("worker %d: %d %s", i, status, b) + return + } + m := decode(t, string(b)) + results[i] = res{id: m["id"].(string), sha: m["sha256"].(string), data: data} + }(i) + } + wg.Wait() + seen := map[string]bool{} + for i, r := range results { + if r.id == "" || seen[r.id] { + t.Fatalf("worker %d: пустой/повторный id %q", i, r.id) + } + seen[r.id] = true + status, got, _ := getNoRedirect(t, c.srv, c.token, "/api/v1/attachments/"+r.id+"/content") + if status != http.StatusOK || hexSHA(got) != r.sha || r.sha != hexSHA(r.data) { + t.Fatalf("worker %d: download %d sha mismatch", i, status) + } + } + logOK(t, "параллельные загрузки целы") +} + +// Ключ объекта назначает сервер и не содержит filename. +func TestObjectKeyIsServerAssigned(t *testing.T) { + logStep(t, "ключ объекта = attachments/{chat}/{id}; filename в ключ не попадает") + c := newChatCtx(t, "att_key") + meta := mustUpload(t, c, "секрет-имя.png", "image/png", noisePNG(t, 16, 16)) + id := uuid.MustParse(meta["id"].(string)) + key := store.AttachmentObjectKey(uuid.MustParse(c.chat), id) + info, err := sharedObjects.Head(context.Background(), key) + if err != nil { + t.Fatalf("объект по ожидаемому ключу %s не найден: %v", key, err) + } + if info.ContentType != "image/png" || info.Size != int64(meta["size_bytes"].(float64)) { + t.Fatalf("объект в S3: %+v", info) + } + if strings.Contains(key, "секрет") { + t.Fatal("filename попал в ключ") + } + logOK(t, "ключ серверный: "+key) +}