diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 00000000..0212ffae --- /dev/null +++ b/Dockerfile @@ -0,0 +1,33 @@ +FROM golang:1.26.3 AS build + +WORKDIR /src + +ENV GOTOOLCHAIN=local +ENV CGO_ENABLED=0 + +COPY go.mod go.sum ./ +RUN go mod download +COPY cmd ./cmd +COPY internal ./internal + +RUN go vet ./... \ + && go test ./... \ + && go build -trimpath -ldflags="-s -w" -o /out/server ./cmd/server + +FROM scratch + +COPY --from=build /out/server /server + +USER 65532:65532 + +ENV APP_HOST=0.0.0.0 +ENV APP_PORT=8080 + +EXPOSE 8080 + +STOPSIGNAL SIGTERM + +HEALTHCHECK --interval=5s --timeout=3s --start-period=5s --retries=3 \ + CMD ["/server", "healthcheck"] + +ENTRYPOINT ["/server"] diff --git a/REPORT.md b/REPORT.md index 9ad2b84f..620a2c6a 100644 --- a/REPORT.md +++ b/REPORT.md @@ -1,9 +1,32 @@ # Отчёт — лабораторная 4 -- Автор, группа: TODO -- Целевая оценка; выбранный трек 5, если нужен: TODO +- Автор, группа: Ситникова Дарья Евгеньевна, БВТ2303 +- Целевая оценка: 4; трек на 5 не заявлен - Commit/PR: TODO после публикации -- Использованные источники, библиотеки и помощь ИИ: TODO +- Использованные источники, библиотеки и помощь ИИ: собственная реализация lab3; Go, pgx/v5, go-redis/v9, golang.org/x/crypto (версии в go.mod); Codex — перенос основы проекта. Дополняется по мере реализации. + +## Текущий этап: перенос основы из lab3 + +06.11.2026 перенесены исходники Go, модуль и зависимости, Dockerfile, миграции PostgreSQL, конфигурация HAProxy, Compose, собственные тесты и скрипты управления стендом. Собственные тесты скопированы из текущего рабочего дерева lab3, включая незакоммиченные доработки. Публичные tests, contracts и документы задания lab4 сохранены. + +Основа: две API-реплики за HAProxy, общие PostgreSQL-сессии и сообщения, Redis-кэш, идемпотентная отправка сообщений. Проект Compose переименован в `messenger-lab4`, volume — в `postgres_lab4_data_v1`, порт LB по умолчанию — `8084`. Данные и секреты lab3 не переносились. Путь Go-модуля сохранён из предыдущей реализации. + +S3 и вложения пока не реализованы. Результаты lab3 не являются доказательствами выполнения lab4. Собственные тесты и hooks перенесены как основа; после добавления S3 их потребуется дополнить. Новые результаты проверок и экспериментов будут записываться в `evidence/`. + +Подготовка и запуск перенесённой основы из корня репозитория: + +```powershell +./scripts/init-local.ps1 +docker compose --env-file .env config --quiet +docker compose --env-file .env up -d --build --wait --wait-timeout 180 +# API: http://127.0.0.1:8084 +# Остановка с сохранением данных: +docker compose down +``` + +Это запуск основы lab3; публичный smoke lab4 требует ещё не реализованные вложения. + +Проверки переноса: `go test ./...`, `go vet ./...`, `scripts/check_contract.py` и `docker compose --env-file .env.example config --quiet` завершились успешно. HTTP-тесты повторены вне песочницы после блокировки localhost в первом запуске. Стенд не запускался. [Результаты](evidence/transfer-checks.txt). ## Запуск из чистого clone diff --git a/cmd/server/dbcheck.go b/cmd/server/dbcheck.go new file mode 100644 index 00000000..3daac573 --- /dev/null +++ b/cmd/server/dbcheck.go @@ -0,0 +1,41 @@ +package main + +import ( + "context" + "errors" + "fmt" + "time" + + "gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/store" +) + +func checkDatabase() error { + ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second) + defer cancel() + + pool, err := store.OpenPostgres(ctx, envOrDefault( + "DATABASE_PASSWORD_FILE", "/run/secrets/postgres_password", + )) + if err != nil { + return err + } + defer pool.Close() + + queryCtx, queryCancel := context.WithTimeout(ctx, 3*time.Second) + defer queryCancel() + + var applied bool + err = pool.QueryRow(queryCtx, + "SELECT EXISTS (SELECT 1 FROM schema_migrations WHERE version = $1)", + int64(1), + ).Scan(&applied) + if err != nil { + return errors.New("cannot read schema_migrations; check database and migrations") + } + if !applied { + return errors.New("migration 000001 is not applied") + } + + fmt.Println("PASS: PostgreSQL connection, migration 000001; pool max_conns=10") + return nil +} diff --git a/cmd/server/main.go b/cmd/server/main.go new file mode 100644 index 00000000..8b831eef --- /dev/null +++ b/cmd/server/main.go @@ -0,0 +1,170 @@ +package main + +import ( + "context" + "errors" + "fmt" + "log" + "net" + "net/http" + "os" + "os/signal" + "strconv" + "sync/atomic" + "syscall" + "time" + + "gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/cache" + "gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/httpapi" + "gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/store" +) + +func main() { + log.SetFlags(log.LstdFlags | log.LUTC) + + if len(os.Args) == 2 && os.Args[1] == "dbcheck" { + if err := checkDatabase(); err != nil { + log.Print(err) + os.Exit(1) + } + return + } + + if len(os.Args) == 2 && (os.Args[1] == "healthcheck" || os.Args[1] == "instance-id") { + if err := healthcheck(); err != nil { + log.Print(err) + os.Exit(1) + } + return + } + + if err := run(); err != nil { + log.Print(err) + os.Exit(1) + } +} + +func run() error { + host := envOrDefault("APP_HOST", "0.0.0.0") + port := envOrDefault("APP_PORT", "8080") + + pool, err := store.OpenPostgres(context.Background(), envOrDefault( + "DATABASE_PASSWORD_FILE", "/run/secrets/postgres_password", + )) + if err != nil { + return err + } + defer pool.Close() + profiles := cache.NewProfiles(envOrDefault("REDIS_ADDR", "redis:6379")) + defer profiles.Close() + db := store.NewPostgresStore(pool).WithProfiles(profiles) + + var stopping atomic.Bool + ttl, err := strconv.ParseInt(envOrDefault("SESSION_TTL_SECONDS", "3600"), 10, 64) + if err != nil { + return errors.New("invalid SESSION_TTL_SECONDS") + } + handler, err := httpapi.NewPostgresHandler(db, &stopping, ttl) + if err != nil { + return err + } + + server := &http.Server{ + Addr: net.JoinHostPort(host, port), + Handler: handler, + ReadHeaderTimeout: 5 * time.Second, + ReadTimeout: 10 * time.Second, + WriteTimeout: 10 * time.Second, + IdleTimeout: 60 * time.Second, + } + + ctx, stop := signal.NotifyContext( + context.Background(), + os.Interrupt, + syscall.SIGTERM, + ) + defer stop() + + serverErrors := make(chan error, 1) + + go func() { + log.Printf("server starting address=%s", server.Addr) + serverErrors <- server.ListenAndServe() + }() + + select { + case err := <-serverErrors: + if errors.Is(err, http.ErrServerClosed) { + return nil + } + return err + + case <-ctx.Done(): + stopping.Store(true) + log.Print("shutdown started timeout=8s") + } + + started := time.Now() + + shutdownCtx, cancel := context.WithTimeout( + context.Background(), + 8*time.Second, + ) + defer cancel() + + if err := server.Shutdown(shutdownCtx); err != nil { + _ = server.Close() + return fmt.Errorf("shutdown forced: %w", err) + } + + log.Printf( + "shutdown completed duration_ms=%d", + time.Since(started).Milliseconds(), + ) + + return nil +} + +func healthcheck() error { + host := envOrDefault("APP_HOST", "0.0.0.0") + port := envOrDefault("APP_PORT", "8080") + + switch host { + case "0.0.0.0", "": + host = "127.0.0.1" + case "::": + host = "::1" + } + + client := &http.Client{ + Timeout: 2 * time.Second, + } + + url := "http://" + net.JoinHostPort(host, port) + "/health/ready" + + response, err := client.Get(url) + if err != nil { + return fmt.Errorf("healthcheck: %w", err) + } + defer response.Body.Close() + + if response.StatusCode != http.StatusOK { + return fmt.Errorf("healthcheck: status=%d", response.StatusCode) + } + if len(os.Args) == 2 && os.Args[1] == "instance-id" { + id := response.Header.Get("X-Instance-Id") + if id == "" { + return errors.New("missing X-Instance-Id") + } + fmt.Println(id) + } + + return nil +} + +func envOrDefault(name string, fallback string) string { + if value := os.Getenv(name); value != "" { + return value + } + return fallback +} diff --git a/compose.yaml b/compose.yaml new file mode 100644 index 00000000..05ab694e --- /dev/null +++ b/compose.yaml @@ -0,0 +1,91 @@ +name: messenger-lab4 + +services: + api: + build: . + scale: 2 + environment: + SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600} + DATABASE_PASSWORD_FILE: /run/secrets/postgres_password + REDIS_ADDR: redis:6379 + secrets: [postgres_password] + cpus: 1.0 + mem_limit: 384m + stop_grace_period: 15s + depends_on: + postgres: + condition: service_healthy + migrate: + condition: service_completed_successfully + redis: + condition: service_started + + lb: + image: haproxy:3.2.4-alpine + ports: + - "127.0.0.1:${LB_PORT:-8084}:8080" + volumes: + - ./infra/haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro + cpus: 0.5 + mem_limit: 64m + depends_on: + api: + condition: service_healthy + + postgres: + image: postgres:17.9-bookworm + environment: + POSTGRES_DB: messenger + POSTGRES_USER: messenger + POSTGRES_PASSWORD_FILE: /run/secrets/postgres_password + POSTGRES_INITDB_ARGS: --encoding=UTF8 + secrets: [postgres_password] + volumes: + - postgres_lab4_data_v1:/var/lib/postgresql/data + cpus: 1.0 + mem_limit: 512m + healthcheck: + test: [CMD-SHELL, "pg_isready -U messenger -d messenger"] + interval: 3s + timeout: 3s + retries: 20 + start_period: 10s + stop_grace_period: 30s + + redis: + image: redis:7.4.11-alpine + command: [redis-server, --save, "", --appendonly, "no", --maxmemory, 64mb, --maxmemory-policy, allkeys-lru] + tmpfs: [/data] + cpus: 0.25 + mem_limit: 128m + healthcheck: + test: [CMD, redis-cli, ping] + interval: 3s + timeout: 2s + retries: 10 + + migrate: + image: postgres:17.9-bookworm + environment: + PGHOST: postgres + PGUSER: messenger + PGDATABASE: messenger + PGCONNECT_TIMEOUT: "5" + secrets: [postgres_password] + volumes: + - ./migrations:/migrations:ro + entrypoint: [/bin/sh, -ec] + command: + - 'export PGPASSWORD="$$(cat /run/secrets/postgres_password)"; exec psql -X -f /migrations/apply.psql' + cpus: 0.5 + mem_limit: 128m + depends_on: + postgres: + condition: service_healthy + +secrets: + postgres_password: + file: ./secrets/postgres_password.txt + +volumes: + postgres_lab4_data_v1: diff --git a/evidence/transfer-checks.txt b/evidence/transfer-checks.txt new file mode 100644 index 00000000..6ca6ce1c --- /dev/null +++ b/evidence/transfer-checks.txt @@ -0,0 +1,18 @@ +Дата: 2026-11-06 +Этап: перенос основы lab3 в lab4; S3 и вложения пока не реализованы. + +Команда: go test ./... +Результат: PASS; httpapi, password, service, store — ok; остальные пакеты без тестов. +Первый запуск в песочнице: HTTP-тесты получили отказ подключения к localhost. +Повторный запуск вне песочницы: exit code 0. + +Команда: go vet ./... +Результат: exit code 0, замечаний нет. + +Команда: C:/Users/homur/.cache/codex-runtimes/codex-primary-runtime/dependencies/python/python.exe -X utf8 scripts/check_contract.py +Результат: PASS: offline skeleton structure, local refs and Python syntax; application NOT tested. + +Команда: docker compose --env-file .env.example config --quiet +Результат: exit code 0, замечаний нет. Для проверки использован пример переменных; локальные secrets не создавались. + +Стенд не запускался. Публичный smoke lab4, S3, сохранность и failover lab4 не проверялись. \ No newline at end of file diff --git a/go.mod b/go.mod new file mode 100644 index 00000000..8eef8f98 --- /dev/null +++ b/go.mod @@ -0,0 +1,20 @@ +module gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork + +go 1.26.3 + +require ( + github.com/jackc/pgx/v5 v5.7.6 + github.com/redis/go-redis/v9 v9.7.3 + golang.org/x/crypto v0.37.0 +) + +require ( + github.com/cespare/xxhash/v2 v2.2.0 // indirect + github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect + github.com/jackc/pgpassfile v1.0.0 // indirect + github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect + github.com/jackc/puddle/v2 v2.2.2 // indirect + golang.org/x/sync v0.13.0 // indirect + golang.org/x/sys v0.32.0 // indirect + golang.org/x/text v0.24.0 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 00000000..daab91e8 --- /dev/null +++ b/go.sum @@ -0,0 +1,40 @@ +github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs= +github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c= +github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA= +github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0= +github.com/cespare/xxhash/v2 v2.2.0 h1:DC2CZ1Ep5Y4k3ZQ899DldepgrayRUGE6BBZ/cd9Cj44= +github.com/cespare/xxhash/v2 v2.2.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78= +github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc= +github.com/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.6 h1:rWQc5FwZSPX58r1OQmkuaNicxdmExaEz5A2DO2hUuTk= +github.com/jackc/pgx/v5 v5.7.6/go.mod h1:aruU7o91Tc2q2cFp5h4uP3f6ztExVpyVv88Xl/8Vl8M= +github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo= +github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/redis/go-redis/v9 v9.7.3 h1:YpPyAayJV+XErNsatSElgRZZVCwXX9QzkKYNvO7x0wM= +github.com/redis/go-redis/v9 v9.7.3/go.mod h1:bGUrSggJ9X9GUmZpZNEOQKaANxSGgOEBRltRTZHSvrA= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk= +github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= +golang.org/x/crypto v0.37.0 h1:kJNSjF/Xp7kU0iB2Z+9viTPMW4EqqsrywMXLJOOsXSE= +golang.org/x/crypto v0.37.0/go.mod h1:vg+k43peMZ0pUMhYmVAWysMK35e6ioLh3wB8ZCAfbVc= +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.32.0 h1:s77OFDvIQeibCmezSnk/q6iAfkdiQaJi4VzroCFrN20= +golang.org/x/sys v0.32.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= +golang.org/x/text v0.24.0 h1:dd5Bzh4yt5KYA8f9CJHCP4FB4D51c2c6JvN37xJJkJ0= +golang.org/x/text v0.24.0/go.mod h1:L8rBsPeo2pSS+xqN0d5u2ikmjtmoJbDBT1b7nHvFCdU= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/infra/haproxy.cfg b/infra/haproxy.cfg new file mode 100644 index 00000000..51d9294a --- /dev/null +++ b/infra/haproxy.cfg @@ -0,0 +1,35 @@ +global + log stdout format raw local0 + maxconn 512 + +defaults + log global + mode http + option httplog + timeout connect 1s + timeout client 15s + timeout server 12s + timeout check 1s + retries 0 + +resolvers docker + nameserver dns 127.0.0.11:53 + resolve_retries 3 + timeout resolve 1s + timeout retry 1s + hold valid 1s + hold obsolete 1s + hold nx 1s + hold timeout 1s + hold refused 1s + +frontend public + bind :8080 + default_backend api + +backend api + balance roundrobin + option httpchk + http-check send meth GET uri /health/ready ver HTTP/1.1 hdr Host api + http-check expect status 200 + server-template replica 10 api:8080 check inter 1s fall 2 rise 2 resolvers docker resolve-prefer ipv4 init-addr none diff --git a/internal/cache/profiles.go b/internal/cache/profiles.go new file mode 100644 index 00000000..a540318b --- /dev/null +++ b/internal/cache/profiles.go @@ -0,0 +1,56 @@ +package cache + +import ( + "context" + "encoding/json" + "time" + + "gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/model" + "github.com/redis/go-redis/v9" +) + +const ProfileTTL = 60 * time.Second + +type Profiles struct{ client *redis.Client } + +func NewProfiles(address string) *Profiles { + return &Profiles{client: redis.NewClient(&redis.Options{ + Addr: address, + Protocol: 2, + MaxRetries: -1, + DialTimeout: 200 * time.Millisecond, + ReadTimeout: 200 * time.Millisecond, + WriteTimeout: 200 * time.Millisecond, + PoolTimeout: 200 * time.Millisecond, + ContextTimeoutEnabled: true, + PoolSize: 10, + MaxActiveConns: 10, + MinIdleConns: 0, + })} +} + +func (p *Profiles) Close() error { return p.client.Close() } + +func (p *Profiles) Get(ctx context.Context, id string) (model.User, bool) { + ctx, cancel := context.WithTimeout(ctx, 250*time.Millisecond) + defer cancel() + raw, err := p.client.Get(ctx, "profile:v1:"+id).Bytes() + if err != nil { + return model.User{}, false + } + var user model.User + if json.Unmarshal(raw, &user) != nil || user.ID != id || user.Username == "" || user.DisplayName == "" || user.CreatedAt.IsZero() { + return model.User{}, false + } + return user, true +} + +func (p *Profiles) Set(ctx context.Context, user model.User) { + raw, err := json.Marshal(user) + if err != nil { + return + } + ctx, cancel := context.WithTimeout(ctx, 250*time.Millisecond) + defer cancel() + _ = p.client.Set(ctx, "profile:v1:"+user.ID, raw, ProfileTTL).Err() +} diff --git a/internal/httpapi/auth.go b/internal/httpapi/auth.go new file mode 100644 index 00000000..4cf0fb80 --- /dev/null +++ b/internal/httpapi/auth.go @@ -0,0 +1,27 @@ +package httpapi + +import ( + "context" + "net/http" + + "gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/model" +) + +type userContextKey struct{} + +func (api *API) authenticate(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + user, err := api.messenger.CurrentUser(r.Header.Get("X-User-Id")) + if err != nil { + writeAppError(w, err) + return + } + + ctx := context.WithValue(r.Context(), userContextKey{}, user) + next.ServeHTTP(w, r.WithContext(ctx)) + }) +} + +func userFromContext(ctx context.Context) model.User { + return ctx.Value(userContextKey{}).(model.User) +} diff --git a/internal/httpapi/chats.go b/internal/httpapi/chats.go new file mode 100644 index 00000000..3c83ce82 --- /dev/null +++ b/internal/httpapi/chats.go @@ -0,0 +1,169 @@ +package httpapi + +import ( + "net/http" + "strconv" + "strings" + + "gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/service" +) + +type createChatRequest struct { + Title string `json:"title"` + MemberIDs []string `json:"member_ids"` +} + +type createMessageRequest struct { + Text string `json:"text"` +} + +func (api *API) chatRoutes(w http.ResponseWriter, r *http.Request) { + actor := userFromContext(r.Context()) + + if r.URL.Path == "/api/v1/chats" { + switch r.Method { + case http.MethodPost: + var body createChatRequest + if !readJSON(w, r, &body, "title", "member_ids") { + return + } + + chat, err := api.messenger.CreateChat( + actor.ID, body.Title, body.MemberIDs, + ) + if err != nil { + writeAppError(w, err) + return + } + + writeJSON(w, http.StatusCreated, chat) + + case http.MethodGet: + limit, cursor, ok := pageParams(w, r) + if !ok { + return + } + + page, err := api.messenger.ListChats(actor.ID, limit, cursor) + if err != nil { + writeAppError(w, err) + return + } + + writeJSON(w, http.StatusOK, page) + + default: + requireMethod(w, r, "GET, POST") + } + return + } + + path := strings.TrimPrefix(r.URL.Path, "/api/v1/chats/") + parts := strings.Split(path, "/") + + if len(parts) == 1 && parts[0] != "" { + if !requireMethod(w, r, http.MethodGet) { + return + } + + chat, err := api.messenger.GetChat(actor.ID, parts[0]) + if err != nil { + writeAppError(w, err) + return + } + + writeJSON(w, http.StatusOK, chat) + return + } + + if len(parts) != 2 || parts[0] == "" || parts[1] != "messages" { + writeError(w, http.StatusNotFound, "not_found", "Resource not found") + return + } + + chat, err := api.messenger.GetChat(actor.ID, parts[0]) + if err != nil { + writeAppError(w, err) + return + } + + switch r.Method { + case http.MethodPost: + var body createMessageRequest + if !readJSON(w, r, &body, "text") { + return + } + + message, err := api.messenger.CreateMessage( + actor.ID, chat.ID, body.Text, + ) + if err != nil { + writeAppError(w, err) + return + } + + writeJSON(w, http.StatusCreated, message) + + case http.MethodGet: + limit, cursor, ok := pageParams(w, r) + if !ok { + return + } + + page, err := api.messenger.ListMessages( + actor.ID, chat.ID, limit, cursor, + ) + if err != nil { + writeAppError(w, err) + return + } + + writeJSON(w, http.StatusOK, page) + + default: + requireMethod(w, r, "GET, POST") + } +} + +func pageParams( + w http.ResponseWriter, + r *http.Request, +) (int, string, bool) { + invalid := func() (int, string, bool) { + writeAppError(w, service.ErrInvalidRequest) + return 0, "", false + } + + query := r.URL.Query() + limit := 50 + + if values, exists := query["limit"]; exists { + if len(values) != 1 || values[0] == "" { + return invalid() + } + + for _, char := range values[0] { + if char < '0' || char > '9' { + return invalid() + } + } + + value, err := strconv.Atoi(values[0]) + if err != nil || value < 1 || value > 100 { + return invalid() + } + + limit = value + } + + cursor := "" + + if values, exists := query["cursor"]; exists { + if len(values) != 1 || values[0] == "" { + return invalid() + } + cursor = values[0] + } + + return limit, cursor, true +} diff --git a/internal/httpapi/chats_test.go b/internal/httpapi/chats_test.go new file mode 100644 index 00000000..52504f83 --- /dev/null +++ b/internal/httpapi/chats_test.go @@ -0,0 +1,502 @@ +package httpapi_test + +import ( + "bytes" + "encoding/json" + "fmt" + "io" + "net/http" + "net/http/httptest" + "net/url" + "sync" + "testing" + "time" + + "gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/model" + "gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/service" +) + +type chatTestClient struct { + base string + client *http.Client +} + +func newChatTestClient(t *testing.T) *chatTestClient { + t.Helper() + + server := httptest.NewServer(newAPI()) + t.Cleanup(server.Close) + + client := server.Client() + client.Timeout = 10 * time.Second + + return &chatTestClient{ + base: server.URL, + client: client, + } +} + +func (c *chatTestClient) call( + method string, + path string, + actorID string, + body any, + wantStatus int, + result any, +) error { + var encoded []byte + var err error + + if body != nil { + encoded, err = json.Marshal(body) + if err != nil { + return err + } + } + + req, err := http.NewRequest( + method, + c.base+path, + bytes.NewReader(encoded), + ) + if err != nil { + return err + } + + if body != nil { + req.Header.Set("Content-Type", "application/json") + } + if actorID != "" { + req.Header.Set("X-User-Id", actorID) + } + + response, err := c.client.Do(req) + if err != nil { + return err + } + defer response.Body.Close() + + data, err := io.ReadAll(response.Body) + if err != nil { + return err + } + + if response.StatusCode != wantStatus { + return fmt.Errorf( + "%s %s: status=%d, want=%d, body=%s", + method, path, response.StatusCode, wantStatus, data, + ) + } + + requestID := response.Header.Get("X-Request-Id") + if requestID == "" { + return fmt.Errorf("%s %s: missing request ID", method, path) + } + + if wantStatus >= 400 { + var problem struct { + Error struct { + Code string `json:"code"` + RequestID string `json:"request_id"` + } `json:"error"` + } + + if err := json.Unmarshal(data, &problem); err != nil { + return err + } + + if problem.Error.Code == "" || + problem.Error.RequestID != requestID { + return fmt.Errorf("invalid error response: %s", data) + } + } + + if result != nil { + return json.Unmarshal(data, result) + } + + return nil +} + +func mustCall( + t *testing.T, + c *chatTestClient, + method string, + path string, + actorID string, + body any, + status int, + result any, +) { + t.Helper() + + if err := c.call(method, path, actorID, body, status, result); err != nil { + t.Fatal(err) + } +} + +func createTestUser( + t *testing.T, + c *chatTestClient, + username string, +) model.User { + t.Helper() + + var user model.User + mustCall( + t, c, http.MethodPost, "/api/v1/users", "", + map[string]any{ + "username": username, + "display_name": username, + }, + http.StatusCreated, &user, + ) + + return user +} + +func createTestChat( + t *testing.T, + c *chatTestClient, + actorID string, + members []string, +) model.Chat { + t.Helper() + + var chat model.Chat + mustCall( + t, c, http.MethodPost, "/api/v1/chats", actorID, + map[string]any{ + "title": "Test chat", + "member_ids": members, + }, + http.StatusCreated, &chat, + ) + + return chat +} + +func readAllMessages( + t *testing.T, + c *chatTestClient, + actorID string, + chatID string, + limit int, +) ([]model.Message, int) { + t.Helper() + + var messages []model.Message + cursor := "" + pages := 0 + seenCursors := make(map[string]bool) + + for { + path := fmt.Sprintf( + "/api/v1/chats/%s/messages?limit=%d", + chatID, limit, + ) + + if cursor != "" { + path += "&cursor=" + url.QueryEscape(cursor) + } + + var page service.Page[model.Message] + mustCall( + t, c, http.MethodGet, path, actorID, + nil, http.StatusOK, &page, + ) + + pages++ + + if page.Items == nil { + t.Fatal("items must be an array, not null") + } + if len(page.Items) > limit { + t.Fatal("page exceeds requested limit") + } + + messages = append(messages, page.Items...) + + if page.NextCursor == nil { + break + } + + cursor = *page.NextCursor + if cursor == "" || seenCursors[cursor] || pages > 100 { + t.Fatal("invalid or repeating pagination cursor") + } + seenCursors[cursor] = true + } + + return messages, pages +} + +func TestChatAccessAndValidation(t *testing.T) { + c := newChatTestClient(t) + + alice := createTestUser(t, c, "alice") + bob := createTestUser(t, c, "bob") + eve := createTestUser(t, c, "eve") + + chat := createTestChat( + t, c, alice.ID, []string{alice.ID, bob.ID}, + ) + path := "/api/v1/chats/" + chat.ID + + mustCall( + t, c, http.MethodGet, path, eve.ID, + nil, http.StatusNotFound, nil, + ) + mustCall( + t, c, http.MethodGet, path+"/messages", eve.ID, + nil, http.StatusNotFound, nil, + ) + mustCall( + t, c, http.MethodPost, path+"/messages", eve.ID, + map[string]any{"text": "not allowed"}, + http.StatusNotFound, nil, + ) + + var hidden service.Page[model.Chat] + mustCall( + t, c, http.MethodGet, "/api/v1/chats", eve.ID, + nil, http.StatusOK, &hidden, + ) + if len(hidden.Items) != 0 { + t.Fatal("outsider sees a private chat") + } + + for _, text := range []string{"", " \t\n"} { + mustCall( + t, c, http.MethodPost, path+"/messages", alice.ID, + map[string]any{"text": text}, + http.StatusBadRequest, nil, + ) + } + + mustCall( + t, c, http.MethodPost, path+"/messages", alice.ID, + map[string]any{ + "text": "hello", + "sender_id": bob.ID, + }, + http.StatusBadRequest, nil, + ) + + for _, members := range [][]string{ + {alice.ID, alice.ID}, + {bob.ID}, + {alice.ID, "00000000-0000-4000-8000-000000000000"}, + } { + mustCall( + t, c, http.MethodPost, "/api/v1/chats", alice.ID, + map[string]any{ + "title": "Invalid chat", + "member_ids": members, + }, + http.StatusBadRequest, nil, + ) + } + + var chats service.Page[model.Chat] + mustCall( + t, c, http.MethodGet, "/api/v1/chats", alice.ID, + nil, http.StatusOK, &chats, + ) + if len(chats.Items) != 1 { + t.Fatalf("expected one chat, got %d", len(chats.Items)) + } + + messages, _ := readAllMessages(t, c, alice.ID, chat.ID, 10) + if len(messages) != 0 { + t.Fatal("rejected messages were saved") + } +} + +func TestMessagePagination(t *testing.T) { + c := newChatTestClient(t) + alice := createTestUser(t, c, "alice") + + chat := createTestChat(t, c, alice.ID, []string{alice.ID}) + other := createTestChat(t, c, alice.ID, []string{alice.ID}) + path := "/api/v1/chats/" + chat.ID + "/messages" + + var sent []model.Message + + for i := 0; i < 7; i++ { + var message model.Message + mustCall( + t, c, http.MethodPost, path, alice.ID, + map[string]any{"text": fmt.Sprintf("Сообщение %d 👋", i)}, + http.StatusCreated, &message, + ) + sent = append(sent, message) + } + + got, pages := readAllMessages(t, c, alice.ID, chat.ID, 2) + + if len(got) != len(sent) || pages != 4 { + t.Fatalf("got %d messages on %d pages", len(got), pages) + } + + for i := range sent { + if got[i] != sent[i] { + t.Fatalf("message %d differs or is out of order", i) + } + } + + var first service.Page[model.Message] + mustCall( + t, c, http.MethodGet, path+"?limit=2", alice.ID, + nil, http.StatusOK, &first, + ) + + if first.NextCursor == nil { + t.Fatal("expected next cursor") + } + + cursor := url.QueryEscape(*first.NextCursor) + + var next service.Page[model.Message] + mustCall( + t, c, http.MethodGet, + path+"?limit=3&cursor="+cursor, alice.ID, + nil, http.StatusOK, &next, + ) + + if len(next.Items) != 3 || next.Items[0].ID != sent[2].ID { + t.Fatal("changing page size lost or repeated a message") + } + + mustCall( + t, c, http.MethodGet, + "/api/v1/chats/"+other.ID+"/messages?cursor="+cursor, + alice.ID, nil, http.StatusBadRequest, nil, + ) + + for _, query := range []string{ + "limit=0", + "limit=101", + "limit=abc", + "cursor=invalid", + } { + mustCall( + t, c, http.MethodGet, path+"?"+query, alice.ID, + nil, http.StatusBadRequest, nil, + ) + } +} + +func TestConcurrentMessages100From10Clients(t *testing.T) { + c := newChatTestClient(t) + + const clients = 10 + const messagesPerClient = 10 + const total = clients * messagesPerClient + + users := make([]model.User, clients) + memberIDs := make([]string, clients) + + for i := range users { + users[i] = createTestUser(t, c, fmt.Sprintf("user_%02d", i)) + memberIDs[i] = users[i].ID + } + + chat := createTestChat(t, c, users[0].ID, memberIDs) + path := "/api/v1/chats/" + chat.ID + "/messages" + + type outcome struct { + message model.Message + err error + } + + results := make(chan outcome, total) + start := make(chan struct{}) + var wg sync.WaitGroup + + for clientIndex := 0; clientIndex < clients; clientIndex++ { + wg.Add(1) + + go func(index int) { + defer wg.Done() + <-start + + for j := 0; j < messagesPerClient; j++ { + text := fmt.Sprintf("client-%d-message-%d", index, j) + var message model.Message + + err := c.call( + http.MethodPost, + path, + users[index].ID, + map[string]any{"text": text}, + http.StatusCreated, + &message, + ) + + if err == nil && + (message.SenderID != users[index].ID || + message.Text != text || + message.ChatID != chat.ID) { + err = fmt.Errorf("incorrect message response") + } + + results <- outcome{message: message, err: err} + } + }(clientIndex) + } + + close(start) + wg.Wait() + close(results) + + expected := make(map[string]model.Message, total) + + for result := range results { + if result.err != nil { + t.Errorf("send failed: %v", result.err) + continue + } + + if _, exists := expected[result.message.ID]; exists { + t.Errorf("duplicate response ID: %s", result.message.ID) + } + + expected[result.message.ID] = result.message + } + + if t.Failed() { + t.FailNow() + } + + if len(expected) != total { + t.Fatalf("expected %d unique responses, got %d", total, len(expected)) + } + + history, pages := readAllMessages( + t, c, users[0].ID, chat.ID, 17, + ) + + if len(history) != total { + t.Fatalf("expected %d stored messages, got %d", total, len(history)) + } + + seen := make(map[string]bool, total) + + for _, message := range history { + if seen[message.ID] { + t.Fatalf("duplicate history ID: %s", message.ID) + } + seen[message.ID] = true + + want, exists := expected[message.ID] + if !exists || want != message { + t.Fatalf("missing or changed message: %s", message.ID) + } + } + + t.Logf( + "clients=%d sent=%d unique_responses=%d stored=%d unique_stored=%d pages=%d", + clients, total, len(expected), len(history), len(seen), pages, + ) +} diff --git a/internal/httpapi/errors.go b/internal/httpapi/errors.go new file mode 100644 index 00000000..88a4b9bb --- /dev/null +++ b/internal/httpapi/errors.go @@ -0,0 +1,87 @@ +package httpapi + +import ( + "errors" + "log" + "net/http" + + "gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/service" + "gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/store" +) + +type errorResponse struct { + Error errorDetails `json:"error"` +} + +type errorDetails struct { + Code string `json:"code"` + Message string `json:"message"` + RequestID string `json:"request_id"` +} + +func writeAppError(w http.ResponseWriter, err error) { + switch { + case errors.Is(err, store.ErrIdempotencyConflict): + writeError(w, http.StatusConflict, "conflict", "Idempotency key already used for another message") + + case errors.Is(err, store.ErrUnavailable): + writeError(w, http.StatusServiceUnavailable, "unavailable", "Service temporarily unavailable") + + case errors.Is(err, service.ErrInvalidRequest): + writeError( + w, http.StatusBadRequest, + "invalid_request", "Invalid request fields", + ) + + case errors.Is(err, service.ErrUnauthorized): + writeError( + w, http.StatusUnauthorized, + "unauthorized", "Valid X-User-Id is required", + ) + + case errors.Is(err, store.ErrUsernameTaken): + writeError( + w, http.StatusConflict, + "conflict", "Username already exists", + ) + + case errors.Is(err, store.ErrInvalidMembers): + writeError( + w, http.StatusBadRequest, + "invalid_request", "Invalid chat members", + ) + + case errors.Is(err, store.ErrNotFound): + writeError( + w, http.StatusNotFound, + "not_found", "Resource not found", + ) + + default: + log.Printf( + "internal error request_id=%s: %v", + w.Header().Get("X-Request-Id"), + err, + ) + + writeError( + w, http.StatusInternalServerError, + "internal_error", "Internal server error", + ) + } +} + +func writeError( + w http.ResponseWriter, + status int, + code string, + message string, +) { + writeJSON(w, status, errorResponse{ + Error: errorDetails{ + Code: code, + Message: message, + RequestID: w.Header().Get("X-Request-Id"), + }, + }) +} diff --git a/internal/httpapi/health.go b/internal/httpapi/health.go new file mode 100644 index 00000000..f3a4fb21 --- /dev/null +++ b/internal/httpapi/health.go @@ -0,0 +1,23 @@ +package httpapi + +import "net/http" + +func handleHealth(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodGet { + w.Header().Set("Allow", http.MethodGet) + + writeError( + w, + http.StatusMethodNotAllowed, + "invalid_request", + "Method not allowed", + ) + return + } + + writeJSON(w, http.StatusOK, struct { + Status string `json:"status"` + }{ + Status: "ok", + }) +} diff --git a/internal/httpapi/instance_test.go b/internal/httpapi/instance_test.go new file mode 100644 index 00000000..a4a340c7 --- /dev/null +++ b/internal/httpapi/instance_test.go @@ -0,0 +1,48 @@ +package httpapi_test + +import ( + "net/http" + "sync/atomic" + "testing" + + "gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/httpapi" + "gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/store" +) + +func TestInstanceIDOnResponses(t *testing.T) { + var stopping atomic.Bool + handler, err := httpapi.NewPostgresHandler(&store.PostgresStore{}, &stopping, 3600) + if err != nil { + t.Fatal(err) + } + var instanceID string + for _, tc := range []struct { + path string + stopping bool + status int + }{ + {"/health/live", false, http.StatusOK}, + {"/missing", false, http.StatusNotFound}, + {"/api/v1/chats", false, http.StatusUnauthorized}, + {"/health/ready", true, http.StatusServiceUnavailable}, + {"/health/live", true, http.StatusOK}, + } { + stopping.Store(tc.stopping) + response := request(handler, http.MethodGet, tc.path, "", "") + if response.Code != tc.status { + t.Fatalf("%s: status=%d, want %d", tc.path, response.Code, tc.status) + } + got := response.Header().Get("X-Instance-Id") + if got == "" { + t.Fatal("missing X-Instance-Id") + } + if instanceID != "" && got != instanceID { + t.Fatalf("instance changed: %q -> %q", instanceID, got) + } + instanceID = got + } + response := request(newAPI(), http.MethodGet, "/health/live", "", "") + if got := response.Header().Get("X-Instance-Id"); got != instanceID { + t.Fatalf("different handlers in one process: %q != %q", got, instanceID) + } +} diff --git a/internal/httpapi/json.go b/internal/httpapi/json.go new file mode 100644 index 00000000..6d9900bf --- /dev/null +++ b/internal/httpapi/json.go @@ -0,0 +1,100 @@ +package httpapi + +import ( + "bytes" + "encoding/json" + "io" + "log" + "mime" + "net/http" + "slices" + "unicode/utf8" +) + +const maxJSONBody = 1 << 20 // 1 MiB + +func readJSON( + w http.ResponseWriter, + r *http.Request, + dst any, + requiredFields ...string, +) bool { + mediaType, _, err := mime.ParseMediaType(r.Header.Get("Content-Type")) + if err != nil || mediaType != "application/json" { + writeError( + w, + http.StatusUnsupportedMediaType, + "unsupported_media_type", + "Content-Type must be application/json", + ) + return false + } + + defer r.Body.Close() + + body, err := io.ReadAll(io.LimitReader(r.Body, maxJSONBody+1)) + if err != nil { + writeError(w, http.StatusBadRequest, "invalid_request", "Cannot read body") + return false + } + + if len(body) > maxJSONBody { + writeError( + w, + http.StatusRequestEntityTooLarge, + "payload_too_large", + "JSON body is too large", + ) + return false + } + + invalid := func() bool { + writeError( + w, + http.StatusBadRequest, + "invalid_request", + "Invalid JSON body", + ) + return false + } + + if !utf8.Valid(body) { + return invalid() + } + + var fields map[string]json.RawMessage + if err := json.Unmarshal(body, &fields); err != nil || fields == nil { + return invalid() + } + + for name := range fields { + if !slices.Contains(requiredFields, name) { + return invalid() + } + } + + for _, name := range requiredFields { + value, exists := fields[name] + if !exists || bytes.Equal(bytes.TrimSpace(value), []byte("null")) { + return invalid() + } + } + + decoder := json.NewDecoder(bytes.NewReader(body)) + decoder.DisallowUnknownFields() + + if err := decoder.Decode(dst); err != nil { + return invalid() + } + + return true +} + +func writeJSON(w http.ResponseWriter, status int, body any) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(status) + + if err := json.NewEncoder(w).Encode(body); err != nil { + log.Printf("cannot write JSON response: %v", err) + } +} diff --git a/internal/httpapi/json_test.go b/internal/httpapi/json_test.go new file mode 100644 index 00000000..f6d20f0a --- /dev/null +++ b/internal/httpapi/json_test.go @@ -0,0 +1,99 @@ +package httpapi_test + +import ( + "encoding/json" + "fmt" + "net/http" + "testing" + + "gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/model" + "gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/service" +) + +func TestJSONFieldNamesAreCaseSensitive(t *testing.T) { + handler := newAPI() + + t.Run("registration", func(t *testing.T) { + for _, body := range []string{ + `{"username":"alice","display_name":"Original","Display_Name":"Changed"}`, + `{"Display_Name":"Changed","username":"alice","display_name":"Original"}`, + `{"username":"alice","display_name":"Original","Username":"bob"}`, + `{"username":"alice","Display_Name":"Changed"}`, + } { + checkError(t, request(handler, http.MethodPost, "/api/v1/users", body, ""), + http.StatusBadRequest, "invalid_request") + } + }) + + created := request(handler, http.MethodPost, "/api/v1/users", + `{"username":"alice","display_name":"Original"}`, "") + if created.Code != http.StatusCreated { + t.Fatalf("valid registration: %d %s", created.Code, created.Body.String()) + } + var user model.User + if err := json.Unmarshal(created.Body.Bytes(), &user); err != nil { + t.Fatal(err) + } + if user.DisplayName != "Original" { + t.Fatalf("display name changed: %q", user.DisplayName) + } + + t.Run("chat", func(t *testing.T) { + for _, body := range []string{ + fmt.Sprintf(`{"title":"Original","Title":"Changed","member_ids":[%q]}`, user.ID), + fmt.Sprintf(`{"Title":"Changed","title":"Original","member_ids":[%q]}`, user.ID), + fmt.Sprintf(`{"title":"Original","member_ids":[%q],"Member_Ids":[]}`, user.ID), + fmt.Sprintf(`{"Title":"Changed","member_ids":[%q]}`, user.ID), + } { + checkError(t, request(handler, http.MethodPost, "/api/v1/chats", body, user.ID), + http.StatusBadRequest, "invalid_request") + } + response := request(handler, http.MethodGet, "/api/v1/chats", "", user.ID) + var page service.Page[model.Chat] + if err := json.Unmarshal(response.Body.Bytes(), &page); err != nil { + t.Fatal(err) + } + if response.Code != http.StatusOK || len(page.Items) != 0 { + t.Fatalf("rejected chats were saved: %d %s", response.Code, response.Body.String()) + } + }) + + created = request(handler, http.MethodPost, "/api/v1/chats", + fmt.Sprintf(`{"title":"Original","member_ids":[%q]}`, user.ID), user.ID) + if created.Code != http.StatusCreated { + t.Fatalf("valid chat: %d %s", created.Code, created.Body.String()) + } + var chat model.Chat + if err := json.Unmarshal(created.Body.Bytes(), &chat); err != nil { + t.Fatal(err) + } + path := "/api/v1/chats/" + chat.ID + "/messages" + + t.Run("message", func(t *testing.T) { + for _, body := range []string{ + `{"text":"Original","Text":"Changed"}`, + `{"Text":"Changed","text":"Original"}`, + `{"text":"Original","TEXT":"Changed"}`, + `{"Text":"Changed"}`, + } { + checkError(t, request(handler, http.MethodPost, path, body, user.ID), + http.StatusBadRequest, "invalid_request") + } + response := request(handler, http.MethodGet, path, "", user.ID) + var page service.Page[model.Message] + if err := json.Unmarshal(response.Body.Bytes(), &page); err != nil { + t.Fatal(err) + } + if response.Code != http.StatusOK || len(page.Items) != 0 { + t.Fatalf("rejected messages were saved: %d %s", response.Code, response.Body.String()) + } + response = request(handler, http.MethodPost, path, `{"text":"Original"}`, user.ID) + var message model.Message + if err := json.Unmarshal(response.Body.Bytes(), &message); err != nil { + t.Fatal(err) + } + if response.Code != http.StatusCreated || message.Text != "Original" { + t.Fatalf("valid message: %d %s", response.Code, response.Body.String()) + } + }) +} diff --git a/internal/httpapi/middleware.go b/internal/httpapi/middleware.go new file mode 100644 index 00000000..a3f626a0 --- /dev/null +++ b/internal/httpapi/middleware.go @@ -0,0 +1,102 @@ +package httpapi + +import ( + "crypto/rand" + "encoding/hex" + "log" + "net/http" + "time" +) + +var processInstanceID = rand.Text() + +func withInstanceID(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("X-Instance-Id", processInstanceID) + next.ServeHTTP(w, r) + }) +} + +func withRequestID(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var randomBytes [16]byte + + if _, err := rand.Read(randomBytes[:]); err != nil { + panic("cannot generate request ID") + } + + requestID := hex.EncodeToString(randomBytes[:]) + w.Header().Set("X-Request-Id", requestID) + + next.ServeHTTP(w, r) + }) +} + +type statusWriter struct { + http.ResponseWriter + status int +} + +func (w *statusWriter) WriteHeader(status int) { + if w.status != 0 { + return + } + + w.status = status + w.ResponseWriter.WriteHeader(status) +} + +func (w *statusWriter) Write(body []byte) (int, error) { + if w.status == 0 { + w.WriteHeader(http.StatusOK) + } + + return w.ResponseWriter.Write(body) +} + +func (w *statusWriter) Unwrap() http.ResponseWriter { + return w.ResponseWriter +} + +func withAccessLog(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + started := time.Now() + writer := &statusWriter{ResponseWriter: w} + + defer func() { + if recovered := recover(); recovered != nil { + log.Printf( + "handler panic request_id=%s", + writer.Header().Get("X-Request-Id"), + ) + + if writer.status == 0 { + writeError( + writer, + http.StatusInternalServerError, + "internal_error", + "Internal server error", + ) + } else { + panic(http.ErrAbortHandler) + } + } + + status := writer.status + if status == 0 { + status = http.StatusOK + } + + log.Printf( + "request_id=%s method=%s path=%q status=%d duration_ms=%d", + writer.Header().Get("X-Request-Id"), + r.Method, + r.URL.Path, + status, + time.Since(started).Milliseconds(), + ) + }() + + next.ServeHTTP(writer, r) + }) +} diff --git a/internal/httpapi/postgres.go b/internal/httpapi/postgres.go new file mode 100644 index 00000000..1cf2eb30 --- /dev/null +++ b/internal/httpapi/postgres.go @@ -0,0 +1,80 @@ +package httpapi + +import ( + "context" + "net/http" + "strings" + "sync/atomic" + + "gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/service" + "gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/store" +) + +func NewPostgresHandler(db *store.PostgresStore, stopping *atomic.Bool, ttl int64) (http.Handler, error) { + registration := service.NewRegistration(db) + sessions, err := service.NewSessions(db, registration, ttl) + if err != nil { + return nil, err + } + chats := &persistentAPI{messenger: service.NewPersistentMessenger(db)} + return withInstanceID(withRequestID(withAccessLog(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if stopping.Load() && r.URL.Path != "/health/live" { + writeAppError(w, store.ErrUnavailable) + return + } + if r.URL.Path == "/api/v1/chats" || strings.HasPrefix(r.URL.Path, "/api/v1/chats/") { + token, err := bearerToken(r) + if err != nil { + sessionError(w, err, false) + return + } + user, err := sessions.CurrentUser(r.Context(), token) + if err != nil { + sessionError(w, err, false) + return + } + ctx := context.WithValue(r.Context(), userContextKey{}, user) + chats.chatRoutes(w, r.WithContext(ctx)) + return + } + switch r.URL.Path { + case "/api/v1/auth/sessions": + loginSession(w, r, sessions) + case "/api/v1/auth/sessions/current": + currentSession(w, r, sessions, true) + case "/api/v1/users/me": + currentSession(w, r, sessions, false) + case "/health/live": + handleHealth(w, r) + case "/health/ready": + if !requireMethod(w, r, http.MethodGet) { + return + } + if err := db.Ping(r.Context()); err != nil { + writeAppError(w, err) + return + } + handleHealth(w, r) + case "/api/v1/users": + if !requireMethod(w, r, http.MethodPost) { + return + } + var body struct { + Username string `json:"username"` + DisplayName string `json:"display_name"` + Password string `json:"password"` + } + if !readJSON(w, r, &body, "username", "display_name", "password") { + return + } + user, err := registration.Register(r.Context(), body.Username, body.DisplayName, body.Password) + if err != nil { + writeAppError(w, err) + return + } + writeJSON(w, http.StatusCreated, user) + default: + writeError(w, http.StatusNotFound, "not_found", "Resource not found") + } + })))), nil +} diff --git a/internal/httpapi/postgres_chats.go b/internal/httpapi/postgres_chats.go new file mode 100644 index 00000000..4cc598b7 --- /dev/null +++ b/internal/httpapi/postgres_chats.go @@ -0,0 +1,119 @@ +package httpapi + +import ( + "net/http" + + "strings" + + "gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/service" +) + +type persistentAPI struct{ messenger *service.PersistentMessenger } + +func (api *persistentAPI) chatRoutes(w http.ResponseWriter, r *http.Request) { + actor := userFromContext(r.Context()) + + if r.URL.Path == "/api/v1/chats" { + switch r.Method { + case http.MethodPost: + var body createChatRequest + if !readJSON(w, r, &body, "title", "member_ids") { + return + } + + chat, err := api.messenger.CreateChat(r.Context(), + actor.ID, body.Title, body.MemberIDs, + ) + if err != nil { + writeAppError(w, err) + return + } + + writeJSON(w, http.StatusCreated, chat) + + case http.MethodGet: + limit, cursor, ok := pageParams(w, r) + if !ok { + return + } + + page, err := api.messenger.ListChats(r.Context(), actor.ID, limit, cursor) + if err != nil { + writeAppError(w, err) + return + } + + writeJSON(w, http.StatusOK, page) + + default: + requireMethod(w, r, "GET, POST") + } + return + } + + path := strings.TrimPrefix(r.URL.Path, "/api/v1/chats/") + parts := strings.Split(path, "/") + + if len(parts) == 1 && parts[0] != "" { + if !requireMethod(w, r, http.MethodGet) { + return + } + + chat, err := api.messenger.GetChat(r.Context(), actor.ID, parts[0]) + if err != nil { + writeAppError(w, err) + return + } + + writeJSON(w, http.StatusOK, chat) + return + } + + if len(parts) != 2 || parts[0] == "" || parts[1] != "messages" { + writeError(w, http.StatusNotFound, "not_found", "Resource not found") + return + } + + chat, err := api.messenger.GetChat(r.Context(), actor.ID, parts[0]) + if err != nil { + writeAppError(w, err) + return + } + + switch r.Method { + case http.MethodPost: + var body createMessageRequest + if !readJSON(w, r, &body, "text") { + return + } + + message, err := api.messenger.CreateMessage(r.Context(), + actor.ID, chat.ID, body.Text, r.Header.Get("Idempotency-Key"), + ) + if err != nil { + writeAppError(w, err) + return + } + + writeJSON(w, http.StatusCreated, message) + + case http.MethodGet: + limit, cursor, ok := pageParams(w, r) + if !ok { + return + } + + page, err := api.messenger.ListMessages(r.Context(), + actor.ID, chat.ID, limit, cursor, + ) + if err != nil { + writeAppError(w, err) + return + } + + writeJSON(w, http.StatusOK, page) + + default: + requireMethod(w, r, "GET, POST") + } +} diff --git a/internal/httpapi/router.go b/internal/httpapi/router.go new file mode 100644 index 00000000..3051b0ae --- /dev/null +++ b/internal/httpapi/router.go @@ -0,0 +1,90 @@ +package httpapi + +import ( + "net/http" + "strings" + "sync/atomic" + + "gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/service" +) + +type API struct { + messenger *service.Messenger +} + +func NewHandler( + messenger *service.Messenger, + stoppingFlags ...*atomic.Bool, +) http.Handler { + api := &API{messenger: messenger} + + var stopping *atomic.Bool + + if len(stoppingFlags) > 0 { + stopping = stoppingFlags[0] + } + + if stopping == nil { + stopping = &atomic.Bool{} + } + + handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if stopping.Load() && r.URL.Path != "/health/live" { + writeError( + w, + http.StatusServiceUnavailable, + "unavailable", + "Server is shutting down", + ) + return + } + + api.route(w, r) + }) + + return withInstanceID(withRequestID(withAccessLog(handler))) +} + +func (api *API) route(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/api/v1/chats" || + strings.HasPrefix(r.URL.Path, "/api/v1/chats/") { + api.authenticate(http.HandlerFunc(api.chatRoutes)).ServeHTTP(w, r) + return + } + + switch r.URL.Path { + case "/health/live", "/health/ready": + handleHealth(w, r) + + case "/api/v1/users": + if !requireMethod(w, r, http.MethodPost) { + return + } + api.createUser(w, r) + + case "/api/v1/users/me": + if !requireMethod(w, r, http.MethodGet) { + return + } + api.authenticate(http.HandlerFunc(api.currentUser)).ServeHTTP(w, r) + + default: + writeError(w, http.StatusNotFound, "not_found", "Resource not found") + } +} + +func requireMethod(w http.ResponseWriter, r *http.Request, method string) bool { + if r.Method == method { + return true + } + + w.Header().Set("Allow", method) + writeError( + w, + http.StatusMethodNotAllowed, + "invalid_request", + "Method not allowed", + ) + + return false +} diff --git a/internal/httpapi/sessions.go b/internal/httpapi/sessions.go new file mode 100644 index 00000000..ca411466 --- /dev/null +++ b/internal/httpapi/sessions.go @@ -0,0 +1,87 @@ +package httpapi + +import ( + "errors" + "io" + "net/http" + "strings" + + "gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/service" +) + +func sessionError(w http.ResponseWriter, err error, basic bool) { + if errors.Is(err, service.ErrUnauthorized) { + challenge := `Bearer realm="messenger"` + if basic { + challenge = `Basic realm="messenger", charset="UTF-8"` + } + w.Header().Set("WWW-Authenticate", challenge) + writeError(w, http.StatusUnauthorized, "unauthorized", "Invalid credentials") + return + } + writeAppError(w, err) +} + +func loginSession(w http.ResponseWriter, r *http.Request, sessions *service.Sessions) { + if !requireMethod(w, r, http.MethodPost) { + return + } + username, secret, ok := r.BasicAuth() + if !ok || len(r.Header.Values("Authorization")) != 1 { + sessionError(w, service.ErrUnauthorized, true) + return + } + body, err := io.ReadAll(io.LimitReader(r.Body, 1)) + if err != nil || len(body) != 0 { + writeAppError(w, service.ErrInvalidRequest) + return + } + result, err := sessions.Login(r.Context(), username, secret) + if err != nil { + sessionError(w, err, true) + return + } + w.Header().Set("Cache-Control", "no-store") + writeJSON(w, http.StatusCreated, result) +} + +func bearerToken(r *http.Request) (string, error) { + if len(r.Header.Values("Authorization")) != 1 { + return "", service.ErrUnauthorized + } + fields := strings.Fields(r.Header.Get("Authorization")) + if len(fields) != 2 || !strings.EqualFold(fields[0], "Bearer") { + return "", service.ErrUnauthorized + } + return fields[1], nil +} + +func currentSession(w http.ResponseWriter, r *http.Request, sessions *service.Sessions, logout bool) { + method := http.MethodGet + if logout { + method = http.MethodDelete + } + if !requireMethod(w, r, method) { + return + } + token, err := bearerToken(r) + if err != nil { + sessionError(w, err, false) + return + } + if logout { + if err := sessions.Logout(r.Context(), token); err != nil { + sessionError(w, err, false) + return + } + w.WriteHeader(http.StatusNoContent) + return + } + user, err := sessions.CurrentUser(r.Context(), token) + if err != nil { + sessionError(w, err, false) + return + } + w.Header().Set("Cache-Control", "no-store") + writeJSON(w, http.StatusOK, user) +} diff --git a/internal/httpapi/users.go b/internal/httpapi/users.go new file mode 100644 index 00000000..7bbe659b --- /dev/null +++ b/internal/httpapi/users.go @@ -0,0 +1,29 @@ +package httpapi + +import "net/http" + +type createUserRequest struct { + Username string `json:"username"` + DisplayName string `json:"display_name"` +} + +func (api *API) createUser(w http.ResponseWriter, r *http.Request) { + var body createUserRequest + + if !readJSON(w, r, &body, "username", "display_name") { + return + } + + user, err := api.messenger.RegisterUser(body.Username, body.DisplayName) + if err != nil { + writeAppError(w, err) + return + } + + writeJSON(w, http.StatusCreated, user) +} + +func (api *API) currentUser(w http.ResponseWriter, r *http.Request) { + user := userFromContext(r.Context()) + writeJSON(w, http.StatusOK, user) +} diff --git a/internal/httpapi/users_test.go b/internal/httpapi/users_test.go new file mode 100644 index 00000000..3802bc0a --- /dev/null +++ b/internal/httpapi/users_test.go @@ -0,0 +1,171 @@ +package httpapi_test + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/httpapi" + "gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/model" + "gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/service" + "gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/store" +) + +func newAPI() http.Handler { + return httpapi.NewHandler( + service.NewMessenger(store.NewMemoryStore()), + ) +} + +func request( + handler http.Handler, + method string, + path string, + body string, + userID string, +) *httptest.ResponseRecorder { + req := httptest.NewRequest(method, path, strings.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + + if userID != "" { + req.Header.Set("X-User-Id", userID) + } + + response := httptest.NewRecorder() + handler.ServeHTTP(response, req) + return response +} + +func checkError( + t *testing.T, + response *httptest.ResponseRecorder, + status int, + code string, +) { + t.Helper() + + if response.Code != status { + t.Fatalf( + "status: got %d, want %d; body=%s", + response.Code, status, response.Body.String(), + ) + } + + var body struct { + Error struct { + Code string `json:"code"` + RequestID string `json:"request_id"` + } `json:"error"` + } + + if err := json.Unmarshal(response.Body.Bytes(), &body); err != nil { + t.Fatalf("decode error response: %v", err) + } + + if body.Error.Code != code { + t.Errorf("error code: got %q, want %q", body.Error.Code, code) + } + + id := response.Header().Get("X-Request-Id") + if id == "" || body.Error.RequestID != id { + t.Error("missing or mismatched request ID") + } +} + +func TestUserHTTPFlow(t *testing.T) { + handler := newAPI() + + body := `{"username":"alice","display_name":"Алиса 👋"}` + + created := request(handler, http.MethodPost, "/api/v1/users", body, "") + if created.Code != http.StatusCreated { + t.Fatalf("registration: %d %s", created.Code, created.Body.String()) + } + + if created.Header().Get("X-Request-Id") == "" { + t.Fatal("registration response has no request ID") + } + + var user model.User + if err := json.Unmarshal(created.Body.Bytes(), &user); err != nil { + t.Fatal(err) + } + + if user.ID == "" || user.CreatedAt.IsZero() || + user.Username != "alice" || user.DisplayName != "Алиса 👋" { + t.Fatalf("invalid user: %+v", user) + } + + me := request(handler, http.MethodGet, "/api/v1/users/me", "", user.ID) + if me.Code != http.StatusOK { + t.Fatalf("current user: %d %s", me.Code, me.Body.String()) + } + + var current model.User + if err := json.Unmarshal(me.Body.Bytes(), ¤t); err != nil { + t.Fatal(err) + } + + if current != user { + t.Fatalf("current user differs: %+v", current) + } + + duplicate := request(handler, http.MethodPost, "/api/v1/users", body, "") + checkError(t, duplicate, http.StatusConflict, "conflict") + + for _, id := range []string{ + "", + "invalid", + "00000000-0000-4000-8000-000000000000", + } { + response := request( + handler, http.MethodGet, "/api/v1/users/me", "", id, + ) + checkError(t, response, http.StatusUnauthorized, "unauthorized") + } +} + +func TestRegistrationInvalidJSON(t *testing.T) { + cases := []string{ + ``, + `{`, + `null`, + `[]`, + `{}`, + `{"username":"alice"}`, + `{"username":null,"display_name":"Alice"}`, + `{"username":123,"display_name":"Alice"}`, + `{"username":"alice","display_name":"Alice","extra":true}`, + `{"username":"alice","display_name":"Alice"} {}`, + `{"username":"Alice","display_name":"Alice"}`, + `{"username":"alice","display_name":" "}`, + } + + for _, body := range cases { + t.Run(body, func(t *testing.T) { + response := request( + newAPI(), http.MethodPost, "/api/v1/users", body, "", + ) + checkError(t, response, http.StatusBadRequest, "invalid_request") + }) + } +} + +func TestRegistrationContentType(t *testing.T) { + req := httptest.NewRequest( + http.MethodPost, + "/api/v1/users", + strings.NewReader(`{"username":"alice","display_name":"Alice"}`), + ) + req.Header.Set("Content-Type", "text/plain") + + response := httptest.NewRecorder() + newAPI().ServeHTTP(response, req) + + checkError( + t, response, + http.StatusUnsupportedMediaType, "unsupported_media_type", + ) +} diff --git a/internal/model/model.go b/internal/model/model.go new file mode 100644 index 00000000..b21401a2 --- /dev/null +++ b/internal/model/model.go @@ -0,0 +1,25 @@ +package model + +import "time" + +type User struct { + ID string `json:"id"` + Username string `json:"username"` + DisplayName string `json:"display_name"` + CreatedAt time.Time `json:"created_at"` +} + +type Chat struct { + ID string `json:"id"` + Title string `json:"title"` + MemberIDs []string `json:"member_ids"` + CreatedAt time.Time `json:"created_at"` +} + +type Message struct { + ID string `json:"id"` + ChatID string `json:"chat_id"` + SenderID string `json:"sender_id"` + Text string `json:"text"` + CreatedAt time.Time `json:"created_at"` +} diff --git a/internal/password/password.go b/internal/password/password.go new file mode 100644 index 00000000..331cc1a4 --- /dev/null +++ b/internal/password/password.go @@ -0,0 +1,76 @@ +package password + +import ( + "crypto/rand" + "crypto/subtle" + "encoding/base64" + "errors" + "fmt" + "strings" + "unicode/utf8" + + "golang.org/x/crypto/argon2" +) + +const ( + memoryKiB uint32 = 64 * 1024 + iterations uint32 = 3 + parallelism uint8 = 4 + saltLength = 16 + keyLength uint32 = 32 +) + +var ( + ErrInvalidPassword = errors.New("password must contain 12 to 128 UTF-8 code points and a non-whitespace character") + ErrInvalidHash = errors.New("invalid or unsupported password hash") + encoding = base64.RawStdEncoding.Strict() + profile = fmt.Sprintf("$argon2id$v=%d$m=%d,t=%d,p=%d$", + argon2.Version, memoryKiB, iterations, parallelism) +) + +func Validate(value string) error { + if !utf8.ValidString(value) { + return ErrInvalidPassword + } + length := utf8.RuneCountInString(value) + if length < 12 || length > 128 || strings.TrimSpace(value) == "" { + return ErrInvalidPassword + } + return nil +} + +func Hash(value string) (string, error) { + if err := Validate(value); err != nil { + return "", err + } + salt := make([]byte, saltLength) + if _, err := rand.Read(salt); err != nil { + return "", fmt.Errorf("generate password salt: %w", err) + } + key := argon2.IDKey([]byte(value), salt, iterations, memoryKiB, parallelism, keyLength) + return profile + encoding.EncodeToString(salt) + "$" + encoding.EncodeToString(key), nil +} + +func Verify(value, encoded string) (bool, error) { + if len(encoded) != len(profile)+encoding.EncodedLen(saltLength)+1+encoding.EncodedLen(int(keyLength)) || + !strings.HasPrefix(encoded, profile) { + return false, ErrInvalidHash + } + parts := strings.Split(strings.TrimPrefix(encoded, profile), "$") + if len(parts) != 2 { + return false, ErrInvalidHash + } + salt, err := encoding.DecodeString(parts[0]) + if err != nil || len(salt) != saltLength { + return false, ErrInvalidHash + } + expected, err := encoding.DecodeString(parts[1]) + if err != nil || len(expected) != int(keyLength) { + return false, ErrInvalidHash + } + if err := Validate(value); err != nil { + return false, nil + } + actual := argon2.IDKey([]byte(value), salt, iterations, memoryKiB, parallelism, keyLength) + return subtle.ConstantTimeCompare(actual, expected) == 1, nil +} diff --git a/internal/password/password_test.go b/internal/password/password_test.go new file mode 100644 index 00000000..2620b01b --- /dev/null +++ b/internal/password/password_test.go @@ -0,0 +1,98 @@ +package password + +import ( + "errors" + "strings" + "testing" +) + +func TestValidate(t *testing.T) { + for _, tc := range []struct { + name string + value string + valid bool + }{ + {"empty", "", false}, + {"11 characters", strings.Repeat("a", 11), false}, + {"12 characters", strings.Repeat("a", 12), true}, + {"128 Unicode characters", strings.Repeat("я", 128), true}, + {"129 Unicode characters", strings.Repeat("я", 129), false}, + {"invalid UTF-8", strings.Repeat("a", 12) + string([]byte{0xff}), false}, + {"only spaces", strings.Repeat(" ", 12), false}, + {"only Unicode whitespace", strings.Repeat("\u00a0\u2003\t\n", 3), false}, + {"spaces preserved", " пароль:секрет ", true}, + {"colon allowed", "пароль:секрет", true}, + } { + t.Run(tc.name, func(t *testing.T) { + err := Validate(tc.value) + if (err == nil) != tc.valid { + t.Fatalf("valid=%v, error=%v", tc.valid, err) + } + if !tc.valid { + if _, err := Hash(tc.value); !errors.Is(err, ErrInvalidPassword) { + t.Fatalf("Hash error=%v", err) + } + } + }) + } +} + +func TestHashAndVerify(t *testing.T) { + value := " пароль:секрет " + first, err := Hash(value) + if err != nil { + t.Fatal(err) + } + second, err := Hash(value) + if err != nil { + t.Fatal(err) + } + if first == second { + t.Fatal("independent salts produced identical records") + } + for _, encoded := range []string{first, second} { + ok, err := Verify(value, encoded) + if err != nil || !ok { + t.Fatalf("correct password: match=%v error=%v", ok, err) + } + } + for _, wrong := range []string{"другой:пароль", strings.TrimSpace(value), "short"} { + ok, err := Verify(wrong, first) + if err != nil || ok { + t.Fatalf("wrong password: match=%v error=%v", ok, err) + } + } +} + +func TestLongUnicodePasswordIsNotTruncated(t *testing.T) { + value := strings.Repeat("я", 128) + encoded, err := Hash(value) + if err != nil { + t.Fatal(err) + } + ok, err := Verify(value, encoded) + if err != nil || !ok { + t.Fatalf("match=%v error=%v", ok, err) + } + ok, err = Verify(strings.Repeat("я", 127)+"ю", encoded) + if err != nil || ok { + t.Fatalf("last character ignored: match=%v error=%v", ok, err) + } +} + +func TestVerifyRejectsMalformedHash(t *testing.T) { + encoded := profile + encoding.EncodeToString(make([]byte, saltLength)) + "$" + encoding.EncodeToString(make([]byte, keyLength)) + for _, broken := range []string{ + "", "plaintext", encoded[:len(encoded)-1], encoded + "$extra", + strings.Replace(encoded, "v=19", "v=18", 1), + strings.Replace(encoded, "m=65536", "m=999999999", 1), + strings.Replace(encoded, "t=3", "t=0", 1), + strings.Replace(encoded, "p=4", "p=0", 1), + profile + "!" + encoded[len(profile)+1:], + } { + ok, err := Verify("пароль:секрет", broken) + if ok || !errors.Is(err, ErrInvalidHash) { + t.Fatalf("match=%v error=%v", ok, err) + } + } +} diff --git a/internal/service/chats.go b/internal/service/chats.go new file mode 100644 index 00000000..b5e7082e --- /dev/null +++ b/internal/service/chats.go @@ -0,0 +1,111 @@ +package service + +import ( + "strings" + "unicode/utf8" + + "gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/model" +) + +func validText(value string, maxLength int) bool { + return utf8.ValidString(value) && + strings.TrimSpace(value) != "" && + utf8.RuneCountInString(value) <= maxLength +} + +func (m *Messenger) CreateChat( + actorID string, + title string, + memberIDs []string, +) (model.Chat, error) { + if !validText(title, 100) || + len(memberIDs) < 1 || + len(memberIDs) > 100 { + return model.Chat{}, ErrInvalidRequest + } + + normalized := make([]string, len(memberIDs)) + + for i, id := range memberIDs { + if !uuidPattern.MatchString(id) { + return model.Chat{}, ErrInvalidRequest + } + normalized[i] = strings.ToLower(id) + } + + return m.store.CreateChat(actorID, title, normalized) +} + +func (m *Messenger) GetChat( + actorID string, + chatID string, +) (model.Chat, error) { + if !uuidPattern.MatchString(chatID) { + return model.Chat{}, ErrInvalidRequest + } + + return m.store.GetChat(actorID, strings.ToLower(chatID)) +} + +func (m *Messenger) ListChats( + actorID string, + limit int, + cursor string, +) (Page[model.Chat], error) { + chats := m.store.ListChats(actorID) + + return paginate( + chats, + "chats:"+actorID, + limit, + cursor, + func(chat model.Chat) position { + return position{CreatedAt: chat.CreatedAt, ID: chat.ID} + }, + ) +} + +func (m *Messenger) CreateMessage( + actorID string, + chatID string, + text string, +) (model.Message, error) { + chat, err := m.GetChat(actorID, chatID) + if err != nil { + return model.Message{}, err + } + + if !validText(text, 4000) { + return model.Message{}, ErrInvalidRequest + } + + return m.store.CreateMessage(actorID, chat.ID, text) +} + +func (m *Messenger) ListMessages( + actorID string, + chatID string, + limit int, + cursor string, +) (Page[model.Message], error) { + if !uuidPattern.MatchString(chatID) { + return Page[model.Message]{}, ErrInvalidRequest + } + + chatID = strings.ToLower(chatID) + + messages, err := m.store.ListMessages(actorID, chatID) + if err != nil { + return Page[model.Message]{}, err + } + + return paginate( + messages, + "messages:"+chatID, + limit, + cursor, + func(message model.Message) position { + return position{CreatedAt: message.CreatedAt, ID: message.ID} + }, + ) +} diff --git a/internal/service/idempotency_test.go b/internal/service/idempotency_test.go new file mode 100644 index 00000000..48e4d1b8 --- /dev/null +++ b/internal/service/idempotency_test.go @@ -0,0 +1,25 @@ +package service + +import ( + "context" + "errors" + "strings" + "testing" +) + +func TestIdempotencyKeyValidation(t *testing.T) { + for _, key := range []string{"a", "retry-1._:ABC09", strings.Repeat("a", 128)} { + if !idempotencyKeyPattern.MatchString(key) { + t.Fatalf("valid key rejected: %q", key) + } + } + for _, key := range []string{"", " ", "a b", "ключ", "a\n", strings.Repeat("a", 129)} { + // Nil DB ensures invalid input is rejected before any storage call. + m := NewPersistentMessenger(nil) + _, err := m.CreateMessage(context.Background(), "actor", + "12345678-1234-4234-8234-123456789abc", "hello", key) + if !errors.Is(err, ErrInvalidRequest) { + t.Fatalf("key %q: got %v, want invalid request", key, err) + } + } +} diff --git a/internal/service/messenger.go b/internal/service/messenger.go new file mode 100644 index 00000000..539ce982 --- /dev/null +++ b/internal/service/messenger.go @@ -0,0 +1,76 @@ +package service + +import ( + "errors" + "regexp" + "strings" + "unicode/utf8" + + "gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/model" + "gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/store" +) + +var ( + ErrInvalidRequest = errors.New("invalid request") + ErrUnauthorized = errors.New("unauthorized") +) + +var ( + usernamePattern = regexp.MustCompile(`^[a-z0-9_]{3,32}$`) + uuidPattern = regexp.MustCompile( + `^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$`, + ) +) + +type Messenger struct { + store *store.MemoryStore +} + +func NewMessenger(memory *store.MemoryStore) *Messenger { + return &Messenger{ + store: memory, + } +} + +func (m *Messenger) RegisterUser( + username string, + displayName string, +) (model.User, error) { + if !usernamePattern.MatchString(username) { + return model.User{}, ErrInvalidRequest + } + + if !utf8.ValidString(displayName) { + return model.User{}, ErrInvalidRequest + } + + length := utf8.RuneCountInString(displayName) + + if length < 1 || length > 100 { + return model.User{}, ErrInvalidRequest + } + + if strings.TrimSpace(displayName) == "" { + return model.User{}, ErrInvalidRequest + } + + return m.store.CreateUser(username, displayName) +} + +func (m *Messenger) CurrentUser(id string) (model.User, error) { + if !uuidPattern.MatchString(id) { + return model.User{}, ErrUnauthorized + } + + user, err := m.store.GetUser(strings.ToLower(id)) + + if errors.Is(err, store.ErrUserNotFound) { + return model.User{}, ErrUnauthorized + } + + if err != nil { + return model.User{}, err + } + + return user, nil +} diff --git a/internal/service/messenger_test.go b/internal/service/messenger_test.go new file mode 100644 index 00000000..dcb79bc9 --- /dev/null +++ b/internal/service/messenger_test.go @@ -0,0 +1,143 @@ +package service_test + +import ( + "errors" + "strings" + "testing" + + "gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/service" + "gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/store" +) + +func TestRegisterUserValidation(t *testing.T) { + tests := []struct { + name string + username string + displayName string + valid bool + }{ + { + name: "valid Unicode name", + username: "alice_01", + displayName: "Алиса 👋", + valid: true, + }, + { + name: "100 Unicode code points", + username: "alice", + displayName: strings.Repeat("👋", 100), + valid: true, + }, + { + name: "101 Unicode code points", + username: "alice", + displayName: strings.Repeat("👋", 101), + }, + { + name: "short username", + username: "ab", + displayName: "Алиса", + }, + { + name: "long username", + username: strings.Repeat("a", 33), + displayName: "Алиса", + }, + { + name: "uppercase username", + username: "Alice", + displayName: "Алиса", + }, + { + name: "non ASCII username", + username: "алиса", + displayName: "Алиса", + }, + { + name: "empty display name", + username: "alice", + displayName: "", + }, + { + name: "whitespace display name", + username: "alice", + displayName: " \t\n", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + m := service.NewMessenger(store.NewMemoryStore()) + + user, err := m.RegisterUser(tt.username, tt.displayName) + + if !tt.valid { + if !errors.Is(err, service.ErrInvalidRequest) { + t.Fatalf("expected ErrInvalidRequest, got %v", err) + } + return + } + + if err != nil { + t.Fatalf("RegisterUser: %v", err) + } + + if user.Username != tt.username || + user.DisplayName != tt.displayName { + t.Fatalf("user fields changed: %+v", user) + } + }) + } +} + +func TestRegisterDuplicateUsername(t *testing.T) { + m := service.NewMessenger(store.NewMemoryStore()) + + if _, err := m.RegisterUser("alice", "Алиса"); err != nil { + t.Fatalf("first registration: %v", err) + } + + _, err := m.RegisterUser("alice", "Другое имя") + if !errors.Is(err, store.ErrUsernameTaken) { + t.Fatalf("expected ErrUsernameTaken, got %v", err) + } +} + +func TestCurrentUser(t *testing.T) { + m := service.NewMessenger(store.NewMemoryStore()) + + created, err := m.RegisterUser("alice", "Алиса") + if err != nil { + t.Fatalf("RegisterUser: %v", err) + } + + for _, id := range []string{ + created.ID, + strings.ToUpper(created.ID), + } { + found, err := m.CurrentUser(id) + if err != nil { + t.Fatalf("CurrentUser(%q): %v", id, err) + } + + if found != created { + t.Fatalf("got %+v, want %+v", found, created) + } + } + + for _, id := range []string{ + "", + "not-a-uuid", + "00000000-0000-4000-8000-000000000000", + } { + _, err := m.CurrentUser(id) + + if !errors.Is(err, service.ErrUnauthorized) { + t.Errorf( + "CurrentUser(%q): expected ErrUnauthorized, got %v", + id, + err, + ) + } + } +} diff --git a/internal/service/pagination.go b/internal/service/pagination.go new file mode 100644 index 00000000..55232267 --- /dev/null +++ b/internal/service/pagination.go @@ -0,0 +1,98 @@ +package service + +import ( + "encoding/base64" + "encoding/json" + "sort" + "time" +) + +type Page[T any] struct { + Items []T `json:"items"` + NextCursor *string `json:"next_cursor"` +} + +type position struct { + CreatedAt time.Time `json:"created_at"` + ID string `json:"id"` +} + +type cursorData struct { + Scope string `json:"scope"` + After position `json:"after"` +} + +func less(a, b position) bool { + if a.CreatedAt.Equal(b.CreatedAt) { + return a.ID < b.ID + } + return a.CreatedAt.Before(b.CreatedAt) +} + +func paginate[T any]( + items []T, + scope string, + limit int, + cursor string, + key func(T) position, +) (Page[T], error) { + if limit < 1 || limit > 100 { + return Page[T]{}, ErrInvalidRequest + } + + var after *position + + if cursor != "" { + raw, err := base64.RawURLEncoding.DecodeString(cursor) + if err != nil { + return Page[T]{}, ErrInvalidRequest + } + + var decoded cursorData + if err := json.Unmarshal(raw, &decoded); err != nil { + return Page[T]{}, ErrInvalidRequest + } + + if decoded.Scope != scope || + decoded.After.CreatedAt.IsZero() || + !uuidPattern.MatchString(decoded.After.ID) { + return Page[T]{}, ErrInvalidRequest + } + + after = &decoded.After + } + + sort.Slice(items, func(i, j int) bool { + return less(key(items[i]), key(items[j])) + }) + + start := 0 + + if after != nil { + start = sort.Search(len(items), func(i int) bool { + return less(*after, key(items[i])) + }) + } + + end := min(start+limit, len(items)) + + page := Page[T]{ + Items: make([]T, end-start), + } + copy(page.Items, items[start:end]) + + if end < len(items) { + raw, err := json.Marshal(cursorData{ + Scope: scope, + After: key(items[end-1]), + }) + if err != nil { + return Page[T]{}, err + } + + next := base64.RawURLEncoding.EncodeToString(raw) + page.NextCursor = &next + } + + return page, nil +} diff --git a/internal/service/persistent.go b/internal/service/persistent.go new file mode 100644 index 00000000..3d7073fc --- /dev/null +++ b/internal/service/persistent.go @@ -0,0 +1,120 @@ +package service + +import ( + "context" + "encoding/base64" + "encoding/json" + "gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/model" + "gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/store" + "regexp" + "strings" +) + +type PersistentMessenger struct{ db *store.PostgresStore } + +func NewPersistentMessenger(db *store.PostgresStore) *PersistentMessenger { + return &PersistentMessenger{db: db} +} + +func (m *PersistentMessenger) CreateChat(ctx context.Context, actor, title string, members []string) (model.Chat, error) { + if !validText(title, 100) || len(members) < 1 || len(members) > 100 { + return model.Chat{}, ErrInvalidRequest + } + normalized := make([]string, len(members)) + seen := make(map[string]bool) + for i, id := range members { + if !uuidPattern.MatchString(id) { + return model.Chat{}, ErrInvalidRequest + } + id = strings.ToLower(id) + if seen[id] { + return model.Chat{}, store.ErrInvalidMembers + } + seen[id] = true + normalized[i] = id + } + if !seen[actor] { + return model.Chat{}, store.ErrInvalidMembers + } + return m.db.CreateChat(ctx, title, normalized) +} +func (m *PersistentMessenger) GetChat(ctx context.Context, actor, id string) (model.Chat, error) { + if !uuidPattern.MatchString(id) { + return model.Chat{}, ErrInvalidRequest + } + return m.db.GetChat(ctx, actor, strings.ToLower(id)) +} +func decodePosition(cursor, scope string, limit int) (*store.Position, error) { + if limit < 1 || limit > 100 { + return nil, ErrInvalidRequest + } + if cursor == "" { + return nil, nil + } + if len(cursor) > 2048 { + return nil, ErrInvalidRequest + } + raw, err := base64.RawURLEncoding.DecodeString(cursor) + if err != nil { + return nil, ErrInvalidRequest + } + var data cursorData + if json.Unmarshal(raw, &data) != nil || data.Scope != scope || data.After.CreatedAt.IsZero() || !uuidPattern.MatchString(data.After.ID) { + return nil, ErrInvalidRequest + } + if data.After.CreatedAt.Year() < 1 || data.After.CreatedAt.Year() > 9999 { + return nil, ErrInvalidRequest + } + return &store.Position{CreatedAt: data.After.CreatedAt, ID: strings.ToLower(data.After.ID)}, nil +} +func databasePage[T any](items []T, limit int, scope string, key func(T) position) (Page[T], error) { + page := Page[T]{Items: items} + if len(items) <= limit { + return page, nil + } + page.Items = items[:limit] + raw, err := json.Marshal(cursorData{Scope: scope, After: key(page.Items[limit-1])}) + if err != nil { + return Page[T]{}, err + } + cursor := base64.RawURLEncoding.EncodeToString(raw) + page.NextCursor = &cursor + return page, nil +} +func (m *PersistentMessenger) ListChats(ctx context.Context, actor string, limit int, cursor string) (Page[model.Chat], error) { + scope := "chats:" + actor + after, err := decodePosition(cursor, scope, limit) + if err != nil { + return Page[model.Chat]{}, err + } + items, err := m.db.ChatPage(ctx, actor, limit+1, after) + if err != nil { + return Page[model.Chat]{}, err + } + return databasePage(items, limit, scope, func(c model.Chat) position { return position{CreatedAt: c.CreatedAt, ID: c.ID} }) +} + +var idempotencyKeyPattern = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`) + +func (m *PersistentMessenger) CreateMessage(ctx context.Context, actor, chatID, text, key string) (model.Message, error) { + if !uuidPattern.MatchString(chatID) || !validText(text, 4000) || !idempotencyKeyPattern.MatchString(key) { + return model.Message{}, ErrInvalidRequest + } + return m.db.CreateMessage(ctx, actor, strings.ToLower(chatID), text, key) +} +func (m *PersistentMessenger) ListMessages(ctx context.Context, actor, chatID string, limit int, cursor string) (Page[model.Message], error) { + chat, err := m.GetChat(ctx, actor, chatID) + if err != nil { + return Page[model.Message]{}, err + } + scope := "messages:" + chat.ID + after, err := decodePosition(cursor, scope, limit) + if err != nil { + return Page[model.Message]{}, err + } + items, err := m.db.MessagePage(ctx, chat.ID, limit+1, after) + if err != nil { + return Page[model.Message]{}, err + } + return databasePage(items, limit, scope, func(message model.Message) position { return position{CreatedAt: message.CreatedAt, ID: message.ID} }) +} diff --git a/internal/service/registration.go b/internal/service/registration.go new file mode 100644 index 00000000..3f4c7764 --- /dev/null +++ b/internal/service/registration.go @@ -0,0 +1,45 @@ +package service + +import ( + "context" + "time" + + "gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/model" + "gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/password" + "gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/store" +) + +type UserWriter interface { + CreateUser(context.Context, string, string, string) (model.User, error) +} + +type Registration struct { + users UserWriter + hashSlots chan struct{} +} + +func NewRegistration(users UserWriter) *Registration { + return &Registration{users: users, hashSlots: make(chan struct{}, 2)} +} + +func (s *Registration) Register(ctx context.Context, username, displayName, secret string) (model.User, error) { + if !usernamePattern.MatchString(username) || !validText(displayName, 100) || password.Validate(secret) != nil { + return model.User{}, ErrInvalidRequest + } + ctx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + select { + case s.hashSlots <- struct{}{}: + case <-ctx.Done(): + return model.User{}, store.ErrUnavailable + } + hash, err := password.Hash(secret) + <-s.hashSlots + if err != nil { + return model.User{}, err + } + if ctx.Err() != nil { + return model.User{}, store.ErrUnavailable + } + return s.users.CreateUser(ctx, username, displayName, hash) +} diff --git a/internal/service/registration_test.go b/internal/service/registration_test.go new file mode 100644 index 00000000..79c071bf --- /dev/null +++ b/internal/service/registration_test.go @@ -0,0 +1,55 @@ +package service + +import ( + "context" + "errors" + "testing" + + "gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/model" + "gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/password" + "gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/store" +) + +type registrationWriter struct { + calls int + hash string + err error +} + +func (w *registrationWriter) CreateUser(_ context.Context, username, displayName, hash string) (model.User, error) { + w.calls++ + w.hash = hash + return model.User{Username: username, DisplayName: displayName}, w.err +} + +func TestRegistrationHashesBeforeStorage(t *testing.T) { + w := ®istrationWriter{} + s := NewRegistration(w) + user, err := s.Register(context.Background(), "alice", "Алиса", "учебный:пароль") + if err != nil || user.Username != "alice" || w.calls != 1 { + t.Fatalf("registration failed: %v", err) + } + ok, err := password.Verify("учебный:пароль", w.hash) + if err != nil || !ok { + t.Fatalf("stored value is not a valid password hash: %v", err) + } + w.err = store.ErrUsernameTaken + _, err = s.Register(context.Background(), "alice", "Алиса", "учебный:пароль") + if !errors.Is(err, store.ErrUsernameTaken) { + t.Fatalf("conflict lost: %v", err) + } +} + +func TestRegistrationRejectsBeforeStorage(t *testing.T) { + w := ®istrationWriter{} + s := NewRegistration(w) + for _, fields := range [][3]string{{"Alice", "Алиса", "учебный:пароль"}, {"alice", " ", "учебный:пароль"}, {"alice", "Алиса", "short"}} { + _, err := s.Register(context.Background(), fields[0], fields[1], fields[2]) + if !errors.Is(err, ErrInvalidRequest) { + t.Fatalf("invalid input accepted: %v", err) + } + } + if w.calls != 0 { + t.Fatal("invalid data reached storage") + } +} diff --git a/internal/service/sessions.go b/internal/service/sessions.go new file mode 100644 index 00000000..6a55f1a1 --- /dev/null +++ b/internal/service/sessions.go @@ -0,0 +1,125 @@ +package service + +import ( + "context" + "crypto/rand" + "crypto/sha256" + "encoding/base64" + "errors" + "time" + + "gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/model" + "gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/password" + "gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/store" +) + +type SessionStore interface { + Credentials(context.Context, string) (model.User, string, error) + CreateSession(context.Context, []byte, string, int64) (time.Time, error) + SessionUser(context.Context, []byte) (model.User, error) + DeleteSession(context.Context, []byte) error +} + +type Sessions struct { + db SessionStore + ttl int64 + hashSlots chan struct{} + dummyHash string +} + +type SessionResponse struct { + Token string `json:"token"` + TokenType string `json:"token_type"` + ExpiresAt time.Time `json:"expires_at"` + User model.User `json:"user"` +} + +func NewSessions(db SessionStore, registration *Registration, ttl int64) (*Sessions, error) { + if ttl < 1 || ttl > 31536000 { + return nil, errors.New("SESSION_TTL_SECONDS must be between 1 and 31536000") + } + dummy, err := password.Hash("dummy-password-for-missing-user") + if err != nil { + return nil, err + } + return &Sessions{db: db, ttl: ttl, hashSlots: registration.hashSlots, dummyHash: dummy}, nil +} + +func (s *Sessions) Login(ctx context.Context, username, secret string) (SessionResponse, error) { + if !usernamePattern.MatchString(username) || password.Validate(secret) != nil { + return SessionResponse{}, ErrUnauthorized + } + ctx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + user, hash, err := s.db.Credentials(ctx, username) + missing := errors.Is(err, store.ErrUserNotFound) + if err != nil && !missing { + return SessionResponse{}, err + } + if missing { + hash = s.dummyHash + } + select { + case s.hashSlots <- struct{}{}: + case <-ctx.Done(): + return SessionResponse{}, store.ErrUnavailable + } + matches, err := password.Verify(secret, hash) + <-s.hashSlots + if err != nil { + return SessionResponse{}, errors.New("stored password hash is invalid") + } + if ctx.Err() != nil { + return SessionResponse{}, store.ErrUnavailable + } + if missing || !matches { + return SessionResponse{}, ErrUnauthorized + } + raw := make([]byte, 32) + if _, err := rand.Read(raw); err != nil { + return SessionResponse{}, errors.New("cannot generate session token") + } + token := base64.RawURLEncoding.EncodeToString(raw) + digest := sha256.Sum256([]byte(token)) + expires, err := s.db.CreateSession(ctx, digest[:], user.ID, s.ttl) + if err != nil { + return SessionResponse{}, err + } + return SessionResponse{Token: token, TokenType: "Bearer", ExpiresAt: expires, User: user}, nil +} + +func tokenDigest(token string) ([]byte, error) { + if len(token) != 43 { + return nil, ErrUnauthorized + } + raw, err := base64.RawURLEncoding.Strict().DecodeString(token) + if err != nil || len(raw) != 32 { + return nil, ErrUnauthorized + } + digest := sha256.Sum256([]byte(token)) + return digest[:], nil +} + +func (s *Sessions) CurrentUser(ctx context.Context, token string) (model.User, error) { + digest, err := tokenDigest(token) + if err != nil { + return model.User{}, err + } + user, err := s.db.SessionUser(ctx, digest) + if errors.Is(err, store.ErrSessionNotFound) { + return model.User{}, ErrUnauthorized + } + return user, err +} + +func (s *Sessions) Logout(ctx context.Context, token string) error { + digest, err := tokenDigest(token) + if err != nil { + return err + } + err = s.db.DeleteSession(ctx, digest) + if errors.Is(err, store.ErrSessionNotFound) { + return ErrUnauthorized + } + return err +} diff --git a/internal/service/sessions_test.go b/internal/service/sessions_test.go new file mode 100644 index 00000000..45dbcabf --- /dev/null +++ b/internal/service/sessions_test.go @@ -0,0 +1,96 @@ +package service + +import ( + "context" + "crypto/sha256" + "errors" + "testing" + "time" + + "gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/model" + "gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/password" + "gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/store" +) + +type sessionFake struct { + hash string + stored []byte + writes int + unavailable bool +} + +func (f *sessionFake) Credentials(_ context.Context, username string) (model.User, string, error) { + if f.unavailable { + return model.User{}, "", store.ErrUnavailable + } + if username != "alice" { + return model.User{}, "", store.ErrUserNotFound + } + return model.User{ID: "user-id", Username: username}, f.hash, nil +} +func (f *sessionFake) CreateSession(_ context.Context, hash []byte, _ string, _ int64) (time.Time, error) { + f.writes++ + f.stored = append([]byte(nil), hash...) + return time.Now().UTC().Add(time.Hour), nil +} +func (f *sessionFake) SessionUser(_ context.Context, hash []byte) (model.User, error) { + if f.unavailable { + return model.User{}, store.ErrUnavailable + } + if string(hash) != string(f.stored) || f.stored == nil { + return model.User{}, store.ErrSessionNotFound + } + return model.User{ID: "user-id", Username: "alice"}, nil +} +func (f *sessionFake) DeleteSession(_ context.Context, hash []byte) error { + if _, err := f.SessionUser(context.Background(), hash); err != nil { + return err + } + f.stored = nil + return nil +} + +func TestSessionLifecycle(t *testing.T) { + hash, err := password.Hash("учебный:пароль") + if err != nil { + t.Fatal(err) + } + db := &sessionFake{hash: hash} + s, err := NewSessions(db, NewRegistration(nil), 3600) + if err != nil { + t.Fatal(err) + } + for _, username := range []string{"alice", "missing"} { + if _, err := s.Login(context.Background(), username, "неверный:пароль"); !errors.Is(err, ErrUnauthorized) { + t.Fatalf("bad credentials: %v", err) + } + } + if db.writes != 0 { + t.Fatal("invalid login created a session") + } + session, err := s.Login(context.Background(), "alice", "учебный:пароль") + if err != nil { + t.Fatal(err) + } + digest := sha256.Sum256([]byte(session.Token)) + if len(session.Token) != 43 || string(db.stored) != string(digest[:]) { + t.Fatal("must store digest of random token") + } + if _, err := s.CurrentUser(context.Background(), session.Token); err != nil { + t.Fatal(err) + } + db.unavailable = true + if _, err := s.CurrentUser(context.Background(), session.Token); !errors.Is(err, store.ErrUnavailable) { + t.Fatalf("outage: %v", err) + } + db.unavailable = false + if err := s.Logout(context.Background(), session.Token); err != nil { + t.Fatal(err) + } + if _, err := s.CurrentUser(context.Background(), session.Token); !errors.Is(err, ErrUnauthorized) { + t.Fatalf("revoked: %v", err) + } + if err := s.Logout(context.Background(), session.Token); !errors.Is(err, ErrUnauthorized) { + t.Fatalf("repeated logout: %v", err) + } +} diff --git a/internal/store/chats.go b/internal/store/chats.go new file mode 100644 index 00000000..78d6f973 --- /dev/null +++ b/internal/store/chats.go @@ -0,0 +1,171 @@ +package store + +import ( + "errors" + "slices" + "time" + + "gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/model" +) + +var ( + ErrNotFound = errors.New("resource not found") + ErrInvalidMembers = errors.New("invalid chat members") +) + +func cloneChat(chat model.Chat) model.Chat { + chat.MemberIDs = slices.Clone(chat.MemberIDs) + return chat +} + +func (s *MemoryStore) CreateChat( + actorID string, + title string, + memberIDs []string, +) (model.Chat, error) { + s.mu.Lock() + defer s.mu.Unlock() + + seen := make(map[string]bool, len(memberIDs)) + + for _, id := range memberIDs { + if seen[id] { + return model.Chat{}, ErrInvalidMembers + } + + if _, exists := s.usersByID[id]; !exists { + return model.Chat{}, ErrInvalidMembers + } + + seen[id] = true + } + + if !seen[actorID] { + return model.Chat{}, ErrInvalidMembers + } + + id, err := newUUID() + if err != nil { + return model.Chat{}, err + } + + for { + if _, exists := s.chatsByID[id]; !exists { + break + } + id, err = newUUID() + if err != nil { + return model.Chat{}, err + } + } + + chat := model.Chat{ + ID: id, + Title: title, + MemberIDs: slices.Clone(memberIDs), + CreatedAt: time.Now().UTC(), + } + + s.chatsByID[id] = chat + s.messagesByChat[id] = []model.Message{} + + return cloneChat(chat), nil +} + +func (s *MemoryStore) GetChat( + actorID string, + chatID string, +) (model.Chat, error) { + s.mu.RLock() + defer s.mu.RUnlock() + + chat, exists := s.chatsByID[chatID] + if !exists || !slices.Contains(chat.MemberIDs, actorID) { + return model.Chat{}, ErrNotFound + } + + return cloneChat(chat), nil +} + +func (s *MemoryStore) ListChats(actorID string) []model.Chat { + s.mu.RLock() + defer s.mu.RUnlock() + + result := make([]model.Chat, 0) + + for _, chat := range s.chatsByID { + if slices.Contains(chat.MemberIDs, actorID) { + result = append(result, cloneChat(chat)) + } + } + + return result +} + +func (s *MemoryStore) CreateMessage( + actorID string, + chatID string, + text string, +) (model.Message, error) { + s.mu.Lock() + defer s.mu.Unlock() + + chat, exists := s.chatsByID[chatID] + if !exists || !slices.Contains(chat.MemberIDs, actorID) { + return model.Message{}, ErrNotFound + } + + id, err := newUUID() + if err != nil { + return model.Message{}, err + } + + history := s.messagesByChat[chatID] + + for slices.ContainsFunc(history, func(message model.Message) bool { + return message.ID == id + }) { + id, err = newUUID() + if err != nil { + return model.Message{}, err + } + } + + createdAt := time.Now().UTC() + + if len(history) > 0 { + last := history[len(history)-1].CreatedAt + if !createdAt.After(last) { + createdAt = last.Add(time.Nanosecond) + } + } + + message := model.Message{ + ID: id, + ChatID: chatID, + SenderID: actorID, + Text: text, + CreatedAt: createdAt, + } + + s.messagesByChat[chatID] = append(history, message) + return message, nil +} + +func (s *MemoryStore) ListMessages( + actorID string, + chatID string, +) ([]model.Message, error) { + s.mu.RLock() + defer s.mu.RUnlock() + + chat, exists := s.chatsByID[chatID] + if !exists || !slices.Contains(chat.MemberIDs, actorID) { + return nil, ErrNotFound + } + + result := make([]model.Message, len(s.messagesByChat[chatID])) + copy(result, s.messagesByChat[chatID]) + + return result, nil +} diff --git a/internal/store/memory.go b/internal/store/memory.go new file mode 100644 index 00000000..851027b7 --- /dev/null +++ b/internal/store/memory.go @@ -0,0 +1,106 @@ +package store + +import ( + "crypto/rand" + "errors" + "fmt" + "sync" + "time" + + "gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/model" +) + +var ( + ErrUsernameTaken = errors.New("username already exists") + ErrUserNotFound = errors.New("user not found") +) + +type MemoryStore struct { + mu sync.RWMutex + + usersByID map[string]model.User + userIDsByName map[string]string + chatsByID map[string]model.Chat + messagesByChat map[string][]model.Message +} + +func NewMemoryStore() *MemoryStore { + return &MemoryStore{ + usersByID: make(map[string]model.User), + userIDsByName: make(map[string]string), + chatsByID: make(map[string]model.Chat), + messagesByChat: make(map[string][]model.Message), + } +} + +func (s *MemoryStore) CreateUser( + username string, + displayName string, +) (model.User, error) { + s.mu.Lock() + defer s.mu.Unlock() + + if _, exists := s.userIDsByName[username]; exists { + return model.User{}, ErrUsernameTaken + } + + id, err := newUUID() + if err != nil { + return model.User{}, fmt.Errorf("generate user ID: %w", err) + } + + for { + if _, exists := s.usersByID[id]; !exists { + break + } + + id, err = newUUID() + if err != nil { + return model.User{}, fmt.Errorf("generate user ID: %w", err) + } + } + + user := model.User{ + ID: id, + Username: username, + DisplayName: displayName, + CreatedAt: time.Now().UTC(), + } + + s.usersByID[user.ID] = user + s.userIDsByName[user.Username] = user.ID + + return user, nil +} + +func (s *MemoryStore) GetUser(id string) (model.User, error) { + s.mu.RLock() + defer s.mu.RUnlock() + + user, exists := s.usersByID[id] + if !exists { + return model.User{}, ErrUserNotFound + } + + return user, nil +} + +func newUUID() (string, error) { + var value [16]byte + + if _, err := rand.Read(value[:]); err != nil { + return "", err + } + + value[6] = (value[6] & 0x0f) | 0x40 + value[8] = (value[8] & 0x3f) | 0x80 + + return fmt.Sprintf( + "%x-%x-%x-%x-%x", + value[0:4], + value[4:6], + value[6:8], + value[8:10], + value[10:16], + ), nil +} diff --git a/internal/store/memory_test.go b/internal/store/memory_test.go new file mode 100644 index 00000000..4d1c67a6 --- /dev/null +++ b/internal/store/memory_test.go @@ -0,0 +1,89 @@ +package store_test + +import ( + "errors" + "sync" + "testing" + + "gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/store" +) + +func TestCreateAndGetUser(t *testing.T) { + s := store.NewMemoryStore() + + created, err := s.CreateUser("alice", "Алиса") + if err != nil { + t.Fatalf("CreateUser: %v", err) + } + + if created.ID == "" { + t.Fatal("user ID is empty") + } + + if created.CreatedAt.IsZero() { + t.Fatal("creation time is empty") + } + + found, err := s.GetUser(created.ID) + if err != nil { + t.Fatalf("GetUser: %v", err) + } + + if found != created { + t.Fatalf("stored user differs: got %+v, want %+v", found, created) + } + + _, err = s.GetUser("00000000-0000-4000-8000-000000000000") + if !errors.Is(err, store.ErrUserNotFound) { + t.Fatalf("expected ErrUserNotFound, got %v", err) + } +} + +func TestConcurrentDuplicateUsername(t *testing.T) { + s := store.NewMemoryStore() + + const clients = 10 + + start := make(chan struct{}) + results := make(chan error, clients) + + var wg sync.WaitGroup + + for i := 0; i < clients; i++ { + wg.Add(1) + + go func() { + defer wg.Done() + + <-start + _, err := s.CreateUser("alice", "Алиса") + results <- err + }() + } + + close(start) + wg.Wait() + close(results) + + var created, conflicts int + + for err := range results { + switch { + case err == nil: + created++ + case errors.Is(err, store.ErrUsernameTaken): + conflicts++ + default: + t.Errorf("unexpected error: %v", err) + } + } + + if created != 1 || conflicts != clients-1 { + t.Fatalf( + "expected 1 creation and %d conflicts; got %d creations and %d conflicts", + clients-1, + created, + conflicts, + ) + } +} diff --git a/internal/store/postgres.go b/internal/store/postgres.go new file mode 100644 index 00000000..08aff21e --- /dev/null +++ b/internal/store/postgres.go @@ -0,0 +1,51 @@ +package store + +import ( + "context" + "errors" + "os" + "strings" + "time" + + "github.com/jackc/pgx/v5/pgxpool" +) + +func OpenPostgres(ctx context.Context, passwordFile string) (*pgxpool.Pool, error) { + password, err := os.ReadFile(passwordFile) + if err != nil { + return nil, errors.New("cannot read PostgreSQL password file") + } + secret := strings.TrimRight(string(password), "\r\n") + if secret == "" { + return nil, errors.New("PostgreSQL password file is empty") + } + + config, err := pgxpool.ParseConfig( + "host=postgres port=5432 dbname=messenger user=messenger sslmode=disable", + ) + if err != nil { + return nil, errors.New("invalid PostgreSQL configuration") + } + config.ConnConfig.Password = secret + config.ConnConfig.ConnectTimeout = 3 * time.Second + config.ConnConfig.RuntimeParams["statement_timeout"] = "3000" + config.ConnConfig.RuntimeParams["lock_timeout"] = "2000" + config.ConnConfig.RuntimeParams["application_name"] = "messenger-lab2" + config.MaxConns = 10 + config.MinConns = 0 + config.MaxConnLifetime = 30 * time.Minute + config.MaxConnIdleTime = 5 * time.Minute + + connectCtx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + + pool, err := pgxpool.NewWithConfig(connectCtx, config) + if err != nil { + return nil, errors.New("cannot create PostgreSQL pool") + } + if err := pool.Ping(connectCtx); err != nil { + pool.Close() + return nil, errors.New("PostgreSQL connection check failed") + } + return pool, nil +} diff --git a/internal/store/postgres_chats.go b/internal/store/postgres_chats.go new file mode 100644 index 00000000..9d0c0bf2 --- /dev/null +++ b/internal/store/postgres_chats.go @@ -0,0 +1,187 @@ +package store + +import ( + "context" + "errors" + "time" + + "gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/model" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgconn" +) + +type Position struct { + CreatedAt time.Time + ID string +} + +func (s *PostgresStore) CreateChat(ctx context.Context, title string, members []string) (model.Chat, error) { + ctx, cancel := context.WithTimeout(ctx, 3*time.Second) + defer cancel() + id, err := newUUID() + if err != nil { + return model.Chat{}, ErrUnavailable + } + tx, err := s.pool.Begin(ctx) + if err != nil { + return model.Chat{}, ErrUnavailable + } + defer tx.Rollback(context.Background()) + chat := model.Chat{ID: id, Title: title, MemberIDs: members} + err = tx.QueryRow(ctx, `INSERT INTO chats(id,title) VALUES($1,$2) RETURNING created_at`, id, title).Scan(&chat.CreatedAt) + if err != nil { + return model.Chat{}, ErrUnavailable + } + for _, member := range members { + _, err = tx.Exec(ctx, `INSERT INTO chat_members(chat_id,user_id) VALUES($1,$2)`, id, member) + if err != nil { + var pgErr *pgconn.PgError + if errors.As(err, &pgErr) && (pgErr.Code == "23503" || pgErr.Code == "23505") { + return model.Chat{}, ErrInvalidMembers + } + return model.Chat{}, ErrUnavailable + } + } + if err := tx.Commit(ctx); err != nil { + return model.Chat{}, ErrUnavailable + } + chat.CreatedAt = chat.CreatedAt.UTC() + return chat, nil +} + +const chatColumns = `c.id::text,c.title,c.created_at,ARRAY(SELECT m.user_id::text FROM chat_members m WHERE m.chat_id=c.id ORDER BY m.user_id)` + +func (s *PostgresStore) GetChat(ctx context.Context, actor, id string) (model.Chat, error) { + ctx, cancel := context.WithTimeout(ctx, 3*time.Second) + defer cancel() + var chat model.Chat + err := s.pool.QueryRow(ctx, `SELECT `+chatColumns+` FROM chats c WHERE c.id=$1 AND EXISTS(SELECT 1 FROM chat_members WHERE chat_id=c.id AND user_id=$2)`, id, actor).Scan(&chat.ID, &chat.Title, &chat.CreatedAt, &chat.MemberIDs) + if errors.Is(err, pgx.ErrNoRows) { + return model.Chat{}, ErrNotFound + } + if err != nil { + return model.Chat{}, ErrUnavailable + } + chat.CreatedAt = chat.CreatedAt.UTC() + return chat, nil +} + +func (s *PostgresStore) ChatPage(ctx context.Context, actor string, limit int, after *Position) ([]model.Chat, error) { + ctx, cancel := context.WithTimeout(ctx, 3*time.Second) + defer cancel() + query := `SELECT ` + chatColumns + ` FROM chats c WHERE EXISTS(SELECT 1 FROM chat_members WHERE chat_id=c.id AND user_id=$1)` + args := []any{actor, limit} + if after != nil { + query += ` AND (c.created_at,c.id)>($3,$4::uuid)` + args = append(args, after.CreatedAt, after.ID) + } + query += ` ORDER BY c.created_at,c.id LIMIT $2` + rows, err := s.pool.Query(ctx, query, args...) + if err != nil { + return nil, ErrUnavailable + } + defer rows.Close() + items := make([]model.Chat, 0) + for rows.Next() { + var chat model.Chat + if err := rows.Scan(&chat.ID, &chat.Title, &chat.CreatedAt, &chat.MemberIDs); err != nil { + return nil, ErrUnavailable + } + chat.CreatedAt = chat.CreatedAt.UTC() + items = append(items, chat) + } + if rows.Err() != nil { + return nil, ErrUnavailable + } + return items, nil +} + +var ErrIdempotencyConflict = errors.New("idempotency key already used for another message") + +func (s *PostgresStore) CreateMessage(ctx context.Context, actor, chatID, text, key string) (model.Message, error) { + ctx, cancel := context.WithTimeout(ctx, 3*time.Second) + defer cancel() + id, err := newUUID() + if err != nil { + return model.Message{}, ErrUnavailable + } + tx, err := s.pool.Begin(ctx) + if err != nil { + return model.Message{}, ErrUnavailable + } + defer tx.Rollback(context.Background()) + + var locked string + err = tx.QueryRow(ctx, `SELECT c.id::text FROM chats c WHERE c.id=$1 AND EXISTS(SELECT 1 FROM chat_members WHERE chat_id=c.id AND user_id=$2) FOR UPDATE OF c`, chatID, actor).Scan(&locked) + if errors.Is(err, pgx.ErrNoRows) { + return model.Message{}, ErrNotFound + } + if err != nil { + return model.Message{}, ErrUnavailable + } + var message model.Message + + err = tx.QueryRow(ctx, `SELECT m.id::text,m.chat_id::text,m.sender_id::text,m.text,m.created_at + FROM message_keys k JOIN messages m ON m.id=k.message_id + WHERE k.user_id=$1 AND k.chat_id=$2 AND k.key=$3 AND k.expires_at>clock_timestamp()`, + actor, chatID, key).Scan(&message.ID, &message.ChatID, &message.SenderID, &message.Text, &message.CreatedAt) + if err == nil { + if message.Text != text { + return model.Message{}, ErrIdempotencyConflict + } + message.CreatedAt = message.CreatedAt.UTC() + return message, nil + } + if !errors.Is(err, pgx.ErrNoRows) { + return model.Message{}, ErrUnavailable + } + err = tx.QueryRow(ctx, `INSERT INTO messages(id,chat_id,sender_id,text,created_at) + VALUES($1,$2,$3,$4,GREATEST(clock_timestamp(), + COALESCE((SELECT created_at + INTERVAL '1 microsecond' FROM messages WHERE chat_id=$2 ORDER BY created_at DESC,id DESC LIMIT 1),clock_timestamp()))) + RETURNING id::text,chat_id::text,sender_id::text,text,created_at`, id, chatID, actor, text).Scan(&message.ID, &message.ChatID, &message.SenderID, &message.Text, &message.CreatedAt) + if err != nil { + return model.Message{}, ErrUnavailable + } + _, err = tx.Exec(ctx, `INSERT INTO message_keys(user_id,chat_id,key,message_id,expires_at) + VALUES($1,$2,$3,$4,clock_timestamp()+INTERVAL '24 hours') + ON CONFLICT(user_id,chat_id,key) DO UPDATE + SET message_id=EXCLUDED.message_id,expires_at=EXCLUDED.expires_at`, actor, chatID, key, message.ID) + if err != nil { + return model.Message{}, ErrUnavailable + } + if err := tx.Commit(ctx); err != nil { + return model.Message{}, ErrUnavailable + } + message.CreatedAt = message.CreatedAt.UTC() + return message, nil +} + +func (s *PostgresStore) MessagePage(ctx context.Context, chatID string, limit int, after *Position) ([]model.Message, error) { + ctx, cancel := context.WithTimeout(ctx, 3*time.Second) + defer cancel() + query := `SELECT id::text,chat_id::text,sender_id::text,text,created_at FROM messages WHERE chat_id=$1` + args := []any{chatID, limit} + if after != nil { + query += ` AND (created_at,id)>($3,$4::uuid)` + args = append(args, after.CreatedAt, after.ID) + } + query += ` ORDER BY messages.created_at,messages.id LIMIT $2` + rows, err := s.pool.Query(ctx, query, args...) + if err != nil { + return nil, ErrUnavailable + } + defer rows.Close() + items := make([]model.Message, 0) + for rows.Next() { + var m model.Message + if err := rows.Scan(&m.ID, &m.ChatID, &m.SenderID, &m.Text, &m.CreatedAt); err != nil { + return nil, ErrUnavailable + } + m.CreatedAt = m.CreatedAt.UTC() + items = append(items, m) + } + if rows.Err() != nil { + return nil, ErrUnavailable + } + return items, nil +} diff --git a/internal/store/postgres_sessions.go b/internal/store/postgres_sessions.go new file mode 100644 index 00000000..4bc4dfc0 --- /dev/null +++ b/internal/store/postgres_sessions.go @@ -0,0 +1,69 @@ +package store + +import ( + "context" + "errors" + "time" + + "gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/model" + "github.com/jackc/pgx/v5" +) + +var ErrSessionNotFound = errors.New("session not found") + +func (s *PostgresStore) Credentials(ctx context.Context, username string) (model.User, string, error) { + ctx, cancel := context.WithTimeout(ctx, 3*time.Second) + defer cancel() + var user model.User + var hash string + err := s.pool.QueryRow(ctx, `SELECT id::text, username, display_name, created_at, password_hash FROM users WHERE username=$1`, username).Scan(&user.ID, &user.Username, &user.DisplayName, &user.CreatedAt, &hash) + if errors.Is(err, pgx.ErrNoRows) { + return model.User{}, "", ErrUserNotFound + } + if err != nil { + return model.User{}, "", ErrUnavailable + } + user.CreatedAt = user.CreatedAt.UTC() + return user, hash, nil +} + +func (s *PostgresStore) CreateSession(ctx context.Context, hash []byte, userID string, ttlSeconds int64) (time.Time, error) { + ctx, cancel := context.WithTimeout(ctx, 3*time.Second) + defer cancel() + var expires time.Time + err := s.pool.QueryRow(ctx, `INSERT INTO sessions (token_hash, user_id, expires_at) + VALUES ($1, $2, CURRENT_TIMESTAMP + $3::bigint * INTERVAL '1 second') RETURNING expires_at`, hash, userID, ttlSeconds).Scan(&expires) + if err != nil { + return time.Time{}, ErrUnavailable + } + return expires.UTC(), nil +} + +func (s *PostgresStore) SessionUser(ctx context.Context, hash []byte) (model.User, error) { + ctx, cancel := context.WithTimeout(ctx, 3*time.Second) + defer cancel() + var userID string + + err := s.pool.QueryRow(ctx, `SELECT user_id::text FROM sessions + WHERE token_hash=$1 AND expires_at > clock_timestamp()`, hash).Scan(&userID) + if errors.Is(err, pgx.ErrNoRows) { + return model.User{}, ErrSessionNotFound + } + if err != nil { + return model.User{}, ErrUnavailable + } + return s.profile(ctx, userID) +} + +func (s *PostgresStore) DeleteSession(ctx context.Context, hash []byte) error { + ctx, cancel := context.WithTimeout(ctx, 3*time.Second) + defer cancel() + tag, err := s.pool.Exec(ctx, `DELETE FROM sessions WHERE token_hash=$1 AND expires_at > clock_timestamp()`, hash) + if err != nil { + return ErrUnavailable + } + if tag.RowsAffected() == 0 { + return ErrSessionNotFound + } + return nil +} diff --git a/internal/store/postgres_users.go b/internal/store/postgres_users.go new file mode 100644 index 00000000..c5e0d9fe --- /dev/null +++ b/internal/store/postgres_users.go @@ -0,0 +1,86 @@ +package store + +import ( + "context" + "errors" + "time" + + "gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/model" + "github.com/jackc/pgx/v5/pgconn" + "github.com/jackc/pgx/v5/pgxpool" +) + +var ErrUnavailable = errors.New("storage unavailable") + +type ProfileCache interface { + Get(context.Context, string) (model.User, bool) + Set(context.Context, model.User) +} + +type PostgresStore struct { + pool *pgxpool.Pool + profiles ProfileCache +} + +func NewPostgresStore(pool *pgxpool.Pool) *PostgresStore { + return &PostgresStore{pool: pool} +} + +func (s *PostgresStore) WithProfiles(profiles ProfileCache) *PostgresStore { + s.profiles = profiles + return s +} + +func (s *PostgresStore) profile(ctx context.Context, id string) (model.User, error) { + if s.profiles != nil { + if user, ok := s.profiles.Get(ctx, id); ok { + return user, nil + } + } + var user model.User + err := s.pool.QueryRow(ctx, `SELECT id::text, username, display_name, created_at FROM users WHERE id=$1`, id).Scan( + &user.ID, &user.Username, &user.DisplayName, &user.CreatedAt, + ) + if err != nil { + return model.User{}, ErrUnavailable + } + user.CreatedAt = user.CreatedAt.UTC() + if s.profiles != nil { + s.profiles.Set(ctx, user) + } + return user, nil +} + +func (s *PostgresStore) CreateUser(ctx context.Context, username, displayName, passwordHash string) (model.User, error) { + id, err := newUUID() + if err != nil { + return model.User{}, errors.New("cannot generate user ID") + } + ctx, cancel := context.WithTimeout(ctx, 3*time.Second) + defer cancel() + var user model.User + err = s.pool.QueryRow(ctx, ` + INSERT INTO users (id, username, display_name, password_hash) + VALUES ($1, $2, $3, $4) + RETURNING id::text, username, display_name, created_at`, + id, username, displayName, passwordHash, + ).Scan(&user.ID, &user.Username, &user.DisplayName, &user.CreatedAt) + if err != nil { + var pgErr *pgconn.PgError + if errors.As(err, &pgErr) && pgErr.Code == "23505" && pgErr.ConstraintName == "users_username_key" { + return model.User{}, ErrUsernameTaken + } + return model.User{}, ErrUnavailable + } + user.CreatedAt = user.CreatedAt.UTC() + return user, nil +} + +func (s *PostgresStore) Ping(ctx context.Context) error { + ctx, cancel := context.WithTimeout(ctx, time.Second) + defer cancel() + if err := s.pool.Ping(ctx); err != nil { + return ErrUnavailable + } + return nil +} diff --git a/migrations/000001_initial.up.sql b/migrations/000001_initial.up.sql new file mode 100644 index 00000000..f1629c57 --- /dev/null +++ b/migrations/000001_initial.up.sql @@ -0,0 +1,49 @@ +CREATE TABLE users ( + id UUID PRIMARY KEY, + username TEXT NOT NULL UNIQUE, + display_name TEXT NOT NULL, + password_hash TEXT NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT users_username_format CHECK (username ~ '^[a-z0-9_]{3,32}$'), + CONSTRAINT users_display_name_length CHECK (char_length(display_name) BETWEEN 1 AND 100), + CONSTRAINT users_password_hash_not_empty CHECK (password_hash <> '') +); + +CREATE TABLE chats ( + id UUID PRIMARY KEY, + title TEXT NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT chats_title_length CHECK (char_length(title) BETWEEN 1 AND 100) +); + +CREATE TABLE 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 chat_members_user_chat_idx ON chat_members (user_id, chat_id); + +CREATE TABLE messages ( + id UUID PRIMARY KEY, + chat_id UUID NOT NULL, + sender_id UUID NOT NULL, + text TEXT NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT messages_sender_membership_fk + FOREIGN KEY (chat_id, sender_id) REFERENCES chat_members(chat_id, user_id), + CONSTRAINT messages_text_length CHECK (char_length(text) BETWEEN 1 AND 4000) +); + +CREATE INDEX messages_chat_history_idx ON messages (chat_id, created_at, id); + +CREATE TABLE sessions ( + token_hash BYTEA PRIMARY KEY, + user_id UUID NOT NULL REFERENCES users(id), + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + expires_at TIMESTAMPTZ NOT NULL, + CONSTRAINT sessions_token_hash_length CHECK (octet_length(token_hash) = 32), + CONSTRAINT sessions_expiry_after_creation CHECK (expires_at > created_at) +); + +CREATE INDEX sessions_expiry_idx ON sessions (expires_at); diff --git a/migrations/000002_message_keys.up.sql b/migrations/000002_message_keys.up.sql new file mode 100644 index 00000000..74bca7e4 --- /dev/null +++ b/migrations/000002_message_keys.up.sql @@ -0,0 +1,8 @@ +CREATE TABLE message_keys ( + user_id UUID NOT NULL REFERENCES users(id), + chat_id UUID NOT NULL REFERENCES chats(id), + key TEXT NOT NULL CHECK (key ~ '^[A-Za-z0-9._:-]{1,128}$'), + message_id UUID NOT NULL REFERENCES messages(id), + expires_at TIMESTAMPTZ NOT NULL, + PRIMARY KEY (user_id, chat_id, key) +); diff --git a/migrations/README.md b/migrations/README.md new file mode 100644 index 00000000..b0d1c4cd --- /dev/null +++ b/migrations/README.md @@ -0,0 +1,23 @@ +# Миграции + +`000001_initial.up.sql` создаёт начальную схему PostgreSQL: пять таблиц и индексы из проекта хранения. `apply.psql` применяет её через psql в контейнере. Применение на новом volume и пропуск версии при повторном запуске подтверждены [выводом пользователя](../evidence/postgres-migration.txt) от 09.10.2026. Конкурентное применение и откат при ошибке ещё не проверены. + +`apply.psql` открывает транзакцию, получает advisory lock, применяет SQL и записывает версию в служебную таблицу в той же транзакции. При ошибке psql завершает работу благодаря ON_ERROR_STOP; незавершённая транзакция откатывается при закрытии соединения. Повторный запуск пропускает применённую версию. Конкурентные запуски используют общий ключ блокировки (2026, 2); ожидание ограничено lock_timeout. Сейчас runner явно знает только версию 1; следующую миграцию нужно будет добавить в последовательность применения. + +Запуск из корня lab2 после готовности PostgreSQL: + +```powershell +docker compose exec -T postgres psql -X -U messenger -d messenger -f /migrations/apply.psql +``` + +Локальный psql подключается внутри контейнера через Unix socket. Для будущего API будет отдельное TCP-подключение с паролем. POSTGRES_USER создаётся официальным образом как bootstrap-superuser — учебное упрощение текущего этапа. + +Поэтому в SQL нет собственных BEGIN/COMMIT и нет CREATE TABLE IF NOT EXISTS: ответственность за однократное применение лежит на runner. IF NOT EXISTS не проверяет соответствие существующей таблицы ожидаемой схеме. После применения версии дальнейшие изменения оформляются новой миграцией. + +UUID передаёт приложение. created_at имеет значение по умолчанию CURRENT_TIMESTAMP (время начала транзакции PostgreSQL); при равном времени порядок задаёт id. TIMESTAMPTZ хранит момент времени, формат UTC для API задаёт приложение. База должна использовать UTF-8, чтобы char_length соответствовал подсчёту Unicode code points в контракте. + +CHECK ограничивает длины строк, но не заменяет проверку строк из одних Unicode-пробелов в Go. Проверка password_hash на непустоту не доказывает применение KDF; формирование и проверка Argon2id будут реализованы в приложении. token_hash хранит 32 байта SHA-256, не строку из 64 шестнадцатеричных символов. + +Внешний ключ messages(chat_id, sender_id) гарантирует существование членства отправителя. Он не заменяет проверку прав пользователя HTTP-запроса. Каскадное удаление не включено; удаления пользователей, чатов и участников обязательным API lab2 не предусмотрены. + +CHECK expires_at > created_at проверяет корректность срока, но не делает сессию автоматически недействительной: каждый защищённый запрос должен проверять expires_at относительно текущего времени. Удаление истёкших строк — отдельная очистка. diff --git a/migrations/apply.psql b/migrations/apply.psql new file mode 100644 index 00000000..46b28e40 --- /dev/null +++ b/migrations/apply.psql @@ -0,0 +1,38 @@ +\set ON_ERROR_STOP on + +BEGIN; +SET LOCAL lock_timeout = '10s'; +SET LOCAL statement_timeout = '30s'; + +-- All migration runners for this application must use this same lock key. +SELECT pg_advisory_xact_lock(2026, 2); + +CREATE TABLE IF NOT EXISTS schema_migrations ( + version BIGINT PRIMARY KEY, + applied_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP +); + +SELECT EXISTS ( + SELECT 1 FROM schema_migrations WHERE version = 1 +) AS initial_applied \gset + +\if :initial_applied + \echo 'Migration 000001 already applied; skipping.' +\else + \ir 000001_initial.up.sql + INSERT INTO schema_migrations (version) VALUES (1); + \echo 'Migration 000001 applied (commit follows).' +\endif + +SELECT EXISTS ( + SELECT 1 FROM schema_migrations WHERE version = 2 +) AS message_keys_applied \gset + +\if :message_keys_applied + \echo 'Migration 000002 already applied; skipping.' +\else + \ir 000002_message_keys.up.sql + INSERT INTO schema_migrations (version) VALUES (2); +\endif + +COMMIT; diff --git a/scripts/compose_actions.py b/scripts/compose_actions.py new file mode 100644 index 00000000..11b56152 --- /dev/null +++ b/scripts/compose_actions.py @@ -0,0 +1,38 @@ +"""Explicit local Compose hooks. No credentials or session tokens are printed.""" +import os +from pathlib import Path +import subprocess +import sys + +ROOT = Path(__file__).resolve().parent.parent + + +def docker(*args, capture=False): + return subprocess.run(["docker", *args], cwd=ROOT, check=True, + text=True, capture_output=capture) + + +def main(): + action = sys.argv[1] + if action == "restart": + # Stop all running application components before restarting shared stores. + docker("compose", "--env-file", ".env", "stop", "lb", "api", "redis", "postgres") + docker("compose", "--env-file", ".env", "up", "-d", "--wait", "--wait-timeout", "60") + elif action == "stop-one": + target = os.environ["TARGET_INSTANCE_ID"] + containers = docker("compose", "ps", "-q", "api", capture=True).stdout.split() + matches = [] + for container in containers: + alias = docker("exec", container, "/server", "instance-id", capture=True).stdout.strip() + if alias == target: + matches.append(container) + if len(matches) != 1: + raise RuntimeError("Expected exactly one API container for target alias") + # One second grace keeps this explicit failure hook within the test budget. + docker("stop", "--time", "1", matches[0]) + else: + raise ValueError("Unknown action") + + +if __name__ == "__main__": + main() diff --git a/scripts/init-local.ps1 b/scripts/init-local.ps1 new file mode 100644 index 00000000..8902107a --- /dev/null +++ b/scripts/init-local.ps1 @@ -0,0 +1,35 @@ +$ErrorActionPreference = 'Stop' + +$repoRoot = Split-Path -Parent $PSScriptRoot +$envPath = Join-Path $repoRoot '.env' +if (-not (Test-Path -LiteralPath $envPath)) { + Copy-Item -LiteralPath (Join-Path $repoRoot '.env.example') -Destination $envPath + Write-Output 'Local .env created (non-secret session TTL).' +} else { + Write-Output 'Existing .env preserved.' +} + +$secretsDirectory = Join-Path $repoRoot 'secrets' +$passwordPath = Join-Path $secretsDirectory 'postgres_password.txt' + +New-Item -ItemType Directory -Path $secretsDirectory -Force | Out-Null + +if (Test-Path -LiteralPath $passwordPath) { + if ((Get-Item -LiteralPath $passwordPath).Length -eq 0) { + throw 'Existing password file is empty. Supply a local password before starting PostgreSQL.' + } + Write-Output 'Existing PostgreSQL password preserved.' + exit 0 +} + +$randomBytes = New-Object byte[] 32 +$generator = [System.Security.Cryptography.RandomNumberGenerator]::Create() +try { + $generator.GetBytes($randomBytes) +} finally { + $generator.Dispose() +} + +$password = [Convert]::ToBase64String($randomBytes) +[System.IO.File]::WriteAllText($passwordPath, $password, [System.Text.Encoding]::ASCII) +Write-Output 'Local PostgreSQL password created in secrets/ (value not printed).' diff --git a/scripts/restart.cmd b/scripts/restart.cmd new file mode 100644 index 00000000..05bd011d --- /dev/null +++ b/scripts/restart.cmd @@ -0,0 +1,6 @@ +@echo off +if defined LAB_PYTHON ( + "%LAB_PYTHON%" -X utf8 "%~dp0compose_actions.py" restart +) else ( + py -X utf8 "%~dp0compose_actions.py" restart +) diff --git a/scripts/restart.sh b/scripts/restart.sh new file mode 100644 index 00000000..5718796b --- /dev/null +++ b/scripts/restart.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +cd "$(dirname "$0")/.." +exec python3 scripts/compose_actions.py restart diff --git a/scripts/stop-one.cmd b/scripts/stop-one.cmd new file mode 100644 index 00000000..0a2d6a32 --- /dev/null +++ b/scripts/stop-one.cmd @@ -0,0 +1,6 @@ +@echo off +if defined LAB_PYTHON ( + "%LAB_PYTHON%" -X utf8 "%~dp0compose_actions.py" stop-one +) else ( + py -X utf8 "%~dp0compose_actions.py" stop-one +) diff --git a/scripts/stop-one.sh b/scripts/stop-one.sh new file mode 100644 index 00000000..5d9e98cf --- /dev/null +++ b/scripts/stop-one.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +cd "$(dirname "$0")/.." +exec python3 scripts/compose_actions.py stop-one diff --git a/student-tests/contract_checks.py b/student-tests/contract_checks.py new file mode 100644 index 00000000..4fbadb25 --- /dev/null +++ b/student-tests/contract_checks.py @@ -0,0 +1,95 @@ +"""Additional Lab3 contract checks against the running stack. + +Only synthetic data are used. --database-checks additionally expires one key +created by this test using local Compose psql, to avoid waiting 24 hours. +""" +import argparse +from concurrent.futures import ThreadPoolExecutor +import json +from pathlib import Path +import subprocess +import sys +import uuid + +ROOT = Path(__file__).resolve().parent.parent +sys.path.insert(0, str(ROOT / "tests")) +from client import Client, check + + +def sql(statement): + return subprocess.run([ + "docker", "compose", "exec", "-T", "postgres", "psql", "-X", "-A", "-t", + "-v", "ON_ERROR_STOP=1", "-U", "messenger", "-d", "messenger", "-c", statement, + ], cwd=ROOT, check=True, capture_output=True, text=True).stdout.strip() + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--base-url", default="http://127.0.0.1:8084") + parser.add_argument("--database-checks", action="store_true") + args = parser.parse_args() + c = Client(args.base_url) + alice, bob, eve, chat = c.bootstrap() + path = "/api/v1/chats/" + chat["id"] + "/messages" + key = uuid.uuid4().hex + text = "Привет, мир" + first = c.message(alice, chat, text, key=key)["json"] + raw = (" " + json.dumps({"text": text}, ensure_ascii=True, indent=2) + "\n").encode() + replay = c.call("POST", path, 201, actor=alice, raw=raw, + headers={"Content-Type": "application/json", "Idempotency-Key": key}, + schema="Message")["json"] + check(first == replay, "Equivalent JSON changed replay result") + for invalid in ["", "a b", "\xe9", "a" * 129]: + c.call("POST", path, 400, actor=alice, body={"text": text}, + headers={"Idempotency-Key": invalid}) + c.message(alice, chat, "Maximum length key", key="a" * 128) + print("PASS: decoded JSON equality; invalid keys -> 400; 128-character key accepted") + + by_bob = c.message(bob, chat, text, key=key)["json"] + check(by_bob["id"] != first["id"], "Different users share an idempotency result") + other_chat = c.call("POST", "/api/v1/chats", 201, actor=alice, + body={"title": "Scope test", "member_ids": [alice["id"]]}, + schema="Chat")["json"] + by_chat = c.message(alice, other_chat, text, key=key)["json"] + check(by_chat["id"] != first["id"], "Different chats share an idempotency result") + c.call("POST", path, 404, actor=eve, body={"text": text}, headers={"Idempotency-Key": key}) + print("PASS: key scope is per user/chat; unauthorized chat replay -> 404") + + race_key = uuid.uuid4().hex + def conflicting(index): + local = Client(args.base_url) + return local.call("POST", path, [201, 409], actor=alice, + body={"text": "race-" + str(index % 2)}, + headers={"Idempotency-Key": race_key}, schema=None) + with ThreadPoolExecutor(max_workers=8) as pool: + results = list(pool.map(conflicting, range(16))) + check(sum(item["status"] == 201 for item in results) == 8, "Wrong number of winning replays") + check(sum(item["status"] == 409 for item in results) == 8, "Wrong number of conflicts") + check(len({item["headers"]["X-Instance-Id"] for item in results}) >= 2, + "Conflicting race did not span replicas") + history = c.call("GET", path + "?limit=100", actor=alice, schema="MessagePage")["json"]["items"] + check(sum(item["text"].startswith("race-") for item in history) == 1, "Conflicting race created duplicates") + print("PASS: concurrent different bodies -> eight 201 and eight 409; one new message") + + if args.database_checks: + # UUID conversion prevents server-returned IDs from becoming SQL syntax. + actor_id = str(uuid.UUID(alice["id"])) + chat_id = str(uuid.UUID(chat["id"])) + where = f"user_id='{actor_id}' AND chat_id='{chat_id}' AND key='{key}'" + check(sql("SELECT count(*) FROM message_keys WHERE " + where + + " AND expires_at>clock_timestamp()+INTERVAL '23 hours'") == "1", "Key TTL too short") + sql("UPDATE message_keys SET expires_at=clock_timestamp()-INTERVAL '1 second' WHERE " + where) + after_expiry = c.message(alice, chat, "New operation after expiry", key=key)["json"] + check(after_expiry["id"] != first["id"], "Expired key was not reusable") + check(c.message(alice, chat, "New operation after expiry", key=key)["json"] == after_expiry, + "New key cycle is not idempotent") + check(sql("SELECT count(*) FROM message_keys WHERE " + where) == "1", "Key replacement duplicated row") + print("PASS: TTL persisted; simulated expiry permits a new idempotent operation") + + c.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=alice) + c.call("POST", path, 401, actor=alice, body={"text": text}, headers={"Idempotency-Key": key}) + print("PASS: revoked session cannot replay a previous operation") + + +if __name__ == "__main__": + main() diff --git a/student-tests/dependency_checks.py b/student-tests/dependency_checks.py new file mode 100644 index 00000000..d3efb191 --- /dev/null +++ b/student-tests/dependency_checks.py @@ -0,0 +1,71 @@ +"""Verify shared-store failures or short session TTL; restores stopped stores.""" +import argparse +import json +from pathlib import Path +import subprocess +import sys +import time +import urllib.error +import urllib.request + +ROOT = Path(__file__).resolve().parent.parent +sys.path.insert(0, str(ROOT / "tests")) +from client import Client, check + + +def docker(*args): + return subprocess.run(["docker", *args], cwd=ROOT, check=True, + capture_output=True, text=True).stdout.strip() + + +def status(url): + try: + response = urllib.request.urlopen(url, timeout=5) + except urllib.error.HTTPError as error: + response = error + with response: + return response.status + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--base-url", default="http://127.0.0.1:8084") + parser.add_argument("--expiry", action="store_true", + help="Requires API SESSION_TTL_SECONDS=2, configured by the operator") + args = parser.parse_args() + client = Client(args.base_url) + actor = client.user("dependencies") + client.call("GET", "/api/v1/users/me", actor=actor, schema="User") + if args.expiry: + time.sleep(2.3) + aliases = set() + for _ in range(12): + response = client.call("GET", "/api/v1/users/me", 401, actor=actor) + aliases.add(response["headers"]["X-Instance-Id"]) + check(len(aliases) >= 2, "Expiry not observed through two replicas") + print("PASS: TTL=2 session rejected by both replicas without re-login") + return + + try: + docker("compose", "stop", "redis") + client.call("GET", "/api/v1/users/me", actor=actor, schema="User") + client.call("GET", "/health/ready", schema="Health") + print("PASS: Redis stopped; profile and readiness still return 200 via LB") + finally: + docker("compose", "up", "-d", "--wait", "--wait-timeout", "60", "redis") + + try: + docker("compose", "stop", "postgres") + check(status(args.base_url + "/health/ready") == 503, "PostgreSQL failure did not disable readiness") + # LB may exclude all APIs, so inspect liveness inside the Docker network. + live = docker("compose", "exec", "-T", "redis", "wget", "-q", "-O", "-", "http://api:8080/health/live") + check(json.loads(live) == {"status": "ok"}, "API process liveness failed") + print("PASS: PostgreSQL stopped; LB readiness=503, API process liveness=200") + finally: + docker("compose", "up", "-d", "--wait", "--wait-timeout", "60") + client.call("GET", "/api/v1/users/me", actor=actor, schema="User") + print("PASS: PostgreSQL restored; original session still valid") + + +if __name__ == "__main__": + main() diff --git a/student-tests/operations_load.py b/student-tests/operations_load.py new file mode 100644 index 00000000..4acfcb06 --- /dev/null +++ b/student-tests/operations_load.py @@ -0,0 +1,192 @@ +"""Run the unchanged public load generator during explicit API operations. + +Usage: python -X utf8 student-tests/operations_load.py baseline|stop1|stop2|rolling +Only synthetic HTTP data are created. Volumes and shared stores are preserved. +""" +import argparse +import json +from pathlib import Path +import subprocess +import sys +import time +import urllib.error +import urllib.request +import uuid + +ROOT = Path(__file__).resolve().parent.parent +BASE = "http://127.0.0.1:8084" +sys.path.insert(0, str(ROOT / "tests")) +from client import Client, Failure + + +def docker(*args): + return subprocess.run(["docker", *args], cwd=ROOT, check=True, + text=True, capture_output=True).stdout.strip() + + +def containers(): + ids = docker("compose", "ps", "-q", "api").split() + return sorted(ids, key=lambda item: docker("inspect", "--format", "{{.Name}}", item)) + + +def wait_visible(container): + deadline = time.monotonic() + 40 + alias = None + while time.monotonic() < deadline: + try: + if alias is None: + alias = docker("exec", container, "/server", "instance-id") + with urllib.request.urlopen(BASE + "/health/ready", timeout=2) as response: + if response.headers.get("X-Instance-Id") == alias: + return alias + except (subprocess.CalledProcessError, urllib.error.URLError, TimeoutError): + pass + time.sleep(0.2) + raise RuntimeError("API did not become visible through LB within 40 seconds") + + +def check_data(client, actor, chat, confirmed, action_started): + """Verify real history reads and writes after stop, not just health.""" + deadline = action_started + 10 + key = uuid.uuid4().hex + first_read = first_write = None + message = None + while time.monotonic() < deadline: + try: + history = client.call("GET", "/api/v1/chats/" + chat["id"] + "/messages?limit=100", + actor=actor, schema="MessagePage")["json"]["items"] + if any(item not in history for item in confirmed): + raise RuntimeError("Confirmed probe message lost") + if first_read is None: + first_read = time.monotonic() - action_started + except Failure: + pass + if message is None: + try: + message = client.message(actor, chat, "operation-probe-" + key, key=key)["json"] + first_write = time.monotonic() - action_started + except Failure: + pass + if first_read is not None and message is not None: + confirmed.append(message) + return {"read_recovery_seconds": round(first_read, 3), + "write_recovery_seconds": round(first_write, 3)} + time.sleep(0.1) + raise RuntimeError("History/read or message/write did not recover within 10 seconds") + + +def main(): + global BASE + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("mode", choices=["baseline", "stop1", "stop2", "rolling"]) + parser.add_argument("--base-url", default=BASE) + parser.add_argument("--output-dir", default="evidence") + parser.add_argument("--force-address-change", action="store_true", + help="During rolling, briefly reserve the removed IP to verify Docker DNS updates") + args = parser.parse_args() + mode = args.mode + BASE = args.base_url.rstrip("/") + evidence_dir = ROOT / args.output_dir + evidence_dir.mkdir(parents=True, exist_ok=True) + original = containers() + if len(original) != 2: + raise RuntimeError("Exactly two running APIs required") + for container in original: + wait_visible(container) + probe = Client(BASE, timeout=1) + actor, _, _, probe_chat = probe.bootstrap() + confirmed = [probe.message(actor, probe_chat, "confirmed-before-operation")["json"]] + duration = 50 if mode == "rolling" else 25 + output = evidence_dir / ("load-" + mode + ".json") + log = evidence_dir / ("load-" + mode + ".txt") + operations = [] + # Capture timestamps independently of load.py, whose elapsed interval starts + # after its own bootstrap. These are separate timing domains. + started = time.monotonic() + with log.open("w", encoding="utf-8") as stream: + process = subprocess.Popen([ + sys.executable, "-X", "utf8", "tests/load.py", "--base-url", BASE, + "--duration", str(duration), "--concurrency", "4", "--output", str(output), + ], cwd=ROOT, stdout=stream, stderr=subprocess.STDOUT) + try: + time.sleep(5) + if process.poll() is not None: + raise RuntimeError("Load generator stopped before operation") + if mode.startswith("stop"): + target = original[int(mode[-1]) - 1] + action_started = time.monotonic() + docker("stop", "--time", "1", target) + recovery = check_data(probe, actor, probe_chat, confirmed, action_started) + # Probe API availability after Docker has confirmed the stop. + survivor = next(item for item in original if item != target) + wait_visible(survivor) + operations.append({"action": "stop", "container": target, + "offset_seconds": round(action_started - started, 3), + "stop_and_ready_seconds": round(time.monotonic() - action_started, 3), + **recovery}) + elif mode == "rolling": + for target in original: + survivor = next(item for item in containers() if item != target) + networks = json.loads(docker("inspect", "--format", "{{json .NetworkSettings.Networks}}", target)) + network_name, network = next(iter(networks.items())) + old_ip = network["IPAddress"] + action_started = time.monotonic() + docker("stop", "--time", "15", target) + recovery = check_data(probe, actor, probe_chat, confirmed, action_started) + docker("rm", target) + holder = None + try: + if args.force_address_change: + holder = docker("run", "--rm", "-d", "--network", network_name, + "--ip", old_ip, "--cpus", "0.05", "--memory", "16m", + "--entrypoint", "/bin/sh", "redis:7.4.11-alpine", "-c", "sleep 120") + # Keep the survivor intact, create only the missing replica. + docker("compose", "up", "-d", "--no-deps", "--no-recreate", "--scale", "api=2", "api") + current = containers() + if survivor not in current or target in current or len(current) != 2: + raise RuntimeError("Replacement changed survivor or did not replace target") + replacement = next(item for item in current if item != survivor) + new_networks = json.loads(docker("inspect", "--format", "{{json .NetworkSettings.Networks}}", replacement)) + new_ip = new_networks[network_name]["IPAddress"] + if args.force_address_change and new_ip == old_ip: + raise RuntimeError("Replacement did not change IP") + alias = wait_visible(replacement) + finally: + if holder is not None: + docker("rm", "-f", holder) + operations.append({"action": "replace", "old_container": target, + "new_container": replacement, "new_instance_alias": alias, + "survivor_container": survivor, + "old_ip": old_ip, "new_ip": new_ip, + "offset_seconds": round(action_started - started, 3), + "replacement_ready_seconds": round(time.monotonic() - action_started, 3), + **recovery}) + if process.poll() is not None: + raise RuntimeError("Load did not span both replacements") + time.sleep(3) + code = process.wait(timeout=duration + 20) + if code != 0: + raise RuntimeError("Load failed; inspect " + str(log)) + history = probe.call("GET", "/api/v1/chats/" + probe_chat["id"] + "/messages?limit=100", + actor=actor, schema="MessagePage")["json"]["items"] + if len(history) != len(confirmed) or any(item not in history for item in confirmed): + raise RuntimeError("Final probe history lost messages or contains duplicates") + finally: + if process.poll() is None: + process.terminate() + process.wait(timeout=10) + docker("compose", "up", "-d", "--wait", "--wait-timeout", "60") + metadata = { + "mode": mode, "operations": operations, + "docker": json.loads(docker("info", "--format", '{"cpus":{{.NCPU}},"memory_bytes":{{.MemTotal}},"version":"{{.ServerVersion}}"}')), + "confirmed_probe_messages": len(confirmed), + "forced_address_change": args.force_address_change, + "note": "One run per mode, concurrency 4, shared load chat, no load POST retries; separate history/write probes retry with a stable key and validate confirmed data. Replacement uses the same image and no migrations.", + } + (evidence_dir / ("operations-" + mode + ".json")).write_text( + json.dumps(metadata, indent=2) + "\n", encoding="utf-8") + print(mode + ": PASS; metrics in " + str(output.relative_to(ROOT)), flush=True) + + +if __name__ == "__main__": + main() diff --git a/student-tests/replicas.py b/student-tests/replicas.py new file mode 100644 index 00000000..292859bf --- /dev/null +++ b/student-tests/replicas.py @@ -0,0 +1,77 @@ +"""Check shared sessions and concurrent idempotency through the public LB only. + +Creates synthetic data; never prints credentials or tokens. +""" +import argparse +import base64 +import concurrent.futures +import json +import urllib.error +import urllib.request +import uuid + +BASE = "http://127.0.0.1:8084" + + +def request(method, path, body=None, token=None, key=None, basic=None): + headers = {"Content-Type": "application/json"} + if token: + headers["Authorization"] = "Bearer " + token + if basic: + headers["Authorization"] = "Basic " + base64.b64encode(basic.encode()).decode() + if key is not None: + headers["Idempotency-Key"] = key + raw = None if body is None else json.dumps(body).encode() + req = urllib.request.Request(BASE + path, data=raw, headers=headers, method=method) + try: + response = urllib.request.urlopen(req, timeout=15) + except urllib.error.HTTPError as error: + response = error + with response: + return response.status, json.load(response), response.headers.get("X-Instance-Id") + + +def main(): + global BASE + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--base-url", default=BASE) + BASE = parser.parse_args().base_url.rstrip("/") + username = "r_" + uuid.uuid4().hex[:20] + password = uuid.uuid4().hex + status, user, _ = request("POST", "/api/v1/users", { + "username": username, "display_name": "Replica test", "password": password, + }) + assert status == 201, status + status, session, _ = request("POST", "/api/v1/auth/sessions", basic=username + ":" + password) + assert status == 201, status + token = session["token"] + instances = set() + for _ in range(20): + status, current, instance = request("GET", "/api/v1/users/me", token=token) + assert status == 200 and current["id"] == user["id"] + assert instance + instances.add(instance) + assert len(instances) >= 2, "Fewer than two API instances observed" + print("PASS: one session accepted by", len(instances), "API instances") + + status, chat, _ = request("POST", "/api/v1/chats", { + "title": "Concurrent retries", "member_ids": [user["id"]], + }, token=token) + assert status == 201, status + path = "/api/v1/chats/" + chat["id"] + "/messages" + key = uuid.uuid4().hex + with concurrent.futures.ThreadPoolExecutor(max_workers=8) as pool: + results = list(pool.map(lambda _: request("POST", path, {"text": "hello"}, token, key), range(16))) + original = results[0][1] + assert all(status == 201 and body == original for status, body, _ in results) + assert len({instance for _, _, instance in results}) >= 2 + assert request("POST", path, {"text": "different"}, token, key)[0] == 409 + assert request("POST", path, {"text": "hello"}, token)[0] == 400 + status, history, _ = request("GET", path, token=token) + assert status == 200 and history["items"] == [original] + print("PASS: 16 parallel retries across replicas returned the same Message; history has one item") + print("PASS: changed text -> 409; missing key -> 400") + + +if __name__ == "__main__": + main()