From 7cbb75c897fae7d217599a71e8173f2d09b65d50 Mon Sep 17 00:00:00 2001 From: Mlvn Date: Thu, 12 Nov 2026 18:08:47 +0300 Subject: [PATCH 1/2] =?UTF-8?q?=D0=A0=D0=B5=D0=B0=D0=BB=D0=B8=D0=B7=D0=BE?= =?UTF-8?q?=D0=B2=D0=B0=D1=82=D1=8C=20lab4:=20=D0=B2=D0=BB=D0=BE=D0=B6?= =?UTF-8?q?=D0=B5=D0=BD=D0=B8=D1=8F=20S3/MinIO,=20=D1=83=D1=80=D0=BE=D0=B2?= =?UTF-8?q?=D0=B5=D0=BD=D1=8C=204=20=D0=B8=20=D1=82=D1=80=D0=B5=D0=BA=202?= =?UTF-8?q?=20reconciler.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Метаданные в PostgreSQL, байты в приватном bucket; sync upload 201 ready; компенсация orphan и cmd/reconcile с dry-run/apply и grace period. --- .env.example | 44 +- Dockerfile | 24 + Makefile | 24 +- REPORT.md | 76 +- cmd/reconcile/main.go | 221 +++++ cmd/s3bootstrap/main.go | 123 +++ cmd/server/main.go | 214 +++++ compose.yaml | 203 +++++ evidence/concurrent-uploads.txt | 8 + evidence/failover.txt | 4 + evidence/persistence.txt | 3 + evidence/private-bucket.txt | 2 + evidence/reconcile.txt | 129 +++ evidence/smoke.txt | 2 + evidence/student-tests.txt | 250 ++++++ go.mod | 54 ++ go.sum | 128 +++ infra/README.md | 13 +- infra/haproxy/haproxy.cfg | 52 ++ infra/minio/app-policy.json | 17 + infra/minio/bootstrap.sh | 32 + internal/api/attachments.go | 448 ++++++++++ internal/api/server.go | 780 ++++++++++++++++++ internal/auth/password.go | 110 +++ internal/blob/memory.go | 162 ++++ internal/blob/minio.go | 197 +++++ internal/config/config.go | 189 +++++ internal/session/redis.go | 135 +++ internal/store/attachments.go | 209 +++++ 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 | 33 + internal/store/store.go | 723 ++++++++++++++++ scripts/check-private-bucket.sh | 31 + scripts/concurrent-uploads.sh | 130 +++ scripts/reconcile-demo.sh | 146 ++++ scripts/restart.sh | 7 + scripts/restore-one.sh | 42 + scripts/stop-one.sh | 44 + scripts/up.sh | 38 + student-tests/api_test.go | 664 +++++++++++++++ student-tests/attachments_test.go | 244 ++++++ 43 files changed, 6075 insertions(+), 36 deletions(-) create mode 100644 Dockerfile create mode 100644 cmd/reconcile/main.go create mode 100644 cmd/s3bootstrap/main.go create mode 100644 cmd/server/main.go create mode 100644 compose.yaml create mode 100644 evidence/concurrent-uploads.txt create mode 100644 evidence/failover.txt create mode 100644 evidence/persistence.txt create mode 100644 evidence/private-bucket.txt create mode 100644 evidence/reconcile.txt create mode 100644 evidence/smoke.txt create mode 100644 evidence/student-tests.txt create mode 100644 go.mod create mode 100644 go.sum create mode 100644 infra/haproxy/haproxy.cfg create mode 100644 infra/minio/app-policy.json create mode 100755 infra/minio/bootstrap.sh create mode 100644 internal/api/attachments.go create mode 100644 internal/api/server.go create mode 100644 internal/auth/password.go create mode 100644 internal/blob/memory.go create mode 100644 internal/blob/minio.go create mode 100644 internal/config/config.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/store.go create mode 100755 scripts/check-private-bucket.sh create mode 100755 scripts/concurrent-uploads.sh create mode 100755 scripts/reconcile-demo.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 100644 student-tests/api_test.go create mode 100644 student-tests/attachments_test.go diff --git a/.env.example b/.env.example index d99d26a2..6d162f97 100644 --- a/.env.example +++ b/.env.example @@ -1,20 +1,40 @@ # 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 -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 + +POSTGRES_USER=messenger +POSTGRES_PASSWORD=messenger +POSTGRES_DB=messenger + +# Внутри сети Compose. Хосту для student-tests — localhost после проброса портов. +DATABASE_URL=postgres://messenger:messenger@postgres:5432/messenger?sslmode=disable +REDIS_URL=redis://redis:6379/0 +SESSION_STORE=redis + +# Число API-реплик за LB. Поднимать: scripts/up.sh или compose --scale api=N +API_REPLICAS=2 +# Лимиты одной API-реплики. +API_CPUS=0.50 +API_MEMORY=256M +# Пул соединений на одну реплику. Суммарно ≈ API_REPLICAS * DB_MAX_CONNS. +DB_MAX_CONNS=5 + +# Лимиты вложений (контракт lab4). MAX_UPLOAD_BYTES=10485760 MAX_IMAGE_PIXELS=40000000 + +# MinIO (S3). Root — только для bootstrap (minio-init). API использует app-ключи. +MINIO_ROOT_USER=minioadmin +MINIO_ROOT_PASSWORD=minioadmin-secret +S3_ENDPOINT=minio:9000 +S3_USE_SSL=0 +S3_REGION=us-east-1 +S3_BUCKET=messenger-attachments +S3_ACCESS_KEY_ID=messenger-app +S3_SECRET_ACCESS_KEY=messenger-app-secret +# Grace period reconciler (секунды): свежие orphan/missing не трогаем. +S3_RECONCILE_GRACE_SECONDS=60 diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 00000000..170f5c01 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,24 @@ +# syntax=docker/dockerfile:1.7 +FROM golang:1.24.2-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 +RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags="-s -w" -o /out/reconcile ./cmd/reconcile +RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags="-s -w" -o /out/s3bootstrap ./cmd/s3bootstrap + +FROM gcr.io/distroless/static-debian12:nonroot +COPY --from=build /out/server /server +COPY --from=build /out/reconcile /reconcile +COPY --from=build /out/s3bootstrap /s3bootstrap +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..9448480d 100644 --- a/Makefile +++ b/Makefile @@ -4,10 +4,10 @@ CA_FILE ?= ACTION_SCRIPT ?= TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",) -.PHONY: help check validate test load test-persistence test-failover +.PHONY: help check validate test load test-persistence test-failover up down student-test private-bucket concurrent reconcile-demo help: - @echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes" + @echo "check: offline structure; validate: full OpenAPI; test: smoke; up/down: compose stand" check: $(PYTHON) scripts/check_contract.py @@ -28,3 +28,23 @@ test-persistence: test-failover: @test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable stop-one hook"; exit 2) $(PYTHON) tests/resilience.py --mode failover --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS) + +up: + bash scripts/up.sh + +down: + docker compose --env-file .env down + +student-test: + DATABASE_URL=postgres://messenger:messenger@127.0.0.1:5432/messenger?sslmode=disable \ + REDIS_URL=redis://127.0.0.1:6379/0 \ + go test ./student-tests/ -count=1 -v + +private-bucket: + bash scripts/check-private-bucket.sh + +concurrent: + bash scripts/concurrent-uploads.sh + +reconcile-demo: + bash scripts/reconcile-demo.sh diff --git a/REPORT.md b/REPORT.md index 9ad2b84f..1bb32a2f 100644 --- a/REPORT.md +++ b/REPORT.md @@ -1,37 +1,81 @@ # Отчёт — лабораторная 4 -- Автор, группа: TODO -- Целевая оценка; выбранный трек 5, если нужен: TODO -- Commit/PR: TODO после публикации -- Использованные источники, библиотеки и помощь ИИ: TODO +- Автор, группа: Белоусов Анатолий Фахраддинович, БПИ2303 +- Целевая оценка; выбранный трек 5: **5, трек 2** (согласованность двух хранилищ / reconciler) +- Commit/PR: ветка `solution/bpi2303-belousov` +- Использованные источники, библиотеки и помощь ИИ: Go `net/http`, `pgx` v5, `go-redis` v9, `minio-go` v7, `madmin-go` v3, `golang.org/x/crypto/argon2`, `google/uuid`; MinIO community-образ `ghcr.io/coollabsio/minio` (официальные `minio/minio` сняты с Docker Hub); HAProxy 2.9; публичные `tests/`; Cursor/Composer. База — реализация lab3. ## Запуск из чистого clone -TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных. +Нужны Docker, Go 1.24+ (student-tests), Python 3.9+. + +```sh +cp .env.example .env +bash scripts/up.sh +# postgres+redis+minio → s3bootstrap → migrate → API×N → LB :8080 +make test +make student-test +make private-bucket +make concurrent +make test-persistence ACTION_SCRIPT=scripts/restart.sh +make test-failover ACTION_SCRIPT=scripts/stop-one.sh +bash scripts/restore-one.sh # после failover +make reconcile-demo # трек 5: dry-run → apply → fresh skip +``` + +Остановка без удаления данных: `docker compose --env-file .env stop`. +Удаление учебных volumes: `docker compose --env-file .env down -v`. + +Образы: сборка `golang:1.24.2-bookworm`, runtime `gcr.io/distroless/static-debian12:nonroot`, PostgreSQL `postgres:16.6`, Redis `redis:7.4.1` (AOF), HAProxy `haproxy:2.9.14-alpine`, MinIO `ghcr.io/coollabsio/minio:RELEASE.2025-10-15T17-29-55Z`. Консоль MinIO не публикуется; API S3 — только `127.0.0.1:9000` для локальной проверки private bucket. ## Архитектура и решения -TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab3, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации. +Клиент → HAProxy → API×2+ → PostgreSQL (метаданные) + Redis (сессии) + приватный MinIO (байты). + +Вложение: сервер назначает ключ `originals/`; `filename` только в метаданных. Порядок записи — **сначала S3 PUT, потом INSERT**; 201 только после обоих. Ошибка INSERT → немедленный Delete объекта; если Delete не удался — orphan подберёт reconciler после grace. + +Загрузка: spool во временный файл (не `ReadAll`), лимит `MaxUploadBytes+1`, MIME по содержимому, размеры PNG/JPEG из заголовка до декодирования пикселей, структурная проверка CRC/EOI. Download — proxy через API (проверка членства), без редиректа на S3. + +Перенесено из lab3: LB, Idempotency-Key, X-Instance-Id, Redis-сессии, failover hooks. Добавлено: миграция `003_attachments.sql`, routes attachments, `cmd/reconcile`, `cmd/s3bootstrap`, MinIO в compose. + +Переменные `.env.example` → compose `x-api-env` / Load / LoadS3: `DATABASE_URL`, `REDIS_URL`, `S3_*`, `MAX_UPLOAD_*`, `S3_RECONCILE_GRACE_SECONDS`. ## Доказательства критериев | Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства | | --- | --- | --- | --- | -| Публичный smoke | make test | TODO | TODO | -| Остальные пункты уровня 3 | TODO | TODO | TODO | -| Все пункты уровня 4, если заявлен | TODO | TODO | TODO | -| Выбранный трек 5, если заявлен | TODO | TODO | TODO | - -TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены. +| Публичный smoke (checksum, ACL) | `make test` | PASS lab4 public API scenario | `evidence/smoke.txt` | +| Offline contract | `make check` | PASS | (stdout) | +| Student-tests вложений/негативы/S3↓ | `make student-test` | PASS | `evidence/student-tests.txt` | +| Private bucket | `make private-bucket` | anonymous GET → HTTP 403 | `evidence/private-bucket.txt` | +| Persistence + оригинал | `make test-persistence ACTION_SCRIPT=scripts/restart.sh` | PASS (restart postgres redis minio api lb) | `evidence/persistence.txt` | +| Failover API + download через другую реплику | `make test-failover ACTION_SCRIPT=scripts/stop-one.sh` | PASS; 2 instance ids до отказа | `evidence/failover.txt` | +| ≥10 concurrent uploads + RSS | `make concurrent` | 12×201; RSS API до/пик/после | `evidence/concurrent-uploads.txt` | +| Трек 2 reconciler | `make reconcile-demo` | orphan deleted; missing unreferenced deleted; referenced kept; fresh skipped | `evidence/reconcile.txt` | ## Эксперименты и отказы -TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения. +**Гипотеза (трек 2):** при grace period reconciler безопасно удаляет только «старые» orphan-объекты и нессылаемые missing-строки; повторный apply идемпотентен; свежий orphan не трогается. -| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных | +Методика: `scripts/reconcile-demo.sh` — SigV4 PUT orphan root-ключом; SQL INSERT missing без объекта; dry-run/`-apply` с `-grace-seconds=0`; затем fresh orphan и dry-run с grace=60s. + +Результаты (локальный прогон): orphan удалён; 2 missing без ссылок удалены; 2 missing с `message_attachments` сохранены; fresh orphan → `orphan_skip_fresh`. Обход: List S3 O(n) + keyset по attachments; elapsed dry-run ~10–30 ms на учебном объёме. + +**Concurrent uploads:** 12 параллельных PNG по ~3.0 MiB (1024², zlib level 0), spool в `/tmp`. +RSS суммарно по API-репликам: before ≈96 MiB, peak ≈98 MiB, after ≈97 MiB — пик не масштабируется +как `N × размер файла` (нет `ReadAll` в кучу). См. `evidence/concurrent-uploads.txt`. + +| Воздействие | Что ожидаем | Что наблюдали | Восстановление | | --- | --- | --- | --- | -| TODO | TODO | TODO | TODO | +| `docker stop` одной API | LB уводит трафик; download с другой реплики | PASS failover | `scripts/restore-one.sh` | +| `restart` всех хранилищ+API | сессия и файл на месте | PASS persistence | volumes сохранены | +| Anonymous GET MinIO | не 200 | 403 | — | +| S3 down (unit) | ready/upload 503 | PASS student-test | — | ## Ограничения и следующие шаги -TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза. +- Официальные образы MinIO/Docker Hub недоступны; закреплён community-образ coollabsio того же RELEASE — риск расхождения с upstream. +- Reconciler не чинит referenced missing (нет исходных байтов) — только детектит; восстановление из бэкапа S3 вне скоупа. +- Student-tests с in-memory blob пишут метаданные в общий Postgres без объектов в MinIO; на учебном стенде их подбирает reconciler (referenced → keep). +- Presigned direct upload (трек 1) не реализован — выбран трек 2. +- Учебные секреты в `.env.example`; в Git не коммитить `.env`. diff --git a/cmd/reconcile/main.go b/cmd/reconcile/main.go new file mode 100644 index 00000000..d9d15d48 --- /dev/null +++ b/cmd/reconcile/main.go @@ -0,0 +1,221 @@ +// Reconciler lab4 (трек 5 / согласованность двух хранилищ). +// +// Сверяет PostgreSQL (attachments) и приватный S3-bucket (префикс originals/). +// По умолчанию dry-run: только отчёт. Флаг -apply выполняет безопасные правки. +// +// Классы расхождений: +// +// orphan — объект в S3 без строки в БД. После grace period удаляется (-apply). +// missing — строка в БД без объекта. Если на вложение нет ссылок из сообщений +// и строка старше grace — удаляется. Ссылаемые (в сообщениях) только +// логируются: удалять их нельзя, файл уже «в истории». +// +// Свежие объекты/строки (моложе grace) не трогаются: гонка «PUT прошёл, INSERT ещё нет» +// не должна приводить к удалению чужой успешной загрузки. +package main + +import ( + "context" + "flag" + "fmt" + "log" + "os" + "os/signal" + "syscall" + "time" + + "github.com/google/uuid" + + "mtusi2026lab4/internal/auth" + "mtusi2026lab4/internal/blob" + "mtusi2026lab4/internal/config" + "mtusi2026lab4/internal/store" +) + +func main() { + apply := flag.Bool("apply", false, "apply safe fixes (default: dry-run)") + graceSec := flag.Int64("grace-seconds", -1, "override S3_RECONCILE_GRACE_SECONDS (-1 = from env)") + pageSize := flag.Int("page-size", 200, "DB page size for attachment refs") + flag.Parse() + + cfg, err := config.Load() + if err != nil { + log.Fatalf("config: %v", err) + } + grace := cfg.ReconcileGrace + if *graceSec >= 0 { + grace = time.Duration(*graceSec) * time.Second + } + s3cfg, err := config.LoadS3() + if err != nil { + log.Fatalf("s3 config: %v", err) + } + + ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, syscall.SIGINT) + defer stop() + + hasher, err := auth.NewHasher() + if err != nil { + log.Fatalf("hasher: %v", err) + } + st, err := store.Open(ctx, cfg.DatabaseURL, hasher, cfg.MaxConns) + if err != nil { + log.Fatalf("postgres: %v", err) + } + defer st.Close() + + bl, err := blob.New(blob.Config{ + Endpoint: s3cfg.Endpoint, + UseSSL: s3cfg.UseSSL, + Region: s3cfg.Region, + Bucket: s3cfg.Bucket, + AccessKey: s3cfg.AccessKey, + SecretKey: s3cfg.SecretKey, + }) + if err != nil { + log.Fatalf("s3: %v", err) + } + if err := bl.Ping(ctx); err != nil { + log.Fatalf("s3 ping: %v", err) + } + + mode := "dry-run" + if *apply { + mode = "apply" + } + log.Printf("reconcile start mode=%s grace=%s bucket=%s page=%d", mode, grace, s3cfg.Bucket, *pageSize) + + started := time.Now() + rep, err := run(ctx, st, bl, grace, *pageSize, *apply) + if err != nil { + log.Fatalf("reconcile: %v", err) + } + elapsed := time.Since(started) + + fmt.Printf("reconcile_report mode=%s elapsed_ms=%d\n", mode, elapsed.Milliseconds()) + fmt.Printf("s3_objects=%d db_rows=%d\n", rep.S3Objects, rep.DBRows) + fmt.Printf("orphans_found=%d orphans_deleted=%d orphans_skipped_fresh=%d\n", + rep.OrphansFound, rep.OrphansDeleted, rep.OrphansSkippedFresh) + fmt.Printf("missing_found=%d missing_deleted=%d missing_referenced=%d missing_skipped_fresh=%d\n", + rep.MissingFound, rep.MissingDeleted, rep.MissingReferenced, rep.MissingSkippedFresh) + for _, line := range rep.Details { + fmt.Println(line) + } + os.Exit(0) +} + +type report struct { + S3Objects int + DBRows int + OrphansFound int + OrphansDeleted int + OrphansSkippedFresh int + MissingFound int + MissingDeleted int + MissingReferenced int + MissingSkippedFresh int + Details []string +} + +func run(ctx context.Context, st *store.Store, bl *blob.Client, grace time.Duration, pageSize int, apply bool) (*report, error) { + if pageSize < 1 || pageSize > 1000 { + pageSize = 200 + } + rep := &report{} + cutoff := time.Now().UTC().Add(-grace) + + objs, err := bl.ListKeys(ctx, blob.KeyPrefix) + if err != nil { + return nil, fmt.Errorf("list s3: %w", err) + } + rep.S3Objects = len(objs) + byKey := make(map[string]blob.ObjectInfo, len(objs)) + for _, o := range objs { + byKey[o.Key] = o + } + + dbKeys := make(map[string]store.AttachmentRef) + var after uuid.UUID + for { + page, err := st.ListAttachmentRefs(ctx, after, pageSize) + if err != nil { + return nil, fmt.Errorf("list db: %w", err) + } + if len(page) == 0 { + break + } + for _, r := range page { + dbKeys[r.ObjectKey] = r + rep.DBRows++ + after = r.ID + } + if len(page) < pageSize { + break + } + } + + // orphan: S3 без строки + for key, o := range byKey { + if _, ok := dbKeys[key]; ok { + continue + } + rep.OrphansFound++ + if o.LastModified.After(cutoff) { + rep.OrphansSkippedFresh++ + rep.Details = append(rep.Details, fmt.Sprintf("orphan_skip_fresh key=%s age<%s", key, grace)) + continue + } + // Повторная проверка: загрузка могла успеть записать строку после ListKeys. + exists, err := st.AttachmentKeyExists(ctx, key) + if err != nil { + return nil, err + } + if exists { + rep.Details = append(rep.Details, fmt.Sprintf("orphan_race_gone key=%s", key)) + continue + } + if apply { + if err := bl.Delete(ctx, key); err != nil { + return nil, fmt.Errorf("delete orphan %s: %w", key, err) + } + rep.OrphansDeleted++ + rep.Details = append(rep.Details, fmt.Sprintf("orphan_deleted key=%s size=%d", key, o.Size)) + } else { + rep.Details = append(rep.Details, fmt.Sprintf("orphan_would_delete key=%s size=%d", key, o.Size)) + } + } + + // missing: строка без объекта + for key, ref := range dbKeys { + if _, ok := byKey[key]; ok { + continue + } + rep.MissingFound++ + if ref.CreatedAt.After(cutoff) { + rep.MissingSkippedFresh++ + rep.Details = append(rep.Details, fmt.Sprintf("missing_skip_fresh id=%s key=%s", ref.ID, key)) + continue + } + if ref.Referenced { + rep.MissingReferenced++ + rep.Details = append(rep.Details, fmt.Sprintf("missing_referenced id=%s key=%s (kept)", ref.ID, key)) + continue + } + if apply { + ok, err := st.DeleteUnreferencedAttachment(ctx, ref.ID) + if err != nil { + return nil, fmt.Errorf("delete missing meta %s: %w", ref.ID, err) + } + if ok { + rep.MissingDeleted++ + rep.Details = append(rep.Details, fmt.Sprintf("missing_deleted id=%s key=%s", ref.ID, key)) + } else { + rep.MissingReferenced++ + rep.Details = append(rep.Details, fmt.Sprintf("missing_race_referenced id=%s key=%s", ref.ID, key)) + } + } else { + rep.Details = append(rep.Details, fmt.Sprintf("missing_would_delete id=%s key=%s", ref.ID, key)) + } + } + return rep, nil +} diff --git a/cmd/s3bootstrap/main.go b/cmd/s3bootstrap/main.go new file mode 100644 index 00000000..a614cb0a --- /dev/null +++ b/cmd/s3bootstrap/main.go @@ -0,0 +1,123 @@ +// Одноразовый bootstrap приватного S3-bucket и app-пользователя с ограниченной политикой. +// Нужен, потому что публичные образы minio/mc с Docker Hub сняты; admin API вызываем из Go. +package main + +import ( + "context" + "fmt" + "log" + "os" + "strings" + "time" + + "github.com/minio/madmin-go/v3" + "github.com/minio/minio-go/v7" + "github.com/minio/minio-go/v7/pkg/credentials" +) + +func main() { + endpoint := env("MINIO_ENDPOINT", "minio:9000") + endpoint = strings.TrimPrefix(strings.TrimPrefix(endpoint, "https://"), "http://") + rootUser := mustEnv("MINIO_ROOT_USER") + rootPass := mustEnv("MINIO_ROOT_PASSWORD") + bucket := env("S3_BUCKET", "messenger-attachments") + appKey := mustEnv("S3_ACCESS_KEY_ID") + appSecret := mustEnv("S3_SECRET_ACCESS_KEY") + useSSL := env("S3_USE_SSL", "0") == "1" || strings.EqualFold(env("S3_USE_SSL", "0"), "true") + + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) + defer cancel() + + mc, err := minio.New(endpoint, &minio.Options{ + Creds: credentials.NewStaticV4(rootUser, rootPass, ""), + Secure: useSSL, + }) + if err != nil { + log.Fatalf("minio client: %v", err) + } + + deadline := time.Now().Add(90 * time.Second) + for { + ok, err := mc.BucketExists(ctx, bucket) + if err == nil { + if !ok { + if err := mc.MakeBucket(ctx, bucket, minio.MakeBucketOptions{}); err != nil { + code := minio.ToErrorResponse(err).Code + if code != "BucketAlreadyOwnedByYou" && code != "BucketAlreadyExists" { + log.Fatalf("make bucket: %v", err) + } + } + } + break + } + if time.Now().After(deadline) { + log.Fatalf("minio not ready: %v", err) + } + log.Printf("waiting for minio: %v", err) + time.Sleep(time.Second) + } + + // Явно запрещаем анонимный доступ (на случай, если кто-то выставил public). + if err := mc.SetBucketPolicy(ctx, bucket, ""); err != nil { + log.Printf("clear bucket policy: %v (продолжаем)", err) + } + + admin, err := madmin.NewWithOptions(endpoint, &madmin.Options{ + Creds: credentials.NewStaticV4(rootUser, rootPass, ""), + Secure: useSSL, + }) + if err != nil { + log.Fatalf("madmin: %v", err) + } + + policyName := "app-attachments" + policy := fmt.Sprintf(`{ + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Action": ["s3:ListBucket"], + "Resource": ["arn:aws:s3:::%s"] + }, + { + "Effect": "Allow", + "Action": ["s3:GetObject", "s3:PutObject", "s3:DeleteObject"], + "Resource": ["arn:aws:s3:::%s/*"] + } + ] +}`, bucket, bucket) + + if err := admin.AddCannedPolicy(ctx, policyName, []byte(policy)); err != nil { + // Уже существует — ок. + log.Printf("add policy: %v", err) + } + if err := admin.AddUser(ctx, appKey, appSecret); err != nil { + log.Printf("add user: %v", err) + } + if _, err := admin.AttachPolicy(ctx, madmin.PolicyAssociationReq{ + Policies: []string{policyName}, + User: appKey, + }); err != nil { + // Старые версии madmin: SetPolicy + if err2 := admin.SetPolicy(ctx, policyName, appKey, false); err2 != nil { + log.Fatalf("attach policy: %v / set policy: %v", err, err2) + } + } + + log.Printf("bootstrap ok bucket=%s app_user=%s private=yes", bucket, appKey) +} + +func env(k, def string) string { + if v := strings.TrimSpace(os.Getenv(k)); v != "" { + return v + } + return def +} + +func mustEnv(k string) string { + v := strings.TrimSpace(os.Getenv(k)) + if v == "" { + log.Fatalf("missing %s", k) + } + return v +} diff --git a/cmd/server/main.go b/cmd/server/main.go new file mode 100644 index 00000000..a700e95f --- /dev/null +++ b/cmd/server/main.go @@ -0,0 +1,214 @@ +// Точка входа HTTP API и одноразового мигратора lab4. +// +// Режимы: +// +// (по умолчанию) — API-реплика: Postgres + Redis + S3, миграции НЕ применяет; +// -migrate — применить SQL и выйти (S3 не нужен); +// -healthcheck — локальный probe /health/ready. +package main + +import ( + "context" + "flag" + "fmt" + "io" + "log" + "net/http" + "os" + "os/signal" + "syscall" + "time" + + "mtusi2026lab4/internal/api" + "mtusi2026lab4/internal/auth" + "mtusi2026lab4/internal/blob" + "mtusi2026lab4/internal/config" + "mtusi2026lab4/internal/session" + "mtusi2026lab4/internal/store" +) + +func main() { + healthcheck := flag.Bool("healthcheck", false, "probe local /health/ready and exit") + migrateOnly := flag.Bool("migrate", false, "apply SQL migrations and exit") + 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() + + if *migrateOnly || cfg.RunMigrations { + if err := st.Migrate(rootCtx); err != nil { + log.Fatalf("migrate: %v", err) + } + log.Printf("migrations applied") + if *migrateOnly { + return + } + } + + sessions, err := waitRedis(rootCtx, cfg.RedisURL, cfg.SessionTTL) + if err != nil { + log.Fatalf("redis: %v", err) + } + defer sessions.Close() + + s3cfg, err := config.LoadS3() + if err != nil { + log.Fatalf("s3 config: %v", err) + } + blobs, err := waitS3(rootCtx, s3cfg) + if err != nil { + log.Fatalf("s3: %v", err) + } + + srvAPI := api.New(st, sessions, blobs, cfg.InstanceID) + srvAPI.MaxUploadBytes = cfg.MaxUploadBytes + srvAPI.MaxImagePixels = cfg.MaxImagePixels + + httpServer := &http.Server{ + Addr: cfg.Addr(), + Handler: srvAPI.Handler(), + ReadHeaderTimeout: 5 * time.Second, + // Upload до 10 MiB: даём запас на медленный клиент. + ReadTimeout: 60 * time.Second, + WriteTimeout: 60 * 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 bucket=%s", + cfg.Addr(), cfg.Env, cfg.InstanceID, cfg.SessionTTL, cfg.MaxConns, s3cfg.Bucket) + 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") +} + +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 waitS3(ctx context.Context, cfg config.S3) (*blob.Client, error) { + deadline := time.Now().Add(45 * time.Second) + var last error + for { + c, err := blob.New(blob.Config{ + Endpoint: cfg.Endpoint, + UseSSL: cfg.UseSSL, + Region: cfg.Region, + Bucket: cfg.Bucket, + AccessKey: cfg.AccessKey, + SecretKey: cfg.SecretKey, + }) + if err == nil { + if err = c.Ping(ctx); err == nil { + return c, nil + } + last = err + } else { + last = err + } + if ctx.Err() != nil || time.Now().After(deadline) { + return nil, last + } + log.Printf("s3 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..7eac7ce6 --- /dev/null +++ b/compose.yaml @@ -0,0 +1,203 @@ +# Локальный стенд lab4: Клиент → HAProxy → API×N → PostgreSQL + Redis + приватный MinIO. +# Публикуется только LB (:8080). Порты API наружу не публикуются. +# MinIO API на 127.0.0.1:9000 — только для локальной проверки private bucket; консоль не публикуется. +# Запуск: bash scripts/up.sh +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 + MAX_UPLOAD_BYTES: ${MAX_UPLOAD_BYTES:-10485760} + MAX_IMAGE_PIXELS: ${MAX_IMAGE_PIXELS:-40000000} + S3_ENDPOINT: ${S3_ENDPOINT:-minio:9000} + S3_USE_SSL: ${S3_USE_SSL:-0} + S3_REGION: ${S3_REGION:-us-east-1} + S3_BUCKET: ${S3_BUCKET:-messenger-attachments} + S3_ACCESS_KEY_ID: ${S3_ACCESS_KEY_ID:-messenger-app} + S3_SECRET_ACCESS_KEY: ${S3_SECRET_ACCESS_KEY:-messenger-app-secret} + S3_RECONCILE_GRACE_SECONDS: ${S3_RECONCILE_GRACE_SECONDS:-60} + +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:5432: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:6379: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/minio с Docker Hub сняты (2026). Собираем из community-образа + # ghcr.io/coollabsio/minio — бинарь последнего community RELEASE. + minio: + image: ghcr.io/coollabsio/minio:RELEASE.2025-10-15T17-29-55Z + command: ["server", "/data", "--address", ":9000", "--console-address", ":9001"] + environment: + MINIO_ROOT_USER: ${MINIO_ROOT_USER:-minioadmin} + MINIO_ROOT_PASSWORD: ${MINIO_ROOT_PASSWORD:-minioadmin-secret} + volumes: + - miniodata:/data + ports: + - "127.0.0.1:9000:9000" + # Консоль :9001 намеренно не публикуется (уровень 4). + # В образе нет curl; TCP-probe + bootstrap ретраит MakeBucket. + healthcheck: + test: ["CMD", "bash", "-c", "exec 3<>/dev/tcp/127.0.0.1/9000"] + interval: 5s + timeout: 3s + retries: 20 + start_period: 10s + stop_grace_period: 10s + deploy: + resources: + limits: + cpus: "0.50" + memory: 512M + + # Bootstrap без mc: бинарь /s3bootstrap из нашего образа (minio-go + madmin). + minio-init: + build: . + entrypoint: ["/s3bootstrap"] + environment: + MINIO_ENDPOINT: minio:9000 + MINIO_ROOT_USER: ${MINIO_ROOT_USER:-minioadmin} + MINIO_ROOT_PASSWORD: ${MINIO_ROOT_PASSWORD:-minioadmin-secret} + S3_BUCKET: ${S3_BUCKET:-messenger-attachments} + S3_ACCESS_KEY_ID: ${S3_ACCESS_KEY_ID:-messenger-app} + S3_SECRET_ACCESS_KEY: ${S3_SECRET_ACCESS_KEY:-messenger-app-secret} + S3_USE_SSL: ${S3_USE_SSL:-0} + depends_on: + minio: + condition: service_healthy + restart: "no" + healthcheck: + disable: true + + migrate: + build: . + command: ["-migrate"] + environment: + <<: *api-env + depends_on: + postgres: + condition: service_healthy + 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} + + reconcile: + build: . + entrypoint: ["/reconcile"] + environment: + <<: *api-env + depends_on: + postgres: + condition: service_healthy + minio: + condition: service_healthy + minio-init: + condition: service_completed_successfully + restart: "no" + deploy: + resources: + limits: + cpus: "0.50" + 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:8080: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: + miniodata: diff --git a/evidence/concurrent-uploads.txt b/evidence/concurrent-uploads.txt new file mode 100644 index 00000000..6769b38a --- /dev/null +++ b/evidence/concurrent-uploads.txt @@ -0,0 +1,8 @@ +concurrent=12 +upload_bytes=3147060 +ok_201=12 +results=[201, 201, 201, 201, 201, 201, 201, 201, 201, 201, 201, 201] +elapsed_s=1.717 +api_rss_kb_before=96654 +api_rss_kb_peak=98006 +api_rss_kb_after=97197 diff --git a/evidence/failover.txt b/evidence/failover.txt new file mode 100644 index 00000000..a4c73971 --- /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://localhost:8080" +Executing explicit failover hook; hook output suppressed to avoid leaking secrets. +{"observed_instances_before": 2, "successful_writes": 112, "failed_attempts": 1, "first_recovery_seconds": 2.928} +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..793b001d --- /dev/null +++ b/evidence/persistence.txt @@ -0,0 +1,3 @@ +python3 tests/resilience.py --mode persistence --action-script "scripts/restart.sh" --base-url "http://localhost:8080" +Executing explicit persistence hook; hook output suppressed to avoid leaking secrets. +PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence. diff --git a/evidence/private-bucket.txt b/evidence/private-bucket.txt new file mode 100644 index 00000000..08767083 --- /dev/null +++ b/evidence/private-bucket.txt @@ -0,0 +1,2 @@ +GET http://127.0.0.1:9000/messenger-attachments/originals/does-not-exist → HTTP 403 body_bytes=381 +PASS: anonymous access denied (HTTP 403) diff --git a/evidence/reconcile.txt b/evidence/reconcile.txt new file mode 100644 index 00000000..61d55664 --- /dev/null +++ b/evidence/reconcile.txt @@ -0,0 +1,129 @@ +=== seed orphan object via root PutObject (python/minio not required: curl+aws style via go) === +orphan_put 200 +=== seed missing metadata (DB row, no S3 object) === +DO +=== dry-run grace=0 === +#1 [internal] load local bake definitions +#1 reading from stdin 683B done +#1 DONE 0.0s + +#2 [internal] load build definition from Dockerfile +#2 transferring dockerfile: 927B done +#2 DONE 0.0s + +#3 resolve image config for docker-image://docker.io/docker/dockerfile:1.7 +#3 DONE 1.0s + +#4 docker-image://docker.io/docker/dockerfile:1.7@sha256:a57df69d0ea827fb7266491f2813635de6f17269be881f696fbfdf2d83dda33e +#4 resolve docker.io/docker/dockerfile:1.7@sha256:a57df69d0ea827fb7266491f2813635de6f17269be881f696fbfdf2d83dda33e done +#4 CACHED + +#5 [internal] load metadata for docker.io/library/golang:1.24.2-bookworm +#5 DONE 0.6s + +#6 [internal] load metadata for gcr.io/distroless/static-debian12:nonroot +#6 DONE 0.7s + +#7 [internal] load .dockerignore +#7 transferring context: 196B done +#7 DONE 0.0s + +#8 [stage-1 1/4] FROM gcr.io/distroless/static-debian12:nonroot@sha256:afa5c872c891853ca7fcf1f12c3edb23f7eeef36189728842dd51042ff57f7ab +#8 resolve gcr.io/distroless/static-debian12:nonroot@sha256:afa5c872c891853ca7fcf1f12c3edb23f7eeef36189728842dd51042ff57f7ab 0.0s done +#8 DONE 0.0s + +#9 [build 1/9] FROM docker.io/library/golang:1.24.2-bookworm@sha256:79390b5e5af9ee6e7b1173ee3eac7fadf6751a545297672916b59bfa0ecf6f71 +#9 resolve docker.io/library/golang:1.24.2-bookworm@sha256:79390b5e5af9ee6e7b1173ee3eac7fadf6751a545297672916b59bfa0ecf6f71 0.0s done +#9 DONE 0.0s + +#10 [internal] load build context +#10 transferring context: 1.21kB 0.0s done +#10 DONE 0.0s + +#11 [stage-1 2/4] COPY --from=build /out/server /server +#11 CACHED + +#12 [stage-1 3/4] COPY --from=build /out/reconcile /reconcile +#12 CACHED + +#13 [build 6/9] COPY internal ./internal +#13 CACHED + +#14 [build 4/9] RUN go mod download +#14 CACHED + +#15 [build 2/9] WORKDIR /src +#15 CACHED + +#16 [build 8/9] RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags="-s -w" -o /out/reconcile ./cmd/reconcile +#16 CACHED + +#17 [build 9/9] RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags="-s -w" -o /out/s3bootstrap ./cmd/s3bootstrap +#17 CACHED + +#18 [build 3/9] COPY go.mod go.sum ./ +#18 CACHED + +#19 [build 5/9] COPY cmd ./cmd +#19 CACHED + +#20 [build 7/9] RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags="-s -w" -o /out/server ./cmd/server +#20 CACHED + +#21 [stage-1 4/4] COPY --from=build /out/s3bootstrap /s3bootstrap +#21 CACHED + +#22 exporting to image +#22 exporting layers 0.0s done +#22 exporting manifest sha256:b3e7db748d123d1baf965ab1e27b5d2a2bea64f3e68fe93798166da5c67b58f3 0.1s done +#22 exporting config sha256:76f75b546642e6ee2a4f055c5a45f1f406f5698112cd37c26b7301bcdcf8839f +#22 exporting config sha256:76f75b546642e6ee2a4f055c5a45f1f406f5698112cd37c26b7301bcdcf8839f 0.0s done +#22 exporting attestation manifest sha256:a877a0a7985478d45981bc5e291b0bc16bf401bfedfe03691ee01f5f50cf1606 +#22 exporting attestation manifest sha256:a877a0a7985478d45981bc5e291b0bc16bf401bfedfe03691ee01f5f50cf1606 0.0s done +#22 exporting manifest list sha256:e53705a39a996dc932198dc966f069d8bb83bba703dbcb6db0fe25d733a4fab7 0.0s done +#22 naming to docker.io/library/mtusi2026lab4-reconcile:latest done +#22 unpacking to docker.io/library/mtusi2026lab4-reconcile:latest done +#22 DONE 0.4s + +#23 resolving provenance for metadata file +#23 DONE 0.0s +2026/11/12 15:06:31 reconcile start mode=dry-run grace=0s bucket=messenger-attachments page=200 +reconcile_report mode=dry-run elapsed_ms=33 +s3_objects=16 db_rows=19 +orphans_found=1 orphans_deleted=0 orphans_skipped_fresh=0 +missing_found=4 missing_deleted=0 missing_referenced=2 missing_skipped_fresh=0 +orphan_would_delete key=originals/00000000-0000-4000-8000-0000000000aa size=12 +missing_referenced id=867bc3f8-3656-4138-a787-b5fc8fc85498 key=originals/867bc3f8-3656-4138-a787-b5fc8fc85498 (kept) +missing_referenced id=cd3c2ce1-b4fb-4229-99e7-356d5ffb4d8b key=originals/cd3c2ce1-b4fb-4229-99e7-356d5ffb4d8b (kept) +missing_would_delete id=ad7a23e7-aa2a-4c95-8d17-52394f8ebfd2 key=originals/ad7a23e7-aa2a-4c95-8d17-52394f8ebfd2 +missing_would_delete id=11111111-1111-4111-8111-111111111111 key=originals/11111111-1111-4111-8111-111111111111 +=== apply grace=0 === +2026/11/12 15:06:33 reconcile start mode=apply grace=0s bucket=messenger-attachments page=200 +reconcile_report mode=apply elapsed_ms=17 +s3_objects=16 db_rows=19 +orphans_found=1 orphans_deleted=1 orphans_skipped_fresh=0 +missing_found=4 missing_deleted=2 missing_referenced=2 missing_skipped_fresh=0 +orphan_deleted key=originals/00000000-0000-4000-8000-0000000000aa size=12 +missing_referenced id=867bc3f8-3656-4138-a787-b5fc8fc85498 key=originals/867bc3f8-3656-4138-a787-b5fc8fc85498 (kept) +missing_deleted id=ad7a23e7-aa2a-4c95-8d17-52394f8ebfd2 key=originals/ad7a23e7-aa2a-4c95-8d17-52394f8ebfd2 +missing_referenced id=cd3c2ce1-b4fb-4229-99e7-356d5ffb4d8b key=originals/cd3c2ce1-b4fb-4229-99e7-356d5ffb4d8b (kept) +missing_deleted id=11111111-1111-4111-8111-111111111111 key=originals/11111111-1111-4111-8111-111111111111 +=== second apply (idempotent) === +2026/11/12 15:06:34 reconcile start mode=apply grace=0s bucket=messenger-attachments page=200 +reconcile_report mode=apply elapsed_ms=7 +s3_objects=15 db_rows=17 +orphans_found=0 orphans_deleted=0 orphans_skipped_fresh=0 +missing_found=2 missing_deleted=0 missing_referenced=2 missing_skipped_fresh=0 +missing_referenced id=cd3c2ce1-b4fb-4229-99e7-356d5ffb4d8b key=originals/cd3c2ce1-b4fb-4229-99e7-356d5ffb4d8b (kept) +missing_referenced id=867bc3f8-3656-4138-a787-b5fc8fc85498 key=originals/867bc3f8-3656-4138-a787-b5fc8fc85498 (kept) +=== fresh orphan skipped with default grace === +fresh_put 200 +2026/11/12 15:06:35 reconcile start mode=dry-run grace=1m0s bucket=messenger-attachments page=200 +reconcile_report mode=dry-run elapsed_ms=13 +s3_objects=16 db_rows=17 +orphans_found=1 orphans_deleted=0 orphans_skipped_fresh=1 +missing_found=2 missing_deleted=0 missing_referenced=0 missing_skipped_fresh=2 +orphan_skip_fresh key=originals/00000000-0000-4000-8000-0000000000bb age<1m0s +missing_skip_fresh id=cd3c2ce1-b4fb-4229-99e7-356d5ffb4d8b key=originals/cd3c2ce1-b4fb-4229-99e7-356d5ffb4d8b +missing_skip_fresh id=867bc3f8-3656-4138-a787-b5fc8fc85498 key=originals/867bc3f8-3656-4138-a787-b5fc8fc85498 +wrote evidence/reconcile.txt diff --git a/evidence/smoke.txt b/evidence/smoke.txt new file mode 100644 index 00000000..1e7b9ff4 --- /dev/null +++ b/evidence/smoke.txt @@ -0,0 +1,2 @@ +python3 tests/smoke.py --base-url "http://localhost:8080" +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..3e6b06d0 --- /dev/null +++ b/evidence/student-tests.txt @@ -0,0 +1,250 @@ +DATABASE_URL=postgres://messenger:messenger@127.0.0.1:5432/messenger?sslmode=disable \ + REDIS_URL=redis://127.0.0.1:6379/0 \ + go test ./student-tests/ -count=1 -v +=== RUN TestMalformedJSONAndValidation + api_test.go:76: → битый JSON, хвост после объекта, лишнее поле, пустой текст, чужой чат +2026/11/12 18:06:18 method=POST path=/api/v1/users status=400 request_id=8c1902bd-a429-4b6c-9a41-39b3dc20c4e8 duration_ms=0 + api_test.go:79: status=400 body={"error":{"code":"invalid_request","message":"malformed json","request_id":"8c1902bd-a429-4b6c-9a41-39b3dc20c4e8"}} +2026/11/12 18:06:18 method=POST path=/api/v1/users status=400 request_id=f01f3adb-78bb-4722-8c40-fcb5939899ec duration_ms=0 + api_test.go:86: status=400 body={"error":{"code":"invalid_request","message":"malformed json","request_id":"f01f3adb-78bb-4722-8c40-fcb5939899ec"}} +2026/11/12 18:06:18 method=POST path=/api/v1/users status=201 request_id=50bdc461-ab51-4108-9e5c-58495ab5edeb duration_ms=52 + api_test.go:91: создан ok_user_327b0fdb id=926f8271-4f8e-4379-b69b-e424e83919d7 +2026/11/12 18:06:18 method=POST path=/api/v1/auth/sessions status=201 request_id=4483c457-abce-4d52-9d97-df7fe1ceed40 duration_ms=39 + api_test.go:92: сессия выпущена, длина токена=64 (значение не печатаем) +2026/11/12 18:06:18 method=POST path=/api/v1/chats status=201 request_id=5ee4d4df-80bf-4212-9b11-15a8beaa22d8 duration_ms=8 +2026/11/12 18:06:18 method=POST path=/api/v1/chats/85991ce8-09f4-48c6-80eb-171e80d344d4/messages status=400 request_id=788d8cb8-5474-470e-b39c-d7fce6962987 duration_ms=3 + api_test.go:99: status=400 body={"error":{"code":"invalid_request","message":"malformed json","request_id":"788d8cb8-5474-470e-b39c-d7fce6962987"}} +2026/11/12 18:06:18 method=POST path=/api/v1/chats/85991ce8-09f4-48c6-80eb-171e80d344d4/messages status=400 request_id=d4632ebb-a886-4338-8372-5d73e2239842 duration_ms=0 + api_test.go:99: status=400 body={"error":{"code":"invalid_request","message":"malformed json","request_id":"d4632ebb-a886-4338-8372-5d73e2239842"}} +2026/11/12 18:06:18 method=POST path=/api/v1/chats/85991ce8-09f4-48c6-80eb-171e80d344d4/messages status=400 request_id=09b6498f-3e15-49b7-9266-ecf84d2a7916 duration_ms=0 + api_test.go:106: status=400 body={"error":{"code":"invalid_request","message":"invalid text","request_id":"09b6498f-3e15-49b7-9266-ecf84d2a7916"}} +2026/11/12 18:06:18 method=POST path=/api/v1/users status=201 request_id=87a631af-6c30-46eb-a783-5b81d3db8d7e duration_ms=36 + api_test.go:111: создан outsider_24331385 id=225d868f-362a-41d4-996b-1881ccf6cd8a +2026/11/12 18:06:18 method=POST path=/api/v1/auth/sessions status=201 request_id=168ea6f0-a4b0-44fa-b272-3ca6fa92fdb8 duration_ms=35 + api_test.go:112: сессия выпущена, длина токена=64 (значение не печатаем) +2026/11/12 18:06:18 method=POST path=/api/v1/chats/85991ce8-09f4-48c6-80eb-171e80d344d4/messages status=404 request_id=d6eebb84-6115-4163-9d68-0a5f4870ac33 duration_ms=5 + api_test.go:114: status=404 body={"error":{"code":"not_found","message":"object not found","request_id":"d6eebb84-6115-4163-9d68-0a5f4870ac33"}} + api_test.go:118: ✓ валидация JSON, хвоста, пустого текста и чужого чата +--- PASS: TestMalformedJSONAndValidation (0.19s) +=== RUN TestMessageTextPreservedAndLengthOnOriginal + api_test.go:124: → пробелы по краям сохраняются; длина считается по исходному тексту +2026/11/12 18:06:18 method=POST path=/api/v1/users status=201 request_id=35882536-5698-47e4-aa4d-b26ca05eccf2 duration_ms=28 + api_test.go:125: создан text_user_b0b3691c id=4d721a90-d23e-4812-bc50-4b91b972f4a9 +2026/11/12 18:06:18 method=POST path=/api/v1/auth/sessions status=201 request_id=68fe42a9-aa1d-4219-89d0-0bea4485c691 duration_ms=52 + api_test.go:126: сессия выпущена, длина токена=64 (значение не печатаем) +2026/11/12 18:06:18 method=POST path=/api/v1/chats status=201 request_id=d2fdb0f8-f7e6-4a7a-906e-bd5a7575c658 duration_ms=73 +2026/11/12 18:06:18 method=POST path=/api/v1/chats/5af6de80-5d24-4e1c-85ba-6064483eee06/messages status=201 request_id=e87c5fb7-9da0-4db4-b3d3-5c2fde5a1f9c duration_ms=31 + api_test.go:133: status=201 body={"attachment_ids":[],"chat_id":"5af6de80-5d24-4e1c-85ba-6064483eee06","created_at":"2026-11-12T15:06:18.586Z","id":"fb22f748-419d-4e21-bad1-15eefd3541fc","sender_id":"4d721a90-d23e-4812-bc50-4b91b972f4a9","text":" строка\nс пробелами "} +2026/11/12 18:06:18 method=POST path=/api/v1/chats/5af6de80-5d24-4e1c-85ba-6064483eee06/messages status=400 request_id=fb0600ea-7684-4546-948c-758bd6de9fe7 duration_ms=0 + api_test.go:145: status=400 body={"error":{"code":"invalid_request","message":"invalid text","request_id":"fb0600ea-7684-4546-948c-758bd6de9fe7"}} + api_test.go:149: ✓ текст сохранён целиком, обход лимита через TrimSpace закрыт +--- PASS: TestMessageTextPreservedAndLengthOnOriginal (0.19s) +=== RUN TestSessionRejectsJSONBody + api_test.go:155: → POST /auth/sessions с телом должен быть 400 даже при верном Basic +2026/11/12 18:06:18 method=POST path=/api/v1/users status=201 request_id=fb41ef9f-6a7e-40d9-9a7b-1a6b999f146a duration_ms=33 + api_test.go:156: создан body_user_f034de4e id=34ffe3cc-0fad-43ef-9c71-167de51999db +2026/11/12 18:06:18 method=POST path=/api/v1/auth/sessions status=400 request_id=64964195-0966-4ef3-a09e-90cc2feddbe4 duration_ms=0 + api_test.go:160: status=400 body={"error":{"code":"invalid_request","message":"session create must not have a body","request_id":"64964195-0966-4ef3-a09e-90cc2feddbe4"}} + api_test.go:164: ✓ вход без JSON body +--- PASS: TestSessionRejectsJSONBody (0.04s) +=== RUN TestWrongPasswordLogoutAndIgnoredUserHeader + api_test.go:170: → неверный пароль, Basic на бизнес-методе, X-User-Id, logout +2026/11/12 18:06:18 method=POST path=/api/v1/users status=201 request_id=db2797ae-6acd-42c7-a935-5180d9f3f9c7 duration_ms=34 + api_test.go:171: создан auth_user_ceeda3df id=9a73b5de-ea1c-452d-a52a-ceada48a8bcb +2026/11/12 18:06:18 method=POST path=/api/v1/users status=201 request_id=4abdf37f-d666-4ffa-aca5-96358c777f19 duration_ms=35 + api_test.go:172: создан auth_other_029a2c01 id=84485afe-e12b-4811-abd5-6a323a4a11b0 +2026/11/12 18:06:18 method=POST path=/api/v1/auth/sessions status=401 request_id=561b7123-f836-4e1b-86e5-3202dd168c02 duration_ms=40 + api_test.go:177: status=401 body={"error":{"code":"unauthorized","message":"authentication required","request_id":"561b7123-f836-4e1b-86e5-3202dd168c02"}} +2026/11/12 18:06:18 method=POST path=/api/v1/auth/sessions status=201 request_id=ff0c1cd3-6893-498b-8a85-1ddcfaea198e duration_ms=37 + api_test.go:182: сессия выпущена, длина токена=64 (значение не печатаем) +2026/11/12 18:06:18 method=GET path=/api/v1/users/me status=401 request_id=fa44aa80-40c9-460c-8318-fbcdd6127ef5 duration_ms=0 + api_test.go:186: status=401 body={"error":{"code":"unauthorized","message":"authentication required","request_id":"fa44aa80-40c9-460c-8318-fbcdd6127ef5"}} +2026/11/12 18:06:18 method=GET path=/api/v1/users/me status=401 request_id=f76f04a1-a69e-4d4a-b6d9-6cefff6de333 duration_ms=0 + api_test.go:192: status=401 body={"error":{"code":"unauthorized","message":"authentication required","request_id":"f76f04a1-a69e-4d4a-b6d9-6cefff6de333"}} +2026/11/12 18:06:18 method=GET path=/api/v1/users/me status=200 request_id=57b7a10b-bcce-4f69-b4eb-84d7dbfe333d duration_ms=5 + api_test.go:201: status=200 body={"created_at":"2026-11-12T15:06:18.678Z","display_name":"Студент","id":"9a73b5de-ea1c-452d-a52a-ceada48a8bcb","username":"auth_user_ceeda3df"} +2026/11/12 18:06:18 method=DELETE path=/api/v1/auth/sessions/current status=204 request_id=ed4b6610-d10e-4f08-933c-0da4c63e1db5 duration_ms=1 + api_test.go:207: logout status=204 +2026/11/12 18:06:18 method=GET path=/api/v1/users/me status=401 request_id=c51a2f42-758f-4a9d-9995-28d1fb1bd0e1 duration_ms=0 +2026/11/12 18:06:18 method=DELETE path=/api/v1/auth/sessions/current status=401 request_id=800ac6d0-86dd-46eb-baab-24c6f45c4993 duration_ms=1 + api_test.go:219: ✓ пароль, заголовки и отзыв сессии +--- PASS: TestWrongPasswordLogoutAndIgnoredUserHeader (0.17s) +=== RUN TestSessionExpiry + api_test.go:225: → SESSION_TTL=2s: тот же токен после паузы должен стать 401, TTL рестартом API не продлевается +2026/11/12 18:06:18 method=POST path=/api/v1/users status=201 request_id=bcb1c96f-65df-40a8-bdac-94727a1cb041 duration_ms=35 + api_test.go:226: создан ttl_user_325de81d id=484fbed9-09a4-4166-8f92-4f69a1fc1689 +2026/11/12 18:06:18 method=POST path=/api/v1/auth/sessions status=201 request_id=2088a908-3d83-4faf-bd43-84ee481db9cb duration_ms=25 + api_test.go:227: сессия выпущена, длина токена=64 (значение не печатаем) +2026/11/12 18:06:21 method=GET path=/api/v1/users/me status=401 request_id=0ba4365e-3bb4-4f55-886d-31698f49dc34 duration_ms=2 + api_test.go:230: status=401 body={"error":{"code":"unauthorized","message":"authentication required","request_id":"0ba4365e-3bb4-4f55-886d-31698f49dc34"}} + api_test.go:234: ✓ истёкшая сессия отклонена +--- PASS: TestSessionExpiry (2.58s) +=== RUN TestDuplicateUsernameRace + api_test.go:241: → 8 параллельных регистраций username=race_6ed0656c +2026/11/12 18:06:21 method=POST path=/api/v1/users status=201 request_id=5402c615-aab8-4b07-a21d-46946f22785b duration_ms=83 +2026/11/12 18:06:21 method=POST path=/api/v1/users status=409 request_id=e860a8f7-fd25-4c0d-abd9-31b50a08db96 duration_ms=85 +2026/11/12 18:06:21 method=POST path=/api/v1/users status=409 request_id=dd17c014-02b9-4fb0-9481-7d4d3d840193 duration_ms=90 +2026/11/12 18:06:21 method=POST path=/api/v1/users status=409 request_id=9a31aa27-6548-4e36-8505-5ec0334ebd76 duration_ms=92 +2026/11/12 18:06:21 method=POST path=/api/v1/users status=409 request_id=d841c975-d516-4b63-b699-661a26ec2175 duration_ms=90 +2026/11/12 18:06:21 method=POST path=/api/v1/users status=409 request_id=c2bf9c03-a386-4ad2-a49d-2749a633654a duration_ms=94 +2026/11/12 18:06:21 method=POST path=/api/v1/users status=409 request_id=cf6d6c68-1668-4991-ab7b-ae77cc69aa47 duration_ms=98 +2026/11/12 18:06:21 method=POST path=/api/v1/users status=409 request_id=025c3a4d-21c6-48ff-89e6-03e6b8f69f62 duration_ms=99 + api_test.go:266: created=1 conflict=7 + api_test.go:270: ✓ UNIQUE username выдержал гонку +--- PASS: TestDuplicateUsernameRace (0.12s) +=== RUN TestChatCreateRollsBack +2026/11/12 18:06:21 method=POST path=/api/v1/users status=201 request_id=57132288-7a2a-49e0-91d3-1b3b2ad8ad5b duration_ms=35 + api_test.go:276: создан roll_user_55538244 id=510834db-6bf3-44ce-9c3e-bc5a3654ffd7 +2026/11/12 18:06:21 method=POST path=/api/v1/auth/sessions status=201 request_id=2d0bfbec-5b2f-435d-90f4-183fed112d83 duration_ms=30 + api_test.go:277: сессия выпущена, длина токена=64 (значение не печатаем) + api_test.go:280: → создание чата с несуществующим участником должно откатиться, title=rollback-2162ebe8-7d02-467d-a256-23b859075201 +2026/11/12 18:06:21 method=POST path=/api/v1/chats status=400 request_id=21f2b61a-aa7d-4c17-9190-50a2070ca522 duration_ms=5 + api_test.go:283: status=400 body={"error":{"code":"invalid_request","message":"unknown member","request_id":"21f2b61a-aa7d-4c17-9190-50a2070ca522"}} + api_test.go:291: строк chats с этим title после ошибки: 0 + api_test.go:295: ✓ транзакция создания чата откатилась +--- PASS: TestChatCreateRollsBack (0.08s) +=== RUN TestPaginationPages + api_test.go:301: → три сообщения, две страницы limit=2, затем последняя +2026/11/12 18:06:21 method=POST path=/api/v1/users status=201 request_id=0a6b83e1-0421-4574-811e-4da75eb44a3f duration_ms=26 + api_test.go:302: создан page_user_0c9c3ed1 id=687fac60-91d1-42d3-84fc-4a49378c362c +2026/11/12 18:06:21 method=POST path=/api/v1/auth/sessions status=201 request_id=646ba194-eeb2-45d8-b535-6afed48abf8d duration_ms=25 + api_test.go:303: сессия выпущена, длина токена=64 (значение не печатаем) +2026/11/12 18:06:21 method=POST path=/api/v1/chats status=201 request_id=a3495c84-c564-4d1c-af3b-374ac0c843e7 duration_ms=2 +2026/11/12 18:06:21 method=POST path=/api/v1/chats/019d7107-c47f-4cc7-9341-3a71f44a1eac/messages status=201 request_id=4cff46d2-34c6-4473-93f0-7473eaccda7a duration_ms=7 +2026/11/12 18:06:21 method=POST path=/api/v1/chats/019d7107-c47f-4cc7-9341-3a71f44a1eac/messages status=201 request_id=54dcd688-e45f-405f-a849-4c9b540c558b duration_ms=2 +2026/11/12 18:06:21 method=POST path=/api/v1/chats/019d7107-c47f-4cc7-9341-3a71f44a1eac/messages status=201 request_id=4b4c1969-acd3-4785-b0a3-a7e1fc6f3d9b duration_ms=2 +2026/11/12 18:06:21 method=GET path=/api/v1/chats/019d7107-c47f-4cc7-9341-3a71f44a1eac/messages status=200 request_id=490be6d4-e04b-49d2-8f10-d45cbbc013df duration_ms=2 + api_test.go:313: status=200 body={"items":[{"attachment_ids":[],"chat_id":"019d7107-c47f-4cc7-9341-3a71f44a1eac","created_at":"2026-11-12T15:06:21.645Z","id":"6e24502d-79d4-4f6c-be3d-ba3480fb7608","sender_id":"687fac60-91d1-42d3-84fc-4a49378c362c","text":"раз"},{"attachment_ids":[],"chat_id":"019d7107-c47f-4cc7-9341-3a71f44a1eac","created_at":"2026-11-12T15:06:21.649Z","id":"88e5a96b-e468-473a-9c4b-92e6ba4f4329","sender_id":"6... +2026/11/12 18:06:21 method=GET path=/api/v1/chats/019d7107-c47f-4cc7-9341-3a71f44a1eac/messages status=200 request_id=1c4e85bf-6325-48e0-81a3-cbd6daeed98b duration_ms=1 + api_test.go:321: status=200 body={"items":[{"attachment_ids":[],"chat_id":"019d7107-c47f-4cc7-9341-3a71f44a1eac","created_at":"2026-11-12T15:06:21.652Z","id":"0f9e9233-a586-4204-a5d8-71afd9d314be","sender_id":"687fac60-91d1-42d3-84fc-4a49378c362c","text":"три"}],"next_cursor":null} + api_test.go:327: ✓ keyset обошёл историю без зависания cursor +--- PASS: TestPaginationPages (0.07s) +=== RUN TestRedisDownIsNotAnonymous + api_test.go:331: → закрытый клиент Redis: вход и Bearer дают 503, а не 200 от анонима +2026/11/12 18:06:21 method=POST path=/api/v1/users status=201 request_id=beeadeed-af0b-47b4-b0e4-7e6421f1f496 duration_ms=25 + api_test.go:343: создан redis_down_bef9688c id=89644793-1ece-4a4a-a601-a29a56d1a4d8 +2026/11/12 18:06:21 method=POST path=/api/v1/auth/sessions status=503 request_id=9762b8fa-434c-445c-823f-0acc5704f4be duration_ms=24 + api_test.go:347: status=503 body={"error":{"code":"unavailable","message":"dependency unavailable","request_id":"9762b8fa-434c-445c-823f-0acc5704f4be"}} +2026/11/12 18:06:21 method=GET path=/api/v1/users/me status=503 request_id=badd3986-bcb8-41c6-a0ba-618ffac05af1 duration_ms=0 + api_test.go:354: status=503 body={"error":{"code":"unavailable","message":"dependency unavailable","request_id":"badd3986-bcb8-41c6-a0ba-618ffac05af1"}} + api_test.go:358: ✓ сбой Redis не стал анонимным доступом +--- PASS: TestRedisDownIsNotAnonymous (0.05s) +=== RUN TestPostgresDownIsNotAnonymous + api_test.go:362: → закрытый пул PostgreSQL: ready/me/login дают 503, без тела пользователя +2026/11/12 18:06:21 method=POST path=/api/v1/users status=201 request_id=a021c019-6aa8-41ce-a7d5-42b488cb43d9 duration_ms=26 + api_test.go:365: создан pg_down_2520dcae id=20f9f190-3b5a-4ff7-ae47-2897b7f18ea4 +2026/11/12 18:06:21 method=POST path=/api/v1/auth/sessions status=201 request_id=fea01055-7d40-4324-9aed-ca5fc456adfd duration_ms=26 + api_test.go:366: сессия выпущена, длина токена=64 (значение не печатаем) +2026/11/12 18:06:21 method=GET path=/health/ready status=503 request_id=32035732-a60e-4d41-b9df-0f94ff733650 duration_ms=0 + api_test.go:387: status=503 body={"error":{"code":"unavailable","message":"dependency unavailable","request_id":"32035732-a60e-4d41-b9df-0f94ff733650"}} +2026/11/12 18:06:21 method=GET path=/api/v1/users/me status=503 request_id=0193b1dd-49dd-4647-9a44-5cdca3091ed0 duration_ms=0 + api_test.go:394: status=503 body={"error":{"code":"unavailable","message":"dependency unavailable","request_id":"0193b1dd-49dd-4647-9a44-5cdca3091ed0"}} +2026/11/12 18:06:21 method=POST path=/api/v1/auth/sessions status=503 request_id=f6fbf5d1-9f1c-452d-951a-3ee09749f6cd duration_ms=0 + api_test.go:401: status=503 body={"error":{"code":"unavailable","message":"dependency unavailable","request_id":"f6fbf5d1-9f1c-452d-951a-3ee09749f6cd"}} + api_test.go:405: ✓ сбой PostgreSQL не стал анонимным доступом +--- PASS: TestPostgresDownIsNotAnonymous (0.09s) +=== RUN TestIdempotencyReplayAndConflict + api_test.go:412: → повтор того же Idempotency-Key возвращает то же сообщение; другой body — 409 +2026/11/12 18:06:21 method=POST path=/api/v1/users status=201 request_id=ba481c3a-d59e-4f1c-b109-273d9cf8f376 duration_ms=27 + api_test.go:413: создан idem_user_5e962710 id=3b9c80ec-af5b-4fcb-8612-df5adf66e7b0 +2026/11/12 18:06:21 method=POST path=/api/v1/auth/sessions status=201 request_id=c7504a83-5f6a-40fd-a47a-6f7a5e611f88 duration_ms=25 + api_test.go:414: сессия выпущена, длина токена=64 (значение не печатаем) +2026/11/12 18:06:21 method=POST path=/api/v1/chats status=201 request_id=6fecfacf-5cf0-42fc-8ae6-cd3499868da5 duration_ms=2 +2026/11/12 18:06:21 method=POST path=/api/v1/chats/bf42b0ff-2d72-4083-888f-d46b0d4bba6b/messages status=201 request_id=ebb16497-7dc3-4b1d-a352-2ec117b1c588 duration_ms=2 + api_test.go:422: status=201 body={"attachment_ids":[],"chat_id":"bf42b0ff-2d72-4083-888f-d46b0d4bba6b","created_at":"2026-11-12T15:06:21.861Z","id":"76a0823b-deb0-4087-820f-6d8d5d955062","sender_id":"3b9c80ec-af5b-4fcb-8612-df5adf66e7b0","text":"один раз"} +2026/11/12 18:06:21 method=POST path=/api/v1/chats/bf42b0ff-2d72-4083-888f-d46b0d4bba6b/messages status=201 request_id=3b737653-a43e-4b6b-901b-80de4724d31b duration_ms=1 + api_test.go:428: status=201 body={"attachment_ids":[],"chat_id":"bf42b0ff-2d72-4083-888f-d46b0d4bba6b","created_at":"2026-11-12T15:06:21.861Z","id":"76a0823b-deb0-4087-820f-6d8d5d955062","sender_id":"3b9c80ec-af5b-4fcb-8612-df5adf66e7b0","text":"один раз"} +2026/11/12 18:06:21 method=POST path=/api/v1/chats/bf42b0ff-2d72-4083-888f-d46b0d4bba6b/messages status=409 request_id=5be94615-9308-4e4f-9b02-04ca003f6e16 duration_ms=1 + api_test.go:437: status=409 body={"error":{"code":"conflict","message":"idempotency key reused with different body","request_id":"5be94615-9308-4e4f-9b02-04ca003f6e16"}} + api_test.go:441: ✓ replay и conflict по Idempotency-Key +--- PASS: TestIdempotencyReplayAndConflict (0.06s) +=== RUN TestIdempotencyKeyRequiredAndConcurrent + api_test.go:447: → нет ключа → 400; 8 параллельных POST с одним ключом → ровно одно сообщение +2026/11/12 18:06:21 method=POST path=/api/v1/users status=201 request_id=2ab93c5e-9ffd-4260-a5dc-b04f6ae5660b duration_ms=25 + api_test.go:448: создан idem_race_f0f21140 id=53f6a58c-3ce4-410c-bf6d-088084ebf4c2 +2026/11/12 18:06:21 method=POST path=/api/v1/auth/sessions status=201 request_id=45711062-65f8-4aac-8563-4790fdc89a3b duration_ms=25 + api_test.go:449: сессия выпущена, длина токена=64 (значение не печатаем) +2026/11/12 18:06:21 method=POST path=/api/v1/chats status=201 request_id=2df6eccd-30af-4e17-80e0-4b52fb771e18 duration_ms=4 +2026/11/12 18:06:21 method=POST path=/api/v1/chats/041835f4-09c3-49eb-aedb-a561d3ce7e92/messages status=400 request_id=26e381a2-4bc0-4eee-b668-9816b9ad2839 duration_ms=0 + api_test.go:467: status=400 body={"error":{"code":"invalid_request","message":"invalid or missing Idempotency-Key","request_id":"26e381a2-4bc0-4eee-b668-9816b9ad2839"}} +2026/11/12 18:06:21 method=POST path=/api/v1/chats/041835f4-09c3-49eb-aedb-a561d3ce7e92/messages status=201 request_id=88713995-6e81-4644-8e0b-7b4c394ca9af duration_ms=7 +2026/11/12 18:06:21 method=POST path=/api/v1/chats/041835f4-09c3-49eb-aedb-a561d3ce7e92/messages status=201 request_id=baaee528-b553-4633-b6f4-2f09abb4b01a duration_ms=10 +2026/11/12 18:06:21 method=POST path=/api/v1/chats/041835f4-09c3-49eb-aedb-a561d3ce7e92/messages status=201 request_id=e283a5e9-ce51-44b2-9a7c-23edbb41b3ba duration_ms=12 +2026/11/12 18:06:21 method=POST path=/api/v1/chats/041835f4-09c3-49eb-aedb-a561d3ce7e92/messages status=201 request_id=68be161c-a944-4b64-ad56-8f14c3068b6e duration_ms=14 +2026/11/12 18:06:21 method=POST path=/api/v1/chats/041835f4-09c3-49eb-aedb-a561d3ce7e92/messages status=201 request_id=45041db6-7633-438e-8e6e-3657e6a4a915 duration_ms=16 +2026/11/12 18:06:21 method=POST path=/api/v1/chats/041835f4-09c3-49eb-aedb-a561d3ce7e92/messages status=201 request_id=191a3c6d-26ac-4359-88e7-d04bf59e7367 duration_ms=17 +2026/11/12 18:06:21 method=POST path=/api/v1/chats/041835f4-09c3-49eb-aedb-a561d3ce7e92/messages status=201 request_id=2c81685c-5ee7-4d2e-81ab-5153014708d3 duration_ms=19 +2026/11/12 18:06:21 method=POST path=/api/v1/chats/041835f4-09c3-49eb-aedb-a561d3ce7e92/messages status=201 request_id=5f23de1d-3352-4864-a40d-fa959abd420e duration_ms=20 + api_test.go:499: unique message ids=1 + api_test.go:503: ✓ ключ обязателен; конкурентный повтор не плодит дубли +--- PASS: TestIdempotencyKeyRequiredAndConcurrent (0.08s) +=== RUN TestInstanceIDHeaderPresent + api_test.go:509: → каждый ответ содержит непустой X-Instance-Id + api_test.go:511: status=200 body={"status":"ok"} + api_test.go:515: ✓ X-Instance-Id=test-instance +--- PASS: TestInstanceIDHeaderPresent (0.00s) +=== RUN TestAttachmentUploadDownloadAndACL + attachments_test.go:38: → upload PNG → 201 ready → download checksum; посторонний — 404 +2026/11/12 18:06:21 method=POST path=/api/v1/users status=201 request_id=50e4a1af-fd0c-4f79-8dda-70a15bb9acd4 duration_ms=28 + attachments_test.go:40: создан att_owner_26e19e85 id=2aaf31d8-5457-4aa8-97fd-5e30ab916418 +2026/11/12 18:06:22 method=POST path=/api/v1/auth/sessions status=201 request_id=c7bf2c56-6b37-46c0-b26a-9fdea9c650c2 duration_ms=27 + attachments_test.go:41: сессия выпущена, длина токена=64 (значение не печатаем) +2026/11/12 18:06:22 method=POST path=/api/v1/users status=201 request_id=a1edcb49-d0cd-40fa-af3a-0d67d0b2ea8b duration_ms=27 + attachments_test.go:42: создан att_stranger_bb876443 id=88bd447e-69a4-448f-96d2-f359e2bfdfe3 +2026/11/12 18:06:22 method=POST path=/api/v1/auth/sessions status=201 request_id=2249a833-a589-425a-aab2-76eb560ae04d duration_ms=27 + attachments_test.go:43: сессия выпущена, длина токена=64 (значение не печатаем) +2026/11/12 18:06:22 method=POST path=/api/v1/chats status=201 request_id=f46c6061-855f-4113-afc6-1c5735e5f0d1 duration_ms=5 +2026/11/12 18:06:22 method=POST path=/api/v1/chats/0dacdbe6-5b95-41e8-817d-6b31549a20c9/attachments status=201 request_id=c74261b2-25cc-4995-a15e-8dff9f19f456 duration_ms=3 +2026/11/12 18:06:22 method=GET path=/api/v1/attachments/867bc3f8-3656-4138-a787-b5fc8fc85498 status=200 request_id=210ea277-a957-43d8-a45b-529cafc1ecd0 duration_ms=1 + attachments_test.go:50: status=200 body={"chat_id":"0dacdbe6-5b95-41e8-817d-6b31549a20c9","content_type":"image/png","created_at":"2026-11-12T15:06:22.067Z","error_code":null,"filename":"pic.png","id":"867bc3f8-3656-4138-a787-b5fc8fc85498","owner_id":"2aaf31d8-5457-4aa8-97fd-5e30ab916418","sha256":"2e9b06dc65a4dec84a3eb3124553ec93ca27c78221e64ab2177d0f1412cfcb20","size_bytes":69,"status":"ready","updated_at":"2026-11-12T15:06:22.067Z","... +2026/11/12 18:06:22 method=GET path=/api/v1/attachments/867bc3f8-3656-4138-a787-b5fc8fc85498/content status=200 request_id=d52949e3-d49d-4cc6-a0ae-d406e07a4db1 duration_ms=0 +2026/11/12 18:06:22 method=GET path=/api/v1/attachments/867bc3f8-3656-4138-a787-b5fc8fc85498 status=404 request_id=1e7cf8e4-64dd-4542-a225-01ae04bbd5ae duration_ms=0 + attachments_test.go:74: status=404 body={"error":{"code":"not_found","message":"object not found","request_id":"1e7cf8e4-64dd-4542-a225-01ae04bbd5ae"}} +2026/11/12 18:06:22 method=GET path=/api/v1/attachments/867bc3f8-3656-4138-a787-b5fc8fc85498/content status=404 request_id=51e58b03-52c7-4ad1-b15f-56a49c443ec1 duration_ms=0 +2026/11/12 18:06:22 method=POST path=/api/v1/chats/0dacdbe6-5b95-41e8-817d-6b31549a20c9/messages status=201 request_id=ae5b57bc-14b1-4d8a-a40d-a71cb4f71935 duration_ms=5 + attachments_test.go:86: status=201 body={"attachment_ids":["867bc3f8-3656-4138-a787-b5fc8fc85498"],"chat_id":"0dacdbe6-5b95-41e8-817d-6b31549a20c9","created_at":"2026-11-12T15:06:22.074Z","id":"0ea80b9c-c870-4e74-a23a-2a3b804970af","sender_id":"2aaf31d8-5457-4aa8-97fd-5e30ab916418","text":"с файлом"} + attachments_test.go:95: ✓ upload/download/ACL и message.attachment_ids +--- PASS: TestAttachmentUploadDownloadAndACL (0.13s) +=== RUN TestAttachmentRejectsBadInput + attachments_test.go:102: → битый PNG, подмена MIME, опасный filename, чужой чат → 4xx не 500 +2026/11/12 18:06:22 method=POST path=/api/v1/users status=201 request_id=4c3e8cba-a49e-417b-8a4d-da66dc3cdf18 duration_ms=28 + attachments_test.go:104: создан att_bad_21539b6c id=f5e5ea5c-5c89-4aba-8393-1d418136d0d7 +2026/11/12 18:06:22 method=POST path=/api/v1/auth/sessions status=201 request_id=db8cea49-9800-450d-8c80-cd85f21fef4c duration_ms=27 + attachments_test.go:105: сессия выпущена, длина токена=64 (значение не печатаем) +2026/11/12 18:06:22 method=POST path=/api/v1/chats status=201 request_id=c37b00b8-95e8-466b-b0bb-c90397b4913c duration_ms=5 +2026/11/12 18:06:22 method=POST path=/api/v1/chats/b88e5748-ce97-4b19-a045-fe10fbf88af3/attachments status=400 request_id=791df656-1869-4832-8e16-d145f3e12568 duration_ms=1 + attachments_test.go:109: status=400 body={"error":{"code":"invalid_request","message":"invalid filename","request_id":"791df656-1869-4832-8e16-d145f3e12568"}} +2026/11/12 18:06:22 method=POST path=/api/v1/chats/b88e5748-ce97-4b19-a045-fe10fbf88af3/attachments status=415 request_id=f8d9fdcc-524a-4c81-a08d-b72803745bdc duration_ms=3 + attachments_test.go:115: status=415 body={"error":{"code":"unsupported_media_type","message":"invalid or unsupported image","request_id":"f8d9fdcc-524a-4c81-a08d-b72803745bdc"}} +2026/11/12 18:06:22 method=POST path=/api/v1/chats/b88e5748-ce97-4b19-a045-fe10fbf88af3/attachments status=415 request_id=6da7b2bc-c552-4885-bd4c-dd888b3a6a4b duration_ms=1 + attachments_test.go:121: status=415 body={"error":{"code":"unsupported_media_type","message":"invalid or unsupported image","request_id":"6da7b2bc-c552-4885-bd4c-dd888b3a6a4b"}} +2026/11/12 18:06:22 method=POST path=/api/v1/chats/b88e5748-ce97-4b19-a045-fe10fbf88af3/attachments status=413 request_id=55dfe90c-9de2-4a34-942d-5e29abb6a181 duration_ms=1 + attachments_test.go:138: status=413 body={"error":{"code":"payload_too_large","message":"file is too large","request_id":"55dfe90c-9de2-4a34-942d-5e29abb6a181"}} +2026/11/12 18:06:22 method=POST path=/api/v1/users status=201 request_id=c4d7a58a-254b-49c8-954d-f69c37badb7b duration_ms=28 + attachments_test.go:143: создан att_other_f29f128d id=3186c693-b42d-4040-82b2-aa46cdf35c10 +2026/11/12 18:06:22 method=POST path=/api/v1/auth/sessions status=201 request_id=17898378-42f5-4bac-a69e-d3673070bc82 duration_ms=28 + attachments_test.go:144: сессия выпущена, длина токена=64 (значение не печатаем) +2026/11/12 18:06:22 method=POST path=/api/v1/chats status=201 request_id=106a6135-6033-49d0-a3af-cdffa50138f3 duration_ms=2 +2026/11/12 18:06:22 method=POST path=/api/v1/chats/48d9e9da-2e02-4663-941b-b1e8fe8f587a/attachments status=404 request_id=a1749a57-1189-4505-b6c7-26726bab488b duration_ms=0 + attachments_test.go:147: status=404 body={"error":{"code":"not_found","message":"object not found","request_id":"a1749a57-1189-4505-b6c7-26726bab488b"}} +2026/11/12 18:06:22 method=POST path=/api/v1/chats/48d9e9da-2e02-4663-941b-b1e8fe8f587a/attachments status=201 request_id=75b83de8-96a1-4b6d-88f3-8c47d1d337d8 duration_ms=1 +2026/11/12 18:06:22 method=POST path=/api/v1/chats/b88e5748-ce97-4b19-a045-fe10fbf88af3/messages status=404 request_id=9202daed-c840-4dad-aaad-57c641b5b60e duration_ms=1 + attachments_test.go:156: status=404 body={"error":{"code":"not_found","message":"object not found","request_id":"9202daed-c840-4dad-aaad-57c641b5b60e"}} + attachments_test.go:160: ✓ негативные сценарии вложений → клиентские 4xx +--- PASS: TestAttachmentRejectsBadInput (0.14s) +=== RUN TestAttachmentS3DownIs503 + attachments_test.go:168: → S3 недоступен: ready и upload → 503 +2026/11/12 18:06:22 method=GET path=/health/ready status=503 request_id=3d89fdba-9a9c-4584-a4c6-3f80db705e0a duration_ms=0 + attachments_test.go:171: status=503 body={"error":{"code":"unavailable","message":"dependency unavailable","request_id":"3d89fdba-9a9c-4584-a4c6-3f80db705e0a"}} +2026/11/12 18:06:22 method=POST path=/api/v1/users status=201 request_id=4e83fd55-0b6c-4d86-9af6-f2fa3c2bdbf2 duration_ms=25 + attachments_test.go:176: создан s3_down_e2a7e91a id=54340923-2d7d-4a06-b2e2-ffaa7d8740bd +2026/11/12 18:06:22 method=POST path=/api/v1/auth/sessions status=201 request_id=0e4ab943-38bb-4a14-a97f-63fbb3290957 duration_ms=25 + attachments_test.go:177: сессия выпущена, длина токена=64 (значение не печатаем) +2026/11/12 18:06:22 method=POST path=/api/v1/chats status=201 request_id=71b90d66-3e07-4558-b3a8-9e7b53dd2692 duration_ms=3 +2026/11/12 18:06:22 request_id=f6f288b3-755c-458e-8d82-ab72fafb64f8 s3_unavailable +2026/11/12 18:06:22 method=POST path=/api/v1/chats/83ee260c-6369-47be-a18e-7fc24884dc4e/attachments status=503 request_id=f6f288b3-755c-458e-8d82-ab72fafb64f8 duration_ms=1 + attachments_test.go:180: status=503 body={"error":{"code":"unavailable","message":"dependency unavailable","request_id":"f6f288b3-755c-458e-8d82-ab72fafb64f8"}} + attachments_test.go:184: ✓ падение S3 → 503 +--- PASS: TestAttachmentS3DownIs503 (0.06s) +PASS +ok mtusi2026lab4/student-tests 4.450s diff --git a/go.mod b/go.mod new file mode 100644 index 00000000..b39d2f7f --- /dev/null +++ b/go.mod @@ -0,0 +1,54 @@ +module mtusi2026lab4 + +go 1.24.0 + +require ( + github.com/google/uuid v1.6.0 + github.com/jackc/pgx/v5 v5.7.4 + github.com/minio/madmin-go/v3 v3.0.107 + github.com/minio/minio-go/v7 v7.0.90 + github.com/redis/go-redis/v9 v9.7.3 + golang.org/x/crypto v0.37.0 +) + +require ( + github.com/cespare/xxhash/v2 v2.3.0 // indirect + github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect + github.com/dustin/go-humanize v1.0.1 // indirect + github.com/go-ini/ini v1.67.0 // indirect + github.com/go-ole/go-ole v1.3.0 // indirect + github.com/goccy/go-json v0.10.5 // indirect + github.com/golang-jwt/jwt/v4 v4.5.2 // indirect + github.com/golang/protobuf v1.5.4 // 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 + github.com/klauspost/compress v1.18.0 // indirect + github.com/klauspost/cpuid/v2 v2.2.10 // indirect + github.com/lufia/plan9stats v0.0.0-20250317134145-8bc96cf8fc35 // indirect + github.com/matttproud/golang_protobuf_extensions v1.0.4 // indirect + github.com/minio/crc64nvme v1.0.1 // indirect + github.com/minio/md5-simd v1.1.2 // indirect + github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect + github.com/philhofer/fwd v1.1.3-0.20240916144458-20a13a1f6b7c // indirect + github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 // indirect + github.com/prometheus/client_model v0.6.2 // indirect + github.com/prometheus/common v0.63.0 // indirect + github.com/prometheus/procfs v0.16.0 // indirect + github.com/prometheus/prom2json v1.4.2 // indirect + github.com/prometheus/prometheus v0.303.0 // indirect + github.com/rs/xid v1.6.0 // indirect + github.com/safchain/ethtool v0.5.10 // indirect + github.com/secure-io/sio-go v0.3.1 // indirect + github.com/shirou/gopsutil/v3 v3.24.5 // indirect + github.com/shoenig/go-m1cpu v0.1.6 // indirect + github.com/tinylib/msgp v1.2.5 // indirect + github.com/tklauser/go-sysconf v0.3.15 // indirect + github.com/tklauser/numcpus v0.10.0 // indirect + github.com/yusufpapurcu/wmi v1.2.4 // indirect + golang.org/x/net v0.39.0 // indirect + golang.org/x/sync v0.13.0 // indirect + golang.org/x/sys v0.32.0 // indirect + golang.org/x/text v0.24.0 // indirect + google.golang.org/protobuf v1.36.6 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 00000000..96afdc89 --- /dev/null +++ b/go.sum @@ -0,0 +1,128 @@ +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.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= +github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= +github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/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/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= +github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= +github.com/go-ini/ini v1.67.0 h1:z6ZrTEZqSWOTyH2FlglNbNgARyHG8oLW9gMELqKr06A= +github.com/go-ini/ini v1.67.0/go.mod h1:ByCAeIL28uOIIG0E3PJtZPDL8WnHpFKFOtgjp+3Ies8= +github.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0= +github.com/go-ole/go-ole v1.3.0 h1:Dt6ye7+vXGIKZ7Xtk4s6/xVdGDQynvom7xCFEdWr6uE= +github.com/go-ole/go-ole v1.3.0/go.mod h1:5LS6F96DhAwUc7C+1HLexzMXY1xGRSryjyPPKW6zv78= +github.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4= +github.com/goccy/go-json v0.10.5/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M= +github.com/golang-jwt/jwt/v4 v4.5.2 h1:YtQM7lnr8iZ+j5q71MGKkNw9Mn7AjHM68uc9g5fXeUI= +github.com/golang-jwt/jwt/v4 v4.5.2/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w39/MY0Ch0= +github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= +github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= +github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= +github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= +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/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo= +github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ= +github.com/klauspost/cpuid/v2 v2.0.1/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= +github.com/klauspost/cpuid/v2 v2.2.10 h1:tBs3QSyvjDyFTq3uoc/9xFpCuOsJQFNPiAhYdw2skhE= +github.com/klauspost/cpuid/v2 v2.2.10/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0= +github.com/lufia/plan9stats v0.0.0-20250317134145-8bc96cf8fc35 h1:PpXWgLPs+Fqr325bN2FD2ISlRRztXibcX6e8f5FR5Dc= +github.com/lufia/plan9stats v0.0.0-20250317134145-8bc96cf8fc35/go.mod h1:autxFIvghDt3jPTLoqZ9OZ7s9qTGNAWmYCjVFWPX/zg= +github.com/matttproud/golang_protobuf_extensions v1.0.4 h1:mmDVorXM7PCGKw94cs5zkfA9PSy5pEvNWRP0ET0TIVo= +github.com/matttproud/golang_protobuf_extensions v1.0.4/go.mod h1:BSXmuO+STAnVfrANrmjBb36TMTDstsz7MSK+HVaYKv4= +github.com/minio/crc64nvme v1.0.1 h1:DHQPrYPdqK7jQG/Ls5CTBZWeex/2FMS3G5XGkycuFrY= +github.com/minio/crc64nvme v1.0.1/go.mod h1:eVfm2fAzLlxMdUGc0EEBGSMmPwmXD5XiNRpnu9J3bvg= +github.com/minio/madmin-go/v3 v3.0.107 h1:MZNlPmJWsbxIvgIACSxmMq4T3PXK9/wil3pMSaTz5HI= +github.com/minio/madmin-go/v3 v3.0.107/go.mod h1:WOe2kYmYl1OIlY2DSRHVQ8j1v4OItARQ6jGyQqcCud8= +github.com/minio/md5-simd v1.1.2 h1:Gdi1DZK69+ZVMoNHRXJyNcxrMA4dSxoYHZSQbirFg34= +github.com/minio/md5-simd v1.1.2/go.mod h1:MzdKDxYpY2BT9XQFocsiZf/NKVtR7nkE4RoEpN+20RM= +github.com/minio/minio-go/v7 v7.0.90 h1:TmSj1083wtAD0kEYTx7a5pFsv3iRYMsOJ6A4crjA1lE= +github.com/minio/minio-go/v7 v7.0.90/go.mod h1:uvMUcGrpgeSAAI6+sD3818508nUyMULw94j2Nxku/Go= +github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA= +github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= +github.com/philhofer/fwd v1.1.3-0.20240916144458-20a13a1f6b7c h1:dAMKvw0MlJT1GshSTtih8C2gDs04w8dReiOGXrGLNoY= +github.com/philhofer/fwd v1.1.3-0.20240916144458-20a13a1f6b7c/go.mod h1:RqIHx9QI14HlwKwm98g9Re5prTQ6LdeRQn+gXJFxsJM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= +github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 h1:o4JXh1EVt9k/+g42oCprj/FisM4qX9L3sZB3upGN2ZU= +github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55/go.mod h1:OmDBASR4679mdNQnz2pUhc2G8CO2JrUAVFDRBDP/hJE= +github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk= +github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE= +github.com/prometheus/common v0.63.0 h1:YR/EIY1o3mEFP/kZCD7iDMnLPlGyuU2Gb3HIcXnA98k= +github.com/prometheus/common v0.63.0/go.mod h1:VVFF/fBIoToEnWRVkYoXEkq3R3paCoxG9PXP74SnV18= +github.com/prometheus/procfs v0.16.0 h1:xh6oHhKwnOJKMYiYBDWmkHqQPyiY40sny36Cmx2bbsM= +github.com/prometheus/procfs v0.16.0/go.mod h1:8veyXUu3nGP7oaCxhX6yeaM5u4stL2FeMXnCqhDthZg= +github.com/prometheus/prom2json v1.4.2 h1:PxCTM+Whqi/eykO1MKsEL0p/zMpxp9ybpsmdFamw6po= +github.com/prometheus/prom2json v1.4.2/go.mod h1:zuvPm7u3epZSbXPWHny6G+o8ETgu6eAK3oPr6yFkRWE= +github.com/prometheus/prometheus v0.303.0 h1:wsNNsbd4EycMCphYnTmNY9JASBVbp7NWwJna857cGpA= +github.com/prometheus/prometheus v0.303.0/go.mod h1:8PMRi+Fk1WzopMDeb0/6hbNs9nV6zgySkU/zds5Lu3o= +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/rs/xid v1.6.0 h1:fV591PaemRlL6JfRxGDEPl69wICngIQ3shQtzfy2gxU= +github.com/rs/xid v1.6.0/go.mod h1:7XoLgs4eV+QndskICGsho+ADou8ySMSjJKDIan90Nz0= +github.com/safchain/ethtool v0.5.10 h1:Im294gZtuf4pSGJRAOGKaASNi3wMeFaGaWuSaomedpc= +github.com/safchain/ethtool v0.5.10/go.mod h1:w9jh2Lx7YBR4UwzLkzCmWl85UY0W2uZdd7/DckVE5+c= +github.com/secure-io/sio-go v0.3.1 h1:dNvY9awjabXTYGsTF1PiCySl9Ltofk9GA3VdWlo7rRc= +github.com/secure-io/sio-go v0.3.1/go.mod h1:+xbkjDzPjwh4Axd07pRKSNriS9SCiYksWnZqdnfpQxs= +github.com/shirou/gopsutil/v3 v3.24.5 h1:i0t8kL+kQTvpAYToeuiVk3TgDeKOFioZO3Ztz/iZ9pI= +github.com/shirou/gopsutil/v3 v3.24.5/go.mod h1:bsoOS1aStSs9ErQ1WWfxllSeS1K5D+U30r2NfcubMVk= +github.com/shoenig/go-m1cpu v0.1.6 h1:nxdKQNcEB6vzgA2E2bvzKIYRuNj7XNJ4S/aRSwKzFtM= +github.com/shoenig/go-m1cpu v0.1.6/go.mod h1:1JJMcUBvfNwpq05QDQVAnx3gUHr9IYF7GNg9SUEw2VQ= +github.com/shoenig/test v0.6.4 h1:kVTaSd7WLz5WZ2IaoM0RSzRsUD+m8wRR+5qvntpn4LU= +github.com/shoenig/test v0.6.4/go.mod h1:byHiCGXqrVaflBLAMq/srcZIHynQPQgeyvkvXnjqq0k= +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.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= +github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= +github.com/tinylib/msgp v1.2.5 h1:WeQg1whrXRFiZusidTQqzETkRpGjFjcIhW6uqWH09po= +github.com/tinylib/msgp v1.2.5/go.mod h1:ykjzy2wzgrlvpDCRc4LA8UXy6D8bzMSuAF3WD57Gok0= +github.com/tklauser/go-sysconf v0.3.15 h1:VE89k0criAymJ/Os65CSn1IXaol+1wrsFHEB8Ol49K4= +github.com/tklauser/go-sysconf v0.3.15/go.mod h1:Dmjwr6tYFIseJw7a3dRLJfsHAMXZ3nEnL/aZY+0IuI4= +github.com/tklauser/numcpus v0.10.0 h1:18njr6LDBk1zuna922MgdjQuJFjrdppsZG60sHGfjso= +github.com/tklauser/numcpus v0.10.0/go.mod h1:BiTKazU708GQTYF4mB+cmlpT2Is1gLk7XVuEeem8LsQ= +github.com/yusufpapurcu/wmi v1.2.4 h1:zFUKzehAFReQwLys1b/iSMl+JQGSCSjtVqQn9bBrPo0= +github.com/yusufpapurcu/wmi v1.2.4/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20200302210943-78000ba7a073/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.37.0 h1:kJNSjF/Xp7kU0iB2Z+9viTPMW4EqqsrywMXLJOOsXSE= +golang.org/x/crypto v0.37.0/go.mod h1:vg+k43peMZ0pUMhYmVAWysMK35e6ioLh3wB8ZCAfbVc= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.39.0 h1:ZCu7HMWDxpXpaiKdhzIfaltL9Lp31x/3fCP11bc6/fY= +golang.org/x/net v0.39.0/go.mod h1:X7NRbYVEA+ewNkCNyJ513WmMdQ3BineSwVtN2zD/d+E= +golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.13.0 h1:AauUjRAJ9OSnvULf/ARrrVywoJDy0YS2AwQ98I37610= +golang.org/x/sync v0.13.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200302150141-5c8b2ff67527/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20201204225414-ed752295db88/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.29.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/sys v0.32.0 h1:s77OFDvIQeibCmezSnk/q6iAfkdiQaJi4VzroCFrN20= +golang.org/x/sys v0.32.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.24.0 h1:dd5Bzh4yt5KYA8f9CJHCP4FB4D51c2c6JvN37xJJkJ0= +golang.org/x/text v0.24.0/go.mod h1:L8rBsPeo2pSS+xqN0d5u2ikmjtmoJbDBT1b7nHvFCdU= +google.golang.org/protobuf v1.36.6 h1:z1NpPI8ku2WgiWnf+t9wTPsn6eP1L7ksHUlkfLvd9xY= +google.golang.org/protobuf v1.36.6/go.mod h1:jduwjTPXsFjZGTmRluh+L6NjiWu7pchiJ2/5YcXBHnY= +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/README.md b/infra/README.md index 5a39e862..8a3e5840 100644 --- a/infra/README.md +++ b/infra/README.md @@ -1,7 +1,8 @@ -# Инфраструктура студента +# Инфраструктура lab4 -Здесь разместите конфигурации выбранных сервисов; основную топологию — в корневом compose.yaml/stack.yaml. `compose.example.yaml` — только worksheet ролей и намеренно не запускается. `contracts/infrastructure.json` задаёт минимальные роли, не готовые образы/пароли. - -В REPORT.md сопоставьте роль → service name → версия/digest → health/readiness → volume → сеть/порт → способ передачи credentials. Приведите bootstrap (schema, bucket, broker topology, а с lab6 provisioning) и безопасное повторение этих команд. - -Приложение строится из исходников. Не используйте заранее существующий образ преподавательского сервера вместо своей реализации. Restart hook перезапускает все соответствующие stores с volumes; failover hook останавливает только заданную API-реплику. +- `haproxy/haproxy.cfg` — LB перед API-репликами (lab3). +- MinIO: образ `ghcr.io/coollabsio/minio:RELEASE.2025-10-15T17-29-55Z` (официальные + `minio/minio` с Docker Hub сняты в 2026; community-сборка того же RELEASE). +- Bootstrap bucket/app-user: бинарь `/s3bootstrap` в образе API (minio-go + madmin), + без зависимости от снятого `minio/mc`. Политика — только List/Get/Put/Delete на + `messenger-attachments`. Консоль MinIO (`:9001`) **не публикуется**. 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/infra/minio/app-policy.json b/infra/minio/app-policy.json new file mode 100644 index 00000000..4469eb80 --- /dev/null +++ b/infra/minio/app-policy.json @@ -0,0 +1,17 @@ +{ + "Version": "2012-10-17", + "Statement": [ + { + "Sid": "ListBucket", + "Effect": "Allow", + "Action": ["s3:ListBucket"], + "Resource": ["arn:aws:s3:::messenger-attachments"] + }, + { + "Sid": "ObjectRW", + "Effect": "Allow", + "Action": ["s3:GetObject", "s3:PutObject", "s3:DeleteObject"], + "Resource": ["arn:aws:s3:::messenger-attachments/*"] + } + ] +} diff --git a/infra/minio/bootstrap.sh b/infra/minio/bootstrap.sh new file mode 100755 index 00000000..c0e1e2e9 --- /dev/null +++ b/infra/minio/bootstrap.sh @@ -0,0 +1,32 @@ +#!/bin/sh +# Идемпотентный bootstrap приватного bucket и app-пользователя с ограниченной политикой. +# Root-ключи только здесь; API работает от S3_ACCESS_KEY_ID / S3_SECRET_ACCESS_KEY. +set -eu + +echo "waiting for minio..." +i=0 +until mc alias set local "http://${MINIO_ENDPOINT}" "${MINIO_ROOT_USER}" "${MINIO_ROOT_PASSWORD}" >/dev/null 2>&1; do + i=$((i + 1)) + if [ "$i" -gt 60 ]; then + echo "minio not ready" >&2 + exit 1 + fi + sleep 1 +done + +mc mb -p "local/${S3_BUCKET}" || true +mc anonymous set none "local/${S3_BUCKET}" + +# Пользователь приложения: повторный add не обязан быть успешен. +if ! mc admin user info local "${S3_ACCESS_KEY_ID}" >/dev/null 2>&1; then + mc admin user add local "${S3_ACCESS_KEY_ID}" "${S3_SECRET_ACCESS_KEY}" +fi +# Политика: create падает, если уже есть — это ок. +mc admin policy create local app-attachments /policy.json 2>/dev/null || \ + mc admin policy add local app-attachments /policy.json 2>/dev/null || true +mc admin policy attach local app-attachments --user "${S3_ACCESS_KEY_ID}" 2>/dev/null || \ + mc admin policy set local app-attachments user="${S3_ACCESS_KEY_ID}" 2>/dev/null || true + +echo "bucket=${S3_BUCKET} private=yes app_user=${S3_ACCESS_KEY_ID}" +mc anonymous get "local/${S3_BUCKET}" || true +echo "bootstrap done" diff --git a/internal/api/attachments.go b/internal/api/attachments.go new file mode 100644 index 00000000..fdea4ea9 --- /dev/null +++ b/internal/api/attachments.go @@ -0,0 +1,448 @@ +package api + +// Вложения lab4: загрузка, метаданные, скачивание. +// +// Загрузка (POST /chats/{id}/attachments?filename=...) идёт строго по шагам, и каждый шаг +// отсекает запрос как можно раньше и дешевле: +// +// 1. Bearer-аутентификация (requireUser), затем членство в чате: посторонний получает 404; +// 2. filename: 1–255 code points, без «/», «\», NUL и управляющих символов — иначе 400; +// 3. заявленный Content-Type — только image/png или image/jpeg, иначе 415; +// 4. тело копируется в спул (временный файл, при его отказе — память) с одновременным SHA-256 +// и жёстким лимитом MaxUploadBytes+1: больше лимита — 413. Тело не буферизуется целиком +// в куче через ReadAll, поэтому пик RAM на загрузку — буфер копирования, а не размер файла; +// 5. тип по содержимому (http.DetectContentType) обязан совпасть с заявленным, иначе 415 (подмена MIME); +// 6. размеры берутся из заголовка PNG/JPEG БЕЗ декодирования пикселей; больше +// MaxImagePixels — 413. Это делается до любой «распаковки»: bomb 60000×60000 весит килобайты; +// 7. дешёвая структурная проверка (PNG: CRC всех чанков и IEND, JPEG: EOI) ловит обрезанные +// и повреждённые файлы — 415; +// 8. PUT в S3 по серверному ключу originals/, затем INSERT метаданных. Только после +// обоих шагов — 201. Если INSERT не удался, объект удаляется сразу, а при отказе удаления +// его подберёт reconciler (cmd/reconcile) после grace period. +// +// До шага 8 в S3 ничего не пишется, поэтому оборванная загрузка клиента не оставляет объектов. + +import ( + "bufio" + "bytes" + "context" + "crypto/sha256" + "encoding/binary" + "encoding/hex" + "errors" + "hash/crc32" + "image" + _ "image/jpeg" // регистрирует декодер JPEG для image.DecodeConfig + "io" + "log" + "mime" + "net/http" + "os" + "strconv" + "strings" + "time" + "unicode" + "unicode/utf8" + + "github.com/google/uuid" + + "mtusi2026lab4/internal/blob" + "mtusi2026lab4/internal/store" +) + +const ( + maxMessageAttachments = 10 + maxFilenameRunes = 255 + // После превышения лимита дочитываем (и выбрасываем) не больше этого объёма: + // клиент успевает получить 413, а не «connection reset» посреди своей отправки. + drainOnOverflow = 64 << 20 +) + +var ( + errBadImage = errors.New("not a valid png/jpeg image") + errTooManyPixels = errors.New("image has too many pixels") + errTooLarge = errors.New("upload exceeds size limit") +) + +func (s *Server) handleUploadAttachment(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 + } + uid := userFrom(r) + if err := s.Store.EnsureChatMember(r.Context(), chatID, uid); err != nil { + s.writeStoreErr(w, r, err, http.StatusNotFound, "not_found", "object not found") + return + } + + filename := r.URL.Query().Get("filename") + if !validFilename(filename) { + writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid filename") + return + } + declared, ok := declaredImageType(r.Header.Get("Content-Type")) + if !ok { + writeError(w, r, http.StatusUnsupportedMediaType, "unsupported_media_type", "only image/png and image/jpeg are accepted") + return + } + // Клиент заранее заявил размер сильно больше лимита — не читаем ни байта. + if r.ContentLength > s.MaxUploadBytes+drainOnOverflow { + writeError(w, r, http.StatusRequestEntityTooLarge, "payload_too_large", "file is too large") + return + } + + sp, err := spoolBody(r.Body, s.MaxUploadBytes) + if err != nil { + switch { + case errors.Is(err, errTooLarge): + writeError(w, r, http.StatusRequestEntityTooLarge, "payload_too_large", "file is too large") + default: + // Обрыв чтения тела или таймаут клиента. Ничего не записано ни в S3, ни в БД. + writeError(w, r, http.StatusBadRequest, "invalid_request", "could not read request body") + } + return + } + defer sp.Close() + + if err := inspectImage(sp.reader(), sp.size, declared, s.MaxImagePixels); err != nil { + switch { + case errors.Is(err, errTooManyPixels): + writeError(w, r, http.StatusRequestEntityTooLarge, "payload_too_large", "image has too many pixels") + default: + writeError(w, r, http.StatusUnsupportedMediaType, "unsupported_media_type", "invalid or unsupported image") + } + return + } + + id := uuid.New() + att := &store.Attachment{ + ID: id, + ChatID: chatID, + OwnerID: uid, + Filename: filename, + ContentType: declared, + SizeBytes: sp.size, + SHA256: sp.sum, + ObjectKey: blob.KeyPrefix + id.String(), + } + + // 1) S3. Тело отдаём как ReadSeeker: minio-go шлёт один PUT без буферизации в памяти. + if err := s.Blob.Put(r.Context(), att.ObjectKey, sp.reader(), sp.size, declared); err != nil { + s.writeBlobErr(w, r, err) + return + } + // 2) PostgreSQL. Ошибка здесь оставила бы объект без строки — убираем его сразу. + if err := s.Store.CreateAttachment(r.Context(), att); err != nil { + s.compensateOrphan(r, att.ObjectKey) + s.writeStoreErr(w, r, err, http.StatusNotFound, "not_found", "object not found") + return + } + writeJSON(w, http.StatusCreated, attachmentDTO(att)) +} + +// compensateOrphan удаляет объект, для которого не удалось записать метаданные. +// Контекст отвязан от запроса: клиент мог отключиться, а чистить всё равно нужно. +// Если и удаление не удалось (S3 мигнул), объект останется до reconciler — это допустимо. +func (s *Server) compensateOrphan(r *http.Request, key string) { + ctx, cancel := context.WithTimeout(context.WithoutCancel(r.Context()), 5*time.Second) + defer cancel() + if err := s.Blob.Delete(ctx, key); err != nil { + log.Printf("request_id=%s orphan_cleanup_failed key=%s (reconciler will remove after grace)", requestID(r), key) + } +} + +func (s *Server) handleGetAttachment(w http.ResponseWriter, r *http.Request) { + att, ok := s.loadAttachment(w, r) + if !ok { + return + } + writeJSON(w, http.StatusOK, attachmentDTO(att)) +} + +// handleDownloadAttachment отдаёт оригинал побайтно через API, без редиректа на S3: +// приватный bucket сам по себе не заменяет проверку членства в чате. +func (s *Server) handleDownloadAttachment(w http.ResponseWriter, r *http.Request) { + att, ok := s.loadAttachment(w, r) + if !ok { + return + } + // variant по умолчанию original. В lab4 вариантов нет (variants=[]), значит любой + // другой — «отсутствующий вариант ready-объекта», то есть 404. + if v := r.URL.Query().Get("variant"); v != "" && v != "original" { + writeError(w, r, http.StatusNotFound, "not_found", "object not found") + return + } + switch att.Status { + case "ready": + default: + writeError(w, r, http.StatusConflict, "conflict", "attachment is not ready") + return + } + rc, err := s.Blob.Get(r.Context(), att.ObjectKey) + if err != nil { + if errors.Is(err, blob.ErrNotFound) { + // Строка есть, объекта нет — несогласованность, её чинит reconciler. + log.Printf("request_id=%s attachment_object_missing id=%s", requestID(r), att.ID) + writeError(w, r, http.StatusNotFound, "not_found", "object not found") + return + } + s.writeBlobErr(w, r, err) + return + } + defer rc.Close() + h := w.Header() + h.Set("Content-Type", att.ContentType) + h.Set("Content-Length", strconv.FormatInt(att.SizeBytes, 10)) + h.Set("X-Content-Type-Options", "nosniff") + h.Set("Cache-Control", "private, no-store") + w.WriteHeader(http.StatusOK) + if _, err := io.Copy(w, rc); err != nil { + // Заголовки уже ушли; клиент увидит обрыв. В лог — без деталей S3. + log.Printf("request_id=%s attachment_stream_error id=%s", requestID(r), att.ID) + } +} + +// loadAttachment разбирает {attachment_id} и проверяет членство в чате вложения. +func (s *Server) loadAttachment(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.GetAttachment(r.Context(), id, userFrom(r)) + if err != nil { + s.writeStoreErr(w, r, err, http.StatusNotFound, "not_found", "object not found") + return nil, false + } + return att, true +} + +// writeBlobErr: недоступный S3 — 503, остальное — 500. Текст ошибки клиенту не уходит. +func (s *Server) writeBlobErr(w http.ResponseWriter, r *http.Request, err error) { + if errors.Is(err, blob.ErrUnavailable) { + log.Printf("request_id=%s s3_unavailable", requestID(r)) + writeError(w, r, http.StatusServiceUnavailable, "unavailable", "dependency unavailable") + return + } + log.Printf("request_id=%s blob_error_type=%T", requestID(r), err) + writeError(w, r, http.StatusInternalServerError, "internal_error", "internal error") +} + +func attachmentDTO(a *store.Attachment) map[string]any { + var errCode any + if a.ErrorCode != nil { + errCode = *a.ErrorCode + } + 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, + "variants": []any{}, + "error_code": errCode, + "created_at": formatTime(a.CreatedAt), + "updated_at": formatTime(a.UpdatedAt), + } +} + +// validFilename: 1–255 code points, валидный UTF-8, не «пустой» после TrimSpace. +// «/», «\», NUL и управляющие символы запрещены: имя только отображается и никогда не +// становится путём или ключом S3. «.» и «..» отвергаются как заведомо опасные. +func validFilename(name string) bool { + if !utf8.ValidString(name) || strings.TrimSpace(name) == "" { + return false + } + if n := utf8.RuneCountInString(name); n < 1 || n > maxFilenameRunes { + return false + } + if name == "." || name == ".." { + return false + } + for _, c := range name { + if c == '/' || c == '\\' || c == 0 || unicode.IsControl(c) { + return false + } + } + return true +} + +// declaredImageType возвращает заявленный Content-Type без параметров, если он разрешён. +func declaredImageType(header string) (string, bool) { + mt, _, err := mime.ParseMediaType(header) + if err != nil { + return "", false + } + switch mt { + case "image/png", "image/jpeg": + return mt, true + } + return "", false +} + +// spooled — принятое тело: размер, SHA-256 и произвольный доступ для проверок и PUT. +type spooled struct { + ra io.ReaderAt + size int64 + sum string + cleanup func() +} + +func (s *spooled) reader() *io.SectionReader { return io.NewSectionReader(s.ra, 0, s.size) } +func (s *spooled) Close() { s.cleanup() } + +// spoolBody читает тело не больше max байт. Временный файл защищает кучу от 10 одновременных +// загрузок по 10 MiB; если /tmp недоступен, откатываемся на память (всё равно ограниченную max). +func spoolBody(body io.Reader, max int64) (*spooled, error) { + h := sha256.New() + f, ferr := os.CreateTemp("", "upload-*") + var ( + dst io.Writer + buf *bytes.Buffer + cleanup = func() {} + ) + if ferr == nil { + cleanup = func() { _ = f.Close(); _ = os.Remove(f.Name()) } + dst = io.MultiWriter(f, h) + } else { + buf = &bytes.Buffer{} + dst = io.MultiWriter(buf, h) + } + n, err := io.Copy(dst, io.LimitReader(body, max+1)) + if err != nil { + cleanup() + return nil, err + } + if n > max { + cleanup() + _, _ = io.CopyN(io.Discard, body, drainOnOverflow) + return nil, errTooLarge + } + sp := &spooled{size: n, sum: hex.EncodeToString(h.Sum(nil)), cleanup: cleanup} + if f != nil && ferr == nil { + sp.ra = f + } else { + sp.ra = bytes.NewReader(buf.Bytes()) + } + return sp, nil +} + +// inspectImage проверяет содержимое. Порядок важен: тип → размеры из заголовка (лимит +// пикселей до любой распаковки) → структура файла. +func inspectImage(sr *io.SectionReader, size int64, declared string, maxPixels int64) error { + head := make([]byte, 512) + n, _ := sr.ReadAt(head, 0) + detected := "" + if n > 0 { + detected = http.DetectContentType(head[:n]) + } + if size < 1 || (detected != "image/png" && detected != "image/jpeg") || detected != declared { + return errBadImage + } + + var w, h int64 + switch detected { + case "image/png": + // IHDR всегда первый чанк: 8 байт сигнатуры, 4 длина, 4 тип, затем width/height. + // Читаем сами: image/png.DecodeConfig отвергает файл с битым CRC раньше, чем + // мы успели бы честно ответить «слишком много пикселей». + if n < 24 || string(head[12:16]) != "IHDR" || binary.BigEndian.Uint32(head[8:12]) != 13 { + return errBadImage + } + w = int64(binary.BigEndian.Uint32(head[16:20])) + h = int64(binary.BigEndian.Uint32(head[20:24])) + case "image/jpeg": + cfg, _, err := image.DecodeConfig(io.NewSectionReader(sr, 0, size)) + if err != nil { + return errBadImage + } + w, h = int64(cfg.Width), int64(cfg.Height) + } + if w < 1 || h < 1 { + return errBadImage + } + if w*h > maxPixels { + return errTooManyPixels + } + + if detected == "image/png" { + return verifyPNG(io.NewSectionReader(sr, 0, size), size) + } + return verifyJPEGTail(sr, size) +} + +// verifyPNG обходит чанки и проверяет их CRC без декомпрессии IDAT: обрезанный или +// испорченный PNG отвергается за один линейный проход по файлу. +func verifyPNG(r io.Reader, size int64) error { + br := bufio.NewReaderSize(r, 64<<10) + if _, err := br.Discard(8); err != nil { // сигнатура уже проверена DetectContentType + return errBadImage + } + consumed := int64(8) + var ( + hdr [8]byte + crcBuf [4]byte + first = true + sawIDAT bool + sawIEND bool + crcHasher = crc32.NewIEEE() + ) + for !sawIEND { + if _, err := io.ReadFull(br, hdr[:]); err != nil { + return errBadImage + } + length := int64(binary.BigEndian.Uint32(hdr[0:4])) + ctype := string(hdr[4:8]) + if length > size-consumed-12 { + return errBadImage + } + if first && ctype != "IHDR" { + return errBadImage + } + first = false + crcHasher.Reset() + _, _ = crcHasher.Write(hdr[4:8]) + if _, err := io.CopyN(crcHasher, br, length); err != nil { + return errBadImage + } + if _, err := io.ReadFull(br, crcBuf[:]); err != nil { + return errBadImage + } + if crcHasher.Sum32() != binary.BigEndian.Uint32(crcBuf[:]) { + return errBadImage + } + consumed += 12 + length + switch ctype { + case "IDAT": + sawIDAT = true + case "IEND": + sawIEND = true + } + } + // Данные после IEND — признак полиглота или склейки файлов, не принимаем. + if !sawIDAT || consumed != size { + return errBadImage + } + return nil +} + +// verifyJPEGTail требует маркер конца изображения EOI (FF D9) в хвосте файла. +// Допускаются нулевые/мусорные байты выравнивания после него (до 1 KiB). +func verifyJPEGTail(sr *io.SectionReader, size int64) error { + tailLen := int64(1024) + if size < tailLen { + tailLen = size + } + tail := make([]byte, tailLen) + if _, err := sr.ReadAt(tail, size-tailLen); err != nil && !errors.Is(err, io.EOF) { + return errBadImage + } + if bytes.LastIndex(tail, []byte{0xFF, 0xD9}) < 0 { + return errBadImage + } + return nil +} diff --git a/internal/api/server.go b/internal/api/server.go new file mode 100644 index 00000000..ef0857bb --- /dev/null +++ b/internal/api/server.go @@ -0,0 +1,780 @@ +// Package api — HTTP-слой lab4 (поверх lab3: LB, идемпотентность, сессии в Redis). +// +// Порядок обработки запроса: +// 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: +// без них нельзя честно принять запись или узнать, кто делает запрос. +// +// POST сообщения требует Idempotency-Key; результат хранится в общей БД, а не в памяти реплики. +// +// Вложения (attachments.go): сырой PNG/JPEG в теле POST, байты в приватном S3, метаданные в +// PostgreSQL. Скачивание — только через этот API, без редиректа на S3. +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" + + "mtusi2026lab4/internal/blob" + "mtusi2026lab4/internal/session" + "mtusi2026lab4/internal/store" +) + +type ctxKey int + +const ( + userKey ctxKey = iota + tokenKey + requestIDKey +) + +const ( + challengeBasic = `Basic realm="messenger", charset="UTF-8"` + challengeBearer = `Bearer realm="messenger"` +) + +// Лимиты вложений по контракту lab4. +const ( + DefaultMaxUploadBytes int64 = 10 << 20 // 10 MiB = 10 485 760 + DefaultMaxImagePixels int64 = 40_000_000 +) + +// BlobStore — то, что API требует от S3-клиента. *blob.Client его реализует; +// интерфейс нужен, чтобы тест мог подставить недоступное хранилище. +type BlobStore interface { + Put(ctx context.Context, key string, r io.Reader, size int64, contentType string) error + Get(ctx context.Context, key string) (io.ReadCloser, error) + Delete(ctx context.Context, key string) error + Ping(ctx context.Context) error +} + +var _ BlobStore = (*blob.Client)(nil) + +// Server связывает HTTP с PostgreSQL, Redis и S3. +type Server struct { + Store *store.Store + Sessions *session.Store + Blob BlobStore + InstanceID string + // Лимиты загрузки. По умолчанию контрактные; main.go может только ужесточить. + MaxUploadBytes int64 + MaxImagePixels int64 + ready atomic.Bool +} + +// New помечает процесс готовым. Реальная зависимость всё равно проверяется в /health/ready. +// instanceID попадает в X-Instance-Id каждого ответа и стабилен на жизнь процесса. +func New(st *store.Store, sessions *session.Store, bl BlobStore, instanceID string) *Server { + s := &Server{ + Store: st, Sessions: sessions, Blob: bl, InstanceID: instanceID, + MaxUploadBytes: DefaultMaxUploadBytes, + MaxImagePixels: DefaultMaxImagePixels, + } + 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)) + 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 + } + // S3 — обязательная зависимость синхронного пути (загрузка и скачивание вложений). + if err := s.Store.Ping(r.Context()); err != nil || s.Sessions.Ping(r.Context()) != nil || + s.Blob.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 и [] равны для хэша. + if len(body.AttachmentIDs) > maxMessageAttachments { + writeError(w, r, http.StatusBadRequest, "invalid_request", "too many attachments") + 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, но только если вложений нет: + // text="" с хотя бы одним вложением разрешён контрактом lab4. + // Пробелы по краям сохраняются как есть, иначе «пробел + 4000 букв» проходил бы как 4000. + if utf8.RuneCountInString(body.Text) > 4000 || + (len(attachmentIDs) == 0 && strings.TrimSpace(body.Text) == "") { + 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.ErrNotReady) { + 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 { + // Всегда массив, даже пустой: клиент lab3 без вложений видит [] (контракт 1.4.0). + att := make([]string, len(m.AttachmentIDs)) + for i, id := range m.AttachmentIDs { + att[i] = id.String() + } + return map[string]any{ + "id": m.ID.String(), + "chat_id": m.ChatID.String(), + "sender_id": m.SenderID.String(), + "text": m.Text, + "attachment_ids": att, + "created_at": formatTime(m.CreatedAt), + } +} + +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/blob/memory.go b/internal/blob/memory.go new file mode 100644 index 00000000..86780877 --- /dev/null +++ b/internal/blob/memory.go @@ -0,0 +1,162 @@ +package blob + +import ( + "bytes" + "context" + "io" + "sync" + "time" +) + +// Memory — in-memory BlobStore для student-tests без живого MinIO. +// Не для production: нет persistence между процессами. +type Memory struct { + mu sync.Mutex + objects map[string]memObj + down bool + bucketOK bool + now func() time.Time +} + +type memObj struct { + data []byte + modTime time.Time +} + +// NewMemory создаёт пустое хранилище с «живым» бакетом. +func NewMemory() *Memory { + return &Memory{ + objects: make(map[string]memObj), + bucketOK: true, + now: time.Now, + } +} + +// SetUnavailable имитирует падение S3 (Ping/Put/Get → ErrUnavailable). +func (m *Memory) SetUnavailable(v bool) { m.mu.Lock(); m.down = v; m.mu.Unlock() } + +func (m *Memory) Bucket() string { return "memory" } + +func (m *Memory) Ping(ctx context.Context) error { + select { + case <-ctx.Done(): + return ctx.Err() + default: + } + m.mu.Lock() + defer m.mu.Unlock() + if m.down || !m.bucketOK { + return ErrUnavailable + } + return nil +} + +func (m *Memory) Put(ctx context.Context, key string, r io.Reader, size int64, _ string) error { + select { + case <-ctx.Done(): + return ctx.Err() + default: + } + m.mu.Lock() + defer m.mu.Unlock() + if m.down { + return ErrUnavailable + } + data, err := io.ReadAll(io.LimitReader(r, size+1)) + if err != nil { + return err + } + if int64(len(data)) != size { + return ErrUnavailable + } + m.objects[key] = memObj{data: append([]byte(nil), data...), modTime: m.now()} + return nil +} + +func (m *Memory) Get(ctx context.Context, key string) (io.ReadCloser, error) { + select { + case <-ctx.Done(): + return nil, ctx.Err() + default: + } + m.mu.Lock() + defer m.mu.Unlock() + if m.down { + return nil, ErrUnavailable + } + o, ok := m.objects[key] + if !ok { + return nil, ErrNotFound + } + return io.NopCloser(bytes.NewReader(o.data)), nil +} + +func (m *Memory) Stat(ctx context.Context, key string) (ObjectInfo, error) { + select { + case <-ctx.Done(): + return ObjectInfo{}, ctx.Err() + default: + } + m.mu.Lock() + defer m.mu.Unlock() + if m.down { + return ObjectInfo{}, ErrUnavailable + } + o, ok := m.objects[key] + if !ok { + return ObjectInfo{}, ErrNotFound + } + return ObjectInfo{Key: key, Size: int64(len(o.data)), LastModified: o.modTime}, nil +} + +func (m *Memory) Delete(ctx context.Context, key string) error { + select { + case <-ctx.Done(): + return ctx.Err() + default: + } + m.mu.Lock() + defer m.mu.Unlock() + if m.down { + return ErrUnavailable + } + delete(m.objects, key) + return nil +} + +func (m *Memory) ListKeys(ctx context.Context, prefix string) ([]ObjectInfo, error) { + select { + case <-ctx.Done(): + return nil, ctx.Err() + default: + } + m.mu.Lock() + defer m.mu.Unlock() + if m.down { + return nil, ErrUnavailable + } + var out []ObjectInfo + for k, o := range m.objects { + if len(prefix) == 0 || (len(k) >= len(prefix) && k[:len(prefix)] == prefix) { + out = append(out, ObjectInfo{Key: k, Size: int64(len(o.data)), LastModified: o.modTime}) + } + } + return out, nil +} + +// Seed кладёт объект напрямую (для тестов reconciler). +func (m *Memory) Seed(key string, data []byte, modTime time.Time) { + m.mu.Lock() + defer m.mu.Unlock() + if modTime.IsZero() { + modTime = m.now() + } + m.objects[key] = memObj{data: append([]byte(nil), data...), modTime: modTime} +} + +var _ interface { + Put(ctx context.Context, key string, r io.Reader, size int64, contentType string) error + Get(ctx context.Context, key string) (io.ReadCloser, error) + Delete(ctx context.Context, key string) error + Ping(ctx context.Context) error +} = (*Memory)(nil) diff --git a/internal/blob/minio.go b/internal/blob/minio.go new file mode 100644 index 00000000..c1527bc8 --- /dev/null +++ b/internal/blob/minio.go @@ -0,0 +1,197 @@ +// Package blob — тонкая обёртка над MinIO (S3 API) для оригиналов вложений lab4. +// +// Байты файлов живут только здесь, а не в PostgreSQL и не на диске API-реплики. +// Ключ объекта назначает сервер (originals/); filename клиента в ключ не попадает. +// Bucket приватный: прямого доступа без подписи нет, скачивание идёт через авторизованный API. +// +// Ошибки сведены к двум классам, чтобы HTTP-слой не знал про minio-go: +// ErrNotFound — объекта нет (404/500 по контексту), ErrUnavailable — S3 недоступен (503). +package blob + +import ( + "context" + "errors" + "fmt" + "io" + "net" + "net/http" + "time" + + "github.com/minio/minio-go/v7" + "github.com/minio/minio-go/v7/pkg/credentials" +) + +// KeyPrefix — префикс ключей оригиналов. Reconciler обходит только его. +const KeyPrefix = "originals/" + +var ( + // ErrNotFound — такого объекта в бакете нет. + ErrNotFound = errors.New("blob: not found") + // ErrUnavailable — S3 не отвечает, отказал в доступе или вернул неожиданную ошибку. + ErrUnavailable = errors.New("blob: unavailable") +) + +// Config — параметры подключения. Секреты приходят из окружения/файла, в логи не попадают. +type Config struct { + Endpoint string // host:port без схемы, например minio:9000 + UseSSL bool + Region string + Bucket string + AccessKey string + SecretKey string +} + +// ObjectInfo — то, что reconciler и тесты знают об объекте. +type ObjectInfo struct { + Key string + Size int64 + LastModified time.Time +} + +// Client — клиент одного бакета. +type Client struct { + mc *minio.Client + bucket string +} + +// New создаёт клиента. Сеть не трогает: доступность проверяют Ping/EnsureBucket. +// +// Таймауты заданы явно. Без них connection refused ретраится minio-go десяток раз, +// и «S3 лежит» вместо быстрого 503 превращается в зависший запрос. +func New(cfg Config) (*Client, error) { + if cfg.Endpoint == "" || cfg.Bucket == "" { + return nil, fmt.Errorf("blob: endpoint and bucket are required") + } + tr := &http.Transport{ + Proxy: nil, + DialContext: (&net.Dialer{ + Timeout: 2 * time.Second, + KeepAlive: 30 * time.Second, + }).DialContext, + MaxIdleConns: 64, + MaxIdleConnsPerHost: 32, + IdleConnTimeout: 60 * time.Second, + TLSHandshakeTimeout: 3 * time.Second, + ResponseHeaderTimeout: 20 * time.Second, + } + mc, err := minio.New(cfg.Endpoint, &minio.Options{ + Creds: credentials.NewStaticV4(cfg.AccessKey, cfg.SecretKey, ""), + Secure: cfg.UseSSL, + Region: cfg.Region, + Transport: tr, + MaxRetries: 2, + }) + if err != nil { + return nil, fmt.Errorf("blob: init client: %w", err) + } + return &Client{mc: mc, bucket: cfg.Bucket}, nil +} + +// Bucket возвращает имя бакета (для логов и отчётов). +func (c *Client) Bucket() string { return c.bucket } + +// EnsureBucket создаёт бакет, если его нет. Идемпотентно. +// В Compose бакет создаёт minio-init с root-правами, а у app-пользователя прав на +// создание нет — функция нужна локальным тестам и ручному запуску на «голом» MinIO. +func (c *Client) EnsureBucket(ctx context.Context) error { + ok, err := c.mc.BucketExists(ctx, c.bucket) + if err != nil { + return classify(err) + } + if ok { + return nil + } + if err := c.mc.MakeBucket(ctx, c.bucket, minio.MakeBucketOptions{}); err != nil { + // Гонка двух инициализаторов: бакет уже создан соседом. + code := minio.ToErrorResponse(err).Code + if code == "BucketAlreadyOwnedByYou" || code == "BucketAlreadyExists" { + return nil + } + return classify(err) + } + return nil +} + +// Ping — проверка для /health/ready. Короткий таймаут: readiness не должна висеть. +func (c *Client) Ping(ctx context.Context) error { + ctx, cancel := context.WithTimeout(ctx, 500*time.Millisecond) + defer cancel() + ok, err := c.mc.BucketExists(ctx, c.bucket) + if err != nil || !ok { + return ErrUnavailable + } + return nil +} + +// Put кладёт объект известного размера. r должен уметь Seek (файл или bytes.Reader): +// тогда minio-go отправляет тело одним запросом без буферизации в памяти. +func (c *Client) Put(ctx context.Context, key string, r io.Reader, size int64, contentType string) error { + _, err := c.mc.PutObject(ctx, c.bucket, key, r, size, minio.PutObjectOptions{ + ContentType: contentType, + // Один PUT для файлов до лимита lab4 (10 MiB): multipart не нужен. + DisableMultipart: true, + }) + return classify(err) +} + +// Get открывает объект на чтение. Существование проверяется сразу (Stat), чтобы HTTP-слой +// успел вернуть 404/503 до отправки заголовков 200. +func (c *Client) Get(ctx context.Context, key string) (io.ReadCloser, error) { + obj, err := c.mc.GetObject(ctx, c.bucket, key, minio.GetObjectOptions{}) + if err != nil { + return nil, classify(err) + } + if _, err := obj.Stat(); err != nil { + _ = obj.Close() + return nil, classify(err) + } + return obj, nil +} + +// Stat возвращает метаданные объекта или ErrNotFound. +func (c *Client) Stat(ctx context.Context, key string) (ObjectInfo, error) { + st, err := c.mc.StatObject(ctx, c.bucket, key, minio.StatObjectOptions{}) + if err != nil { + return ObjectInfo{}, classify(err) + } + return ObjectInfo{Key: st.Key, Size: st.Size, LastModified: st.LastModified}, nil +} + +// Delete удаляет объект. Отсутствие объекта — не ошибка (S3 DELETE идемпотентен). +func (c *Client) Delete(ctx context.Context, key string) error { + err := c.mc.RemoveObject(ctx, c.bucket, key, minio.RemoveObjectOptions{}) + if err != nil && errors.Is(classify(err), ErrNotFound) { + return nil + } + return classify(err) +} + +// ListKeys возвращает все объекты с префиксом (рекурсивно). Для reconciler: +// стоимость обхода — O(число объектов), память — по записи на объект. +func (c *Client) ListKeys(ctx context.Context, prefix string) ([]ObjectInfo, error) { + var out []ObjectInfo + for o := range c.mc.ListObjects(ctx, c.bucket, minio.ListObjectsOptions{Prefix: prefix, Recursive: true}) { + if o.Err != nil { + return nil, classify(o.Err) + } + out = append(out, ObjectInfo{Key: o.Key, Size: o.Size, LastModified: o.LastModified}) + } + return out, nil +} + +// classify сводит ошибки minio-go к ErrNotFound/ErrUnavailable. Текст исходной ошибки +// наружу не возвращаем: в нём могут быть endpoint и имя бакета. +func classify(err error) error { + if err == nil { + return nil + } + switch minio.ToErrorResponse(err).Code { + case "NoSuchKey", "NotFound": + return ErrNotFound + } + if minio.ToErrorResponse(err).StatusCode == http.StatusNotFound && + minio.ToErrorResponse(err).Code != "NoSuchBucket" { + return ErrNotFound + } + return ErrUnavailable +} diff --git a/internal/config/config.go b/internal/config/config.go new file mode 100644 index 00000000..9caac942 --- /dev/null +++ b/internal/config/config.go @@ -0,0 +1,189 @@ +// Package config читает настройки процесса из окружения. +// +// Для lab4 добавлены S3_* и лимиты вложений. +// +// Прямые 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). Контракт: 10 MiB и 40 млн пикселей. + MaxUploadBytes int64 + MaxImagePixels int64 + // ReconcileGrace — минимальный возраст объекта/строки, прежде чем reconciler их тронет. + ReconcileGrace time.Duration +} + +// S3 — параметры подключения к S3-совместимому хранилищу. +type S3 struct { + Endpoint string + UseSSL bool + Region string + Bucket string + AccessKey string + SecretKey string +} + +// 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 + } + + 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 + } + + cfg.MaxUploadBytes, err = getenvInt64("MAX_UPLOAD_BYTES", 10485760, 1, 10485760) + if err != nil { + return cfg, err + } + cfg.MaxImagePixels, err = getenvInt64("MAX_IMAGE_PIXELS", 40000000, 1, 40000000) + if err != nil { + return cfg, err + } + graceSec, err := getenvInt64("S3_RECONCILE_GRACE_SECONDS", 60, 0, 7*24*3600) + if err != nil { + return cfg, err + } + cfg.ReconcileGrace = time.Duration(graceSec) * time.Second + + cfg.RunMigrations = truthy(os.Getenv("RUN_MIGRATIONS")) + return cfg, nil +} + +// LoadS3 читает настройки S3. Ключи — из S3_ACCESS_KEY_ID / S3_SECRET_ACCESS_KEY +// либо из файлов *_FILE. Пустые ключи — ошибка запуска API (migrate без S3 обходится). +func LoadS3() (S3, error) { + var ( + c S3 + err error + ) + c.Endpoint = getenv("S3_ENDPOINT", "minio:9000") + // Endpoint может прийти со схемой http:// — minio-go ждёт host:port. + c.Endpoint = strings.TrimPrefix(c.Endpoint, "https://") + c.Endpoint = strings.TrimPrefix(c.Endpoint, "http://") + c.Region = getenv("S3_REGION", "us-east-1") + c.Bucket = getenv("S3_BUCKET", "messenger-attachments") + c.UseSSL = truthy(os.Getenv("S3_USE_SSL")) + c.AccessKey, err = getenvOrFile("S3_ACCESS_KEY_ID", "S3_ACCESS_KEY_ID_FILE") + if err != nil { + return c, err + } + c.SecretKey, err = getenvOrFile("S3_SECRET_ACCESS_KEY", "S3_SECRET_ACCESS_KEY_FILE") + if err != nil { + return c, err + } + return c, 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 getenvInt64(key string, fallback, lo, hi int64) (int64, error) { + raw := strings.TrimSpace(os.Getenv(key)) + if raw == "" { + return fallback, nil + } + n, err := strconv.ParseInt(raw, 10, 64) + if err != nil || n < lo || n > hi { + return 0, fmt.Errorf("invalid %s", key) + } + return n, nil +} + +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/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..7dfde9d5 --- /dev/null +++ b/internal/store/attachments.go @@ -0,0 +1,209 @@ +// Вложения lab4: метаданные в PostgreSQL, байты в S3 (пакет blob). +// +// Согласованность двух хранилищ строится на порядке «сначала S3, потом БД»: +// 1. PUT объекта в S3 по серверному ключу; +// 2. INSERT строки attachments. +// +// Если PUT прошёл, а INSERT нет, остаётся объект без строки (orphan). API пытается удалить +// его сразу, а если не вышло, его удалит reconciler после grace period. Обратный порядок +// опаснее: строка без объекта отдавала бы клиенту 201 на файл, которого нет. +package store + +import ( + "context" + "errors" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5" +) + +// ErrNotReady — вложение существует в этом чате, но ещё не ready (в lab4 недостижимо, +// зарезервировано под асинхронную обработку lab5). +var ErrNotReady = errors.New("attachment not ready") + +// Attachment — метаданные оригинала. ObjectKey во внешний JSON не попадает. +type Attachment struct { + ID uuid.UUID + ChatID uuid.UUID + OwnerID uuid.UUID + Filename string + ContentType string + SizeBytes int64 + SHA256 string + ObjectKey string + Status string + ErrorCode *string + CreatedAt time.Time + UpdatedAt time.Time +} + +// CreateAttachment пишет метаданные после успешного PUT в S3. ID и ObjectKey задаёт вызывающий: +// ключ нужен до записи в БД. Членство в чате проверяется в самом INSERT — если автора уже +// нет в чате, строка не появится и вернётся ErrNotFound. +func (s *Store) CreateAttachment(ctx context.Context, a *Attachment) error { + ctx, cancel := context.WithTimeout(ctx, queryTimeout) + defer cancel() + now := nowUTC() + a.Status = "ready" + a.ErrorCode = nil + a.CreatedAt, a.UpdatedAt = now, now + 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, created_at, updated_at + ) + SELECT $1, $2, $3, $4, $5, $6, $7, $8, $9, NULL, $10, $10 + 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.CreatedAt) + if err != nil { + return mapWriteErr(err) + } + if tag.RowsAffected() != 1 { + return ErrNotFound + } + return nil +} + +// GetAttachment отдаёт вложение только участнику его чата. Чужому и несуществующему — +// одинаковый ErrNotFound (HTTP 404): наличие чужого файла не раскрываем. +func (s *Store) GetAttachment(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.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.CreatedAt, &a.UpdatedAt) + if errors.Is(err, pgx.ErrNoRows) { + return nil, ErrNotFound + } + if err != nil { + return nil, mapWriteErr(err) + } + return &a, nil +} + +// EnsureChatMember — публичная проверка «пользователь состоит в чате» (ErrNotFound иначе). +func (s *Store) EnsureChatMember(ctx context.Context, chatID, userID uuid.UUID) error { + return s.ensureMember(ctx, chatID, userID) +} + +// ListAttachmentIDsForMessage возвращает ID вложений сообщения в порядке запроса. +// Пустой результат — непустой срез нулевой длины, чтобы JSON дал [], а не null. +func (s *Store) ListAttachmentIDsForMessage(ctx context.Context, messageID uuid.UUID) ([]uuid.UUID, error) { + ctx, cancel := context.WithTimeout(ctx, queryTimeout) + defer cancel() + byMsg, err := attachmentIDsByMessage(ctx, s.pool, []uuid.UUID{messageID}) + if err != nil { + return nil, err + } + return byMsg[messageID], nil +} + +// querier — общая часть pgxpool.Pool и pgx.Tx. +type querier interface { + Query(ctx context.Context, sql string, args ...any) (pgx.Rows, error) +} + +// attachmentIDsByMessage — один запрос на страницу сообщений (без N+1). +// Все ключи результата заполнены: у сообщений без вложений значение — пустой срез. +// +// q — пул или транзакция: внутри транзакции запрос обязан идти по её соединению, иначе при +// маленьком пуле транзакция занимает соединение и ждёт второе. +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)) + if len(messageIDs) == 0 { + return out, nil + } + strs := make([]string, len(messageIDs)) + for i, id := range messageIDs { + out[id] = []uuid.UUID{} + strs[i] = id.String() + } + rows, err := q.Query(ctx, ` + SELECT message_id, attachment_id + FROM message_attachments + WHERE message_id = ANY($1::uuid[]) + ORDER BY message_id, position`, strs) + 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()) +} + +// AttachmentRef — строка attachments для reconciler: только то, что нужно для сверки с S3. +type AttachmentRef struct { + ID uuid.UUID + ObjectKey string + SizeBytes int64 + CreatedAt time.Time + Referenced bool // есть ли хотя бы одно сообщение со ссылкой на файл +} + +// ListAttachmentRefs — keyset-страница по id. Страницы небольшие: у соединения +// statement_timeout 3 с, один огромный SELECT на большой таблице под него не уложится. +func (s *Store) ListAttachmentRefs(ctx context.Context, after uuid.UUID, 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.size_bytes, a.created_at, + EXISTS (SELECT 1 FROM message_attachments ma WHERE ma.attachment_id = a.id) + FROM attachments a + WHERE a.id > $1 + ORDER BY a.id + LIMIT $2`, after, 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.SizeBytes, &r.CreatedAt, &r.Referenced); err != nil { + return nil, mapWriteErr(err) + } + out = append(out, r) + } + return out, mapWriteErr(rows.Err()) +} + +// AttachmentKeyExists — повторная проверка перед удалением orphan: между листингом S3 +// и удалением объект мог получить строку (загрузка закончилась). Это страховка поверх grace. +func (s *Store) AttachmentKeyExists(ctx context.Context, objectKey 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)`, objectKey).Scan(&ok) + return ok, mapWriteErr(err) +} + +// DeleteUnreferencedAttachment удаляет строку, только если на неё нет ссылок из сообщений. +// Условие NOT EXISTS в самом DELETE закрывает гонку «сообщение прикрепили, пока мы решали». +// Возвращает true, если строка была удалена. +func (s *Store) DeleteUnreferencedAttachment(ctx context.Context, id uuid.UUID) (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 NOT EXISTS (SELECT 1 FROM message_attachments ma WHERE ma.attachment_id = a.id)`, id) + 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..af091554 --- /dev/null +++ b/internal/store/migrations/003_attachments.sql @@ -0,0 +1,33 @@ +-- Вложения lab4. Метаданные в PostgreSQL, байты в приватном S3-bucket (MinIO). +-- Ключ объекта назначает сервер: originals/. +-- 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), + sha256 text NOT NULL CHECK (sha256 ~ '^[a-f0-9]{64}$'), + object_key text COLLATE "C" NOT NULL, + status text NOT NULL DEFAULT 'ready' CHECK (status IN ('ready')), + error_code text, + created_at timestamptz NOT NULL, + updated_at timestamptz NOT NULL, + CONSTRAINT attachments_object_key_unique UNIQUE (object_key) +); + +CREATE INDEX IF NOT EXISTS attachments_chat_idx ON attachments (chat_id); + +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/store.go b/internal/store/store.go new file mode 100644 index 00000000..55517f1c --- /dev/null +++ b/internal/store/store.go @@ -0,0 +1,723 @@ +// Package store — пользователи, чаты, сообщения и ключи идемпотентности в PostgreSQL. +// +// Источник истины — только эти таблицы. Память процесса после рестарта пуста, +// поэтому ни одного map с данными здесь нет. Каждый запрос параметризован ($1, $2): +// текст сообщения не склеивается в SQL. +// +// Создание чата — одна транзакция: строка чата и все участники фиксируются вместе +// либо не фиксируются вообще. Уникальность username обеспечивает UNIQUE, а не проверка +// «сначала SELECT, потом INSERT» (та проверка проигрывает гонке). +// +// Вложения (lab4) — файл attachments.go: метаданные в PostgreSQL, байты в S3. Сообщение +// ссылается на вложения через message_attachments; ссылки пишутся в той же транзакции, +// что и само сообщение и ключ идемпотентности. +// +// Идемпотентность сообщения тоже живёт в 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" + + "mtusi2026lab4/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 назначает сервер. +// AttachmentIDs всегда непустой срез нулевой длины, если вложений нет (JSON даёт []). +type Message struct { + ID uuid.UUID + ChatID uuid.UUID + SenderID uuid.UUID + Text string + AttachmentIDs []uuid.UUID + CreatedAt time.Time +} + +// 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(), + 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. иначе проверить членство в чате и вложения: каждое должно существовать, лежать +// в ЭТОМ чате и быть ready (чужое/неизвестное — ErrNotFound, не ready — ErrNotReady); +// 5. INSERT message + message_attachments + idempotency_keys в той же транзакции; +// 6. COMMIT (advisory lock снимается вместе с транзакцией). +// +// attachmentIDs уже без дубликатов (проверяет HTTP-слой), порядок сохраняется. +// Пустой текст допустим только вместе с вложениями — это тоже проверяет HTTP-слой. +// Другой 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() + if attachmentIDs == nil { + attachmentIDs = []uuid.UUID{} + } + + 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 + } + byMsg, err := attachmentIDsByMessage(ctx, tx, []uuid.UUID{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, + AttachmentIDs: byMsg[msgID], + CreatedAt: msgCreated, + }, + 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) + } + + attStrs := make([]string, len(attachmentIDs)) + for i, id := range attachmentIDs { + attStrs[i] = id.String() + } + if len(attStrs) > 0 { + // chat_id = $2 — вложение другого чата неотличимо от несуществующего (404, не 403). + rows, err := tx.Query(ctx, ` + SELECT status FROM attachments WHERE id = ANY($1::uuid[]) AND chat_id = $2`, attStrs, chatID) + if err != nil { + return nil, mapWriteErr(err) + } + found, notReady := 0, false + for rows.Next() { + var status string + if err := rows.Scan(&status); err != nil { + rows.Close() + return nil, mapWriteErr(err) + } + found++ + if status != "ready" { + notReady = true + } + } + rows.Close() + if err := rows.Err(); err != nil { + return nil, mapWriteErr(err) + } + if found != len(attStrs) { + return nil, ErrNotFound + } + if notReady { + return nil, ErrNotReady + } + } + + msg := &Message{ + ID: uuid.New(), + ChatID: chatID, + SenderID: senderID, + Text: text, + AttachmentIDs: append([]uuid.UUID{}, attachmentIDs...), + CreatedAt: nowUTC(), + } + 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) + } + if len(attStrs) > 0 { + // WITH ORDINALITY сохраняет порядок attachment_ids из запроса. + if _, err := tx.Exec(ctx, ` + INSERT INTO message_attachments (message_id, attachment_id, position) + SELECT $1, u.id, (u.ord - 1)::smallint + FROM unnest($2::uuid[]) WITH ORDINALITY AS u(id, ord)`, msg.ID, attStrs); err != nil { + return nil, mapWriteErr(err) + } + } + + // response_body заполняем каноническим Message JSON уже здесь, чтобы replay + // не зависел от повторной сериализации в HTTP-слое с другим порядком полей. + bodyJSON, err := json.Marshal(map[string]any{ + "id": msg.ID.String(), + "chat_id": msg.ChatID.String(), + "sender_id": msg.SenderID.String(), + "text": msg.Text, + "attachment_ids": attStrs, + "created_at": msg.CreatedAt.UTC().Truncate(time.Millisecond).Format("2006-01-02T15:04:05.000Z"), + }) + 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 + }) + // Вложения страницы — одним запросом, а не по запросу на сообщение. + 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 nil, nil, err + } + for i := range items { + items[i].AttachmentIDs = byMsg[items[i].ID] + } + 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 +} + +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/check-private-bucket.sh b/scripts/check-private-bucket.sh new file mode 100755 index 00000000..fc7f98fc --- /dev/null +++ b/scripts/check-private-bucket.sh @@ -0,0 +1,31 @@ +#!/bin/sh +# Уровень 4: прямое неаутентифицированное чтение объекта из bucket должно отказать. +# Ожидание: HTTP 403 (или отказ соединения / 400 Signature) — не 200 с телом файла. +set -eu +ROOT=$(CDPATH= cd -- "$(dirname "$0")/.." && pwd) +cd "$ROOT" + +BUCKET=${S3_BUCKET:-messenger-attachments} +ENDPOINT=${S3_PUBLIC_ENDPOINT:-http://127.0.0.1:9000} +# Любой ключ: даже несуществующий при private bucket не должен отдаваться анониму как 200+тело. +URL="${ENDPOINT}/${BUCKET}/originals/does-not-exist" + +code=$(curl -sS -o /tmp/private-bucket-body.$$ -w '%{http_code}' "$URL" || echo "000") +body_len=$(wc -c < /tmp/private-bucket-body.$$ | tr -d ' ') +rm -f /tmp/private-bucket-body.$$ + +echo "GET $URL → HTTP $code body_bytes=$body_len" +case "$code" in + 200) + echo "FAIL: anonymous GET returned 200" >&2 + exit 1 + ;; + 000) + echo "FAIL: could not reach MinIO at $ENDPOINT" >&2 + exit 1 + ;; + *) + echo "PASS: anonymous access denied (HTTP $code)" + exit 0 + ;; +esac diff --git a/scripts/concurrent-uploads.sh b/scripts/concurrent-uploads.sh new file mode 100755 index 00000000..8af43750 --- /dev/null +++ b/scripts/concurrent-uploads.sh @@ -0,0 +1,130 @@ +#!/bin/sh +# Уровень 4: ≥10 одновременных загрузок + пик RSS API-реплик. +set -eu +ROOT=$(CDPATH= cd -- "$(dirname "$0")/.." && pwd) +cd "$ROOT" +export BASE_URL=${BASE_URL:-http://127.0.0.1:8080} +export N=${N:-12} +export OUT=${OUT:-evidence/concurrent-uploads.txt} +mkdir -p evidence + +python3 - <<'PY' +import base64, binascii, json, os, struct, subprocess, sys, threading, time, urllib.request, uuid, zlib + +base = os.environ["BASE_URL"] +n = int(os.environ["N"]) +out = os.environ["OUT"] + +def req(method, path, data=None, headers=None, timeout=60): + h = dict(headers or {}) + body = data + if isinstance(data, (dict, list)): + body = json.dumps(data).encode() + h.setdefault("Content-Type", "application/json") + r = urllib.request.Request(base + path, data=body, headers=h, method=method) + with urllib.request.urlopen(r, timeout=timeout) as resp: + return resp.status, resp.read() + +def chunk(tag, data): + return struct.pack(">I", len(data)) + tag + data + struct.pack(">I", binascii.crc32(tag + data) & 0xffffffff) + +# 1024×1024 RGB, zlib level 0 → ~3 MiB: заметнее для RSS, всё ещё ≪ 10 MiB лимита. +w = h = 1024 +ihdr = struct.pack(">IIBBBBB", w, h, 8, 2, 0, 0, 0) +raw = b"".join(b"\x00" + bytes(w * 3) for _ in range(h)) +big = b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", ihdr) + chunk(b"IDAT", zlib.compress(raw, 0)) + chunk(b"IEND", b"") +print(f"upload_size_bytes={len(big)}", flush=True) + +uname = "cu_" + uuid.uuid4().hex[:10] +password = "correct-horse-1" +st, body = req("POST", "/api/v1/users", {"username": uname, "display_name": "CU", "password": password}) +assert st == 201, body +uid = json.loads(body)["id"] +basic = base64.b64encode(f"{uname}:{password}".encode()).decode() +st, body = req("POST", "/api/v1/auth/sessions", headers={"Authorization": f"Basic {basic}"}) +assert st == 201, body +token = json.loads(body)["token"] +st, body = req("POST", "/api/v1/chats", {"title": "concurrent", "member_ids": [uid]}, + headers={"Authorization": f"Bearer {token}"}) +assert st == 201, body +chat = json.loads(body)["id"] + +def api_rss_kb(): + try: + ids = subprocess.check_output( + ["docker", "compose", "--env-file", ".env", "ps", "-q", "api"], text=True + ).split() + total = 0 + for i in ids: + line = subprocess.check_output( + ["docker", "stats", "--no-stream", "--format", "{{.MemUsage}}", i], text=True + ).strip() + part = line.split("/")[0].strip() + num = float("".join(ch for ch in part if ch.isdigit() or ch == ".")) + if "GiB" in part: + total += int(num * 1024 * 1024) + elif "MiB" in part: + total += int(num * 1024) + else: + total += int(num) + return total + except Exception as e: + print("rss_err", e, flush=True) + return -1 + +rss_before = api_rss_kb() +peak = {"v": rss_before} +stop = threading.Event() + +def monitor(): + while not stop.is_set(): + v = api_rss_kb() + if v > peak["v"]: + peak["v"] = v + time.sleep(0.2) + +mon = threading.Thread(target=monitor, daemon=True) +mon.start() +results = [None] * n +barrier = threading.Barrier(n) + +def worker(i): + barrier.wait(60) + try: + r = urllib.request.Request( + f"{base}/api/v1/chats/{chat}/attachments?filename=c{i}.png", + data=big, + headers={"Authorization": f"Bearer {token}", "Content-Type": "image/png"}, + method="POST", + ) + with urllib.request.urlopen(r, timeout=120) as resp: + results[i] = resp.status + except Exception as e: + results[i] = str(e) + +threads = [threading.Thread(target=worker, args=(i,)) for i in range(n)] +t0 = time.time() +for th in threads: + th.start() +for th in threads: + th.join() +elapsed = time.time() - t0 +stop.set() +mon.join(timeout=1) +rss_after = api_rss_kb() +ok = sum(1 for r in results if r == 201) +text = "\n".join([ + f"concurrent={n}", + f"upload_bytes={len(big)}", + f"ok_201={ok}", + f"results={results}", + f"elapsed_s={elapsed:.3f}", + f"api_rss_kb_before={rss_before}", + f"api_rss_kb_peak={peak['v']}", + f"api_rss_kb_after={rss_after}", +]) + "\n" +print(text, end="") +open(out, "w").write(text) +sys.exit(0 if ok == n else 1) +PY +echo "wrote $OUT" diff --git a/scripts/reconcile-demo.sh b/scripts/reconcile-demo.sh new file mode 100755 index 00000000..7bc99c6a --- /dev/null +++ b/scripts/reconcile-demo.sh @@ -0,0 +1,146 @@ +#!/bin/sh +# Трек 5: внедрить orphan + missing, показать dry-run и apply, доказать защиту fresh. +set -eu +ROOT=$(CDPATH= cd -- "$(dirname "$0")/.." && pwd) +cd "$ROOT" +OUT=${OUT:-evidence/reconcile.txt} +mkdir -p evidence +: >"$OUT" + +log() { echo "$@" | tee -a "$OUT"; } + +BUCKET=$(grep -E '^S3_BUCKET=' .env | cut -d= -f2-) +BUCKET=${BUCKET:-messenger-attachments} +ROOT_USER=$(grep -E '^MINIO_ROOT_USER=' .env | cut -d= -f2-) +ROOT_PASS=$(grep -E '^MINIO_ROOT_PASSWORD=' .env | cut -d= -f2-) +ROOT_USER=${ROOT_USER:-minioadmin} +ROOT_PASS=${ROOT_PASS:-minioadmin-secret} +ORPHAN_KEY="originals/00000000-0000-4000-8000-0000000000aa" + +log "=== seed orphan object via root PutObject (python/minio not required: curl+aws style via go) ===" +# Используем временный контейнер с нашим s3bootstrap-окружением нельзя для PUT. +# Кладём объект через API MinIO SDK в одноразовом python boto? Проще — docker run с +# нашим образом и маленьким go-one-liner... Пишем через awscli-совместимый путь: +# minio client отсутствует → используем python3 + urllib подписанный запрос слишком сложен. +# Простой путь: временный Go в scripts/seed_orphan — нет. Используем docker compose run +# с entrypoint /s3bootstrap нельзя. Добавим флаг... +# Практика: python boto3 если есть, иначе raw Put через minio-go в compose run server? +# Самое простое — python3 и hashlib hmac для SigV4. + +python3 - <&1 | tee -a "$OUT" + +log "=== apply grace=0 ===" +docker compose --env-file .env run --rm --no-deps reconcile -apply -grace-seconds=0 2>&1 | tee -a "$OUT" + +log "=== second apply (idempotent) ===" +docker compose --env-file .env run --rm --no-deps reconcile -apply -grace-seconds=0 2>&1 | tee -a "$OUT" + +log "=== fresh orphan skipped with default grace ===" +python3 - <&1 | tee -a "$OUT" + +log "wrote $OUT" diff --git a/scripts/restart.sh b/scripts/restart.sh new file mode 100755 index 00000000..9f0235ae --- /dev/null +++ b/scripts/restart.sh @@ -0,0 +1,7 @@ +#!/bin/sh +# Перезапуск API (всех реплик), LB и всех хранилищ без удаления volumes. +# Важно: именно restart, а не up -d — иначе PID/StartedAt у живых контейнеров не меняются. +set -eu +ROOT=$(CDPATH= cd -- "$(dirname "$0")/.." && pwd) +cd "$ROOT" +docker compose --env-file .env restart postgres redis minio api lb diff --git a/scripts/restore-one.sh b/scripts/restore-one.sh new file mode 100755 index 00000000..56e6b2df --- /dev/null +++ b/scripts/restore-one.sh @@ -0,0 +1,42 @@ +#!/bin/sh +# Поднимает недостающие / остановленные API-реплики до API_REPLICAS после stop-one. +# Не трогает volumes и не делает down -v. Миграции уже применены — не пересоздаём migrate. +set -eu +ROOT=$(CDPATH= cd -- "$(dirname "$0")/.." && pwd) +cd "$ROOT" +API_REPLICAS=$(grep -E '^API_REPLICAS=' .env 2>/dev/null | cut -d= -f2- || true) +API_REPLICAS=${API_REPLICAS:-2} + +# Стартуем остановленные контейнеры сервиса api и добираем scale при нехватке. +docker compose --env-file .env start api 2>/dev/null || true +docker compose --env-file .env up -d --no-deps --scale "api=${API_REPLICAS}" api + +deadline=$(( $(date +%s) + 90 )) +while :; do + if curl -fsS "http://127.0.0.1:8080/health/ready" >/dev/null 2>&1; then + # Ждём, пока LB реально видит ≥2 instance id (не только один backend). + ids=$( + python3 - <<'PY' +import urllib.request +ids=set() +for _ in range(24): + try: + with urllib.request.urlopen('http://127.0.0.1:8080/health/live', timeout=1) as r: + i=r.headers.get('X-Instance-Id') + if i: ids.add(i) + except Exception: + pass +print(len(ids)) +PY + ) + if [ "$ids" -ge 2 ] || [ "$API_REPLICAS" -lt 2 ]; then + exit 0 + fi + fi + if [ "$(date +%s)" -ge "$deadline" ]; then + echo "restore timeout (replicas visible via LB: ${ids:-0})" >&2 + docker compose --env-file .env ps >&2 || true + exit 1 + fi + sleep 1 +done diff --git a/scripts/stop-one.sh b/scripts/stop-one.sh new file mode 100755 index 00000000..049a3785 --- /dev/null +++ b/scripts/stop-one.sh @@ -0,0 +1,44 @@ +#!/bin/sh +# Останавливает РОВНО одну API-реплику, чей X-Instance-Id = TARGET_INSTANCE_ID. +# Реплика остаётся остановленной; восстановление — scripts/restore-one.sh или compose up. +# Не трогает postgres/redis/lb/volumes. Должен завершиться за <10 с. +set -eu +: "${TARGET_INSTANCE_ID:?test provides target API instance alias}" + +ROOT=$(CDPATH= cd -- "$(dirname "$0")/.." && pwd) +cd "$ROOT" + +ids=$(docker compose --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 + # Совпадает с config.InstanceID: hostname контейнера, если INSTANCE_ID не задан. + 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 + # Явный stop контейнера; restart: "no" у api гарантирует, что он не вернётся сам. + docker stop -t 8 "$id" >/dev/null + # Подтверждаем, что контейнер действительно не running — иначе failover-тест врёт. + 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 diff --git a/scripts/up.sh b/scripts/up.sh new file mode 100755 index 00000000..51bd2f2a --- /dev/null +++ b/scripts/up.sh @@ -0,0 +1,38 @@ +#!/bin/sh +# Единая последовательность запуска стенда lab4. +# 1) postgres+redis+minio 2) bootstrap bucket 3) миграции 4) API×N 5) HAProxy +set -eu +ROOT=$(CDPATH= cd -- "$(dirname "$0")/.." && pwd) +cd "$ROOT" + +if [ ! -f .env ]; then + cp .env.example .env + echo "created .env from .env.example" >&2 +fi + +API_REPLICAS=$(grep -E '^API_REPLICAS=' .env | cut -d= -f2- || true) +API_REPLICAS=${API_REPLICAS:-2} + +docker compose --env-file .env config --quiet +docker compose --env-file .env up -d --build postgres redis minio +docker compose --env-file .env run --rm minio-init +docker compose --env-file .env run --rm --build migrate +docker compose --env-file .env up -d --build --scale "api=${API_REPLICAS}" --no-deps api +docker compose --env-file .env up -d --no-deps lb + +echo "waiting for http://127.0.0.1:8080/health/ready via LB..." +deadline=$(( $(date +%s) + 180 )) +while :; do + if curl -fsS "http://127.0.0.1:8080/health/ready" >/dev/null 2>&1; then + echo "ready" + docker compose --env-file .env ps + exit 0 + fi + if [ "$(date +%s)" -ge "$deadline" ]; then + echo "timeout waiting for readiness" >&2 + docker compose --env-file .env ps >&2 || true + docker compose --env-file .env logs --tail=80 api lb minio minio-init >&2 || true + exit 1 + fi + sleep 1 +done diff --git a/student-tests/api_test.go b/student-tests/api_test.go new file mode 100644 index 00000000..ab0a303e --- /dev/null +++ b/student-tests/api_test.go @@ -0,0 +1,664 @@ +// Собственные проверки lab3 (плюс регрессия lab2). Им нужен уже поднятый +// PostgreSQL и Redis (docker compose up / scripts/up.sh): контракт требует +// настоящую БД, а не 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" + + "mtusi2026lab4/internal/api" + "mtusi2026lab4/internal/auth" + "mtusi2026lab4/internal/blob" + "mtusi2026lab4/internal/session" + "mtusi2026lab4/internal/store" +) + +var ( + sharedStore *store.Store + sharedSessions *session.Store + sharedRedisURL string +) + +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) + } + 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, blob.NewMemory(), "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, blob.NewMemory(), "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, blob.NewMemory(), "test-instance").Handler()) +} + +func newAPIBlob(t *testing.T, ttl time.Duration, bl api.BlobStore) *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, bl, "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..2cb3dd86 --- /dev/null +++ b/student-tests/attachments_test.go @@ -0,0 +1,244 @@ +package studenttests + +import ( + "bytes" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "fmt" + "io" + "net/http" + "net/http/httptest" + "net/url" + "testing" + "time" + + "mtusi2026lab4/internal/api" + "mtusi2026lab4/internal/blob" + "mtusi2026lab4/internal/session" +) + +// 1×1 PNG (valid IHDR + IDAT + IEND, CRC проверены). +var tinyPNG = []byte{ + 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, + 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, + 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, + 0x08, 0x02, 0x00, 0x00, 0x00, 0x90, 0x77, 0x53, + 0xde, 0x00, 0x00, 0x00, 0x0c, 0x49, 0x44, 0x41, + 0x54, 0x78, 0xda, 0x63, 0xf8, 0xcf, 0xc0, 0x00, + 0x00, 0x03, 0x01, 0x01, 0x00, 0xf7, 0x03, 0x41, + 0x43, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, + 0x44, 0xae, 0x42, 0x60, 0x82, +} + +func TestAttachmentUploadDownloadAndACL(t *testing.T) { + mem := blob.NewMemory() + srv := newAPIBlob(t, time.Hour, mem) + defer srv.Close() + logStep(t, "upload PNG → 201 ready → download checksum; посторонний — 404") + + owner := register(t, srv, "att_owner") + ownerTok := login(t, srv, owner.username, owner.password) + stranger := register(t, srv, "att_stranger") + strangerTok := login(t, srv, stranger.username, stranger.password) + chat := createChat(t, srv, ownerTok, owner.id, "Вложения") + + attID, sha := uploadPNG(t, srv, ownerTok, chat, "pic.png", tinyPNG) + status, body := do(t, srv, http.MethodGet, "/api/v1/attachments/"+attID, map[string]string{ + "Authorization": "Bearer " + ownerTok, + }, "") + logResult(t, status, body) + if status != http.StatusOK { + t.Fatalf("meta: %d %s", status, body) + } + meta := decode(t, body) + if meta["status"] != "ready" || meta["sha256"] != sha { + t.Fatalf("meta unexpected: %+v", meta) + } + + statusCode, raw, hdr := downloadBytes(t, srv, ownerTok, attID) + if statusCode != http.StatusOK { + t.Fatalf("download: %d", statusCode) + } + if hdr.Get("Content-Type") != "image/png" { + t.Fatalf("content-type: %q", hdr.Get("Content-Type")) + } + sum := sha256.Sum256(raw) + if hex.EncodeToString(sum[:]) != sha { + t.Fatalf("checksum mismatch") + } + + status, body = do(t, srv, http.MethodGet, "/api/v1/attachments/"+attID, map[string]string{ + "Authorization": "Bearer " + strangerTok, + }, "") + logResult(t, status, body) + if status != http.StatusNotFound { + t.Fatalf("stranger meta: %d", status) + } + statusCode, _, _ = downloadBytes(t, srv, strangerTok, attID) + if statusCode != http.StatusNotFound { + t.Fatalf("stranger download: %d", statusCode) + } + + status, body = do(t, srv, http.MethodPost, "/api/v1/chats/"+chat+"/messages", map[string]string{ + "Authorization": "Bearer " + ownerTok, + }, fmt.Sprintf(`{"text":"с файлом","attachment_ids":[%q]}`, attID)) + logResult(t, status, body) + if status != http.StatusCreated { + t.Fatalf("message with att: %d %s", status, body) + } + msg := decode(t, body) + ids, _ := msg["attachment_ids"].([]any) + if len(ids) != 1 || ids[0] != attID { + t.Fatalf("attachment_ids: %+v", msg["attachment_ids"]) + } + logOK(t, "upload/download/ACL и message.attachment_ids") +} + +func TestAttachmentRejectsBadInput(t *testing.T) { + mem := blob.NewMemory() + srv := newAPIBlob(t, time.Hour, mem) + defer srv.Close() + logStep(t, "битый PNG, подмена MIME, опасный filename, чужой чат → 4xx не 500") + + user := register(t, srv, "att_bad") + tok := login(t, srv, user.username, user.password) + chat := createChat(t, srv, tok, user.id, "Отказы") + + status, body := uploadRaw(t, srv, tok, chat, "../x.png", "image/png", tinyPNG) + logResult(t, status, body) + if status != http.StatusBadRequest { + t.Fatalf("bad filename: %d", status) + } + + status, body = uploadRaw(t, srv, tok, chat, "x.jpg", "image/jpeg", tinyPNG) + logResult(t, status, body) + if status != http.StatusUnsupportedMediaType { + t.Fatalf("mime mismatch: %d", status) + } + + status, body = uploadRaw(t, srv, tok, chat, "bad.png", "image/png", tinyPNG[:20]) + logResult(t, status, body) + if status != http.StatusUnsupportedMediaType { + t.Fatalf("truncated: %d", status) + } + + // Отдельный сервер с маленьким лимитом: реально шлём 2 KiB, ожидаем 413. + small := blob.NewMemory() + sessions, err := session.Open(sharedRedisURL, time.Hour) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = sessions.Close() }) + apiSrv := api.New(sharedStore, sessions, small, "test-small-limit") + apiSrv.MaxUploadBytes = 1024 + limSrv := httptest.NewServer(apiSrv.Handler()) + defer limSrv.Close() + status, body = uploadRaw(t, limSrv, tok, chat, "huge.png", "image/png", make([]byte, 2048)) + logResult(t, status, body) + if status != http.StatusRequestEntityTooLarge { + t.Fatalf("too large body: %d", status) + } + + other := register(t, srv, "att_other") + otherTok := login(t, srv, other.username, other.password) + otherChat := createChat(t, srv, otherTok, other.id, "Чужой") + status, body = uploadRaw(t, srv, tok, otherChat, "x.png", "image/png", tinyPNG) + logResult(t, status, body) + if status != http.StatusNotFound { + t.Fatalf("foreign chat upload: %d", status) + } + + attID, _ := uploadPNG(t, srv, otherTok, otherChat, "o.png", tinyPNG) + status, body = do(t, srv, http.MethodPost, "/api/v1/chats/"+chat+"/messages", map[string]string{ + "Authorization": "Bearer " + tok, + }, fmt.Sprintf(`{"text":"steal","attachment_ids":[%q]}`, attID)) + logResult(t, status, body) + if status != http.StatusNotFound { + t.Fatalf("foreign attachment_id: %d %s", status, body) + } + logOK(t, "негативные сценарии вложений → клиентские 4xx") +} + +func TestAttachmentS3DownIs503(t *testing.T) { + mem := blob.NewMemory() + mem.SetUnavailable(true) + srv := newAPIBlob(t, time.Hour, mem) + defer srv.Close() + logStep(t, "S3 недоступен: ready и upload → 503") + + status, body := do(t, srv, http.MethodGet, "/health/ready", nil, "") + logResult(t, status, body) + if status != http.StatusServiceUnavailable { + t.Fatalf("ready: %d", status) + } + + user := register(t, srv, "s3_down") + tok := login(t, srv, user.username, user.password) + chat := createChat(t, srv, tok, user.id, "S3 down") + status, body = uploadRaw(t, srv, tok, chat, "x.png", "image/png", tinyPNG) + logResult(t, status, body) + if status != http.StatusServiceUnavailable { + t.Fatalf("upload with s3 down: %d %s", status, body) + } + logOK(t, "падение S3 → 503") +} + +func uploadPNG(t *testing.T, srv *httptest.Server, token, chatID, filename string, data []byte) (id, sha string) { + t.Helper() + status, body := uploadRaw(t, srv, token, chatID, filename, "image/png", data) + if status != http.StatusCreated { + t.Fatalf("upload: %d %s", status, body) + } + var att struct { + ID string `json:"id"` + SHA256 string `json:"sha256"` + Status string `json:"status"` + } + if err := json.Unmarshal([]byte(body), &att); err != nil { + t.Fatal(err) + } + if att.Status != "ready" || att.ID == "" { + t.Fatalf("upload body: %s", body) + } + sum := sha256.Sum256(data) + want := hex.EncodeToString(sum[:]) + if att.SHA256 != want { + t.Fatalf("sha got=%s want=%s", att.SHA256, want) + } + return att.ID, att.SHA256 +} + +func uploadRaw(t *testing.T, srv *httptest.Server, token, chatID, filename, ctype string, data []byte) (int, string) { + t.Helper() + u := srv.URL + "/api/v1/chats/" + chatID + "/attachments?filename=" + url.QueryEscape(filename) + req, err := http.NewRequest(http.MethodPost, u, bytes.NewReader(data)) + if err != nil { + t.Fatal(err) + } + req.Header.Set("Authorization", "Bearer "+token) + req.Header.Set("Content-Type", ctype) + 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) +} + +func downloadBytes(t *testing.T, srv *httptest.Server, token, attID string) (int, []byte, http.Header) { + t.Helper() + req, err := http.NewRequest(http.MethodGet, srv.URL+"/api/v1/attachments/"+attID+"/content", nil) + if err != nil { + t.Fatal(err) + } + req.Header.Set("Authorization", "Bearer "+token) + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + b, _ := io.ReadAll(resp.Body) + return resp.StatusCode, b, resp.Header.Clone() +} -- 2.54.0 From fef1c30050f32d6f30c4cc81332c4c991e9b8413 Mon Sep 17 00:00:00 2001 From: Mlvn Date: Thu, 12 Nov 2026 18:25:21 +0300 Subject: [PATCH 2/2] =?UTF-8?q?=D0=97=D0=B0=D0=BC=D0=B5=D0=BD=D0=B8=D1=82?= =?UTF-8?q?=D1=8C=20lab4=20=D0=BD=D0=B0=20aws-sdk=20S3-=D0=B2=D0=BB=D0=BE?= =?UTF-8?q?=D0=B6=D0=B5=D0=BD=D0=B8=D1=8F,=20=D1=83=D1=80=D0=BE=D0=B2?= =?UTF-8?q?=D0=B5=D0=BD=D1=8C=204=20=D0=B8=20=D1=82=D1=80=D0=B5=D0=BA=202?= =?UTF-8?q?=20reconciler.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Единый бинарник с objectstore/reconcile, pinned MinIO при недоступности Docker Hub, автотесты и evidence на оценку 5. --- .env.example | 49 +- Dockerfile | 6 +- Makefile | 61 +- REPORT.md | 67 +- SUBMISSION.md | 58 ++ cmd/reconcile/main.go | 221 ----- cmd/s3bootstrap/main.go | 123 --- cmd/server/main.go | 156 ++-- compose.yaml | 191 ++-- evidence/check.txt | 2 + evidence/concurrent-uploads.txt | 8 - evidence/failover.txt | 4 +- evidence/private-bucket.txt | 23 +- evidence/reconcile.txt | 129 --- evidence/stack-notes.txt | 9 + evidence/student-tests.txt | 676 +++++++++----- evidence/track2-run.txt | 30 + evidence/track2/1_dry_run.exitcode | 1 + evidence/track2/1_dry_run.json | 82 ++ evidence/track2/2_real.exitcode | 1 + evidence/track2/2_real.json | 82 ++ evidence/track2/3_repeat.exitcode | 1 + evidence/track2/3_repeat.json | 29 + evidence/track2/cost.txt | 4 + evidence/track2/environment.txt | 4 + evidence/track2/state_after_dry_run.txt | 12 + evidence/track2/state_after_real.txt | 12 + evidence/track2/state_before.txt | 12 + evidence/upload-mem-run.txt | 18 + evidence/upload-memory/limit_4.stats | 201 ++++ evidence/upload-memory/limit_64.stats | 416 +++++++++ evidence/upload-memory/summary.txt | 14 + go.mod | 57 +- go.sum | 140 +-- internal/api/attachments.go | 573 ++++++------ internal/api/imagecheck.go | 181 ++++ internal/api/server.go | 89 +- internal/blob/memory.go | 162 ---- internal/blob/minio.go | 197 ---- internal/config/config.go | 123 ++- internal/objectstore/s3.go | 304 +++++++ internal/reconcile/reconcile.go | 377 ++++++++ internal/store/attachments.go | 258 ++++-- internal/store/migrations/003_attachments.sql | 22 +- internal/store/store.go | 122 +-- scripts/_lib.sh | 53 ++ scripts/check-private-bucket.sh | 31 - scripts/check_private_bucket.sh | 73 ++ scripts/concurrent-uploads.sh | 130 --- scripts/reconcile-demo.sh | 146 --- scripts/restart.sh | 3 +- scripts/run_track2.sh | 143 +++ scripts/up.sh | 23 +- scripts/upload_mem_experiment.sh | 120 +++ student-tests/api_test.go | 47 +- student-tests/attachments_test.go | 859 ++++++++++++++---- student-tests/reconcile_test.go | 198 ++++ 57 files changed, 4628 insertions(+), 2505 deletions(-) create mode 100644 SUBMISSION.md delete mode 100644 cmd/reconcile/main.go delete mode 100644 cmd/s3bootstrap/main.go create mode 100644 evidence/check.txt delete mode 100644 evidence/concurrent-uploads.txt delete mode 100644 evidence/reconcile.txt create mode 100644 evidence/stack-notes.txt create mode 100644 evidence/track2-run.txt create mode 100644 evidence/track2/1_dry_run.exitcode create mode 100644 evidence/track2/1_dry_run.json create mode 100644 evidence/track2/2_real.exitcode create mode 100644 evidence/track2/2_real.json create mode 100644 evidence/track2/3_repeat.exitcode create mode 100644 evidence/track2/3_repeat.json create mode 100644 evidence/track2/cost.txt create mode 100644 evidence/track2/environment.txt create mode 100644 evidence/track2/state_after_dry_run.txt create mode 100644 evidence/track2/state_after_real.txt create mode 100644 evidence/track2/state_before.txt create mode 100644 evidence/upload-mem-run.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 internal/api/imagecheck.go delete mode 100644 internal/blob/memory.go delete mode 100644 internal/blob/minio.go create mode 100644 internal/objectstore/s3.go create mode 100644 internal/reconcile/reconcile.go create mode 100755 scripts/_lib.sh delete mode 100755 scripts/check-private-bucket.sh create mode 100755 scripts/check_private_bucket.sh delete mode 100755 scripts/concurrent-uploads.sh delete mode 100755 scripts/reconcile-demo.sh create mode 100755 scripts/run_track2.sh create mode 100755 scripts/upload_mem_experiment.sh create mode 100644 student-tests/reconcile_test.go diff --git a/.env.example b/.env.example index 6d162f97..072c05c8 100644 --- a/.env.example +++ b/.env.example @@ -17,24 +17,43 @@ SESSION_STORE=redis # Число API-реплик за LB. Поднимать: scripts/up.sh или compose --scale api=N API_REPLICAS=2 -# Лимиты одной API-реплики. +# Лимиты одной API-реплики (суммарный бюджет track1 = replicas * эти значения). API_CPUS=0.50 API_MEMORY=256M +# Мягкий лимит кучи Go (ниже API_MEMORY): GC работает активнее до OOM-kill. +API_GOMEMLIMIT=200MiB # Пул соединений на одну реплику. Суммарно ≈ API_REPLICAS * DB_MAX_CONNS. DB_MAX_CONNS=5 -# Лимиты вложений (контракт lab4). -MAX_UPLOAD_BYTES=10485760 -MAX_IMAGE_PIXELS=40000000 - -# MinIO (S3). Root — только для bootstrap (minio-init). API использует app-ключи. -MINIO_ROOT_USER=minioadmin -MINIO_ROOT_PASSWORD=minioadmin-secret -S3_ENDPOINT=minio:9000 -S3_USE_SSL=0 +# ---------------- lab4: S3 (MinIO) ---------------- +# Root-учётка MinIO: нужна ТОЛЬКО сервисам minio и minio-init. API её не получает. +MINIO_ROOT_USER=minio-root +MINIO_ROOT_PASSWORD=minio-root-secret-change-me +# Пользователь API (создаётся minio-init) с политикой только на bucket ниже. Секрет >= 8 символов. +# Эти же значения получают api/migrate/reconcile как S3_ACCESS_KEY / S3_SECRET_KEY. +S3_ENDPOINT=http://minio:9000 S3_REGION=us-east-1 -S3_BUCKET=messenger-attachments -S3_ACCESS_KEY_ID=messenger-app -S3_SECRET_ACCESS_KEY=messenger-app-secret -# Grace period reconciler (секунды): свежие orphan/missing не трогаем. -S3_RECONCILE_GRACE_SECONDS=60 +S3_BUCKET=messenger +S3_ACCESS_KEY=messenger-api +S3_SECRET_KEY=messenger-api-secret-change-me +# Path-style адресация (http://minio:9000/bucket/key) — единственный вариант для MinIO в Compose. +S3_FORCE_PATH_STYLE=1 +# Reconciler: объект без строки в БД моложе этого возраста не трогаем (загрузка могла быть «в полёте»). +S3_ORPHAN_GRACE_SECONDS=300 +# Сколько загрузок реплика буферизует в RAM одновременно (пик RAM ≈ значение * 10 MiB). +UPLOAD_MAX_CONCURRENCY=4 + +# Порты хоста (только 127.0.0.1). Меняйте, если 8080/5432/6379/9000 уже заняты. +LB_HOST_PORT=8080 +POSTGRES_HOST_PORT=5432 +REDIS_HOST_PORT=6379 +MINIO_HOST_PORT=9000 +# Консоль MinIO отключена (MINIO_BROWSER=off) и порт 9001 не публикуется. + +# Образы S3. По умолчанию в compose.yaml — pinned community MinIO + Chainguard mc +# (официальные minio/minio и minio/mc с Docker Hub в этой среде недоступны). +# Если Docker Hub доступен, можно вернуть официальные теги: +# MINIO_IMAGE=minio/minio:RELEASE.2024-12-18T13-15-44Z +# MC_IMAGE=minio/mc:RELEASE.2024-11-21T17-21-54Z +MINIO_IMAGE=ghcr.io/coollabsio/minio:RELEASE.2025-10-15T17-29-55Z +MC_IMAGE=cgr.dev/chainguard/minio-client:latest-dev diff --git a/Dockerfile b/Dockerfile index 170f5c01..dae1065e 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,18 +1,14 @@ # syntax=docker/dockerfile:1.7 -FROM golang:1.24.2-bookworm AS build +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 -RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags="-s -w" -o /out/reconcile ./cmd/reconcile -RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags="-s -w" -o /out/s3bootstrap ./cmd/s3bootstrap FROM gcr.io/distroless/static-debian12:nonroot COPY --from=build /out/server /server -COPY --from=build /out/reconcile /reconcile -COPY --from=build /out/s3bootstrap /s3bootstrap USER nonroot:nonroot EXPOSE 8080 ENV APP_HOST=0.0.0.0 \ diff --git a/Makefile b/Makefile index 9448480d..ae4429b6 100644 --- a/Makefile +++ b/Makefile @@ -4,10 +4,47 @@ CA_FILE ?= ACTION_SCRIPT ?= TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",) -.PHONY: help check validate test load test-persistence test-failover up down student-test private-bucket concurrent reconcile-demo +# Параметры подключения student-tests к стенду (порты берутся из .env, если он есть). +# Значения по умолчанию совпадают с .env.example: postgres/redis/minio на 127.0.0.1. +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),5432) +REDIS_PORT := $(or $(call env_val,REDIS_HOST_PORT),6379) +MINIO_PORT := $(or $(call env_val,MINIO_HOST_PORT),9000) +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 student-test track2 private-bucket upload-mem help: - @echo "check: offline structure; validate: full OpenAPI; test: smoke; up/down: compose stand" + @echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes" + @echo "up: scripts/up.sh; student-test: go-тесты lab2-4 против поднятого стенда; track2: reconciler (evidence/track2)" + @echo "private-bucket: проверка приватности bucket; upload-mem: эксперимент пика памяти при >=10 загрузках" + +up: + bash scripts/up.sh + +# Собственные тесты студента (включая lab4: вложения, S3 down, компенсация, reconciler). +# Нужен поднятый стенд: порты postgres/redis/minio опубликованы на 127.0.0.1. +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 + +# Трек 2: инъекция orphan/missing, dry-run, реальный запуск, повтор; evidence в evidence/track2/. +track2: + bash scripts/run_track2.sh + +private-bucket: + bash scripts/check_private_bucket.sh | tee evidence/private-bucket.txt + +upload-mem: + bash scripts/upload_mem_experiment.sh check: $(PYTHON) scripts/check_contract.py @@ -28,23 +65,3 @@ test-persistence: test-failover: @test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable stop-one hook"; exit 2) $(PYTHON) tests/resilience.py --mode failover --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS) - -up: - bash scripts/up.sh - -down: - docker compose --env-file .env down - -student-test: - DATABASE_URL=postgres://messenger:messenger@127.0.0.1:5432/messenger?sslmode=disable \ - REDIS_URL=redis://127.0.0.1:6379/0 \ - go test ./student-tests/ -count=1 -v - -private-bucket: - bash scripts/check-private-bucket.sh - -concurrent: - bash scripts/concurrent-uploads.sh - -reconcile-demo: - bash scripts/reconcile-demo.sh diff --git a/REPORT.md b/REPORT.md index 1bb32a2f..c2140126 100644 --- a/REPORT.md +++ b/REPORT.md @@ -3,79 +3,92 @@ - Автор, группа: Белоусов Анатолий Фахраддинович, БПИ2303 - Целевая оценка; выбранный трек 5: **5, трек 2** (согласованность двух хранилищ / reconciler) - Commit/PR: ветка `solution/bpi2303-belousov` -- Использованные источники, библиотеки и помощь ИИ: Go `net/http`, `pgx` v5, `go-redis` v9, `minio-go` v7, `madmin-go` v3, `golang.org/x/crypto/argon2`, `google/uuid`; MinIO community-образ `ghcr.io/coollabsio/minio` (официальные `minio/minio` сняты с Docker Hub); HAProxy 2.9; публичные `tests/`; Cursor/Composer. База — реализация lab3. +- Использованные источники, библиотеки и помощь ИИ: Go `net/http`, `pgx` v5, `go-redis` v9, `aws-sdk-go-v2` (S3), `golang.org/x/crypto/argon2`, `google/uuid`; MinIO community-образ `ghcr.io/coollabsio/minio:RELEASE.2025-10-15T17-29-55Z` + клиент `cgr.dev/chainguard/minio-client:latest-dev` (официальные `minio/minio`/`minio/mc` на Docker Hub из стенда недоступны: pull access denied); HAProxy 2.9; публичные `tests/`; Cursor/Composer. База — реализация lab3 (LB, Redis-сессии, Idempotency-Key, failover). ## Запуск из чистого clone -Нужны Docker, Go 1.24+ (student-tests), Python 3.9+. +Нужны Docker, Go 1.23+ (student-tests), Python 3.9+. ```sh cp .env.example .env bash scripts/up.sh -# postgres+redis+minio → s3bootstrap → migrate → API×N → LB :8080 +# postgres+redis+minio → minio-init → migrate → API×N → LB :8080 +make check make test make student-test make private-bucket -make concurrent +make upload-mem make test-persistence ACTION_SCRIPT=scripts/restart.sh make test-failover ACTION_SCRIPT=scripts/stop-one.sh bash scripts/restore-one.sh # после failover -make reconcile-demo # трек 5: dry-run → apply → fresh skip +make track2 # трек 5: dry-run → apply → repeat (~1 мин) ``` Остановка без удаления данных: `docker compose --env-file .env stop`. Удаление учебных volumes: `docker compose --env-file .env down -v`. -Образы: сборка `golang:1.24.2-bookworm`, runtime `gcr.io/distroless/static-debian12:nonroot`, PostgreSQL `postgres:16.6`, Redis `redis:7.4.1` (AOF), HAProxy `haproxy:2.9.14-alpine`, MinIO `ghcr.io/coollabsio/minio:RELEASE.2025-10-15T17-29-55Z`. Консоль MinIO не публикуется; API S3 — только `127.0.0.1:9000` для локальной проверки private bucket. +Образы: сборка `golang:1.23.8-bookworm`, runtime `gcr.io/distroless/static-debian12:nonroot`, PostgreSQL `postgres:16.6`, Redis `redis:7.4.1` (AOF), HAProxy `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`); S3 API — только `127.0.0.1:9000` для private-bucket и student-tests. ## Архитектура и решения Клиент → HAProxy → API×2+ → PostgreSQL (метаданные) + Redis (сессии) + приватный MinIO (байты). -Вложение: сервер назначает ключ `originals/`; `filename` только в метаданных. Порядок записи — **сначала S3 PUT, потом INSERT**; 201 только после обоих. Ошибка INSERT → немедленный Delete объекта; если Delete не удался — orphan подберёт reconciler после grace. +**Вложение.** Сервер назначает ключ `attachments/{chat_id}/{attachment_id}`; `filename` только в метаданных и не попадает в путь. Порядок записи — **сначала S3 PUT, потом INSERT**; 201 `ready` только после обоих. Ошибка INSERT → немедленный Delete объекта (`compensateOrphan`); если Delete не удался — orphan подберёт reconciler после grace (`S3_ORPHAN_GRACE_SECONDS`, по умолчанию 300). -Загрузка: spool во временный файл (не `ReadAll`), лимит `MaxUploadBytes+1`, MIME по содержимому, размеры PNG/JPEG из заголовка до декодирования пикселей, структурная проверка CRC/EOI. Download — proxy через API (проверка членства), без редиректа на S3. +**Загрузка.** Тело буферизуется в RAM с лимитом `MaxUploadBytes+1` (`http.MaxBytesReader`) и слотом `UPLOAD_MAX_CONCURRENCY` (пик ≈ concurrency × 10 MiB на реплику). MIME — по содержимому; размеры PNG/JPEG читаются из заголовка до полного декодирования пикселей (`internal/api/imagecheck.go`); структурная проверка CRC/EOI. Download — proxy через API (проверка членства в чате), без редиректа на S3 и без раскрытия `object_key`. -Перенесено из lab3: LB, Idempotency-Key, X-Instance-Id, Redis-сессии, failover hooks. Добавлено: миграция `003_attachments.sql`, routes attachments, `cmd/reconcile`, `cmd/s3bootstrap`, MinIO в compose. +**S3-клиент.** Тонкая обёртка `internal/objectstore` над `aws-sdk-go-v2` (path-style, статические credentials учётки `messenger-api`). Root-учётка MinIO есть только у сервисов `minio` и `minio-init`. -Переменные `.env.example` → compose `x-api-env` / Load / LoadS3: `DATABASE_URL`, `REDIS_URL`, `S3_*`, `MAX_UPLOAD_*`, `S3_RECONCILE_GRACE_SECONDS`. +**Bootstrap.** `minio-init` идемпотентно: приватный bucket, политика `messenger-api-rw` только на этот bucket (без CreateBucket/admin), пользователь API, самопроверка привязки политики. + +**Reconciler (трек 2).** Режим `/server -reconcile` / `-reconcile-dry-run` / `-reconcile-prune-missing` в том же бинарнике (`internal/reconcile`). Сливает отсортированные потоки ListObjectsV2 и keyset по `attachments.object_key COLLATE "C"`. Удаляет только «созревшие» orphan-объекты схемы `attachments/{uuid}/{uuid}`; чужие ключи не трогает; missing **используемые** — только ALERT (exit 2); stale unused при prune — DELETE строки; свежие (< grace) — skip. + +Перенесено из lab3: LB, Idempotency-Key, `X-Instance-Id`, Redis-сессии, failover hooks (`scripts/stop-one.sh`, `restore-one.sh`, `restart.sh`). Добавлено: миграция `003_attachments.sql`, routes attachments, `objectstore`, `reconcile`, MinIO в compose, `scripts/run_track2.sh`, `check_private_bucket.sh`, `upload_mem_experiment.sh`. ## Доказательства критериев | Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства | | --- | --- | --- | --- | +| Offline contract | `make check` | PASS | `evidence/check.txt` | | Публичный smoke (checksum, ACL) | `make test` | PASS lab4 public API scenario | `evidence/smoke.txt` | -| Offline contract | `make check` | PASS | (stdout) | -| Student-tests вложений/негативы/S3↓ | `make student-test` | PASS | `evidence/student-tests.txt` | -| Private bucket | `make private-bucket` | anonymous GET → HTTP 403 | `evidence/private-bucket.txt` | -| Persistence + оригинал | `make test-persistence ACTION_SCRIPT=scripts/restart.sh` | PASS (restart postgres redis minio api lb) | `evidence/persistence.txt` | -| Failover API + download через другую реплику | `make test-failover ACTION_SCRIPT=scripts/stop-one.sh` | PASS; 2 instance ids до отказа | `evidence/failover.txt` | -| ≥10 concurrent uploads + RSS | `make concurrent` | 12×201; RSS API до/пик/после | `evidence/concurrent-uploads.txt` | -| Трек 2 reconciler | `make reconcile-demo` | orphan deleted; missing unreferenced deleted; referenced kept; fresh skipped | `evidence/reconcile.txt` | +| Student-tests вложений/негативы/S3↓/компенсация/reconciler | `make student-test` | PASS (ok student-tests) | `evidence/student-tests.txt` | +| Private bucket | `make private-bucket` | anonymous GET/LIST/PUT → 403; API user ограничен bucket; :9001 нет | `evidence/private-bucket.txt` | +| Persistence + оригинал | `make test-persistence ACTION_SCRIPT=scripts/restart.sh` | PASS | `evidence/persistence.txt` | +| Failover API + download через другую реплику | `make test-failover ACTION_SCRIPT=scripts/stop-one.sh` | PASS; 2 instance ids до отказа; recovery ~2.8 s | `evidence/failover.txt` | +| ≥10 concurrent uploads + пик RAM | `make upload-mem` | 80×201; peak 172 MiB @ concurrency=64 vs 84 MiB @ 4 | `evidence/upload-memory/` | +| Трек 2 reconciler | `make track2` | orphan deleted; missing used kept; stale pruned; fresh skipped; repeat idempotent | `evidence/track2/` | ## Эксперименты и отказы -**Гипотеза (трек 2):** при grace period reconciler безопасно удаляет только «старые» orphan-объекты и нессылаемые missing-строки; повторный apply идемпотентен; свежий orphan не трогается. +**Гипотеза (трек 2):** при grace period reconciler безопасно удаляет только «старые» orphan-объекты и нессылаемые missing-строки; повторный apply идемпотентен; свежий orphan и используемое missing не трогаются; чужая схема ключа не трогается. -Методика: `scripts/reconcile-demo.sh` — SigV4 PUT orphan root-ключом; SQL INSERT missing без объекта; dry-run/`-apply` с `-grace-seconds=0`; затем fresh orphan и dry-run с grace=60s. +Методика: `scripts/run_track2.sh` — инъекция через root-`mc` (orphan_old, bulk 300, foreign key, удаление объекта у used/stale) + sleep grace → fresh violations → dry-run → apply+prune → repeat. Код выхода 2 ожидаем (есть used missing). -Результаты (локальный прогон): orphan удалён; 2 missing без ссылок удалены; 2 missing с `message_attachments` сохранены; fresh orphan → `orphan_skip_fresh`. Обход: List S3 O(n) + keyset по attachments; elapsed dry-run ~10–30 ms на учебном объёме. +Результаты локального прогона (`evidence/track2/cost.txt`): -**Concurrent uploads:** 12 параллельных PNG по ~3.0 MiB (1024², zlib level 0), spool в `/tmp`. -RSS суммарно по API-репликам: before ≈96 MiB, peak ≈98 MiB, after ≈97 MiB — пик не масштабируется -как `N × размер файла` (нет `ReadAll` в кучу). См. `evidence/concurrent-uploads.txt`. +| шаг | s3_objects | delete_calls | duration_ms | +| --- | ---: | ---: | ---: | +| dry-run | 342 | 0 | 82 | +| real | 342 | 301 | 357 | +| repeat | 41 | 0 | 17 | + +Инварианты: все PASS (см. `evidence/track2-run.txt`). + +**Пик памяти при ≥10 одновременных загрузках** (`evidence/upload-memory/summary.txt`): файл ~7.3 MiB, 20 клиентов × 4 повтора, 2 реплики × 256M. При `UPLOAD_MAX_CONCURRENCY=64` peak ≈172 MiB/реплика; при `=4` peak ≈80–84 MiB. Лимит слотов ограничивает пик пропорционально concurrency, а не числу клиентов. | Воздействие | Что ожидаем | Что наблюдали | Восстановление | | --- | --- | --- | --- | | `docker stop` одной API | LB уводит трафик; download с другой реплики | PASS failover | `scripts/restore-one.sh` | | `restart` всех хранилищ+API | сессия и файл на месте | PASS persistence | volumes сохранены | | Anonymous GET MinIO | не 200 | 403 | — | -| S3 down (unit) | ready/upload 503 | PASS student-test | — | +| S3 down (student-test) | ready/upload 503 | PASS | — | +| PUT ok + INSERT fail | компенсация Delete | PASS `TestCompensationWhenPostgresFailsAfterPut` | reconciler как страховка | ## Ограничения и следующие шаги -- Официальные образы MinIO/Docker Hub недоступны; закреплён community-образ coollabsio того же RELEASE — риск расхождения с upstream. -- Reconciler не чинит referenced missing (нет исходных байтов) — только детектит; восстановление из бэкапа S3 вне скоупа. -- Student-tests с in-memory blob пишут метаданные в общий Postgres без объектов в MinIO; на учебном стенде их подбирает reconciler (referenced → keep). +- Официальные образы MinIO/Docker Hub недоступны на стенде; закреплён community-образ coollabsio того же класса RELEASE + Chainguard mc — риск расхождения с upstream. При доступности Hub: `MINIO_IMAGE`/`MC_IMAGE` в `.env`. +- Reconciler не восстанавливает referenced missing (нет исходных байтов) — только детектит (exit 2); восстановление из бэкапа S3 вне скоупа. - Presigned direct upload (трек 1) не реализован — выбран трек 2. - Учебные секреты в `.env.example`; в Git не коммитить `.env`. + +Инструкция по сдаче для себя: `SUBMISSION.md`. diff --git a/SUBMISSION.md b/SUBMISSION.md new file mode 100644 index 00000000..b86f52c7 --- /dev/null +++ b/SUBMISSION.md @@ -0,0 +1,58 @@ +# Как сдать лабораторную 4 (для меня) + +Краткий чеклист перед защитой и после замечаний ревью. + +## Что уже сделано в этом PR + +- База — решение lab3 (HAProxy → API×2+, Redis-сессии, Idempotency-Key, failover). +- Lab4: приватный MinIO, метаданные в PostgreSQL, байты в S3; `POST .../attachments` → 201 ready; download через API; `attachment_ids` в сообщениях. +- Уровень 4: негативы (размер, MIME, pixels, filename, чужой чат), компенсация S3→PG, лимит concurrency + эксперимент памяти, limited S3 user, private-bucket check. +- Оценка **5**, трек **2** (reconciler): `make track2` → `evidence/track2/`. +- Публичные проверки: `make test`, `test-persistence`, `test-failover`, `make student-test`, `make private-bucket`. + +## Перед защитой (локально) + +```sh +cp .env.example .env +bash scripts/up.sh +make check +make test +make student-test +make private-bucket +make test-persistence ACTION_SCRIPT=scripts/restart.sh +make test-failover ACTION_SCRIPT=scripts/stop-one.sh +bash scripts/restore-one.sh +make track2 +# опционально (пересоздаёт API с разными UPLOAD_MAX_CONCURRENCY): +make upload-mem +``` + +Если Docker Hub недоступен для `minio/minio` — в `.env` уже стоят рабочие `MINIO_IMAGE`/`MC_IMAGE` (coollabsio + Chainguard mc). + +## Что говорить на защиту + +1. Загрузить fixture → message с `attachment_ids` → скачать вторым участником → SHA-256 совпал; третий — 404; anonymous S3 GET — 403. +2. Порядок: PUT S3 → INSERT PG → 201; при ошибке INSERT — Delete; иначе reconciler после grace. +3. Failover: `stop-one.sh` — download через другую реплику; persistence — оригинал после restart. +4. Трек 2: dry-run не меняет данные; real удаляет mature orphan; used missing — ALERT; fresh — skip; repeat — 0 deletes. +5. Память: `UPLOAD_MAX_CONCURRENCY=4` режет пик (~80 MiB) vs 64 (~170 MiB) на ~7 MiB файлах. + +## PR + +- Ветка: `solution/bpi2303-belousov` +- База PR: `mtusi2026/mtusi2026lab4` → `main` +- Заголовок: `ЛР 4 — БПИ2303 — Белоусов — на 5` +- Не коммитить `.env`, токены, volumes. +- После замечаний — пуш в ту же ветку, тот же PR. + +## Если что-то красное + +| Симптом | Что проверить | +| --- | --- | +| `pull access denied` для minio/minio | `MINIO_IMAGE`/`MC_IMAGE` в `.env` (см. `.env.example`) | +| `less than two API instances` | `bash scripts/restore-one.sh`, `API_REPLICAS=2` | +| failover видит остановленную реплику | у `api` `restart: "no"`; `stop-one.sh` делает `docker stop` | +| student-test не видит БД/S3 | порты `127.0.0.1:5432/6379/9000` | +| track2 падает на `s3sh` | образ `MC_IMAGE` с `/bin/sh` (нужен `latest-dev` у Chainguard) | + +Подробности архитектуры и таблица доказательств — в `REPORT.md`. diff --git a/cmd/reconcile/main.go b/cmd/reconcile/main.go deleted file mode 100644 index d9d15d48..00000000 --- a/cmd/reconcile/main.go +++ /dev/null @@ -1,221 +0,0 @@ -// Reconciler lab4 (трек 5 / согласованность двух хранилищ). -// -// Сверяет PostgreSQL (attachments) и приватный S3-bucket (префикс originals/). -// По умолчанию dry-run: только отчёт. Флаг -apply выполняет безопасные правки. -// -// Классы расхождений: -// -// orphan — объект в S3 без строки в БД. После grace period удаляется (-apply). -// missing — строка в БД без объекта. Если на вложение нет ссылок из сообщений -// и строка старше grace — удаляется. Ссылаемые (в сообщениях) только -// логируются: удалять их нельзя, файл уже «в истории». -// -// Свежие объекты/строки (моложе grace) не трогаются: гонка «PUT прошёл, INSERT ещё нет» -// не должна приводить к удалению чужой успешной загрузки. -package main - -import ( - "context" - "flag" - "fmt" - "log" - "os" - "os/signal" - "syscall" - "time" - - "github.com/google/uuid" - - "mtusi2026lab4/internal/auth" - "mtusi2026lab4/internal/blob" - "mtusi2026lab4/internal/config" - "mtusi2026lab4/internal/store" -) - -func main() { - apply := flag.Bool("apply", false, "apply safe fixes (default: dry-run)") - graceSec := flag.Int64("grace-seconds", -1, "override S3_RECONCILE_GRACE_SECONDS (-1 = from env)") - pageSize := flag.Int("page-size", 200, "DB page size for attachment refs") - flag.Parse() - - cfg, err := config.Load() - if err != nil { - log.Fatalf("config: %v", err) - } - grace := cfg.ReconcileGrace - if *graceSec >= 0 { - grace = time.Duration(*graceSec) * time.Second - } - s3cfg, err := config.LoadS3() - if err != nil { - log.Fatalf("s3 config: %v", err) - } - - ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, syscall.SIGINT) - defer stop() - - hasher, err := auth.NewHasher() - if err != nil { - log.Fatalf("hasher: %v", err) - } - st, err := store.Open(ctx, cfg.DatabaseURL, hasher, cfg.MaxConns) - if err != nil { - log.Fatalf("postgres: %v", err) - } - defer st.Close() - - bl, err := blob.New(blob.Config{ - Endpoint: s3cfg.Endpoint, - UseSSL: s3cfg.UseSSL, - Region: s3cfg.Region, - Bucket: s3cfg.Bucket, - AccessKey: s3cfg.AccessKey, - SecretKey: s3cfg.SecretKey, - }) - if err != nil { - log.Fatalf("s3: %v", err) - } - if err := bl.Ping(ctx); err != nil { - log.Fatalf("s3 ping: %v", err) - } - - mode := "dry-run" - if *apply { - mode = "apply" - } - log.Printf("reconcile start mode=%s grace=%s bucket=%s page=%d", mode, grace, s3cfg.Bucket, *pageSize) - - started := time.Now() - rep, err := run(ctx, st, bl, grace, *pageSize, *apply) - if err != nil { - log.Fatalf("reconcile: %v", err) - } - elapsed := time.Since(started) - - fmt.Printf("reconcile_report mode=%s elapsed_ms=%d\n", mode, elapsed.Milliseconds()) - fmt.Printf("s3_objects=%d db_rows=%d\n", rep.S3Objects, rep.DBRows) - fmt.Printf("orphans_found=%d orphans_deleted=%d orphans_skipped_fresh=%d\n", - rep.OrphansFound, rep.OrphansDeleted, rep.OrphansSkippedFresh) - fmt.Printf("missing_found=%d missing_deleted=%d missing_referenced=%d missing_skipped_fresh=%d\n", - rep.MissingFound, rep.MissingDeleted, rep.MissingReferenced, rep.MissingSkippedFresh) - for _, line := range rep.Details { - fmt.Println(line) - } - os.Exit(0) -} - -type report struct { - S3Objects int - DBRows int - OrphansFound int - OrphansDeleted int - OrphansSkippedFresh int - MissingFound int - MissingDeleted int - MissingReferenced int - MissingSkippedFresh int - Details []string -} - -func run(ctx context.Context, st *store.Store, bl *blob.Client, grace time.Duration, pageSize int, apply bool) (*report, error) { - if pageSize < 1 || pageSize > 1000 { - pageSize = 200 - } - rep := &report{} - cutoff := time.Now().UTC().Add(-grace) - - objs, err := bl.ListKeys(ctx, blob.KeyPrefix) - if err != nil { - return nil, fmt.Errorf("list s3: %w", err) - } - rep.S3Objects = len(objs) - byKey := make(map[string]blob.ObjectInfo, len(objs)) - for _, o := range objs { - byKey[o.Key] = o - } - - dbKeys := make(map[string]store.AttachmentRef) - var after uuid.UUID - for { - page, err := st.ListAttachmentRefs(ctx, after, pageSize) - if err != nil { - return nil, fmt.Errorf("list db: %w", err) - } - if len(page) == 0 { - break - } - for _, r := range page { - dbKeys[r.ObjectKey] = r - rep.DBRows++ - after = r.ID - } - if len(page) < pageSize { - break - } - } - - // orphan: S3 без строки - for key, o := range byKey { - if _, ok := dbKeys[key]; ok { - continue - } - rep.OrphansFound++ - if o.LastModified.After(cutoff) { - rep.OrphansSkippedFresh++ - rep.Details = append(rep.Details, fmt.Sprintf("orphan_skip_fresh key=%s age<%s", key, grace)) - continue - } - // Повторная проверка: загрузка могла успеть записать строку после ListKeys. - exists, err := st.AttachmentKeyExists(ctx, key) - if err != nil { - return nil, err - } - if exists { - rep.Details = append(rep.Details, fmt.Sprintf("orphan_race_gone key=%s", key)) - continue - } - if apply { - if err := bl.Delete(ctx, key); err != nil { - return nil, fmt.Errorf("delete orphan %s: %w", key, err) - } - rep.OrphansDeleted++ - rep.Details = append(rep.Details, fmt.Sprintf("orphan_deleted key=%s size=%d", key, o.Size)) - } else { - rep.Details = append(rep.Details, fmt.Sprintf("orphan_would_delete key=%s size=%d", key, o.Size)) - } - } - - // missing: строка без объекта - for key, ref := range dbKeys { - if _, ok := byKey[key]; ok { - continue - } - rep.MissingFound++ - if ref.CreatedAt.After(cutoff) { - rep.MissingSkippedFresh++ - rep.Details = append(rep.Details, fmt.Sprintf("missing_skip_fresh id=%s key=%s", ref.ID, key)) - continue - } - if ref.Referenced { - rep.MissingReferenced++ - rep.Details = append(rep.Details, fmt.Sprintf("missing_referenced id=%s key=%s (kept)", ref.ID, key)) - continue - } - if apply { - ok, err := st.DeleteUnreferencedAttachment(ctx, ref.ID) - if err != nil { - return nil, fmt.Errorf("delete missing meta %s: %w", ref.ID, err) - } - if ok { - rep.MissingDeleted++ - rep.Details = append(rep.Details, fmt.Sprintf("missing_deleted id=%s key=%s", ref.ID, key)) - } else { - rep.MissingReferenced++ - rep.Details = append(rep.Details, fmt.Sprintf("missing_race_referenced id=%s key=%s", ref.ID, key)) - } - } else { - rep.Details = append(rep.Details, fmt.Sprintf("missing_would_delete id=%s key=%s", ref.ID, key)) - } - } - return rep, nil -} diff --git a/cmd/s3bootstrap/main.go b/cmd/s3bootstrap/main.go deleted file mode 100644 index a614cb0a..00000000 --- a/cmd/s3bootstrap/main.go +++ /dev/null @@ -1,123 +0,0 @@ -// Одноразовый bootstrap приватного S3-bucket и app-пользователя с ограниченной политикой. -// Нужен, потому что публичные образы minio/mc с Docker Hub сняты; admin API вызываем из Go. -package main - -import ( - "context" - "fmt" - "log" - "os" - "strings" - "time" - - "github.com/minio/madmin-go/v3" - "github.com/minio/minio-go/v7" - "github.com/minio/minio-go/v7/pkg/credentials" -) - -func main() { - endpoint := env("MINIO_ENDPOINT", "minio:9000") - endpoint = strings.TrimPrefix(strings.TrimPrefix(endpoint, "https://"), "http://") - rootUser := mustEnv("MINIO_ROOT_USER") - rootPass := mustEnv("MINIO_ROOT_PASSWORD") - bucket := env("S3_BUCKET", "messenger-attachments") - appKey := mustEnv("S3_ACCESS_KEY_ID") - appSecret := mustEnv("S3_SECRET_ACCESS_KEY") - useSSL := env("S3_USE_SSL", "0") == "1" || strings.EqualFold(env("S3_USE_SSL", "0"), "true") - - ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) - defer cancel() - - mc, err := minio.New(endpoint, &minio.Options{ - Creds: credentials.NewStaticV4(rootUser, rootPass, ""), - Secure: useSSL, - }) - if err != nil { - log.Fatalf("minio client: %v", err) - } - - deadline := time.Now().Add(90 * time.Second) - for { - ok, err := mc.BucketExists(ctx, bucket) - if err == nil { - if !ok { - if err := mc.MakeBucket(ctx, bucket, minio.MakeBucketOptions{}); err != nil { - code := minio.ToErrorResponse(err).Code - if code != "BucketAlreadyOwnedByYou" && code != "BucketAlreadyExists" { - log.Fatalf("make bucket: %v", err) - } - } - } - break - } - if time.Now().After(deadline) { - log.Fatalf("minio not ready: %v", err) - } - log.Printf("waiting for minio: %v", err) - time.Sleep(time.Second) - } - - // Явно запрещаем анонимный доступ (на случай, если кто-то выставил public). - if err := mc.SetBucketPolicy(ctx, bucket, ""); err != nil { - log.Printf("clear bucket policy: %v (продолжаем)", err) - } - - admin, err := madmin.NewWithOptions(endpoint, &madmin.Options{ - Creds: credentials.NewStaticV4(rootUser, rootPass, ""), - Secure: useSSL, - }) - if err != nil { - log.Fatalf("madmin: %v", err) - } - - policyName := "app-attachments" - policy := fmt.Sprintf(`{ - "Version": "2012-10-17", - "Statement": [ - { - "Effect": "Allow", - "Action": ["s3:ListBucket"], - "Resource": ["arn:aws:s3:::%s"] - }, - { - "Effect": "Allow", - "Action": ["s3:GetObject", "s3:PutObject", "s3:DeleteObject"], - "Resource": ["arn:aws:s3:::%s/*"] - } - ] -}`, bucket, bucket) - - if err := admin.AddCannedPolicy(ctx, policyName, []byte(policy)); err != nil { - // Уже существует — ок. - log.Printf("add policy: %v", err) - } - if err := admin.AddUser(ctx, appKey, appSecret); err != nil { - log.Printf("add user: %v", err) - } - if _, err := admin.AttachPolicy(ctx, madmin.PolicyAssociationReq{ - Policies: []string{policyName}, - User: appKey, - }); err != nil { - // Старые версии madmin: SetPolicy - if err2 := admin.SetPolicy(ctx, policyName, appKey, false); err2 != nil { - log.Fatalf("attach policy: %v / set policy: %v", err, err2) - } - } - - log.Printf("bootstrap ok bucket=%s app_user=%s private=yes", bucket, appKey) -} - -func env(k, def string) string { - if v := strings.TrimSpace(os.Getenv(k)); v != "" { - return v - } - return def -} - -func mustEnv(k string) string { - v := strings.TrimSpace(os.Getenv(k)) - if v == "" { - log.Fatalf("missing %s", k) - } - return v -} diff --git a/cmd/server/main.go b/cmd/server/main.go index a700e95f..c612b60a 100644 --- a/cmd/server/main.go +++ b/cmd/server/main.go @@ -1,14 +1,25 @@ -// Точка входа HTTP API и одноразового мигратора lab4. +// Точка входа HTTP API, одноразового мигратора и reconciler (lab4). // // Режимы: // -// (по умолчанию) — API-реплика: Postgres + Redis + S3, миграции НЕ применяет; -// -migrate — применить SQL и выйти (S3 не нужен); -// -healthcheck — локальный probe /health/ready. +// (по умолчанию) — 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" @@ -21,15 +32,19 @@ import ( "mtusi2026lab4/internal/api" "mtusi2026lab4/internal/auth" - "mtusi2026lab4/internal/blob" "mtusi2026lab4/internal/config" + "mtusi2026lab4/internal/objectstore" + "mtusi2026lab4/internal/reconcile" "mtusi2026lab4/internal/session" "mtusi2026lab4/internal/store" ) func main() { healthcheck := flag.Bool("healthcheck", false, "probe local /health/ready and exit") - migrateOnly := flag.Bool("migrate", false, "apply SQL migrations 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()) @@ -53,49 +68,66 @@ func main() { } 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() - s3cfg, err := config.LoadS3() - if err != nil { - log.Fatalf("s3 config: %v", err) - } - blobs, err := waitS3(rootCtx, s3cfg) - if err != nil { - log.Fatalf("s3: %v", err) + // API стартует только при доступном S3 и существующем bucket; затем доступность + // контролирует /health/ready (недоступный S3 → 503). + if err := waitBucket(rootCtx, objects); err != nil { + log.Fatalf("bucket: %v", err) } - srvAPI := api.New(st, sessions, blobs, cfg.InstanceID) - srvAPI.MaxUploadBytes = cfg.MaxUploadBytes - srvAPI.MaxImagePixels = cfg.MaxImagePixels - + srvAPI := api.New(st, sessions, objects, cfg.InstanceID).WithUploadConcurrency(cfg.UploadMaxConcurrency) httpServer := &http.Server{ Addr: cfg.Addr(), Handler: srvAPI.Handler(), ReadHeaderTimeout: 5 * time.Second, - // Upload до 10 MiB: даём запас на медленный клиент. - ReadTimeout: 60 * time.Second, - WriteTimeout: 60 * 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 bucket=%s", - cfg.Addr(), cfg.Env, cfg.InstanceID, cfg.SessionTTL, cfg.MaxConns, s3cfg.Bucket) + 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 } @@ -117,6 +149,54 @@ func main() { 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 @@ -159,38 +239,6 @@ func waitRedis(ctx context.Context, redisURL string, ttl time.Duration) (*sessio } } -func waitS3(ctx context.Context, cfg config.S3) (*blob.Client, error) { - deadline := time.Now().Add(45 * time.Second) - var last error - for { - c, err := blob.New(blob.Config{ - Endpoint: cfg.Endpoint, - UseSSL: cfg.UseSSL, - Region: cfg.Region, - Bucket: cfg.Bucket, - AccessKey: cfg.AccessKey, - SecretKey: cfg.SecretKey, - }) - if err == nil { - if err = c.Ping(ctx); err == nil { - return c, nil - } - last = err - } else { - last = err - } - if ctx.Err() != nil || time.Now().After(deadline) { - return nil, last - } - log.Printf("s3 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 { diff --git a/compose.yaml b/compose.yaml index 7eac7ce6..d08da63b 100644 --- a/compose.yaml +++ b/compose.yaml @@ -1,7 +1,15 @@ -# Локальный стенд lab4: Клиент → HAProxy → API×N → PostgreSQL + Redis + приватный MinIO. -# Публикуется только LB (:8080). Порты API наружу не публикуются. -# MinIO API на 127.0.0.1:9000 — только для локальной проверки private bucket; консоль не публикуется. -# Запуск: bash scripts/up.sh +# Локальный стенд lab4: Клиент → HAProxy → API×N → общие PostgreSQL, Redis и приватный S3 (MinIO). +# Публикуется только LB (:8080) и S3 API на 127.0.0.1:9000 (нужен лишь для проверки +# «приватный bucket недоступен без подписи» и для student-tests с хоста). +# Консоль MinIO ОТКЛЮЧЕНА (MINIO_BROWSER=off) и порт 9001 не публикуется вообще. +# Порты API наружу не публикуются. +# Запуск: bash scripts/up.sh (minio+minio-init → миграции → --scale api=N → lb) +# container_name не задаём: иначе --scale одного сервиса невозможен. +# +# Образы MinIO/mc закреплены точными тегами (через переменные только на случай, если +# реестр отдаёт другой образ: см. REPORT). Root-учётка MinIO нужна ТОЛЬКО сервису minio +# и одноразовому minio-init. API/migrate/reconcile живут на отдельном пользователе +# messenger-api с политикой только на bucket messenger. x-api-env: &api-env APP_HOST: 0.0.0.0 APP_PORT: 8080 @@ -12,15 +20,18 @@ x-api-env: &api-env 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 - MAX_UPLOAD_BYTES: ${MAX_UPLOAD_BYTES:-10485760} - MAX_IMAGE_PIXELS: ${MAX_IMAGE_PIXELS:-40000000} - S3_ENDPOINT: ${S3_ENDPOINT:-minio:9000} - S3_USE_SSL: ${S3_USE_SSL:-0} + # --- lab4: S3 (не root-учётка!) --- + S3_ENDPOINT: http://minio:9000 S3_REGION: ${S3_REGION:-us-east-1} - S3_BUCKET: ${S3_BUCKET:-messenger-attachments} - S3_ACCESS_KEY_ID: ${S3_ACCESS_KEY_ID:-messenger-app} - S3_SECRET_ACCESS_KEY: ${S3_SECRET_ACCESS_KEY:-messenger-app-secret} - S3_RECONCILE_GRACE_SECONDS: ${S3_RECONCILE_GRACE_SECONDS:-60} + 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} + # Мягкий лимит кучи Go ниже cgroup-лимита контейнера (API_MEMORY): GC становится агрессивнее + # до OOM-kill, а не после него. + GOMEMLIMIT: ${API_GOMEMLIMIT:-200MiB} services: postgres: @@ -32,7 +43,7 @@ services: volumes: - pgdata:/var/lib/postgresql/data ports: - - "127.0.0.1:5432:5432" + - "127.0.0.1:${POSTGRES_HOST_PORT:-5432}:5432" healthcheck: test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER:-messenger} -d ${POSTGRES_DB:-messenger}"] interval: 5s @@ -51,7 +62,7 @@ services: volumes: - redisdata:/data ports: - - "127.0.0.1:6379:6379" + - "127.0.0.1:${REDIS_HOST_PORT:-6379}:6379" healthcheck: test: ["CMD", "redis-cli", "ping"] interval: 5s @@ -64,52 +75,102 @@ services: cpus: "0.50" memory: 256M - # Публичные minio/minio с Docker Hub сняты (2026). Собираем из community-образа - # ghcr.io/coollabsio/minio — бинарь последнего community RELEASE. + # Приватный S3. Данные — в именованном volume mindata (переживает restart и down без -v). minio: - image: ghcr.io/coollabsio/minio:RELEASE.2025-10-15T17-29-55Z - command: ["server", "/data", "--address", ":9000", "--console-address", ":9001"] + # По умолчанию — pinned community-образ (официальный minio/minio на Docker Hub + # из этой среды недоступен: pull access denied). Переопределение: MINIO_IMAGE. + 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:-minioadmin} - MINIO_ROOT_PASSWORD: ${MINIO_ROOT_PASSWORD:-minioadmin-secret} + # Root-учётка: только для самого сервера и minio-init. API её не получает. + MINIO_ROOT_USER: ${MINIO_ROOT_USER:-minio-root} + MINIO_ROOT_PASSWORD: ${MINIO_ROOT_PASSWORD:-minio-root-secret-change-me} + # Консоль отключена полностью: порт 9001 не слушается и не публикуется. + MINIO_BROWSER: "off" volumes: - - miniodata:/data + - mindata:/data ports: - - "127.0.0.1:9000:9000" - # Консоль :9001 намеренно не публикуется (уровень 4). - # В образе нет curl; TCP-probe + bootstrap ретраит MakeBucket. + # Только loopback хоста (для scripts/check_private_bucket.sh и student-tests). + - "127.0.0.1:${MINIO_HOST_PORT:-9000}:9000" healthcheck: - test: ["CMD", "bash", "-c", "exec 3<>/dev/tcp/127.0.0.1/9000"] - interval: 5s + # coollabsio/minio и официальный образ содержат mc; curl есть не везде — + # сначала mc ready, затем HTTP health (если curl доступен). + 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: 10s + start_period: 5s stop_grace_period: 10s deploy: resources: limits: - cpus: "0.50" + cpus: "1.0" memory: 512M - # Bootstrap без mc: бинарь /s3bootstrap из нашего образа (minio-go + madmin). + # Одноразовый bootstrap S3 (идемпотентный, можно запускать сколько угодно раз): + # 1) приватный bucket (mb --ignore-existing + anonymous none); + # 2) политика messenger-api-rw ТОЛЬКО на этот bucket (без CreateBucket/admin-прав); + # 3) пользователь messenger-api с секретом из окружения и привязка политики; + # 4) самопроверка: политика действительно привязана, иначе контейнер падает. minio-init: - build: . - entrypoint: ["/s3bootstrap"] + # latest-dev — с /bin/sh (нужен entrypoint-override в up/s3sh). При доступности + # Docker Hub можно заменить на minio/mc:RELEASE.2024-11-21T17-21-54Z. + image: ${MC_IMAGE:-cgr.dev/chainguard/minio-client:latest-dev} + entrypoint: ["/bin/sh", "-c"] environment: - MINIO_ENDPOINT: minio:9000 - MINIO_ROOT_USER: ${MINIO_ROOT_USER:-minioadmin} - MINIO_ROOT_PASSWORD: ${MINIO_ROOT_PASSWORD:-minioadmin-secret} - S3_BUCKET: ${S3_BUCKET:-messenger-attachments} - S3_ACCESS_KEY_ID: ${S3_ACCESS_KEY_ID:-messenger-app} - S3_SECRET_ACCESS_KEY: ${S3_SECRET_ACCESS_KEY:-messenger-app-secret} - S3_USE_SSL: ${S3_USE_SSL:-0} + 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" - healthcheck: - disable: true + deploy: + resources: + limits: + memory: 128M + # Одноразовый мигратор. Не в depends_on API: иначе compose спотыкается о restart:no. + # Запускается явно из scripts/up.sh: docker compose run --rm migrate + # Заодно идемпотентно проверяет, что bucket существует. migrate: build: . command: ["-migrate"] @@ -118,6 +179,31 @@ services: 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 + + # Reconciler трека 2: /server -reconcile [-reconcile-dry-run] [-reconcile-prune-missing]. + # Запуск по требованию (profile tools, не стартует с up): + # docker compose run --rm reconcile -reconcile-dry-run + reconcile: + build: . + command: ["-reconcile"] + environment: + <<: *api-env + depends_on: + postgres: + condition: service_healthy + minio: + condition: service_healthy + profiles: ["tools"] restart: "no" healthcheck: disable: true @@ -149,6 +235,8 @@ services: retries: 10 start_period: 15s stop_grace_period: 10s + # no: иначе после docker stop в stop-one.sh демон может снова поднять реплику, + # и failover-тест увидит TARGET_INSTANCE_ID среди живых ответов. restart: "no" deploy: resources: @@ -156,31 +244,12 @@ services: cpus: ${API_CPUS:-0.50} memory: ${API_MEMORY:-256M} - reconcile: - build: . - entrypoint: ["/reconcile"] - environment: - <<: *api-env - depends_on: - postgres: - condition: service_healthy - minio: - condition: service_healthy - minio-init: - condition: service_completed_successfully - restart: "no" - deploy: - resources: - limits: - cpus: "0.50" - 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:8080:8080" + - "127.0.0.1:${LB_HOST_PORT:-8080}:8080" depends_on: api: condition: service_healthy @@ -200,4 +269,4 @@ services: volumes: pgdata: redisdata: - miniodata: + mindata: 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/concurrent-uploads.txt b/evidence/concurrent-uploads.txt deleted file mode 100644 index 6769b38a..00000000 --- a/evidence/concurrent-uploads.txt +++ /dev/null @@ -1,8 +0,0 @@ -concurrent=12 -upload_bytes=3147060 -ok_201=12 -results=[201, 201, 201, 201, 201, 201, 201, 201, 201, 201, 201, 201] -elapsed_s=1.717 -api_rss_kb_before=96654 -api_rss_kb_peak=98006 -api_rss_kb_after=97197 diff --git a/evidence/failover.txt b/evidence/failover.txt index a4c73971..30d530ff 100644 --- a/evidence/failover.txt +++ b/evidence/failover.txt @@ -1,4 +1,6 @@ python3 tests/resilience.py --mode failover --action-script "scripts/stop-one.sh" --base-url "http://localhost:8080" Executing explicit failover hook; hook output suppressed to avoid leaking secrets. -{"observed_instances_before": 2, "successful_writes": 112, "failed_attempts": 1, "first_recovery_seconds": 2.928} +{"observed_instances_before": 2, "successful_writes": 111, "failed_attempts": 1, "first_recovery_seconds": 2.809} PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence. + Container mtusi2026lab4-api-1 Running + Container mtusi2026lab4-api-2 Running diff --git a/evidence/private-bucket.txt b/evidence/private-bucket.txt index 08767083..2c181aca 100644 --- a/evidence/private-bucket.txt +++ b/evidence/private-bucket.txt @@ -1,2 +1,21 @@ -GET http://127.0.0.1:9000/messenger-attachments/originals/does-not-exist → HTTP 403 body_bytes=381 -PASS: anonymous access denied (HTTP 403) +== подготовка: загрузить реальное вложение через API и узнать его object_key +attachment=eeac261a-a963-44ae-b34d-0638cef7fb30 (ключ в 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 9000 tcp}] +PASS в Publishers нет 9001 +PASS S3 API только на 127.0.0.1 +ИТОГ: bucket приватный diff --git a/evidence/reconcile.txt b/evidence/reconcile.txt deleted file mode 100644 index 61d55664..00000000 --- a/evidence/reconcile.txt +++ /dev/null @@ -1,129 +0,0 @@ -=== seed orphan object via root PutObject (python/minio not required: curl+aws style via go) === -orphan_put 200 -=== seed missing metadata (DB row, no S3 object) === -DO -=== dry-run grace=0 === -#1 [internal] load local bake definitions -#1 reading from stdin 683B done -#1 DONE 0.0s - -#2 [internal] load build definition from Dockerfile -#2 transferring dockerfile: 927B done -#2 DONE 0.0s - -#3 resolve image config for docker-image://docker.io/docker/dockerfile:1.7 -#3 DONE 1.0s - -#4 docker-image://docker.io/docker/dockerfile:1.7@sha256:a57df69d0ea827fb7266491f2813635de6f17269be881f696fbfdf2d83dda33e -#4 resolve docker.io/docker/dockerfile:1.7@sha256:a57df69d0ea827fb7266491f2813635de6f17269be881f696fbfdf2d83dda33e done -#4 CACHED - -#5 [internal] load metadata for docker.io/library/golang:1.24.2-bookworm -#5 DONE 0.6s - -#6 [internal] load metadata for gcr.io/distroless/static-debian12:nonroot -#6 DONE 0.7s - -#7 [internal] load .dockerignore -#7 transferring context: 196B done -#7 DONE 0.0s - -#8 [stage-1 1/4] FROM gcr.io/distroless/static-debian12:nonroot@sha256:afa5c872c891853ca7fcf1f12c3edb23f7eeef36189728842dd51042ff57f7ab -#8 resolve gcr.io/distroless/static-debian12:nonroot@sha256:afa5c872c891853ca7fcf1f12c3edb23f7eeef36189728842dd51042ff57f7ab 0.0s done -#8 DONE 0.0s - -#9 [build 1/9] FROM docker.io/library/golang:1.24.2-bookworm@sha256:79390b5e5af9ee6e7b1173ee3eac7fadf6751a545297672916b59bfa0ecf6f71 -#9 resolve docker.io/library/golang:1.24.2-bookworm@sha256:79390b5e5af9ee6e7b1173ee3eac7fadf6751a545297672916b59bfa0ecf6f71 0.0s done -#9 DONE 0.0s - -#10 [internal] load build context -#10 transferring context: 1.21kB 0.0s done -#10 DONE 0.0s - -#11 [stage-1 2/4] COPY --from=build /out/server /server -#11 CACHED - -#12 [stage-1 3/4] COPY --from=build /out/reconcile /reconcile -#12 CACHED - -#13 [build 6/9] COPY internal ./internal -#13 CACHED - -#14 [build 4/9] RUN go mod download -#14 CACHED - -#15 [build 2/9] WORKDIR /src -#15 CACHED - -#16 [build 8/9] RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags="-s -w" -o /out/reconcile ./cmd/reconcile -#16 CACHED - -#17 [build 9/9] RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags="-s -w" -o /out/s3bootstrap ./cmd/s3bootstrap -#17 CACHED - -#18 [build 3/9] COPY go.mod go.sum ./ -#18 CACHED - -#19 [build 5/9] COPY cmd ./cmd -#19 CACHED - -#20 [build 7/9] RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags="-s -w" -o /out/server ./cmd/server -#20 CACHED - -#21 [stage-1 4/4] COPY --from=build /out/s3bootstrap /s3bootstrap -#21 CACHED - -#22 exporting to image -#22 exporting layers 0.0s done -#22 exporting manifest sha256:b3e7db748d123d1baf965ab1e27b5d2a2bea64f3e68fe93798166da5c67b58f3 0.1s done -#22 exporting config sha256:76f75b546642e6ee2a4f055c5a45f1f406f5698112cd37c26b7301bcdcf8839f -#22 exporting config sha256:76f75b546642e6ee2a4f055c5a45f1f406f5698112cd37c26b7301bcdcf8839f 0.0s done -#22 exporting attestation manifest sha256:a877a0a7985478d45981bc5e291b0bc16bf401bfedfe03691ee01f5f50cf1606 -#22 exporting attestation manifest sha256:a877a0a7985478d45981bc5e291b0bc16bf401bfedfe03691ee01f5f50cf1606 0.0s done -#22 exporting manifest list sha256:e53705a39a996dc932198dc966f069d8bb83bba703dbcb6db0fe25d733a4fab7 0.0s done -#22 naming to docker.io/library/mtusi2026lab4-reconcile:latest done -#22 unpacking to docker.io/library/mtusi2026lab4-reconcile:latest done -#22 DONE 0.4s - -#23 resolving provenance for metadata file -#23 DONE 0.0s -2026/11/12 15:06:31 reconcile start mode=dry-run grace=0s bucket=messenger-attachments page=200 -reconcile_report mode=dry-run elapsed_ms=33 -s3_objects=16 db_rows=19 -orphans_found=1 orphans_deleted=0 orphans_skipped_fresh=0 -missing_found=4 missing_deleted=0 missing_referenced=2 missing_skipped_fresh=0 -orphan_would_delete key=originals/00000000-0000-4000-8000-0000000000aa size=12 -missing_referenced id=867bc3f8-3656-4138-a787-b5fc8fc85498 key=originals/867bc3f8-3656-4138-a787-b5fc8fc85498 (kept) -missing_referenced id=cd3c2ce1-b4fb-4229-99e7-356d5ffb4d8b key=originals/cd3c2ce1-b4fb-4229-99e7-356d5ffb4d8b (kept) -missing_would_delete id=ad7a23e7-aa2a-4c95-8d17-52394f8ebfd2 key=originals/ad7a23e7-aa2a-4c95-8d17-52394f8ebfd2 -missing_would_delete id=11111111-1111-4111-8111-111111111111 key=originals/11111111-1111-4111-8111-111111111111 -=== apply grace=0 === -2026/11/12 15:06:33 reconcile start mode=apply grace=0s bucket=messenger-attachments page=200 -reconcile_report mode=apply elapsed_ms=17 -s3_objects=16 db_rows=19 -orphans_found=1 orphans_deleted=1 orphans_skipped_fresh=0 -missing_found=4 missing_deleted=2 missing_referenced=2 missing_skipped_fresh=0 -orphan_deleted key=originals/00000000-0000-4000-8000-0000000000aa size=12 -missing_referenced id=867bc3f8-3656-4138-a787-b5fc8fc85498 key=originals/867bc3f8-3656-4138-a787-b5fc8fc85498 (kept) -missing_deleted id=ad7a23e7-aa2a-4c95-8d17-52394f8ebfd2 key=originals/ad7a23e7-aa2a-4c95-8d17-52394f8ebfd2 -missing_referenced id=cd3c2ce1-b4fb-4229-99e7-356d5ffb4d8b key=originals/cd3c2ce1-b4fb-4229-99e7-356d5ffb4d8b (kept) -missing_deleted id=11111111-1111-4111-8111-111111111111 key=originals/11111111-1111-4111-8111-111111111111 -=== second apply (idempotent) === -2026/11/12 15:06:34 reconcile start mode=apply grace=0s bucket=messenger-attachments page=200 -reconcile_report mode=apply elapsed_ms=7 -s3_objects=15 db_rows=17 -orphans_found=0 orphans_deleted=0 orphans_skipped_fresh=0 -missing_found=2 missing_deleted=0 missing_referenced=2 missing_skipped_fresh=0 -missing_referenced id=cd3c2ce1-b4fb-4229-99e7-356d5ffb4d8b key=originals/cd3c2ce1-b4fb-4229-99e7-356d5ffb4d8b (kept) -missing_referenced id=867bc3f8-3656-4138-a787-b5fc8fc85498 key=originals/867bc3f8-3656-4138-a787-b5fc8fc85498 (kept) -=== fresh orphan skipped with default grace === -fresh_put 200 -2026/11/12 15:06:35 reconcile start mode=dry-run grace=1m0s bucket=messenger-attachments page=200 -reconcile_report mode=dry-run elapsed_ms=13 -s3_objects=16 db_rows=17 -orphans_found=1 orphans_deleted=0 orphans_skipped_fresh=1 -missing_found=2 missing_deleted=0 missing_referenced=0 missing_skipped_fresh=2 -orphan_skip_fresh key=originals/00000000-0000-4000-8000-0000000000bb age<1m0s -missing_skip_fresh id=cd3c2ce1-b4fb-4229-99e7-356d5ffb4d8b key=originals/cd3c2ce1-b4fb-4229-99e7-356d5ffb4d8b -missing_skip_fresh id=867bc3f8-3656-4138-a787-b5fc8fc85498 key=originals/867bc3f8-3656-4138-a787-b5fc8fc85498 -wrote evidence/reconcile.txt diff --git a/evidence/stack-notes.txt b/evidence/stack-notes.txt new file mode 100644 index 00000000..90523dbd --- /dev/null +++ b/evidence/stack-notes.txt @@ -0,0 +1,9 @@ +Evidence снят на стенде compose-проекта mtusi2026lab4 (2026-11-12). +Образы MinIO: официальные minio/minio и minio/mc на Docker Hub недоступны +(pull access denied), поэтому закреплены: + MINIO_IMAGE=ghcr.io/coollabsio/minio:RELEASE.2025-10-15T17-29-55Z + MC_IMAGE=cgr.dev/chainguard/minio-client:latest-dev +Остальные: postgres:16.6, redis:7.4.1, haproxy:2.9.14-alpine, сборка Dockerfile +(golang:1.23.8-bookworm → distroless/static-debian12:nonroot). +S3 SDK в приложении: aws-sdk-go-v2 (internal/objectstore), не minio-go. +Прогоны: make check/test/student-test/private-bucket/test-persistence/test-failover/track2/upload-mem — PASS. diff --git a/evidence/student-tests.txt b/evidence/student-tests.txt index 3e6b06d0..ccf27737 100644 --- a/evidence/student-tests.txt +++ b/evidence/student-tests.txt @@ -1,250 +1,460 @@ -DATABASE_URL=postgres://messenger:messenger@127.0.0.1:5432/messenger?sslmode=disable \ - REDIS_URL=redis://127.0.0.1:6379/0 \ - go test ./student-tests/ -count=1 -v +DATABASE_URL="${DATABASE_URL:-postgres://messenger:messenger@127.0.0.1:5432/messenger?sslmode=disable}" \ + REDIS_URL="${REDIS_URL:-redis://127.0.0.1:6379/0}" \ + S3_ENDPOINT="${S3_ENDPOINT:-http://127.0.0.1:9000}" \ + 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:76: → битый JSON, хвост после объекта, лишнее поле, пустой текст, чужой чат -2026/11/12 18:06:18 method=POST path=/api/v1/users status=400 request_id=8c1902bd-a429-4b6c-9a41-39b3dc20c4e8 duration_ms=0 - api_test.go:79: status=400 body={"error":{"code":"invalid_request","message":"malformed json","request_id":"8c1902bd-a429-4b6c-9a41-39b3dc20c4e8"}} -2026/11/12 18:06:18 method=POST path=/api/v1/users status=400 request_id=f01f3adb-78bb-4722-8c40-fcb5939899ec duration_ms=0 - api_test.go:86: status=400 body={"error":{"code":"invalid_request","message":"malformed json","request_id":"f01f3adb-78bb-4722-8c40-fcb5939899ec"}} -2026/11/12 18:06:18 method=POST path=/api/v1/users status=201 request_id=50bdc461-ab51-4108-9e5c-58495ab5edeb duration_ms=52 - api_test.go:91: создан ok_user_327b0fdb id=926f8271-4f8e-4379-b69b-e424e83919d7 -2026/11/12 18:06:18 method=POST path=/api/v1/auth/sessions status=201 request_id=4483c457-abce-4d52-9d97-df7fe1ceed40 duration_ms=39 - api_test.go:92: сессия выпущена, длина токена=64 (значение не печатаем) -2026/11/12 18:06:18 method=POST path=/api/v1/chats status=201 request_id=5ee4d4df-80bf-4212-9b11-15a8beaa22d8 duration_ms=8 -2026/11/12 18:06:18 method=POST path=/api/v1/chats/85991ce8-09f4-48c6-80eb-171e80d344d4/messages status=400 request_id=788d8cb8-5474-470e-b39c-d7fce6962987 duration_ms=3 - api_test.go:99: status=400 body={"error":{"code":"invalid_request","message":"malformed json","request_id":"788d8cb8-5474-470e-b39c-d7fce6962987"}} -2026/11/12 18:06:18 method=POST path=/api/v1/chats/85991ce8-09f4-48c6-80eb-171e80d344d4/messages status=400 request_id=d4632ebb-a886-4338-8372-5d73e2239842 duration_ms=0 - api_test.go:99: status=400 body={"error":{"code":"invalid_request","message":"malformed json","request_id":"d4632ebb-a886-4338-8372-5d73e2239842"}} -2026/11/12 18:06:18 method=POST path=/api/v1/chats/85991ce8-09f4-48c6-80eb-171e80d344d4/messages status=400 request_id=09b6498f-3e15-49b7-9266-ecf84d2a7916 duration_ms=0 - api_test.go:106: status=400 body={"error":{"code":"invalid_request","message":"invalid text","request_id":"09b6498f-3e15-49b7-9266-ecf84d2a7916"}} -2026/11/12 18:06:18 method=POST path=/api/v1/users status=201 request_id=87a631af-6c30-46eb-a783-5b81d3db8d7e duration_ms=36 - api_test.go:111: создан outsider_24331385 id=225d868f-362a-41d4-996b-1881ccf6cd8a -2026/11/12 18:06:18 method=POST path=/api/v1/auth/sessions status=201 request_id=168ea6f0-a4b0-44fa-b272-3ca6fa92fdb8 duration_ms=35 + api_test.go:96: → битый JSON, хвост после объекта, лишнее поле, пустой текст, чужой чат +2026/11/12 18:20:59 method=POST path=/api/v1/users status=400 request_id=fa0e0154-7179-46f6-a79e-40b9f96bc7f6 duration_ms=0 + api_test.go:99: status=400 body={"error":{"code":"invalid_request","message":"malformed json","request_id":"fa0e0154-7179-46f6-a79e-40b9f96bc7f6"}} +2026/11/12 18:20:59 method=POST path=/api/v1/users status=400 request_id=a8fac635-4393-45c5-86c7-e7590eecfa9d duration_ms=0 + api_test.go:106: status=400 body={"error":{"code":"invalid_request","message":"malformed json","request_id":"a8fac635-4393-45c5-86c7-e7590eecfa9d"}} +2026/11/12 18:20:59 method=POST path=/api/v1/users status=201 request_id=b5966c7b-18bb-4655-bd59-f1ca02ec3d1d duration_ms=33 + api_test.go:111: создан ok_user_1c171dca id=3003e48f-ecc3-4ca2-97ab-5877b345771c +2026/11/12 18:20:59 method=POST path=/api/v1/auth/sessions status=201 request_id=354d5646-2f2f-4e59-a07c-8a03e5e81d5d duration_ms=33 api_test.go:112: сессия выпущена, длина токена=64 (значение не печатаем) -2026/11/12 18:06:18 method=POST path=/api/v1/chats/85991ce8-09f4-48c6-80eb-171e80d344d4/messages status=404 request_id=d6eebb84-6115-4163-9d68-0a5f4870ac33 duration_ms=5 - api_test.go:114: status=404 body={"error":{"code":"not_found","message":"object not found","request_id":"d6eebb84-6115-4163-9d68-0a5f4870ac33"}} - api_test.go:118: ✓ валидация JSON, хвоста, пустого текста и чужого чата ---- PASS: TestMalformedJSONAndValidation (0.19s) +2026/11/12 18:20:59 method=POST path=/api/v1/chats status=201 request_id=911115c9-4961-495f-9b0f-4d3ad5291f5b duration_ms=4 +2026/11/12 18:20:59 method=POST path=/api/v1/chats/d68b28fc-ef27-4da8-8002-8f2c5a40dc84/messages status=400 request_id=bf51256d-0f8c-4c74-911b-dcf466c1cb54 duration_ms=0 + api_test.go:119: status=400 body={"error":{"code":"invalid_request","message":"malformed json","request_id":"bf51256d-0f8c-4c74-911b-dcf466c1cb54"}} +2026/11/12 18:20:59 method=POST path=/api/v1/chats/d68b28fc-ef27-4da8-8002-8f2c5a40dc84/messages status=400 request_id=6f3a8af4-bd5f-4b94-beb3-21fb6a6bff1a duration_ms=0 + api_test.go:119: status=400 body={"error":{"code":"invalid_request","message":"malformed json","request_id":"6f3a8af4-bd5f-4b94-beb3-21fb6a6bff1a"}} +2026/11/12 18:20:59 method=POST path=/api/v1/chats/d68b28fc-ef27-4da8-8002-8f2c5a40dc84/messages status=400 request_id=0b63768a-a205-4ec6-98b0-e8095fb0ab41 duration_ms=0 + api_test.go:126: status=400 body={"error":{"code":"invalid_request","message":"invalid text","request_id":"0b63768a-a205-4ec6-98b0-e8095fb0ab41"}} +2026/11/12 18:20:59 method=POST path=/api/v1/users status=201 request_id=b5a68f91-6e4d-4b4e-a801-92ad3566afea duration_ms=28 + api_test.go:131: создан outsider_514a1758 id=4461c75b-23a7-4996-b3af-df63e11a4f8e +2026/11/12 18:20:59 method=POST path=/api/v1/auth/sessions status=201 request_id=d95a8147-b39b-490e-9c73-8cd507d78bc1 duration_ms=29 + api_test.go:132: сессия выпущена, длина токена=64 (значение не печатаем) +2026/11/12 18:20:59 method=POST path=/api/v1/chats/d68b28fc-ef27-4da8-8002-8f2c5a40dc84/messages status=404 request_id=b8d0ce6f-ad84-40a4-88dc-789530cddaa2 duration_ms=4 + api_test.go:134: status=404 body={"error":{"code":"not_found","message":"object not found","request_id":"b8d0ce6f-ad84-40a4-88dc-789530cddaa2"}} + api_test.go:138: ✓ валидация JSON, хвоста, пустого текста и чужого чата +--- PASS: TestMalformedJSONAndValidation (0.14s) === RUN TestMessageTextPreservedAndLengthOnOriginal - api_test.go:124: → пробелы по краям сохраняются; длина считается по исходному тексту -2026/11/12 18:06:18 method=POST path=/api/v1/users status=201 request_id=35882536-5698-47e4-aa4d-b26ca05eccf2 duration_ms=28 - api_test.go:125: создан text_user_b0b3691c id=4d721a90-d23e-4812-bc50-4b91b972f4a9 -2026/11/12 18:06:18 method=POST path=/api/v1/auth/sessions status=201 request_id=68fe42a9-aa1d-4219-89d0-0bea4485c691 duration_ms=52 - api_test.go:126: сессия выпущена, длина токена=64 (значение не печатаем) -2026/11/12 18:06:18 method=POST path=/api/v1/chats status=201 request_id=d2fdb0f8-f7e6-4a7a-906e-bd5a7575c658 duration_ms=73 -2026/11/12 18:06:18 method=POST path=/api/v1/chats/5af6de80-5d24-4e1c-85ba-6064483eee06/messages status=201 request_id=e87c5fb7-9da0-4db4-b3d3-5c2fde5a1f9c duration_ms=31 - api_test.go:133: status=201 body={"attachment_ids":[],"chat_id":"5af6de80-5d24-4e1c-85ba-6064483eee06","created_at":"2026-11-12T15:06:18.586Z","id":"fb22f748-419d-4e21-bad1-15eefd3541fc","sender_id":"4d721a90-d23e-4812-bc50-4b91b972f4a9","text":" строка\nс пробелами "} -2026/11/12 18:06:18 method=POST path=/api/v1/chats/5af6de80-5d24-4e1c-85ba-6064483eee06/messages status=400 request_id=fb0600ea-7684-4546-948c-758bd6de9fe7 duration_ms=0 - api_test.go:145: status=400 body={"error":{"code":"invalid_request","message":"invalid text","request_id":"fb0600ea-7684-4546-948c-758bd6de9fe7"}} - api_test.go:149: ✓ текст сохранён целиком, обход лимита через TrimSpace закрыт ---- PASS: TestMessageTextPreservedAndLengthOnOriginal (0.19s) + api_test.go:144: → пробелы по краям сохраняются; длина считается по исходному тексту +2026/11/12 18:20:59 method=POST path=/api/v1/users status=201 request_id=b527081d-7a58-4600-b524-8c948a217014 duration_ms=29 + api_test.go:145: создан text_user_9e4c66a9 id=771330ae-06a7-456c-9a94-3e8051cd9d16 +2026/11/12 18:20:59 method=POST path=/api/v1/auth/sessions status=201 request_id=f476e861-fe56-4870-87d7-059ec9192a9e duration_ms=31 + api_test.go:146: сессия выпущена, длина токена=64 (значение не печатаем) +2026/11/12 18:20:59 method=POST path=/api/v1/chats status=201 request_id=49c0699c-e4c2-4026-90d0-f6a52e0fc726 duration_ms=4 +2026/11/12 18:20:59 method=POST path=/api/v1/chats/c73e9300-8849-4189-86b3-13fa74c535c8/messages status=201 request_id=05f3985a-1a41-4f50-bc1b-5db995c288f6 duration_ms=5 + api_test.go:153: status=201 body={"attachment_ids":[],"chat_id":"c73e9300-8849-4189-86b3-13fa74c535c8","created_at":"2026-11-12T15:20:59.401Z","id":"4e33499f-bdc1-494f-bbf3-f97bff764db2","sender_id":"771330ae-06a7-456c-9a94-3e8051cd9d16","text":" строка\nс пробелами "} +2026/11/12 18:20:59 method=POST path=/api/v1/chats/c73e9300-8849-4189-86b3-13fa74c535c8/messages status=400 request_id=9c79e4f6-94ef-457f-a39b-0679097832cc duration_ms=0 + api_test.go:165: status=400 body={"error":{"code":"invalid_request","message":"invalid text","request_id":"9c79e4f6-94ef-457f-a39b-0679097832cc"}} + api_test.go:169: ✓ текст сохранён целиком, обход лимита через TrimSpace закрыт +--- PASS: TestMessageTextPreservedAndLengthOnOriginal (0.07s) === RUN TestSessionRejectsJSONBody - api_test.go:155: → POST /auth/sessions с телом должен быть 400 даже при верном Basic -2026/11/12 18:06:18 method=POST path=/api/v1/users status=201 request_id=fb41ef9f-6a7e-40d9-9a7b-1a6b999f146a duration_ms=33 - api_test.go:156: создан body_user_f034de4e id=34ffe3cc-0fad-43ef-9c71-167de51999db -2026/11/12 18:06:18 method=POST path=/api/v1/auth/sessions status=400 request_id=64964195-0966-4ef3-a09e-90cc2feddbe4 duration_ms=0 - api_test.go:160: status=400 body={"error":{"code":"invalid_request","message":"session create must not have a body","request_id":"64964195-0966-4ef3-a09e-90cc2feddbe4"}} - api_test.go:164: ✓ вход без JSON body ---- PASS: TestSessionRejectsJSONBody (0.04s) + api_test.go:175: → POST /auth/sessions с телом должен быть 400 даже при верном Basic +2026/11/12 18:20:59 method=POST path=/api/v1/users status=201 request_id=b793beaa-8f40-40cf-8260-25ed6b915464 duration_ms=27 + api_test.go:176: создан body_user_828ebe14 id=675b83d5-dd2f-443d-8714-011b476ba871 +2026/11/12 18:20:59 method=POST path=/api/v1/auth/sessions status=400 request_id=26dee1ba-82a6-4de2-a4ce-7e9f01f9b5c4 duration_ms=0 + api_test.go:180: status=400 body={"error":{"code":"invalid_request","message":"session create must not have a body","request_id":"26dee1ba-82a6-4de2-a4ce-7e9f01f9b5c4"}} + api_test.go:184: ✓ вход без JSON body +--- PASS: TestSessionRejectsJSONBody (0.03s) === RUN TestWrongPasswordLogoutAndIgnoredUserHeader - api_test.go:170: → неверный пароль, Basic на бизнес-методе, X-User-Id, logout -2026/11/12 18:06:18 method=POST path=/api/v1/users status=201 request_id=db2797ae-6acd-42c7-a935-5180d9f3f9c7 duration_ms=34 - api_test.go:171: создан auth_user_ceeda3df id=9a73b5de-ea1c-452d-a52a-ceada48a8bcb -2026/11/12 18:06:18 method=POST path=/api/v1/users status=201 request_id=4abdf37f-d666-4ffa-aca5-96358c777f19 duration_ms=35 - api_test.go:172: создан auth_other_029a2c01 id=84485afe-e12b-4811-abd5-6a323a4a11b0 -2026/11/12 18:06:18 method=POST path=/api/v1/auth/sessions status=401 request_id=561b7123-f836-4e1b-86e5-3202dd168c02 duration_ms=40 - api_test.go:177: status=401 body={"error":{"code":"unauthorized","message":"authentication required","request_id":"561b7123-f836-4e1b-86e5-3202dd168c02"}} -2026/11/12 18:06:18 method=POST path=/api/v1/auth/sessions status=201 request_id=ff0c1cd3-6893-498b-8a85-1ddcfaea198e duration_ms=37 - api_test.go:182: сессия выпущена, длина токена=64 (значение не печатаем) -2026/11/12 18:06:18 method=GET path=/api/v1/users/me status=401 request_id=fa44aa80-40c9-460c-8318-fbcdd6127ef5 duration_ms=0 - api_test.go:186: status=401 body={"error":{"code":"unauthorized","message":"authentication required","request_id":"fa44aa80-40c9-460c-8318-fbcdd6127ef5"}} -2026/11/12 18:06:18 method=GET path=/api/v1/users/me status=401 request_id=f76f04a1-a69e-4d4a-b6d9-6cefff6de333 duration_ms=0 - api_test.go:192: status=401 body={"error":{"code":"unauthorized","message":"authentication required","request_id":"f76f04a1-a69e-4d4a-b6d9-6cefff6de333"}} -2026/11/12 18:06:18 method=GET path=/api/v1/users/me status=200 request_id=57b7a10b-bcce-4f69-b4eb-84d7dbfe333d duration_ms=5 - api_test.go:201: status=200 body={"created_at":"2026-11-12T15:06:18.678Z","display_name":"Студент","id":"9a73b5de-ea1c-452d-a52a-ceada48a8bcb","username":"auth_user_ceeda3df"} -2026/11/12 18:06:18 method=DELETE path=/api/v1/auth/sessions/current status=204 request_id=ed4b6610-d10e-4f08-933c-0da4c63e1db5 duration_ms=1 - api_test.go:207: logout status=204 -2026/11/12 18:06:18 method=GET path=/api/v1/users/me status=401 request_id=c51a2f42-758f-4a9d-9995-28d1fb1bd0e1 duration_ms=0 -2026/11/12 18:06:18 method=DELETE path=/api/v1/auth/sessions/current status=401 request_id=800ac6d0-86dd-46eb-baab-24c6f45c4993 duration_ms=1 - api_test.go:219: ✓ пароль, заголовки и отзыв сессии ---- PASS: TestWrongPasswordLogoutAndIgnoredUserHeader (0.17s) + api_test.go:190: → неверный пароль, Basic на бизнес-методе, X-User-Id, logout +2026/11/12 18:20:59 method=POST path=/api/v1/users status=201 request_id=1564c2ae-4a37-4258-9903-38a5b832ef72 duration_ms=33 + api_test.go:191: создан auth_user_bf5d4fc3 id=bfc3f22d-97cf-41a1-8cd5-c6c0f6a274dd +2026/11/12 18:20:59 method=POST path=/api/v1/users status=201 request_id=2e48e45d-cef8-426a-b782-ce4fb4f6fcec duration_ms=28 + api_test.go:192: создан auth_other_99f1a3b7 id=f119c141-7566-4b75-8256-f809af4e515e +2026/11/12 18:20:59 method=POST path=/api/v1/auth/sessions status=401 request_id=8f67f30b-10aa-4eba-a649-687e79bf0f10 duration_ms=27 + api_test.go:197: status=401 body={"error":{"code":"unauthorized","message":"authentication required","request_id":"8f67f30b-10aa-4eba-a649-687e79bf0f10"}} +2026/11/12 18:20:59 method=POST path=/api/v1/auth/sessions status=201 request_id=0ed3a21e-c386-40a3-84a6-788acd837203 duration_ms=28 + api_test.go:202: сессия выпущена, длина токена=64 (значение не печатаем) +2026/11/12 18:20:59 method=GET path=/api/v1/users/me status=401 request_id=c7d4e9e6-4dad-4d36-ade5-693584e2da9a duration_ms=0 + api_test.go:206: status=401 body={"error":{"code":"unauthorized","message":"authentication required","request_id":"c7d4e9e6-4dad-4d36-ade5-693584e2da9a"}} +2026/11/12 18:20:59 method=GET path=/api/v1/users/me status=401 request_id=e5a1a151-d7e9-4784-8e3c-eec0572a29b0 duration_ms=0 + api_test.go:212: status=401 body={"error":{"code":"unauthorized","message":"authentication required","request_id":"e5a1a151-d7e9-4784-8e3c-eec0572a29b0"}} +2026/11/12 18:20:59 method=GET path=/api/v1/users/me status=200 request_id=1937777f-6431-4846-bc9b-fcca5009074a duration_ms=2 + api_test.go:221: status=200 body={"created_at":"2026-11-12T15:20:59.468Z","display_name":"Студент","id":"bfc3f22d-97cf-41a1-8cd5-c6c0f6a274dd","username":"auth_user_bf5d4fc3"} +2026/11/12 18:20:59 method=DELETE path=/api/v1/auth/sessions/current status=204 request_id=b4bbd138-9c71-4451-ba2b-5b381aa0401d duration_ms=1 + api_test.go:227: logout status=204 +2026/11/12 18:20:59 method=GET path=/api/v1/users/me status=401 request_id=ac6f2a1e-32bf-41f7-b321-3f2fa8816358 duration_ms=0 +2026/11/12 18:20:59 method=DELETE path=/api/v1/auth/sessions/current status=401 request_id=e8f2c8bd-0a42-4374-960f-df0ebdc4fcd1 duration_ms=0 + api_test.go:239: ✓ пароль, заголовки и отзыв сессии +--- PASS: TestWrongPasswordLogoutAndIgnoredUserHeader (0.13s) === RUN TestSessionExpiry - api_test.go:225: → SESSION_TTL=2s: тот же токен после паузы должен стать 401, TTL рестартом API не продлевается -2026/11/12 18:06:18 method=POST path=/api/v1/users status=201 request_id=bcb1c96f-65df-40a8-bdac-94727a1cb041 duration_ms=35 - api_test.go:226: создан ttl_user_325de81d id=484fbed9-09a4-4166-8f92-4f69a1fc1689 -2026/11/12 18:06:18 method=POST path=/api/v1/auth/sessions status=201 request_id=2088a908-3d83-4faf-bd43-84ee481db9cb duration_ms=25 - api_test.go:227: сессия выпущена, длина токена=64 (значение не печатаем) -2026/11/12 18:06:21 method=GET path=/api/v1/users/me status=401 request_id=0ba4365e-3bb4-4f55-886d-31698f49dc34 duration_ms=2 - api_test.go:230: status=401 body={"error":{"code":"unauthorized","message":"authentication required","request_id":"0ba4365e-3bb4-4f55-886d-31698f49dc34"}} - api_test.go:234: ✓ истёкшая сессия отклонена ---- PASS: TestSessionExpiry (2.58s) + api_test.go:245: → SESSION_TTL=2s: тот же токен после паузы должен стать 401, TTL рестартом API не продлевается +2026/11/12 18:20:59 method=POST path=/api/v1/users status=201 request_id=45a35d1d-103e-4a8b-aca3-59294454b6c3 duration_ms=27 + api_test.go:246: создан ttl_user_d32ecfcc id=75d6a1f0-24d2-45d3-9dd1-87ab1f0fb879 +2026/11/12 18:20:59 method=POST path=/api/v1/auth/sessions status=201 request_id=02995f15-e546-4f31-a1b0-583446f063f6 duration_ms=31 + api_test.go:247: сессия выпущена, длина токена=64 (значение не печатаем) +2026/11/12 18:21:02 method=GET path=/api/v1/users/me status=401 request_id=01385dc3-1b7f-4f73-bf17-2ee106a16744 duration_ms=4 + api_test.go:250: status=401 body={"error":{"code":"unauthorized","message":"authentication required","request_id":"01385dc3-1b7f-4f73-bf17-2ee106a16744"}} + api_test.go:254: ✓ истёкшая сессия отклонена +--- PASS: TestSessionExpiry (2.57s) === RUN TestDuplicateUsernameRace - api_test.go:241: → 8 параллельных регистраций username=race_6ed0656c -2026/11/12 18:06:21 method=POST path=/api/v1/users status=201 request_id=5402c615-aab8-4b07-a21d-46946f22785b duration_ms=83 -2026/11/12 18:06:21 method=POST path=/api/v1/users status=409 request_id=e860a8f7-fd25-4c0d-abd9-31b50a08db96 duration_ms=85 -2026/11/12 18:06:21 method=POST path=/api/v1/users status=409 request_id=dd17c014-02b9-4fb0-9481-7d4d3d840193 duration_ms=90 -2026/11/12 18:06:21 method=POST path=/api/v1/users status=409 request_id=9a31aa27-6548-4e36-8505-5ec0334ebd76 duration_ms=92 -2026/11/12 18:06:21 method=POST path=/api/v1/users status=409 request_id=d841c975-d516-4b63-b699-661a26ec2175 duration_ms=90 -2026/11/12 18:06:21 method=POST path=/api/v1/users status=409 request_id=c2bf9c03-a386-4ad2-a49d-2749a633654a duration_ms=94 -2026/11/12 18:06:21 method=POST path=/api/v1/users status=409 request_id=cf6d6c68-1668-4991-ab7b-ae77cc69aa47 duration_ms=98 -2026/11/12 18:06:21 method=POST path=/api/v1/users status=409 request_id=025c3a4d-21c6-48ff-89e6-03e6b8f69f62 duration_ms=99 - api_test.go:266: created=1 conflict=7 - api_test.go:270: ✓ UNIQUE username выдержал гонку + api_test.go:261: → 8 параллельных регистраций username=race_8b242d62 +2026/11/12 18:21:02 method=POST path=/api/v1/users status=201 request_id=67cd4204-3850-4742-89f7-cf3dacdc5512 duration_ms=83 +2026/11/12 18:21:02 method=POST path=/api/v1/users status=409 request_id=f6108dc2-aab8-4915-8612-89b3cae46956 duration_ms=84 +2026/11/12 18:21:02 method=POST path=/api/v1/users status=409 request_id=228330cc-a61e-4a87-a277-5c237419e39c duration_ms=85 +2026/11/12 18:21:02 method=POST path=/api/v1/users status=409 request_id=73d04aba-4c41-4753-bcab-5987b01d4394 duration_ms=103 +2026/11/12 18:21:02 method=POST path=/api/v1/users status=409 request_id=d6130b6b-81da-45d1-961f-e4b5f97e8423 duration_ms=103 +2026/11/12 18:21:02 method=POST path=/api/v1/users status=409 request_id=389805da-aa70-414f-a39a-f6a1a50eb52e duration_ms=104 +2026/11/12 18:21:02 method=POST path=/api/v1/users status=409 request_id=d8802c10-b6fa-4d77-ac49-ac9e351b1129 duration_ms=52 +2026/11/12 18:21:02 method=POST path=/api/v1/users status=409 request_id=be270ccf-b860-477c-a3a7-f699e5facac8 duration_ms=107 + api_test.go:286: created=1 conflict=7 + api_test.go:290: ✓ UNIQUE username выдержал гонку --- PASS: TestDuplicateUsernameRace (0.12s) === RUN TestChatCreateRollsBack -2026/11/12 18:06:21 method=POST path=/api/v1/users status=201 request_id=57132288-7a2a-49e0-91d3-1b3b2ad8ad5b duration_ms=35 - api_test.go:276: создан roll_user_55538244 id=510834db-6bf3-44ce-9c3e-bc5a3654ffd7 -2026/11/12 18:06:21 method=POST path=/api/v1/auth/sessions status=201 request_id=2d0bfbec-5b2f-435d-90f4-183fed112d83 duration_ms=30 - api_test.go:277: сессия выпущена, длина токена=64 (значение не печатаем) - api_test.go:280: → создание чата с несуществующим участником должно откатиться, title=rollback-2162ebe8-7d02-467d-a256-23b859075201 -2026/11/12 18:06:21 method=POST path=/api/v1/chats status=400 request_id=21f2b61a-aa7d-4c17-9190-50a2070ca522 duration_ms=5 - api_test.go:283: status=400 body={"error":{"code":"invalid_request","message":"unknown member","request_id":"21f2b61a-aa7d-4c17-9190-50a2070ca522"}} - api_test.go:291: строк chats с этим title после ошибки: 0 - api_test.go:295: ✓ транзакция создания чата откатилась ---- PASS: TestChatCreateRollsBack (0.08s) +2026/11/12 18:21:02 method=POST path=/api/v1/users status=201 request_id=c7f53e21-7b97-44c1-b26f-f14c0a4eb5cb duration_ms=30 + api_test.go:296: создан roll_user_029f22dd id=85341e8a-d2d6-4afd-a4dd-492ef3930966 +2026/11/12 18:21:02 method=POST path=/api/v1/auth/sessions status=201 request_id=e6df8f11-becc-442c-a601-5dab32ec31b6 duration_ms=31 + api_test.go:297: сессия выпущена, длина токена=64 (значение не печатаем) + api_test.go:300: → создание чата с несуществующим участником должно откатиться, title=rollback-b3694b1e-4545-4db4-96ce-8dd2ae367339 +2026/11/12 18:21:02 method=POST path=/api/v1/chats status=400 request_id=a5786f7e-1195-4a15-b7be-864554368cc4 duration_ms=4 + api_test.go:303: status=400 body={"error":{"code":"invalid_request","message":"unknown member","request_id":"a5786f7e-1195-4a15-b7be-864554368cc4"}} + api_test.go:311: строк chats с этим title после ошибки: 0 + api_test.go:315: ✓ транзакция создания чата откатилась +--- PASS: TestChatCreateRollsBack (0.07s) === RUN TestPaginationPages - api_test.go:301: → три сообщения, две страницы limit=2, затем последняя -2026/11/12 18:06:21 method=POST path=/api/v1/users status=201 request_id=0a6b83e1-0421-4574-811e-4da75eb44a3f duration_ms=26 - api_test.go:302: создан page_user_0c9c3ed1 id=687fac60-91d1-42d3-84fc-4a49378c362c -2026/11/12 18:06:21 method=POST path=/api/v1/auth/sessions status=201 request_id=646ba194-eeb2-45d8-b535-6afed48abf8d duration_ms=25 - api_test.go:303: сессия выпущена, длина токена=64 (значение не печатаем) -2026/11/12 18:06:21 method=POST path=/api/v1/chats status=201 request_id=a3495c84-c564-4d1c-af3b-374ac0c843e7 duration_ms=2 -2026/11/12 18:06:21 method=POST path=/api/v1/chats/019d7107-c47f-4cc7-9341-3a71f44a1eac/messages status=201 request_id=4cff46d2-34c6-4473-93f0-7473eaccda7a duration_ms=7 -2026/11/12 18:06:21 method=POST path=/api/v1/chats/019d7107-c47f-4cc7-9341-3a71f44a1eac/messages status=201 request_id=54dcd688-e45f-405f-a849-4c9b540c558b duration_ms=2 -2026/11/12 18:06:21 method=POST path=/api/v1/chats/019d7107-c47f-4cc7-9341-3a71f44a1eac/messages status=201 request_id=4b4c1969-acd3-4785-b0a3-a7e1fc6f3d9b duration_ms=2 -2026/11/12 18:06:21 method=GET path=/api/v1/chats/019d7107-c47f-4cc7-9341-3a71f44a1eac/messages status=200 request_id=490be6d4-e04b-49d2-8f10-d45cbbc013df duration_ms=2 - api_test.go:313: status=200 body={"items":[{"attachment_ids":[],"chat_id":"019d7107-c47f-4cc7-9341-3a71f44a1eac","created_at":"2026-11-12T15:06:21.645Z","id":"6e24502d-79d4-4f6c-be3d-ba3480fb7608","sender_id":"687fac60-91d1-42d3-84fc-4a49378c362c","text":"раз"},{"attachment_ids":[],"chat_id":"019d7107-c47f-4cc7-9341-3a71f44a1eac","created_at":"2026-11-12T15:06:21.649Z","id":"88e5a96b-e468-473a-9c4b-92e6ba4f4329","sender_id":"6... -2026/11/12 18:06:21 method=GET path=/api/v1/chats/019d7107-c47f-4cc7-9341-3a71f44a1eac/messages status=200 request_id=1c4e85bf-6325-48e0-81a3-cbd6daeed98b duration_ms=1 - api_test.go:321: status=200 body={"items":[{"attachment_ids":[],"chat_id":"019d7107-c47f-4cc7-9341-3a71f44a1eac","created_at":"2026-11-12T15:06:21.652Z","id":"0f9e9233-a586-4204-a5d8-71afd9d314be","sender_id":"687fac60-91d1-42d3-84fc-4a49378c362c","text":"три"}],"next_cursor":null} - api_test.go:327: ✓ keyset обошёл историю без зависания cursor ---- PASS: TestPaginationPages (0.07s) + api_test.go:321: → три сообщения, две страницы limit=2, затем последняя +2026/11/12 18:21:02 method=POST path=/api/v1/users status=201 request_id=e25dc219-59af-439f-b2b2-e1795c63495e duration_ms=31 + api_test.go:322: создан page_user_971473ff id=5b35d54a-baab-4005-82cd-6dd335c6a35b +2026/11/12 18:21:02 method=POST path=/api/v1/auth/sessions status=201 request_id=a922dbce-d04d-4422-8f3d-499f3b5dcf7f duration_ms=31 + api_test.go:323: сессия выпущена, длина токена=64 (значение не печатаем) +2026/11/12 18:21:02 method=POST path=/api/v1/chats status=201 request_id=37b3a3ce-06e0-43d2-aff8-3ee62b5e50ef duration_ms=4 +2026/11/12 18:21:02 method=POST path=/api/v1/chats/9441439c-5a18-4cff-b1fb-076fe39873ec/messages status=201 request_id=ee5ce5b8-b173-47ed-acaa-443782e75e1a duration_ms=5 +2026/11/12 18:21:02 method=POST path=/api/v1/chats/9441439c-5a18-4cff-b1fb-076fe39873ec/messages status=201 request_id=30d842ab-2f7d-4e02-bded-ce088b50fd5a duration_ms=2 +2026/11/12 18:21:02 method=POST path=/api/v1/chats/9441439c-5a18-4cff-b1fb-076fe39873ec/messages status=201 request_id=1603f1fc-8f4a-4c79-972d-b64ce2bc50e0 duration_ms=2 +2026/11/12 18:21:02 method=GET path=/api/v1/chats/9441439c-5a18-4cff-b1fb-076fe39873ec/messages status=200 request_id=b53d1590-9c22-444f-b19d-ca10abde871b duration_ms=2 + api_test.go:333: status=200 body={"items":[{"attachment_ids":[],"chat_id":"9441439c-5a18-4cff-b1fb-076fe39873ec","created_at":"2026-11-12T15:21:02.399Z","id":"46c8084e-4bbf-4ea4-baaf-cf5ff22015de","sender_id":"5b35d54a-baab-4005-82cd-6dd335c6a35b","text":"раз"},{"attachment_ids":[],"chat_id":"9441439c-5a18-4cff-b1fb-076fe39873ec","created_at":"2026-11-12T15:21:02.402Z","id":"24b8e53a-4e6e-49d9-b627-aa863532acde","sender_id":"5... +2026/11/12 18:21:02 method=GET path=/api/v1/chats/9441439c-5a18-4cff-b1fb-076fe39873ec/messages status=200 request_id=28aa665c-685f-4bfa-a5dc-91b24b279648 duration_ms=1 + api_test.go:341: status=200 body={"items":[{"attachment_ids":[],"chat_id":"9441439c-5a18-4cff-b1fb-076fe39873ec","created_at":"2026-11-12T15:21:02.405Z","id":"0bc4c157-1db2-45f1-bc8f-c7e2fd251fcb","sender_id":"5b35d54a-baab-4005-82cd-6dd335c6a35b","text":"три"}],"next_cursor":null} + api_test.go:347: ✓ keyset обошёл историю без зависания cursor +--- PASS: TestPaginationPages (0.08s) === RUN TestRedisDownIsNotAnonymous - api_test.go:331: → закрытый клиент Redis: вход и Bearer дают 503, а не 200 от анонима -2026/11/12 18:06:21 method=POST path=/api/v1/users status=201 request_id=beeadeed-af0b-47b4-b0e4-7e6421f1f496 duration_ms=25 - api_test.go:343: создан redis_down_bef9688c id=89644793-1ece-4a4a-a601-a29a56d1a4d8 -2026/11/12 18:06:21 method=POST path=/api/v1/auth/sessions status=503 request_id=9762b8fa-434c-445c-823f-0acc5704f4be duration_ms=24 - api_test.go:347: status=503 body={"error":{"code":"unavailable","message":"dependency unavailable","request_id":"9762b8fa-434c-445c-823f-0acc5704f4be"}} -2026/11/12 18:06:21 method=GET path=/api/v1/users/me status=503 request_id=badd3986-bcb8-41c6-a0ba-618ffac05af1 duration_ms=0 - api_test.go:354: status=503 body={"error":{"code":"unavailable","message":"dependency unavailable","request_id":"badd3986-bcb8-41c6-a0ba-618ffac05af1"}} - api_test.go:358: ✓ сбой Redis не стал анонимным доступом ---- PASS: TestRedisDownIsNotAnonymous (0.05s) + api_test.go:351: → закрытый клиент Redis: вход и Bearer дают 503, а не 200 от анонима +2026/11/12 18:21:02 method=POST path=/api/v1/users status=201 request_id=277a8f32-4f5e-476d-9f83-897759b43fcb duration_ms=27 + api_test.go:363: создан redis_down_434d965b id=05f8b57e-d9a6-47eb-8eb5-6d6a8b9ce4b4 +2026/11/12 18:21:02 method=POST path=/api/v1/auth/sessions status=503 request_id=bb6e9374-c7fd-413f-bc34-85a68e668196 duration_ms=32 + api_test.go:367: status=503 body={"error":{"code":"unavailable","message":"dependency unavailable","request_id":"bb6e9374-c7fd-413f-bc34-85a68e668196"}} +2026/11/12 18:21:02 method=GET path=/api/v1/users/me status=503 request_id=6a80272f-2ff0-4c56-bf92-5226321a43b7 duration_ms=0 + api_test.go:374: status=503 body={"error":{"code":"unavailable","message":"dependency unavailable","request_id":"6a80272f-2ff0-4c56-bf92-5226321a43b7"}} + api_test.go:378: ✓ сбой Redis не стал анонимным доступом +--- PASS: TestRedisDownIsNotAnonymous (0.06s) === RUN TestPostgresDownIsNotAnonymous - api_test.go:362: → закрытый пул PostgreSQL: ready/me/login дают 503, без тела пользователя -2026/11/12 18:06:21 method=POST path=/api/v1/users status=201 request_id=a021c019-6aa8-41ce-a7d5-42b488cb43d9 duration_ms=26 - api_test.go:365: создан pg_down_2520dcae id=20f9f190-3b5a-4ff7-ae47-2897b7f18ea4 -2026/11/12 18:06:21 method=POST path=/api/v1/auth/sessions status=201 request_id=fea01055-7d40-4324-9aed-ca5fc456adfd duration_ms=26 - api_test.go:366: сессия выпущена, длина токена=64 (значение не печатаем) -2026/11/12 18:06:21 method=GET path=/health/ready status=503 request_id=32035732-a60e-4d41-b9df-0f94ff733650 duration_ms=0 - api_test.go:387: status=503 body={"error":{"code":"unavailable","message":"dependency unavailable","request_id":"32035732-a60e-4d41-b9df-0f94ff733650"}} -2026/11/12 18:06:21 method=GET path=/api/v1/users/me status=503 request_id=0193b1dd-49dd-4647-9a44-5cdca3091ed0 duration_ms=0 - api_test.go:394: status=503 body={"error":{"code":"unavailable","message":"dependency unavailable","request_id":"0193b1dd-49dd-4647-9a44-5cdca3091ed0"}} -2026/11/12 18:06:21 method=POST path=/api/v1/auth/sessions status=503 request_id=f6fbf5d1-9f1c-452d-951a-3ee09749f6cd duration_ms=0 - api_test.go:401: status=503 body={"error":{"code":"unavailable","message":"dependency unavailable","request_id":"f6fbf5d1-9f1c-452d-951a-3ee09749f6cd"}} - api_test.go:405: ✓ сбой PostgreSQL не стал анонимным доступом ---- PASS: TestPostgresDownIsNotAnonymous (0.09s) + api_test.go:382: → закрытый пул PostgreSQL: ready/me/login дают 503, без тела пользователя +2026/11/12 18:21:02 method=POST path=/api/v1/users status=201 request_id=9a8e419e-7195-44c0-90f1-e22f68b0c0ed duration_ms=26 + api_test.go:385: создан pg_down_a45c5163 id=540fb38c-746a-4976-8329-f0fc999d7b43 +2026/11/12 18:21:02 method=POST path=/api/v1/auth/sessions status=201 request_id=972edcb9-3c0d-4880-bcd8-0872c1843436 duration_ms=28 + api_test.go:386: сессия выпущена, длина токена=64 (значение не печатаем) +2026/11/12 18:21:02 method=GET path=/health/ready status=503 request_id=251fd7a0-4c17-4b81-a12d-760a5f385a62 duration_ms=0 + api_test.go:407: status=503 body={"error":{"code":"unavailable","message":"dependency unavailable","request_id":"251fd7a0-4c17-4b81-a12d-760a5f385a62"}} +2026/11/12 18:21:02 method=GET path=/api/v1/users/me status=503 request_id=125676e0-2daa-4c1e-a3ea-0acf0d325f6e duration_ms=0 + api_test.go:414: status=503 body={"error":{"code":"unavailable","message":"dependency unavailable","request_id":"125676e0-2daa-4c1e-a3ea-0acf0d325f6e"}} +2026/11/12 18:21:02 method=POST path=/api/v1/auth/sessions status=503 request_id=f70eeb19-072d-4c52-bd73-28a94d22ad25 duration_ms=0 + api_test.go:421: status=503 body={"error":{"code":"unavailable","message":"dependency unavailable","request_id":"f70eeb19-072d-4c52-bd73-28a94d22ad25"}} + api_test.go:425: ✓ сбой PostgreSQL не стал анонимным доступом +--- PASS: TestPostgresDownIsNotAnonymous (0.10s) === RUN TestIdempotencyReplayAndConflict - api_test.go:412: → повтор того же Idempotency-Key возвращает то же сообщение; другой body — 409 -2026/11/12 18:06:21 method=POST path=/api/v1/users status=201 request_id=ba481c3a-d59e-4f1c-b109-273d9cf8f376 duration_ms=27 - api_test.go:413: создан idem_user_5e962710 id=3b9c80ec-af5b-4fcb-8612-df5adf66e7b0 -2026/11/12 18:06:21 method=POST path=/api/v1/auth/sessions status=201 request_id=c7504a83-5f6a-40fd-a47a-6f7a5e611f88 duration_ms=25 - api_test.go:414: сессия выпущена, длина токена=64 (значение не печатаем) -2026/11/12 18:06:21 method=POST path=/api/v1/chats status=201 request_id=6fecfacf-5cf0-42fc-8ae6-cd3499868da5 duration_ms=2 -2026/11/12 18:06:21 method=POST path=/api/v1/chats/bf42b0ff-2d72-4083-888f-d46b0d4bba6b/messages status=201 request_id=ebb16497-7dc3-4b1d-a352-2ec117b1c588 duration_ms=2 - api_test.go:422: status=201 body={"attachment_ids":[],"chat_id":"bf42b0ff-2d72-4083-888f-d46b0d4bba6b","created_at":"2026-11-12T15:06:21.861Z","id":"76a0823b-deb0-4087-820f-6d8d5d955062","sender_id":"3b9c80ec-af5b-4fcb-8612-df5adf66e7b0","text":"один раз"} -2026/11/12 18:06:21 method=POST path=/api/v1/chats/bf42b0ff-2d72-4083-888f-d46b0d4bba6b/messages status=201 request_id=3b737653-a43e-4b6b-901b-80de4724d31b duration_ms=1 - api_test.go:428: status=201 body={"attachment_ids":[],"chat_id":"bf42b0ff-2d72-4083-888f-d46b0d4bba6b","created_at":"2026-11-12T15:06:21.861Z","id":"76a0823b-deb0-4087-820f-6d8d5d955062","sender_id":"3b9c80ec-af5b-4fcb-8612-df5adf66e7b0","text":"один раз"} -2026/11/12 18:06:21 method=POST path=/api/v1/chats/bf42b0ff-2d72-4083-888f-d46b0d4bba6b/messages status=409 request_id=5be94615-9308-4e4f-9b02-04ca003f6e16 duration_ms=1 - api_test.go:437: status=409 body={"error":{"code":"conflict","message":"idempotency key reused with different body","request_id":"5be94615-9308-4e4f-9b02-04ca003f6e16"}} - api_test.go:441: ✓ replay и conflict по Idempotency-Key ---- PASS: TestIdempotencyReplayAndConflict (0.06s) + api_test.go:431: → повтор того же Idempotency-Key возвращает то же сообщение; другой body — 409 +2026/11/12 18:21:02 method=POST path=/api/v1/users status=201 request_id=0d4af35c-da66-4ee5-8954-25a22a743eb5 duration_ms=32 + api_test.go:432: создан idem_user_e3f9d6d2 id=d17c622a-5fce-4359-9c46-1533a11aaf20 +2026/11/12 18:21:02 method=POST path=/api/v1/auth/sessions status=201 request_id=3d54129e-26ff-4150-b9b0-1e3752cf3891 duration_ms=31 + api_test.go:433: сессия выпущена, длина токена=64 (значение не печатаем) +2026/11/12 18:21:02 method=POST path=/api/v1/chats status=201 request_id=bf767947-ff6a-43ba-86a5-5f4751565635 duration_ms=2 +2026/11/12 18:21:02 method=POST path=/api/v1/chats/1544a1e8-ef0a-4aa8-9722-46541cb43c58/messages status=201 request_id=6d3afa33-b457-4751-af43-265f66c9f62a duration_ms=3 + api_test.go:441: status=201 body={"attachment_ids":[],"chat_id":"1544a1e8-ef0a-4aa8-9722-46541cb43c58","created_at":"2026-11-12T15:21:02.647Z","id":"83c4daef-265c-47e8-ad6f-a8a56f76103b","sender_id":"d17c622a-5fce-4359-9c46-1533a11aaf20","text":"один раз"} +2026/11/12 18:21:02 method=POST path=/api/v1/chats/1544a1e8-ef0a-4aa8-9722-46541cb43c58/messages status=201 request_id=109b5934-6580-43a0-a5e1-6d903509000f duration_ms=3 + api_test.go:447: status=201 body={"attachment_ids":[],"chat_id":"1544a1e8-ef0a-4aa8-9722-46541cb43c58","created_at":"2026-11-12T15:21:02.647Z","id":"83c4daef-265c-47e8-ad6f-a8a56f76103b","sender_id":"d17c622a-5fce-4359-9c46-1533a11aaf20","text":"один раз"} +2026/11/12 18:21:02 method=POST path=/api/v1/chats/1544a1e8-ef0a-4aa8-9722-46541cb43c58/messages status=409 request_id=8b39f1a2-1c71-4ca9-82a2-dc904b61567b duration_ms=5 + api_test.go:456: status=409 body={"error":{"code":"conflict","message":"idempotency key reused with different body","request_id":"8b39f1a2-1c71-4ca9-82a2-dc904b61567b"}} + api_test.go:460: ✓ replay и conflict по Idempotency-Key +--- PASS: TestIdempotencyReplayAndConflict (0.08s) === RUN TestIdempotencyKeyRequiredAndConcurrent - api_test.go:447: → нет ключа → 400; 8 параллельных POST с одним ключом → ровно одно сообщение -2026/11/12 18:06:21 method=POST path=/api/v1/users status=201 request_id=2ab93c5e-9ffd-4260-a5dc-b04f6ae5660b duration_ms=25 - api_test.go:448: создан idem_race_f0f21140 id=53f6a58c-3ce4-410c-bf6d-088084ebf4c2 -2026/11/12 18:06:21 method=POST path=/api/v1/auth/sessions status=201 request_id=45711062-65f8-4aac-8563-4790fdc89a3b duration_ms=25 - api_test.go:449: сессия выпущена, длина токена=64 (значение не печатаем) -2026/11/12 18:06:21 method=POST path=/api/v1/chats status=201 request_id=2df6eccd-30af-4e17-80e0-4b52fb771e18 duration_ms=4 -2026/11/12 18:06:21 method=POST path=/api/v1/chats/041835f4-09c3-49eb-aedb-a561d3ce7e92/messages status=400 request_id=26e381a2-4bc0-4eee-b668-9816b9ad2839 duration_ms=0 - api_test.go:467: status=400 body={"error":{"code":"invalid_request","message":"invalid or missing Idempotency-Key","request_id":"26e381a2-4bc0-4eee-b668-9816b9ad2839"}} -2026/11/12 18:06:21 method=POST path=/api/v1/chats/041835f4-09c3-49eb-aedb-a561d3ce7e92/messages status=201 request_id=88713995-6e81-4644-8e0b-7b4c394ca9af duration_ms=7 -2026/11/12 18:06:21 method=POST path=/api/v1/chats/041835f4-09c3-49eb-aedb-a561d3ce7e92/messages status=201 request_id=baaee528-b553-4633-b6f4-2f09abb4b01a duration_ms=10 -2026/11/12 18:06:21 method=POST path=/api/v1/chats/041835f4-09c3-49eb-aedb-a561d3ce7e92/messages status=201 request_id=e283a5e9-ce51-44b2-9a7c-23edbb41b3ba duration_ms=12 -2026/11/12 18:06:21 method=POST path=/api/v1/chats/041835f4-09c3-49eb-aedb-a561d3ce7e92/messages status=201 request_id=68be161c-a944-4b64-ad56-8f14c3068b6e duration_ms=14 -2026/11/12 18:06:21 method=POST path=/api/v1/chats/041835f4-09c3-49eb-aedb-a561d3ce7e92/messages status=201 request_id=45041db6-7633-438e-8e6e-3657e6a4a915 duration_ms=16 -2026/11/12 18:06:21 method=POST path=/api/v1/chats/041835f4-09c3-49eb-aedb-a561d3ce7e92/messages status=201 request_id=191a3c6d-26ac-4359-88e7-d04bf59e7367 duration_ms=17 -2026/11/12 18:06:21 method=POST path=/api/v1/chats/041835f4-09c3-49eb-aedb-a561d3ce7e92/messages status=201 request_id=2c81685c-5ee7-4d2e-81ab-5153014708d3 duration_ms=19 -2026/11/12 18:06:21 method=POST path=/api/v1/chats/041835f4-09c3-49eb-aedb-a561d3ce7e92/messages status=201 request_id=5f23de1d-3352-4864-a40d-fa959abd420e duration_ms=20 - api_test.go:499: unique message ids=1 - api_test.go:503: ✓ ключ обязателен; конкурентный повтор не плодит дубли ---- PASS: TestIdempotencyKeyRequiredAndConcurrent (0.08s) + api_test.go:466: → нет ключа → 400; 8 параллельных POST с одним ключом → ровно одно сообщение +2026/11/12 18:21:02 method=POST path=/api/v1/users status=201 request_id=780585d1-1fad-4b6b-9c8b-7563c9d3a5d0 duration_ms=27 + api_test.go:467: создан idem_race_d71b6a08 id=f14cc2a5-5694-4b69-9446-a8f8c25f8982 +2026/11/12 18:21:02 method=POST path=/api/v1/auth/sessions status=201 request_id=8b357ab5-a2a0-4f93-9736-3d3812141fb3 duration_ms=25 + api_test.go:468: сессия выпущена, длина токена=64 (значение не печатаем) +2026/11/12 18:21:02 method=POST path=/api/v1/chats status=201 request_id=4bf498fa-2472-4f47-8fd1-1b3c472124cd duration_ms=2 +2026/11/12 18:21:02 method=POST path=/api/v1/chats/59069236-2d0e-4e64-aae1-4730a11b5821/messages status=400 request_id=052440d0-9d02-4892-b948-9b7fa305a505 duration_ms=0 + api_test.go:486: status=400 body={"error":{"code":"invalid_request","message":"invalid or missing Idempotency-Key","request_id":"052440d0-9d02-4892-b948-9b7fa305a505"}} +2026/11/12 18:21:02 method=POST path=/api/v1/chats/59069236-2d0e-4e64-aae1-4730a11b5821/messages status=201 request_id=a0ede04f-3b74-40dc-982d-9ff0e207cac4 duration_ms=5 +2026/11/12 18:21:02 method=POST path=/api/v1/chats/59069236-2d0e-4e64-aae1-4730a11b5821/messages status=201 request_id=187324fd-daf2-4e31-8436-56a8347de10f duration_ms=8 +2026/11/12 18:21:02 method=POST path=/api/v1/chats/59069236-2d0e-4e64-aae1-4730a11b5821/messages status=201 request_id=afec4ba7-8198-450f-ae46-3938a8a9bffa duration_ms=10 +2026/11/12 18:21:02 method=POST path=/api/v1/chats/59069236-2d0e-4e64-aae1-4730a11b5821/messages status=201 request_id=38044bb9-cf2f-4b36-9da0-7381d933c008 duration_ms=14 +2026/11/12 18:21:02 method=POST path=/api/v1/chats/59069236-2d0e-4e64-aae1-4730a11b5821/messages status=201 request_id=8b9ca85f-72d7-4fa8-ae06-aa59513ec3e6 duration_ms=18 +2026/11/12 18:21:02 method=POST path=/api/v1/chats/59069236-2d0e-4e64-aae1-4730a11b5821/messages status=201 request_id=accb1cb9-d98c-475e-a2ed-6e896e9841ac duration_ms=20 +2026/11/12 18:21:02 method=POST path=/api/v1/chats/59069236-2d0e-4e64-aae1-4730a11b5821/messages status=201 request_id=4fef2a6e-e58f-4567-9150-e19cd868f6e7 duration_ms=21 +2026/11/12 18:21:02 method=POST path=/api/v1/chats/59069236-2d0e-4e64-aae1-4730a11b5821/messages status=201 request_id=99e0e4a8-5387-4f9d-82e4-5fd1ef448cf0 duration_ms=22 + api_test.go:518: unique message ids=1 + api_test.go:522: ✓ ключ обязателен; конкурентный повтор не плодит дубли +--- PASS: TestIdempotencyKeyRequiredAndConcurrent (0.09s) === RUN TestInstanceIDHeaderPresent - api_test.go:509: → каждый ответ содержит непустой X-Instance-Id - api_test.go:511: status=200 body={"status":"ok"} - api_test.go:515: ✓ X-Instance-Id=test-instance + 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.00s) -=== RUN TestAttachmentUploadDownloadAndACL - attachments_test.go:38: → upload PNG → 201 ready → download checksum; посторонний — 404 -2026/11/12 18:06:21 method=POST path=/api/v1/users status=201 request_id=50e4a1af-fd0c-4f79-8dda-70a15bb9acd4 duration_ms=28 - attachments_test.go:40: создан att_owner_26e19e85 id=2aaf31d8-5457-4aa8-97fd-5e30ab916418 -2026/11/12 18:06:22 method=POST path=/api/v1/auth/sessions status=201 request_id=c7bf2c56-6b37-46c0-b26a-9fdea9c650c2 duration_ms=27 - attachments_test.go:41: сессия выпущена, длина токена=64 (значение не печатаем) -2026/11/12 18:06:22 method=POST path=/api/v1/users status=201 request_id=a1edcb49-d0cd-40fa-af3a-0d67d0b2ea8b duration_ms=27 - attachments_test.go:42: создан att_stranger_bb876443 id=88bd447e-69a4-448f-96d2-f359e2bfdfe3 -2026/11/12 18:06:22 method=POST path=/api/v1/auth/sessions status=201 request_id=2249a833-a589-425a-aab2-76eb560ae04d duration_ms=27 - attachments_test.go:43: сессия выпущена, длина токена=64 (значение не печатаем) -2026/11/12 18:06:22 method=POST path=/api/v1/chats status=201 request_id=f46c6061-855f-4113-afc6-1c5735e5f0d1 duration_ms=5 -2026/11/12 18:06:22 method=POST path=/api/v1/chats/0dacdbe6-5b95-41e8-817d-6b31549a20c9/attachments status=201 request_id=c74261b2-25cc-4995-a15e-8dff9f19f456 duration_ms=3 -2026/11/12 18:06:22 method=GET path=/api/v1/attachments/867bc3f8-3656-4138-a787-b5fc8fc85498 status=200 request_id=210ea277-a957-43d8-a45b-529cafc1ecd0 duration_ms=1 - attachments_test.go:50: status=200 body={"chat_id":"0dacdbe6-5b95-41e8-817d-6b31549a20c9","content_type":"image/png","created_at":"2026-11-12T15:06:22.067Z","error_code":null,"filename":"pic.png","id":"867bc3f8-3656-4138-a787-b5fc8fc85498","owner_id":"2aaf31d8-5457-4aa8-97fd-5e30ab916418","sha256":"2e9b06dc65a4dec84a3eb3124553ec93ca27c78221e64ab2177d0f1412cfcb20","size_bytes":69,"status":"ready","updated_at":"2026-11-12T15:06:22.067Z","... -2026/11/12 18:06:22 method=GET path=/api/v1/attachments/867bc3f8-3656-4138-a787-b5fc8fc85498/content status=200 request_id=d52949e3-d49d-4cc6-a0ae-d406e07a4db1 duration_ms=0 -2026/11/12 18:06:22 method=GET path=/api/v1/attachments/867bc3f8-3656-4138-a787-b5fc8fc85498 status=404 request_id=1e7cf8e4-64dd-4542-a225-01ae04bbd5ae duration_ms=0 - attachments_test.go:74: status=404 body={"error":{"code":"not_found","message":"object not found","request_id":"1e7cf8e4-64dd-4542-a225-01ae04bbd5ae"}} -2026/11/12 18:06:22 method=GET path=/api/v1/attachments/867bc3f8-3656-4138-a787-b5fc8fc85498/content status=404 request_id=51e58b03-52c7-4ad1-b15f-56a49c443ec1 duration_ms=0 -2026/11/12 18:06:22 method=POST path=/api/v1/chats/0dacdbe6-5b95-41e8-817d-6b31549a20c9/messages status=201 request_id=ae5b57bc-14b1-4d8a-a40d-a71cb4f71935 duration_ms=5 - attachments_test.go:86: status=201 body={"attachment_ids":["867bc3f8-3656-4138-a787-b5fc8fc85498"],"chat_id":"0dacdbe6-5b95-41e8-817d-6b31549a20c9","created_at":"2026-11-12T15:06:22.074Z","id":"0ea80b9c-c870-4e74-a23a-2a3b804970af","sender_id":"2aaf31d8-5457-4aa8-97fd-5e30ab916418","text":"с файлом"} - attachments_test.go:95: ✓ upload/download/ACL и message.attachment_ids ---- PASS: TestAttachmentUploadDownloadAndACL (0.13s) -=== RUN TestAttachmentRejectsBadInput - attachments_test.go:102: → битый PNG, подмена MIME, опасный filename, чужой чат → 4xx не 500 -2026/11/12 18:06:22 method=POST path=/api/v1/users status=201 request_id=4c3e8cba-a49e-417b-8a4d-da66dc3cdf18 duration_ms=28 - attachments_test.go:104: создан att_bad_21539b6c id=f5e5ea5c-5c89-4aba-8393-1d418136d0d7 -2026/11/12 18:06:22 method=POST path=/api/v1/auth/sessions status=201 request_id=db8cea49-9800-450d-8c80-cd85f21fef4c duration_ms=27 - attachments_test.go:105: сессия выпущена, длина токена=64 (значение не печатаем) -2026/11/12 18:06:22 method=POST path=/api/v1/chats status=201 request_id=c37b00b8-95e8-466b-b0bb-c90397b4913c duration_ms=5 -2026/11/12 18:06:22 method=POST path=/api/v1/chats/b88e5748-ce97-4b19-a045-fe10fbf88af3/attachments status=400 request_id=791df656-1869-4832-8e16-d145f3e12568 duration_ms=1 - attachments_test.go:109: status=400 body={"error":{"code":"invalid_request","message":"invalid filename","request_id":"791df656-1869-4832-8e16-d145f3e12568"}} -2026/11/12 18:06:22 method=POST path=/api/v1/chats/b88e5748-ce97-4b19-a045-fe10fbf88af3/attachments status=415 request_id=f8d9fdcc-524a-4c81-a08d-b72803745bdc duration_ms=3 - attachments_test.go:115: status=415 body={"error":{"code":"unsupported_media_type","message":"invalid or unsupported image","request_id":"f8d9fdcc-524a-4c81-a08d-b72803745bdc"}} -2026/11/12 18:06:22 method=POST path=/api/v1/chats/b88e5748-ce97-4b19-a045-fe10fbf88af3/attachments status=415 request_id=6da7b2bc-c552-4885-bd4c-dd888b3a6a4b duration_ms=1 - attachments_test.go:121: status=415 body={"error":{"code":"unsupported_media_type","message":"invalid or unsupported image","request_id":"6da7b2bc-c552-4885-bd4c-dd888b3a6a4b"}} -2026/11/12 18:06:22 method=POST path=/api/v1/chats/b88e5748-ce97-4b19-a045-fe10fbf88af3/attachments status=413 request_id=55dfe90c-9de2-4a34-942d-5e29abb6a181 duration_ms=1 - attachments_test.go:138: status=413 body={"error":{"code":"payload_too_large","message":"file is too large","request_id":"55dfe90c-9de2-4a34-942d-5e29abb6a181"}} -2026/11/12 18:06:22 method=POST path=/api/v1/users status=201 request_id=c4d7a58a-254b-49c8-954d-f69c37badb7b duration_ms=28 - attachments_test.go:143: создан att_other_f29f128d id=3186c693-b42d-4040-82b2-aa46cdf35c10 -2026/11/12 18:06:22 method=POST path=/api/v1/auth/sessions status=201 request_id=17898378-42f5-4bac-a69e-d3673070bc82 duration_ms=28 - attachments_test.go:144: сессия выпущена, длина токена=64 (значение не печатаем) -2026/11/12 18:06:22 method=POST path=/api/v1/chats status=201 request_id=106a6135-6033-49d0-a3af-cdffa50138f3 duration_ms=2 -2026/11/12 18:06:22 method=POST path=/api/v1/chats/48d9e9da-2e02-4663-941b-b1e8fe8f587a/attachments status=404 request_id=a1749a57-1189-4505-b6c7-26726bab488b duration_ms=0 - attachments_test.go:147: status=404 body={"error":{"code":"not_found","message":"object not found","request_id":"a1749a57-1189-4505-b6c7-26726bab488b"}} -2026/11/12 18:06:22 method=POST path=/api/v1/chats/48d9e9da-2e02-4663-941b-b1e8fe8f587a/attachments status=201 request_id=75b83de8-96a1-4b6d-88f3-8c47d1d337d8 duration_ms=1 -2026/11/12 18:06:22 method=POST path=/api/v1/chats/b88e5748-ce97-4b19-a045-fe10fbf88af3/messages status=404 request_id=9202daed-c840-4dad-aaad-57c641b5b60e duration_ms=1 - attachments_test.go:156: status=404 body={"error":{"code":"not_found","message":"object not found","request_id":"9202daed-c840-4dad-aaad-57c641b5b60e"}} - attachments_test.go:160: ✓ негативные сценарии вложений → клиентские 4xx ---- PASS: TestAttachmentRejectsBadInput (0.14s) -=== RUN TestAttachmentS3DownIs503 - attachments_test.go:168: → S3 недоступен: ready и upload → 503 -2026/11/12 18:06:22 method=GET path=/health/ready status=503 request_id=3d89fdba-9a9c-4584-a4c6-3f80db705e0a duration_ms=0 - attachments_test.go:171: status=503 body={"error":{"code":"unavailable","message":"dependency unavailable","request_id":"3d89fdba-9a9c-4584-a4c6-3f80db705e0a"}} -2026/11/12 18:06:22 method=POST path=/api/v1/users status=201 request_id=4e83fd55-0b6c-4d86-9af6-f2fa3c2bdbf2 duration_ms=25 - attachments_test.go:176: создан s3_down_e2a7e91a id=54340923-2d7d-4a06-b2e2-ffaa7d8740bd -2026/11/12 18:06:22 method=POST path=/api/v1/auth/sessions status=201 request_id=0e4ab943-38bb-4a14-a97f-63fbb3290957 duration_ms=25 - attachments_test.go:177: сессия выпущена, длина токена=64 (значение не печатаем) -2026/11/12 18:06:22 method=POST path=/api/v1/chats status=201 request_id=71b90d66-3e07-4558-b3a8-9e7b53dd2692 duration_ms=3 -2026/11/12 18:06:22 request_id=f6f288b3-755c-458e-8d82-ab72fafb64f8 s3_unavailable -2026/11/12 18:06:22 method=POST path=/api/v1/chats/83ee260c-6369-47be-a18e-7fc24884dc4e/attachments status=503 request_id=f6f288b3-755c-458e-8d82-ab72fafb64f8 duration_ms=1 - attachments_test.go:180: status=503 body={"error":{"code":"unavailable","message":"dependency unavailable","request_id":"f6f288b3-755c-458e-8d82-ab72fafb64f8"}} - attachments_test.go:184: ✓ падение S3 → 503 ---- PASS: TestAttachmentS3DownIs503 (0.06s) +=== RUN TestAttachmentRoundTripAndAccessControl + attachments_test.go:203: → PNG и JPEG: 201 ready, sha256/size, download без redirect, доступ только участникам +2026/11/12 18:21:02 method=POST path=/api/v1/users status=201 request_id=6e4cf788-8399-4032-9159-6d2029d3c612 duration_ms=28 + attachments_test.go:206: создан att_alice_0369edce id=92d6e1b1-fc12-4766-8054-8eac013c417d +2026/11/12 18:21:02 method=POST path=/api/v1/users status=201 request_id=7ecee9dd-ef8d-4328-b3f7-6aa143868994 duration_ms=29 + attachments_test.go:207: создан att_bob_634fd3d1 id=8c427980-01eb-4916-a099-98c4694eed5f +2026/11/12 18:21:02 method=POST path=/api/v1/users status=201 request_id=72dbeb2f-eae9-4b4b-9b44-afa6a2559ef8 duration_ms=32 + attachments_test.go:208: создан att_eve_44a9b03a id=c045b1c2-e6ac-4732-8000-7f0c36964fc5 +2026/11/12 18:21:02 method=POST path=/api/v1/auth/sessions status=201 request_id=602a420d-1655-4496-a09c-d064ebe15692 duration_ms=28 + attachments_test.go:209: сессия выпущена, длина токена=64 (значение не печатаем) +2026/11/12 18:21:02 method=POST path=/api/v1/auth/sessions status=201 request_id=ee3b3b0c-ad73-43ba-8505-2005b0ebcd14 duration_ms=26 + attachments_test.go:210: сессия выпущена, длина токена=64 (значение не печатаем) +2026/11/12 18:21:02 method=POST path=/api/v1/auth/sessions status=201 request_id=cec3c99a-aab9-4e2a-a208-e17b0dc93324 duration_ms=25 + attachments_test.go:211: сессия выпущена, длина токена=64 (значение не печатаем) +2026/11/12 18:21:02 method=POST path=/api/v1/chats status=201 request_id=a0e3f7dc-bde5-400a-b32d-95a991150b96 duration_ms=2 +2026/11/12 18:21:02 method=POST path=/api/v1/chats/bb480e58-f08e-46ec-addc-89f9f0a3a52f/attachments status=201 request_id=da72f69e-6084-4304-8102-1bae9cda4426 duration_ms=14 +2026/11/12 18:21:02 method=GET path=/api/v1/attachments/71f98842-17c6-4837-9426-ec2951c22766 status=200 request_id=b3080e14-d0b6-457e-ad6b-ff1a72f9acd7 duration_ms=1 +2026/11/12 18:21:02 method=GET path=/api/v1/attachments/71f98842-17c6-4837-9426-ec2951c22766/content status=200 request_id=b33b54c6-963d-43de-b7ee-956b80a6aa65 duration_ms=3 +2026/11/12 18:21:02 method=POST path=/api/v1/chats/bb480e58-f08e-46ec-addc-89f9f0a3a52f/attachments status=201 request_id=06960154-31d0-4008-8255-760cbaf10f50 duration_ms=6 +2026/11/12 18:21:02 method=GET path=/api/v1/attachments/71f98842-17c6-4837-9426-ec2951c22766 status=404 request_id=d0d252ae-b286-4bdc-b906-2af551f712b8 duration_ms=0 + attachments_test.go:259: status=404 body={"error":{"code":"not_found","message":"object not found","request_id":"d0d252ae-b286-4bdc-b906-2af551f712b8"}} +2026/11/12 18:21:02 method=GET path=/api/v1/attachments/71f98842-17c6-4837-9426-ec2951c22766/content status=404 request_id=a0539da8-2730-43ac-b728-490c162068ce duration_ms=0 + attachments_test.go:259: status=404 body={"error":{"code":"not_found","message":"object not found","request_id":"a0539da8-2730-43ac-b728-490c162068ce"}} +2026/11/12 18:21:02 method=POST path=/api/v1/chats/bb480e58-f08e-46ec-addc-89f9f0a3a52f/attachments status=404 request_id=d6aefebd-c85e-4938-b93d-e51f115a7bf6 duration_ms=0 +2026/11/12 18:21:02 method=POST path=/api/v1/chats/bb480e58-f08e-46ec-addc-89f9f0a3a52f/attachments status=401 request_id=1d398754-6ebd-4785-98b5-44fbe48bb372 duration_ms=0 +2026/11/12 18:21:02 method=GET path=/api/v1/attachments/71f98842-17c6-4837-9426-ec2951c22766/content status=404 request_id=6c3e9b82-7f94-4992-998c-7832da849a08 duration_ms=0 +2026/11/12 18:21:02 method=GET path=/api/v1/attachments/d255ba11-5aef-4461-8c90-29ca5c4d5a8a status=404 request_id=e0993f8d-f2e1-4fe5-8a9e-afdc3343da36 duration_ms=0 +2026/11/12 18:21:02 method=POST path=/api/v1/chats/bb480e58-f08e-46ec-addc-89f9f0a3a52f/messages status=201 request_id=3887ce82-79cc-4323-a368-a62c836d88ba duration_ms=6 + attachments_test.go:288: status=201 body={"attachment_ids":["ba356163-1259-4131-b94d-78015d549baa","71f98842-17c6-4837-9426-ec2951c22766"],"chat_id":"bb480e58-f08e-46ec-addc-89f9f0a3a52f","created_at":"2026-11-12T15:21:02.960Z","id":"7a06e1d0-ba84-4721-81b3-6ca52581484f","sender_id":"92d6e1b1-fc12-4766-8054-8eac013c417d","text":"смотри"} +2026/11/12 18:21:02 method=POST path=/api/v1/chats/bb480e58-f08e-46ec-addc-89f9f0a3a52f/messages status=201 request_id=51180a21-9726-4992-9201-5916574ddc1a duration_ms=2 +2026/11/12 18:21:02 method=POST path=/api/v1/chats/bb480e58-f08e-46ec-addc-89f9f0a3a52f/messages status=409 request_id=338693e4-08fd-4919-966d-a298fb02f948 duration_ms=1 +2026/11/12 18:21:02 method=GET path=/api/v1/chats/bb480e58-f08e-46ec-addc-89f9f0a3a52f/messages status=200 request_id=fe8e7004-cf2f-4632-b7f0-62352052b027 duration_ms=1 +2026/11/12 18:21:02 method=GET path=/api/v1/chats/bb480e58-f08e-46ec-addc-89f9f0a3a52f/messages status=404 request_id=42999fe0-4ec6-49c0-a6d9-49a747b86054 duration_ms=0 + attachments_test.go:319: ✓ upload/download/доступ/replay работают, внутренние ключи не раскрываются +--- PASS: TestAttachmentRoundTripAndAccessControl (0.22s) +=== RUN TestAttachmentTooLarge + attachments_test.go:324: → ровно 10 MiB проходит лимит размера (дальше 415 как не-картинка), 10 MiB+1 → 413 +2026/11/12 18:21:03 method=POST path=/api/v1/users status=201 request_id=a38c61bf-2bba-43e2-b065-ef44916ec6be duration_ms=28 + attachments_test.go:325: создан att_big_06b1c5dc id=c4bf6d5c-200b-41df-885f-1ca705dd887d +2026/11/12 18:21:03 method=POST path=/api/v1/auth/sessions status=201 request_id=07115aad-600a-4222-877c-70ea59d6cb30 duration_ms=25 + attachments_test.go:325: сессия выпущена, длина токена=64 (значение не печатаем) +2026/11/12 18:21:03 method=POST path=/api/v1/chats status=201 request_id=9732c58f-df62-43bd-ab87-5e20100c4340 duration_ms=2 +2026/11/12 18:21:03 method=POST path=/api/v1/chats/1d9c5bd2-a92d-48c7-a035-7edcd49da48c/attachments status=415 request_id=551e1b8f-759f-4caf-942b-4435997f350d duration_ms=3 + attachments_test.go:330: status=415 body={"error":{"code":"unsupported_media_type","message":"file is not a valid png/jpeg image","request_id":"551e1b8f-759f-4caf-942b-4435997f350d"}} +2026/11/12 18:21:03 method=POST path=/api/v1/chats/1d9c5bd2-a92d-48c7-a035-7edcd49da48c/attachments status=413 request_id=37f1c631-3aad-4523-991c-75db111b3a06 duration_ms=4 + attachments_test.go:337: status=413 body={"error":{"code":"payload_too_large","message":"file is too large","request_id":"37f1c631-3aad-4523-991c-75db111b3a06"}} +2026/11/12 18:21:03 method=POST path=/api/v1/chats/1d9c5bd2-a92d-48c7-a035-7edcd49da48c/attachments status=413 request_id=e82efd26-b2d8-46b3-b65e-248446bebbbf duration_ms=4 +2026/11/12 18:21:03 method=POST path=/api/v1/chats/1d9c5bd2-a92d-48c7-a035-7edcd49da48c/attachments status=413 request_id=67fc6b9c-ec45-4119-85a2-ea35c2f60e77 duration_ms=8 + attachments_test.go:364: ✓ лимит байтов: граница точная, работает и для chunked +--- PASS: TestAttachmentTooLarge (0.08s) +=== RUN TestAttachmentPixelLimit + attachments_test.go:369: → 8000x5000 (=40 млн) принимается, 8000x5001 → 413 +2026/11/12 18:21:03 method=POST path=/api/v1/users status=201 request_id=8b544036-7b74-44fc-ba8b-7341f6a76968 duration_ms=26 + attachments_test.go:370: создан att_px_74e2479b id=127820d4-2fce-4e84-8e64-7050d620006d +2026/11/12 18:21:03 method=POST path=/api/v1/auth/sessions status=201 request_id=a9dd2101-110e-4fff-a5a6-4d4df7c6928e duration_ms=26 + attachments_test.go:370: сессия выпущена, длина токена=64 (значение не печатаем) +2026/11/12 18:21:03 method=POST path=/api/v1/chats status=201 request_id=e5fe6311-319a-4386-b011-396b7e349758 duration_ms=2 + attachments_test.go:373: PNG 8000x5000 занимает 9860 байт на проводе +2026/11/12 18:21:03 method=POST path=/api/v1/chats/ff4de357-c5ea-4edd-8110-c0b21ddc2cda/attachments status=201 request_id=496c7692-87b3-4597-8532-dec4c1970617 duration_ms=4 +2026/11/12 18:21:03 method=POST path=/api/v1/chats/ff4de357-c5ea-4edd-8110-c0b21ddc2cda/attachments status=413 request_id=f4ecc33c-52cf-458a-8d90-5aaffdbceb16 duration_ms=0 + attachments_test.go:381: status=413 body={"error":{"code":"payload_too_large","message":"image has too many pixels","request_id":"f4ecc33c-52cf-458a-8d90-5aaffdbceb16"}} + attachments_test.go:385: ✓ лимит пикселей по заголовку, без полного декода +--- PASS: TestAttachmentPixelLimit (0.08s) +=== RUN TestAttachmentCorruptAndMimeSpoof + attachments_test.go:390: → мусор, усечённые PNG/JPEG, битый CRC, GIF под видом PNG, подмена Content-Type +2026/11/12 18:21:03 method=POST path=/api/v1/users status=201 request_id=87dc6e69-788e-458c-b29b-408171e7e34c duration_ms=25 + attachments_test.go:391: создан att_bad_d38447a8 id=becc49c6-2c78-40bc-8e4f-8beb6eb3545b +2026/11/12 18:21:03 method=POST path=/api/v1/auth/sessions status=201 request_id=3d12be94-553c-46fa-a049-b69dda676470 duration_ms=26 + attachments_test.go:391: сессия выпущена, длина токена=64 (значение не печатаем) +2026/11/12 18:21:03 method=POST path=/api/v1/chats status=201 request_id=8c9f44ac-33e5-4922-9adb-8a26ea8a5218 duration_ms=3 +2026/11/12 18:21:03 method=POST path=/api/v1/chats/1311e2d9-336e-422a-94a7-0653927b6aa2/attachments status=415 request_id=01f41150-69a5-4b67-ba43-90e77a6ad19f duration_ms=1 + attachments_test.go:419: случайные байты как png → 415 +2026/11/12 18:21:03 method=POST path=/api/v1/chats/1311e2d9-336e-422a-94a7-0653927b6aa2/attachments status=415 request_id=beabb3eb-054e-4f84-971a-68461686358e duration_ms=0 + attachments_test.go:419: пустое тело → 415 +2026/11/12 18:21:03 method=POST path=/api/v1/chats/1311e2d9-336e-422a-94a7-0653927b6aa2/attachments status=415 request_id=9bee11e4-c293-4961-ad9a-b67ceb74159d duration_ms=1 + attachments_test.go:419: усечённый PNG → 415 +2026/11/12 18:21:03 method=POST path=/api/v1/chats/1311e2d9-336e-422a-94a7-0653927b6aa2/attachments status=415 request_id=2c339eff-701e-462f-a774-410acebf148d duration_ms=0 + attachments_test.go:419: усечённый JPEG → 415 +2026/11/12 18:21:03 method=POST path=/api/v1/chats/1311e2d9-336e-422a-94a7-0653927b6aa2/attachments status=415 request_id=a6f23d48-1d77-4c7b-86a7-21baf6421fd1 duration_ms=0 + attachments_test.go:419: PNG с битым CRC → 415 +2026/11/12 18:21:03 method=POST path=/api/v1/chats/1311e2d9-336e-422a-94a7-0653927b6aa2/attachments status=415 request_id=e5955056-1e64-4f99-af56-d669b25e55e1 duration_ms=0 + attachments_test.go:419: GIF под видом PNG → 415 +2026/11/12 18:21:03 method=POST path=/api/v1/chats/1311e2d9-336e-422a-94a7-0653927b6aa2/attachments status=415 request_id=507a1420-7016-4afa-a880-4222584deef9 duration_ms=0 + attachments_test.go:419: PNG под видом JPEG (спуфинг) → 415 +2026/11/12 18:21:03 method=POST path=/api/v1/chats/1311e2d9-336e-422a-94a7-0653927b6aa2/attachments status=415 request_id=cbe98dc7-a32e-43d1-b222-c354394326c7 duration_ms=0 + attachments_test.go:419: JPEG под видом PNG (спуфинг) → 415 +2026/11/12 18:21:03 method=POST path=/api/v1/chats/1311e2d9-336e-422a-94a7-0653927b6aa2/attachments status=415 request_id=14149874-3231-474d-970c-62ec7e4b5a07 duration_ms=0 + attachments_test.go:419: валидный PNG, но Content-Type text/plain → 415 +2026/11/12 18:21:03 method=POST path=/api/v1/chats/1311e2d9-336e-422a-94a7-0653927b6aa2/attachments status=415 request_id=3a1e91b0-dbbd-45bb-b027-09231e71bffe duration_ms=0 + attachments_test.go:419: валидный PNG без Content-Type → 415 +2026/11/12 18:21:03 method=POST path=/api/v1/chats/1311e2d9-336e-422a-94a7-0653927b6aa2/attachments status=415 request_id=75feae20-26cf-4610-a15b-2da6db8b3c39 duration_ms=0 + attachments_test.go:419: валидный PNG, Content-Type image/gif → 415 +2026/11/12 18:21:03 method=POST path=/api/v1/chats/1311e2d9-336e-422a-94a7-0653927b6aa2/attachments status=201 request_id=d5ac73a6-35ae-4f0c-a876-377f943ac912 duration_ms=7 + attachments_test.go:437: ✓ все повреждённые/подменённые файлы → 415, строки в БД не создаются +--- PASS: TestAttachmentCorruptAndMimeSpoof (0.08s) +=== RUN TestAttachmentFilenameValidation + attachments_test.go:441: → filename: '/', '\', NUL, управляющие, пустое, >255 → 400; unicode и пробелы допустимы +2026/11/12 18:21:03 method=POST path=/api/v1/users status=201 request_id=40d2e58b-dc12-4be0-b2dc-5fc79bcf2d20 duration_ms=27 + attachments_test.go:442: создан att_name_f56bf6c9 id=23d33717-5ceb-40c1-9dc0-21f0d1c28dda +2026/11/12 18:21:03 method=POST path=/api/v1/auth/sessions status=201 request_id=4640a2a0-b172-4090-864f-aba20005ee49 duration_ms=27 + attachments_test.go:442: сессия выпущена, длина токена=64 (значение не печатаем) +2026/11/12 18:21:03 method=POST path=/api/v1/chats status=201 request_id=f5010f50-f611-4f9e-a754-0cbcb7ac23c4 duration_ms=4 +2026/11/12 18:21:03 method=POST path=/api/v1/chats/e221a5f7-4599-44b5-a2a6-c1ecf06a387c/attachments status=400 request_id=4e0d5c3d-1a46-45f2-bdb5-dfa98cc258bb duration_ms=0 +2026/11/12 18:21:03 method=POST path=/api/v1/chats/e221a5f7-4599-44b5-a2a6-c1ecf06a387c/attachments status=400 request_id=fa331260-0306-4fb9-9b6f-f4a710875c9f duration_ms=0 +2026/11/12 18:21:03 method=POST path=/api/v1/chats/e221a5f7-4599-44b5-a2a6-c1ecf06a387c/attachments status=400 request_id=93e97dc4-0ab3-47e8-ad88-0849360f9e26 duration_ms=0 +2026/11/12 18:21:03 method=POST path=/api/v1/chats/e221a5f7-4599-44b5-a2a6-c1ecf06a387c/attachments status=400 request_id=488c7efb-3620-4a17-91d5-a7ea99e90bc1 duration_ms=0 +2026/11/12 18:21:03 method=POST path=/api/v1/chats/e221a5f7-4599-44b5-a2a6-c1ecf06a387c/attachments status=400 request_id=72e31491-8750-4d18-8749-50e36593a850 duration_ms=0 +2026/11/12 18:21:03 method=POST path=/api/v1/chats/e221a5f7-4599-44b5-a2a6-c1ecf06a387c/attachments status=400 request_id=3c45fb04-8b0d-4046-a533-34b9ff296d58 duration_ms=0 +2026/11/12 18:21:03 method=POST path=/api/v1/chats/e221a5f7-4599-44b5-a2a6-c1ecf06a387c/attachments status=400 request_id=368ee4ed-4e92-4658-9a8c-bfd9a285a60c duration_ms=0 +2026/11/12 18:21:03 method=POST path=/api/v1/chats/e221a5f7-4599-44b5-a2a6-c1ecf06a387c/attachments status=400 request_id=6ab9d83f-74ef-4d74-ab1c-a5545cd5a8b1 duration_ms=0 +2026/11/12 18:21:03 method=POST path=/api/v1/chats/e221a5f7-4599-44b5-a2a6-c1ecf06a387c/attachments status=400 request_id=e0449682-ba68-493f-8a32-8fdaf2995b1d duration_ms=0 +2026/11/12 18:21:03 method=POST path=/api/v1/chats/e221a5f7-4599-44b5-a2a6-c1ecf06a387c/attachments status=400 request_id=fe6a0d4c-d09d-4cc6-99b1-fe5fcb2b703d duration_ms=0 +2026/11/12 18:21:03 method=POST path=/api/v1/chats/e221a5f7-4599-44b5-a2a6-c1ecf06a387c/attachments status=400 request_id=0782590f-cdc8-4968-bf16-75d50c70fcb0 duration_ms=0 +2026/11/12 18:21:03 method=POST path=/api/v1/chats/e221a5f7-4599-44b5-a2a6-c1ecf06a387c/attachments status=201 request_id=47014ac4-41fa-4b5e-8812-e5252b405605 duration_ms=5 +2026/11/12 18:21:03 method=POST path=/api/v1/chats/e221a5f7-4599-44b5-a2a6-c1ecf06a387c/attachments status=201 request_id=a6ae5e5a-312b-4d60-80dd-5b1331351326 duration_ms=4 +2026/11/12 18:21:03 method=POST path=/api/v1/chats/e221a5f7-4599-44b5-a2a6-c1ecf06a387c/attachments status=201 request_id=3db5881c-a069-426f-b45f-ae945c3c132c duration_ms=4 + attachments_test.go:472: ✓ опасные имена отклоняются, обычные Unicode-имена сохраняются как есть +--- PASS: TestAttachmentFilenameValidation (0.09s) +=== RUN TestMessageAttachmentRules + attachments_test.go:478: → foreign attachment_id, вложение другого чата, неизвестный id, лимиты и пустой текст +2026/11/12 18:21:03 method=POST path=/api/v1/users status=201 request_id=b9cb6860-4b63-4991-9161-49e712f566ca duration_ms=27 + attachments_test.go:481: создан rule_alice_c69fdfb5 id=2ed8e71c-b59d-48d2-9270-9f91440088f3 +2026/11/12 18:21:03 method=POST path=/api/v1/users status=201 request_id=7a5bd2e4-218d-4d89-a951-d7729d4d8637 duration_ms=26 + attachments_test.go:482: создан rule_mal_0875e0ad id=8e4fe916-85e5-49ba-86db-4b834cbb3e38 +2026/11/12 18:21:03 method=POST path=/api/v1/auth/sessions status=201 request_id=9c3559f0-f5a5-4b3c-8fd8-47464d816dd9 duration_ms=26 + attachments_test.go:483: сессия выпущена, длина токена=64 (значение не печатаем) +2026/11/12 18:21:03 method=POST path=/api/v1/auth/sessions status=201 request_id=8a19c95c-354f-4e5e-976c-7ff15b33f111 duration_ms=26 + attachments_test.go:484: сессия выпущена, длина токена=64 (значение не печатаем) +2026/11/12 18:21:03 method=POST path=/api/v1/chats status=201 request_id=e11ca7fc-a6df-4be7-b50d-37f7eb82b6f7 duration_ms=2 +2026/11/12 18:21:03 method=POST path=/api/v1/chats status=201 request_id=c0527ca6-ba95-4357-9054-7b7876e4ff56 duration_ms=2 +2026/11/12 18:21:03 method=POST path=/api/v1/chats status=201 request_id=ecb5246d-77fe-47d6-b3f5-6f62f24f5dce duration_ms=1 +2026/11/12 18:21:03 method=POST path=/api/v1/chats/ba67794f-6e3d-491d-b209-30e75075610b/attachments status=201 request_id=51b70749-b7eb-44a2-aadb-d32c558455a6 duration_ms=4 +2026/11/12 18:21:03 method=POST path=/api/v1/chats/f8dff763-c43e-477b-a13c-634840b972c7/attachments status=201 request_id=0ff47167-3a0e-4938-b85c-318c52b94d9c duration_ms=7 +2026/11/12 18:21:03 method=POST path=/api/v1/chats/ba67794f-6e3d-491d-b209-30e75075610b/messages status=404 request_id=5b9ed3e5-e43b-4e3e-b587-79a7999c8171 duration_ms=2 + attachments_test.go:499: status=404 body={"error":{"code":"not_found","message":"object not found","request_id":"5b9ed3e5-e43b-4e3e-b587-79a7999c8171"}} +2026/11/12 18:21:03 method=POST path=/api/v1/chats/7ef09876-6342-45b3-8763-08c9cbedd450/messages status=404 request_id=2b8a18ce-f02d-424f-87ed-0369d2b6c1e0 duration_ms=1 + attachments_test.go:505: status=404 body={"error":{"code":"not_found","message":"object not found","request_id":"2b8a18ce-f02d-424f-87ed-0369d2b6c1e0"}} +2026/11/12 18:21:03 method=POST path=/api/v1/chats/ba67794f-6e3d-491d-b209-30e75075610b/messages status=404 request_id=e1e742db-a87b-4038-9e7c-7eaa6b14a249 duration_ms=2 +2026/11/12 18:21:03 method=POST path=/api/v1/chats/ba67794f-6e3d-491d-b209-30e75075610b/messages status=404 request_id=bb593e90-63a4-43fd-92ba-ff7bc9db70a4 duration_ms=2 +2026/11/12 18:21:03 method=GET path=/api/v1/chats/ba67794f-6e3d-491d-b209-30e75075610b/messages status=200 request_id=addcd400-b6de-41ac-94c0-07118333ecb7 duration_ms=0 +2026/11/12 18:21:03 method=POST path=/api/v1/chats/ba67794f-6e3d-491d-b209-30e75075610b/messages status=400 request_id=8fbfbcbf-b7f5-44ff-9ac4-9ae8d2c0f125 duration_ms=0 +2026/11/12 18:21:03 method=POST path=/api/v1/chats/ba67794f-6e3d-491d-b209-30e75075610b/messages status=400 request_id=8adb91a2-d1b7-4c04-a70a-2220c60d9dbd duration_ms=0 +2026/11/12 18:21:03 method=POST path=/api/v1/chats/ba67794f-6e3d-491d-b209-30e75075610b/messages status=400 request_id=a4f053ab-614f-43d5-8a5d-8cb709c9ebda duration_ms=0 +2026/11/12 18:21:03 method=POST path=/api/v1/chats/ba67794f-6e3d-491d-b209-30e75075610b/messages status=400 request_id=422ad727-1d32-49f4-8c32-0e1e4d69adb7 duration_ms=0 +2026/11/12 18:21:03 method=POST path=/api/v1/chats/ba67794f-6e3d-491d-b209-30e75075610b/messages status=201 request_id=447bbf49-037b-4fcf-850b-ea704f48af30 duration_ms=3 +2026/11/12 18:21:03 method=POST path=/api/v1/chats/ba67794f-6e3d-491d-b209-30e75075610b/attachments status=201 request_id=64c91a01-556e-4f05-84b8-060f06ea9b97 duration_ms=7 +2026/11/12 18:21:03 method=POST path=/api/v1/chats/ba67794f-6e3d-491d-b209-30e75075610b/attachments status=201 request_id=198f124f-93e8-43fe-905c-35804e9e6963 duration_ms=4 +2026/11/12 18:21:03 method=POST path=/api/v1/chats/ba67794f-6e3d-491d-b209-30e75075610b/attachments status=201 request_id=89d7ca2a-fdf7-488f-b7bb-33c472bedd07 duration_ms=4 +2026/11/12 18:21:03 method=POST path=/api/v1/chats/ba67794f-6e3d-491d-b209-30e75075610b/attachments status=201 request_id=26676c65-1e95-47b1-a1c0-371aff9a3447 duration_ms=4 +2026/11/12 18:21:03 method=POST path=/api/v1/chats/ba67794f-6e3d-491d-b209-30e75075610b/attachments status=201 request_id=35039c37-0108-4258-b680-01ba331055d1 duration_ms=5 +2026/11/12 18:21:03 method=POST path=/api/v1/chats/ba67794f-6e3d-491d-b209-30e75075610b/attachments status=201 request_id=cdcaf7a0-a79a-4529-a92f-ea90dcbde1a1 duration_ms=6 +2026/11/12 18:21:03 method=POST path=/api/v1/chats/ba67794f-6e3d-491d-b209-30e75075610b/attachments status=201 request_id=959cc0c6-dd65-4176-96c7-b3be0dbf0511 duration_ms=4 +2026/11/12 18:21:03 method=POST path=/api/v1/chats/ba67794f-6e3d-491d-b209-30e75075610b/attachments status=201 request_id=01ca5d27-fa2b-4ec9-b4d9-b7c79aa3853b duration_ms=4 +2026/11/12 18:21:03 method=POST path=/api/v1/chats/ba67794f-6e3d-491d-b209-30e75075610b/attachments status=201 request_id=eea2e1c9-8160-4dd1-a51c-4f18ce4ec645 duration_ms=3 +2026/11/12 18:21:03 method=POST path=/api/v1/chats/ba67794f-6e3d-491d-b209-30e75075610b/attachments status=201 request_id=7a5bebc5-f84c-4604-baef-41ee23875067 duration_ms=3 +2026/11/12 18:21:03 method=POST path=/api/v1/chats/ba67794f-6e3d-491d-b209-30e75075610b/messages status=201 request_id=e1a3cb5e-2b70-4afa-a39f-5a7c134398dc duration_ms=5 +2026/11/12 18:21:03 method=POST path=/api/v1/chats/ba67794f-6e3d-491d-b209-30e75075610b/messages status=201 request_id=de7f1761-1e00-4c1e-b42d-5ac221473cd8 duration_ms=2 + attachments_test.go:565: ✓ чужое/другой чат/неизвестное → 404, лимиты → 400, пустой текст только с вложением +--- PASS: TestMessageAttachmentRules (0.21s) +=== RUN TestS3DownGivesLimitedError + attachments_test.go:571: → API с недоступным S3: upload/ready → 503, без утечек и полуфабрикатов в БД +2026/11/12 18:21:03 method=POST path=/api/v1/users status=201 request_id=28474f4e-0a5c-48cb-85d6-a4f8c18931be duration_ms=28 + attachments_test.go:580: создан att_down_be3d20bc id=7b75f89b-5333-4875-b920-69edf9803751 +2026/11/12 18:21:03 method=POST path=/api/v1/auth/sessions status=201 request_id=5d95ef5e-f3e5-4c97-89e9-fc2bf8d2de04 duration_ms=33 + attachments_test.go:580: сессия выпущена, длина токена=64 (значение не печатаем) +2026/11/12 18:21:03 method=POST path=/api/v1/chats status=201 request_id=e3e3a8ad-bcce-41c6-ae4e-cec583c0ebfc duration_ms=2 +2026/11/12 18:21:04 request_id=fcb84c10-04bd-4cfe-b0cf-5c546de7cee1 attachment_put_failed err=object store unavailable +2026/11/12 18:21:04 method=POST path=/api/v1/chats/67011494-ea93-4cc1-afcf-e6906dc4e560/attachments status=503 request_id=fcb84c10-04bd-4cfe-b0cf-5c546de7cee1 duration_ms=1271 + attachments_test.go:591: upload при лежащем S3: status=503 за 1.272s body={"error":{"code":"unavailable","message":"dependency unavailable","request_id":"fcb84c10-04bd-4cfe-b0cf-5c546de7cee1"}} +2026/11/12 18:21:04 method=GET path=/health/ready status=503 request_id=be8ccc50-9756-4656-b12c-2662b55dada1 duration_ms=131 + attachments_test.go:616: ✓ лежащий S3 → 503 без деталей, ready=503, live=200, БД чиста +--- PASS: TestS3DownGivesLimitedError (1.48s) +=== RUN TestCompensationWhenPostgresFailsAfterPut + attachments_test.go:633: → отказ PG после успешного PUT: объект удаляется компенсацией +2026/11/12 18:21:05 method=POST path=/api/v1/users status=201 request_id=3f4dfeac-f9bd-40af-8ca0-13391d0ef203 duration_ms=44 + attachments_test.go:635: создан att_comp_d1d08db2 id=114e5155-1aa2-46b5-9c42-fab4ff3a670d +2026/11/12 18:21:05 method=POST path=/api/v1/auth/sessions status=201 request_id=c7902eca-e898-4474-93c7-42733b26f62f duration_ms=39 + attachments_test.go:635: сессия выпущена, длина токена=64 (значение не печатаем) +2026/11/12 18:21:05 method=POST path=/api/v1/chats status=201 request_id=ebf99fd6-6fab-4182-8d46-3a73018c444d duration_ms=5 +2026/11/12 18:21:05 request_id=a8e660c6-0f0b-4e5f-8286-66dfc16e957c attachment_compensated key=attachments/3fd3ff59-5aab-4036-9021-922ba3677d30/f603c13e-4000-44c9-9eb5-42c6c5e70525 (PG insert не удался, объект удалён) +2026/11/12 18:21:05 method=POST path=/api/v1/chats/3fd3ff59-5aab-4036-9021-922ba3677d30/attachments status=503 request_id=a8e660c6-0f0b-4e5f-8286-66dfc16e957c duration_ms=9 + attachments_test.go:668: status=503 body={"error":{"code":"unavailable","message":"dependency unavailable","request_id":"a8e660c6-0f0b-4e5f-8286-66dfc16e957c"}} + key=attachments/3fd3ff59-5aab-4036-9021-922ba3677d30/f603c13e-4000-44c9-9eb5-42c6c5e70525 + attachments_test.go:682: ✓ orphan после отказа PG удалён сразу; если бы удаление не удалось — его уберёт reconciler +--- PASS: TestCompensationWhenPostgresFailsAfterPut (0.16s) +=== RUN TestConcurrentUploads + attachments_test.go:687: → 12 параллельных загрузок: все 201, уникальные id, sha256 совпадает +2026/11/12 18:21:05 method=POST path=/api/v1/users status=201 request_id=fd1ff7b6-038f-41ec-8463-3fd9dbb9b4fe duration_ms=28 + attachments_test.go:688: создан att_conc_729779e9 id=067c689f-0d1d-4b41-bdea-6eb65ae92fbc +2026/11/12 18:21:05 method=POST path=/api/v1/auth/sessions status=201 request_id=423752b8-2326-44f0-b48f-c5ae3e4eacae duration_ms=26 + attachments_test.go:688: сессия выпущена, длина токена=64 (значение не печатаем) +2026/11/12 18:21:05 method=POST path=/api/v1/chats status=201 request_id=e4b1ca4e-d18e-45ce-b60d-b88baa0cace1 duration_ms=3 +2026/11/12 18:21:05 method=POST path=/api/v1/chats/3e5fb333-8a7a-4b72-ab7c-2b0c69d79cfb/attachments status=201 request_id=842c0196-6ea1-4bb5-8450-0182451d43bb duration_ms=24 +2026/11/12 18:21:05 method=POST path=/api/v1/chats/3e5fb333-8a7a-4b72-ab7c-2b0c69d79cfb/attachments status=201 request_id=91e0e4e9-3367-4a49-b66f-057b300dc7d8 duration_ms=22 +2026/11/12 18:21:05 method=POST path=/api/v1/chats/3e5fb333-8a7a-4b72-ab7c-2b0c69d79cfb/attachments status=201 request_id=e9c7d4bf-c4aa-4ae2-8929-f83d6ef5ebd2 duration_ms=23 +2026/11/12 18:21:05 method=POST path=/api/v1/chats/3e5fb333-8a7a-4b72-ab7c-2b0c69d79cfb/attachments status=201 request_id=ea3d7a13-607e-484c-85f7-66944202c90b duration_ms=28 +2026/11/12 18:21:05 method=POST path=/api/v1/chats/3e5fb333-8a7a-4b72-ab7c-2b0c69d79cfb/attachments status=201 request_id=599764a6-60c2-4601-b010-87306de3308b duration_ms=31 +2026/11/12 18:21:05 method=POST path=/api/v1/chats/3e5fb333-8a7a-4b72-ab7c-2b0c69d79cfb/attachments status=201 request_id=7307aa9a-b9b0-42a0-9954-d2c6ac5fc73c duration_ms=34 +2026/11/12 18:21:05 method=POST path=/api/v1/chats/3e5fb333-8a7a-4b72-ab7c-2b0c69d79cfb/attachments status=201 request_id=a9fab778-7f4a-42d2-831d-c91b055316dd duration_ms=37 +2026/11/12 18:21:05 method=POST path=/api/v1/chats/3e5fb333-8a7a-4b72-ab7c-2b0c69d79cfb/attachments status=201 request_id=56bc0db3-9caf-4ab1-87e3-0b079bb65949 duration_ms=42 +2026/11/12 18:21:05 method=POST path=/api/v1/chats/3e5fb333-8a7a-4b72-ab7c-2b0c69d79cfb/attachments status=201 request_id=5bb79162-f7f8-4717-b0c6-cca67420a035 duration_ms=44 +2026/11/12 18:21:05 method=POST path=/api/v1/chats/3e5fb333-8a7a-4b72-ab7c-2b0c69d79cfb/attachments status=201 request_id=8f2b880b-faf9-4ebf-acb0-86715b023b8e duration_ms=46 +2026/11/12 18:21:05 method=POST path=/api/v1/chats/3e5fb333-8a7a-4b72-ab7c-2b0c69d79cfb/attachments status=201 request_id=b7aec8d5-0748-4f2a-aaac-dcc5ffd924b1 duration_ms=47 +2026/11/12 18:21:05 method=POST path=/api/v1/chats/3e5fb333-8a7a-4b72-ab7c-2b0c69d79cfb/attachments status=201 request_id=c6c1d078-1df0-4693-94b4-415c4ec67b61 duration_ms=49 +2026/11/12 18:21:05 method=GET path=/api/v1/attachments/7ec3a691-cfca-467b-b0a2-ff4e1f53c949/content status=200 request_id=177f750c-a9d5-4624-aa3a-7515d536e5a1 duration_ms=3 +2026/11/12 18:21:05 method=GET path=/api/v1/attachments/12529cbe-d38a-4fa9-9ae1-a5f93019d1ed/content status=200 request_id=9160b307-b1f8-4042-8ba0-6eba4bd45430 duration_ms=4 +2026/11/12 18:21:05 method=GET path=/api/v1/attachments/856c227c-f06e-414a-81e5-562ec4f1c5a8/content status=200 request_id=d2d18836-fc10-4ec4-9183-d33d39f749ea duration_ms=3 +2026/11/12 18:21:05 method=GET path=/api/v1/attachments/7e980bbe-48a1-40c7-a82a-52459dd20e46/content status=200 request_id=850aeded-fff7-4591-a889-5f3bfecefcb8 duration_ms=3 +2026/11/12 18:21:05 method=GET path=/api/v1/attachments/1fc778ae-90d7-4f91-b268-b18ef96605b6/content status=200 request_id=b176d12b-906b-49c0-bb74-605a323cd5c8 duration_ms=3 +2026/11/12 18:21:05 method=GET path=/api/v1/attachments/886f5134-5ebe-49ae-83da-9edf27026f83/content status=200 request_id=868ee301-cde4-4e17-a7a5-52cf6bbd5547 duration_ms=4 +2026/11/12 18:21:05 method=GET path=/api/v1/attachments/43e2cb09-1a68-47a2-b523-be02aea103e3/content status=200 request_id=1f3f748f-8bbb-42e7-8fe3-9a9ad3ebd46f duration_ms=3 +2026/11/12 18:21:05 method=GET path=/api/v1/attachments/d8a8d773-00b5-4090-9e23-42c7c72b4139/content status=200 request_id=2f7bc742-8fd3-4dec-aa96-983ea818e320 duration_ms=3 +2026/11/12 18:21:05 method=GET path=/api/v1/attachments/761e93f4-4522-45f8-89c8-fdae1343bb29/content status=200 request_id=e1e71780-72d2-4f6e-8228-e47881938f45 duration_ms=3 +2026/11/12 18:21:05 method=GET path=/api/v1/attachments/9dbac555-6be3-4310-83d5-a6c7fc6d949d/content status=200 request_id=22d7fc16-aeaa-4d11-976b-0996cdaae1d1 duration_ms=3 +2026/11/12 18:21:05 method=GET path=/api/v1/attachments/eb4d547a-b80d-44f6-b6c8-5a29190b3e96/content status=200 request_id=91b301eb-81a6-4ad9-a0a5-b4a0f6c9d7d3 duration_ms=3 +2026/11/12 18:21:05 method=GET path=/api/v1/attachments/c1d2796d-ee2b-462b-8190-c99cd40bf68d/content status=200 request_id=43c98164-f333-43b3-be42-85de3fe36a8d duration_ms=2 + attachments_test.go:722: ✓ параллельные загрузки целы +--- PASS: TestConcurrentUploads (0.17s) +=== RUN TestObjectKeyIsServerAssigned + attachments_test.go:727: → ключ объекта = attachments/{chat}/{id}; filename в ключ не попадает +2026/11/12 18:21:05 method=POST path=/api/v1/users status=201 request_id=4b5d980a-bb3a-42b4-9d2d-572ed3a9bc85 duration_ms=28 + attachments_test.go:728: создан att_key_890af9c3 id=7df2d519-ee05-4b51-9322-6263cc7490c3 +2026/11/12 18:21:05 method=POST path=/api/v1/auth/sessions status=201 request_id=39ca6337-75c6-4fda-a393-8292baec5db1 duration_ms=27 + attachments_test.go:728: сессия выпущена, длина токена=64 (значение не печатаем) +2026/11/12 18:21:05 method=POST path=/api/v1/chats status=201 request_id=79d3a97e-3cc5-4ae9-81cc-a0698201e9cf duration_ms=3 +2026/11/12 18:21:05 method=POST path=/api/v1/chats/70b9221c-d96d-415f-9fa6-5625c371595f/attachments status=201 request_id=13642977-9dd9-4b28-b66e-7b2d73c3a8ba duration_ms=4 + attachments_test.go:742: ✓ ключ серверный: attachments/70b9221c-d96d-415f-9fa6-5625c371595f/eb535487-7035-4e1e-9f56-8af382801a83 +--- PASS: TestObjectKeyIsServerAssigned (0.07s) +=== RUN TestReconcilerOrphanAndMissing + reconcile_test.go:25: → orphan/missing: dry-run ничего не меняет; свежие и используемые не удаляются; повтор идемпотентен +2026/11/12 18:21:05 method=POST path=/api/v1/users status=201 request_id=2e6e9279-44cd-420e-8da9-37754018b14f duration_ms=26 + reconcile_test.go:29: создан rec_081c44dc id=d3cb5e2e-d253-4d2c-b736-ccd10389a7e9 +2026/11/12 18:21:05 method=POST path=/api/v1/auth/sessions status=201 request_id=d306f630-fb12-4b39-876e-6419974cdb52 duration_ms=25 + reconcile_test.go:29: сессия выпущена, длина токена=64 (значение не печатаем) +2026/11/12 18:21:05 method=POST path=/api/v1/chats status=201 request_id=2ad9df61-3514-40d4-a630-10572053ee9b duration_ms=2 + reconcile_test.go:74: смещение часов S3 относительно теста: 436ms + reconcile.go:261: SKIP fresh orphan (age=0s < grace=1m0s): attachments/a6879c34-a366-4607-bb21-40ebb859e124/53936b3d-2a3e-4beb-892d-5a7ef38f36c7 + reconcile.go:315: SKIP fresh missing (age=0s < grace=1m0s): attachments/a6879c34-a366-4607-bb21-40ebb859e124/9146c2dd-8862-4246-a9ac-af1e88f70fd7 + reconcile.go:320: DRY-RUN missing object, unused stale row (id=91bb90cc-e9bf-444c-86c3-f71c1669aaf8) would be pruned: attachments/a6879c34-a366-4607-bb21-40ebb859e124/91bb90cc-e9bf-444c-86c3-f71c1669aaf8 + reconcile.go:312: ALERT used attachment lost its object (id=fb31ee3d-5f80-4ae1-a5ed-7e71fa766189, не удаляется): attachments/a6879c34-a366-4607-bb21-40ebb859e124/fb31ee3d-5f80-4ae1-a5ed-7e71fa766189 + reconcile.go:254: SKIP unknown key (вне схемы attachments/{uuid}/{uuid}): attachments/not-a-uuid/779931ae-697b-418f-8be3-2284ebbe9858 + reconcile_test.go:135: R1 dry-run, now: {DryRun:true GraceSeconds:60 PruneMissing:true S3ObjectsScanned:36 DBRowsScanned:37 S3ListCalls:19 DBPages:20 HeadCalls:3 DeleteCalls:0 DurationMs:108 Matched:34 OrphansFound:0 OrphansDeleted:0 OrphansFresh:1 OrphansRaced:0 UnknownKeys:1 OrphanSampleKey:[] MissingFound:3 MissingUsed:1 MissingFresh:1 MissingStale:1 MissingPruned:0 MissingRaced:0 MissingSample:[attachments/a6879c34-a366-4607-bb21-40ebb859e124/9146c2dd-8862-4246-a9ac-af1e88f70fd7 attachments/a6879c34-a366-4607-bb21-40ebb859e124/91bb90cc-e9bf-444c-86c3-f71c1669aaf8 attachments/a6879c34-a366-4607-bb21-40ebb859e124/fb31ee3d-5f80-4ae1-a5ed-7e71fa766189] Errors:0} + reconcile.go:277: DRY-RUN would delete orphan (age=2m0s, size=14): attachments/a6879c34-a366-4607-bb21-40ebb859e124/53936b3d-2a3e-4beb-892d-5a7ef38f36c7 + reconcile.go:320: DRY-RUN missing object, unused stale row (id=9146c2dd-8862-4246-a9ac-af1e88f70fd7) would be pruned: attachments/a6879c34-a366-4607-bb21-40ebb859e124/9146c2dd-8862-4246-a9ac-af1e88f70fd7 + reconcile.go:320: DRY-RUN missing object, unused stale row (id=91bb90cc-e9bf-444c-86c3-f71c1669aaf8) would be pruned: attachments/a6879c34-a366-4607-bb21-40ebb859e124/91bb90cc-e9bf-444c-86c3-f71c1669aaf8 + reconcile.go:312: ALERT used attachment lost its object (id=fb31ee3d-5f80-4ae1-a5ed-7e71fa766189, не удаляется): attachments/a6879c34-a366-4607-bb21-40ebb859e124/fb31ee3d-5f80-4ae1-a5ed-7e71fa766189 + reconcile.go:254: SKIP unknown key (вне схемы attachments/{uuid}/{uuid}): attachments/not-a-uuid/779931ae-697b-418f-8be3-2284ebbe9858 + reconcile_test.go:147: R2 dry-run, +120s: {DryRun:true GraceSeconds:60 PruneMissing:true S3ObjectsScanned:36 DBRowsScanned:37 S3ListCalls:19 DBPages:20 HeadCalls:3 DeleteCalls:0 DurationMs:126 Matched:34 OrphansFound:1 OrphansDeleted:0 OrphansFresh:0 OrphansRaced:0 UnknownKeys:1 OrphanSampleKey:[attachments/a6879c34-a366-4607-bb21-40ebb859e124/53936b3d-2a3e-4beb-892d-5a7ef38f36c7] MissingFound:3 MissingUsed:1 MissingFresh:0 MissingStale:2 MissingPruned:0 MissingRaced:0 MissingSample:[attachments/a6879c34-a366-4607-bb21-40ebb859e124/9146c2dd-8862-4246-a9ac-af1e88f70fd7 attachments/a6879c34-a366-4607-bb21-40ebb859e124/91bb90cc-e9bf-444c-86c3-f71c1669aaf8 attachments/a6879c34-a366-4607-bb21-40ebb859e124/fb31ee3d-5f80-4ae1-a5ed-7e71fa766189] Errors:0} + reconcile.go:285: DELETED orphan (age=2m0s, size=14): attachments/a6879c34-a366-4607-bb21-40ebb859e124/53936b3d-2a3e-4beb-892d-5a7ef38f36c7 + reconcile.go:322: REPORT missing object, unused stale row (id=9146c2dd-8862-4246-a9ac-af1e88f70fd7), prune выключен: attachments/a6879c34-a366-4607-bb21-40ebb859e124/9146c2dd-8862-4246-a9ac-af1e88f70fd7 + reconcile.go:322: REPORT missing object, unused stale row (id=91bb90cc-e9bf-444c-86c3-f71c1669aaf8), prune выключен: attachments/a6879c34-a366-4607-bb21-40ebb859e124/91bb90cc-e9bf-444c-86c3-f71c1669aaf8 + reconcile.go:312: ALERT used attachment lost its object (id=fb31ee3d-5f80-4ae1-a5ed-7e71fa766189, не удаляется): attachments/a6879c34-a366-4607-bb21-40ebb859e124/fb31ee3d-5f80-4ae1-a5ed-7e71fa766189 + reconcile.go:254: SKIP unknown key (вне схемы attachments/{uuid}/{uuid}): attachments/not-a-uuid/779931ae-697b-418f-8be3-2284ebbe9858 + reconcile_test.go:156: R3 real, +120s, prune off: {DryRun:false GraceSeconds:60 PruneMissing:false S3ObjectsScanned:36 DBRowsScanned:37 S3ListCalls:19 DBPages:20 HeadCalls:3 DeleteCalls:1 DurationMs:99 Matched:34 OrphansFound:1 OrphansDeleted:1 OrphansFresh:0 OrphansRaced:0 UnknownKeys:1 OrphanSampleKey:[attachments/a6879c34-a366-4607-bb21-40ebb859e124/53936b3d-2a3e-4beb-892d-5a7ef38f36c7] MissingFound:3 MissingUsed:1 MissingFresh:0 MissingStale:2 MissingPruned:0 MissingRaced:0 MissingSample:[attachments/a6879c34-a366-4607-bb21-40ebb859e124/9146c2dd-8862-4246-a9ac-af1e88f70fd7 attachments/a6879c34-a366-4607-bb21-40ebb859e124/91bb90cc-e9bf-444c-86c3-f71c1669aaf8 attachments/a6879c34-a366-4607-bb21-40ebb859e124/fb31ee3d-5f80-4ae1-a5ed-7e71fa766189] Errors:0} + reconcile.go:315: SKIP fresh missing (age=0s < grace=1m0s): attachments/a6879c34-a366-4607-bb21-40ebb859e124/9146c2dd-8862-4246-a9ac-af1e88f70fd7 + reconcile.go:331: PRUNED row without object (id=91bb90cc-e9bf-444c-86c3-f71c1669aaf8): attachments/a6879c34-a366-4607-bb21-40ebb859e124/91bb90cc-e9bf-444c-86c3-f71c1669aaf8 + reconcile.go:312: ALERT used attachment lost its object (id=fb31ee3d-5f80-4ae1-a5ed-7e71fa766189, не удаляется): attachments/a6879c34-a366-4607-bb21-40ebb859e124/fb31ee3d-5f80-4ae1-a5ed-7e71fa766189 + reconcile.go:254: SKIP unknown key (вне схемы attachments/{uuid}/{uuid}): attachments/not-a-uuid/779931ae-697b-418f-8be3-2284ebbe9858 + reconcile_test.go:171: R4 real, now, prune on: {DryRun:false GraceSeconds:60 PruneMissing:true S3ObjectsScanned:35 DBRowsScanned:37 S3ListCalls:18 DBPages:20 HeadCalls:3 DeleteCalls:0 DurationMs:111 Matched:34 OrphansFound:0 OrphansDeleted:0 OrphansFresh:0 OrphansRaced:0 UnknownKeys:1 OrphanSampleKey:[] MissingFound:3 MissingUsed:1 MissingFresh:1 MissingStale:1 MissingPruned:1 MissingRaced:0 MissingSample:[attachments/a6879c34-a366-4607-bb21-40ebb859e124/9146c2dd-8862-4246-a9ac-af1e88f70fd7 attachments/a6879c34-a366-4607-bb21-40ebb859e124/91bb90cc-e9bf-444c-86c3-f71c1669aaf8 attachments/a6879c34-a366-4607-bb21-40ebb859e124/fb31ee3d-5f80-4ae1-a5ed-7e71fa766189] Errors:0} + reconcile.go:315: SKIP fresh missing (age=0s < grace=1m0s): attachments/a6879c34-a366-4607-bb21-40ebb859e124/9146c2dd-8862-4246-a9ac-af1e88f70fd7 + reconcile.go:312: ALERT used attachment lost its object (id=fb31ee3d-5f80-4ae1-a5ed-7e71fa766189, не удаляется): attachments/a6879c34-a366-4607-bb21-40ebb859e124/fb31ee3d-5f80-4ae1-a5ed-7e71fa766189 + reconcile.go:254: SKIP unknown key (вне схемы attachments/{uuid}/{uuid}): attachments/not-a-uuid/779931ae-697b-418f-8be3-2284ebbe9858 + reconcile_test.go:183: R5 repeat: {DryRun:false GraceSeconds:60 PruneMissing:true S3ObjectsScanned:35 DBRowsScanned:36 S3ListCalls:18 DBPages:19 HeadCalls:2 DeleteCalls:0 DurationMs:89 Matched:34 OrphansFound:0 OrphansDeleted:0 OrphansFresh:0 OrphansRaced:0 UnknownKeys:1 OrphanSampleKey:[] MissingFound:2 MissingUsed:1 MissingFresh:1 MissingStale:0 MissingPruned:0 MissingRaced:0 MissingSample:[attachments/a6879c34-a366-4607-bb21-40ebb859e124/9146c2dd-8862-4246-a9ac-af1e88f70fd7 attachments/a6879c34-a366-4607-bb21-40ebb859e124/fb31ee3d-5f80-4ae1-a5ed-7e71fa766189] Errors:0} + reconcile.go:331: PRUNED row without object (id=9146c2dd-8862-4246-a9ac-af1e88f70fd7): attachments/a6879c34-a366-4607-bb21-40ebb859e124/9146c2dd-8862-4246-a9ac-af1e88f70fd7 + reconcile.go:312: ALERT used attachment lost its object (id=fb31ee3d-5f80-4ae1-a5ed-7e71fa766189, не удаляется): attachments/a6879c34-a366-4607-bb21-40ebb859e124/fb31ee3d-5f80-4ae1-a5ed-7e71fa766189 + reconcile.go:254: SKIP unknown key (вне схемы attachments/{uuid}/{uuid}): attachments/not-a-uuid/779931ae-697b-418f-8be3-2284ebbe9858 + reconcile_test.go:189: R6 real, +120s, prune on: {DryRun:false GraceSeconds:60 PruneMissing:true S3ObjectsScanned:35 DBRowsScanned:36 S3ListCalls:18 DBPages:19 HeadCalls:2 DeleteCalls:0 DurationMs:113 Matched:34 OrphansFound:0 OrphansDeleted:0 OrphansFresh:0 OrphansRaced:0 UnknownKeys:1 OrphanSampleKey:[] MissingFound:2 MissingUsed:1 MissingFresh:0 MissingStale:1 MissingPruned:1 MissingRaced:0 MissingSample:[attachments/a6879c34-a366-4607-bb21-40ebb859e124/9146c2dd-8862-4246-a9ac-af1e88f70fd7 attachments/a6879c34-a366-4607-bb21-40ebb859e124/fb31ee3d-5f80-4ae1-a5ed-7e71fa766189] Errors:0} + reconcile_test.go:197: ✓ orphan удалён после grace, чужие ключи/свежие/используемые целы, dry-run и повтор безопасны +--- PASS: TestReconcilerOrphanAndMissing (0.75s) PASS -ok mtusi2026lab4/student-tests 4.450s +ok mtusi2026lab4/student-tests 7.559s diff --git a/evidence/track2-run.txt b/evidence/track2-run.txt new file mode 100644 index 00000000..b578774f --- /dev/null +++ b/evidence/track2-run.txt @@ -0,0 +1,30 @@ +bash scripts/run_track2.sh +== 1. подготовка данных через API +== 2. инъекция сбоев в S3 (root-учётка mc, только для сценария) + пачка из 300 orphan-объектов для замера стоимости обхода +== 3. ждём 45+2 с: orphan_old/missing_stale «стареют» за grace + теперь «свежие» нарушения (моложе grace): +== 4. dry-run (ничего не должно измениться) + 1_dry_run: exit=2 (orphans_found=301 deleted=0 missing_found=3 used=1 pruned=0 duration_ms=82) +== 5. реальный запуск + 2_real: exit=2 (orphans_found=301 deleted=301 missing_found=3 used=1 pruned=1 duration_ms=357) +== 6. повторный запуск (идемпотентность) + 3_repeat: exit=2 (orphans_found=0 deleted=0 missing_found=2 used=1 pruned=0 duration_ms=17) +== 7. проверка инвариантов +PASS dry-run не менял данные +PASS dry-run нашёл orphan-ы, но не удалил (deleted=0) +PASS dry-run: missing used/stale/fresh обнаружены +PASS real: orphan_old и пачка удалены +PASS real: orphan_old действительно исчез из S3 +PASS real: свежий orphan цел +PASS real: объект с чужой схемой ключа цел +PASS real: control (строка+объект) цел +PASS real: used без объекта НЕ удалён, есть alert +PASS real: stale unused без объекта удалена (prune) +PASS real: fresh без объекта НЕ удалена +PASS repeat: идемпотентность (0 удалений, 0 prune) +# Стоимость обхода (из JSON-отчётов) +1_dry_run s3_objects=342 db_rows=42 s3_list_calls=1 db_pages=2 head_calls=3 delete_calls=0 duration_ms=82 +2_real s3_objects=342 db_rows=42 s3_list_calls=1 db_pages=2 head_calls=3 delete_calls=301 duration_ms=357 +3_repeat s3_objects=41 db_rows=41 s3_list_calls=1 db_pages=2 head_calls=2 delete_calls=0 duration_ms=17 +ИТОГ track2: все инварианты выполнены (evidence в evidence/track2/) diff --git a/evidence/track2/1_dry_run.exitcode b/evidence/track2/1_dry_run.exitcode new file mode 100644 index 00000000..0cfbf088 --- /dev/null +++ b/evidence/track2/1_dry_run.exitcode @@ -0,0 +1 @@ +2 diff --git a/evidence/track2/1_dry_run.json b/evidence/track2/1_dry_run.json new file mode 100644 index 00000000..bfae9ded --- /dev/null +++ b/evidence/track2/1_dry_run.json @@ -0,0 +1,82 @@ +{ + "dry_run": true, + "grace_seconds": 45, + "prune_missing": true, + "s3_objects_scanned": 342, + "db_rows_scanned": 42, + "s3_list_calls": 1, + "db_pages": 2, + "s3_head_calls": 3, + "s3_delete_calls": 0, + "duration_ms": 82, + "matched": 39, + "orphans_found": 301, + "orphans_deleted": 0, + "orphans_fresh": 1, + "orphans_raced": 0, + "unknown_keys": 1, + "orphan_sample_keys": [ + "attachments/c663250b-ffcf-4b99-bc00-685e249bec01/ded39c6a-59db-4b8c-ab68-22b1dd015ed7", + "attachments/dd91de03-4651-4d65-a91b-08b3e9e2d8f0/00ad9195-f154-41ec-b8e1-b5bcd007bf70", + "attachments/dd91de03-4651-4d65-a91b-08b3e9e2d8f0/00b04295-d403-4a7c-8f0a-b1acf9445b54", + "attachments/dd91de03-4651-4d65-a91b-08b3e9e2d8f0/021b397d-b610-42ff-ba41-1df1eddc0c15", + "attachments/dd91de03-4651-4d65-a91b-08b3e9e2d8f0/039cdcb0-a161-4f3b-bcd2-f023b925056c", + "attachments/dd91de03-4651-4d65-a91b-08b3e9e2d8f0/03a9a04a-2de8-4d5a-938d-491b81c17d8a", + "attachments/dd91de03-4651-4d65-a91b-08b3e9e2d8f0/04765935-ee49-4470-ad20-760e0194e03e", + "attachments/dd91de03-4651-4d65-a91b-08b3e9e2d8f0/04dbb0dc-00d6-494f-9cd0-7fc1e14347b7", + "attachments/dd91de03-4651-4d65-a91b-08b3e9e2d8f0/058b9e86-cd0d-4c0f-9de5-9f9e65ec5cbf", + "attachments/dd91de03-4651-4d65-a91b-08b3e9e2d8f0/0656e05f-6957-4581-bf0b-85076bd1f850", + "attachments/dd91de03-4651-4d65-a91b-08b3e9e2d8f0/06cd38d1-233b-44d0-ab5f-9a0f05c7d3a0", + "attachments/dd91de03-4651-4d65-a91b-08b3e9e2d8f0/070c49a4-be67-45cf-a727-9c535b589ecb", + "attachments/dd91de03-4651-4d65-a91b-08b3e9e2d8f0/07f9b3a5-7f2b-4c09-8ea7-a6e3efbf8e2c", + "attachments/dd91de03-4651-4d65-a91b-08b3e9e2d8f0/0817d1c4-1341-4255-8e2b-5676797b0be3", + "attachments/dd91de03-4651-4d65-a91b-08b3e9e2d8f0/0838a07c-dcae-4076-bcbf-eb53753177a2", + "attachments/dd91de03-4651-4d65-a91b-08b3e9e2d8f0/087ca7b1-0f38-4517-9866-16d9a8ba95b8", + "attachments/dd91de03-4651-4d65-a91b-08b3e9e2d8f0/08a49513-d0d4-43e9-b3e9-8203c291b023", + "attachments/dd91de03-4651-4d65-a91b-08b3e9e2d8f0/0963b36c-0375-41e6-b763-6e5c4a5dcd29", + "attachments/dd91de03-4651-4d65-a91b-08b3e9e2d8f0/09fbeba6-4bfb-459a-ac1c-022543a48760", + "attachments/dd91de03-4651-4d65-a91b-08b3e9e2d8f0/0ad6ad0c-1e38-4430-a9a9-a3d9937753df", + "attachments/dd91de03-4651-4d65-a91b-08b3e9e2d8f0/0b82a572-89b0-4ad5-82bc-d321f09fc05f", + "attachments/dd91de03-4651-4d65-a91b-08b3e9e2d8f0/0bba8c5b-cfe9-405b-9c63-9ca75c8800d7", + "attachments/dd91de03-4651-4d65-a91b-08b3e9e2d8f0/0e25074c-fc1d-4a77-a208-bb278f93ea62", + "attachments/dd91de03-4651-4d65-a91b-08b3e9e2d8f0/0e2b663e-f32d-4550-8a0d-ebefbb02a47c", + "attachments/dd91de03-4651-4d65-a91b-08b3e9e2d8f0/0f7d1a3e-23eb-4a9f-aeeb-53d0b2f21982", + "attachments/dd91de03-4651-4d65-a91b-08b3e9e2d8f0/104c44f5-5fe3-41e0-b576-afd4d6c342c4", + "attachments/dd91de03-4651-4d65-a91b-08b3e9e2d8f0/1057fcab-bfda-47ed-8e0c-31ba7614758c", + "attachments/dd91de03-4651-4d65-a91b-08b3e9e2d8f0/10945365-d87f-4581-a69c-a520a959a1f5", + "attachments/dd91de03-4651-4d65-a91b-08b3e9e2d8f0/10ea6156-2bb0-4a75-862c-e8e2af426ea1", + "attachments/dd91de03-4651-4d65-a91b-08b3e9e2d8f0/110e2087-08b8-493b-9c4d-b22220f05d3a", + "attachments/dd91de03-4651-4d65-a91b-08b3e9e2d8f0/114a75a8-1211-443c-8bd5-4558a4971104", + "attachments/dd91de03-4651-4d65-a91b-08b3e9e2d8f0/11d0fc7b-e96f-42bf-a6a2-f85102ec038b", + "attachments/dd91de03-4651-4d65-a91b-08b3e9e2d8f0/14b30e10-d80a-4118-b152-0e1a7dd9a06a", + "attachments/dd91de03-4651-4d65-a91b-08b3e9e2d8f0/157ebb20-4c70-4938-aa3f-5e8f67464e02", + "attachments/dd91de03-4651-4d65-a91b-08b3e9e2d8f0/182ace2b-7d4f-4b76-94c9-fac65a57a58d", + "attachments/dd91de03-4651-4d65-a91b-08b3e9e2d8f0/1998e8d6-4a41-451f-b34e-0aafbd7e17f9", + "attachments/dd91de03-4651-4d65-a91b-08b3e9e2d8f0/1b9e2efe-436a-457c-bb0a-b517b7007484", + "attachments/dd91de03-4651-4d65-a91b-08b3e9e2d8f0/1bdb7260-923e-49d4-8383-437dcfd6d689", + "attachments/dd91de03-4651-4d65-a91b-08b3e9e2d8f0/1c8a308a-37e3-4f78-9f49-2d59d40435e5", + "attachments/dd91de03-4651-4d65-a91b-08b3e9e2d8f0/1d62b390-7c52-428c-8ff4-8d26c02619e0", + "attachments/dd91de03-4651-4d65-a91b-08b3e9e2d8f0/1dd3d1c4-f2fc-408c-a769-ca7473c2ed0d", + "attachments/dd91de03-4651-4d65-a91b-08b3e9e2d8f0/1dfb697b-e9db-44b1-848d-4f0fdbefde1e", + "attachments/dd91de03-4651-4d65-a91b-08b3e9e2d8f0/1e1e0483-4532-4402-b523-b88a7fa99fcb", + "attachments/dd91de03-4651-4d65-a91b-08b3e9e2d8f0/1ef09544-7b5b-4732-8a10-564fc2f41a26", + "attachments/dd91de03-4651-4d65-a91b-08b3e9e2d8f0/1fe30ad6-0fde-47de-9efa-3d38d9a599b5", + "attachments/dd91de03-4651-4d65-a91b-08b3e9e2d8f0/226aa095-45db-47b8-ab36-3cb884d4efa4", + "attachments/dd91de03-4651-4d65-a91b-08b3e9e2d8f0/2409cc53-7aaf-4feb-bc76-70f5c4fe0ef5", + "attachments/dd91de03-4651-4d65-a91b-08b3e9e2d8f0/26008aac-6963-4ffa-b066-2d2b47313752", + "attachments/dd91de03-4651-4d65-a91b-08b3e9e2d8f0/28500936-1e4a-47b4-a239-40c4d6c439b3", + "attachments/dd91de03-4651-4d65-a91b-08b3e9e2d8f0/28f82c57-fab8-40f3-8037-a3642a393188" + ], + "missing_found": 3, + "missing_used": 1, + "missing_fresh": 1, + "missing_stale": 1, + "missing_pruned": 0, + "missing_raced": 0, + "missing_sample_keys": [ + "attachments/81c741de-ff8a-4ba5-ac62-a5ff24b813be/099a16b6-c97f-49af-9b50-dfb3ac7c915f", + "attachments/81c741de-ff8a-4ba5-ac62-a5ff24b813be/1ae801fe-496f-4d56-97e9-e5d35d93adb3", + "attachments/81c741de-ff8a-4ba5-ac62-a5ff24b813be/ae998afd-4424-4cd3-8153-f4e45deb3a07" + ], + "errors": 0 +} diff --git a/evidence/track2/2_real.exitcode b/evidence/track2/2_real.exitcode new file mode 100644 index 00000000..0cfbf088 --- /dev/null +++ b/evidence/track2/2_real.exitcode @@ -0,0 +1 @@ +2 diff --git a/evidence/track2/2_real.json b/evidence/track2/2_real.json new file mode 100644 index 00000000..23900551 --- /dev/null +++ b/evidence/track2/2_real.json @@ -0,0 +1,82 @@ +{ + "dry_run": false, + "grace_seconds": 45, + "prune_missing": true, + "s3_objects_scanned": 342, + "db_rows_scanned": 42, + "s3_list_calls": 1, + "db_pages": 2, + "s3_head_calls": 3, + "s3_delete_calls": 301, + "duration_ms": 357, + "matched": 39, + "orphans_found": 301, + "orphans_deleted": 301, + "orphans_fresh": 1, + "orphans_raced": 0, + "unknown_keys": 1, + "orphan_sample_keys": [ + "attachments/c663250b-ffcf-4b99-bc00-685e249bec01/ded39c6a-59db-4b8c-ab68-22b1dd015ed7", + "attachments/dd91de03-4651-4d65-a91b-08b3e9e2d8f0/00ad9195-f154-41ec-b8e1-b5bcd007bf70", + "attachments/dd91de03-4651-4d65-a91b-08b3e9e2d8f0/00b04295-d403-4a7c-8f0a-b1acf9445b54", + "attachments/dd91de03-4651-4d65-a91b-08b3e9e2d8f0/021b397d-b610-42ff-ba41-1df1eddc0c15", + "attachments/dd91de03-4651-4d65-a91b-08b3e9e2d8f0/039cdcb0-a161-4f3b-bcd2-f023b925056c", + "attachments/dd91de03-4651-4d65-a91b-08b3e9e2d8f0/03a9a04a-2de8-4d5a-938d-491b81c17d8a", + "attachments/dd91de03-4651-4d65-a91b-08b3e9e2d8f0/04765935-ee49-4470-ad20-760e0194e03e", + "attachments/dd91de03-4651-4d65-a91b-08b3e9e2d8f0/04dbb0dc-00d6-494f-9cd0-7fc1e14347b7", + "attachments/dd91de03-4651-4d65-a91b-08b3e9e2d8f0/058b9e86-cd0d-4c0f-9de5-9f9e65ec5cbf", + "attachments/dd91de03-4651-4d65-a91b-08b3e9e2d8f0/0656e05f-6957-4581-bf0b-85076bd1f850", + "attachments/dd91de03-4651-4d65-a91b-08b3e9e2d8f0/06cd38d1-233b-44d0-ab5f-9a0f05c7d3a0", + "attachments/dd91de03-4651-4d65-a91b-08b3e9e2d8f0/070c49a4-be67-45cf-a727-9c535b589ecb", + "attachments/dd91de03-4651-4d65-a91b-08b3e9e2d8f0/07f9b3a5-7f2b-4c09-8ea7-a6e3efbf8e2c", + "attachments/dd91de03-4651-4d65-a91b-08b3e9e2d8f0/0817d1c4-1341-4255-8e2b-5676797b0be3", + "attachments/dd91de03-4651-4d65-a91b-08b3e9e2d8f0/0838a07c-dcae-4076-bcbf-eb53753177a2", + "attachments/dd91de03-4651-4d65-a91b-08b3e9e2d8f0/087ca7b1-0f38-4517-9866-16d9a8ba95b8", + "attachments/dd91de03-4651-4d65-a91b-08b3e9e2d8f0/08a49513-d0d4-43e9-b3e9-8203c291b023", + "attachments/dd91de03-4651-4d65-a91b-08b3e9e2d8f0/0963b36c-0375-41e6-b763-6e5c4a5dcd29", + "attachments/dd91de03-4651-4d65-a91b-08b3e9e2d8f0/09fbeba6-4bfb-459a-ac1c-022543a48760", + "attachments/dd91de03-4651-4d65-a91b-08b3e9e2d8f0/0ad6ad0c-1e38-4430-a9a9-a3d9937753df", + "attachments/dd91de03-4651-4d65-a91b-08b3e9e2d8f0/0b82a572-89b0-4ad5-82bc-d321f09fc05f", + "attachments/dd91de03-4651-4d65-a91b-08b3e9e2d8f0/0bba8c5b-cfe9-405b-9c63-9ca75c8800d7", + "attachments/dd91de03-4651-4d65-a91b-08b3e9e2d8f0/0e25074c-fc1d-4a77-a208-bb278f93ea62", + "attachments/dd91de03-4651-4d65-a91b-08b3e9e2d8f0/0e2b663e-f32d-4550-8a0d-ebefbb02a47c", + "attachments/dd91de03-4651-4d65-a91b-08b3e9e2d8f0/0f7d1a3e-23eb-4a9f-aeeb-53d0b2f21982", + "attachments/dd91de03-4651-4d65-a91b-08b3e9e2d8f0/104c44f5-5fe3-41e0-b576-afd4d6c342c4", + "attachments/dd91de03-4651-4d65-a91b-08b3e9e2d8f0/1057fcab-bfda-47ed-8e0c-31ba7614758c", + "attachments/dd91de03-4651-4d65-a91b-08b3e9e2d8f0/10945365-d87f-4581-a69c-a520a959a1f5", + "attachments/dd91de03-4651-4d65-a91b-08b3e9e2d8f0/10ea6156-2bb0-4a75-862c-e8e2af426ea1", + "attachments/dd91de03-4651-4d65-a91b-08b3e9e2d8f0/110e2087-08b8-493b-9c4d-b22220f05d3a", + "attachments/dd91de03-4651-4d65-a91b-08b3e9e2d8f0/114a75a8-1211-443c-8bd5-4558a4971104", + "attachments/dd91de03-4651-4d65-a91b-08b3e9e2d8f0/11d0fc7b-e96f-42bf-a6a2-f85102ec038b", + "attachments/dd91de03-4651-4d65-a91b-08b3e9e2d8f0/14b30e10-d80a-4118-b152-0e1a7dd9a06a", + "attachments/dd91de03-4651-4d65-a91b-08b3e9e2d8f0/157ebb20-4c70-4938-aa3f-5e8f67464e02", + "attachments/dd91de03-4651-4d65-a91b-08b3e9e2d8f0/182ace2b-7d4f-4b76-94c9-fac65a57a58d", + "attachments/dd91de03-4651-4d65-a91b-08b3e9e2d8f0/1998e8d6-4a41-451f-b34e-0aafbd7e17f9", + "attachments/dd91de03-4651-4d65-a91b-08b3e9e2d8f0/1b9e2efe-436a-457c-bb0a-b517b7007484", + "attachments/dd91de03-4651-4d65-a91b-08b3e9e2d8f0/1bdb7260-923e-49d4-8383-437dcfd6d689", + "attachments/dd91de03-4651-4d65-a91b-08b3e9e2d8f0/1c8a308a-37e3-4f78-9f49-2d59d40435e5", + "attachments/dd91de03-4651-4d65-a91b-08b3e9e2d8f0/1d62b390-7c52-428c-8ff4-8d26c02619e0", + "attachments/dd91de03-4651-4d65-a91b-08b3e9e2d8f0/1dd3d1c4-f2fc-408c-a769-ca7473c2ed0d", + "attachments/dd91de03-4651-4d65-a91b-08b3e9e2d8f0/1dfb697b-e9db-44b1-848d-4f0fdbefde1e", + "attachments/dd91de03-4651-4d65-a91b-08b3e9e2d8f0/1e1e0483-4532-4402-b523-b88a7fa99fcb", + "attachments/dd91de03-4651-4d65-a91b-08b3e9e2d8f0/1ef09544-7b5b-4732-8a10-564fc2f41a26", + "attachments/dd91de03-4651-4d65-a91b-08b3e9e2d8f0/1fe30ad6-0fde-47de-9efa-3d38d9a599b5", + "attachments/dd91de03-4651-4d65-a91b-08b3e9e2d8f0/226aa095-45db-47b8-ab36-3cb884d4efa4", + "attachments/dd91de03-4651-4d65-a91b-08b3e9e2d8f0/2409cc53-7aaf-4feb-bc76-70f5c4fe0ef5", + "attachments/dd91de03-4651-4d65-a91b-08b3e9e2d8f0/26008aac-6963-4ffa-b066-2d2b47313752", + "attachments/dd91de03-4651-4d65-a91b-08b3e9e2d8f0/28500936-1e4a-47b4-a239-40c4d6c439b3", + "attachments/dd91de03-4651-4d65-a91b-08b3e9e2d8f0/28f82c57-fab8-40f3-8037-a3642a393188" + ], + "missing_found": 3, + "missing_used": 1, + "missing_fresh": 1, + "missing_stale": 1, + "missing_pruned": 1, + "missing_raced": 0, + "missing_sample_keys": [ + "attachments/81c741de-ff8a-4ba5-ac62-a5ff24b813be/099a16b6-c97f-49af-9b50-dfb3ac7c915f", + "attachments/81c741de-ff8a-4ba5-ac62-a5ff24b813be/1ae801fe-496f-4d56-97e9-e5d35d93adb3", + "attachments/81c741de-ff8a-4ba5-ac62-a5ff24b813be/ae998afd-4424-4cd3-8153-f4e45deb3a07" + ], + "errors": 0 +} diff --git a/evidence/track2/3_repeat.exitcode b/evidence/track2/3_repeat.exitcode new file mode 100644 index 00000000..0cfbf088 --- /dev/null +++ b/evidence/track2/3_repeat.exitcode @@ -0,0 +1 @@ +2 diff --git a/evidence/track2/3_repeat.json b/evidence/track2/3_repeat.json new file mode 100644 index 00000000..bc5f521f --- /dev/null +++ b/evidence/track2/3_repeat.json @@ -0,0 +1,29 @@ +{ + "dry_run": false, + "grace_seconds": 45, + "prune_missing": true, + "s3_objects_scanned": 41, + "db_rows_scanned": 41, + "s3_list_calls": 1, + "db_pages": 2, + "s3_head_calls": 2, + "s3_delete_calls": 0, + "duration_ms": 17, + "matched": 39, + "orphans_found": 0, + "orphans_deleted": 0, + "orphans_fresh": 1, + "orphans_raced": 0, + "unknown_keys": 1, + "missing_found": 2, + "missing_used": 1, + "missing_fresh": 1, + "missing_stale": 0, + "missing_pruned": 0, + "missing_raced": 0, + "missing_sample_keys": [ + "attachments/81c741de-ff8a-4ba5-ac62-a5ff24b813be/1ae801fe-496f-4d56-97e9-e5d35d93adb3", + "attachments/81c741de-ff8a-4ba5-ac62-a5ff24b813be/ae998afd-4424-4cd3-8153-f4e45deb3a07" + ], + "errors": 0 +} diff --git a/evidence/track2/cost.txt b/evidence/track2/cost.txt new file mode 100644 index 00000000..3573c654 --- /dev/null +++ b/evidence/track2/cost.txt @@ -0,0 +1,4 @@ +# Стоимость обхода (из JSON-отчётов) +1_dry_run s3_objects=342 db_rows=42 s3_list_calls=1 db_pages=2 head_calls=3 delete_calls=0 duration_ms=82 +2_real s3_objects=342 db_rows=42 s3_list_calls=1 db_pages=2 head_calls=3 delete_calls=301 duration_ms=357 +3_repeat s3_objects=41 db_rows=41 s3_list_calls=1 db_pages=2 head_calls=2 delete_calls=0 duration_ms=17 diff --git a/evidence/track2/environment.txt b/evidence/track2/environment.txt new file mode 100644 index 00000000..22295ea4 --- /dev/null +++ b/evidence/track2/environment.txt @@ -0,0 +1,4 @@ +date_utc=2026-11-12T15:21:46Z +git_commit=7cbb75c +grace_seconds=45 bulk_orphans=300 +api_replicas=2 diff --git a/evidence/track2/state_after_dry_run.txt b/evidence/track2/state_after_dry_run.txt new file mode 100644 index 00000000..80292527 --- /dev/null +++ b/evidence/track2/state_after_dry_run.txt @@ -0,0 +1,12 @@ +object attachments/c663250b-ffcf-4b99-bc00-685e249bec01/ded39c6a-59db-4b8c-ab68-22b1dd015ed7 +object attachments/74a0c5c8-52c2-4593-8412-faecd3b8d224/df2d1ad8-b8a4-4396-bd4d-c1f1e2dc6ea4 +object attachments/not-a-uuid/11beac19-a9cc-4b6f-aced-890d4b34f4df +object attachments/81c741de-ff8a-4ba5-ac62-a5ff24b813be/dcf68250-72e0-4027-a61d-17858bb60937 +NO-object attachments/81c741de-ff8a-4ba5-ac62-a5ff24b813be/1ae801fe-496f-4d56-97e9-e5d35d93adb3 +NO-object attachments/81c741de-ff8a-4ba5-ac62-a5ff24b813be/099a16b6-c97f-49af-9b50-dfb3ac7c915f +NO-object attachments/81c741de-ff8a-4ba5-ac62-a5ff24b813be/ae998afd-4424-4cd3-8153-f4e45deb3a07 +row[control]=1 +row[used]=1 +row[stale]=1 +row[fresh]=1 +bulk_objects=300 diff --git a/evidence/track2/state_after_real.txt b/evidence/track2/state_after_real.txt new file mode 100644 index 00000000..3fb8c532 --- /dev/null +++ b/evidence/track2/state_after_real.txt @@ -0,0 +1,12 @@ +NO-object attachments/c663250b-ffcf-4b99-bc00-685e249bec01/ded39c6a-59db-4b8c-ab68-22b1dd015ed7 +object attachments/74a0c5c8-52c2-4593-8412-faecd3b8d224/df2d1ad8-b8a4-4396-bd4d-c1f1e2dc6ea4 +object attachments/not-a-uuid/11beac19-a9cc-4b6f-aced-890d4b34f4df +object attachments/81c741de-ff8a-4ba5-ac62-a5ff24b813be/dcf68250-72e0-4027-a61d-17858bb60937 +NO-object attachments/81c741de-ff8a-4ba5-ac62-a5ff24b813be/1ae801fe-496f-4d56-97e9-e5d35d93adb3 +NO-object attachments/81c741de-ff8a-4ba5-ac62-a5ff24b813be/099a16b6-c97f-49af-9b50-dfb3ac7c915f +NO-object attachments/81c741de-ff8a-4ba5-ac62-a5ff24b813be/ae998afd-4424-4cd3-8153-f4e45deb3a07 +row[control]=1 +row[used]=1 +row[stale]=0 +row[fresh]=1 +bulk_objects=0 diff --git a/evidence/track2/state_before.txt b/evidence/track2/state_before.txt new file mode 100644 index 00000000..80292527 --- /dev/null +++ b/evidence/track2/state_before.txt @@ -0,0 +1,12 @@ +object attachments/c663250b-ffcf-4b99-bc00-685e249bec01/ded39c6a-59db-4b8c-ab68-22b1dd015ed7 +object attachments/74a0c5c8-52c2-4593-8412-faecd3b8d224/df2d1ad8-b8a4-4396-bd4d-c1f1e2dc6ea4 +object attachments/not-a-uuid/11beac19-a9cc-4b6f-aced-890d4b34f4df +object attachments/81c741de-ff8a-4ba5-ac62-a5ff24b813be/dcf68250-72e0-4027-a61d-17858bb60937 +NO-object attachments/81c741de-ff8a-4ba5-ac62-a5ff24b813be/1ae801fe-496f-4d56-97e9-e5d35d93adb3 +NO-object attachments/81c741de-ff8a-4ba5-ac62-a5ff24b813be/099a16b6-c97f-49af-9b50-dfb3ac7c915f +NO-object attachments/81c741de-ff8a-4ba5-ac62-a5ff24b813be/ae998afd-4424-4cd3-8153-f4e45deb3a07 +row[control]=1 +row[used]=1 +row[stale]=1 +row[fresh]=1 +bulk_objects=300 diff --git a/evidence/upload-mem-run.txt b/evidence/upload-mem-run.txt new file mode 100644 index 00000000..8662f0eb --- /dev/null +++ b/evidence/upload-mem-run.txt @@ -0,0 +1,18 @@ +bash scripts/upload_mem_experiment.sh +== генерация PNG-шума 1600x1600 +размер файла: 7.33 MiB +== случай UPLOAD_MAX_CONCURRENCY=64: пересоздаём API (replicas=2) +--- UPLOAD_MAX_CONCURRENCY=64 (параллельных клиентов=20, повторов=4, файл=7684003 байт, длительность=10s) +статусы HTTP: 80 201 +время ответа: min=0.58s p50=1.94s max=4.43s +пик памяти реплик, MiB (лимит контейнера 256M): + mtusi2026lab4-api-1: idle=25.2 peak=172.0 + mtusi2026lab4-api-2: idle=25.6 peak=171.7 +== случай UPLOAD_MAX_CONCURRENCY=4: пересоздаём API (replicas=2) +--- UPLOAD_MAX_CONCURRENCY=4 (параллельных клиентов=20, повторов=4, файл=7684003 байт, длительность=7s) +статусы HTTP: 80 201 +время ответа: min=0.41s p50=1.40s max=3.45s +пик памяти реплик, MiB (лимит контейнера 256M): + mtusi2026lab4-api-1: idle=25.7 peak=78.4 + mtusi2026lab4-api-2: idle=25.4 peak=83.7 +готово: evidence/upload-memory/summary.txt diff --git a/evidence/upload-memory/limit_4.stats b/evidence/upload-memory/limit_4.stats new file mode 100644 index 00000000..d327ec41 --- /dev/null +++ b/evidence/upload-memory/limit_4.stats @@ -0,0 +1,201 @@ +mtusi2026lab4-api-1 25.67MiB / 256MiB +mtusi2026lab4-api-2 25.38MiB / 256MiB +mtusi2026lab4-api-1 25.67MiB / 256MiB  +mtusi2026lab4-api-2 25.38MiB / 256MiB  +  +mtusi2026lab4-api-1 25.67MiB / 256MiB +mtusi2026lab4-api-2 25.38MiB / 256MiB +mtusi2026lab4-api-1 25.67MiB / 256MiB  +mtusi2026lab4-api-2 25.38MiB / 256MiB  +  +mtusi2026lab4-api-1 25.68MiB / 256MiB +mtusi2026lab4-api-2 25.39MiB / 256MiB +mtusi2026lab4-api-1 25.68MiB / 256MiB  +mtusi2026lab4-api-2 25.39MiB / 256MiB  +  +mtusi2026lab4-api-1 25.68MiB / 256MiB +mtusi2026lab4-api-2 25.39MiB / 256MiB +mtusi2026lab4-api-1 25.68MiB / 256MiB  +mtusi2026lab4-api-2 25.39MiB / 256MiB  +  +mtusi2026lab4-api-1 25.68MiB / 256MiB +mtusi2026lab4-api-2 25.52MiB / 256MiB +mtusi2026lab4-api-1 25.68MiB / 256MiB  +mtusi2026lab4-api-2 25.52MiB / 256MiB  +  +mtusi2026lab4-api-1 25.68MiB / 256MiB +mtusi2026lab4-api-2 25.52MiB / 256MiB +mtusi2026lab4-api-1 25.68MiB / 256MiB  +mtusi2026lab4-api-2 25.52MiB / 256MiB  +  +mtusi2026lab4-api-1 42.18MiB / 256MiB +mtusi2026lab4-api-2 45.74MiB / 256MiB +mtusi2026lab4-api-1 42.18MiB / 256MiB  +mtusi2026lab4-api-2 45.74MiB / 256MiB  +  +mtusi2026lab4-api-1 42.18MiB / 256MiB +mtusi2026lab4-api-2 45.74MiB / 256MiB +mtusi2026lab4-api-1 42.18MiB / 256MiB  +mtusi2026lab4-api-2 45.74MiB / 256MiB  +  +mtusi2026lab4-api-1 59.63MiB / 256MiB +mtusi2026lab4-api-2 58.85MiB / 256MiB +mtusi2026lab4-api-1 59.63MiB / 256MiB  +mtusi2026lab4-api-2 58.85MiB / 256MiB  +  +mtusi2026lab4-api-1 59.63MiB / 256MiB +mtusi2026lab4-api-2 58.85MiB / 256MiB +mtusi2026lab4-api-1 59.63MiB / 256MiB  +mtusi2026lab4-api-2 58.85MiB / 256MiB  +  +mtusi2026lab4-api-1 72.73MiB / 256MiB +mtusi2026lab4-api-2 75.04MiB / 256MiB +mtusi2026lab4-api-1 72.73MiB / 256MiB  +mtusi2026lab4-api-2 75.04MiB / 256MiB  +  +mtusi2026lab4-api-1 72.73MiB / 256MiB +mtusi2026lab4-api-2 75.04MiB / 256MiB +mtusi2026lab4-api-1 72.73MiB / 256MiB  +mtusi2026lab4-api-2 75.04MiB / 256MiB  +  +mtusi2026lab4-api-1 78.41MiB / 256MiB +mtusi2026lab4-api-2 83.72MiB / 256MiB +mtusi2026lab4-api-1 78.41MiB / 256MiB  +mtusi2026lab4-api-2 83.72MiB / 256MiB  +  +mtusi2026lab4-api-1 78.41MiB / 256MiB +mtusi2026lab4-api-2 83.72MiB / 256MiB +mtusi2026lab4-api-1 78.41MiB / 256MiB  +mtusi2026lab4-api-2 83.72MiB / 256MiB  +  +mtusi2026lab4-api-1 76.77MiB / 256MiB +mtusi2026lab4-api-2 78.75MiB / 256MiB +mtusi2026lab4-api-1 76.77MiB / 256MiB  +mtusi2026lab4-api-2 78.75MiB / 256MiB  +  +mtusi2026lab4-api-1 76.77MiB / 256MiB +mtusi2026lab4-api-2 78.75MiB / 256MiB +mtusi2026lab4-api-1 76.77MiB / 256MiB  +mtusi2026lab4-api-2 78.75MiB / 256MiB  +  +mtusi2026lab4-api-1 75.07MiB / 256MiB +mtusi2026lab4-api-2 74.89MiB / 256MiB +mtusi2026lab4-api-1 75.07MiB / 256MiB  +mtusi2026lab4-api-2 74.89MiB / 256MiB  +  +mtusi2026lab4-api-1 75.07MiB / 256MiB +mtusi2026lab4-api-2 74.89MiB / 256MiB +mtusi2026lab4-api-1 75.07MiB / 256MiB  +mtusi2026lab4-api-2 74.89MiB / 256MiB  +  +mtusi2026lab4-api-1 76.92MiB / 256MiB +mtusi2026lab4-api-2 74.88MiB / 256MiB +mtusi2026lab4-api-1 76.92MiB / 256MiB  +mtusi2026lab4-api-2 74.88MiB / 256MiB  +  +mtusi2026lab4-api-1 76.92MiB / 256MiB +mtusi2026lab4-api-2 74.88MiB / 256MiB +mtusi2026lab4-api-1 76.92MiB / 256MiB  +mtusi2026lab4-api-2 74.88MiB / 256MiB  +  +mtusi2026lab4-api-1 76.89MiB / 256MiB +mtusi2026lab4-api-2 74.65MiB / 256MiB +mtusi2026lab4-api-1 76.89MiB / 256MiB  +mtusi2026lab4-api-2 74.65MiB / 256MiB  +  +mtusi2026lab4-api-1 76.89MiB / 256MiB +mtusi2026lab4-api-2 74.65MiB / 256MiB +mtusi2026lab4-api-1 76.89MiB / 256MiB  +mtusi2026lab4-api-2 74.65MiB / 256MiB  +  +mtusi2026lab4-api-1 76.9MiB / 256MiB +mtusi2026lab4-api-2 74.65MiB / 256MiB +mtusi2026lab4-api-1 76.9MiB / 256MiB  +mtusi2026lab4-api-2 74.65MiB / 256MiB  +  +mtusi2026lab4-api-1 76.9MiB / 256MiB +mtusi2026lab4-api-2 74.65MiB / 256MiB +mtusi2026lab4-api-1 76.9MiB / 256MiB  +mtusi2026lab4-api-2 74.65MiB / 256MiB  +  +mtusi2026lab4-api-1 76.9MiB / 256MiB +mtusi2026lab4-api-2 74.65MiB / 256MiB +mtusi2026lab4-api-1 76.9MiB / 256MiB  +mtusi2026lab4-api-2 74.65MiB / 256MiB  +  +mtusi2026lab4-api-1 -- / -- +mtusi2026lab4-api-2 -- / -- +mtusi2026lab4-api-1 -- / --  +mtusi2026lab4-api-2 -- / --  +  +mtusi2026lab4-api-1 -- / -- +mtusi2026lab4-api-2 -- / -- +mtusi2026lab4-api-1 -- / --  +mtusi2026lab4-api-2 -- / --  +  +mtusi2026lab4-api-1 -- / -- +mtusi2026lab4-api-2 -- / -- +mtusi2026lab4-api-1 -- / --  +mtusi2026lab4-api-2 -- / --  +  +mtusi2026lab4-api-1 -- / -- +mtusi2026lab4-api-2 -- / -- +mtusi2026lab4-api-1 -- / --  +mtusi2026lab4-api-2 -- / --  +  +mtusi2026lab4-api-1 -- / -- +mtusi2026lab4-api-2 -- / -- +mtusi2026lab4-api-1 -- / --  +mtusi2026lab4-api-2 -- / --  +  +mtusi2026lab4-api-1 -- / -- +mtusi2026lab4-api-2 -- / -- +mtusi2026lab4-api-1 -- / --  +mtusi2026lab4-api-2 -- / --  +  +mtusi2026lab4-api-1 -- / -- +mtusi2026lab4-api-2 -- / -- +mtusi2026lab4-api-1 -- / --  +mtusi2026lab4-api-2 -- / --  +  +mtusi2026lab4-api-1 -- / -- +mtusi2026lab4-api-2 -- / -- +mtusi2026lab4-api-1 -- / --  +mtusi2026lab4-api-2 -- / --  +  +mtusi2026lab4-api-1 -- / -- +mtusi2026lab4-api-2 -- / -- +mtusi2026lab4-api-1 -- / --  +mtusi2026lab4-api-2 -- / --  +  +mtusi2026lab4-api-1 -- / -- +mtusi2026lab4-api-2 -- / -- +mtusi2026lab4-api-1 -- / --  +mtusi2026lab4-api-2 -- / --  +  +mtusi2026lab4-api-1 -- / -- +mtusi2026lab4-api-2 -- / -- +mtusi2026lab4-api-1 -- / --  +mtusi2026lab4-api-2 -- / --  +  +mtusi2026lab4-api-1 -- / -- +mtusi2026lab4-api-2 -- / -- +mtusi2026lab4-api-1 -- / --  +mtusi2026lab4-api-2 -- / --  +  +mtusi2026lab4-api-1 -- / -- +mtusi2026lab4-api-2 -- / -- +mtusi2026lab4-api-1 -- / --  +mtusi2026lab4-api-2 -- / --  +  +mtusi2026lab4-api-1 -- / -- +mtusi2026lab4-api-2 -- / -- +mtusi2026lab4-api-1 -- / --  +mtusi2026lab4-api-2 -- / --  +  +mtusi2026lab4-api-1 -- / -- +mtusi2026lab4-api-2 -- / -- +mtusi2026lab4-api-1 -- / --  +mtusi2026lab4-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..2ee52977 --- /dev/null +++ b/evidence/upload-memory/limit_64.stats @@ -0,0 +1,416 @@ +mtusi2026lab4-api-1 25.21MiB / 256MiB +mtusi2026lab4-api-2 25.61MiB / 256MiB +mtusi2026lab4-api-1 25.21MiB / 256MiB  +mtusi2026lab4-api-2 25.61MiB / 256MiB  +  +mtusi2026lab4-api-1 25.21MiB / 256MiB +mtusi2026lab4-api-2 25.61MiB / 256MiB +mtusi2026lab4-api-1 25.21MiB / 256MiB  +mtusi2026lab4-api-2 25.61MiB / 256MiB  +  +mtusi2026lab4-api-1 24.97MiB / 256MiB +mtusi2026lab4-api-2 25.62MiB / 256MiB +mtusi2026lab4-api-1 24.97MiB / 256MiB  +mtusi2026lab4-api-2 25.62MiB / 256MiB  +  +mtusi2026lab4-api-1 24.97MiB / 256MiB +mtusi2026lab4-api-2 25.62MiB / 256MiB +mtusi2026lab4-api-1 24.97MiB / 256MiB  +mtusi2026lab4-api-2 25.62MiB / 256MiB  +  +mtusi2026lab4-api-1 79.45MiB / 256MiB +mtusi2026lab4-api-2 75.33MiB / 256MiB +mtusi2026lab4-api-1 79.45MiB / 256MiB  +mtusi2026lab4-api-2 75.33MiB / 256MiB  +  +mtusi2026lab4-api-1 79.45MiB / 256MiB +mtusi2026lab4-api-2 75.33MiB / 256MiB +mtusi2026lab4-api-1 79.45MiB / 256MiB  +mtusi2026lab4-api-2 75.33MiB / 256MiB  +  +mtusi2026lab4-api-1 88.68MiB / 256MiB +mtusi2026lab4-api-2 88.5MiB / 256MiB +mtusi2026lab4-api-1 88.68MiB / 256MiB  +mtusi2026lab4-api-2 88.5MiB / 256MiB  +  +mtusi2026lab4-api-1 88.68MiB / 256MiB +mtusi2026lab4-api-2 88.5MiB / 256MiB +mtusi2026lab4-api-1 88.68MiB / 256MiB  +mtusi2026lab4-api-2 88.5MiB / 256MiB  +  +mtusi2026lab4-api-1 117.4MiB / 256MiB +mtusi2026lab4-api-2 119.8MiB / 256MiB +mtusi2026lab4-api-1 117.4MiB / 256MiB  +mtusi2026lab4-api-2 119.8MiB / 256MiB  +  +mtusi2026lab4-api-1 117.4MiB / 256MiB +mtusi2026lab4-api-2 119.8MiB / 256MiB +mtusi2026lab4-api-1 117.4MiB / 256MiB  +mtusi2026lab4-api-2 119.8MiB / 256MiB  +  +mtusi2026lab4-api-1 118MiB / 256MiB +mtusi2026lab4-api-2 128MiB / 256MiB +mtusi2026lab4-api-1 118MiB / 256MiB  +mtusi2026lab4-api-2 128MiB / 256MiB  +  +mtusi2026lab4-api-1 118MiB / 256MiB +mtusi2026lab4-api-2 128MiB / 256MiB +mtusi2026lab4-api-1 118MiB / 256MiB  +mtusi2026lab4-api-2 128MiB / 256MiB  +  +mtusi2026lab4-api-1 134.3MiB / 256MiB +mtusi2026lab4-api-2 119.5MiB / 256MiB +mtusi2026lab4-api-1 134.3MiB / 256MiB  +mtusi2026lab4-api-2 119.5MiB / 256MiB  +  +mtusi2026lab4-api-1 134.3MiB / 256MiB +mtusi2026lab4-api-2 119.5MiB / 256MiB +mtusi2026lab4-api-1 134.3MiB / 256MiB  +mtusi2026lab4-api-2 119.5MiB / 256MiB  +  +mtusi2026lab4-api-1 159.7MiB / 256MiB +mtusi2026lab4-api-2 160.9MiB / 256MiB +mtusi2026lab4-api-1 159.7MiB / 256MiB  +mtusi2026lab4-api-2 160.9MiB / 256MiB  +  +mtusi2026lab4-api-1 159.7MiB / 256MiB +mtusi2026lab4-api-2 160.9MiB / 256MiB +mtusi2026lab4-api-1 159.7MiB / 256MiB  +mtusi2026lab4-api-2 160.9MiB / 256MiB  +  +mtusi2026lab4-api-1 166.9MiB / 256MiB +mtusi2026lab4-api-2 168.1MiB / 256MiB +mtusi2026lab4-api-1 166.9MiB / 256MiB  +mtusi2026lab4-api-2 168.1MiB / 256MiB  +  +mtusi2026lab4-api-1 166.9MiB / 256MiB +mtusi2026lab4-api-2 168.1MiB / 256MiB +mtusi2026lab4-api-1 166.9MiB / 256MiB  +mtusi2026lab4-api-2 168.1MiB / 256MiB  +  +mtusi2026lab4-api-1 172MiB / 256MiB +mtusi2026lab4-api-2 167.8MiB / 256MiB +mtusi2026lab4-api-1 172MiB / 256MiB  +mtusi2026lab4-api-2 167.8MiB / 256MiB  +  +mtusi2026lab4-api-1 172MiB / 256MiB +mtusi2026lab4-api-2 167.8MiB / 256MiB +mtusi2026lab4-api-1 172MiB / 256MiB  +mtusi2026lab4-api-2 167.8MiB / 256MiB  +  +mtusi2026lab4-api-1 165.1MiB / 256MiB +mtusi2026lab4-api-2 171.7MiB / 256MiB +mtusi2026lab4-api-1 165.1MiB / 256MiB  +mtusi2026lab4-api-2 171.7MiB / 256MiB  +  +mtusi2026lab4-api-1 165.1MiB / 256MiB +mtusi2026lab4-api-2 171.7MiB / 256MiB +mtusi2026lab4-api-1 165.1MiB / 256MiB  +mtusi2026lab4-api-2 171.7MiB / 256MiB  +  +mtusi2026lab4-api-1 158.7MiB / 256MiB +mtusi2026lab4-api-2 169.3MiB / 256MiB +mtusi2026lab4-api-1 158.7MiB / 256MiB  +mtusi2026lab4-api-2 169.3MiB / 256MiB  +  +mtusi2026lab4-api-1 158.7MiB / 256MiB +mtusi2026lab4-api-2 169.3MiB / 256MiB +mtusi2026lab4-api-1 158.7MiB / 256MiB  +mtusi2026lab4-api-2 169.3MiB / 256MiB  +  +mtusi2026lab4-api-1 158.7MiB / 256MiB +mtusi2026lab4-api-2 169.2MiB / 256MiB +mtusi2026lab4-api-1 158.7MiB / 256MiB  +mtusi2026lab4-api-2 169.2MiB / 256MiB  +  +mtusi2026lab4-api-1 158.7MiB / 256MiB +mtusi2026lab4-api-2 169.2MiB / 256MiB +mtusi2026lab4-api-1 158.7MiB / 256MiB  +mtusi2026lab4-api-2 169.2MiB / 256MiB  +  +mtusi2026lab4-api-1 158.7MiB / 256MiB +mtusi2026lab4-api-2 171.1MiB / 256MiB +mtusi2026lab4-api-1 158.7MiB / 256MiB  +mtusi2026lab4-api-2 171.1MiB / 256MiB  +  +mtusi2026lab4-api-1 -- / -- +mtusi2026lab4-api-2 -- / -- +mtusi2026lab4-api-1 -- / --  +mtusi2026lab4-api-2 -- / --  +  +mtusi2026lab4-api-1 -- / -- +mtusi2026lab4-api-2 -- / -- +mtusi2026lab4-api-1 -- / --  +mtusi2026lab4-api-2 -- / --  +  +mtusi2026lab4-api-1 -- / -- +mtusi2026lab4-api-2 -- / -- +mtusi2026lab4-api-1 -- / --  +mtusi2026lab4-api-2 -- / --  +  +mtusi2026lab4-api-1 -- / -- +mtusi2026lab4-api-2 -- / -- +mtusi2026lab4-api-1 -- / --  +mtusi2026lab4-api-2 -- / --  +  +mtusi2026lab4-api-1 -- / -- +mtusi2026lab4-api-2 -- / -- +mtusi2026lab4-api-1 -- / --  +mtusi2026lab4-api-2 -- / --  +  +mtusi2026lab4-api-1 -- / -- +mtusi2026lab4-api-2 -- / -- +mtusi2026lab4-api-1 -- / --  +mtusi2026lab4-api-2 -- / --  +  +mtusi2026lab4-api-1 -- / -- +mtusi2026lab4-api-2 -- / -- +mtusi2026lab4-api-1 -- / --  +mtusi2026lab4-api-2 -- / --  +  +mtusi2026lab4-api-1 -- / -- +mtusi2026lab4-api-2 -- / -- +mtusi2026lab4-api-1 -- / --  +mtusi2026lab4-api-2 -- / --  +  +mtusi2026lab4-api-1 -- / -- +mtusi2026lab4-api-2 -- / -- +mtusi2026lab4-api-1 -- / --  +mtusi2026lab4-api-2 -- / --  +  +mtusi2026lab4-api-1 -- / -- +mtusi2026lab4-api-2 -- / -- +mtusi2026lab4-api-1 -- / --  +mtusi2026lab4-api-2 -- / --  +  +mtusi2026lab4-api-1 -- / -- +mtusi2026lab4-api-2 -- / -- +mtusi2026lab4-api-1 -- / --  +mtusi2026lab4-api-2 -- / --  +  +mtusi2026lab4-api-1 -- / -- +mtusi2026lab4-api-2 -- / -- +mtusi2026lab4-api-1 -- / --  +mtusi2026lab4-api-2 -- / --  +  +mtusi2026lab4-api-1 -- / -- +mtusi2026lab4-api-2 -- / -- +mtusi2026lab4-api-1 -- / --  +mtusi2026lab4-api-2 -- / --  +  +mtusi2026lab4-api-1 -- / -- +mtusi2026lab4-api-2 -- / -- +mtusi2026lab4-api-1 -- / --  +mtusi2026lab4-api-2 -- / --  +  +mtusi2026lab4-api-1 -- / -- +mtusi2026lab4-api-2 -- / -- +mtusi2026lab4-api-1 -- / --  +mtusi2026lab4-api-2 -- / --  +  +mtusi2026lab4-api-1 -- / -- +mtusi2026lab4-api-2 -- / -- +mtusi2026lab4-api-1 -- / --  +mtusi2026lab4-api-2 -- / --  +  +mtusi2026lab4-api-1 -- / -- +mtusi2026lab4-api-2 -- / -- +mtusi2026lab4-api-1 -- / --  +mtusi2026lab4-api-2 -- / --  +  +mtusi2026lab4-api-1 -- / -- +mtusi2026lab4-api-2 -- / -- +mtusi2026lab4-api-1 -- / --  +mtusi2026lab4-api-2 -- / --  +  +mtusi2026lab4-api-1 -- / -- +mtusi2026lab4-api-2 -- / -- +mtusi2026lab4-api-1 -- / --  +mtusi2026lab4-api-2 -- / --  +  +mtusi2026lab4-api-1 -- / -- +mtusi2026lab4-api-2 -- / -- +mtusi2026lab4-api-1 -- / --  +mtusi2026lab4-api-2 -- / --  +  +mtusi2026lab4-api-1 -- / -- +mtusi2026lab4-api-2 -- / -- +mtusi2026lab4-api-1 -- / --  +mtusi2026lab4-api-2 -- / --  +  +mtusi2026lab4-api-1 -- / -- +mtusi2026lab4-api-2 -- / -- +mtusi2026lab4-api-1 -- / --  +mtusi2026lab4-api-2 -- / --  +  +mtusi2026lab4-api-1 -- / -- +mtusi2026lab4-api-2 -- / -- +mtusi2026lab4-api-1 -- / --  +mtusi2026lab4-api-2 -- / --  +  +mtusi2026lab4-api-1 -- / -- +mtusi2026lab4-api-2 -- / -- +mtusi2026lab4-api-1 -- / --  +mtusi2026lab4-api-2 -- / --  +  +mtusi2026lab4-api-1 -- / -- +mtusi2026lab4-api-2 -- / -- +mtusi2026lab4-api-1 -- / --  +mtusi2026lab4-api-2 -- / --  +  +mtusi2026lab4-api-1 -- / -- +mtusi2026lab4-api-2 -- / -- +mtusi2026lab4-api-1 -- / --  +mtusi2026lab4-api-2 -- / --  +  +mtusi2026lab4-api-1 -- / -- +mtusi2026lab4-api-2 -- / -- +mtusi2026lab4-api-1 -- / --  +mtusi2026lab4-api-2 -- / --  +  +mtusi2026lab4-api-1 -- / -- +mtusi2026lab4-api-2 -- / -- +mtusi2026lab4-api-1 -- / --  +mtusi2026lab4-api-2 -- / --  +  +mtusi2026lab4-api-1 -- / -- +mtusi2026lab4-api-2 -- / -- +mtusi2026lab4-api-1 -- / --  +mtusi2026lab4-api-2 -- / --  +  +mtusi2026lab4-api-1 -- / -- +mtusi2026lab4-api-2 -- / -- +mtusi2026lab4-api-1 -- / --  +mtusi2026lab4-api-2 -- / --  +  +mtusi2026lab4-api-1 -- / -- +mtusi2026lab4-api-2 -- / -- +mtusi2026lab4-api-1 -- / --  +mtusi2026lab4-api-2 -- / --  +  +mtusi2026lab4-api-1 -- / -- +mtusi2026lab4-api-2 -- / -- +mtusi2026lab4-api-1 -- / --  +mtusi2026lab4-api-2 -- / --  +  +mtusi2026lab4-api-1 -- / -- +mtusi2026lab4-api-2 -- / -- +mtusi2026lab4-api-1 -- / --  +mtusi2026lab4-api-2 -- / --  +  +mtusi2026lab4-api-1 -- / -- +mtusi2026lab4-api-2 -- / -- +mtusi2026lab4-api-1 -- / --  +mtusi2026lab4-api-2 -- / --  +  +mtusi2026lab4-api-1 -- / -- +mtusi2026lab4-api-2 -- / -- +mtusi2026lab4-api-1 -- / --  +mtusi2026lab4-api-2 -- / --  +  +mtusi2026lab4-api-1 -- / -- +mtusi2026lab4-api-2 -- / -- +mtusi2026lab4-api-1 -- / --  +mtusi2026lab4-api-2 -- / --  +  +mtusi2026lab4-api-1 -- / -- +mtusi2026lab4-api-2 -- / -- +mtusi2026lab4-api-1 -- / --  +mtusi2026lab4-api-2 -- / --  +  +mtusi2026lab4-api-1 -- / -- +mtusi2026lab4-api-2 -- / -- +mtusi2026lab4-api-1 -- / --  +mtusi2026lab4-api-2 -- / --  +  +mtusi2026lab4-api-1 -- / -- +mtusi2026lab4-api-2 -- / -- +mtusi2026lab4-api-1 -- / --  +mtusi2026lab4-api-2 -- / --  +  +mtusi2026lab4-api-1 -- / -- +mtusi2026lab4-api-2 -- / -- +mtusi2026lab4-api-1 -- / --  +mtusi2026lab4-api-2 -- / --  +  +mtusi2026lab4-api-1 -- / -- +mtusi2026lab4-api-2 -- / -- +mtusi2026lab4-api-1 -- / --  +mtusi2026lab4-api-2 -- / --  +  +mtusi2026lab4-api-1 -- / -- +mtusi2026lab4-api-2 -- / -- +mtusi2026lab4-api-1 -- / --  +mtusi2026lab4-api-2 -- / --  +  +mtusi2026lab4-api-1 -- / -- +mtusi2026lab4-api-2 -- / -- +mtusi2026lab4-api-1 -- / --  +mtusi2026lab4-api-2 -- / --  +  +mtusi2026lab4-api-1 -- / -- +mtusi2026lab4-api-2 -- / -- +mtusi2026lab4-api-1 -- / --  +mtusi2026lab4-api-2 -- / --  +  +mtusi2026lab4-api-1 -- / -- +mtusi2026lab4-api-2 -- / -- +mtusi2026lab4-api-1 -- / --  +mtusi2026lab4-api-2 -- / --  +  +mtusi2026lab4-api-1 -- / -- +mtusi2026lab4-api-2 -- / -- +mtusi2026lab4-api-1 -- / --  +mtusi2026lab4-api-2 -- / --  +  +mtusi2026lab4-api-1 -- / -- +mtusi2026lab4-api-2 -- / -- +mtusi2026lab4-api-1 -- / --  +mtusi2026lab4-api-2 -- / --  +  +mtusi2026lab4-api-1 -- / -- +mtusi2026lab4-api-2 -- / -- +mtusi2026lab4-api-1 -- / --  +mtusi2026lab4-api-2 -- / --  +  +mtusi2026lab4-api-1 -- / -- +mtusi2026lab4-api-2 -- / -- +mtusi2026lab4-api-1 -- / --  +mtusi2026lab4-api-2 -- / --  +  +mtusi2026lab4-api-1 -- / -- +mtusi2026lab4-api-2 -- / -- +mtusi2026lab4-api-1 -- / --  +mtusi2026lab4-api-2 -- / --  +  +mtusi2026lab4-api-1 -- / -- +mtusi2026lab4-api-2 -- / -- +mtusi2026lab4-api-1 -- / --  +mtusi2026lab4-api-2 -- / --  +  +mtusi2026lab4-api-1 -- / -- +mtusi2026lab4-api-2 -- / -- +mtusi2026lab4-api-1 -- / --  +mtusi2026lab4-api-2 -- / --  +  +mtusi2026lab4-api-1 -- / -- +mtusi2026lab4-api-2 -- / -- +mtusi2026lab4-api-1 -- / --  +mtusi2026lab4-api-2 -- / --  +  +mtusi2026lab4-api-1 -- / -- +mtusi2026lab4-api-2 -- / -- +mtusi2026lab4-api-1 -- / --  +mtusi2026lab4-api-2 -- / --  +  +mtusi2026lab4-api-1 -- / -- +mtusi2026lab4-api-2 -- / -- +mtusi2026lab4-api-1 -- / --  +mtusi2026lab4-api-2 -- / --  +  +mtusi2026lab4-api-1 -- / -- +mtusi2026lab4-api-2 -- / -- +mtusi2026lab4-api-1 -- / --  +mtusi2026lab4-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..9646c120 --- /dev/null +++ b/evidence/upload-memory/summary.txt @@ -0,0 +1,14 @@ +# Эксперимент пика памяти при одновременных загрузках +# дата: 2026-11-12T15:22:53Z, реплик API: 2, commit: 7cbb75c +--- UPLOAD_MAX_CONCURRENCY=64 (параллельных клиентов=20, повторов=4, файл=7684003 байт, длительность=10s) +статусы HTTP: 80 201 +время ответа: min=0.58s p50=1.94s max=4.43s +пик памяти реплик, MiB (лимит контейнера 256M): + mtusi2026lab4-api-1: idle=25.2 peak=172.0 + mtusi2026lab4-api-2: idle=25.6 peak=171.7 +--- UPLOAD_MAX_CONCURRENCY=4 (параллельных клиентов=20, повторов=4, файл=7684003 байт, длительность=7s) +статусы HTTP: 80 201 +время ответа: min=0.41s p50=1.40s max=3.45s +пик памяти реплик, MiB (лимит контейнера 256M): + mtusi2026lab4-api-1: idle=25.7 peak=78.4 + mtusi2026lab4-api-2: idle=25.4 peak=83.7 diff --git a/go.mod b/go.mod index b39d2f7f..4f1bd26a 100644 --- a/go.mod +++ b/go.mod @@ -1,54 +1,33 @@ module mtusi2026lab4 -go 1.24.0 +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/minio/madmin-go/v3 v3.0.107 - github.com/minio/minio-go/v7 v7.0.90 github.com/redis/go-redis/v9 v9.7.3 - golang.org/x/crypto v0.37.0 + golang.org/x/crypto v0.36.0 ) require ( - github.com/cespare/xxhash/v2 v2.3.0 // indirect + 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/dustin/go-humanize v1.0.1 // indirect - github.com/go-ini/ini v1.67.0 // indirect - github.com/go-ole/go-ole v1.3.0 // indirect - github.com/goccy/go-json v0.10.5 // indirect - github.com/golang-jwt/jwt/v4 v4.5.2 // indirect - github.com/golang/protobuf v1.5.4 // 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 - github.com/klauspost/compress v1.18.0 // indirect - github.com/klauspost/cpuid/v2 v2.2.10 // indirect - github.com/lufia/plan9stats v0.0.0-20250317134145-8bc96cf8fc35 // indirect - github.com/matttproud/golang_protobuf_extensions v1.0.4 // indirect - github.com/minio/crc64nvme v1.0.1 // indirect - github.com/minio/md5-simd v1.1.2 // indirect - github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect - github.com/philhofer/fwd v1.1.3-0.20240916144458-20a13a1f6b7c // indirect - github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 // indirect - github.com/prometheus/client_model v0.6.2 // indirect - github.com/prometheus/common v0.63.0 // indirect - github.com/prometheus/procfs v0.16.0 // indirect - github.com/prometheus/prom2json v1.4.2 // indirect - github.com/prometheus/prometheus v0.303.0 // indirect - github.com/rs/xid v1.6.0 // indirect - github.com/safchain/ethtool v0.5.10 // indirect - github.com/secure-io/sio-go v0.3.1 // indirect - github.com/shirou/gopsutil/v3 v3.24.5 // indirect - github.com/shoenig/go-m1cpu v0.1.6 // indirect - github.com/tinylib/msgp v1.2.5 // indirect - github.com/tklauser/go-sysconf v0.3.15 // indirect - github.com/tklauser/numcpus v0.10.0 // indirect - github.com/yusufpapurcu/wmi v1.2.4 // indirect - golang.org/x/net v0.39.0 // indirect - golang.org/x/sync v0.13.0 // indirect - golang.org/x/sys v0.32.0 // indirect - golang.org/x/text v0.24.0 // indirect - google.golang.org/protobuf v1.36.6 // 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 index 96afdc89..99cec08c 100644 --- a/go.sum +++ b/go.sum @@ -1,30 +1,38 @@ +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.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= -github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +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.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= -github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/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/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= -github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= -github.com/go-ini/ini v1.67.0 h1:z6ZrTEZqSWOTyH2FlglNbNgARyHG8oLW9gMELqKr06A= -github.com/go-ini/ini v1.67.0/go.mod h1:ByCAeIL28uOIIG0E3PJtZPDL8WnHpFKFOtgjp+3Ies8= -github.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0= -github.com/go-ole/go-ole v1.3.0 h1:Dt6ye7+vXGIKZ7Xtk4s6/xVdGDQynvom7xCFEdWr6uE= -github.com/go-ole/go-ole v1.3.0/go.mod h1:5LS6F96DhAwUc7C+1HLexzMXY1xGRSryjyPPKW6zv78= -github.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4= -github.com/goccy/go-json v0.10.5/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M= -github.com/golang-jwt/jwt/v4 v4.5.2 h1:YtQM7lnr8iZ+j5q71MGKkNw9Mn7AjHM68uc9g5fXeUI= -github.com/golang-jwt/jwt/v4 v4.5.2/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w39/MY0Ch0= -github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= -github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= -github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= -github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= -github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= 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= @@ -35,93 +43,23 @@ 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/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo= -github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ= -github.com/klauspost/cpuid/v2 v2.0.1/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= -github.com/klauspost/cpuid/v2 v2.2.10 h1:tBs3QSyvjDyFTq3uoc/9xFpCuOsJQFNPiAhYdw2skhE= -github.com/klauspost/cpuid/v2 v2.2.10/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0= -github.com/lufia/plan9stats v0.0.0-20250317134145-8bc96cf8fc35 h1:PpXWgLPs+Fqr325bN2FD2ISlRRztXibcX6e8f5FR5Dc= -github.com/lufia/plan9stats v0.0.0-20250317134145-8bc96cf8fc35/go.mod h1:autxFIvghDt3jPTLoqZ9OZ7s9qTGNAWmYCjVFWPX/zg= -github.com/matttproud/golang_protobuf_extensions v1.0.4 h1:mmDVorXM7PCGKw94cs5zkfA9PSy5pEvNWRP0ET0TIVo= -github.com/matttproud/golang_protobuf_extensions v1.0.4/go.mod h1:BSXmuO+STAnVfrANrmjBb36TMTDstsz7MSK+HVaYKv4= -github.com/minio/crc64nvme v1.0.1 h1:DHQPrYPdqK7jQG/Ls5CTBZWeex/2FMS3G5XGkycuFrY= -github.com/minio/crc64nvme v1.0.1/go.mod h1:eVfm2fAzLlxMdUGc0EEBGSMmPwmXD5XiNRpnu9J3bvg= -github.com/minio/madmin-go/v3 v3.0.107 h1:MZNlPmJWsbxIvgIACSxmMq4T3PXK9/wil3pMSaTz5HI= -github.com/minio/madmin-go/v3 v3.0.107/go.mod h1:WOe2kYmYl1OIlY2DSRHVQ8j1v4OItARQ6jGyQqcCud8= -github.com/minio/md5-simd v1.1.2 h1:Gdi1DZK69+ZVMoNHRXJyNcxrMA4dSxoYHZSQbirFg34= -github.com/minio/md5-simd v1.1.2/go.mod h1:MzdKDxYpY2BT9XQFocsiZf/NKVtR7nkE4RoEpN+20RM= -github.com/minio/minio-go/v7 v7.0.90 h1:TmSj1083wtAD0kEYTx7a5pFsv3iRYMsOJ6A4crjA1lE= -github.com/minio/minio-go/v7 v7.0.90/go.mod h1:uvMUcGrpgeSAAI6+sD3818508nUyMULw94j2Nxku/Go= -github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA= -github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= -github.com/philhofer/fwd v1.1.3-0.20240916144458-20a13a1f6b7c h1:dAMKvw0MlJT1GshSTtih8C2gDs04w8dReiOGXrGLNoY= -github.com/philhofer/fwd v1.1.3-0.20240916144458-20a13a1f6b7c/go.mod h1:RqIHx9QI14HlwKwm98g9Re5prTQ6LdeRQn+gXJFxsJM= +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/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= -github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 h1:o4JXh1EVt9k/+g42oCprj/FisM4qX9L3sZB3upGN2ZU= -github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55/go.mod h1:OmDBASR4679mdNQnz2pUhc2G8CO2JrUAVFDRBDP/hJE= -github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk= -github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE= -github.com/prometheus/common v0.63.0 h1:YR/EIY1o3mEFP/kZCD7iDMnLPlGyuU2Gb3HIcXnA98k= -github.com/prometheus/common v0.63.0/go.mod h1:VVFF/fBIoToEnWRVkYoXEkq3R3paCoxG9PXP74SnV18= -github.com/prometheus/procfs v0.16.0 h1:xh6oHhKwnOJKMYiYBDWmkHqQPyiY40sny36Cmx2bbsM= -github.com/prometheus/procfs v0.16.0/go.mod h1:8veyXUu3nGP7oaCxhX6yeaM5u4stL2FeMXnCqhDthZg= -github.com/prometheus/prom2json v1.4.2 h1:PxCTM+Whqi/eykO1MKsEL0p/zMpxp9ybpsmdFamw6po= -github.com/prometheus/prom2json v1.4.2/go.mod h1:zuvPm7u3epZSbXPWHny6G+o8ETgu6eAK3oPr6yFkRWE= -github.com/prometheus/prometheus v0.303.0 h1:wsNNsbd4EycMCphYnTmNY9JASBVbp7NWwJna857cGpA= -github.com/prometheus/prometheus v0.303.0/go.mod h1:8PMRi+Fk1WzopMDeb0/6hbNs9nV6zgySkU/zds5Lu3o= 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/rs/xid v1.6.0 h1:fV591PaemRlL6JfRxGDEPl69wICngIQ3shQtzfy2gxU= -github.com/rs/xid v1.6.0/go.mod h1:7XoLgs4eV+QndskICGsho+ADou8ySMSjJKDIan90Nz0= -github.com/safchain/ethtool v0.5.10 h1:Im294gZtuf4pSGJRAOGKaASNi3wMeFaGaWuSaomedpc= -github.com/safchain/ethtool v0.5.10/go.mod h1:w9jh2Lx7YBR4UwzLkzCmWl85UY0W2uZdd7/DckVE5+c= -github.com/secure-io/sio-go v0.3.1 h1:dNvY9awjabXTYGsTF1PiCySl9Ltofk9GA3VdWlo7rRc= -github.com/secure-io/sio-go v0.3.1/go.mod h1:+xbkjDzPjwh4Axd07pRKSNriS9SCiYksWnZqdnfpQxs= -github.com/shirou/gopsutil/v3 v3.24.5 h1:i0t8kL+kQTvpAYToeuiVk3TgDeKOFioZO3Ztz/iZ9pI= -github.com/shirou/gopsutil/v3 v3.24.5/go.mod h1:bsoOS1aStSs9ErQ1WWfxllSeS1K5D+U30r2NfcubMVk= -github.com/shoenig/go-m1cpu v0.1.6 h1:nxdKQNcEB6vzgA2E2bvzKIYRuNj7XNJ4S/aRSwKzFtM= -github.com/shoenig/go-m1cpu v0.1.6/go.mod h1:1JJMcUBvfNwpq05QDQVAnx3gUHr9IYF7GNg9SUEw2VQ= -github.com/shoenig/test v0.6.4 h1:kVTaSd7WLz5WZ2IaoM0RSzRsUD+m8wRR+5qvntpn4LU= -github.com/shoenig/test v0.6.4/go.mod h1:byHiCGXqrVaflBLAMq/srcZIHynQPQgeyvkvXnjqq0k= 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.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= -github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= -github.com/tinylib/msgp v1.2.5 h1:WeQg1whrXRFiZusidTQqzETkRpGjFjcIhW6uqWH09po= -github.com/tinylib/msgp v1.2.5/go.mod h1:ykjzy2wzgrlvpDCRc4LA8UXy6D8bzMSuAF3WD57Gok0= -github.com/tklauser/go-sysconf v0.3.15 h1:VE89k0criAymJ/Os65CSn1IXaol+1wrsFHEB8Ol49K4= -github.com/tklauser/go-sysconf v0.3.15/go.mod h1:Dmjwr6tYFIseJw7a3dRLJfsHAMXZ3nEnL/aZY+0IuI4= -github.com/tklauser/numcpus v0.10.0 h1:18njr6LDBk1zuna922MgdjQuJFjrdppsZG60sHGfjso= -github.com/tklauser/numcpus v0.10.0/go.mod h1:BiTKazU708GQTYF4mB+cmlpT2Is1gLk7XVuEeem8LsQ= -github.com/yusufpapurcu/wmi v1.2.4 h1:zFUKzehAFReQwLys1b/iSMl+JQGSCSjtVqQn9bBrPo0= -github.com/yusufpapurcu/wmi v1.2.4/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0= -golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= -golang.org/x/crypto v0.0.0-20200302210943-78000ba7a073/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= -golang.org/x/crypto v0.37.0 h1:kJNSjF/Xp7kU0iB2Z+9viTPMW4EqqsrywMXLJOOsXSE= -golang.org/x/crypto v0.37.0/go.mod h1:vg+k43peMZ0pUMhYmVAWysMK35e6ioLh3wB8ZCAfbVc= -golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= -golang.org/x/net v0.39.0 h1:ZCu7HMWDxpXpaiKdhzIfaltL9Lp31x/3fCP11bc6/fY= -golang.org/x/net v0.39.0/go.mod h1:X7NRbYVEA+ewNkCNyJ513WmMdQ3BineSwVtN2zD/d+E= -golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.13.0 h1:AauUjRAJ9OSnvULf/ARrrVywoJDy0YS2AwQ98I37610= -golang.org/x/sync v0.13.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA= -golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200302150141-5c8b2ff67527/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20201204225414-ed752295db88/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.29.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= -golang.org/x/sys v0.32.0 h1:s77OFDvIQeibCmezSnk/q6iAfkdiQaJi4VzroCFrN20= -golang.org/x/sys v0.32.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= -golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= -golang.org/x/text v0.24.0 h1:dd5Bzh4yt5KYA8f9CJHCP4FB4D51c2c6JvN37xJJkJ0= -golang.org/x/text v0.24.0/go.mod h1:L8rBsPeo2pSS+xqN0d5u2ikmjtmoJbDBT1b7nHvFCdU= -google.golang.org/protobuf v1.36.6 h1:z1NpPI8ku2WgiWnf+t9wTPsn6eP1L7ksHUlkfLvd9xY= -google.golang.org/protobuf v1.36.6/go.mod h1:jduwjTPXsFjZGTmRluh+L6NjiWu7pchiJ2/5YcXBHnY= +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= diff --git a/internal/api/attachments.go b/internal/api/attachments.go index fdea4ea9..0f48b7fb 100644 --- a/internal/api/attachments.go +++ b/internal/api/attachments.go @@ -1,43 +1,35 @@ package api -// Вложения lab4: загрузка, метаданные, скачивание. +// HTTP-слой вложений lab4. // -// Загрузка (POST /chats/{id}/attachments?filename=...) идёт строго по шагам, и каждый шаг -// отсекает запрос как можно раньше и дешевле: +// Модель согласованности двух хранилищ (S3 + PostgreSQL), т.к. общей транзакции у них нет: // -// 1. Bearer-аутентификация (requireUser), затем членство в чате: посторонний получает 404; -// 2. filename: 1–255 code points, без «/», «\», NUL и управляющих символов — иначе 400; -// 3. заявленный Content-Type — только image/png или image/jpeg, иначе 415; -// 4. тело копируется в спул (временный файл, при его отказе — память) с одновременным SHA-256 -// и жёстким лимитом MaxUploadBytes+1: больше лимита — 413. Тело не буферизуется целиком -// в куче через ReadAll, поэтому пик RAM на загрузку — буфер копирования, а не размер файла; -// 5. тип по содержимому (http.DetectContentType) обязан совпасть с заявленным, иначе 415 (подмена MIME); -// 6. размеры берутся из заголовка PNG/JPEG БЕЗ декодирования пикселей; больше -// MaxImagePixels — 413. Это делается до любой «распаковки»: bomb 60000×60000 весит килобайты; -// 7. дешёвая структурная проверка (PNG: CRC всех чанков и IEND, JPEG: EOI) ловит обрезанные -// и повреждённые файлы — 415; -// 8. PUT в S3 по серверному ключу originals/, затем INSERT метаданных. Только после -// обоих шагов — 201. Если INSERT не удался, объект удаляется сразу, а при отказе удаления -// его подберёт reconciler (cmd/reconcile) после grace period. +// 1. проверяем всё, что можно, ДО записи (доступ, имя, тип, размер, содержимое); +// 2. PUT оригинала в S3 по ключу attachments/{chat}/{id}; +// 3. INSERT метаданных в PostgreSQL; +// 4. только после этого — 201 ready. // -// До шага 8 в S3 ничего не пишется, поэтому оборванная загрузка клиента не оставляет объектов. +// Что если процесс/сеть упали между 2 и 3, или INSERT вернул ошибку? +// - Остаётся лишний ОБЪЕКТ без строки (orphan). Строки без файла не бывает — +// ради этого PUT делается ПЕРВЫМ. Пользователь не увидит «битое» вложение, +// а лишний объект безвреден: на него никто не ссылается. +// - При ошибке INSERT мы сразу пытаемся удалить объект (компенсация, compensateOrphan). +// - Если и удаление не удалось (процесс убит, S3 моргнул) — объект подберёт reconciler +// (`/server -reconcile`): он удаляет объекты без строки старше S3_ORPHAN_GRACE_SECONDS. +// Grace нужен, чтобы не снести объект, у которого INSERT ещё «в полёте». +// - Обрыв соединения клиентом во время передачи тела: до PUT мы ничего не пишем, +// а PUT/INSERT привязаны к контексту запроса и отменяются. import ( - "bufio" "bytes" "context" "crypto/sha256" - "encoding/binary" "encoding/hex" "errors" - "hash/crc32" - "image" - _ "image/jpeg" // регистрирует декодер JPEG для image.DecodeConfig "io" "log" "mime" "net/http" - "os" "strconv" "strings" "time" @@ -46,194 +38,274 @@ import ( "github.com/google/uuid" - "mtusi2026lab4/internal/blob" + "mtusi2026lab4/internal/objectstore" "mtusi2026lab4/internal/store" ) const ( - maxMessageAttachments = 10 - maxFilenameRunes = 255 - // После превышения лимита дочитываем (и выбрасываем) не больше этого объёма: - // клиент успевает получить 413, а не «connection reset» посреди своей отправки. - drainOnOverflow = 64 << 20 + // drainLimit — сколько байт «лишнего» тела дочитываем при раннем отказе (413/415/400). + // Если сервер ответил и закрыл соединение, пока клиент ещё пишет, клиент получит + // RST вместо читаемого 413. Дочитывание ограничено, чтобы это не стало каналом + // для бесплатной траты трафика. + drainLimit = 16 << 20 + // slotWait — сколько загрузка ждёт свободный слот буферизации, прежде чем получить 429. + // Меньше таймаутов HAProxy (15 с), чтобы клиент получил осмысленный ответ. + slotWait = 8 * time.Second ) -var ( - errBadImage = errors.New("not a valid png/jpeg image") - errTooManyPixels = errors.New("image has too many pixels") - errTooLarge = errors.New("upload exceeds size limit") -) +// 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 { - writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid chat id") + s.rejectUpload(w, r, http.StatusBadRequest, "invalid_request", "invalid chat id") return } uid := userFrom(r) - if err := s.Store.EnsureChatMember(r.Context(), chatID, uid); err != nil { - s.writeStoreErr(w, r, err, http.StatusNotFound, "not_found", "object not found") + + // 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 } - filename := r.URL.Query().Get("filename") - if !validFilename(filename) { - writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid filename") - return - } - declared, ok := declaredImageType(r.Header.Get("Content-Type")) + // 2. filename — только для отображения. Опасные символы отклоняем сразу (400): + // даже зная, что в путь/ключ он не попадает, не храним то, что опасно показывать. + filename, ok := validFilename(r.URL.Query().Get("filename")) if !ok { - writeError(w, r, http.StatusUnsupportedMediaType, "unsupported_media_type", "only image/png and image/jpeg are accepted") - return - } - // Клиент заранее заявил размер сильно больше лимита — не читаем ни байта. - if r.ContentLength > s.MaxUploadBytes+drainOnOverflow { - writeError(w, r, http.StatusRequestEntityTooLarge, "payload_too_large", "file is too large") + s.rejectUpload(w, r, http.StatusBadRequest, "invalid_request", "invalid filename") return } - sp, err := spoolBody(r.Body, s.MaxUploadBytes) + // 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 { - switch { - case errors.Is(err, errTooLarge): - writeError(w, r, http.StatusRequestEntityTooLarge, "payload_too_large", "file is too large") - default: - // Обрыв чтения тела или таймаут клиента. Ничего не записано ни в S3, ни в БД. - writeError(w, r, http.StatusBadRequest, "invalid_request", "could not read request body") - } - return - } - defer sp.Close() - - if err := inspectImage(sp.reader(), sp.size, declared, s.MaxImagePixels); err != nil { - switch { - case errors.Is(err, errTooManyPixels): - writeError(w, r, http.StatusRequestEntityTooLarge, "payload_too_large", "image has too many pixels") - default: - writeError(w, r, http.StatusUnsupportedMediaType, "unsupported_media_type", "invalid or unsupported image") + 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 } - id := uuid.New() + // 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: id, + ID: attID, ChatID: chatID, OwnerID: uid, Filename: filename, - ContentType: declared, - SizeBytes: sp.size, - SHA256: sp.sum, - ObjectKey: blob.KeyPrefix + id.String(), + 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 } - // 1) S3. Тело отдаём как ReadSeeker: minio-go шлёт один PUT без буферизации в памяти. - if err := s.Blob.Put(r.Context(), att.ObjectKey, sp.reader(), sp.size, declared); err != nil { - s.writeBlobErr(w, r, err) - return - } - // 2) PostgreSQL. Ошибка здесь оставила бы объект без строки — убираем его сразу. - if err := s.Store.CreateAttachment(r.Context(), att); err != nil { - s.compensateOrphan(r, att.ObjectKey) - s.writeStoreErr(w, r, err, http.StatusNotFound, "not_found", "object not found") - return - } + // 11. Теперь честно: и байты, и метаданные сохранены. writeJSON(w, http.StatusCreated, attachmentDTO(att)) } -// compensateOrphan удаляет объект, для которого не удалось записать метаданные. -// Контекст отвязан от запроса: клиент мог отключиться, а чистить всё равно нужно. -// Если и удаление не удалось (S3 мигнул), объект останется до reconciler — это допустимо. +// compensateOrphan убирает объект, для которого не удалось записать метаданные. +// Контекст новый и короткий. Если удаление не прошло — это не ошибка запроса: +// объект станет orphan и будет удалён reconciler'ом после grace-периода. func (s *Server) compensateOrphan(r *http.Request, key string) { - ctx, cancel := context.WithTimeout(context.WithoutCancel(r.Context()), 5*time.Second) + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() - if err := s.Blob.Delete(ctx, key); err != nil { - log.Printf("request_id=%s orphan_cleanup_failed key=%s (reconciler will remove after grace)", requestID(r), key) + 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.loadAttachment(w, r) + att, ok := s.loadAttachmentForRequest(w, r) if !ok { return } writeJSON(w, http.StatusOK, attachmentDTO(att)) } -// handleDownloadAttachment отдаёт оригинал побайтно через API, без редиректа на S3: -// приватный bucket сам по себе не заменяет проверку членства в чате. +// handleDownloadAttachment — GET /api/v1/attachments/{id}/content: байты через API, без redirect. +// Прямой доступ к bucket не нужен ни клиенту, ни другой реплике: любая реплика читает +// из общего S3, поэтому остановка загрузившей реплики ничего не ломает. func (s *Server) handleDownloadAttachment(w http.ResponseWriter, r *http.Request) { - att, ok := s.loadAttachment(w, r) + att, ok := s.loadAttachmentForRequest(w, r) if !ok { return } - // variant по умолчанию original. В lab4 вариантов нет (variants=[]), значит любой - // другой — «отсутствующий вариант ready-объекта», то есть 404. - if v := r.URL.Query().Get("variant"); v != "" && v != "original" { + // 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 - } - switch att.Status { - case "ready": 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 } - rc, err := s.Blob.Get(r.Context(), att.ObjectKey) + + body, _, err := s.Objects.Get(r.Context(), att.ObjectKey) if err != nil { - if errors.Is(err, blob.ErrNotFound) { - // Строка есть, объекта нет — несогласованность, её чинит reconciler. - log.Printf("request_id=%s attachment_object_missing id=%s", requestID(r), att.ID) - writeError(w, r, http.StatusNotFound, "not_found", "object not found") + 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 } - s.writeBlobErr(w, r, err) + log.Printf("request_id=%s attachment_get_failed err=%v", requestID(r), err) + writeError(w, r, http.StatusServiceUnavailable, "unavailable", "dependency unavailable") return } - defer rc.Close() + 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, rc); err != nil { - // Заголовки уже ушли; клиент увидит обрыв. В лог — без деталей S3. - log.Printf("request_id=%s attachment_stream_error id=%s", requestID(r), att.ID) + // Потоково: в памяти реплики лежит только буфер копирования, не весь файл. + if _, err := io.Copy(w, body); err != nil { + // Заголовки уже отправлены, статус не изменить; клиент увидит обрыв. + log.Printf("request_id=%s attachment_stream_interrupted", requestID(r)) } } -// loadAttachment разбирает {attachment_id} и проверяет членство в чате вложения. -func (s *Server) loadAttachment(w http.ResponseWriter, r *http.Request) (*store.Attachment, bool) { +// 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.GetAttachment(r.Context(), id, userFrom(r)) + 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, http.StatusNotFound, "not_found", "object not found") + s.writeStoreErr(w, r, err, 0, "", "") return nil, false } return att, true } -// writeBlobErr: недоступный S3 — 503, остальное — 500. Текст ошибки клиенту не уходит. -func (s *Server) writeBlobErr(w http.ResponseWriter, r *http.Request, err error) { - if errors.Is(err, blob.ErrUnavailable) { - log.Printf("request_id=%s s3_unavailable", requestID(r)) - writeError(w, r, http.StatusServiceUnavailable, "unavailable", "dependency unavailable") - return - } - log.Printf("request_id=%s blob_error_type=%T", requestID(r), err) - writeError(w, r, http.StatusInternalServerError, "internal_error", "internal error") -} - +// attachmentDTO — публичное представление. object_key и bucket НЕ раскрываются. func attachmentDTO(a *store.Attachment) map[string]any { - var errCode any - if a.ErrorCode != nil { - errCode = *a.ErrorCode - } return map[string]any{ "id": a.ID.String(), "chat_id": a.ChatID.String(), @@ -243,206 +315,77 @@ func attachmentDTO(a *store.Attachment) map[string]any { "size_bytes": a.SizeBytes, "sha256": a.SHA256, "status": a.Status, - "variants": []any{}, - "error_code": errCode, - "created_at": formatTime(a.CreatedAt), - "updated_at": formatTime(a.UpdatedAt), + // lab4: производных вариантов нет (они появятся с воркером в lab5+). + "variants": []any{}, + "error_code": a.ErrorCode, + "created_at": formatTime(a.CreatedAt), + "updated_at": formatTime(a.UpdatedAt), } } -// validFilename: 1–255 code points, валидный UTF-8, не «пустой» после TrimSpace. -// «/», «\», NUL и управляющие символы запрещены: имя только отображается и никогда не -// становится путём или ключом S3. «.» и «..» отвергаются как заведомо опасные. -func validFilename(name string) bool { - if !utf8.ValidString(name) || strings.TrimSpace(name) == "" { - return false +// 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 } - if n := utf8.RuneCountInString(name); n < 1 || n > maxFilenameRunes { - return false - } - if name == "." || name == ".." { - return false - } - for _, c := range name { - if c == '/' || c == '\\' || c == 0 || unicode.IsControl(c) { - return false - } - } - return true } -// declaredImageType возвращает заявленный Content-Type без параметров, если он разрешён. -func declaredImageType(header string) (string, bool) { - mt, _, err := mime.ParseMediaType(header) - if err != nil { - return "", false - } - switch mt { - case "image/png", "image/jpeg": - return mt, true - } - return "", 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) } -// spooled — принятое тело: размер, SHA-256 и произвольный доступ для проверок и PUT. -type spooled struct { - ra io.ReaderAt - size int64 - sum string - cleanup func() -} - -func (s *spooled) reader() *io.SectionReader { return io.NewSectionReader(s.ra, 0, s.size) } -func (s *spooled) Close() { s.cleanup() } - -// spoolBody читает тело не больше max байт. Временный файл защищает кучу от 10 одновременных -// загрузок по 10 MiB; если /tmp недоступен, откатываемся на память (всё равно ограниченную max). -func spoolBody(body io.Reader, max int64) (*spooled, error) { - h := sha256.New() - f, ferr := os.CreateTemp("", "upload-*") - var ( - dst io.Writer - buf *bytes.Buffer - cleanup = func() {} - ) - if ferr == nil { - cleanup = func() { _ = f.Close(); _ = os.Remove(f.Name()) } - dst = io.MultiWriter(f, h) - } else { - buf = &bytes.Buffer{} - dst = io.MultiWriter(buf, h) +// 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) } - n, err := io.Copy(dst, io.LimitReader(body, max+1)) - if err != nil { - cleanup() + if _, err := buf.ReadFrom(r.Body); err != nil { return nil, err } - if n > max { - cleanup() - _, _ = io.CopyN(io.Discard, body, drainOnOverflow) - return nil, errTooLarge - } - sp := &spooled{size: n, sum: hex.EncodeToString(h.Sum(nil)), cleanup: cleanup} - if f != nil && ferr == nil { - sp.ra = f - } else { - sp.ra = bytes.NewReader(buf.Bytes()) - } - return sp, nil + return buf.Bytes(), nil } -// inspectImage проверяет содержимое. Порядок важен: тип → размеры из заголовка (лимит -// пикселей до любой распаковки) → структура файла. -func inspectImage(sr *io.SectionReader, size int64, declared string, maxPixels int64) error { - head := make([]byte, 512) - n, _ := sr.ReadAt(head, 0) - detected := "" - if n > 0 { - detected = http.DetectContentType(head[:n]) +// 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 size < 1 || (detected != "image/png" && detected != "image/jpeg") || detected != declared { - return errBadImage + if n := utf8.RuneCountInString(raw); n < 1 || n > 255 { + return "", false } - - var w, h int64 - switch detected { - case "image/png": - // IHDR всегда первый чанк: 8 байт сигнатуры, 4 длина, 4 тип, затем width/height. - // Читаем сами: image/png.DecodeConfig отвергает файл с битым CRC раньше, чем - // мы успели бы честно ответить «слишком много пикселей». - if n < 24 || string(head[12:16]) != "IHDR" || binary.BigEndian.Uint32(head[8:12]) != 13 { - return errBadImage + 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 } - w = int64(binary.BigEndian.Uint32(head[16:20])) - h = int64(binary.BigEndian.Uint32(head[20:24])) - case "image/jpeg": - cfg, _, err := image.DecodeConfig(io.NewSectionReader(sr, 0, size)) - if err != nil { - return errBadImage - } - w, h = int64(cfg.Width), int64(cfg.Height) } - if w < 1 || h < 1 { - return errBadImage - } - if w*h > maxPixels { - return errTooManyPixels - } - - if detected == "image/png" { - return verifyPNG(io.NewSectionReader(sr, 0, size), size) - } - return verifyJPEGTail(sr, size) -} - -// verifyPNG обходит чанки и проверяет их CRC без декомпрессии IDAT: обрезанный или -// испорченный PNG отвергается за один линейный проход по файлу. -func verifyPNG(r io.Reader, size int64) error { - br := bufio.NewReaderSize(r, 64<<10) - if _, err := br.Discard(8); err != nil { // сигнатура уже проверена DetectContentType - return errBadImage - } - consumed := int64(8) - var ( - hdr [8]byte - crcBuf [4]byte - first = true - sawIDAT bool - sawIEND bool - crcHasher = crc32.NewIEEE() - ) - for !sawIEND { - if _, err := io.ReadFull(br, hdr[:]); err != nil { - return errBadImage - } - length := int64(binary.BigEndian.Uint32(hdr[0:4])) - ctype := string(hdr[4:8]) - if length > size-consumed-12 { - return errBadImage - } - if first && ctype != "IHDR" { - return errBadImage - } - first = false - crcHasher.Reset() - _, _ = crcHasher.Write(hdr[4:8]) - if _, err := io.CopyN(crcHasher, br, length); err != nil { - return errBadImage - } - if _, err := io.ReadFull(br, crcBuf[:]); err != nil { - return errBadImage - } - if crcHasher.Sum32() != binary.BigEndian.Uint32(crcBuf[:]) { - return errBadImage - } - consumed += 12 + length - switch ctype { - case "IDAT": - sawIDAT = true - case "IEND": - sawIEND = true - } - } - // Данные после IEND — признак полиглота или склейки файлов, не принимаем. - if !sawIDAT || consumed != size { - return errBadImage - } - return nil -} - -// verifyJPEGTail требует маркер конца изображения EOI (FF D9) в хвосте файла. -// Допускаются нулевые/мусорные байты выравнивания после него (до 1 KiB). -func verifyJPEGTail(sr *io.SectionReader, size int64) error { - tailLen := int64(1024) - if size < tailLen { - tailLen = size - } - tail := make([]byte, tailLen) - if _, err := sr.ReadAt(tail, size-tailLen); err != nil && !errors.Is(err, io.EOF) { - return errBadImage - } - if bytes.LastIndex(tail, []byte{0xFF, 0xD9}) < 0 { - return errBadImage - } - return nil + 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 index ef0857bb..9bb9f594 100644 --- a/internal/api/server.go +++ b/internal/api/server.go @@ -1,4 +1,4 @@ -// Package api — HTTP-слой lab4 (поверх lab3: LB, идемпотентность, сессии в Redis). +// Package api — HTTP-слой lab4 (lab3 + вложения в S3). // // Порядок обработки запроса: // 1. X-Request-Id и X-Instance-Id на каждый ответ, включая ошибки; @@ -6,13 +6,11 @@ // 3. маршрут; // 4. для защищённых маршрутов — только Bearer. Basic и X-User-Id доступ не дают. // -// /health/live отвечает, пока процесс жив. /health/ready ещё проверяет PostgreSQL, Redis и S3: -// без них нельзя честно принять запись или узнать, кто делает запрос. +// /health/live отвечает, пока процесс жив. /health/ready ещё проверяет PostgreSQL, Redis +// и S3: без них нельзя честно принять запись, узнать, кто делает запрос, или принять/отдать +// вложение (lab4: недоступный S3 → 503, балансировщик снимает реплику). // // POST сообщения требует Idempotency-Key; результат хранится в общей БД, а не в памяти реплики. -// -// Вложения (attachments.go): сырой PNG/JPEG в теле POST, байты в приватном S3, метаданные в -// PostgreSQL. Скачивание — только через этот API, без редиректа на S3. package api import ( @@ -36,7 +34,7 @@ import ( "github.com/google/uuid" - "mtusi2026lab4/internal/blob" + "mtusi2026lab4/internal/objectstore" "mtusi2026lab4/internal/session" "mtusi2026lab4/internal/store" ) @@ -54,43 +52,27 @@ const ( challengeBearer = `Bearer realm="messenger"` ) -// Лимиты вложений по контракту lab4. -const ( - DefaultMaxUploadBytes int64 = 10 << 20 // 10 MiB = 10 485 760 - DefaultMaxImagePixels int64 = 40_000_000 -) - -// BlobStore — то, что API требует от S3-клиента. *blob.Client его реализует; -// интерфейс нужен, чтобы тест мог подставить недоступное хранилище. -type BlobStore interface { - Put(ctx context.Context, key string, r io.Reader, size int64, contentType string) error - Get(ctx context.Context, key string) (io.ReadCloser, error) - Delete(ctx context.Context, key string) error - Ping(ctx context.Context) error -} - -var _ BlobStore = (*blob.Client)(nil) - -// Server связывает HTTP с PostgreSQL, Redis и S3. +// Server связывает HTTP с PostgreSQL и Redis. type Server struct { Store *store.Store Sessions *session.Store - Blob BlobStore + Objects *objectstore.Store // приватный S3-bucket с оригиналами вложений InstanceID string - // Лимиты загрузки. По умолчанию контрактные; main.go может только ужесточить. - MaxUploadBytes int64 - MaxImagePixels int64 - ready atomic.Bool + 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, bl BlobStore, instanceID string) *Server { - s := &Server{ - Store: st, Sessions: sessions, Blob: bl, InstanceID: instanceID, - MaxUploadBytes: DefaultMaxUploadBytes, - MaxImagePixels: DefaultMaxImagePixels, - } +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 } @@ -113,6 +95,7 @@ func (s *Server) Handler() http.Handler { 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)) @@ -128,9 +111,11 @@ func (s *Server) handleReady(w http.ResponseWriter, r *http.Request) { writeError(w, r, http.StatusServiceUnavailable, "unavailable", "service is shutting down") return } - // S3 — обязательная зависимость синхронного пути (загрузка и скачивание вложений). - if err := s.Store.Ping(r.Context()); err != nil || s.Sessions.Ping(r.Context()) != nil || - s.Blob.Ping(r.Context()) != nil { + // 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 } @@ -346,9 +331,11 @@ func (s *Server) handleCreateMessage(w http.ResponseWriter, r *http.Request) { writeDecodeErr(w, r, err) return } - // attachment_ids: 0–10 уникальных UUID; отсутствующий ключ, null и [] равны для хэша. - if len(body.AttachmentIDs) > maxMessageAttachments { - writeError(w, r, http.StatusBadRequest, "invalid_request", "too many attachments") + // 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)) @@ -368,11 +355,11 @@ func (s *Server) handleCreateMessage(w http.ResponseWriter, r *http.Request) { attachmentIDs = append(attachmentIDs, id) canonicalIDs = append(canonicalIDs, id.String()) } - // Длина — по исходному тексту. Непустота — по TrimSpace, но только если вложений нет: - // text="" с хотя бы одним вложением разрешён контрактом lab4. - // Пробелы по краям сохраняются как есть, иначе «пробел + 4000 букв» проходил бы как 4000. + // Непустота — по TrimSpace; длина и сохранение — по исходному тексту. + // Иначе пробелы по краям пропадают, а строка «пробел + 4000 букв» проходит как 4000. + // lab4: пустой текст допустим, если есть хотя бы одно вложение (сообщение «только файл»). if utf8.RuneCountInString(body.Text) > 4000 || - (len(attachmentIDs) == 0 && strings.TrimSpace(body.Text) == "") { + (strings.TrimSpace(body.Text) == "" && len(attachmentIDs) == 0) { writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid text") return } @@ -390,7 +377,7 @@ func (s *Server) handleCreateMessage(w http.ResponseWriter, r *http.Request) { writeError(w, r, http.StatusConflict, "conflict", "idempotency key reused with different body") return } - if errors.Is(err, store.ErrNotReady) { + if errors.Is(err, store.ErrAttachmentNotReady) { writeError(w, r, http.StatusConflict, "conflict", "attachment is not ready") return } @@ -689,18 +676,18 @@ func chatDTO(c *store.Chat) map[string]any { } func messageDTO(m *store.Message) map[string]any { - // Всегда массив, даже пустой: клиент lab3 без вложений видит [] (контракт 1.4.0). - att := make([]string, len(m.AttachmentIDs)) + // attachment_ids обязателен в ответе (контракт 1.4.0): всегда массив, не null. + ids := make([]string, len(m.AttachmentIDs)) for i, id := range m.AttachmentIDs { - att[i] = id.String() + 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, - "attachment_ids": att, "created_at": formatTime(m.CreatedAt), + "attachment_ids": ids, } } diff --git a/internal/blob/memory.go b/internal/blob/memory.go deleted file mode 100644 index 86780877..00000000 --- a/internal/blob/memory.go +++ /dev/null @@ -1,162 +0,0 @@ -package blob - -import ( - "bytes" - "context" - "io" - "sync" - "time" -) - -// Memory — in-memory BlobStore для student-tests без живого MinIO. -// Не для production: нет persistence между процессами. -type Memory struct { - mu sync.Mutex - objects map[string]memObj - down bool - bucketOK bool - now func() time.Time -} - -type memObj struct { - data []byte - modTime time.Time -} - -// NewMemory создаёт пустое хранилище с «живым» бакетом. -func NewMemory() *Memory { - return &Memory{ - objects: make(map[string]memObj), - bucketOK: true, - now: time.Now, - } -} - -// SetUnavailable имитирует падение S3 (Ping/Put/Get → ErrUnavailable). -func (m *Memory) SetUnavailable(v bool) { m.mu.Lock(); m.down = v; m.mu.Unlock() } - -func (m *Memory) Bucket() string { return "memory" } - -func (m *Memory) Ping(ctx context.Context) error { - select { - case <-ctx.Done(): - return ctx.Err() - default: - } - m.mu.Lock() - defer m.mu.Unlock() - if m.down || !m.bucketOK { - return ErrUnavailable - } - return nil -} - -func (m *Memory) Put(ctx context.Context, key string, r io.Reader, size int64, _ string) error { - select { - case <-ctx.Done(): - return ctx.Err() - default: - } - m.mu.Lock() - defer m.mu.Unlock() - if m.down { - return ErrUnavailable - } - data, err := io.ReadAll(io.LimitReader(r, size+1)) - if err != nil { - return err - } - if int64(len(data)) != size { - return ErrUnavailable - } - m.objects[key] = memObj{data: append([]byte(nil), data...), modTime: m.now()} - return nil -} - -func (m *Memory) Get(ctx context.Context, key string) (io.ReadCloser, error) { - select { - case <-ctx.Done(): - return nil, ctx.Err() - default: - } - m.mu.Lock() - defer m.mu.Unlock() - if m.down { - return nil, ErrUnavailable - } - o, ok := m.objects[key] - if !ok { - return nil, ErrNotFound - } - return io.NopCloser(bytes.NewReader(o.data)), nil -} - -func (m *Memory) Stat(ctx context.Context, key string) (ObjectInfo, error) { - select { - case <-ctx.Done(): - return ObjectInfo{}, ctx.Err() - default: - } - m.mu.Lock() - defer m.mu.Unlock() - if m.down { - return ObjectInfo{}, ErrUnavailable - } - o, ok := m.objects[key] - if !ok { - return ObjectInfo{}, ErrNotFound - } - return ObjectInfo{Key: key, Size: int64(len(o.data)), LastModified: o.modTime}, nil -} - -func (m *Memory) Delete(ctx context.Context, key string) error { - select { - case <-ctx.Done(): - return ctx.Err() - default: - } - m.mu.Lock() - defer m.mu.Unlock() - if m.down { - return ErrUnavailable - } - delete(m.objects, key) - return nil -} - -func (m *Memory) ListKeys(ctx context.Context, prefix string) ([]ObjectInfo, error) { - select { - case <-ctx.Done(): - return nil, ctx.Err() - default: - } - m.mu.Lock() - defer m.mu.Unlock() - if m.down { - return nil, ErrUnavailable - } - var out []ObjectInfo - for k, o := range m.objects { - if len(prefix) == 0 || (len(k) >= len(prefix) && k[:len(prefix)] == prefix) { - out = append(out, ObjectInfo{Key: k, Size: int64(len(o.data)), LastModified: o.modTime}) - } - } - return out, nil -} - -// Seed кладёт объект напрямую (для тестов reconciler). -func (m *Memory) Seed(key string, data []byte, modTime time.Time) { - m.mu.Lock() - defer m.mu.Unlock() - if modTime.IsZero() { - modTime = m.now() - } - m.objects[key] = memObj{data: append([]byte(nil), data...), modTime: modTime} -} - -var _ interface { - Put(ctx context.Context, key string, r io.Reader, size int64, contentType string) error - Get(ctx context.Context, key string) (io.ReadCloser, error) - Delete(ctx context.Context, key string) error - Ping(ctx context.Context) error -} = (*Memory)(nil) diff --git a/internal/blob/minio.go b/internal/blob/minio.go deleted file mode 100644 index c1527bc8..00000000 --- a/internal/blob/minio.go +++ /dev/null @@ -1,197 +0,0 @@ -// Package blob — тонкая обёртка над MinIO (S3 API) для оригиналов вложений lab4. -// -// Байты файлов живут только здесь, а не в PostgreSQL и не на диске API-реплики. -// Ключ объекта назначает сервер (originals/); filename клиента в ключ не попадает. -// Bucket приватный: прямого доступа без подписи нет, скачивание идёт через авторизованный API. -// -// Ошибки сведены к двум классам, чтобы HTTP-слой не знал про minio-go: -// ErrNotFound — объекта нет (404/500 по контексту), ErrUnavailable — S3 недоступен (503). -package blob - -import ( - "context" - "errors" - "fmt" - "io" - "net" - "net/http" - "time" - - "github.com/minio/minio-go/v7" - "github.com/minio/minio-go/v7/pkg/credentials" -) - -// KeyPrefix — префикс ключей оригиналов. Reconciler обходит только его. -const KeyPrefix = "originals/" - -var ( - // ErrNotFound — такого объекта в бакете нет. - ErrNotFound = errors.New("blob: not found") - // ErrUnavailable — S3 не отвечает, отказал в доступе или вернул неожиданную ошибку. - ErrUnavailable = errors.New("blob: unavailable") -) - -// Config — параметры подключения. Секреты приходят из окружения/файла, в логи не попадают. -type Config struct { - Endpoint string // host:port без схемы, например minio:9000 - UseSSL bool - Region string - Bucket string - AccessKey string - SecretKey string -} - -// ObjectInfo — то, что reconciler и тесты знают об объекте. -type ObjectInfo struct { - Key string - Size int64 - LastModified time.Time -} - -// Client — клиент одного бакета. -type Client struct { - mc *minio.Client - bucket string -} - -// New создаёт клиента. Сеть не трогает: доступность проверяют Ping/EnsureBucket. -// -// Таймауты заданы явно. Без них connection refused ретраится minio-go десяток раз, -// и «S3 лежит» вместо быстрого 503 превращается в зависший запрос. -func New(cfg Config) (*Client, error) { - if cfg.Endpoint == "" || cfg.Bucket == "" { - return nil, fmt.Errorf("blob: endpoint and bucket are required") - } - tr := &http.Transport{ - Proxy: nil, - DialContext: (&net.Dialer{ - Timeout: 2 * time.Second, - KeepAlive: 30 * time.Second, - }).DialContext, - MaxIdleConns: 64, - MaxIdleConnsPerHost: 32, - IdleConnTimeout: 60 * time.Second, - TLSHandshakeTimeout: 3 * time.Second, - ResponseHeaderTimeout: 20 * time.Second, - } - mc, err := minio.New(cfg.Endpoint, &minio.Options{ - Creds: credentials.NewStaticV4(cfg.AccessKey, cfg.SecretKey, ""), - Secure: cfg.UseSSL, - Region: cfg.Region, - Transport: tr, - MaxRetries: 2, - }) - if err != nil { - return nil, fmt.Errorf("blob: init client: %w", err) - } - return &Client{mc: mc, bucket: cfg.Bucket}, nil -} - -// Bucket возвращает имя бакета (для логов и отчётов). -func (c *Client) Bucket() string { return c.bucket } - -// EnsureBucket создаёт бакет, если его нет. Идемпотентно. -// В Compose бакет создаёт minio-init с root-правами, а у app-пользователя прав на -// создание нет — функция нужна локальным тестам и ручному запуску на «голом» MinIO. -func (c *Client) EnsureBucket(ctx context.Context) error { - ok, err := c.mc.BucketExists(ctx, c.bucket) - if err != nil { - return classify(err) - } - if ok { - return nil - } - if err := c.mc.MakeBucket(ctx, c.bucket, minio.MakeBucketOptions{}); err != nil { - // Гонка двух инициализаторов: бакет уже создан соседом. - code := minio.ToErrorResponse(err).Code - if code == "BucketAlreadyOwnedByYou" || code == "BucketAlreadyExists" { - return nil - } - return classify(err) - } - return nil -} - -// Ping — проверка для /health/ready. Короткий таймаут: readiness не должна висеть. -func (c *Client) Ping(ctx context.Context) error { - ctx, cancel := context.WithTimeout(ctx, 500*time.Millisecond) - defer cancel() - ok, err := c.mc.BucketExists(ctx, c.bucket) - if err != nil || !ok { - return ErrUnavailable - } - return nil -} - -// Put кладёт объект известного размера. r должен уметь Seek (файл или bytes.Reader): -// тогда minio-go отправляет тело одним запросом без буферизации в памяти. -func (c *Client) Put(ctx context.Context, key string, r io.Reader, size int64, contentType string) error { - _, err := c.mc.PutObject(ctx, c.bucket, key, r, size, minio.PutObjectOptions{ - ContentType: contentType, - // Один PUT для файлов до лимита lab4 (10 MiB): multipart не нужен. - DisableMultipart: true, - }) - return classify(err) -} - -// Get открывает объект на чтение. Существование проверяется сразу (Stat), чтобы HTTP-слой -// успел вернуть 404/503 до отправки заголовков 200. -func (c *Client) Get(ctx context.Context, key string) (io.ReadCloser, error) { - obj, err := c.mc.GetObject(ctx, c.bucket, key, minio.GetObjectOptions{}) - if err != nil { - return nil, classify(err) - } - if _, err := obj.Stat(); err != nil { - _ = obj.Close() - return nil, classify(err) - } - return obj, nil -} - -// Stat возвращает метаданные объекта или ErrNotFound. -func (c *Client) Stat(ctx context.Context, key string) (ObjectInfo, error) { - st, err := c.mc.StatObject(ctx, c.bucket, key, minio.StatObjectOptions{}) - if err != nil { - return ObjectInfo{}, classify(err) - } - return ObjectInfo{Key: st.Key, Size: st.Size, LastModified: st.LastModified}, nil -} - -// Delete удаляет объект. Отсутствие объекта — не ошибка (S3 DELETE идемпотентен). -func (c *Client) Delete(ctx context.Context, key string) error { - err := c.mc.RemoveObject(ctx, c.bucket, key, minio.RemoveObjectOptions{}) - if err != nil && errors.Is(classify(err), ErrNotFound) { - return nil - } - return classify(err) -} - -// ListKeys возвращает все объекты с префиксом (рекурсивно). Для reconciler: -// стоимость обхода — O(число объектов), память — по записи на объект. -func (c *Client) ListKeys(ctx context.Context, prefix string) ([]ObjectInfo, error) { - var out []ObjectInfo - for o := range c.mc.ListObjects(ctx, c.bucket, minio.ListObjectsOptions{Prefix: prefix, Recursive: true}) { - if o.Err != nil { - return nil, classify(o.Err) - } - out = append(out, ObjectInfo{Key: o.Key, Size: o.Size, LastModified: o.LastModified}) - } - return out, nil -} - -// classify сводит ошибки minio-go к ErrNotFound/ErrUnavailable. Текст исходной ошибки -// наружу не возвращаем: в нём могут быть endpoint и имя бакета. -func classify(err error) error { - if err == nil { - return nil - } - switch minio.ToErrorResponse(err).Code { - case "NoSuchKey", "NotFound": - return ErrNotFound - } - if minio.ToErrorResponse(err).StatusCode == http.StatusNotFound && - minio.ToErrorResponse(err).Code != "NoSuchBucket" { - return ErrNotFound - } - return ErrUnavailable -} diff --git a/internal/config/config.go b/internal/config/config.go index 9caac942..ea55e4ad 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -1,7 +1,5 @@ // Package config читает настройки процесса из окружения. // -// Для lab4 добавлены S3_* и лимиты вложений. -// // Прямые URL (DATABASE_URL, REDIS_URL) удобны в Compose. // Вариант *_FILE из .env.example нужен, если секрет смонтирован файлом: // тогда в переменной лежит путь, а не сам секрет. @@ -28,21 +26,28 @@ type Config struct { RunMigrations bool IdempotencyTTL time.Duration - // Лимиты вложений (lab4). Контракт: 10 MiB и 40 млн пикселей. - MaxUploadBytes int64 - MaxImagePixels int64 - // ReconcileGrace — минимальный возраст объекта/строки, прежде чем reconciler их тронет. - ReconcileGrace time.Duration -} + // --- lab4: объектное хранилище (S3-совместимое, MinIO) --- -// S3 — параметры подключения к S3-совместимому хранилищу. -type S3 struct { - Endpoint string - UseSSL bool - Region string - Bucket string - AccessKey string - SecretKey string + // 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 без файла — ошибка запуска, а не тихий дефолт на чужой хост. @@ -84,6 +89,12 @@ func Load() (Config, error) { 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() @@ -93,47 +104,47 @@ func Load() (Config, error) { cfg.InstanceID = host } - cfg.MaxUploadBytes, err = getenvInt64("MAX_UPLOAD_BYTES", 10485760, 1, 10485760) - if err != nil { - return cfg, err - } - cfg.MaxImagePixels, err = getenvInt64("MAX_IMAGE_PIXELS", 40000000, 1, 40000000) - if err != nil { - return cfg, err - } - graceSec, err := getenvInt64("S3_RECONCILE_GRACE_SECONDS", 60, 0, 7*24*3600) - if err != nil { - return cfg, err - } - cfg.ReconcileGrace = time.Duration(graceSec) * time.Second - + // Миграции по умолчанию выключены у API-реплик: их гоняет одноразовый сервис migrate. + // Для локальных тестов и -migrate флага включается явно. cfg.RunMigrations = truthy(os.Getenv("RUN_MIGRATIONS")) return cfg, nil } -// LoadS3 читает настройки S3. Ключи — из S3_ACCESS_KEY_ID / S3_SECRET_ACCESS_KEY -// либо из файлов *_FILE. Пустые ключи — ошибка запуска API (migrate без S3 обходится). -func LoadS3() (S3, error) { - var ( - c S3 - err error - ) - c.Endpoint = getenv("S3_ENDPOINT", "minio:9000") - // Endpoint может прийти со схемой http:// — minio-go ждёт host:port. - c.Endpoint = strings.TrimPrefix(c.Endpoint, "https://") - c.Endpoint = strings.TrimPrefix(c.Endpoint, "http://") - c.Region = getenv("S3_REGION", "us-east-1") - c.Bucket = getenv("S3_BUCKET", "messenger-attachments") - c.UseSSL = truthy(os.Getenv("S3_USE_SSL")) - c.AccessKey, err = getenvOrFile("S3_ACCESS_KEY_ID", "S3_ACCESS_KEY_ID_FILE") - if err != nil { - return c, err +// 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") } - c.SecretKey, err = getenvOrFile("S3_SECRET_ACCESS_KEY", "S3_SECRET_ACCESS_KEY_FILE") + 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 c, err + return err } - return c, nil + 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 внутри контейнера. @@ -148,18 +159,6 @@ func getenv(key, fallback string) string { return fallback } -func getenvInt64(key string, fallback, lo, hi int64) (int64, error) { - raw := strings.TrimSpace(os.Getenv(key)) - if raw == "" { - return fallback, nil - } - n, err := strconv.ParseInt(raw, 10, 64) - if err != nil || n < lo || n > hi { - return 0, fmt.Errorf("invalid %s", key) - } - return n, nil -} - func getenvOrFile(directKey, fileKey string) (string, error) { if v := strings.TrimSpace(os.Getenv(directKey)); v != "" { return v, nil 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..e138c21b --- /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" + + "mtusi2026lab4/internal/objectstore" + "mtusi2026lab4/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/store/attachments.go b/internal/store/attachments.go index 7dfde9d5..2bbf6851 100644 --- a/internal/store/attachments.go +++ b/internal/store/attachments.go @@ -1,12 +1,12 @@ -// Вложения lab4: метаданные в PostgreSQL, байты в S3 (пакет blob). +// Метаданные вложений (lab4): таблицы attachments и message_attachments. // -// Согласованность двух хранилищ строится на порядке «сначала S3, потом БД»: -// 1. PUT объекта в S3 по серверному ключу; -// 2. INSERT строки attachments. +// Разделение ответственности: +// - байты оригинала лежат в приватном S3-bucket по ключу attachments/{chat}/{id}; +// - здесь — всё остальное: чат, владелец, имя для показа, тип, размер, sha256, ключ. // -// Если PUT прошёл, а INSERT нет, остаётся объект без строки (orphan). API пытается удалить -// его сразу, а если не вышло, его удалит reconciler после grace period. Обратный порядок -// опаснее: строка без объекта отдавала бы клиенту 201 на файл, которого нет. +// Порядок «PUT в S3, потом INSERT здесь» выбран намеренно (см. api/attachments.go): +// при сбое между шагами остаётся лишний ОБЪЕКТ (его безопасно убирает reconciler), +// а не строка без файла (она бы отдавала пользователю ошибку при скачивании). package store import ( @@ -18,68 +18,85 @@ import ( "github.com/jackc/pgx/v5" ) -// ErrNotReady — вложение существует в этом чате, но ещё не ready (в lab4 недостижимо, -// зарезервировано под асинхронную обработку lab5). -var ErrNotReady = errors.New("attachment not ready") +// StatusReady — единственный статус lab4: 201 возвращается только после сохранения +// и оригинала в S3, и метаданных в PostgreSQL. +const StatusReady = "ready" -// Attachment — метаданные оригинала. ObjectKey во внешний JSON не попадает. +// Attachment — строка таблицы attachments. type Attachment struct { ID uuid.UUID ChatID uuid.UUID OwnerID uuid.UUID Filename string - ContentType string + ContentType string // image/png | image/jpeg, определён по содержимому SizeBytes int64 - SHA256 string - ObjectKey string + SHA256 string // lowercase hex + ObjectKey string // внутренний, клиенту не отдаётся Status string ErrorCode *string + Width int + Height int CreatedAt time.Time UpdatedAt time.Time } -// CreateAttachment пишет метаданные после успешного PUT в S3. ID и ObjectKey задаёт вызывающий: -// ключ нужен до записи в БД. Членство в чате проверяется в самом INSERT — если автора уже -// нет в чате, строка не появится и вернётся ErrNotFound. +// 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() - now := nowUTC() - a.Status = "ready" - a.ErrorCode = nil - a.CreatedAt, a.UpdatedAt = now, now 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, created_at, updated_at - ) - SELECT $1, $2, $3, $4, $5, $6, $7, $8, $9, NULL, $10, $10 + 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.CreatedAt) + 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 } -// GetAttachment отдаёт вложение только участнику его чата. Чужому и несуществующему — -// одинаковый ErrNotFound (HTTP 404): наличие чужого файла не раскрываем. -func (s *Store) GetAttachment(ctx context.Context, id, userID uuid.UUID) (*Attachment, error) { +// 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.created_at, a.updated_at + 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.CreatedAt, &a.UpdatedAt) + &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 } @@ -89,48 +106,97 @@ func (s *Store) GetAttachment(ctx context.Context, id, userID uuid.UUID) (*Attac return &a, nil } -// EnsureChatMember — публичная проверка «пользователь состоит в чате» (ErrNotFound иначе). -func (s *Store) EnsureChatMember(ctx context.Context, chatID, userID uuid.UUID) error { - return s.ensureMember(ctx, chatID, userID) -} - -// ListAttachmentIDsForMessage возвращает ID вложений сообщения в порядке запроса. -// Пустой результат — непустой срез нулевой длины, чтобы JSON дал [], а не null. -func (s *Store) ListAttachmentIDsForMessage(ctx context.Context, messageID uuid.UUID) ([]uuid.UUID, error) { +// CountAttachmentsInChat нужен тестам: после отказа S3/PG в чате не должно оставаться +// «полуфабрикатов» (строк метаданных без успешной загрузки). +func (s *Store) CountAttachmentsInChat(ctx context.Context, chatID uuid.UUID) (int, error) { ctx, cancel := context.WithTimeout(ctx, queryTimeout) defer cancel() - byMsg, err := attachmentIDsByMessage(ctx, s.pool, []uuid.UUID{messageID}) + 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 } -// querier — общая часть pgxpool.Pool и pgx.Tx. -type querier interface { - Query(ctx context.Context, sql string, args ...any) (pgx.Rows, error) -} - -// attachmentIDsByMessage — один запрос на страницу сообщений (без N+1). -// Все ключи результата заполнены: у сообщений без вложений значение — пустой срез. -// -// q — пул или транзакция: внутри транзакции запрос обязан идти по её соединению, иначе при -// маленьком пуле транзакция занимает соединение и ждёт второе. +// 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 } - strs := make([]string, len(messageIDs)) - for i, id := range messageIDs { - out[id] = []uuid.UUID{} - strs[i] = id.String() - } rows, err := q.Query(ctx, ` SELECT message_id, attachment_id FROM message_attachments - WHERE message_id = ANY($1::uuid[]) - ORDER BY message_id, position`, strs) + WHERE message_id = ANY($1) + ORDER BY message_id, position`, messageIDs) if err != nil { return nil, mapWriteErr(err) } @@ -145,27 +211,51 @@ func attachmentIDsByMessage(ctx context.Context, q querier, messageIDs []uuid.UU return out, mapWriteErr(rows.Err()) } -// AttachmentRef — строка attachments для reconciler: только то, что нужно для сверки с S3. -type AttachmentRef struct { - ID uuid.UUID - ObjectKey string - SizeBytes int64 - CreatedAt time.Time - Referenced bool // есть ли хотя бы одно сообщение со ссылкой на файл +// 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 } -// ListAttachmentRefs — keyset-страница по id. Страницы небольшие: у соединения -// statement_timeout 3 с, один огромный SELECT на большой таблице под него не уложится. -func (s *Store) ListAttachmentRefs(ctx context.Context, after uuid.UUID, limit int) ([]AttachmentRef, error) { +// --------------------------------------------------------------------------- +// Методы для 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.size_bytes, a.created_at, + 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.id > $1 - ORDER BY a.id - LIMIT $2`, after, limit) + WHERE a.object_key > $1 + ORDER BY a.object_key + LIMIT $2`, afterKey, limit) if err != nil { return nil, mapWriteErr(err) } @@ -173,7 +263,7 @@ func (s *Store) ListAttachmentRefs(ctx context.Context, after uuid.UUID, limit i var out []AttachmentRef for rows.Next() { var r AttachmentRef - if err := rows.Scan(&r.ID, &r.ObjectKey, &r.SizeBytes, &r.CreatedAt, &r.Referenced); err != nil { + if err := rows.Scan(&r.ID, &r.ObjectKey, &r.CreatedAt, &r.Used); err != nil { return nil, mapWriteErr(err) } out = append(out, r) @@ -181,27 +271,29 @@ func (s *Store) ListAttachmentRefs(ctx context.Context, after uuid.UUID, limit i return out, mapWriteErr(rows.Err()) } -// AttachmentKeyExists — повторная проверка перед удалением orphan: между листингом S3 -// и удалением объект мог получить строку (загрузка закончилась). Это страховка поверх grace. -func (s *Store) AttachmentKeyExists(ctx context.Context, objectKey string) (bool, error) { +// 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)`, objectKey).Scan(&ok) + err := s.pool.QueryRow(ctx, `SELECT EXISTS (SELECT 1 FROM attachments WHERE object_key = $1)`, key).Scan(&ok) return ok, mapWriteErr(err) } -// DeleteUnreferencedAttachment удаляет строку, только если на неё нет ссылок из сообщений. -// Условие NOT EXISTS в самом DELETE закрывает гонку «сообщение прикрепили, пока мы решали». -// Возвращает true, если строка была удалена. -func (s *Store) DeleteUnreferencedAttachment(ctx context.Context, id uuid.UUID) (bool, error) { +// 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 NOT EXISTS (SELECT 1 FROM message_attachments ma WHERE ma.attachment_id = a.id)`, id) + 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) } diff --git a/internal/store/migrations/003_attachments.sql b/internal/store/migrations/003_attachments.sql index af091554..818319fd 100644 --- a/internal/store/migrations/003_attachments.sql +++ b/internal/store/migrations/003_attachments.sql @@ -1,28 +1,42 @@ --- Вложения lab4. Метаданные в PostgreSQL, байты в приватном S3-bucket (MinIO). --- Ключ объекта назначает сервер: originals/. --- filename только для отображения, в ключ не попадает. +-- Вложения 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), @@ -30,4 +44,4 @@ CREATE TABLE IF NOT EXISTS message_attachments ( PRIMARY KEY (message_id, attachment_id) ); -CREATE INDEX IF NOT EXISTS message_attachments_attachment_idx ON message_attachments (attachment_id); +CREATE INDEX IF NOT EXISTS message_attachments_attachment_idx ON message_attachments (attachment_id) diff --git a/internal/store/store.go b/internal/store/store.go index 55517f1c..7d57ebb1 100644 --- a/internal/store/store.go +++ b/internal/store/store.go @@ -8,10 +8,6 @@ // либо не фиксируются вообще. Уникальность username обеспечивает UNIQUE, а не проверка // «сначала SELECT, потом INSERT» (та проверка проигрывает гонке). // -// Вложения (lab4) — файл attachments.go: метаданные в PostgreSQL, байты в S3. Сообщение -// ссылается на вложения через message_attachments; ссылки пишутся в той же транзакции, -// что и само сообщение и ключ идемпотентности. -// // Идемпотентность сообщения тоже живёт в PostgreSQL, а не в памяти реплики: // два параллельных POST с одним ключом через разные API-контейнеры видят один PK. package store @@ -66,14 +62,15 @@ type Chat struct { } // Message — одно подтверждённое сообщение. sender_id назначает сервер. -// AttachmentIDs всегда непустой срез нулевой длины, если вложений нет (JSON даёт []). type Message struct { - ID uuid.UUID - ChatID uuid.UUID - SenderID uuid.UUID - Text string + ID uuid.UUID + ChatID uuid.UUID + SenderID uuid.UUID + Text string + CreatedAt time.Time + // AttachmentIDs — вложения в порядке, заданном клиентом. Никогда nil в ответах API + // (контракт: attachment_ids обязателен, по умолчанию []). AttachmentIDs []uuid.UUID - CreatedAt time.Time } // PageCursor — позиция keyset. Клиент видит только opaque-строку в пакете api. @@ -318,11 +315,12 @@ func (s *Store) CreateMessage(ctx context.Context, chatID, senderID uuid.UUID, t ctx, cancel := context.WithTimeout(ctx, queryTimeout) defer cancel() msg := &Message{ - ID: uuid.New(), - ChatID: chatID, - SenderID: senderID, - Text: text, - CreatedAt: nowUTC(), + ID: uuid.New(), + ChatID: chatID, + SenderID: senderID, + Text: text, + CreatedAt: nowUTC(), + // Внутренний путь без вложений; поле не nil, чтобы JSON дал [], а не null. AttachmentIDs: []uuid.UUID{}, } tag, err := s.pool.Exec(ctx, ` @@ -346,20 +344,22 @@ type IdempotentMessage struct { Replayed bool } -// CreateMessageIdempotent атомарно создаёт сообщение со вложениями и запоминает ответ по ключу. +// CreateMessageIdempotent атомарно создаёт сообщение и запоминает ответ по ключу. // // Алгоритм (общая БД, любые реплики): // 1. BEGIN; // 2. pg_advisory_xact_lock по хешу (user, method, path, key) — сериализует конкурентов // ещё до INSERT messages, иначе два победителя гонки успели бы создать два сообщения; -// 3. SELECT сохранённого ключа — если есть, сравнить hash и вернуть Message (с его вложениями); -// 4. иначе проверить членство в чате и вложения: каждое должно существовать, лежать -// в ЭТОМ чате и быть ready (чужое/неизвестное — ErrNotFound, не ready — ErrNotReady); -// 5. INSERT message + message_attachments + idempotency_keys в той же транзакции; +// 3. SELECT сохранённого ключа — если есть, сравнить hash и вернуть Message; +// 4. иначе проверить членство, затем вложения (lab4): все принадлежат ЭТОМУ чату и ready, +// строки блокируются FOR SHARE, чтобы удаление (reconciler) не вклинилось до COMMIT; +// 5. INSERT message + INSERT message_attachments + INSERT idempotency_keys в той же +// транзакции: сообщение либо видно целиком вместе со ссылками на вложения, либо нет; // 6. COMMIT (advisory lock снимается вместе с транзакцией). // -// attachmentIDs уже без дубликатов (проверяет HTTP-слой), порядок сохраняется. -// Пустой текст допустим только вместе с вложениями — это тоже проверяет HTTP-слой. +// Чужое и неизвестное вложение (в т.ч. из другого чата) неразличимы: оба дают ErrNotFound +// (HTTP 404), чтобы нельзя было перебором выяснить, существует ли чужой файл. +// // Другой request_hash → ErrIdempotencyConflict. Транзиентный 5xx сюда не попадает: // запись ключа только после успешной подготовки 201. func (s *Store) CreateMessageIdempotent( @@ -371,9 +371,6 @@ func (s *Store) CreateMessageIdempotent( ) (*IdempotentMessage, error) { ctx, cancel := context.WithTimeout(ctx, queryTimeout) defer cancel() - if attachmentIDs == nil { - attachmentIDs = []uuid.UUID{} - } tx, err := s.pool.Begin(ctx) if err != nil { @@ -405,7 +402,8 @@ func (s *Store) CreateMessageIdempotent( if storedHash != requestHash { return nil, ErrIdempotencyConflict } - byMsg, err := attachmentIDsByMessage(ctx, tx, []uuid.UUID{msgID}) + // Replay обязан вернуть ТОТ ЖЕ набор вложений, что и первый ответ. + replayIDs, err := loadMessageAttachmentIDs(ctx, tx, msgID) if err != nil { return nil, err } @@ -418,8 +416,8 @@ func (s *Store) CreateMessageIdempotent( ChatID: msgChat, SenderID: msgSender, Text: msgText, - AttachmentIDs: byMsg[msgID], CreatedAt: msgCreated, + AttachmentIDs: replayIDs, }, Replayed: true, }, nil @@ -437,39 +435,10 @@ func (s *Store) CreateMessageIdempotent( return nil, mapWriteErr(err) } - attStrs := make([]string, len(attachmentIDs)) - for i, id := range attachmentIDs { - attStrs[i] = id.String() - } - if len(attStrs) > 0 { - // chat_id = $2 — вложение другого чата неотличимо от несуществующего (404, не 403). - rows, err := tx.Query(ctx, ` - SELECT status FROM attachments WHERE id = ANY($1::uuid[]) AND chat_id = $2`, attStrs, chatID) - if err != nil { - return nil, mapWriteErr(err) - } - found, notReady := 0, false - for rows.Next() { - var status string - if err := rows.Scan(&status); err != nil { - rows.Close() - return nil, mapWriteErr(err) - } - found++ - if status != "ready" { - notReady = true - } - } - rows.Close() - if err := rows.Err(); err != nil { - return nil, mapWriteErr(err) - } - if found != len(attStrs) { - return nil, ErrNotFound - } - if notReady { - return nil, ErrNotReady - } + // Вложения проверяем ПОСЛЕ членства: посторонний в чат получает 404 по чату, + // а не информацию о существовании файлов. + if err := lockMessageAttachments(ctx, tx, chatID, attachmentIDs); err != nil { + return nil, err } msg := &Message{ @@ -477,8 +446,8 @@ func (s *Store) CreateMessageIdempotent( ChatID: chatID, SenderID: senderID, Text: text, - AttachmentIDs: append([]uuid.UUID{}, attachmentIDs...), CreatedAt: nowUTC(), + AttachmentIDs: append([]uuid.UUID{}, attachmentIDs...), } if _, err := tx.Exec(ctx, ` INSERT INTO messages (id, chat_id, sender_id, text, created_at) @@ -486,25 +455,28 @@ func (s *Store) CreateMessageIdempotent( msg.ID, msg.ChatID, msg.SenderID, msg.Text, msg.CreatedAt); err != nil { return nil, mapWriteErr(err) } - if len(attStrs) > 0 { - // WITH ORDINALITY сохраняет порядок attachment_ids из запроса. + // Порядок attachment_ids клиента сохраняется в position. + for i, aid := range attachmentIDs { if _, err := tx.Exec(ctx, ` INSERT INTO message_attachments (message_id, attachment_id, position) - SELECT $1, u.id, (u.ord - 1)::smallint - FROM unnest($2::uuid[]) WITH ORDINALITY AS u(id, ord)`, msg.ID, attStrs); err != nil { + 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, - "attachment_ids": attStrs, "created_at": msg.CreatedAt.UTC().Truncate(time.Millisecond).Format("2006-01-02T15:04:05.000Z"), + "attachment_ids": attachmentStrs, }) if err != nil { return nil, err @@ -576,18 +548,10 @@ func (s *Store) ListMessages(ctx context.Context, chatID, userID uuid.UUID, limi hasNext, items := trimPage(items, limit, func(m Message) (time.Time, uuid.UUID) { return m.CreatedAt, m.ID }) - // Вложения страницы — одним запросом, а не по запросу на сообщение. - 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 { + // Вложения страницы одним запросом (а не N+1): WHERE message_id = ANY(id страницы). + if err := s.attachMessageAttachments(ctx, items); err != nil { return nil, nil, err } - for i := range items { - items[i].AttachmentIDs = byMsg[items[i].ID] - } var cursor *PageCursor if hasNext { last := items[len(items)-1] @@ -608,6 +572,12 @@ func (s *Store) CountChatsByTitle(ctx context.Context, title string) (int, error 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() diff --git a/scripts/_lib.sh b/scripts/_lib.sh new file mode 100755 index 00000000..b5cb5772 --- /dev/null +++ b/scripts/_lib.sh @@ -0,0 +1,53 @@ +# Общие функции для скриптов lab4 (подключается через `. scripts/_lib.sh`, не запускается сам). +# Предполагает, что ROOT уже вычислен и текущий каталог — корень репозитория. + +# Значение KEY из .env (или значение по умолчанию). Секреты скрипты не печатают. +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 --env-file .env" +LB_PORT=$(env_get LB_HOST_PORT 8080) +MINIO_PORT=$(env_get MINIO_HOST_PORT 9000) +S3_BUCKET=$(env_get S3_BUCKET messenger) +BASE_URL=${BASE_URL:-http://127.0.0.1:${LB_PORT}} + +# JSON-поле верхнего уровня (python3 есть на машине студента; jq не требуем). +json_get() { python3 -c 'import json,sys; print(json.load(sys.stdin)[sys.argv[1]])' "$1"; } + +# register_and_login → печатает "TOKEN USER_ID". Каждый вызов создаёт нового пользователя. +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 TOKEN USER_ID → chat_id +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 TOKEN CHAT FILE [CONTENT_TYPE] → JSON вложения +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 SQL → результат без выравнивания (для чтения object_key и счётчиков) +psql_q() { + $DC exec -T postgres sh -c 'psql -U "$POSTGRES_USER" -d "$POSTGRES_DB" -Atc "$1"' _ "$1" +} + +# s3sh 'КОМАНДЫ mc' — выполнить в одноразовом контейнере mc с ROOT-учёткой (только для +# диагностики и инъекции сбоев в скриптах: API root-ключей не получает). +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())'; } diff --git a/scripts/check-private-bucket.sh b/scripts/check-private-bucket.sh deleted file mode 100755 index fc7f98fc..00000000 --- a/scripts/check-private-bucket.sh +++ /dev/null @@ -1,31 +0,0 @@ -#!/bin/sh -# Уровень 4: прямое неаутентифицированное чтение объекта из bucket должно отказать. -# Ожидание: HTTP 403 (или отказ соединения / 400 Signature) — не 200 с телом файла. -set -eu -ROOT=$(CDPATH= cd -- "$(dirname "$0")/.." && pwd) -cd "$ROOT" - -BUCKET=${S3_BUCKET:-messenger-attachments} -ENDPOINT=${S3_PUBLIC_ENDPOINT:-http://127.0.0.1:9000} -# Любой ключ: даже несуществующий при private bucket не должен отдаваться анониму как 200+тело. -URL="${ENDPOINT}/${BUCKET}/originals/does-not-exist" - -code=$(curl -sS -o /tmp/private-bucket-body.$$ -w '%{http_code}' "$URL" || echo "000") -body_len=$(wc -c < /tmp/private-bucket-body.$$ | tr -d ' ') -rm -f /tmp/private-bucket-body.$$ - -echo "GET $URL → HTTP $code body_bytes=$body_len" -case "$code" in - 200) - echo "FAIL: anonymous GET returned 200" >&2 - exit 1 - ;; - 000) - echo "FAIL: could not reach MinIO at $ENDPOINT" >&2 - exit 1 - ;; - *) - echo "PASS: anonymous access denied (HTTP $code)" - exit 0 - ;; -esac 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/concurrent-uploads.sh b/scripts/concurrent-uploads.sh deleted file mode 100755 index 8af43750..00000000 --- a/scripts/concurrent-uploads.sh +++ /dev/null @@ -1,130 +0,0 @@ -#!/bin/sh -# Уровень 4: ≥10 одновременных загрузок + пик RSS API-реплик. -set -eu -ROOT=$(CDPATH= cd -- "$(dirname "$0")/.." && pwd) -cd "$ROOT" -export BASE_URL=${BASE_URL:-http://127.0.0.1:8080} -export N=${N:-12} -export OUT=${OUT:-evidence/concurrent-uploads.txt} -mkdir -p evidence - -python3 - <<'PY' -import base64, binascii, json, os, struct, subprocess, sys, threading, time, urllib.request, uuid, zlib - -base = os.environ["BASE_URL"] -n = int(os.environ["N"]) -out = os.environ["OUT"] - -def req(method, path, data=None, headers=None, timeout=60): - h = dict(headers or {}) - body = data - if isinstance(data, (dict, list)): - body = json.dumps(data).encode() - h.setdefault("Content-Type", "application/json") - r = urllib.request.Request(base + path, data=body, headers=h, method=method) - with urllib.request.urlopen(r, timeout=timeout) as resp: - return resp.status, resp.read() - -def chunk(tag, data): - return struct.pack(">I", len(data)) + tag + data + struct.pack(">I", binascii.crc32(tag + data) & 0xffffffff) - -# 1024×1024 RGB, zlib level 0 → ~3 MiB: заметнее для RSS, всё ещё ≪ 10 MiB лимита. -w = h = 1024 -ihdr = struct.pack(">IIBBBBB", w, h, 8, 2, 0, 0, 0) -raw = b"".join(b"\x00" + bytes(w * 3) for _ in range(h)) -big = b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", ihdr) + chunk(b"IDAT", zlib.compress(raw, 0)) + chunk(b"IEND", b"") -print(f"upload_size_bytes={len(big)}", flush=True) - -uname = "cu_" + uuid.uuid4().hex[:10] -password = "correct-horse-1" -st, body = req("POST", "/api/v1/users", {"username": uname, "display_name": "CU", "password": password}) -assert st == 201, body -uid = json.loads(body)["id"] -basic = base64.b64encode(f"{uname}:{password}".encode()).decode() -st, body = req("POST", "/api/v1/auth/sessions", headers={"Authorization": f"Basic {basic}"}) -assert st == 201, body -token = json.loads(body)["token"] -st, body = req("POST", "/api/v1/chats", {"title": "concurrent", "member_ids": [uid]}, - headers={"Authorization": f"Bearer {token}"}) -assert st == 201, body -chat = json.loads(body)["id"] - -def api_rss_kb(): - try: - ids = subprocess.check_output( - ["docker", "compose", "--env-file", ".env", "ps", "-q", "api"], text=True - ).split() - total = 0 - for i in ids: - line = subprocess.check_output( - ["docker", "stats", "--no-stream", "--format", "{{.MemUsage}}", i], text=True - ).strip() - part = line.split("/")[0].strip() - num = float("".join(ch for ch in part if ch.isdigit() or ch == ".")) - if "GiB" in part: - total += int(num * 1024 * 1024) - elif "MiB" in part: - total += int(num * 1024) - else: - total += int(num) - return total - except Exception as e: - print("rss_err", e, flush=True) - return -1 - -rss_before = api_rss_kb() -peak = {"v": rss_before} -stop = threading.Event() - -def monitor(): - while not stop.is_set(): - v = api_rss_kb() - if v > peak["v"]: - peak["v"] = v - time.sleep(0.2) - -mon = threading.Thread(target=monitor, daemon=True) -mon.start() -results = [None] * n -barrier = threading.Barrier(n) - -def worker(i): - barrier.wait(60) - try: - r = urllib.request.Request( - f"{base}/api/v1/chats/{chat}/attachments?filename=c{i}.png", - data=big, - headers={"Authorization": f"Bearer {token}", "Content-Type": "image/png"}, - method="POST", - ) - with urllib.request.urlopen(r, timeout=120) as resp: - results[i] = resp.status - except Exception as e: - results[i] = str(e) - -threads = [threading.Thread(target=worker, args=(i,)) for i in range(n)] -t0 = time.time() -for th in threads: - th.start() -for th in threads: - th.join() -elapsed = time.time() - t0 -stop.set() -mon.join(timeout=1) -rss_after = api_rss_kb() -ok = sum(1 for r in results if r == 201) -text = "\n".join([ - f"concurrent={n}", - f"upload_bytes={len(big)}", - f"ok_201={ok}", - f"results={results}", - f"elapsed_s={elapsed:.3f}", - f"api_rss_kb_before={rss_before}", - f"api_rss_kb_peak={peak['v']}", - f"api_rss_kb_after={rss_after}", -]) + "\n" -print(text, end="") -open(out, "w").write(text) -sys.exit(0 if ok == n else 1) -PY -echo "wrote $OUT" diff --git a/scripts/reconcile-demo.sh b/scripts/reconcile-demo.sh deleted file mode 100755 index 7bc99c6a..00000000 --- a/scripts/reconcile-demo.sh +++ /dev/null @@ -1,146 +0,0 @@ -#!/bin/sh -# Трек 5: внедрить orphan + missing, показать dry-run и apply, доказать защиту fresh. -set -eu -ROOT=$(CDPATH= cd -- "$(dirname "$0")/.." && pwd) -cd "$ROOT" -OUT=${OUT:-evidence/reconcile.txt} -mkdir -p evidence -: >"$OUT" - -log() { echo "$@" | tee -a "$OUT"; } - -BUCKET=$(grep -E '^S3_BUCKET=' .env | cut -d= -f2-) -BUCKET=${BUCKET:-messenger-attachments} -ROOT_USER=$(grep -E '^MINIO_ROOT_USER=' .env | cut -d= -f2-) -ROOT_PASS=$(grep -E '^MINIO_ROOT_PASSWORD=' .env | cut -d= -f2-) -ROOT_USER=${ROOT_USER:-minioadmin} -ROOT_PASS=${ROOT_PASS:-minioadmin-secret} -ORPHAN_KEY="originals/00000000-0000-4000-8000-0000000000aa" - -log "=== seed orphan object via root PutObject (python/minio not required: curl+aws style via go) ===" -# Используем временный контейнер с нашим s3bootstrap-окружением нельзя для PUT. -# Кладём объект через API MinIO SDK в одноразовом python boto? Проще — docker run с -# нашим образом и маленьким go-one-liner... Пишем через awscli-совместимый путь: -# minio client отсутствует → используем python3 + urllib подписанный запрос слишком сложен. -# Простой путь: временный Go в scripts/seed_orphan — нет. Используем docker compose run -# с entrypoint /s3bootstrap нельзя. Добавим флаг... -# Практика: python boto3 если есть, иначе raw Put через minio-go в compose run server? -# Самое простое — python3 и hashlib hmac для SigV4. - -python3 - <&1 | tee -a "$OUT" - -log "=== apply grace=0 ===" -docker compose --env-file .env run --rm --no-deps reconcile -apply -grace-seconds=0 2>&1 | tee -a "$OUT" - -log "=== second apply (idempotent) ===" -docker compose --env-file .env run --rm --no-deps reconcile -apply -grace-seconds=0 2>&1 | tee -a "$OUT" - -log "=== fresh orphan skipped with default grace ===" -python3 - <&1 | tee -a "$OUT" - -log "wrote $OUT" diff --git a/scripts/restart.sh b/scripts/restart.sh index 9f0235ae..d520d13e 100755 --- a/scripts/restart.sh +++ b/scripts/restart.sh @@ -1,6 +1,7 @@ #!/bin/sh -# Перезапуск API (всех реплик), LB и всех хранилищ без удаления volumes. +# Перезапуск API (всех реплик), LB и ВСЕХ хранилищ (postgres, redis, minio) без удаления volumes. # Важно: именно restart, а не up -d — иначе PID/StartedAt у живых контейнеров не меняются. +# Данные вложений лежат в volume mindata, метаданные — в pgdata: оба переживают restart. set -eu ROOT=$(CDPATH= cd -- "$(dirname "$0")/.." && pwd) cd "$ROOT" diff --git a/scripts/run_track2.sh b/scripts/run_track2.sh new file mode 100755 index 00000000..66944810 --- /dev/null +++ b/scripts/run_track2.sh @@ -0,0 +1,143 @@ +#!/bin/sh +# Трек 2 (согласованность S3 <-> PostgreSQL): повторяемый сценарий reconciler. +# +# Что делает: +# 1. Создаёт расхождения на ОБЕИХ сторонах: +# orphan_old — объект в S3 без строки (инъекция root-учёткой mc), «созрел» дольше grace; +# orphan_fresh — такой же, но только что (не должен быть тронут); +# orphan_bulk — пачка N orphan-объектов (замер стоимости обхода); +# foreign_key — объект с чужой схемой ключа (не должен быть тронут никогда); +# missing_used — вложение прикреплено к сообщению, объект из S3 удалён (ТОЛЬКО отчёт); +# missing_stale — старое неиспользуемое вложение без объекта (кандидат на prune); +# missing_fresh — свежее вложение без объекта (не трогаем); +# control — здоровое вложение с объектом, прикреплено к сообщению (не трогаем). +# 2. dry-run → ничего не меняется (проверяется снимком до/после); +# 3. реальный запуск (-reconcile -reconcile-prune-missing); +# 4. повторный запуск → 0 действий (идемпотентность); +# 5. проверяет инварианты и пишет evidence/track2/*. +# grace для сценария сокращён (TRACK2_GRACE_SECONDS, по умолчанию 45 с; «свежие» нарушения +# должны остаться моложе grace до конца сценария, а он занимает ~20-30 с после их создания) и передаётся ТОЛЬКО +# контейнеру reconcile; у API остаётся S3_ORPHAN_GRACE_SECONDS из .env (300 с). +# Код выхода 2 у reconcile — «найдено используемое вложение без объекта» — здесь ожидаем. +set -eu +ROOT=$(CDPATH= cd -- "$(dirname "$0")/.." && pwd) +cd "$ROOT" +. scripts/_lib.sh + +GRACE=${TRACK2_GRACE_SECONDS:-45} +BULK=${TRACK2_BULK_ORPHANS:-300} +OUT=evidence/track2 +mkdir -p "$OUT" +rm -f "$OUT"/*.txt "$OUT"/*.json + +curl -fsS "$BASE_URL/health/ready" >/dev/null || { echo "стенд не готов: bash scripts/up.sh" >&2; exit 1; } +# Образ reconcile собираем заранее: иначе лог сборки попал бы в stdout первого запуска (JSON-отчёт). +$DC build reconcile >/dev/null 2>&1 +{ + echo "date_utc=$(date -u +%Y-%m-%dT%H:%M:%SZ)" + echo "git_commit=$(git rev-parse --short HEAD 2>/dev/null || echo n/a)" + echo "grace_seconds=$GRACE bulk_orphans=$BULK" + echo "api_replicas=$($DC ps -q api | wc -l | tr -d ' ')" +} > "$OUT/environment.txt" + +echo "== 1. подготовка данных через API" +set -- $(register_and_login); TOK=$1; UID_=$2 +CHAT=$(create_chat "$TOK" "$UID_") +SAMPLE=tests/fixtures/sample.png + +att_id() { upload_file "$TOK" "$CHAT" "$SAMPLE" | json_get id; } +key_of() { psql_q "SELECT object_key FROM attachments WHERE id='$1'"; } +post_msg() { # post_msg ID... → message JSON + ids=$(printf '"%s",' "$@"); ids="[${ids%,}]" + curl -fsS -X POST "$BASE_URL/api/v1/chats/$CHAT/messages" -H "Authorization: Bearer $TOK" \ + -H "Idempotency-Key: t2-$(uuid)" -H 'Content-Type: application/json' -d "{\"text\":\"track2\",\"attachment_ids\":$ids}" +} + +CONTROL=$(att_id); USED=$(att_id); STALE=$(att_id) +post_msg "$CONTROL" "$USED" >/dev/null +K_CONTROL=$(key_of "$CONTROL"); K_USED=$(key_of "$USED"); K_STALE=$(key_of "$STALE") + +OLD_CHAT=$(uuid); K_ORPHAN_OLD="attachments/$OLD_CHAT/$(uuid)" +K_FOREIGN="attachments/not-a-uuid/$(uuid)" +BULK_CHAT=$(uuid) +echo "== 2. инъекция сбоев в S3 (root-учётка mc, только для сценария)" +s3sh "echo orphan-old | mc pipe local/$S3_BUCKET/$K_ORPHAN_OLD >/dev/null && echo foreign | mc pipe local/$S3_BUCKET/$K_FOREIGN >/dev/null" +s3sh "mc rm local/$S3_BUCKET/$K_USED >/dev/null && mc rm local/$S3_BUCKET/$K_STALE >/dev/null" +echo " пачка из $BULK orphan-объектов для замера стоимости обхода" +s3sh "mkdir -p /tmp/bulk && cd /tmp/bulk && i=0 && while [ \$i -lt $BULK ]; do : > \$(cat /proc/sys/kernel/random/uuid); i=\$((i+1)); done && mc cp --recursive /tmp/bulk/ local/$S3_BUCKET/attachments/$BULK_CHAT/ >/dev/null" + +echo "== 3. ждём ${GRACE}+2 с: orphan_old/missing_stale «стареют» за grace" +sleep $((GRACE + 2)) +echo " теперь «свежие» нарушения (моложе grace):" +FRESH_ATT=$(att_id); K_FRESH=$(key_of "$FRESH_ATT") +s3sh "mc rm local/$S3_BUCKET/$K_FRESH >/dev/null" +K_ORPHAN_FRESH="attachments/$(uuid)/$(uuid)" +s3sh "echo orphan-fresh | mc pipe local/$S3_BUCKET/$K_ORPHAN_FRESH >/dev/null" + +snapshot() { # snapshot FILE — состояние обеих сторон по ключам сценария (один запуск mc на снимок) + ALL=$(s3sh "mc find local/$S3_BUCKET --name '*'") + { + for k in "$K_ORPHAN_OLD" "$K_ORPHAN_FRESH" "$K_FOREIGN" "$K_CONTROL" "$K_USED" "$K_STALE" "$K_FRESH"; do + if printf '%s\n' "$ALL" | grep -qF "/$k"; then o=object; else o=NO-object; fi + printf '%-9s %s\n' "$o" "$k" + done + for pair in "control:$CONTROL" "used:$USED" "stale:$STALE" "fresh:$FRESH_ATT"; do + n=$(psql_q "SELECT count(*) FROM attachments WHERE id='${pair#*:}'") + printf 'row[%s]=%s\n' "${pair%%:*}" "$n" + done + echo "bulk_objects=$(printf '%s\n' "$ALL" | grep -c "/attachments/$BULK_CHAT/" || true)" + } > "$1" +} + +reconcile() { # reconcile NAME ARGS... → NAME.json (stdout), NAME.log (stderr), печатает код выхода + name=$1; shift + rc=0 + $DC run --rm -T --no-deps -e S3_ORPHAN_GRACE_SECONDS="$GRACE" reconcile "$@" \ + > "$OUT/$name.json" 2> "$OUT/$name.log" || rc=$? + echo "$rc" > "$OUT/$name.exitcode" + echo " $name: exit=$rc ($(python3 -c 'import json,sys; r=json.load(open(sys.argv[1])); print("orphans_found=%s deleted=%s missing_found=%s used=%s pruned=%s duration_ms=%s" % (r["orphans_found"],r["orphans_deleted"],r["missing_found"],r["missing_used"],r["missing_pruned"],r["duration_ms"]))' "$OUT/$name.json"))" +} +field() { python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))[sys.argv[2]])' "$OUT/$1.json" "$2"; } + +snapshot "$OUT/state_before.txt" +echo "== 4. dry-run (ничего не должно измениться)" +reconcile 1_dry_run -reconcile-dry-run -reconcile-prune-missing +snapshot "$OUT/state_after_dry_run.txt" +echo "== 5. реальный запуск" +reconcile 2_real -reconcile -reconcile-prune-missing +snapshot "$OUT/state_after_real.txt" +echo "== 6. повторный запуск (идемпотентность)" +reconcile 3_repeat -reconcile -reconcile-prune-missing + +echo "== 7. проверка инвариантов" +fail=0 +check() { if [ "$2" = ok ]; then echo "PASS $1"; else echo "FAIL $1"; fail=1; fi; } +t() { if eval "$1"; then echo ok; else echo no; fi; } + +check "dry-run не менял данные" "$(t "diff -q $OUT/state_before.txt $OUT/state_after_dry_run.txt >/dev/null")" +check "dry-run нашёл orphan-ы, но не удалил (deleted=0)" "$(t "[ $(field 1_dry_run orphans_found) -ge $((BULK+1)) ] && [ $(field 1_dry_run orphans_deleted) -eq 0 ] && [ $(field 1_dry_run s3_delete_calls) -eq 0 ]")" +check "dry-run: missing used/stale/fresh обнаружены" "$(t "[ $(field 1_dry_run missing_used) -ge 1 ] && [ $(field 1_dry_run missing_stale) -ge 1 ] && [ $(field 1_dry_run missing_fresh) -ge 1 ]")" +check "real: orphan_old и пачка удалены" "$(t "[ $(field 2_real orphans_deleted) -ge $((BULK+1)) ]")" +check "real: orphan_old действительно исчез из S3" "$(t "grep -q 'NO-object $K_ORPHAN_OLD' $OUT/state_after_real.txt")" +check "real: свежий orphan цел" "$(t "grep -q '^object $K_ORPHAN_FRESH' $OUT/state_after_real.txt")" +check "real: объект с чужой схемой ключа цел" "$(t "grep -q '^object $K_FOREIGN' $OUT/state_after_real.txt")" +check "real: control (строка+объект) цел" "$(t "grep -q '^object $K_CONTROL' $OUT/state_after_real.txt && grep -q 'row\[control\]=1' $OUT/state_after_real.txt")" +check "real: used без объекта НЕ удалён, есть alert" "$(t "grep -q 'row\[used\]=1' $OUT/state_after_real.txt && [ $(field 2_real missing_used) -ge 1 ] && [ \$(cat $OUT/2_real.exitcode) -eq 2 ]")" +check "real: stale unused без объекта удалена (prune)" "$(t "grep -q 'row\[stale\]=0' $OUT/state_after_real.txt && [ $(field 2_real missing_pruned) -ge 1 ]")" +check "real: fresh без объекта НЕ удалена" "$(t "grep -q 'row\[fresh\]=1' $OUT/state_after_real.txt")" +check "repeat: идемпотентность (0 удалений, 0 prune)" "$(t "[ $(field 3_repeat orphans_deleted) -eq 0 ] && [ $(field 3_repeat missing_pruned) -eq 0 ] && [ $(field 3_repeat orphans_found) -eq 0 ]")" + +{ + echo "# Стоимость обхода (из JSON-отчётов)" + for n in 1_dry_run 2_real 3_repeat; do + python3 - "$OUT/$n.json" "$n" <<'PY' +import json, sys +r = json.load(open(sys.argv[1])) +print("%-10s s3_objects=%-5d db_rows=%-4d s3_list_calls=%-3d db_pages=%-3d head_calls=%-3d delete_calls=%-4d duration_ms=%d" + % (sys.argv[2], r["s3_objects_scanned"], r["db_rows_scanned"], r["s3_list_calls"], r["db_pages"], + r["s3_head_calls"], r["s3_delete_calls"], r["duration_ms"])) +PY + done +} | tee "$OUT/cost.txt" + +[ "$fail" = 0 ] && echo "ИТОГ track2: все инварианты выполнены (evidence в $OUT/)" || { echo "ИТОГ track2: ЕСТЬ ОШИБКИ"; exit 1; } diff --git a/scripts/up.sh b/scripts/up.sh index 51bd2f2a..cc0e614f 100755 --- a/scripts/up.sh +++ b/scripts/up.sh @@ -1,6 +1,11 @@ #!/bin/sh # Единая последовательность запуска стенда lab4. -# 1) postgres+redis+minio 2) bootstrap bucket 3) миграции 4) API×N 5) HAProxy +# 1) postgres + redis + minio (ждём healthcheck) +# 2) minio-init: приватный bucket, пользователь messenger-api, политика (идемпотентно) +# 3) однократные миграции (заодно проверка bucket) +# 4) API×N 5) HAProxy +# Порядок важен: API и migrate не стартуют, пока bucket и S3-пользователь не готовы, +# иначе первая же загрузка вложения получила бы 503. set -eu ROOT=$(CDPATH= cd -- "$(dirname "$0")/.." && pwd) cd "$ROOT" @@ -10,20 +15,24 @@ if [ ! -f .env ]; then echo "created .env from .env.example" >&2 fi -API_REPLICAS=$(grep -E '^API_REPLICAS=' .env | cut -d= -f2- || true) +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:-8080} docker compose --env-file .env config --quiet -docker compose --env-file .env up -d --build postgres redis minio +# --wait: возвращаемся, только когда у сервисов с healthcheck статус healthy. +docker compose --env-file .env up -d --build --wait postgres redis minio +# minio-init — одноразовый (restart: no): run --rm дожидается завершения и возвращает его код. docker compose --env-file .env run --rm minio-init docker compose --env-file .env run --rm --build migrate docker compose --env-file .env up -d --build --scale "api=${API_REPLICAS}" --no-deps api docker compose --env-file .env up -d --no-deps lb -echo "waiting for http://127.0.0.1:8080/health/ready via LB..." -deadline=$(( $(date +%s) + 180 )) +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:8080/health/ready" >/dev/null 2>&1; then + if curl -fsS "http://127.0.0.1:${LB_PORT}/health/ready" >/dev/null 2>&1; then echo "ready" docker compose --env-file .env ps exit 0 @@ -31,7 +40,7 @@ while :; do if [ "$(date +%s)" -ge "$deadline" ]; then echo "timeout waiting for readiness" >&2 docker compose --env-file .env ps >&2 || true - docker compose --env-file .env logs --tail=80 api lb minio minio-init >&2 || true + docker compose --env-file .env logs --tail=80 api lb minio >&2 || true exit 1 fi sleep 1 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 index ab0a303e..c95d4598 100644 --- a/student-tests/api_test.go +++ b/student-tests/api_test.go @@ -1,6 +1,7 @@ -// Собственные проверки lab3 (плюс регрессия lab2). Им нужен уже поднятый -// PostgreSQL и Redis (docker compose up / scripts/up.sh): контракт требует -// настоящую БД, а не sqlmock. HTTP бьём в httptest.Server поверх того же Store, +// Собственные проверки 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. // // Каждый тест пишет в лог, что именно проверяет и какой статус получил. @@ -25,7 +26,7 @@ import ( "mtusi2026lab4/internal/api" "mtusi2026lab4/internal/auth" - "mtusi2026lab4/internal/blob" + "mtusi2026lab4/internal/objectstore" "mtusi2026lab4/internal/session" "mtusi2026lab4/internal/store" ) @@ -34,6 +35,8 @@ var ( sharedStore *store.Store sharedSessions *session.Store sharedRedisURL string + // sharedObjects — клиент к тому же MinIO, что и реплики (учётка messenger-api, не root). + sharedObjects *objectstore.Store ) func TestMain(m *testing.M) { @@ -61,6 +64,23 @@ func TestMain(m *testing.M) { 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) @@ -336,7 +356,7 @@ func TestRedisDownIsNotAnonymous(t *testing.T) { if err := closed.Close(); err != nil { t.Fatal(err) } - srv := httptest.NewServer(api.New(sharedStore, closed, blob.NewMemory(), "test-closed-redis").Handler()) + srv := httptest.NewServer(api.New(sharedStore, closed, sharedObjects, "test-closed-redis").Handler()) defer srv.Close() regSrv := newAPI(t, time.Hour) defer regSrv.Close() @@ -380,7 +400,7 @@ func TestPostgresDownIsNotAnonymous(t *testing.T) { t.Fatal(err) } t.Cleanup(func() { _ = sessions.Close() }) - srv := httptest.NewServer(api.New(broken, sessions, blob.NewMemory(), "test-broken-pg").Handler()) + 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, "") @@ -405,7 +425,6 @@ func TestPostgresDownIsNotAnonymous(t *testing.T) { logOK(t, "сбой PostgreSQL не стал анонимным доступом") } - func TestIdempotencyReplayAndConflict(t *testing.T) { srv := newAPI(t, time.Hour) defer srv.Close() @@ -450,7 +469,7 @@ func TestIdempotencyKeyRequiredAndConcurrent(t *testing.T) { chat := createChat(t, srv, token, user.id, "Гонка ключа") // Явно без ключа: хелпер doRaw подставляет ключ только если заголовок пуст — - // поэтому бьём в doRaw с пустым Idempotency-Key, переопределив после... + // поэтому бьём в doRaw с пустым Idempotency-Key, переопределив после... // Проще: отдельный raw-запрос. req, err := http.NewRequest(http.MethodPost, srv.URL+"/api/v1/chats/"+chat+"/messages", strings.NewReader(`{"text":"без ключа"}`)) if err != nil { @@ -528,17 +547,7 @@ func newAPI(t *testing.T, ttl time.Duration) *httptest.Server { t.Fatal(err) } t.Cleanup(func() { _ = sessions.Close() }) - return httptest.NewServer(api.New(sharedStore, sessions, blob.NewMemory(), "test-instance").Handler()) -} - -func newAPIBlob(t *testing.T, ttl time.Duration, bl api.BlobStore) *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, bl, "test-instance").Handler()) + return httptest.NewServer(api.New(sharedStore, sessions, sharedObjects, "test-instance").Handler()) } func register(t *testing.T, srv *httptest.Server, prefix string) account { diff --git a/student-tests/attachments_test.go b/student-tests/attachments_test.go index 2cb3dd86..c11bc080 100644 --- a/student-tests/attachments_test.go +++ b/student-tests/attachments_test.go @@ -1,244 +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" - "encoding/json" + "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" + "mtusi2026lab4/internal/api" - "mtusi2026lab4/internal/blob" + "mtusi2026lab4/internal/auth" + "mtusi2026lab4/internal/objectstore" "mtusi2026lab4/internal/session" + "mtusi2026lab4/internal/store" ) -// 1×1 PNG (valid IHDR + IDAT + IEND, CRC проверены). -var tinyPNG = []byte{ - 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, - 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, - 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, - 0x08, 0x02, 0x00, 0x00, 0x00, 0x90, 0x77, 0x53, - 0xde, 0x00, 0x00, 0x00, 0x0c, 0x49, 0x44, 0x41, - 0x54, 0x78, 0xda, 0x63, 0xf8, 0xcf, 0xc0, 0x00, - 0x00, 0x03, 0x01, 0x01, 0x00, 0xf7, 0x03, 0x41, - 0x43, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, - 0x44, 0xae, 0x42, 0x60, 0x82, +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() } -func TestAttachmentUploadDownloadAndACL(t *testing.T) { - mem := blob.NewMemory() - srv := newAPIBlob(t, time.Hour, mem) +// 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() - logStep(t, "upload PNG → 201 ready → download checksum; посторонний — 404") + 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} - owner := register(t, srv, "att_owner") - ownerTok := login(t, srv, owner.username, owner.password) - stranger := register(t, srv, "att_stranger") - strangerTok := login(t, srv, stranger.username, stranger.password) - chat := createChat(t, srv, ownerTok, owner.id, "Вложения") - - attID, sha := uploadPNG(t, srv, ownerTok, chat, "pic.png", tinyPNG) - status, body := do(t, srv, http.MethodGet, "/api/v1/attachments/"+attID, map[string]string{ - "Authorization": "Bearer " + ownerTok, - }, "") - logResult(t, status, body) - if status != http.StatusOK { - t.Fatalf("meta: %d %s", status, body) + 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) } - meta := decode(t, body) - if meta["status"] != "ready" || meta["sha256"] != sha { - t.Fatalf("meta unexpected: %+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") } - statusCode, raw, hdr := downloadBytes(t, srv, ownerTok, attID) - if statusCode != http.StatusOK { - t.Fatalf("download: %d", statusCode) - } - if hdr.Get("Content-Type") != "image/png" { - t.Fatalf("content-type: %q", hdr.Get("Content-Type")) - } - sum := sha256.Sum256(raw) - if hex.EncodeToString(sum[:]) != sha { - t.Fatalf("checksum mismatch") + // 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) } - status, body = do(t, srv, http.MethodGet, "/api/v1/attachments/"+attID, map[string]string{ - "Authorization": "Bearer " + strangerTok, - }, "") + // Посторонний: метаданные, байты, загрузка — всё 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("stranger meta: %d", status) + t.Fatalf("чужое attachment_id: %d %s", status, body) } - statusCode, _, _ = downloadBytes(t, srv, strangerTok, attID) - if statusCode != http.StatusNotFound { - t.Fatalf("stranger download: %d", statusCode) - } - - status, body = do(t, srv, http.MethodPost, "/api/v1/chats/"+chat+"/messages", map[string]string{ - "Authorization": "Bearer " + ownerTok, - }, fmt.Sprintf(`{"text":"с файлом","attachment_ids":[%q]}`, attID)) + // 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("message with att: %d %s", status, body) + t.Fatalf("пустой текст с вложением: %d %s", status, body) } - msg := decode(t, body) - ids, _ := msg["attachment_ids"].([]any) - if len(ids) != 1 || ids[0] != attID { - t.Fatalf("attachment_ids: %+v", msg["attachment_ids"]) + if m := decode(t, body); m["text"] != "" { + t.Fatalf("text: %v", m["text"]) } - logOK(t, "upload/download/ACL и message.attachment_ids") + 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, пустой текст только с вложением") } -func TestAttachmentRejectsBadInput(t *testing.T) { - mem := blob.NewMemory() - srv := newAPIBlob(t, time.Hour, mem) - defer srv.Close() - logStep(t, "битый PNG, подмена MIME, опасный filename, чужой чат → 4xx не 500") - - user := register(t, srv, "att_bad") - tok := login(t, srv, user.username, user.password) - chat := createChat(t, srv, tok, user.id, "Отказы") - - status, body := uploadRaw(t, srv, tok, chat, "../x.png", "image/png", tinyPNG) - logResult(t, status, body) - if status != http.StatusBadRequest { - t.Fatalf("bad filename: %d", status) +// 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) } - - status, body = uploadRaw(t, srv, tok, chat, "x.jpg", "image/jpeg", tinyPNG) - logResult(t, status, body) - if status != http.StatusUnsupportedMediaType { - t.Fatalf("mime mismatch: %d", status) - } - - status, body = uploadRaw(t, srv, tok, chat, "bad.png", "image/png", tinyPNG[:20]) - logResult(t, status, body) - if status != http.StatusUnsupportedMediaType { - t.Fatalf("truncated: %d", status) - } - - // Отдельный сервер с маленьким лимитом: реально шлём 2 KiB, ожидаем 413. - small := blob.NewMemory() + // Пользователь и чат — через нормальный API; недоступный S3 подсовываем второй реплике. + good := newChatCtx(t, "att_down") sessions, err := session.Open(sharedRedisURL, time.Hour) if err != nil { t.Fatal(err) } - t.Cleanup(func() { _ = sessions.Close() }) - apiSrv := api.New(sharedStore, sessions, small, "test-small-limit") - apiSrv.MaxUploadBytes = 1024 - limSrv := httptest.NewServer(apiSrv.Handler()) - defer limSrv.Close() - status, body = uploadRaw(t, limSrv, tok, chat, "huge.png", "image/png", make([]byte, 2048)) - logResult(t, status, body) - if status != http.StatusRequestEntityTooLarge { - t.Fatalf("too large body: %d", status) - } - - other := register(t, srv, "att_other") - otherTok := login(t, srv, other.username, other.password) - otherChat := createChat(t, srv, otherTok, other.id, "Чужой") - status, body = uploadRaw(t, srv, tok, otherChat, "x.png", "image/png", tinyPNG) - logResult(t, status, body) - if status != http.StatusNotFound { - t.Fatalf("foreign chat upload: %d", status) - } - - attID, _ := uploadPNG(t, srv, otherTok, otherChat, "o.png", tinyPNG) - status, body = do(t, srv, http.MethodPost, "/api/v1/chats/"+chat+"/messages", map[string]string{ - "Authorization": "Bearer " + tok, - }, fmt.Sprintf(`{"text":"steal","attachment_ids":[%q]}`, attID)) - logResult(t, status, body) - if status != http.StatusNotFound { - t.Fatalf("foreign attachment_id: %d %s", status, body) - } - logOK(t, "негативные сценарии вложений → клиентские 4xx") -} - -func TestAttachmentS3DownIs503(t *testing.T) { - mem := blob.NewMemory() - mem.SetUnavailable(true) - srv := newAPIBlob(t, time.Hour, mem) + defer sessions.Close() + srv := httptest.NewServer(api.New(sharedStore, sessions, dead, "dead-s3").Handler()) defer srv.Close() - logStep(t, "S3 недоступен: ready и upload → 503") - status, body := do(t, srv, http.MethodGet, "/health/ready", nil, "") - logResult(t, status, body) - if status != http.StatusServiceUnavailable { - t.Fatalf("ready: %d", status) + 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)) } - user := register(t, srv, "s3_down") - tok := login(t, srv, user.username, user.password) - chat := createChat(t, srv, tok, user.id, "S3 down") - status, body = uploadRaw(t, srv, tok, chat, "x.png", "image/png", tinyPNG) - logResult(t, status, body) + status, b, _ = doRaw2(t, srv, "/health/ready") if status != http.StatusServiceUnavailable { - t.Fatalf("upload with s3 down: %d %s", status, body) + t.Fatalf("/health/ready при лежащем S3: %d %s", status, b) } - logOK(t, "падение S3 → 503") + 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 uploadPNG(t *testing.T, srv *httptest.Server, token, chatID, filename string, data []byte) (id, sha string) { +func doRaw2(t *testing.T, srv *httptest.Server, path string) (int, []byte, http.Header) { t.Helper() - status, body := uploadRaw(t, srv, token, chatID, filename, "image/png", data) - if status != http.StatusCreated { - t.Fatalf("upload: %d %s", status, body) - } - var att struct { - ID string `json:"id"` - SHA256 string `json:"sha256"` - Status string `json:"status"` - } - if err := json.Unmarshal([]byte(body), &att); err != nil { - t.Fatal(err) - } - if att.Status != "ready" || att.ID == "" { - t.Fatalf("upload body: %s", body) - } - sum := sha256.Sum256(data) - want := hex.EncodeToString(sum[:]) - if att.SHA256 != want { - t.Fatalf("sha got=%s want=%s", att.SHA256, want) - } - return att.ID, att.SHA256 -} - -func uploadRaw(t *testing.T, srv *httptest.Server, token, chatID, filename, ctype string, data []byte) (int, string) { - t.Helper() - u := srv.URL + "/api/v1/chats/" + chatID + "/attachments?filename=" + url.QueryEscape(filename) - req, err := http.NewRequest(http.MethodPost, u, bytes.NewReader(data)) - if err != nil { - t.Fatal(err) - } - req.Header.Set("Authorization", "Bearer "+token) - req.Header.Set("Content-Type", ctype) - resp, err := http.DefaultClient.Do(req) + 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, string(b) + return resp.StatusCode, b, resp.Header } -func downloadBytes(t *testing.T, srv *httptest.Server, token, attID string) (int, []byte, http.Header) { - t.Helper() - req, err := http.NewRequest(http.MethodGet, srv.URL+"/api/v1/attachments/"+attID+"/content", nil) +// Компенсация: 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) } - req.Header.Set("Authorization", "Bearer "+token) - resp, err := http.DefaultClient.Do(req) + // Отдельный пул, который «умрёт» ровно между 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 resp.Body.Close() - b, _ := io.ReadAll(resp.Body) - return resp.StatusCode, b, resp.Header.Clone() + 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) } diff --git a/student-tests/reconcile_test.go b/student-tests/reconcile_test.go new file mode 100644 index 00000000..9f431a54 --- /dev/null +++ b/student-tests/reconcile_test.go @@ -0,0 +1,198 @@ +// Трек 2: reconciler S3 <-> PostgreSQL. Тест создаёт расхождения на ОБЕИХ сторонах +// и проходит сценарий dry-run → реальный запуск → повтор, проверяя, что свежие и +// используемые вложения не удаляются. +// +// Возраст объектов в тесте регулируется «часами» reconciler (Options.Now), а не sleep: +// так тест быстрый и не зависит от рассинхрона часов хоста и контейнера MinIO +// (на Docker Desktop они могут расходиться на секунды) — смещение измеряется по пробному объекту. +package studenttests + +import ( + "bytes" + "context" + "errors" + "testing" + "time" + + "github.com/google/uuid" + + "mtusi2026lab4/internal/objectstore" + "mtusi2026lab4/internal/reconcile" + "mtusi2026lab4/internal/store" +) + +func TestReconcilerOrphanAndMissing(t *testing.T) { + logStep(t, "orphan/missing: dry-run ничего не меняет; свежие и используемые не удаляются; повтор идемпотентен") + ctx := context.Background() + const grace = 60 * time.Second + + c := newChatCtx(t, "rec") + chatID := uuid.MustParse(c.chat) + owner := uuid.MustParse(c.owner.id) + + put := func(key string) { + t.Helper() + data := []byte("reconcile-test") + if err := sharedObjects.Put(ctx, key, bytes.NewReader(data), int64(len(data)), "image/png"); err != nil { + t.Fatalf("put %s: %v", key, err) + } + } + exists := func(key string) bool { + t.Helper() + _, err := sharedObjects.Head(ctx, key) + if err == nil { + return true + } + if errors.Is(err, objectstore.ErrNotFound) { + return false + } + t.Fatalf("head %s: %v", key, err) + return false + } + rowExists := func(a *store.Attachment) bool { + t.Helper() + _, err := sharedStore.GetAttachmentForUser(ctx, a.ID, owner) + if err == nil { + return true + } + if errors.Is(err, store.ErrNotFound) { + return false + } + t.Fatalf("get row: %v", err) + return false + } + + // Смещение часов S3 относительно хоста: пробный объект, LastModified у сервера. + probeKey := store.AttachmentObjectKey(chatID, uuid.New()) + put(probeKey) + info, err := sharedObjects.Head(ctx, probeKey) + if err != nil { + t.Fatal(err) + } + skew := time.Since(info.LastModified) // >0, если часы S3 отстают + _ = sharedObjects.Delete(ctx, probeKey) + t.Logf("смещение часов S3 относительно теста: %s", skew.Round(time.Millisecond)) + clockNow := func(shift time.Duration) func() time.Time { + return func() time.Time { return time.Now().Add(-skew).Add(shift) } + } + + newRow := func(filename string, createdAt time.Time) *store.Attachment { + t.Helper() + id := uuid.New() + a := &store.Attachment{ + ID: id, ChatID: chatID, OwnerID: owner, Filename: filename, + ContentType: "image/png", SizeBytes: 14, SHA256: hexSHA([]byte(filename)), + ObjectKey: store.AttachmentObjectKey(chatID, id), Status: store.StatusReady, + Width: 1, Height: 1, CreatedAt: createdAt.UTC().Truncate(time.Millisecond), + } + if err := sharedStore.CreateAttachment(ctx, a); err != nil { + t.Fatalf("create row %s: %v", filename, err) + } + return a + } + + now := time.Now() + // A: orphan — объект без строки. + orphanKey := store.AttachmentObjectKey(chatID, uuid.New()) + put(orphanKey) + // F: объект с чужой схемой ключа — reconciler не должен его трогать никогда. + foreignKey := "attachments/not-a-uuid/" + uuid.NewString() + put(foreignKey) + // E: контроль — согласованная пара «строка + объект», используется сообщением. + rowE := newRow("control", now.Add(-time.Hour)) + put(rowE.ObjectKey) + // B: неиспользуемая, старая, без объекта. C: используемая сообщением, без объекта. + rowB := newRow("stale-unused-missing", now.Add(-time.Hour)) + rowC := newRow("used-missing", now.Add(-time.Hour)) + // D: свежая строка без объекта. + rowD := newRow("fresh-missing", now) + put(rowC.ObjectKey) // на время создания сообщения объект C есть, потом «потеряем» его + msgKey := "rec-" + uuid.NewString() + if _, err := sharedStore.CreateMessageIdempotent(ctx, chatID, owner, "с вложениями", + []uuid.UUID{rowE.ID, rowC.ID}, "POST", "/api/v1/chats/"+c.chat+"/messages", msgKey, "hash-"+msgKey); err != nil { + t.Fatalf("message with attachments: %v", err) + } + if err := sharedObjects.Delete(ctx, rowC.ObjectKey); err != nil { // потеря байтов у используемого вложения + t.Fatal(err) + } + t.Cleanup(func() { put(rowC.ObjectKey) }) // вернуть объект, чтобы не оставлять «дыру» в общей БД стенда + + run := func(name string, dry, prune bool, shift time.Duration) *reconcile.Report { + t.Helper() + rc := &reconcile.Reconciler{DB: sharedStore, Objects: sharedObjects, Opts: reconcile.Options{ + DryRun: dry, Grace: grace, PruneMissing: prune, PageSize: 2, // 2 — чтобы пройти многостраничный merge + Now: clockNow(shift), Logf: t.Logf, + }} + rep, err := rc.Run(ctx) + if err != nil { + t.Fatalf("%s: %v", name, err) + } + t.Logf("%s: %+v", name, *rep) + return rep + } + + // R1: dry-run «сейчас» — A свежий, всё остальное только в отчёте. + r1 := run("R1 dry-run, now", true, true, 0) + if r1.OrphansFresh < 1 || r1.OrphansFound != 0 || r1.OrphansDeleted != 0 || r1.DeleteCalls != 0 || r1.MissingPruned != 0 { + t.Fatalf("R1: свежий orphan не должен считаться кандидатом на удаление: %+v", *r1) + } + if r1.MissingUsed < 1 || r1.MissingStale < 1 || r1.MissingFresh < 1 || r1.UnknownKeys < 1 { + t.Fatalf("R1: не обнаружены missing used/stale/fresh или чужой ключ: %+v", *r1) + } + if !exists(orphanKey) || !rowExists(rowB) || !rowExists(rowC) || !rowExists(rowD) { + t.Fatal("R1 (dry-run) изменил данные") + } + + // R2: dry-run через 2 минуты — A уже «старый», но dry-run не удаляет. + r2 := run("R2 dry-run, +120s", true, true, 2*time.Minute) + if r2.OrphansFound < 1 || r2.OrphansDeleted != 0 || r2.DeleteCalls != 0 || r2.MissingPruned != 0 { + t.Fatalf("R2: %+v", *r2) + } + if !exists(orphanKey) || !rowExists(rowB) || !rowExists(rowD) { + t.Fatal("R2 (dry-run) изменил данные") + } + + // R3: реальный запуск +120s, prune выключен: удаляется только orphan, строки остаются. + r3 := run("R3 real, +120s, prune off", false, false, 2*time.Minute) + if r3.OrphansDeleted < 1 || r3.MissingPruned != 0 { + t.Fatalf("R3: %+v", *r3) + } + if exists(orphanKey) { + t.Fatal("R3: orphan должен быть удалён") + } + if !exists(foreignKey) { + t.Fatal("R3: объект с чужой схемой ключа удалён — недопустимо") + } + if !rowExists(rowB) || !rowExists(rowC) || !rowExists(rowD) || !exists(rowE.ObjectKey) { + t.Fatal("R3: затронуты строки/объекты, которые трогать нельзя") + } + + // R4: реальный запуск «сейчас» с prune: удаляется только СТАРАЯ НЕИСПОЛЬЗУЕМАЯ B. + r4 := run("R4 real, now, prune on", false, true, 0) + if r4.MissingPruned < 1 || rowExists(rowB) { + t.Fatalf("R4: B должна быть удалена: %+v", *r4) + } + if !rowExists(rowC) { + t.Fatal("R4: используемое вложение C удалено — недопустимо") + } + if !rowExists(rowD) { + t.Fatal("R4: свежая строка D удалена — недопустимо") + } + + // R5: повтор — ничего не находит и не меняет (идемпотентность). + r5 := run("R5 repeat", false, true, 0) + if r5.OrphansDeleted != 0 || r5.MissingPruned != 0 || r5.OrphansFound != 0 { + t.Fatalf("R5 не идемпотентен: %+v", *r5) + } + + // R6: через 2 минуты D стала «старой», её можно убрать; C и E — никогда. + r6 := run("R6 real, +120s, prune on", false, true, 2*time.Minute) + if r6.MissingPruned < 1 || rowExists(rowD) { + t.Fatalf("R6: D должна быть удалена: %+v", *r6) + } + if !rowExists(rowC) || !rowExists(rowE) || !exists(rowE.ObjectKey) { + t.Fatal("R6: используемые вложения затронуты — недопустимо") + } + _ = sharedObjects.Delete(ctx, foreignKey) + logOK(t, "orphan удалён после grace, чужие ключи/свежие/используемые целы, dry-run и повтор безопасны") +} -- 2.54.0