From 76322040e5047cb5a40088cbad18f7fffc4e2194 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=93=D0=BE=D0=BB=D0=B8=D0=BA=D0=BE=D0=B2=20Maximillian?= =?UTF-8?q?=20=D0=90=D0=BD=D1=82=D0=BE=D0=BD?= Date: Sun, 18 Oct 2026 21:14:01 +0300 Subject: [PATCH] import lab3 files --- Dockerfile | 29 +++ backend/cmd/server/main.go | 164 ++++++++++++++ backend/go.mod | 53 +++++ backend/go.sum | 138 ++++++++++++ backend/internal/config/config.go | 119 ++++++++++ backend/internal/domain/entity.go | 37 ++++ backend/internal/domain/errors.go | 105 +++++++++ backend/internal/domain/idempotency.go | 23 ++ backend/internal/domain/repository.go | 37 ++++ backend/internal/httpapi/dto/chat.go | 39 ++++ backend/internal/httpapi/dto/error.go | 82 +++++++ backend/internal/httpapi/dto/health.go | 5 + backend/internal/httpapi/dto/message.go | 41 ++++ backend/internal/httpapi/dto/session.go | 21 ++ backend/internal/httpapi/dto/user.go | 29 +++ backend/internal/httpapi/handler/auth.go | 77 +++++++ backend/internal/httpapi/handler/bind.go | 52 +++++ backend/internal/httpapi/handler/chat.go | 88 ++++++++ backend/internal/httpapi/handler/health.go | 54 +++++ backend/internal/httpapi/handler/message.go | 87 ++++++++ backend/internal/httpapi/handler/response.go | 44 ++++ backend/internal/httpapi/handler/user.go | 43 ++++ .../httpapi/middleware/auth_legacy.go | 38 ++++ backend/internal/httpapi/middleware/bearer.go | 70 ++++++ .../internal/httpapi/middleware/context.go | 30 +++ .../internal/httpapi/middleware/instance.go | 31 +++ .../internal/httpapi/middleware/requestid.go | 32 +++ backend/internal/httpapi/router.go | 50 +++++ backend/internal/service/chat.go | 95 ++++++++ backend/internal/service/message.go | 100 +++++++++ backend/internal/service/password.go | 112 ++++++++++ backend/internal/service/session.go | 127 +++++++++++ backend/internal/service/user.go | 78 +++++++ .../internal/storage/_legacy/memory/chat.go | 102 +++++++++ .../internal/storage/_legacy/memory/cursor.go | 47 ++++ .../storage/_legacy/memory/message.go | 93 ++++++++ .../storage/_legacy/memory/storage.go | 34 +++ .../internal/storage/_legacy/memory/user.go | 59 +++++ backend/internal/storage/postgres/chat.go | 195 +++++++++++++++++ backend/internal/storage/postgres/cursor.go | 46 ++++ backend/internal/storage/postgres/db.go | 75 +++++++ backend/internal/storage/postgres/errors.go | 71 ++++++ backend/internal/storage/postgres/message.go | 203 ++++++++++++++++++ backend/internal/storage/postgres/session.go | 59 +++++ backend/internal/storage/postgres/storage.go | 18 ++ backend/internal/storage/postgres/user.go | 76 +++++++ backend/internal/storage/redis/client.go | 33 +++ backend/internal/storage/redis/errors.go | 31 +++ backend/internal/storage/redis/session.go | 80 +++++++ backend/migrations/0001_init.sql | 67 ++++++ backend/migrations/0002_idempotency.sql | 35 +++ backend/migrations/embed.go | 6 + compose.yaml | 163 ++++++++++++++ infra/nginx.conf | 46 ++++ student-tests/README.md | 79 +++++++ student-tests/load-k6.js | 125 +++++++++++ student-tests/run_all.py | 26 +++ student-tests/seed_large.py | 82 +++++++ student-tests/seed_messages.py | 56 +++++ student-tests/test_auth.py | 81 +++++++ student-tests/test_cases.py | 112 ++++++++++ student-tests/test_concurrency.py | 81 +++++++ student-tests/test_expiry.py | 46 ++++ student-tests/test_resilience.py | 89 ++++++++ 64 files changed, 4446 insertions(+) create mode 100644 Dockerfile create mode 100644 backend/cmd/server/main.go create mode 100644 backend/go.mod create mode 100644 backend/go.sum create mode 100644 backend/internal/config/config.go create mode 100644 backend/internal/domain/entity.go create mode 100644 backend/internal/domain/errors.go create mode 100644 backend/internal/domain/idempotency.go create mode 100644 backend/internal/domain/repository.go create mode 100644 backend/internal/httpapi/dto/chat.go create mode 100644 backend/internal/httpapi/dto/error.go create mode 100644 backend/internal/httpapi/dto/health.go create mode 100644 backend/internal/httpapi/dto/message.go create mode 100644 backend/internal/httpapi/dto/session.go create mode 100644 backend/internal/httpapi/dto/user.go create mode 100644 backend/internal/httpapi/handler/auth.go create mode 100644 backend/internal/httpapi/handler/bind.go create mode 100644 backend/internal/httpapi/handler/chat.go create mode 100644 backend/internal/httpapi/handler/health.go create mode 100644 backend/internal/httpapi/handler/message.go create mode 100644 backend/internal/httpapi/handler/response.go create mode 100644 backend/internal/httpapi/handler/user.go create mode 100644 backend/internal/httpapi/middleware/auth_legacy.go create mode 100644 backend/internal/httpapi/middleware/bearer.go create mode 100644 backend/internal/httpapi/middleware/context.go create mode 100644 backend/internal/httpapi/middleware/instance.go create mode 100644 backend/internal/httpapi/middleware/requestid.go create mode 100644 backend/internal/httpapi/router.go create mode 100644 backend/internal/service/chat.go create mode 100644 backend/internal/service/message.go create mode 100644 backend/internal/service/password.go create mode 100644 backend/internal/service/session.go create mode 100644 backend/internal/service/user.go create mode 100644 backend/internal/storage/_legacy/memory/chat.go create mode 100644 backend/internal/storage/_legacy/memory/cursor.go create mode 100644 backend/internal/storage/_legacy/memory/message.go create mode 100644 backend/internal/storage/_legacy/memory/storage.go create mode 100644 backend/internal/storage/_legacy/memory/user.go create mode 100644 backend/internal/storage/postgres/chat.go create mode 100644 backend/internal/storage/postgres/cursor.go create mode 100644 backend/internal/storage/postgres/db.go create mode 100644 backend/internal/storage/postgres/errors.go create mode 100644 backend/internal/storage/postgres/message.go create mode 100644 backend/internal/storage/postgres/session.go create mode 100644 backend/internal/storage/postgres/storage.go create mode 100644 backend/internal/storage/postgres/user.go create mode 100644 backend/internal/storage/redis/client.go create mode 100644 backend/internal/storage/redis/errors.go create mode 100644 backend/internal/storage/redis/session.go create mode 100644 backend/migrations/0001_init.sql create mode 100644 backend/migrations/0002_idempotency.sql create mode 100644 backend/migrations/embed.go create mode 100644 compose.yaml create mode 100644 infra/nginx.conf create mode 100644 student-tests/README.md create mode 100644 student-tests/load-k6.js create mode 100644 student-tests/run_all.py create mode 100644 student-tests/seed_large.py create mode 100644 student-tests/seed_messages.py create mode 100644 student-tests/test_auth.py create mode 100644 student-tests/test_cases.py create mode 100644 student-tests/test_concurrency.py create mode 100644 student-tests/test_expiry.py create mode 100644 student-tests/test_resilience.py diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..1622925 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,29 @@ +FROM golang:1.26.1-alpine AS builder + +WORKDIR /src + +COPY backend/go.mod backend/go.sum ./ +RUN go mod download + +COPY backend/ . + +RUN CGO_ENABLED=0 GOOS=linux go build \ + -trimpath \ + -ldflags="-s -w" \ + -o /out/server \ + ./cmd/server + +FROM alpine:3.20 + +RUN adduser -D -u 1000 app + +COPY --from=builder /out/server /server + +EXPOSE 8080 + +USER app + +HEALTHCHECK --interval=10s --timeout=3s --start-period=5s --retries=3 \ + CMD wget -q -O - http://127.0.0.1:8080/health/live >/dev/null || exit 1 + +ENTRYPOINT ["/server"] \ No newline at end of file diff --git a/backend/cmd/server/main.go b/backend/cmd/server/main.go new file mode 100644 index 0000000..9302d29 --- /dev/null +++ b/backend/cmd/server/main.go @@ -0,0 +1,164 @@ +package main + +import ( + "context" + "errors" + "fmt" + "log" + "net/http" + "os" + "os/signal" + "strings" + "sync/atomic" + "syscall" + "time" + + "high-loud-apps-labs/internal/config" + "high-loud-apps-labs/internal/domain" + "high-loud-apps-labs/internal/httpapi" + "high-loud-apps-labs/internal/httpapi/handler" + "high-loud-apps-labs/internal/httpapi/middleware" + "high-loud-apps-labs/internal/service" + "high-loud-apps-labs/internal/storage/postgres" + redisstore "high-loud-apps-labs/internal/storage/redis" +) + +func main() { + if len(os.Args) > 1 && os.Args[1] == "migrate" { + if err := runMigrate(); err != nil { + log.Fatalf("миграции: %v", err) + } + return + } + + cfg, err := config.Load() + if err != nil { + log.Fatalf("конфигурация: %v", err) + } + + addr := cfg.Host + ":" + cfg.Port + + ctx := context.Background() + pool, err := postgres.Connect(ctx, postgres.Config{ + URL: cfg.DatabaseURL, + MaxConns: 10, + MinConns: 1, + MaxConnLifetime: time.Hour, + MaxConnIdleTime: 30 * time.Minute, + ConnectTimeout: 5 * time.Second, + }) + if err != nil { + log.Fatalf("БД: %v", err) + } + defer pool.Close() + + store := postgres.New(pool) + + sessionRepo, cachePing, closeSession := newSessionRepo(cfg, store) + defer closeSession() + + hasher := service.NewArgon2idHasher() + + userSvc := service.NewUserService(store.Users(), hasher) + sessionSvc := service.NewSessionService(store.Users(), sessionRepo, hasher, cfg.SessionTTL) + chatSvc := service.NewChatService(store.Chats(), store.Users()) + messageSvc := service.NewMessageService(store.Messages(), store.Chats(), cfg.IdempotencyTTL) + + healthChecks := []handler.HealthCheck{ + func(ctx context.Context) error { return pool.Ping(ctx) }, + } + if cachePing != nil { + healthChecks = append(healthChecks, cachePing) + } + + var ready atomic.Bool + ready.Store(true) + + router := httpapi.NewRouter( + httpapi.Handlers{ + Health: handler.NewHealthHandler(healthChecks...).WithReadyFlag(&ready), + User: handler.NewUserHandler(userSvc), + Chat: handler.NewChatHandler(chatSvc), + Message: handler.NewMessageHandler(messageSvc), + Auth: handler.NewAuthHandler(sessionSvc), + }, + middleware.BearerAuth(sessionSvc), + ) + + srv := &http.Server{Addr: addr, Handler: router} + + go func() { + log.Printf("Запускаем на %s (SESSION_STORE=%s)", addr, cfg.SessionStore) + if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) { + log.Fatalf("Ошибка запуска: %v", err) + } + }() + + quit := make(chan os.Signal, 1) + signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM) + <-quit + + log.Printf("Получен сигнал завершения; readiness выключен, drain %s", cfg.ShutdownDrain) + ready.Store(false) + + if cfg.ShutdownDrain > 0 { + time.Sleep(cfg.ShutdownDrain) + } + + log.Println("Drain завершён, останавливаем HTTP-сервер...") + shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + if err := srv.Shutdown(shutdownCtx); err != nil { + log.Fatalf("Ошибка при остановке: %v", err) + } + log.Println("Сервер остановлен") +} + +// runMigrate — одноразовый прогон goose. Запускается как `/server migrate`. +// Использует те же DATABASE_URL_FILE / DATABASE_URL, что и сервер. +// Отдельный процесс, поэтому не конкурирует с репликами за goose lock. +func runMigrate() error { + cfg, err := config.Load() + if err != nil { + return fmt.Errorf("конфигурация: %w", err) + } + + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) + defer cancel() + + pool, err := postgres.Connect(ctx, postgres.Config{ + URL: cfg.DatabaseURL, + ConnectTimeout: 5 * time.Second, + }) + if err != nil { + return fmt.Errorf("БД: %w", err) + } + defer pool.Close() + + if err := postgres.RunMigrations(ctx, pool); err != nil { + return fmt.Errorf("применение миграций: %w", err) + } + return nil +} + +func newSessionRepo(cfg *config.Config, store *postgres.Storage) (domain.SessionRepository, handler.HealthCheck, func()) { + switch strings.ToLower(cfg.SessionStore) { + case "", "postgres": + return store.Sessions(), nil, func() {} + case "redis": + if cfg.CacheURL == "" { + log.Fatalf("SESSION_STORE=%s требует CACHE_URL_FILE или CACHE_URL", cfg.SessionStore) + } + client, err := redisstore.NewClient(cfg.CacheURL) + if err != nil { + log.Fatalf("redis: %v", err) + } + ping := func(ctx context.Context) error { + return client.Ping(ctx).Err() + } + return redisstore.NewSessionRepo(client), ping, func() { _ = client.Close() } + default: + log.Fatalf("SESSION_STORE=%q не поддерживается", cfg.SessionStore) + return nil, nil, nil + } +} diff --git a/backend/go.mod b/backend/go.mod new file mode 100644 index 0000000..12d34e9 --- /dev/null +++ b/backend/go.mod @@ -0,0 +1,53 @@ +module high-loud-apps-labs + +go 1.26.1 + +require ( + github.com/gin-gonic/gin v1.12.0 + github.com/google/uuid v1.6.0 + github.com/jackc/pgerrcode v0.0.0-20250907135507-afb5586c32a6 + github.com/jackc/pgx/v5 v5.7.1 + github.com/pressly/goose/v3 v3.22.1 + golang.org/x/crypto v0.57.0 +) + +require ( + github.com/bytedance/gopkg v0.1.3 // indirect + github.com/bytedance/sonic v1.15.0 // indirect + github.com/bytedance/sonic/loader v0.5.0 // indirect + github.com/cespare/xxhash/v2 v2.3.0 // indirect + github.com/cloudwego/base64x v0.1.6 // indirect + github.com/gabriel-vasile/mimetype v1.4.12 // indirect + github.com/gin-contrib/sse v1.1.0 // indirect + github.com/go-playground/locales v0.14.1 // indirect + github.com/go-playground/universal-translator v0.18.1 // indirect + github.com/go-playground/validator/v10 v10.30.1 // indirect + github.com/goccy/go-json v0.10.5 // indirect + github.com/goccy/go-yaml v1.19.2 // indirect + github.com/jackc/pgpassfile v1.0.0 // indirect + github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect + github.com/jackc/puddle/v2 v2.2.2 // indirect + github.com/json-iterator/go v1.1.12 // indirect + github.com/klauspost/cpuid/v2 v2.3.0 // indirect + github.com/leodido/go-urn v1.4.0 // indirect + github.com/mattn/go-isatty v0.0.20 // indirect + github.com/mfridman/interpolate v0.0.2 // indirect + github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect + github.com/modern-go/reflect2 v1.0.2 // indirect + github.com/pelletier/go-toml/v2 v2.2.4 // indirect + github.com/quic-go/qpack v0.6.0 // indirect + github.com/quic-go/quic-go v0.59.0 // indirect + github.com/redis/go-redis/v9 v9.22.0 // indirect + github.com/sethvargo/go-retry v0.3.0 // indirect + github.com/twitchyliquid64/golang-asm v0.15.1 // indirect + github.com/ugorji/go/codec v1.3.1 // indirect + go.mongodb.org/mongo-driver/v2 v2.5.0 // indirect + go.uber.org/atomic v1.11.0 // indirect + go.uber.org/multierr v1.11.0 // indirect + golang.org/x/arch v0.22.0 // indirect + golang.org/x/net v0.58.0 // indirect + golang.org/x/sync v0.23.0 // indirect + golang.org/x/sys v0.48.0 // indirect + golang.org/x/text v0.42.0 // indirect + google.golang.org/protobuf v1.36.10 // indirect +) diff --git a/backend/go.sum b/backend/go.sum new file mode 100644 index 0000000..ae83588 --- /dev/null +++ b/backend/go.sum @@ -0,0 +1,138 @@ +github.com/bytedance/gopkg v0.1.3 h1:TPBSwH8RsouGCBcMBktLt1AymVo2TVsBVCY4b6TnZ/M= +github.com/bytedance/gopkg v0.1.3/go.mod h1:576VvJ+eJgyCzdjS+c4+77QF3p7ubbtiKARP3TxducM= +github.com/bytedance/sonic v1.15.0 h1:/PXeWFaR5ElNcVE84U0dOHjiMHQOwNIx3K4ymzh/uSE= +github.com/bytedance/sonic v1.15.0/go.mod h1:tFkWrPz0/CUCLEF4ri4UkHekCIcdnkqXw9VduqpJh0k= +github.com/bytedance/sonic/loader v0.5.0 h1:gXH3KVnatgY7loH5/TkeVyXPfESoqSBSBEiDd5VjlgE= +github.com/bytedance/sonic/loader v0.5.0/go.mod h1:AR4NYCk5DdzZizZ5djGqQ92eEhCCcdf5x77udYiSJRo= +github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= +github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/cloudwego/base64x v0.1.6 h1:t11wG9AECkCDk5fMSoxmufanudBtJ+/HemLstXDLI2M= +github.com/cloudwego/base64x v0.1.6/go.mod h1:OFcloc187FXDaYHvrNIjxSe8ncn0OOM8gEHfghB2IPU= +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/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= +github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= +github.com/gabriel-vasile/mimetype v1.4.12 h1:e9hWvmLYvtp846tLHam2o++qitpguFiYCKbn0w9jyqw= +github.com/gabriel-vasile/mimetype v1.4.12/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s= +github.com/gin-contrib/sse v1.1.0 h1:n0w2GMuUpWDVp7qSpvze6fAu9iRxJY4Hmj6AmBOU05w= +github.com/gin-contrib/sse v1.1.0/go.mod h1:hxRZ5gVpWMT7Z0B0gSNYqqsSCNIJMjzvm6fqCz9vjwM= +github.com/gin-gonic/gin v1.12.0 h1:b3YAbrZtnf8N//yjKeU2+MQsh2mY5htkZidOM7O0wG8= +github.com/gin-gonic/gin v1.12.0/go.mod h1:VxccKfsSllpKshkBWgVgRniFFAzFb9csfngsqANjnLc= +github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s= +github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= +github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA= +github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= +github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY= +github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY= +github.com/go-playground/validator/v10 v10.30.1 h1:f3zDSN/zOma+w6+1Wswgd9fLkdwy06ntQJp0BBvFG0w= +github.com/go-playground/validator/v10 v10.30.1/go.mod h1:oSuBIQzuJxL//3MelwSLD5hc2Tu889bF0Idm9Dg26cM= +github.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4= +github.com/goccy/go-json v0.10.5/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M= +github.com/goccy/go-yaml v1.19.2 h1:PmFC1S6h8ljIz6gMRBopkjP1TVT7xuwrButHID66PoM= +github.com/goccy/go-yaml v1.19.2/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA= +github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= +github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= +github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k= +github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM= +github.com/jackc/pgerrcode v0.0.0-20250907135507-afb5586c32a6 h1:D/V0gu4zQ3cL2WKeVNVM4r2gLxGGf6McLwgXzRTo2RQ= +github.com/jackc/pgerrcode v0.0.0-20250907135507-afb5586c32a6/go.mod h1:a/s9Lp5W7n/DD0VrVoyJ00FbP2ytTPDVOivvn2bMlds= +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.1 h1:x7SYsPBYDkHDksogeSmZZ5xzThcTgRz++I5E+ePFUcs= +github.com/jackc/pgx/v5 v5.7.1/go.mod h1:e7O26IywZZ+naJtWWos6i6fvWK+29etgITqrqHLfoZA= +github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo= +github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= +github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= +github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= +github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y= +github.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0= +github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ= +github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI= +github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= +github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/mfridman/interpolate v0.0.2 h1:pnuTK7MQIxxFz1Gr+rjSIx9u7qVjf5VOoM/u6BbAxPY= +github.com/mfridman/interpolate v0.0.2/go.mod h1:p+7uk6oE07mpE/Ik1b8EckO0O4ZXiGAfshKBWLUM9Xg= +github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= +github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= +github.com/ncruces/go-strftime v0.1.9 h1:bY0MQC28UADQmHmaF5dgpLmImcShSi2kHU9XLdhx/f4= +github.com/ncruces/go-strftime v0.1.9/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls= +github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4= +github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/pressly/goose/v3 v3.22.1 h1:2zICEfr1O3yTP9BRZMGPj7qFxQ+ik6yeo+z1LMuioLc= +github.com/pressly/goose/v3 v3.22.1/go.mod h1:xtMpbstWyCpyH+0cxLTMCENWBG+0CSxvTsXhW95d5eo= +github.com/quic-go/qpack v0.6.0 h1:g7W+BMYynC1LbYLSqRt8PBg5Tgwxn214ZZR34VIOjz8= +github.com/quic-go/qpack v0.6.0/go.mod h1:lUpLKChi8njB4ty2bFLX2x4gzDqXwUpaO1DP9qMDZII= +github.com/quic-go/quic-go v0.59.0 h1:OLJkp1Mlm/aS7dpKgTc6cnpynnD2Xg7C1pwL6vy/SAw= +github.com/quic-go/quic-go v0.59.0/go.mod h1:upnsH4Ju1YkqpLXC305eW3yDZ4NfnNbmQRCMWS58IKU= +github.com/redis/go-redis/v9 v9.22.0 h1:laDvpYXTJtZLloinw1fA5Kqd6HAEH2XKxOkG/PDq2F0= +github.com/redis/go-redis/v9 v9.22.0/go.mod h1:y2g0Wj8rQvuK0ELM+oxSudcLtC09JScs98I/X9gRWY4= +github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE= +github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= +github.com/sethvargo/go-retry v0.3.0 h1:EEt31A35QhrcRZtrYFDTBg91cqZVnFL2navjDrah2SE= +github.com/sethvargo/go-retry v0.3.0/go.mod h1:mNX17F0C/HguQMyMyJxcnU471gOZGxCLyYaFyAZraas= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= +github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= +github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= +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.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= +github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI= +github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08= +github.com/ugorji/go/codec v1.3.1 h1:waO7eEiFDwidsBN6agj1vJQ4AG7lh2yqXyOXqhgQuyY= +github.com/ugorji/go/codec v1.3.1/go.mod h1:pRBVtBSKl77K30Bv8R2P+cLSGaTtex6fsA2Wjqmfxj4= +go.mongodb.org/mongo-driver/v2 v2.5.0 h1:yXUhImUjjAInNcpTcAlPHiT7bIXhshCTL3jVBkF3xaE= +go.mongodb.org/mongo-driver/v2 v2.5.0/go.mod h1:yOI9kBsufol30iFsl1slpdq1I0eHPzybRWdyYUs8K/0= +go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE= +go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0= +go.uber.org/mock v0.6.0 h1:hyF9dfmbgIX5EfOdasqLsWD6xqpNZlXblLB/Dbnwv3Y= +go.uber.org/mock v0.6.0/go.mod h1:KiVJ4BqZJaMj4svdfmHM0AUx4NJYO8ZNpPnZn1Z+BBU= +go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= +go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= +golang.org/x/arch v0.22.0 h1:c/Zle32i5ttqRXjdLyyHZESLD/bB90DCU1g9l/0YBDI= +golang.org/x/arch v0.22.0/go.mod h1:dNHoOeKiyja7GTvF9NJS1l3Z2yntpQNzgrjh1cU103A= +golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M= +golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA= +golang.org/x/net v0.58.0 h1:ynWG7rqYi4ccpTEuPZ2QGWHktVEM9DMCj9yzDE0Q7To= +golang.org/x/net v0.58.0/go.mod h1:YwCddHnFlT7eLQqVprV19OnhLGtc5xOKgE0RyqgfWAU= +golang.org/x/sync v0.23.0 h1:KameEIfc1IkluZyXWLn39Wd4tURc6GbCiISGiZm2bQk= +golang.org/x/sync v0.23.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= +golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo= +golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= +golang.org/x/text v0.42.0 h1:JbOZXgfeCPU9gacVtYliJqOhD+zhrEqK4LfdpmlUZqI= +golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E= +google.golang.org/protobuf v1.36.10 h1:AYd7cD/uASjIL6Q9LiTjz8JLcrh/88q5UObnmY3aOOE= +google.golang.org/protobuf v1.36.10/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= +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= +modernc.org/gc/v3 v3.0.0-20240107210532-573471604cb6 h1:5D53IMaUuA5InSeMu9eJtlQXS2NxAhyWQvkKEgXZhHI= +modernc.org/gc/v3 v3.0.0-20240107210532-573471604cb6/go.mod h1:Qz0X07sNOR1jWYCrJMEnbW/X55x206Q7Vt4mz6/wHp4= +modernc.org/mathutil v1.6.0 h1:fRe9+AmYlaej+64JsEEhoWuAYBkOtQiMEU7n/XgfYi4= +modernc.org/mathutil v1.6.0/go.mod h1:Ui5Q9q1TR2gFm0AQRqQUaBWFLAhQpCwNcuhBOSedWPo= +modernc.org/memory v1.8.0 h1:IqGTL6eFMaDZZhEWwcREgeMXYwmW83LYW8cROZYkg+E= +modernc.org/memory v1.8.0/go.mod h1:XPZ936zp5OMKGWPqbD3JShgd/ZoQ7899TUuQqxY+peU= +modernc.org/sqlite v1.33.0 h1:WWkA/T2G17okiLGgKAj4/RMIvgyMT19yQ038160IeYk= +modernc.org/sqlite v1.33.0/go.mod h1:9uQ9hF/pCZoYZK73D/ud5Z7cIRIILSZI8NdIemVMTX8= +modernc.org/strutil v1.2.0 h1:agBi9dp1I+eOnxXeiZawM8F4LawKv4NzGWSaLfyeNZA= +modernc.org/strutil v1.2.0/go.mod h1:/mdcBmfOibveCTBxUl5B5l6W+TTH1FXPLHZE6bTosX0= +modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y= +modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM= diff --git a/backend/internal/config/config.go b/backend/internal/config/config.go new file mode 100644 index 0000000..3541ffc --- /dev/null +++ b/backend/internal/config/config.go @@ -0,0 +1,119 @@ +package config + +import ( + "fmt" + "os" + "strconv" + "strings" + "time" +) + +type Config struct { + Host string + Port string + DatabaseURL string + SessionStore string + CacheURL string + SessionTTL time.Duration + IdempotencyTTL time.Duration + ShutdownDrain time.Duration +} + +func Load() (*Config, error) { + dsn, err := readSecret("DATABASE_URL_FILE", "DATABASE_URL") + if err != nil { + return nil, fmt.Errorf("database url: %w", err) + } + + cacheURL, err := readSecretOptional("CACHE_URL_FILE", "CACHE_URL") + if err != nil { + return nil, fmt.Errorf("cache url: %w", err) + } + + ttlSeconds, err := readInt("SESSION_TTL_SECONDS", 3600) + if err != nil { + return nil, fmt.Errorf("SESSION_TTL_SECONDS: %w", err) + } + if ttlSeconds <= 0 { + return nil, fmt.Errorf("SESSION_TTL_SECONDS должен быть положительным") + } + + idemSeconds, err := readInt("IDEMPOTENCY_TTL_SECONDS", 86400) + if err != nil { + return nil, fmt.Errorf("IDEMPOTENCY_TTL_SECONDS: %w", err) + } + if idemSeconds <= 0 { + return nil, fmt.Errorf("IDEMPOTENCY_TTL_SECONDS должен быть положительным") + } + + drainSeconds, err := readInt("SHUTDOWN_DRAIN_SECONDS", 3) + if err != nil { + return nil, fmt.Errorf("SHUTDOWN_DRAIN_SECONDS: %w", err) + } + if drainSeconds < 0 { + return nil, fmt.Errorf("SHUTDOWN_DRAIN_SECONDS не может быть отрицательным") + } + + store := strings.ToLower(getenv("SESSION_STORE", "postgres")) + switch store { + case "postgres", "redis", "valkey": + default: + return nil, fmt.Errorf("SESSION_STORE=%q не поддерживается", store) + } + + return &Config{ + Host: getenv("APP_HOST", "0.0.0.0"), + Port: getenv("APP_PORT", "8080"), + DatabaseURL: dsn, + SessionStore: store, + CacheURL: cacheURL, + SessionTTL: time.Duration(ttlSeconds) * time.Second, + IdempotencyTTL: time.Duration(idemSeconds) * time.Second, + ShutdownDrain: time.Duration(drainSeconds) * time.Second, + }, nil +} + +func getenv(key, def string) string { + if v := os.Getenv(key); v != "" { + return v + } + return def +} + +func readInt(key string, def int) (int, error) { + v := os.Getenv(key) + if v == "" { + return def, nil + } + n, err := strconv.Atoi(v) + if err != nil { + return 0, fmt.Errorf("не целое число: %q", v) + } + return n, nil +} + +func readSecret(fileEnv, envKey string) (string, error) { + v, err := readSecretOptional(fileEnv, envKey) + if err != nil { + return "", err + } + if v == "" { + return "", fmt.Errorf("не задан %s или %s", fileEnv, envKey) + } + return v, nil +} + +func readSecretOptional(fileEnv, envKey string) (string, error) { + if path := os.Getenv(fileEnv); path != "" { + b, err := os.ReadFile(path) + if err != nil { + return "", fmt.Errorf("чтение %s=%s: %w", fileEnv, path, err) + } + s := strings.TrimSpace(string(b)) + if s == "" { + return "", fmt.Errorf("файл %s пуст", path) + } + return s, nil + } + return os.Getenv(envKey), nil +} diff --git a/backend/internal/domain/entity.go b/backend/internal/domain/entity.go new file mode 100644 index 0000000..6af9812 --- /dev/null +++ b/backend/internal/domain/entity.go @@ -0,0 +1,37 @@ +package domain + +import "time" + +type Health struct { + Status string +} + +type User struct { + ID string + Username string + DisplayName string + PasswordHash string // в DTO UserResponse его не будет + CreatedAt time.Time +} + +type Chat struct { + ID string + Title string + MemberIDs []string + CreatedAt time.Time +} + +type Message struct { + ID string + ChatID string + SenderID string + Text string + CreatedAt time.Time +} + +type Session struct { + TokenHash []byte + UserID string + ExpiresAt time.Time + CreatedAt time.Time +} diff --git a/backend/internal/domain/errors.go b/backend/internal/domain/errors.go new file mode 100644 index 0000000..0ec6795 --- /dev/null +++ b/backend/internal/domain/errors.go @@ -0,0 +1,105 @@ +package domain + +import ( + "errors" + "fmt" +) + +type ErrorCode string + +const ( + CodeInvalidRequest ErrorCode = "invalid_request" + CodeUnauthorized ErrorCode = "unauthorized" + CodeNotFound ErrorCode = "not_found" + CodeConflict ErrorCode = "conflict" + CodeUnsupportedMediaType ErrorCode = "unsupported_media_type" + CodeInternalError ErrorCode = "internal_error" + CodeUnavailable ErrorCode = "unavailable" +) + +var ( + ErrNotFound = errors.New("не найдено") + ErrAlreadyExists = errors.New("уже существует") + ErrInvalidInput = errors.New("некорректные данные") + ErrUnauthorized = errors.New("требуется аутентификация") + ErrUnsupportedMediaType = errors.New("неподдерживаемый тип содержимого") + ErrUnavailable = errors.New("сервис недоступен") +) + +type NotFoundError struct { + Entity string + ID string +} + +func (e *NotFoundError) Error() string { + return fmt.Sprintf("%s с id %q не найден", e.Entity, e.ID) +} +func (e *NotFoundError) Unwrap() error { return ErrNotFound } +func (e *NotFoundError) Code() ErrorCode { return CodeNotFound } + +type AlreadyExistsError struct { + Entity string + Field string + Value string +} + +func (e *AlreadyExistsError) Error() string { + return fmt.Sprintf("%s с %s %q уже существует", e.Entity, e.Field, e.Value) +} +func (e *AlreadyExistsError) Unwrap() error { return ErrAlreadyExists } +func (e *AlreadyExistsError) Code() ErrorCode { return CodeConflict } + +type IdempotencyConflictError struct { + Key string +} + +func (e *IdempotencyConflictError) Error() string { + return "Idempotency-Key " + e.Key + " уже использован с другим телом запроса" +} + +func (e *IdempotencyConflictError) Unwrap() error { return ErrAlreadyExists } +func (e *IdempotencyConflictError) Code() ErrorCode { return CodeConflict } + +type ValidationError struct { + Field string + Message string +} + +func (e *ValidationError) Error() string { + return fmt.Sprintf("ошибка валидации поля %q: %s", e.Field, e.Message) +} +func (e *ValidationError) Unwrap() error { return ErrInvalidInput } +func (e *ValidationError) Code() ErrorCode { return CodeInvalidRequest } + +type UnauthorizedError struct { + Reason string // для логов; в JSON не попадает +} + +func (e *UnauthorizedError) Error() string { + return "требуется аутентификация" +} +func (e *UnauthorizedError) Unwrap() error { return ErrUnauthorized } +func (e *UnauthorizedError) Code() ErrorCode { return CodeUnauthorized } + +type UnsupportedMediaTypeError struct { + MediaType string +} + +func (e *UnsupportedMediaTypeError) Error() string { + if e.MediaType == "" { + return "требуется Content-Type: application/json" + } + return fmt.Sprintf("неподдерживаемый Content-Type %q; требуется application/json", e.MediaType) +} +func (e *UnsupportedMediaTypeError) Unwrap() error { return ErrUnsupportedMediaType } +func (e *UnsupportedMediaTypeError) Code() ErrorCode { return CodeUnsupportedMediaType } + +type UnavailableError struct { + Reason string // для логов; в JSON не попадает +} + +func (e *UnavailableError) Error() string { + return "сервис временно недоступен" +} +func (e *UnavailableError) Unwrap() error { return ErrUnavailable } +func (e *UnavailableError) Code() ErrorCode { return CodeUnavailable } diff --git a/backend/internal/domain/idempotency.go b/backend/internal/domain/idempotency.go new file mode 100644 index 0000000..f7616d9 --- /dev/null +++ b/backend/internal/domain/idempotency.go @@ -0,0 +1,23 @@ +package domain + +import ( + "crypto/sha256" +) + +type IdempotencyScope struct { + UserID string + Method string + Path string + Key string +} + +type CreateIdempotentResult struct { + Status int + Body []byte + Replayed bool +} + +func RequestHash(text string) []byte { + sum := sha256.Sum256([]byte(text)) + return sum[:] +} diff --git a/backend/internal/domain/repository.go b/backend/internal/domain/repository.go new file mode 100644 index 0000000..f26793a --- /dev/null +++ b/backend/internal/domain/repository.go @@ -0,0 +1,37 @@ +package domain + +import ( + "context" + "time" +) + +type UserRepository interface { + Create(ctx context.Context, user *User) error + GetByID(ctx context.Context, id string) (*User, error) + GetByUsername(ctx context.Context, username string) (*User, error) +} + +type ChatRepository interface { + Create(ctx context.Context, chat *Chat) error + GetByID(ctx context.Context, id string) (*Chat, error) + ListByMember(ctx context.Context, userID string, limit int, cursor *string) ([]Chat, *string, error) +} + +type MessageRepository interface { + Create(ctx context.Context, message *Message) error + ListByChat(ctx context.Context, chatID string, limit int, cursor *string) ([]Message, *string, error) + CreateIdempotent( + ctx context.Context, + scope IdempotencyScope, + requestHash []byte, + fresh *Message, + freshResponse []byte, + ttl time.Duration, + ) (*CreateIdempotentResult, error) +} + +type SessionRepository interface { + Create(ctx context.Context, session *Session) error + GetByTokenHash(ctx context.Context, tokenHash []byte) (*Session, error) + DeleteByTokenHash(ctx context.Context, tokenHash []byte) error +} diff --git a/backend/internal/httpapi/dto/chat.go b/backend/internal/httpapi/dto/chat.go new file mode 100644 index 0000000..a9bf042 --- /dev/null +++ b/backend/internal/httpapi/dto/chat.go @@ -0,0 +1,39 @@ +package dto + +import ( + "high-loud-apps-labs/internal/domain" +) + +type CreateChatRequest struct { + Title string `json:"title" binding:"required,min=1,max=100"` + MemberIDs []string `json:"member_ids" binding:"required,min=1,max=100,dive,uuid"` +} + +type ChatResponse struct { + ID string `json:"id"` + Title string `json:"title"` + MemberIDs []string `json:"member_ids"` + CreatedAt string `json:"created_at"` +} + +type ChatPageResponse struct { + Items []ChatResponse `json:"items"` + NextCursor *string `json:"next_cursor"` +} + +func ChatFromDomain(c *domain.Chat) ChatResponse { + return ChatResponse{ + ID: c.ID, + Title: c.Title, + MemberIDs: append([]string(nil), c.MemberIDs...), + CreatedAt: c.CreatedAt.UTC().Format(timeFormat), + } +} + +func ChatsFromDomain(items []domain.Chat) []ChatResponse { + out := make([]ChatResponse, len(items)) + for i := range items { + out[i] = ChatFromDomain(&items[i]) + } + return out +} diff --git a/backend/internal/httpapi/dto/error.go b/backend/internal/httpapi/dto/error.go new file mode 100644 index 0000000..4466e73 --- /dev/null +++ b/backend/internal/httpapi/dto/error.go @@ -0,0 +1,82 @@ +package dto + +import ( + "errors" + + "high-loud-apps-labs/internal/domain" +) + +// делаем вложенный ответ через вкладку ErrorBody в обертку. + +type ErrorBody struct { + Code string `json:"code"` + Message string `json:"message"` + RequestID string `json:"request_id"` +} + +type ErrorResponse struct { + Error ErrorBody `json:"error"` +} + +type coded interface { + Code() domain.ErrorCode +} + +func ErrorFromDomain(err error, requestID string) ErrorResponse { + var c coded + if errors.As(err, &c) { + code := c.Code() + message := err.Error() + if code == domain.CodeInternalError { + message = "внутренняя ошибка" + } + return ErrorResponse{Error: ErrorBody{ + Code: string(code), + Message: message, + RequestID: requestID, + }} + } + code := domain.CodeInternalError + switch { + case errors.Is(err, domain.ErrNotFound): + code = domain.CodeNotFound + case errors.Is(err, domain.ErrAlreadyExists): + code = domain.CodeConflict + case errors.Is(err, domain.ErrInvalidInput): + code = domain.CodeInvalidRequest + case errors.Is(err, domain.ErrUnauthorized): + code = domain.CodeUnauthorized + case errors.Is(err, domain.ErrUnsupportedMediaType): + code = domain.CodeUnsupportedMediaType + case errors.Is(err, domain.ErrUnavailable): + code = domain.CodeUnavailable + } + message := err.Error() + if code == domain.CodeInternalError { + message = "внутренняя ошибка" + } + return ErrorResponse{Error: ErrorBody{ + Code: string(code), + Message: message, + RequestID: requestID, + }} +} + +func StatusFromError(err error) int { + switch { + case errors.Is(err, domain.ErrNotFound): + return 404 + case errors.Is(err, domain.ErrAlreadyExists): + return 409 + case errors.Is(err, domain.ErrInvalidInput): + return 400 + case errors.Is(err, domain.ErrUnauthorized): + return 401 + case errors.Is(err, domain.ErrUnsupportedMediaType): + return 415 + case errors.Is(err, domain.ErrUnavailable): + return 503 + default: + return 500 + } +} diff --git a/backend/internal/httpapi/dto/health.go b/backend/internal/httpapi/dto/health.go new file mode 100644 index 0000000..8bb3503 --- /dev/null +++ b/backend/internal/httpapi/dto/health.go @@ -0,0 +1,5 @@ +package dto + +type HealthResponse struct { + Status string `json:"status"` +} diff --git a/backend/internal/httpapi/dto/message.go b/backend/internal/httpapi/dto/message.go new file mode 100644 index 0000000..8cb70b8 --- /dev/null +++ b/backend/internal/httpapi/dto/message.go @@ -0,0 +1,41 @@ +package dto + +import ( + "high-loud-apps-labs/internal/domain" +) + +type CreateMessageRequest struct { + Text string `json:"text" binding:"required,min=1,max=4000"` + AttachmentIDs []string `json:"attachment_ids"` +} + +type MessageResponse struct { + ID string `json:"id"` + ChatID string `json:"chat_id"` + SenderID string `json:"sender_id"` + Text string `json:"text"` + CreatedAt string `json:"created_at"` +} + +type MessagePageResponse struct { + Items []MessageResponse `json:"items"` + NextCursor *string `json:"next_cursor"` +} + +func MessageFromDomain(m *domain.Message) MessageResponse { + return MessageResponse{ + ID: m.ID, + ChatID: m.ChatID, + SenderID: m.SenderID, + Text: m.Text, + CreatedAt: m.CreatedAt.UTC().Format(timeFormat), + } +} + +func MessagesFromDomain(items []domain.Message) []MessageResponse { + out := make([]MessageResponse, len(items)) + for i := range items { + out[i] = MessageFromDomain(&items[i]) + } + return out +} diff --git a/backend/internal/httpapi/dto/session.go b/backend/internal/httpapi/dto/session.go new file mode 100644 index 0000000..174430c --- /dev/null +++ b/backend/internal/httpapi/dto/session.go @@ -0,0 +1,21 @@ +package dto + +import ( + "high-loud-apps-labs/internal/domain" +) + +type SessionResponse struct { + Token string `json:"token"` + TokenType string `json:"token_type"` + ExpiresAt string `json:"expires_at"` + User UserResponse `json:"user"` +} + +func SessionResponseFromDomain(s *domain.Session, token string, u *domain.User) SessionResponse { + return SessionResponse{ + Token: token, + TokenType: "Bearer", + ExpiresAt: s.ExpiresAt.UTC().Format(timeFormat), + User: UserFromDomain(u), + } +} diff --git a/backend/internal/httpapi/dto/user.go b/backend/internal/httpapi/dto/user.go new file mode 100644 index 0000000..0851941 --- /dev/null +++ b/backend/internal/httpapi/dto/user.go @@ -0,0 +1,29 @@ +package dto + +import ( + "high-loud-apps-labs/internal/domain" +) + +const timeFormat = "2006-01-02T15:04:05.000000Z07:00" + +type CreateUserRequest struct { + Username string `json:"username" binding:"required,min=3,max=32"` + DisplayName string `json:"display_name" binding:"required,min=1,max=100"` + Password string `json:"password" binding:"required,min=12,max=512"` +} + +type UserResponse struct { + ID string `json:"id"` + Username string `json:"username"` + DisplayName string `json:"display_name"` + CreatedAt string `json:"created_at"` +} + +func UserFromDomain(u *domain.User) UserResponse { + return UserResponse{ + ID: u.ID, + Username: u.Username, + DisplayName: u.DisplayName, + CreatedAt: u.CreatedAt.UTC().Format(timeFormat), + } +} diff --git a/backend/internal/httpapi/handler/auth.go b/backend/internal/httpapi/handler/auth.go new file mode 100644 index 0000000..b06a872 --- /dev/null +++ b/backend/internal/httpapi/handler/auth.go @@ -0,0 +1,77 @@ +package handler + +import ( + "encoding/base64" + "net/http" + "strings" + + "github.com/gin-gonic/gin" + + "high-loud-apps-labs/internal/domain" + "high-loud-apps-labs/internal/httpapi/dto" + "high-loud-apps-labs/internal/httpapi/middleware" + "high-loud-apps-labs/internal/service" +) + +type AuthHandler struct { + sessions *service.SessionService +} + +func NewAuthHandler(sessions *service.SessionService) *AuthHandler { + return &AuthHandler{sessions: sessions} +} + +func (h *AuthHandler) CreateSession(c *gin.Context) { + username, password, err := parseBasicAuth(c) + if err != nil { + respondBasicChallenge(c, err) + return + } + + session, token, user, err := h.sessions.Login(c.Request.Context(), username, password) + if err != nil { + respondBasicChallenge(c, err) + return + } + + c.JSON(http.StatusCreated, dto.SessionResponseFromDomain(session, token, user)) +} + +// RevokeCurrent отзывает текущую сессию. Токен уже проверен BearerAuth, +// поэтому здесь его достаточно передать в SessionService. +func (h *AuthHandler) RevokeCurrent(c *gin.Context) { + token := middleware.CurrentToken(c) + if token == "" { + respondError(c, &domain.UnauthorizedError{Reason: "нет токена"}) + return + } + + if err := h.sessions.Revoke(c.Request.Context(), token); err != nil { + respondError(c, err) + return + } + + c.Status(http.StatusNoContent) +} + +// parseBasicAuth читает Authorization: Basic base64(username:password). +func parseBasicAuth(c *gin.Context) (string, string, error) { + const prefix = "Basic " + + auth := c.GetHeader("Authorization") + if len(auth) < len(prefix) || !strings.EqualFold(auth[:len(prefix)], prefix) { + return "", "", &domain.UnauthorizedError{Reason: "требуется Basic"} + } + + decoded, err := base64.StdEncoding.DecodeString(auth[len(prefix):]) + if err != nil { + return "", "", &domain.UnauthorizedError{Reason: "некорректный Base64"} + } + + username, password, ok := strings.Cut(string(decoded), ":") + if !ok || username == "" { + return "", "", &domain.UnauthorizedError{Reason: "некорректный Basic-формат"} + } + + return username, password, nil +} diff --git a/backend/internal/httpapi/handler/bind.go b/backend/internal/httpapi/handler/bind.go new file mode 100644 index 0000000..cca7387 --- /dev/null +++ b/backend/internal/httpapi/handler/bind.go @@ -0,0 +1,52 @@ +package handler + +import ( + "bytes" + "encoding/json" + "errors" + "io" + "mime" + "strings" + + "github.com/gin-gonic/gin" + "github.com/gin-gonic/gin/binding" + + "high-loud-apps-labs/internal/domain" +) + +func bindStrictJSON(c *gin.Context, dst any) error { + ct := c.GetHeader("Content-Type") + mediaType, _, err := mime.ParseMediaType(ct) + if ct == "" || err != nil || !strings.EqualFold(mediaType, "application/json") { + return &domain.UnsupportedMediaTypeError{MediaType: ct} + } + + body, err := io.ReadAll(c.Request.Body) + if err != nil { + return &badRequestError{msg: "не удалось прочитать тело запроса"} + } + _ = c.Request.Body.Close() + + dec := json.NewDecoder(bytes.NewReader(body)) + dec.DisallowUnknownFields() + + if err := dec.Decode(dst); err != nil { + if errors.Is(err, io.EOF) { + return &badRequestError{msg: "тело запроса обязательно"} + } + return &badRequestError{msg: err.Error()} + } + + // Отклоняем любой непустой остаток после первого JSON-значения. + var extra json.RawMessage + if err := dec.Decode(&extra); !errors.Is(err, io.EOF) { + return &badRequestError{msg: "тело запроса содержит данные после JSON"} + } + + if v := binding.Validator; v != nil { + if err := v.ValidateStruct(dst); err != nil { + return &badRequestError{msg: err.Error()} + } + } + return nil +} diff --git a/backend/internal/httpapi/handler/chat.go b/backend/internal/httpapi/handler/chat.go new file mode 100644 index 0000000..86fc2cd --- /dev/null +++ b/backend/internal/httpapi/handler/chat.go @@ -0,0 +1,88 @@ +package handler + +import ( + "net/http" + "strconv" + + "github.com/gin-gonic/gin" + + "high-loud-apps-labs/internal/httpapi/dto" + "high-loud-apps-labs/internal/httpapi/middleware" + "high-loud-apps-labs/internal/service" +) + +type ChatHandler struct { + chats *service.ChatService +} + +func NewChatHandler(chats *service.ChatService) *ChatHandler { + return &ChatHandler{chats: chats} +} + +func (h *ChatHandler) Create(c *gin.Context) { + var req dto.CreateChatRequest + if err := bindStrictJSON(c, &req); err != nil { + respondError(c, err) + return + } + me := middleware.CurrentUser(c) + + chat, err := h.chats.Create(c.Request.Context(), me.ID, req.Title, req.MemberIDs) + if err != nil { + respondError(c, err) + return + } + c.JSON(http.StatusCreated, dto.ChatFromDomain(chat)) +} + +func (h *ChatHandler) Get(c *gin.Context) { + me := middleware.CurrentUser(c) + + chatID, err := parseUUIDPathParam(c, "chat_id") + if err != nil { + respondError(c, err) + return + } + + chat, err := h.chats.Get(c.Request.Context(), me.ID, chatID) + if err != nil { + respondError(c, err) + return + } + c.JSON(http.StatusOK, dto.ChatFromDomain(chat)) +} + +func (h *ChatHandler) List(c *gin.Context) { + me := middleware.CurrentUser(c) + limit, cursor, err := parseListQuery(c) + if err != nil { + respondError(c, err) + return + } + + items, next, err := h.chats.List(c.Request.Context(), me.ID, limit, cursor) + if err != nil { + respondError(c, err) + return + } + c.JSON(http.StatusOK, dto.ChatPageResponse{ + Items: dto.ChatsFromDomain(items), + NextCursor: next, + }) +} + +func parseListQuery(c *gin.Context) (int, *string, error) { + limit := 50 + if v := c.Query("limit"); v != "" { + n, err := strconv.Atoi(v) + if err != nil || n < 1 || n > 100 { + return 0, nil, &badRequestError{msg: "limit должен быть целым 1..100"} + } + limit = n + } + var cursor *string + if v := c.Query("cursor"); v != "" { + cursor = &v + } + return limit, cursor, nil +} diff --git a/backend/internal/httpapi/handler/health.go b/backend/internal/httpapi/handler/health.go new file mode 100644 index 0000000..0099565 --- /dev/null +++ b/backend/internal/httpapi/handler/health.go @@ -0,0 +1,54 @@ +package handler + +import ( + "context" + "net/http" + "sync/atomic" + "time" + + "github.com/gin-gonic/gin" + + "high-loud-apps-labs/internal/domain" + "high-loud-apps-labs/internal/httpapi/dto" +) + +type HealthCheck func(ctx context.Context) error + +type HealthHandler struct { + checks []HealthCheck + ready *atomic.Bool +} + +func NewHealthHandler(checks ...HealthCheck) *HealthHandler { + return &HealthHandler{checks: checks} +} + +func (h *HealthHandler) WithReadyFlag(v *atomic.Bool) *HealthHandler { + h.ready = v + return h +} + +func (h *HealthHandler) Live(c *gin.Context) { + c.JSON(http.StatusOK, dto.HealthResponse{Status: "ok"}) +} + +func (h *HealthHandler) Ready(c *gin.Context) { + if h.ready != nil && !h.ready.Load() { + respondError(c, &domain.UnavailableError{Reason: "shutting down"}) + return + } + + ctx, cancel := context.WithTimeout(c.Request.Context(), 2*time.Second) + defer cancel() + + for _, check := range h.checks { + if check == nil { + continue + } + if err := check(ctx); err != nil { + respondError(c, &domain.UnavailableError{Reason: "зависимость недоступна"}) + return + } + } + c.JSON(http.StatusOK, dto.HealthResponse{Status: "ok"}) +} diff --git a/backend/internal/httpapi/handler/message.go b/backend/internal/httpapi/handler/message.go new file mode 100644 index 0000000..e8de058 --- /dev/null +++ b/backend/internal/httpapi/handler/message.go @@ -0,0 +1,87 @@ +package handler + +import ( + "net/http" + "regexp" + + "github.com/gin-gonic/gin" + + "high-loud-apps-labs/internal/httpapi/dto" + "high-loud-apps-labs/internal/httpapi/middleware" + "high-loud-apps-labs/internal/service" +) + +var idempotencyKeyPattern = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`) + +type MessageHandler struct { + messages *service.MessageService +} + +func NewMessageHandler(messages *service.MessageService) *MessageHandler { + return &MessageHandler{messages: messages} +} + +func (h *MessageHandler) Create(c *gin.Context) { + var req dto.CreateMessageRequest + if err := bindStrictJSON(c, &req); err != nil { + respondError(c, err) + return + } + + key := c.GetHeader("Idempotency-Key") + if key == "" || !idempotencyKeyPattern.MatchString(key) { + respondError(c, &badRequestError{ + msg: "Idempotency-Key обязателен и должен соответствовать ^[A-Za-z0-9._:-]{1,128}$", + }) + return + } + + me := middleware.CurrentUser(c) + + chatID, err := parseUUIDPathParam(c, "chat_id") + if err != nil { + respondError(c, err) + return + } + + result, err := h.messages.Create( + c.Request.Context(), + me.ID, + chatID, + req.Text, + key, + c.Request.URL.Path, + ) + if err != nil { + respondError(c, err) + return + } + + c.Data(result.Status, "application/json", result.Body) +} + +func (h *MessageHandler) List(c *gin.Context) { + me := middleware.CurrentUser(c) + + chatID, err := parseUUIDPathParam(c, "chat_id") + if err != nil { + respondError(c, err) + return + } + + limit, cursor, err := parseListQuery(c) + if err != nil { + respondError(c, err) + return + } + + items, next, err := h.messages.List(c.Request.Context(), me.ID, chatID, limit, cursor) + if err != nil { + respondError(c, err) + return + } + c.JSON(http.StatusOK, dto.MessagePageResponse{ + Items: dto.MessagesFromDomain(items), + NextCursor: next, + }) +} diff --git a/backend/internal/httpapi/handler/response.go b/backend/internal/httpapi/handler/response.go new file mode 100644 index 0000000..8cad0b3 --- /dev/null +++ b/backend/internal/httpapi/handler/response.go @@ -0,0 +1,44 @@ +package handler + +import ( + "github.com/gin-gonic/gin" + "github.com/google/uuid" + + "high-loud-apps-labs/internal/domain" + "high-loud-apps-labs/internal/httpapi/dto" + "high-loud-apps-labs/internal/httpapi/middleware" +) + +type badRequestError struct{ msg string } + +func (e *badRequestError) Error() string { return e.msg } +func (e *badRequestError) Unwrap() error { return domain.ErrInvalidInput } +func (e *badRequestError) Code() domain.ErrorCode { return domain.CodeInvalidRequest } + +func parseUUIDPathParam(c *gin.Context, name string) (string, error) { + raw := c.Param(name) + if raw == "" { + return "", &badRequestError{msg: "параметр " + name + " обязателен"} + } + + id, err := uuid.Parse(raw) + if err != nil { + return "", &badRequestError{msg: "параметр " + name + " должен быть корректным UUID"} + } + + return id.String(), nil +} + +func respondError(c *gin.Context, err error) { + reqID := middleware.GetRequestID(c) + c.JSON(dto.StatusFromError(err), dto.ErrorFromDomain(err, reqID)) +} + +// respondBasicChallenge выставляет WWW-Authenticate для 401 на /auth/sessions. +// На не-401 ответах заголовок не ставится как по контракту нужно +func respondBasicChallenge(c *gin.Context, err error) { + if dto.StatusFromError(err) == 401 { + c.Header("WWW-Authenticate", `Basic realm="messenger", charset="UTF-8"`) + } + respondError(c, err) +} diff --git a/backend/internal/httpapi/handler/user.go b/backend/internal/httpapi/handler/user.go new file mode 100644 index 0000000..7697b50 --- /dev/null +++ b/backend/internal/httpapi/handler/user.go @@ -0,0 +1,43 @@ +package handler + +import ( + "net/http" + + "github.com/gin-gonic/gin" + + "high-loud-apps-labs/internal/httpapi/dto" + "high-loud-apps-labs/internal/httpapi/middleware" + "high-loud-apps-labs/internal/service" +) + +type UserHandler struct { + users *service.UserService +} + +func NewUserHandler(users *service.UserService) *UserHandler { + return &UserHandler{users: users} +} + +func (h *UserHandler) Create(c *gin.Context) { + var req dto.CreateUserRequest + if err := bindStrictJSON(c, &req); err != nil { + respondError(c, err) + return + } + + u, err := h.users.Create(c.Request.Context(), req.Username, req.DisplayName, req.Password) + if err != nil { + respondError(c, err) + return + } + c.JSON(http.StatusCreated, dto.UserFromDomain(u)) +} + +func (h *UserHandler) Current(c *gin.Context) { + u := middleware.CurrentUser(c) + if u == nil { + respondError(c, &badRequestError{msg: "нет текущего пользователя"}) + return + } + c.JSON(http.StatusOK, dto.UserFromDomain(u)) +} diff --git a/backend/internal/httpapi/middleware/auth_legacy.go b/backend/internal/httpapi/middleware/auth_legacy.go new file mode 100644 index 0000000..e3192da --- /dev/null +++ b/backend/internal/httpapi/middleware/auth_legacy.go @@ -0,0 +1,38 @@ +package middleware + +import ( + "net/http" + + "github.com/gin-gonic/gin" + + "high-loud-apps-labs/internal/domain" + "high-loud-apps-labs/internal/httpapi/dto" +) + +func Auth(users domain.UserRepository) gin.HandlerFunc { + return func(c *gin.Context) { + id := c.GetHeader("X-User-Id") + if id == "" { + abortUnauthorized(c, "требуется X-User-Id") + return + } + + u, err := users.GetByID(c.Request.Context(), id) + if err != nil { + abortUnauthorized(c, "неизвестный пользователь") + return + } + + c.Set(CurrentUserKey, u) + c.Next() + } +} + +func abortUnauthorized(c *gin.Context, msg string) { + reqID := GetRequestID(c) + body := dto.ErrorFromDomain( + &domain.UnauthorizedError{Reason: msg}, + reqID, + ) + c.AbortWithStatusJSON(http.StatusUnauthorized, body) +} diff --git a/backend/internal/httpapi/middleware/bearer.go b/backend/internal/httpapi/middleware/bearer.go new file mode 100644 index 0000000..fc904aa --- /dev/null +++ b/backend/internal/httpapi/middleware/bearer.go @@ -0,0 +1,70 @@ +package middleware + +import ( + "context" + "strings" + "time" + + "github.com/gin-gonic/gin" + + "high-loud-apps-labs/internal/domain" + "high-loud-apps-labs/internal/httpapi/dto" + "high-loud-apps-labs/internal/service" +) + +const authTimeout = 3 * time.Second + +// BearerAuth читает Authorization: Bearer , проверяет сессию +// через SessionService и кладёт пользователя и токен в контекст. +func BearerAuth(sessions *service.SessionService) gin.HandlerFunc { + return func(c *gin.Context) { + token, ok := parseBearerToken(c) + if !ok { + abortBearer(c, "требуется Bearer") + return + } + + ctx, cancel := context.WithTimeout(c.Request.Context(), authTimeout) + defer cancel() + + user, err := sessions.Resolve(ctx, token) + if err != nil { + abortBearerWithErr(c, err) + return + } + + c.Set(CurrentUserKey, user) + c.Set(CurrentTokenKey, token) + c.Next() + } +} + +// parseBearerToken читает Authorization: Bearer . +func parseBearerToken(c *gin.Context) (string, bool) { + const prefix = "Bearer " + auth := c.GetHeader("Authorization") + if len(auth) < len(prefix) || !strings.EqualFold(auth[:len(prefix)], prefix) { + return "", false + } + token := strings.TrimSpace(auth[len(prefix):]) + if token == "" { + return "", false + } + return token, true +} + +func abortBearer(c *gin.Context, reason string) { + abortBearerWithErr(c, &domain.UnauthorizedError{Reason: reason}) +} + +// abortBearerWithErr формирует ответ на ошибку аутентификации. +// Заголовок WWW-Authenticate: Bearer выставляется только на 401; +// при 503 (недоступность БД/кэша) — обычный ответ ошибки без challenge. +func abortBearerWithErr(c *gin.Context, err error) { + reqID := GetRequestID(c) + status := dto.StatusFromError(err) + if status == 401 { + c.Header("WWW-Authenticate", `Bearer realm="messenger"`) + } + c.AbortWithStatusJSON(status, dto.ErrorFromDomain(err, reqID)) +} diff --git a/backend/internal/httpapi/middleware/context.go b/backend/internal/httpapi/middleware/context.go new file mode 100644 index 0000000..f467d36 --- /dev/null +++ b/backend/internal/httpapi/middleware/context.go @@ -0,0 +1,30 @@ +package middleware + +import ( + "github.com/gin-gonic/gin" + + "high-loud-apps-labs/internal/domain" +) + +const ( + CurrentUserKey = "current_user" + CurrentTokenKey = "current_token" +) + +func CurrentUser(c *gin.Context) *domain.User { + if v, ok := c.Get(CurrentUserKey); ok { + if u, ok := v.(*domain.User); ok { + return u + } + } + return nil +} + +func CurrentToken(c *gin.Context) string { + if v, ok := c.Get(CurrentTokenKey); ok { + if s, ok := v.(string); ok { + return s + } + } + return "" +} diff --git a/backend/internal/httpapi/middleware/instance.go b/backend/internal/httpapi/middleware/instance.go new file mode 100644 index 0000000..583488c --- /dev/null +++ b/backend/internal/httpapi/middleware/instance.go @@ -0,0 +1,31 @@ +package middleware + +import ( + "os" + + "github.com/gin-gonic/gin" + "github.com/google/uuid" +) + +const InstanceIDHeader = "X-Instance-Id" + +var instanceID = resolveInstanceID() + +func resolveInstanceID() string { + if v := os.Getenv("INSTANCE_ID"); v != "" { + return v + } + if v, err := os.Hostname(); err == nil && v != "" { + return v + } + return uuid.NewString() +} + +func Instance() gin.HandlerFunc { + return func(c *gin.Context) { + c.Writer.Header().Set(InstanceIDHeader, instanceID) + c.Next() + } +} + +func GetInstanceID() string { return instanceID } diff --git a/backend/internal/httpapi/middleware/requestid.go b/backend/internal/httpapi/middleware/requestid.go new file mode 100644 index 0000000..43c9011 --- /dev/null +++ b/backend/internal/httpapi/middleware/requestid.go @@ -0,0 +1,32 @@ +package middleware + +import ( + "github.com/gin-gonic/gin" + "github.com/google/uuid" +) + +const ( + RequestIDKey = "request_id" + RequestIDHeader = "X-Request-Id" +) + +func RequestID() gin.HandlerFunc { + return func(c *gin.Context) { + id := c.GetHeader(RequestIDHeader) + if id == "" { + id = uuid.NewString() + } + c.Set(RequestIDKey, id) + c.Writer.Header().Set(RequestIDHeader, id) + c.Next() + } +} + +func GetRequestID(c *gin.Context) string { + if v, ok := c.Get(RequestIDKey); ok { + if s, ok := v.(string); ok { + return s + } + } + return "" +} diff --git a/backend/internal/httpapi/router.go b/backend/internal/httpapi/router.go new file mode 100644 index 0000000..8da3087 --- /dev/null +++ b/backend/internal/httpapi/router.go @@ -0,0 +1,50 @@ +package httpapi + +import ( + "github.com/gin-gonic/gin" + + "high-loud-apps-labs/internal/httpapi/handler" + "high-loud-apps-labs/internal/httpapi/middleware" +) + +type Handlers struct { + Health *handler.HealthHandler + User *handler.UserHandler + Chat *handler.ChatHandler + Message *handler.MessageHandler + Auth *handler.AuthHandler +} + +func NewRouter(h Handlers, auth gin.HandlerFunc) *gin.Engine { + gin.EnableJsonDecoderDisallowUnknownFields() + + r := gin.New() + r.Use(gin.Logger()) + r.Use(gin.Recovery()) + r.Use(middleware.RequestID()) + r.Use(middleware.Instance()) + + r.GET("/health/live", h.Health.Live) + r.GET("/health/ready", h.Health.Ready) + + api := r.Group("/api/v1") + { + api.POST("/users", h.User.Create) + api.POST("/auth/sessions", h.Auth.CreateSession) + } + + protected := api.Group("") + protected.Use(auth) + { + protected.DELETE("/auth/sessions/current", h.Auth.RevokeCurrent) + + protected.GET("/users/me", h.User.Current) + protected.POST("/chats", h.Chat.Create) + protected.GET("/chats", h.Chat.List) + protected.GET("/chats/:chat_id", h.Chat.Get) + protected.POST("/chats/:chat_id/messages", h.Message.Create) + protected.GET("/chats/:chat_id/messages", h.Message.List) + } + + return r +} diff --git a/backend/internal/service/chat.go b/backend/internal/service/chat.go new file mode 100644 index 0000000..caa8dce --- /dev/null +++ b/backend/internal/service/chat.go @@ -0,0 +1,95 @@ +package service + +import ( + "context" + "errors" + "strings" + "time" + "unicode/utf8" + + "github.com/google/uuid" + + "high-loud-apps-labs/internal/domain" +) + +type ChatService struct { + chats domain.ChatRepository + users domain.UserRepository +} + +func NewChatService(chats domain.ChatRepository, users domain.UserRepository) *ChatService { + return &ChatService{chats: chats, users: users} +} + +func (s *ChatService) Create(ctx context.Context, creatorID, title string, memberIDs []string) (*domain.Chat, error) { + if strings.TrimSpace(title) == "" { + return nil, &domain.ValidationError{ + Field: "title", + Message: "не может состоять только из пробелов", + } + } + if utf8.RuneCountInString(title) > 100 { + return nil, &domain.ValidationError{ + Field: "title", + Message: "не более 100 символов", + } + } + + seen := make(map[string]struct{}, len(memberIDs)) + for _, id := range memberIDs { + if _, dup := seen[id]; dup { + return nil, &domain.ValidationError{ + Field: "member_ids", + Message: "дубликаты запрещены", + } + } + seen[id] = struct{}{} + } + + if _, ok := seen[creatorID]; !ok { + return nil, &domain.ValidationError{ + Field: "member_ids", + Message: "создатель должен входить в список участников", + } + } + + for _, id := range memberIDs { + if _, err := s.users.GetByID(ctx, id); err != nil { + if errors.Is(err, domain.ErrNotFound) { + return nil, &domain.ValidationError{ + Field: "member_ids", + Message: "неизвестный участник " + id, + } + } + return nil, err + } + } + + c := &domain.Chat{ + ID: uuid.NewString(), + Title: title, + MemberIDs: append([]string(nil), memberIDs...), + CreatedAt: time.Now().UTC(), + } + if err := s.chats.Create(ctx, c); err != nil { + return nil, err + } + return c, nil +} + +func (s *ChatService) Get(ctx context.Context, userID, chatID string) (*domain.Chat, error) { + c, err := s.chats.GetByID(ctx, chatID) + if err != nil { + return nil, err + } + for _, m := range c.MemberIDs { + if m == userID { + return c, nil + } + } + return nil, &domain.NotFoundError{Entity: "chat", ID: chatID} +} + +func (s *ChatService) List(ctx context.Context, userID string, limit int, cursor *string) ([]domain.Chat, *string, error) { + return s.chats.ListByMember(ctx, userID, limit, cursor) +} diff --git a/backend/internal/service/message.go b/backend/internal/service/message.go new file mode 100644 index 0000000..3c178cf --- /dev/null +++ b/backend/internal/service/message.go @@ -0,0 +1,100 @@ +package service + +import ( + "context" + "encoding/json" + "net/http" + "strings" + "time" + "unicode/utf8" + + "github.com/google/uuid" + + "high-loud-apps-labs/internal/domain" + "high-loud-apps-labs/internal/httpapi/dto" +) + +type MessageService struct { + messages domain.MessageRepository + chats domain.ChatRepository + idempotencyTTL time.Duration +} + +func NewMessageService( + messages domain.MessageRepository, + chats domain.ChatRepository, + idempotencyTTL time.Duration, +) *MessageService { + return &MessageService{ + messages: messages, + chats: chats, + idempotencyTTL: idempotencyTTL, + } +} + +func (s *MessageService) Create(ctx context.Context, senderID, chatID, text, idempotencyKey, requestPath string, +) (*domain.CreateIdempotentResult, error) { + if strings.TrimSpace(text) == "" { + return nil, &domain.ValidationError{ + Field: "text", + Message: "не может состоять только из пробелов", + } + } + if utf8.RuneCountInString(text) > 4000 { + return nil, &domain.ValidationError{ + Field: "text", + Message: "не более 4000 символов", + } + } + + if err := s.ensureMember(ctx, senderID, chatID); err != nil { + return nil, err + } + + fresh := &domain.Message{ + ID: uuid.NewString(), + ChatID: chatID, + SenderID: senderID, + Text: text, + CreatedAt: time.Now().UTC(), + } + + body, err := json.Marshal(dto.MessageFromDomain(fresh)) + if err != nil { + return nil, err + } + + return s.messages.CreateIdempotent( + ctx, + domain.IdempotencyScope{ + UserID: senderID, + Method: http.MethodPost, + Path: requestPath, + Key: idempotencyKey, + }, + domain.RequestHash(text), + fresh, + body, + s.idempotencyTTL, + ) +} + +func (s *MessageService) List(ctx context.Context, userID, chatID string, limit int, cursor *string) ([]domain.Message, *string, error) { + if err := s.ensureMember(ctx, userID, chatID); err != nil { + return nil, nil, err + } + return s.messages.ListByChat(ctx, chatID, limit, cursor) +} + +func (s *MessageService) ensureMember(ctx context.Context, userID, chatID string) error { + c, err := s.chats.GetByID(ctx, chatID) + if err != nil { + return err + } + for _, m := range c.MemberIDs { + if m == userID { + return nil + } + } + return &domain.NotFoundError{Entity: "chat", ID: chatID} +} diff --git a/backend/internal/service/password.go b/backend/internal/service/password.go new file mode 100644 index 0000000..1f0659f --- /dev/null +++ b/backend/internal/service/password.go @@ -0,0 +1,112 @@ +package service + +import ( + "crypto/rand" + "crypto/subtle" + "encoding/base64" + "errors" + "fmt" + "strings" + + "golang.org/x/crypto/argon2" +) + +// PasswordHasher хеширует пароли и проверяет пароль сохранённого хеша. +type PasswordHasher interface { + Hash(password string) (string, error) + Verify(password, encoded string) (bool, error) +} + +type Argon2idHasher struct { + memory uint32 + iterations uint32 + parallelism uint8 + saltLength uint32 + keyLength uint32 +} + +func NewArgon2idHasher() *Argon2idHasher { + return &Argon2idHasher{ + memory: 64 * 1024, + iterations: 3, + parallelism: 4, + saltLength: 16, + keyLength: 32, + } +} + +func (h *Argon2idHasher) Hash(password string) (string, error) { + salt := make([]byte, h.saltLength) + if _, err := rand.Read(salt); err != nil { + return "", fmt.Errorf("генерация соли: %w", err) + } + + key := argon2.IDKey( + []byte(password), + salt, + h.iterations, + h.memory, + h.parallelism, + h.keyLength, + ) + + return fmt.Sprintf( + "$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s", + argon2.Version, + h.memory, + h.iterations, + h.parallelism, + base64.RawStdEncoding.EncodeToString(salt), + base64.RawStdEncoding.EncodeToString(key), + ), nil +} + +// Verify сравнивает пароль с сохранённым PHC-хешем. +// Возвращает false и nil при неверном пароле. +// Возвращает false и ошибку, если строка хеша повреждена или несовместима. +func (h *Argon2idHasher) Verify(password, encoded string) (bool, error) { + parts := strings.Split(encoded, "$") + if len(parts) != 6 || parts[1] != "argon2id" { + return false, errors.New("некорректный формат хеша") + } + + var version int + if n, err := fmt.Sscanf(parts[2], "v=%d", &version); err != nil || n != 1 { + return false, errors.New("некорректная версия хеша") + } + if version != argon2.Version { + return false, errors.New("неподдерживаемая версия Argon2") + } + + var ( + memory uint32 + iterations uint32 + parallelism uint8 + ) + if n, err := fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d", &memory, &iterations, ¶llelism); err != nil || n != 3 { + return false, errors.New("некорректные параметры хеша") + } + + salt, err := base64.RawStdEncoding.DecodeString(parts[4]) + if err != nil { + return false, errors.New("некорректная соль") + } + + wantKey, err := base64.RawStdEncoding.DecodeString(parts[5]) + if err != nil { + return false, errors.New("некорректный ключ") + } + + gotKey := argon2.IDKey( + []byte(password), + salt, + iterations, + memory, + parallelism, + uint32(len(wantKey)), + ) + + return subtle.ConstantTimeCompare(gotKey, wantKey) == 1, nil +} + +var _ PasswordHasher = (*Argon2idHasher)(nil) diff --git a/backend/internal/service/session.go b/backend/internal/service/session.go new file mode 100644 index 0000000..ee7216b --- /dev/null +++ b/backend/internal/service/session.go @@ -0,0 +1,127 @@ +package service + +import ( + "context" + "crypto/rand" + "crypto/sha256" + "encoding/base64" + "errors" + "fmt" + "time" + + "high-loud-apps-labs/internal/domain" +) + +// SessionService отвечает за вход, проверку и отзыв сессий. +type SessionService struct { + users domain.UserRepository + sessions domain.SessionRepository + hasher PasswordHasher + ttl time.Duration +} + +// NewSessionService создаёт сервис с заданным TTL сессий. +func NewSessionService( + users domain.UserRepository, + sessions domain.SessionRepository, + hasher PasswordHasher, + ttl time.Duration, +) *SessionService { + return &SessionService{ + users: users, + sessions: sessions, + hasher: hasher, + ttl: ttl, + } +} + +// Login проверяет username/password и создаёт новую сессию. +// Возвращает сессию, открытый токен и пользователя. +// Открытый токен уходит клиенту; в БД сохраняется только его SHA-256. +func (s *SessionService) Login(ctx context.Context, username, password string) (*domain.Session, string, *domain.User, error) { + user, err := s.users.GetByUsername(ctx, username) + if err != nil { + if errors.Is(err, domain.ErrNotFound) { + return nil, "", nil, &domain.UnauthorizedError{Reason: "неверные учётные данные"} + } + return nil, "", nil, err + } + + ok, err := s.hasher.Verify(password, user.PasswordHash) + if err != nil { + return nil, "", nil, err + } + if !ok { + return nil, "", nil, &domain.UnauthorizedError{Reason: "неверные учётные данные"} + } + + token, err := generateToken() + if err != nil { + return nil, "", nil, err + } + + tokenHash := sha256.Sum256([]byte(token)) + now := time.Now().UTC() + + session := &domain.Session{ + TokenHash: tokenHash[:], + UserID: user.ID, + ExpiresAt: now.Add(s.ttl), + CreatedAt: now, + } + if err := s.sessions.Create(ctx, session); err != nil { + return nil, "", nil, err + } + + return session, token, user, nil +} + +// Resolve проверяет токен и возвращает пользователя сессии. +// Истёкший, отозванный или неизвестный токен - UnauthorizedError по контракту +func (s *SessionService) Resolve(ctx context.Context, token string) (*domain.User, error) { + if token == "" { + return nil, &domain.UnauthorizedError{Reason: "пустой токен"} + } + + tokenHash := sha256.Sum256([]byte(token)) + + session, err := s.sessions.GetByTokenHash(ctx, tokenHash[:]) + if err != nil { + if errors.Is(err, domain.ErrNotFound) { + return nil, &domain.UnauthorizedError{Reason: "неизвестный токен"} + } + return nil, err + } + + if !session.ExpiresAt.After(time.Now().UTC()) { + return nil, &domain.UnauthorizedError{Reason: "сессия истекла"} + } + + user, err := s.users.GetByID(ctx, session.UserID) + if err != nil { + if errors.Is(err, domain.ErrNotFound) { + return nil, &domain.UnauthorizedError{Reason: "пользователь сессии не найден"} + } + return nil, err + } + + return user, nil +} + +// Revoke удаляет сессию по токену. +func (s *SessionService) Revoke(ctx context.Context, token string) error { + if token == "" { + return nil + } + tokenHash := sha256.Sum256([]byte(token)) + return s.sessions.DeleteByTokenHash(ctx, tokenHash[:]) +} + +// generateToken возвращает 32 случайных байта в base64url без паддинга=. +func generateToken() (string, error) { + buf := make([]byte, 32) + if _, err := rand.Read(buf); err != nil { + return "", fmt.Errorf("генерация токена: %w", err) + } + return base64.RawURLEncoding.EncodeToString(buf), nil +} diff --git a/backend/internal/service/user.go b/backend/internal/service/user.go new file mode 100644 index 0000000..e7b7547 --- /dev/null +++ b/backend/internal/service/user.go @@ -0,0 +1,78 @@ +package service + +import ( + "context" + "regexp" + "strings" + "time" + "unicode/utf8" + + "github.com/google/uuid" + + "high-loud-apps-labs/internal/domain" +) + +var usernamePattern = regexp.MustCompile(`^[a-z0-9_]{3,32}$`) + +type UserService struct { + users domain.UserRepository + hasher PasswordHasher +} + +func NewUserService(users domain.UserRepository, hasher PasswordHasher) *UserService { + return &UserService{users: users, hasher: hasher} +} + +func (s *UserService) Create(ctx context.Context, username, displayName, password string) (*domain.User, error) { + if !usernamePattern.MatchString(username) { + return nil, &domain.ValidationError{ + Field: "username", + Message: "должен соответствовать ^[a-z0-9_]{3,32}$", + } + } + if strings.TrimSpace(displayName) == "" { + return nil, &domain.ValidationError{ + Field: "display_name", + Message: "не может состоять только из пробелов", + } + } + if utf8.RuneCountInString(displayName) > 100 { + return nil, &domain.ValidationError{ + Field: "display_name", + Message: "не более 100 символов", + } + } + + passwordRunes := utf8.RuneCountInString(password) + if passwordRunes < 12 || passwordRunes > 128 { + return nil, &domain.ValidationError{ + Field: "password", + Message: "длина 12–128 символов", + } + } + + hash, err := s.hasher.Hash(password) + if err != nil { + return nil, err + } + + u := &domain.User{ + ID: uuid.NewString(), + Username: username, + DisplayName: displayName, + PasswordHash: hash, + CreatedAt: time.Now().UTC(), + } + if err := s.users.Create(ctx, u); err != nil { + return nil, err + } + return u, nil +} + +func (s *UserService) GetByID(ctx context.Context, id string) (*domain.User, error) { + return s.users.GetByID(ctx, id) +} + +func (s *UserService) GetByUsername(ctx context.Context, username string) (*domain.User, error) { + return s.users.GetByUsername(ctx, username) +} diff --git a/backend/internal/storage/_legacy/memory/chat.go b/backend/internal/storage/_legacy/memory/chat.go new file mode 100644 index 0000000..a2e18d0 --- /dev/null +++ b/backend/internal/storage/_legacy/memory/chat.go @@ -0,0 +1,102 @@ +package memory + +import ( + "context" + "slices" + + "high-loud-apps-labs/internal/domain" +) + +func (r *ChatRepo) Create(ctx context.Context, chat *domain.Chat) error { + if err := ctx.Err(); err != nil { + return err + } + r.mu.Lock() + defer r.mu.Unlock() + + stored := *chat + stored.MemberIDs = append([]string(nil), chat.MemberIDs...) + r.chats[chat.ID] = &stored + return nil +} + +func (r *ChatRepo) GetByID(ctx context.Context, id string) (*domain.Chat, error) { + if err := ctx.Err(); err != nil { + return nil, err + } + r.mu.RLock() + defer r.mu.RUnlock() + + c, ok := r.chats[id] + if !ok { + return nil, &domain.NotFoundError{Entity: "chat", ID: id} + } + copy := *c + copy.MemberIDs = append([]string(nil), c.MemberIDs...) + return ©, nil +} + +func (r *ChatRepo) ListByMember(ctx context.Context, userID string, limit int, cursor *string) ([]domain.Chat, *string, error) { + if err := ctx.Err(); err != nil { + return nil, nil, err + } + r.mu.RLock() + defer r.mu.RUnlock() + + scope := "chats:" + userID + + all := make([]domain.Chat, 0) + for _, c := range r.chats { + for _, m := range c.MemberIDs { + if m == userID { + copy := *c + copy.MemberIDs = append([]string(nil), c.MemberIDs...) + all = append(all, copy) + break + } + } + } + + slices.SortFunc(all, func(a, b domain.Chat) int { + if lessThan(a.CreatedAt, a.ID, b.CreatedAt, b.ID) { + return -1 + } + if lessThan(b.CreatedAt, b.ID, a.CreatedAt, a.ID) { + return 1 + } + return 0 + }) + + start := 0 + if cursor != nil { + t, id, err := decodeCursor(*cursor, scope) + if err != nil { + return nil, nil, err + } + start = len(all) + for i, c := range all { + if lessThan(t, id, c.CreatedAt, c.ID) { + start = i + break + } + } + } + + if start >= len(all) { + return []domain.Chat{}, nil, nil + } + end := start + limit + if end > len(all) { + end = len(all) + } + page := all[start:end] + + var next *string + if end < len(all) { + last := page[len(page)-1] + c := encodeCursor(scope, last.CreatedAt, last.ID) + next = &c + } + + return page, next, nil +} diff --git a/backend/internal/storage/_legacy/memory/cursor.go b/backend/internal/storage/_legacy/memory/cursor.go new file mode 100644 index 0000000..ef0ebac --- /dev/null +++ b/backend/internal/storage/_legacy/memory/cursor.go @@ -0,0 +1,47 @@ +package memory + +import ( + "encoding/base64" + "strings" + "time" + + "high-loud-apps-labs/internal/domain" +) + +func encodeCursor(scope string, createdAt time.Time, id string) string { + raw := scope + "|" + createdAt.UTC().Format(time.RFC3339Nano) + "|" + id + return base64.RawURLEncoding.EncodeToString([]byte(raw)) +} + +func decodeCursor(cursor, expectedScope string) (time.Time, string, error) { + data, err := base64.RawURLEncoding.DecodeString(cursor) + if err != nil { + return time.Time{}, "", badCursor() + } + parts := strings.SplitN(string(data), "|", 3) + if len(parts) != 3 { + return time.Time{}, "", badCursor() + } + if parts[0] != expectedScope { + return time.Time{}, "", badCursor() + } + t, err := time.Parse(time.RFC3339Nano, parts[1]) + if err != nil { + return time.Time{}, "", badCursor() + } + return t, parts[2], nil +} + +func badCursor() error { + return &domain.ValidationError{ + Field: "cursor", + Message: "некорректный формат", + } +} + +func lessThan(aTime time.Time, aID string, bTime time.Time, bID string) bool { + if aTime.Equal(bTime) { + return aID < bID + } + return aTime.Before(bTime) +} diff --git a/backend/internal/storage/_legacy/memory/message.go b/backend/internal/storage/_legacy/memory/message.go new file mode 100644 index 0000000..463b757 --- /dev/null +++ b/backend/internal/storage/_legacy/memory/message.go @@ -0,0 +1,93 @@ +package memory + +import ( + "context" + "slices" + "time" + + "high-loud-apps-labs/internal/domain" +) + +func (r *MessageRepo) Create(ctx context.Context, message *domain.Message) error { + if err := ctx.Err(); err != nil { + return err + } + r.mu.Lock() + defer r.mu.Unlock() + + stored := *message + r.messages[message.ChatID] = append(r.messages[message.ChatID], stored) + return nil +} + +func (r *MessageRepo) ListByChat(ctx context.Context, chatID string, limit int, cursor *string) ([]domain.Message, *string, error) { + if err := ctx.Err(); err != nil { + return nil, nil, err + } + r.mu.RLock() + defer r.mu.RUnlock() + + scope := "messages:" + chatID + + var ( + afterTime time.Time + afterID string + hasCursor bool + ) + if cursor != nil { + t, id, err := decodeCursor(*cursor, scope) + if err != nil { + return nil, nil, err + } + afterTime = t + afterID = id + hasCursor = true + } + + src := r.messages[chatID] + if len(src) == 0 { + return []domain.Message{}, nil, nil + } + + all := make([]domain.Message, len(src)) + copy(all, src) + + slices.SortFunc(all, func(a, b domain.Message) int { + if lessThan(a.CreatedAt, a.ID, b.CreatedAt, b.ID) { + return -1 + } + if lessThan(b.CreatedAt, b.ID, a.CreatedAt, a.ID) { + return 1 + } + return 0 + }) + + start := 0 + if hasCursor { + start = len(all) + for i, m := range all { + if lessThan(afterTime, afterID, m.CreatedAt, m.ID) { + start = i + break + } + } + } + + if start >= len(all) { + return []domain.Message{}, nil, nil + } + end := start + limit + if end > len(all) { + end = len(all) + } + page := all[start:end] + + var next *string + if end < len(all) { + last := page[len(page)-1] + c := encodeCursor(scope, last.CreatedAt, last.ID) + next = &c + } + + return page, next, nil +} diff --git a/backend/internal/storage/_legacy/memory/storage.go b/backend/internal/storage/_legacy/memory/storage.go new file mode 100644 index 0000000..5b96773 --- /dev/null +++ b/backend/internal/storage/_legacy/memory/storage.go @@ -0,0 +1,34 @@ +package memory + +import ( + "sync" + + "high-loud-apps-labs/internal/domain" +) + +type Storage struct { + mu sync.RWMutex + users map[string]*domain.User + chats map[string]*domain.Chat + messages map[string][]domain.Message +} + +func New() *Storage { + return &Storage{ + users: make(map[string]*domain.User), + chats: make(map[string]*domain.Chat), + messages: make(map[string][]domain.Message), + } +} + +func (s *Storage) Users() *UserRepo { return &UserRepo{s} } +func (s *Storage) Chats() *ChatRepo { return &ChatRepo{s} } +func (s *Storage) Messages() *MessageRepo { return &MessageRepo{s} } + +type UserRepo struct{ *Storage } +type ChatRepo struct{ *Storage } +type MessageRepo struct{ *Storage } + +var _ domain.UserRepository = (*UserRepo)(nil) +var _ domain.ChatRepository = (*ChatRepo)(nil) +var _ domain.MessageRepository = (*MessageRepo)(nil) diff --git a/backend/internal/storage/_legacy/memory/user.go b/backend/internal/storage/_legacy/memory/user.go new file mode 100644 index 0000000..713162b --- /dev/null +++ b/backend/internal/storage/_legacy/memory/user.go @@ -0,0 +1,59 @@ +package memory + +import ( + "context" + + "high-loud-apps-labs/internal/domain" +) + +func (r *UserRepo) Create(ctx context.Context, user *domain.User) error { + if err := ctx.Err(); err != nil { + return err + } + r.mu.Lock() + defer r.mu.Unlock() + + for _, u := range r.users { + if u.Username == user.Username { + return &domain.AlreadyExistsError{ + Entity: "user", + Field: "username", + Value: user.Username, + } + } + } + stored := *user + r.users[user.ID] = &stored + return nil +} + +func (r *UserRepo) GetByID(ctx context.Context, id string) (*domain.User, error) { + if err := ctx.Err(); err != nil { + return nil, err + } + r.mu.RLock() + defer r.mu.RUnlock() + + u, ok := r.users[id] + if !ok { + return nil, &domain.NotFoundError{Entity: "user", ID: id} + } + copy := *u + return ©, nil +} + +func (r *UserRepo) GetByUsername(ctx context.Context, username string) (*domain.User, error) { + if err := ctx.Err(); err != nil { + return nil, err + } + r.mu.RLock() + defer r.mu.RUnlock() + + for _, u := range r.users { + if u.Username == username { + copy := *u + return ©, nil + } + } + return nil, &domain.NotFoundError{Entity: "user", ID: username} +} diff --git a/backend/internal/storage/postgres/chat.go b/backend/internal/storage/postgres/chat.go new file mode 100644 index 0000000..8afc6f2 --- /dev/null +++ b/backend/internal/storage/postgres/chat.go @@ -0,0 +1,195 @@ +package postgres + +import ( + "context" + "time" + + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgxpool" + + "high-loud-apps-labs/internal/domain" +) + +type ChatRepo struct { + pool *pgxpool.Pool +} + +func NewChatRepo(pool *pgxpool.Pool) *ChatRepo { + return &ChatRepo{pool: pool} +} + +// Create атомарно создаёт чат и его участников. +func (r *ChatRepo) Create(ctx context.Context, chat *domain.Chat) error { + tx, err := r.pool.Begin(ctx) + if err != nil { + return mapError(err) + } + defer func() { _ = tx.Rollback(ctx) }() + + const qChat = `INSERT INTO chats (id, title, created_at) VALUES ($1::uuid, $2, $3)` + if _, err := tx.Exec(ctx, qChat, chat.ID, chat.Title, chat.CreatedAt); err != nil { + if checkViolation(err) { + return &domain.ValidationError{Field: "chat", Message: "нарушено ограничение целостности"} + } + return mapError(err) + } + + const qMember = `INSERT INTO chat_members (chat_id, user_id) VALUES ($1::uuid, $2::uuid)` + for _, uid := range chat.MemberIDs { + if _, err := tx.Exec(ctx, qMember, chat.ID, uid); err != nil { + if foreignKeyViolation(err) { + return &domain.ValidationError{ + Field: "member_ids", + Message: "неизвестный участник " + uid, + } + } + if uniqueViolation(err) { + return &domain.ValidationError{ + Field: "member_ids", + Message: "дубликаты запрещены", + } + } + return mapError(err) + } + } + + return mapError(tx.Commit(ctx)) +} + +func (r *ChatRepo) GetByID(ctx context.Context, id string) (*domain.Chat, error) { + const q = `SELECT id, title, created_at FROM chats WHERE id = $1::uuid` + c := &domain.Chat{} + err := r.pool.QueryRow(ctx, q, id).Scan(&c.ID, &c.Title, &c.CreatedAt) + if err != nil { + return nil, notFound(err, "chat", id) + } + members, err := r.loadMembers(ctx, []string{c.ID}) + if err != nil { + return nil, err + } + c.MemberIDs = members[c.ID] + if c.MemberIDs == nil { + c.MemberIDs = []string{} + } + return c, nil +} + +func (r *ChatRepo) ListByMember(ctx context.Context, userID string, limit int, cursor *string) ([]domain.Chat, *string, error) { + scope := "chats:" + userID + + var ( + afterTime time.Time + afterID string + hasCursor bool + ) + if cursor != nil { + t, id, err := decodeCursor(*cursor, scope) + if err != nil { + return nil, nil, err + } + afterTime = t + afterID = id + hasCursor = true + } + + var ( + rows pgx.Rows + err error + ) + if hasCursor { + const q = ` + SELECT c.id, c.title, c.created_at + FROM chats c + JOIN chat_members m ON m.chat_id = c.id + WHERE m.user_id = $1::uuid + AND (c.created_at, c.id) > ($2, $3::uuid) + ORDER BY c.created_at, c.id + LIMIT $4 + ` + rows, err = r.pool.Query(ctx, q, userID, afterTime, afterID, limit+1) + } else { + const q = ` + SELECT c.id, c.title, c.created_at + FROM chats c + JOIN chat_members m ON m.chat_id = c.id + WHERE m.user_id = $1::uuid + ORDER BY c.created_at, c.id + LIMIT $2 + ` + rows, err = r.pool.Query(ctx, q, userID, limit+1) + } + if err != nil { + return nil, nil, mapError(err) + } + defer rows.Close() + + page := make([]domain.Chat, 0, limit) + for rows.Next() { + var c domain.Chat + if err := rows.Scan(&c.ID, &c.Title, &c.CreatedAt); err != nil { + return nil, nil, mapError(err) + } + page = append(page, c) + } + if err := rows.Err(); err != nil { + return nil, nil, mapError(err) + } + + var next *string + if len(page) > limit { + page = page[:limit] + last := page[len(page)-1] + c := encodeCursor(scope, last.CreatedAt, last.ID) + next = &c + } + + if len(page) > 0 { + ids := make([]string, len(page)) + for i := range page { + ids[i] = page[i].ID + } + members, err := r.loadMembers(ctx, ids) + if err != nil { + return nil, nil, err + } + for i := range page { + if m, ok := members[page[i].ID]; ok { + page[i].MemberIDs = m + } else { + page[i].MemberIDs = []string{} + } + } + } + + return page, next, nil +} + +// loadMembers одним запросом собирает участников для указанных чатов. +func (r *ChatRepo) loadMembers(ctx context.Context, chatIDs []string) (map[string][]string, error) { + if len(chatIDs) == 0 { + return map[string][]string{}, nil + } + const q = ` + SELECT chat_id, user_id + FROM chat_members + WHERE chat_id = ANY($1::uuid[]) + ORDER BY chat_id, user_id + ` + rows, err := r.pool.Query(ctx, q, chatIDs) + if err != nil { + return nil, mapError(err) + } + defer rows.Close() + + result := make(map[string][]string, len(chatIDs)) + for rows.Next() { + var chatID, userID string + if err := rows.Scan(&chatID, &userID); err != nil { + return nil, mapError(err) + } + result[chatID] = append(result[chatID], userID) + } + return result, mapError(rows.Err()) +} + +var _ domain.ChatRepository = (*ChatRepo)(nil) diff --git a/backend/internal/storage/postgres/cursor.go b/backend/internal/storage/postgres/cursor.go new file mode 100644 index 0000000..044ffee --- /dev/null +++ b/backend/internal/storage/postgres/cursor.go @@ -0,0 +1,46 @@ +package postgres + +import ( + "encoding/base64" + "strings" + "time" + + "high-loud-apps-labs/internal/domain" + + "github.com/google/uuid" +) + +// Взял за основу что в inmemery делал +func encodeCursor(scope string, createdAt time.Time, id string) string { + raw := scope + "|" + createdAt.UTC().Format(time.RFC3339Nano) + "|" + id + return base64.RawURLEncoding.EncodeToString([]byte(raw)) +} + +func decodeCursor(cursor, expectedScope string) (time.Time, string, error) { + data, err := base64.RawURLEncoding.DecodeString(cursor) + if err != nil { + return time.Time{}, "", badCursor() + } + parts := strings.SplitN(string(data), "|", 3) + if len(parts) != 3 { + return time.Time{}, "", badCursor() + } + if parts[0] != expectedScope { + return time.Time{}, "", badCursor() + } + t, err := time.Parse(time.RFC3339Nano, parts[1]) + if err != nil { + return time.Time{}, "", badCursor() + } + if _, err := uuid.Parse(parts[2]); err != nil { + return time.Time{}, "", badCursor() + } + return t, parts[2], nil +} + +func badCursor() error { + return &domain.ValidationError{ + Field: "cursor", + Message: "некорректный формат", + } +} diff --git a/backend/internal/storage/postgres/db.go b/backend/internal/storage/postgres/db.go new file mode 100644 index 0000000..ad27e83 --- /dev/null +++ b/backend/internal/storage/postgres/db.go @@ -0,0 +1,75 @@ +package postgres + +import ( + "context" + "fmt" + "time" + + "github.com/jackc/pgx/v5/pgxpool" + "github.com/jackc/pgx/v5/stdlib" + "github.com/pressly/goose/v3" + + "high-loud-apps-labs/migrations" +) + +type Config struct { + URL string + MaxConns int32 + MinConns int32 + MaxConnLifetime time.Duration + MaxConnIdleTime time.Duration + ConnectTimeout time.Duration +} + +func Connect(ctx context.Context, cfg Config) (*pgxpool.Pool, error) { + if cfg.URL == "" { + return nil, fmt.Errorf("DATABASE_URL пустой") + } + + poolCfg, err := pgxpool.ParseConfig(cfg.URL) + if err != nil { + return nil, fmt.Errorf("разбор DATABASE_URL: %w", err) + } + if cfg.MaxConns > 0 { + poolCfg.MaxConns = cfg.MaxConns + } + if cfg.MinConns > 0 { + poolCfg.MinConns = cfg.MinConns + } + if cfg.MaxConnLifetime > 0 { + poolCfg.MaxConnLifetime = cfg.MaxConnLifetime + } + if cfg.MaxConnIdleTime > 0 { + poolCfg.MaxConnIdleTime = cfg.MaxConnIdleTime + } + if cfg.ConnectTimeout > 0 { + poolCfg.ConnConfig.ConnectTimeout = cfg.ConnectTimeout + } + poolCfg.HealthCheckPeriod = 10 * time.Second + + pool, err := pgxpool.NewWithConfig(ctx, poolCfg) + if err != nil { + return nil, fmt.Errorf("создание пула: %w", err) + } + + pingCtx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + if err := pool.Ping(pingCtx); err != nil { + pool.Close() + return nil, fmt.Errorf("ping БД: %w", err) + } + return pool, nil +} + +func RunMigrations(ctx context.Context, pool *pgxpool.Pool) error { + db := stdlib.OpenDBFromPool(pool) + + goose.SetBaseFS(migrations.FS) + if err := goose.SetDialect("postgres"); err != nil { + return fmt.Errorf("goose dialect: %w", err) + } + if err := goose.UpContext(ctx, db, "."); err != nil { + return fmt.Errorf("применение миграций: %w", err) + } + return nil +} diff --git a/backend/internal/storage/postgres/errors.go b/backend/internal/storage/postgres/errors.go new file mode 100644 index 0000000..6386128 --- /dev/null +++ b/backend/internal/storage/postgres/errors.go @@ -0,0 +1,71 @@ +package postgres + +import ( + "context" + "errors" + + "github.com/jackc/pgerrcode" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgconn" + + "high-loud-apps-labs/internal/domain" +) + +type coded interface { + Code() domain.ErrorCode +} + +// mapError переводит ошибки драйвера в доменные. +func mapError(err error) error { + if err == nil { + return nil + } + var c coded + if errors.As(err, &c) { + return err + } + if errors.Is(err, pgx.ErrNoRows) { + return err + } + if errors.Is(err, context.DeadlineExceeded) { + return &domain.UnavailableError{Reason: "превышено время ожидания БД"} + } + if errors.Is(err, context.Canceled) { + return &domain.UnavailableError{Reason: "запрос отменён"} + } + return &domain.UnavailableError{Reason: err.Error()} +} + +func notFound(err error, entity, id string) error { + if err == nil { + return nil + } + if errors.Is(err, pgx.ErrNoRows) { + return &domain.NotFoundError{Entity: entity, ID: id} + } + return mapError(err) +} + +func uniqueViolation(err error) bool { + var pgErr *pgconn.PgError + if errors.As(err, &pgErr) { + return pgErr.Code == pgerrcode.UniqueViolation + } + return false +} + +func foreignKeyViolation(err error) bool { + var pgErr *pgconn.PgError + if errors.As(err, &pgErr) { + return pgErr.Code == pgerrcode.ForeignKeyViolation + } + return false +} + +func checkViolation(err error) bool { + var pgErr *pgconn.PgError + if errors.As(err, &pgErr) { + return pgErr.Code == pgerrcode.CheckViolation + } + return false +} diff --git a/backend/internal/storage/postgres/message.go b/backend/internal/storage/postgres/message.go new file mode 100644 index 0000000..dd2db13 --- /dev/null +++ b/backend/internal/storage/postgres/message.go @@ -0,0 +1,203 @@ +package postgres + +import ( + "bytes" + "context" + "net/http" + "time" + + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgxpool" + + "high-loud-apps-labs/internal/domain" +) + +type MessageRepo struct { + pool *pgxpool.Pool +} + +func NewMessageRepo(pool *pgxpool.Pool) *MessageRepo { + return &MessageRepo{pool: pool} +} + +func (r *MessageRepo) Create(ctx context.Context, m *domain.Message) error { + const q = ` + INSERT INTO messages (id, chat_id, sender_id, text, created_at) + VALUES ($1::uuid, $2::uuid, $3::uuid, $4, $5) + ` + _, err := r.pool.Exec(ctx, q, m.ID, m.ChatID, m.SenderID, m.Text, m.CreatedAt) + if err != nil { + if foreignKeyViolation(err) { + return &domain.NotFoundError{Entity: "chat", ID: m.ChatID} + } + if checkViolation(err) { + return &domain.ValidationError{Field: "text", Message: "нарушено ограничение"} + } + return err + } + return nil +} +func (r *MessageRepo) CreateIdempotent( + ctx context.Context, + scope domain.IdempotencyScope, + requestHash []byte, + fresh *domain.Message, + freshResponse []byte, + ttl time.Duration, +) (*domain.CreateIdempotentResult, error) { + tx, err := r.pool.Begin(ctx) + if err != nil { + return nil, mapError(err) + } + defer func() { _ = tx.Rollback(ctx) }() + + // 1) Убираем просроченную запись, чтобы ON CONFLICT сработал + // только на живой, а не на истёкшей строке. + if _, err := tx.Exec(ctx, ` + DELETE FROM idempotency_keys + WHERE user_id = $1::uuid AND method = $2 AND path = $3 AND key = $4 + AND expires_at <= now() + `, scope.UserID, scope.Method, scope.Path, scope.Key); err != nil { + return nil, mapError(err) + } + + // 2) Резервируем слот. Если параллельная реплика уже вставила — + // Postgres заблокирует конфликтный INSERT и мы увидим RowsAffected=0 + // только после того, как конкурент закоммитит или откатится. + expiresAt := time.Now().UTC().Add(ttl) + tag, err := tx.Exec(ctx, ` + INSERT INTO idempotency_keys + (user_id, method, path, key, request_hash, response_status, response_body, expires_at) + VALUES ($1::uuid, $2, $3, $4, $5, $6, $7, $8) + ON CONFLICT (user_id, method, path, key) DO NOTHING + `, scope.UserID, scope.Method, scope.Path, scope.Key, + requestHash, http.StatusCreated, freshResponse, expiresAt) + if err != nil { + return nil, mapError(err) + } + + // 3) Слот занят — читаем сохранённый ответ в этой же транзакции. + if tag.RowsAffected() == 0 { + var ( + storedHash []byte + storedStatus int + storedBody []byte + ) + err := tx.QueryRow(ctx, ` + SELECT request_hash, response_status, response_body + FROM idempotency_keys + WHERE user_id = $1::uuid AND method = $2 AND path = $3 AND key = $4 + `, scope.UserID, scope.Method, scope.Path, scope.Key). + Scan(&storedHash, &storedStatus, &storedBody) + if err != nil { + return nil, mapError(err) + } + + if !bytes.Equal(storedHash, requestHash) { + return nil, &domain.IdempotencyConflictError{Key: scope.Key} + } + + if err := tx.Commit(ctx); err != nil { + return nil, mapError(err) + } + return &domain.CreateIdempotentResult{ + Status: storedStatus, + Body: storedBody, + Replayed: true, + }, nil + } + + // 4) Слот наш — вставляем сообщение в той же транзакции. + if _, err := tx.Exec(ctx, ` + INSERT INTO messages (id, chat_id, sender_id, text, created_at) + VALUES ($1::uuid, $2::uuid, $3::uuid, $4, $5) + `, fresh.ID, fresh.ChatID, fresh.SenderID, fresh.Text, fresh.CreatedAt); err != nil { + if foreignKeyViolation(err) { + return nil, &domain.NotFoundError{Entity: "chat", ID: fresh.ChatID} + } + if checkViolation(err) { + return nil, &domain.ValidationError{Field: "text", Message: "нарушено ограничение"} + } + return nil, mapError(err) + } + + if err := tx.Commit(ctx); err != nil { + return nil, mapError(err) + } + return &domain.CreateIdempotentResult{ + Status: http.StatusCreated, + Body: freshResponse, + Replayed: false, + }, nil +} + +func (r *MessageRepo) ListByChat(ctx context.Context, chatID string, limit int, cursor *string) ([]domain.Message, *string, error) { + scope := "messages:" + chatID + + var ( + afterTime time.Time + afterID string + hasCursor bool + ) + if cursor != nil { + t, id, err := decodeCursor(*cursor, scope) + if err != nil { + return nil, nil, err + } + afterTime = t + afterID = id + hasCursor = true + } + + var ( + rows pgx.Rows + err error + ) + if hasCursor { + const q = ` + SELECT id, chat_id, sender_id, text, created_at + FROM messages + WHERE chat_id = $1::uuid + AND (created_at, id) > ($2, $3::uuid) + ORDER BY created_at, id + LIMIT $4 + ` + rows, err = r.pool.Query(ctx, q, chatID, afterTime, afterID, limit+1) + } else { + const q = ` + SELECT id, chat_id, sender_id, text, created_at + FROM messages + WHERE chat_id = $1::uuid + ORDER BY created_at, id + LIMIT $2 + ` + rows, err = r.pool.Query(ctx, q, chatID, limit+1) + } + if err != nil { + return nil, nil, err + } + defer rows.Close() + + page := make([]domain.Message, 0, limit) + for rows.Next() { + var m domain.Message + if err := rows.Scan(&m.ID, &m.ChatID, &m.SenderID, &m.Text, &m.CreatedAt); err != nil { + return nil, nil, err + } + page = append(page, m) + } + if err := rows.Err(); err != nil { + return nil, nil, err + } + + var next *string + if len(page) > limit { + page = page[:limit] + last := page[len(page)-1] + c := encodeCursor(scope, last.CreatedAt, last.ID) + next = &c + } + return page, next, nil +} + +var _ domain.MessageRepository = (*MessageRepo)(nil) diff --git a/backend/internal/storage/postgres/session.go b/backend/internal/storage/postgres/session.go new file mode 100644 index 0000000..430a9e6 --- /dev/null +++ b/backend/internal/storage/postgres/session.go @@ -0,0 +1,59 @@ +package postgres + +import ( + "context" + + "github.com/jackc/pgx/v5/pgxpool" + + "high-loud-apps-labs/internal/domain" +) + +type SessionRepo struct { + pool *pgxpool.Pool +} + +func NewSessionRepo(pool *pgxpool.Pool) *SessionRepo { + return &SessionRepo{pool: pool} +} + +func (r *SessionRepo) Create(ctx context.Context, s *domain.Session) error { + const q = ` + INSERT INTO sessions (token_hash, user_id, expires_at, created_at) + VALUES ($1, $2::uuid, $3, $4) + ` + _, err := r.pool.Exec(ctx, q, s.TokenHash, s.UserID, s.ExpiresAt, s.CreatedAt) + if err != nil { + if uniqueViolation(err) { + return &domain.AlreadyExistsError{ + Entity: "session", + Field: "token_hash", + Value: "", + } + } + return mapError(err) + } + return nil +} + +func (r *SessionRepo) GetByTokenHash(ctx context.Context, tokenHash []byte) (*domain.Session, error) { + const q = ` + SELECT token_hash, user_id, expires_at, created_at + FROM sessions + WHERE token_hash = $1 + ` + s := &domain.Session{} + err := r.pool.QueryRow(ctx, q, tokenHash). + Scan(&s.TokenHash, &s.UserID, &s.ExpiresAt, &s.CreatedAt) + if err != nil { + return nil, notFound(err, "session", "") + } + return s, nil +} + +func (r *SessionRepo) DeleteByTokenHash(ctx context.Context, tokenHash []byte) error { + const q = `DELETE FROM sessions WHERE token_hash = $1` + _, err := r.pool.Exec(ctx, q, tokenHash) + return mapError(err) +} + +var _ domain.SessionRepository = (*SessionRepo)(nil) diff --git a/backend/internal/storage/postgres/storage.go b/backend/internal/storage/postgres/storage.go new file mode 100644 index 0000000..110fef1 --- /dev/null +++ b/backend/internal/storage/postgres/storage.go @@ -0,0 +1,18 @@ +package postgres + +import "github.com/jackc/pgx/v5/pgxpool" + +type Storage struct { + pool *pgxpool.Pool +} + +func New(pool *pgxpool.Pool) *Storage { + return &Storage{pool: pool} +} + +func (s *Storage) Pool() *pgxpool.Pool { return s.pool } + +func (s *Storage) Users() *UserRepo { return &UserRepo{pool: s.pool} } +func (s *Storage) Chats() *ChatRepo { return &ChatRepo{pool: s.pool} } +func (s *Storage) Messages() *MessageRepo { return &MessageRepo{pool: s.pool} } +func (s *Storage) Sessions() *SessionRepo { return &SessionRepo{pool: s.pool} } diff --git a/backend/internal/storage/postgres/user.go b/backend/internal/storage/postgres/user.go new file mode 100644 index 0000000..418f35a --- /dev/null +++ b/backend/internal/storage/postgres/user.go @@ -0,0 +1,76 @@ +package postgres + +import ( + "context" + + "github.com/jackc/pgx/v5/pgxpool" + + "high-loud-apps-labs/internal/domain" +) + +type UserRepo struct { + pool *pgxpool.Pool +} + +func NewUserRepo(pool *pgxpool.Pool) *UserRepo { + return &UserRepo{pool: pool} +} + +func (r *UserRepo) Create(ctx context.Context, user *domain.User) error { + const q = ` + INSERT INTO users (id, username, display_name, password_hash, created_at) + VALUES ($1::uuid, $2, $3, $4, $5) + ` + _, err := r.pool.Exec(ctx, q, + user.ID, user.Username, user.DisplayName, user.PasswordHash, user.CreatedAt, + ) + if err != nil { + if uniqueViolation(err) { + return &domain.AlreadyExistsError{ + Entity: "user", + Field: "username", + Value: user.Username, + } + } + if checkViolation(err) { + return &domain.ValidationError{ + Field: "user", + Message: "нарушено ограничение целостности", + } + } + return mapError(err) + } + return nil +} + +func (r *UserRepo) GetByID(ctx context.Context, id string) (*domain.User, error) { + const q = ` + SELECT id, username, display_name, password_hash, created_at + FROM users + WHERE id = $1::uuid + ` + u := &domain.User{} + err := r.pool.QueryRow(ctx, q, id). + Scan(&u.ID, &u.Username, &u.DisplayName, &u.PasswordHash, &u.CreatedAt) + if err != nil { + return nil, notFound(err, "user", id) + } + return u, nil +} + +func (r *UserRepo) GetByUsername(ctx context.Context, username string) (*domain.User, error) { + const q = ` + SELECT id, username, display_name, password_hash, created_at + FROM users + WHERE username = $1 + ` + u := &domain.User{} + err := r.pool.QueryRow(ctx, q, username). + Scan(&u.ID, &u.Username, &u.DisplayName, &u.PasswordHash, &u.CreatedAt) + if err != nil { + return nil, notFound(err, "user", username) + } + return u, nil +} + +var _ domain.UserRepository = (*UserRepo)(nil) diff --git a/backend/internal/storage/redis/client.go b/backend/internal/storage/redis/client.go new file mode 100644 index 0000000..0da6614 --- /dev/null +++ b/backend/internal/storage/redis/client.go @@ -0,0 +1,33 @@ +package redis + +import ( + "context" + "fmt" + "time" + + "github.com/redis/go-redis/v9" +) + +func NewClient(url string) (*redis.Client, error) { + opt, err := redis.ParseURL(url) + if err != nil { + return nil, fmt.Errorf("разбор URL: %w", err) + } + + opt.DialTimeout = 700 * time.Millisecond + opt.ReadTimeout = 700 * time.Millisecond + opt.WriteTimeout = 700 * time.Millisecond + opt.MaxRetries = 1 + opt.PoolSize = 10 + opt.ConnMaxIdleTime = time.Minute + + client := redis.NewClient(opt) + + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + if err := client.Ping(ctx).Err(); err != nil { + _ = client.Close() + return nil, fmt.Errorf("ping: %w", err) + } + return client, nil +} diff --git a/backend/internal/storage/redis/errors.go b/backend/internal/storage/redis/errors.go new file mode 100644 index 0000000..55e3422 --- /dev/null +++ b/backend/internal/storage/redis/errors.go @@ -0,0 +1,31 @@ +package redis + +import ( + "context" + "errors" + + "high-loud-apps-labs/internal/domain" +) + +type coded interface { + Code() domain.ErrorCode +} + +// mapError переводит ошибки драйвера в доменные. +// Любая недоступность redis (dial/read/write/context) → UnavailableError (503). +func mapError(err error) error { + if err == nil { + return nil + } + var c coded + if errors.As(err, &c) { + return err + } + if errors.Is(err, context.DeadlineExceeded) { + return &domain.UnavailableError{Reason: "превышено время ожидания redis"} + } + if errors.Is(err, context.Canceled) { + return &domain.UnavailableError{Reason: "запрос отменён"} + } + return &domain.UnavailableError{Reason: err.Error()} +} diff --git a/backend/internal/storage/redis/session.go b/backend/internal/storage/redis/session.go new file mode 100644 index 0000000..0aecfd5 --- /dev/null +++ b/backend/internal/storage/redis/session.go @@ -0,0 +1,80 @@ +package redis + +import ( + "context" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "time" + + "github.com/redis/go-redis/v9" + + "high-loud-apps-labs/internal/domain" +) + +const sessionKeyPrefix = "session:" + +type SessionRepo struct { + client *redis.Client +} + +func NewSessionRepo(client *redis.Client) *SessionRepo { + return &SessionRepo{client: client} +} + +type sessionValue struct { + UserID string `json:"user_id"` + ExpiresAt time.Time `json:"expires_at"` + CreatedAt time.Time `json:"created_at"` +} + +func (r *SessionRepo) key(tokenHash []byte) string { + return sessionKeyPrefix + hex.EncodeToString(tokenHash) +} + +func (r *SessionRepo) Create(ctx context.Context, s *domain.Session) error { + ttl := time.Until(s.ExpiresAt) + if ttl <= 0 { + return nil + } + + data, err := json.Marshal(sessionValue{ + UserID: s.UserID, + ExpiresAt: s.ExpiresAt.UTC(), + CreatedAt: s.CreatedAt.UTC(), + }) + if err != nil { + return fmt.Errorf("сериализация сессии: %w", err) + } + + return mapError(r.client.Set(ctx, r.key(s.TokenHash), data, ttl).Err()) +} + +func (r *SessionRepo) GetByTokenHash(ctx context.Context, tokenHash []byte) (*domain.Session, error) { + data, err := r.client.Get(ctx, r.key(tokenHash)).Bytes() + if err != nil { + if errors.Is(err, redis.Nil) { + return nil, &domain.NotFoundError{Entity: "session"} + } + return nil, mapError(err) + } + + var sv sessionValue + if err := json.Unmarshal(data, &sv); err != nil { + return nil, fmt.Errorf("разбор сессии: %w", err) + } + + return &domain.Session{ + TokenHash: tokenHash, + UserID: sv.UserID, + ExpiresAt: sv.ExpiresAt, + CreatedAt: sv.CreatedAt, + }, nil +} + +func (r *SessionRepo) DeleteByTokenHash(ctx context.Context, tokenHash []byte) error { + return mapError(r.client.Del(ctx, r.key(tokenHash)).Err()) +} + +var _ domain.SessionRepository = (*SessionRepo)(nil) diff --git a/backend/migrations/0001_init.sql b/backend/migrations/0001_init.sql new file mode 100644 index 0000000..d9fad40 --- /dev/null +++ b/backend/migrations/0001_init.sql @@ -0,0 +1,67 @@ +-- +goose Up +-- +goose StatementBegin +CREATE TABLE users ( + id UUID PRIMARY KEY, + username TEXT NOT NULL, + display_name TEXT NOT NULL, + password_hash TEXT NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + CONSTRAINT users_username_format + CHECK (username ~ '^[a-z0-9_]{3,32}$'), + CONSTRAINT users_display_name_not_blank + CHECK (display_name !~ '^[[:space:]]*$'), + CONSTRAINT users_display_name_len + CHECK (char_length(display_name) <= 100), + CONSTRAINT users_password_hash_not_blank + CHECK (length(password_hash) > 0) +); +CREATE UNIQUE INDEX users_username_uniq ON users (username); + +CREATE TABLE chats ( + id UUID PRIMARY KEY, + title TEXT NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + CONSTRAINT chats_title_not_blank CHECK (title !~ '^[[:space:]]*$'), + CONSTRAINT chats_title_len CHECK (char_length(title) <= 100) +); +CREATE INDEX chats_created_id_idx ON chats (created_at, id); + +CREATE TABLE chat_members ( + chat_id UUID NOT NULL REFERENCES chats(id) ON DELETE CASCADE, + user_id UUID NOT NULL REFERENCES users(id) ON DELETE RESTRICT, + joined_at TIMESTAMPTZ NOT NULL DEFAULT now(), + PRIMARY KEY (chat_id, user_id) +); +CREATE INDEX chat_members_user_idx ON chat_members (user_id, chat_id); + +CREATE TABLE messages ( + id UUID PRIMARY KEY, + chat_id UUID NOT NULL REFERENCES chats(id) ON DELETE CASCADE, + sender_id UUID NOT NULL REFERENCES users(id) ON DELETE RESTRICT, + text TEXT NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + CONSTRAINT messages_text_not_blank CHECK (text !~ '^[[:space:]]*$'), + CONSTRAINT messages_text_len CHECK (char_length(text) <= 4000) +); +CREATE INDEX messages_chat_created_id_idx + ON messages (chat_id, created_at, id); + +CREATE TABLE sessions ( + token_hash BYTEA PRIMARY KEY, + user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, + expires_at TIMESTAMPTZ NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + CONSTRAINT sessions_token_hash_len CHECK (octet_length(token_hash) = 32) +); +CREATE INDEX sessions_user_idx ON sessions (user_id); +CREATE INDEX sessions_expires_idx ON sessions (expires_at); +-- +goose StatementEnd + +-- +goose Down +-- +goose StatementBegin +DROP TABLE IF EXISTS sessions; +DROP TABLE IF EXISTS messages; +DROP TABLE IF EXISTS chat_members; +DROP TABLE IF EXISTS chats; +DROP TABLE IF EXISTS users; +-- +goose StatementEnd \ No newline at end of file diff --git a/backend/migrations/0002_idempotency.sql b/backend/migrations/0002_idempotency.sql new file mode 100644 index 0000000..0ad719c --- /dev/null +++ b/backend/migrations/0002_idempotency.sql @@ -0,0 +1,35 @@ +-- +goose Up +-- +goose StatementBegin +CREATE TABLE idempotency_keys ( + user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, + method TEXT NOT NULL, + path TEXT NOT NULL, + key TEXT NOT NULL, + request_hash BYTEA NOT NULL, + response_status INT NOT NULL, + response_body BYTEA NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + expires_at TIMESTAMPTZ NOT NULL, + + CONSTRAINT idempotency_keys_pkey + PRIMARY KEY (user_id, method, path, key), + CONSTRAINT idempotency_keys_key_len + CHECK (char_length(key) BETWEEN 1 AND 128), + CONSTRAINT idempotency_keys_method_len + CHECK (char_length(method) BETWEEN 1 AND 16), + CONSTRAINT idempotency_keys_path_len + CHECK (char_length(path) BETWEEN 1 AND 2048), + CONSTRAINT idempotency_keys_hash_len + CHECK (octet_length(request_hash) = 32), + CONSTRAINT idempotency_keys_status_range + CHECK (response_status BETWEEN 100 AND 599) +); + +CREATE INDEX idempotency_keys_expires_idx + ON idempotency_keys (expires_at); +-- +goose StatementEnd + +-- +goose Down +-- +goose StatementBegin +DROP TABLE IF EXISTS idempotency_keys; +-- +goose StatementEnd \ No newline at end of file diff --git a/backend/migrations/embed.go b/backend/migrations/embed.go new file mode 100644 index 0000000..91cca1c --- /dev/null +++ b/backend/migrations/embed.go @@ -0,0 +1,6 @@ +package migrations + +import "embed" + +//go:embed *.sql +var FS embed.FS diff --git a/compose.yaml b/compose.yaml new file mode 100644 index 0000000..ebacf84 --- /dev/null +++ b/compose.yaml @@ -0,0 +1,163 @@ +name: mtusi-messenger-lab3 + +x-api-resources: &api-resources + limits: + cpus: "${API_CPUS:-0.5}" + memory: "${API_MEMORY:-256M}" + reservations: + cpus: "${API_CPU_RESERVATION:-0.1}" + memory: "${API_MEMORY_RESERVATION:-64M}" + +services: + postgres: + image: postgres:16.4-alpine + restart: unless-stopped + environment: + POSTGRES_USER: messenger + POSTGRES_PASSWORD_FILE: /run/secrets/postgres_password + POSTGRES_DB: messenger + secrets: + - postgres_password + volumes: + - postgres_data:/var/lib/postgresql/data + healthcheck: + test: ["CMD-SHELL", "pg_isready -U messenger -d messenger"] + interval: 5s + timeout: 3s + retries: 10 + start_period: 5s + deploy: + resources: + limits: + cpus: "${POSTGRES_CPUS:-1.0}" + memory: ${POSTGRES_MEMORY:-1G} + reservations: + cpus: "${POSTGRES_CPU_RESERVATION:-0.25}" + memory: ${POSTGRES_MEMORY_RESERVATION:-256M} + networks: + - internal + + redis: + image: redis:7.4-alpine + restart: unless-stopped + command: + - redis-server + - --appendonly + - "yes" + - --appendfsync + - everysec + - --save + - "60 1000" + volumes: + - redis_data:/data + healthcheck: + test: ["CMD", "redis-cli", "ping"] + interval: 5s + timeout: 3s + retries: 10 + start_period: 5s + deploy: + resources: + limits: + cpus: "${REDIS_CPUS:-0.5}" + memory: ${REDIS_MEMORY:-256M} + networks: + - internal + + migrate: + build: + context: . + dockerfile: Dockerfile + image: mtusi-messenger-api:lab3 + restart: "no" + command: ["migrate"] + environment: + DATABASE_URL_FILE: /run/secrets/database_url + secrets: + - database_url + depends_on: + postgres: + condition: service_healthy + healthcheck: + disable: true + deploy: + resources: + limits: + cpus: "0.5" + memory: 128M + networks: + - internal + + api: + build: + context: . + dockerfile: Dockerfile + image: mtusi-messenger-api:lab3 + restart: unless-stopped + environment: + APP_HOST: "0.0.0.0" + APP_PORT: "8080" + DATABASE_URL_FILE: /run/secrets/database_url + CACHE_URL_FILE: /run/secrets/cache_url + SESSION_STORE: "redis" + SESSION_TTL_SECONDS: "${SESSION_TTL_SECONDS:-3600}" + IDEMPOTENCY_TTL_SECONDS: "${IDEMPOTENCY_TTL_SECONDS:-86400}" + SHUTDOWN_DRAIN_SECONDS: "${SHUTDOWN_DRAIN_SECONDS:-3}" + GIN_MODE: "release" + secrets: + - database_url + - cache_url + depends_on: + postgres: + condition: service_healthy + redis: + condition: service_healthy + migrate: + condition: service_completed_successfully + expose: + - "8080" + stop_grace_period: 15s + healthcheck: + test: ["CMD-SHELL", "wget -q -O - http://127.0.0.1:8080/health/ready >/dev/null || exit 1"] + interval: 5s + timeout: 3s + retries: 5 + start_period: 10s + deploy: + replicas: ${API_REPLICAS:-2} + resources: *api-resources + networks: + - internal + + lb: + image: nginx:1.27.4-alpine + restart: unless-stopped + ports: + - "${LB_PORT:-8080}:8080" + volumes: + - ./infra/nginx.conf:/etc/nginx/nginx.conf:ro + depends_on: + api: + condition: service_started + deploy: + resources: + limits: + cpus: "0.5" + memory: 128M + networks: + - internal +secrets: + postgres_password: + file: ./secrets/postgres_password + database_url: + file: ./secrets/database_url + cache_url: + file: ./secrets/cache_url + +volumes: + postgres_data: + redis_data: + +networks: + internal: + driver: bridge \ No newline at end of file diff --git a/infra/nginx.conf b/infra/nginx.conf new file mode 100644 index 0000000..c29a135 --- /dev/null +++ b/infra/nginx.conf @@ -0,0 +1,46 @@ +worker_processes auto; + +events { + worker_connections 1024; +} + +http { + access_log /dev/stdout; + error_log /dev/stderr warn; + + resolver 127.0.0.11 valid=10s ipv6=off; + + upstream backend { + zone backend 64k; + + server api:8080 resolve max_fails=2 fail_timeout=5s; + + keepalive 32; + keepalive_requests 1000; + keepalive_timeout 60s; + } + + server { + listen 8080; + server_tokens off; + + location / { + proxy_pass http://backend; + + proxy_http_version 1.1; + proxy_set_header Connection ""; + + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + + proxy_connect_timeout 2s; + proxy_send_timeout 30s; + proxy_read_timeout 30s; + + proxy_next_upstream error timeout; + proxy_next_upstream_tries 2; + } + } +} \ No newline at end of file diff --git a/student-tests/README.md b/student-tests/README.md new file mode 100644 index 0000000..8deda0f --- /dev/null +++ b/student-tests/README.md @@ -0,0 +1,79 @@ +# Собственные тесты + +Проверки негативных сценариев, конкурентной работы, жизненного цикла +сессий и отказов хранилищ. Отдельно от публичных `tests/`. + +Сервер должен быть поднят на `http://localhost:8080`. + +## Быстрый прогон + + python student-tests/run_all.py --base-url http://localhost:8080 + +Запускает `test_cases.py`, `test_concurrency.py`, `test_auth.py`. +Это базовый набор, не требующий особой конфигурации стенда. + +## Отдельные сценарии + + python student-tests/test_expiry.py --base-url http://localhost:8080 + +Требует стенд с `SESSION_TTL_SECONDS=2`. Проверяет, что сессия +перестаёт работать после истечения TTL. Меняй TTL в `compose.yaml`, +перезапускай api и прогоняй. + + python student-tests/test_resilience.py --service redis + python student-tests/test_resilience.py --service postgres + +Требуют запущенного Docker и работающего стенда. Скрипт останавливает +указанный сервис через `docker compose stop`, проверяет, что защищённые +endpoint отдают 503 unavailable (не 401 и не 500), и запускает сервис +обратно. + +## Данные для EXPLAIN + + python student-tests/seed_messages.py --count 10000 + student-tests/explain_history.sh + +`seed_messages.py` печатает `chat_id`; передай его в `explain_history.sh`, +результат сохранится в `evidence/explain_history.txt`. +## Трек 2: план запроса и восстановление + +Исследование на ≥100 000 сообщениях с неравномерными размерами чатов. + + python student-tests/seed_large.py + # сохранить chat_id из вывода в evidence/chat_ids.txt + + student-tests/explain_history.sh + student-tests/compare_indexes.sh + student-tests/write_bench.sh + student-tests/backup_restore.sh + +Результаты попадают в `evidence/`: + +- `explain_history.txt` — EXPLAIN (ANALYZE, BUFFERS) ключевого запроса +- `index_comparison.txt` — baseline vs covering vs Seq Scan +- `write_cost.txt` — время 5000 INSERT под разными индексами +- `backup_restore.txt` — pg_dump → pg_restore → сверка счётчиков и md5 + +Восстановленный контейнер `pg_restore_target` оставлен для ручной проверки +и удаляется вручную после эксперимента. + +## Нагрузка (k6) + +Open-loop генератор: фиксированный arrival rate, устраняет coordinated +omission, отдельные метрики для POST /messages. Дополняет `tests/load.py` +(closed-loop), а не заменяет его. + + k6 run -e RATE=50 -e DURATION=30s student-tests/load-k6.js + k6 run -e RATE=50 -e DURATION=3m \ + --summary-export evidence/k6-rolling.json \ + student-tests/load-k6.js + +Setup регистрирует отдельного пользователя и создаёт чат. Чтобы нагружать +существующий чат (например, из `seed_large.py`), задай `CHAT_ID` и `TOKEN`: + + CHAT_ID=... TOKEN=... k6 run -e RATE=50 -e DURATION=1m student-tests/load-k6.js + +Summary (`--summary-export`) — JSON с p50/p95/p99 `write_latency_ms`, +`write_errors.rate`, `http_reqs.rate`. Порог `write_errors<1%` встроен в +options.thresholds: k6 вернёт non-zero exit, если под нагрузкой появились +ошибки сверх порога. \ No newline at end of file diff --git a/student-tests/load-k6.js b/student-tests/load-k6.js new file mode 100644 index 0000000..df8c3d1 --- /dev/null +++ b/student-tests/load-k6.js @@ -0,0 +1,125 @@ +// k6 — open-loop нагрузка на POST /messages. +// +// В отличие от tests/load.py (closed-loop) генерирует фиксированный +// arrival rate независимо от того, как быстро отвечает сервер. Это +// устраняет coordinated omission: если сервер тормозит, k6 не снижает +// интенсивность, а честно измеряет latency и долю ошибок. +// +// Два режима: +// 1. Default — setup регистрирует пользователя, логинится и создаёт чат. +// 2. External — если заданы CHAT_ID и TOKEN, используется существующий +// чат (например, из student-tests/seed_large.py). Регистрация не нужна. +// +// Запуск: +// k6 run -e RATE=50 -e DURATION=30s student-tests/load-k6.js +// k6 run -e RATE=50 -e DURATION=3m student-tests/load-k6.js \ +// --summary-export evidence/k6-rolling.json +// CHAT_ID=... TOKEN=... k6 run -e RATE=50 -e DURATION=1m student-tests/load-k6.js +// +// Метрики: +// write_latency_ms — latency POST /messages (p50/p95/p99 в summary) +// write_errors — доля не-201 +// write_total — счётчик запросов + +import http from 'k6/http'; +import encoding from 'k6/encoding'; +import { check, fail } from 'k6'; +import { Trend, Rate, Counter } from 'k6/metrics'; + +const RATE = parseInt(__ENV.RATE || '50', 10); +const DURATION = __ENV.DURATION || '1m'; +const BASE = __ENV.BASE_URL || 'http://localhost:8080'; +const EXTERNAL_CHAT = __ENV.CHAT_ID || ''; +const EXTERNAL_TOKEN = __ENV.TOKEN || ''; + +const writeLatency = new Trend('write_latency_ms', true); +const writeErrors = new Rate('write_errors'); +const writeTotal = new Counter('write_total'); + +export const options = { + scenarios: { + writes: { + executor: 'constant-arrival-rate', + rate: RATE, + timeUnit: '1s', + duration: DURATION, + preAllocatedVUs: Math.max(50, RATE * 2), + maxVUs: Math.max(200, RATE * 4), + }, + }, + thresholds: { + // Порог уровня 4: не более 1% ошибок. В треке 1 проверим, + // удерживается ли при разных профилях нагрузки. + 'write_errors': ['rate<0.01'], + }, +}; + +export function setup() { + if (EXTERNAL_CHAT && EXTERNAL_TOKEN) { + return { token: EXTERNAL_TOKEN, chatId: EXTERNAL_CHAT }; + } + if ((EXTERNAL_CHAT && !EXTERNAL_TOKEN) || (!EXTERNAL_CHAT && EXTERNAL_TOKEN)) { + fail('CHAT_ID и TOKEN должны задаваться вместе'); + } + + const suffix = Math.random().toString(36).slice(2, 10); + const username = `k6_${suffix}`; + const password = 'Example-pass-12345678'; + + const reg = http.post(`${BASE}/api/v1/users`, JSON.stringify({ + username, display_name: `K6 ${suffix}`, password, + }), { headers: { 'Content-Type': 'application/json' } }); + if (reg.status !== 201) fail(`register failed: ${reg.status} ${reg.body}`); + + const user = reg.json(); + const encoded = encoding.b64encode(`${username}:${password}`); + + const sess = http.post(`${BASE}/api/v1/auth/sessions`, null, { + headers: { 'Authorization': `Basic ${encoded}` }, + }); + if (sess.status !== 201) fail(`login failed: ${sess.status} ${sess.body}`); + + const token = sess.json().token; + + const chat = http.post(`${BASE}/api/v1/chats`, JSON.stringify({ + title: `k6 chat ${suffix}`, + member_ids: [user.id], + }), { + headers: { + 'Content-Type': 'application/json', + 'Authorization': `Bearer ${token}`, + }, + }); + if (chat.status !== 201) fail(`chat failed: ${chat.status} ${chat.body}`); + + return { token, chatId: chat.json().id }; +} + +export default function (data) { + const key = `k6-${__VU}-${__ITER}-${Date.now()}`; + const body = JSON.stringify({ text: `msg vu=${__VU} iter=${__ITER}` }); + + const res = http.post( + `${BASE}/api/v1/chats/${data.chatId}/messages`, + body, + { + headers: { + 'Content-Type': 'application/json', + 'Authorization': `Bearer ${data.token}`, + 'Idempotency-Key': key, + }, + tags: { name: 'POST /messages' }, + }, + ); + + writeTotal.add(1); + writeLatency.add(res.timings.duration); + writeErrors.add(res.status !== 201); + + check(res, { + 'status is 201': (r) => r.status === 201, + 'has message id': (r) => { + try { return !!r.json().id; } catch { return false; } + }, + }); +} \ No newline at end of file diff --git a/student-tests/run_all.py b/student-tests/run_all.py new file mode 100644 index 0000000..69f0467 --- /dev/null +++ b/student-tests/run_all.py @@ -0,0 +1,26 @@ +#!/usr/bin/env python3 +import subprocess +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parent + +QUICK = ('test_cases.py', 'test_concurrency.py', 'test_auth.py') + + +def main(): + args = sys.argv[1:] + failed = [] + for script in QUICK: + print(f'=== {script} ===') + result = subprocess.run([sys.executable, str(ROOT / script), *args]) + if result.returncode != 0: + failed.append(script) + if failed: + print('FAILED:', ', '.join(failed)) + sys.exit(1) + print('=== Все тесты прошли ===') + + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/student-tests/seed_large.py b/student-tests/seed_large.py new file mode 100644 index 0000000..4aeabad --- /dev/null +++ b/student-tests/seed_large.py @@ -0,0 +1,82 @@ +#!/usr/bin/env python3 +"""Сидирует 100k сообщений в 24 чата с неравномерными размерами (трек 2).""" +import base64 +import sys +import time +import uuid +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / 'tests')) + +from client import Client, arguments, check, run # noqa: E402 + + +def make_user(c, label): + username = f'{label}_{uuid.uuid4().hex[:12]}' + password = 'T3st-' + uuid.uuid4().hex + user = c.call('POST', '/api/v1/users', 201, body={ + 'username': username, 'display_name': label.capitalize(), + 'password': password}, schema='User')['json'] + cred = base64.b64encode(f'{username}:{password}'.encode()).decode() + s = c.call('POST', '/api/v1/auth/sessions', 201, + headers={'Authorization': 'Basic ' + cred}, schema='Session')['json'] + return {'id': user['id'], 'username': username, 'token': s['token']} + + +def seed_chat(base_url, ca_file, alice, bob, title, count, workers=8): + c = Client(base_url, ca_file) + chat = c.call('POST', '/api/v1/chats', 201, actor=alice, body={ + 'title': title, 'member_ids': [alice['id'], bob['id']]}, + schema='Chat')['json'] + chat_id = chat['id'] + + per_worker = count // workers + remainder = count - per_worker * workers + + def worker(wid): + local = Client(base_url, ca_file, timeout=20) + n = per_worker + (1 if wid < remainder else 0) + for i in range(n): + local.call('POST', f'/api/v1/chats/{chat_id}/messages', 201, + actor=alice, body={'text': f'{title} #{wid}-{i}'}, + schema='Message') + + started = time.monotonic() + with ThreadPoolExecutor(max_workers=workers) as pool: + list(pool.map(worker, range(workers))) + elapsed = time.monotonic() - started + print(f' {title}: {count} сообщений за {elapsed:.1f}s ({count/max(elapsed,0.001):.0f}/s)') + return chat_id + + +def main(): + args = arguments('Сидирует неравномерные чаты для трека 2') + c = Client(args.base_url, args.ca_file) + alice = make_user(c, 'track2_a') + bob = make_user(c, 'track2_b') + + plan = ( + [('hot', 55_000)] + + [('medium-%d' % i, 10_000) for i in range(1, 4)] + + [('small-%d' % i, 1_000) for i in range(1, 11)] + + [('tiny-%d' % i, 500) for i in range(1, 11)] + ) + total = sum(n for _, n in plan) + check(total == 100_000, f'сумма {total} != 100000') + + result = {} + started = time.monotonic() + for title, count in plan: + result[title] = seed_chat(args.base_url, args.ca_file, alice, bob, title, count) + elapsed = time.monotonic() - started + + print(f'\nВсего {total} сообщений за {elapsed:.1f}s ({total/elapsed:.0f}/s)') + print('chat_id для EXPLAIN (сохраните эти значения):') + for title in ('hot', 'medium-1', 'small-1', 'tiny-1'): + print(f' {title}: {result[title]}') + + +if __name__ == '__main__': + run(main) \ No newline at end of file diff --git a/student-tests/seed_messages.py b/student-tests/seed_messages.py new file mode 100644 index 0000000..47bd608 --- /dev/null +++ b/student-tests/seed_messages.py @@ -0,0 +1,56 @@ +#!/usr/bin/env python3 +"""Заполняет один чат N сообщениями. Надо EXPLAIN.""" +import base64 +import sys +import time +import uuid +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / 'tests')) + +from client import Client, arguments, check, run # noqa: E402 + + +def make_user(c, label): + username = f'{label}_{uuid.uuid4().hex[:12]}' + password = 'T3st-' + uuid.uuid4().hex + user = c.call('POST', '/api/v1/users', 201, body={ + 'username': username, 'display_name': label.capitalize(), + 'password': password}, schema='User')['json'] + cred = base64.b64encode(f'{username}:{password}'.encode()).decode() + s = c.call('POST', '/api/v1/auth/sessions', 201, + headers={'Authorization': 'Basic ' + cred}, schema='Session')['json'] + return {'id': user['id'], 'token': s['token']} + + +def main(): + def configure(p): + p.add_argument('--count', type=int, default=10000) + + args = arguments('Сид для EXPLAIN: создаёт count сообщений в новом чате', configure) + check(args.count >= 1 and args.count <= 1_000_000, 'count вне диапазона') + + c = Client(args.base_url, args.ca_file) + alice = make_user(c, 'seed_a') + bob = make_user(c, 'seed_b') + + chat = c.call('POST', '/api/v1/chats', 201, actor=alice, body={ + 'title': 'Seed chat', 'member_ids': [alice['id'], bob['id']]}, + schema='Chat')['json'] + + started = time.monotonic() + for i in range(args.count): + c.call('POST', f"/api/v1/chats/{chat['id']}/messages", 201, + actor=alice, body={'text': f'seed message {i}'}, schema='Message') + if (i + 1) % 1000 == 0: + print(f' {i + 1}/{args.count}') + + elapsed = time.monotonic() - started + print(f'seeded {args.count} messages in {elapsed:.1f}s ' + f'({args.count / elapsed:.0f}/s)') + print(f'chat_id={chat["id"]}') + + +if __name__ == '__main__': + run(main) \ No newline at end of file diff --git a/student-tests/test_auth.py b/student-tests/test_auth.py new file mode 100644 index 0000000..5fab75d --- /dev/null +++ b/student-tests/test_auth.py @@ -0,0 +1,81 @@ +#!/usr/bin/env python3 +import base64 +import uuid +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / 'tests')) + +from client import Client, Failure, arguments, check, run # noqa: E402 + + +def register(c, username, password): + c.call('POST', '/api/v1/users', 201, body={ + 'username': username, + 'display_name': 'Auth test', + 'password': password, + }) + + +def login(c, username, password): + cred = base64.b64encode(f'{username}:{password}'.encode()).decode() + r = c.call('POST', '/api/v1/auth/sessions', 201, + headers={'Authorization': 'Basic ' + cred}, schema='Session') + return r['json'] + + +def main(): + args = arguments('Logout и неверные учётные данные') + c = Client(args.base_url, args.ca_file) + + # --- logout отзывает текущую сессию --- + username = 'lo_' + uuid.uuid4().hex[:10] + password = 'T3st-' + uuid.uuid4().hex + register(c, username, password) + session = login(c, username, password) + actor = {'id': session['user']['id'], 'token': session['token']} + + # токен работает + c.call('GET', '/api/v1/users/me', actor=actor, schema='User') + + # отзываем + c.call('DELETE', '/api/v1/auth/sessions/current', 204, actor=actor) + + # тот же токен больше не работает + c.call('GET', '/api/v1/users/me', 401, actor=actor) + c.call('DELETE', '/api/v1/auth/sessions/current', 401, actor=actor) + + # --- неверный пароль и неизвестный username дают одинаковый 401 --- + wrong = base64.b64encode(f'{username}:wrong-password-123'.encode()).decode() + r_wrong = c.call('POST', '/api/v1/auth/sessions', 401, + headers={'Authorization': 'Basic ' + wrong}) + check('Basic' in r_wrong['headers'].get('WWW-Authenticate', ''), + 'нет WWW-Authenticate: Basic на неверный пароль') + + unknown = base64.b64encode( + f'nobody_{uuid.uuid4().hex[:10]}:any-password-123'.encode()).decode() + r_unknown = c.call('POST', '/api/v1/auth/sessions', 401, + headers={'Authorization': 'Basic ' + unknown}) + + check(r_wrong['json']['error']['code'] == 'unauthorized', + 'неверный пароль: ожидался код unauthorized') + check(r_unknown['json']['error']['code'] == 'unauthorized', + 'неизвестный username: ожидался код unauthorized') + check(r_wrong['json']['error']['message'] == r_unknown['json']['error']['message'], + 'сообщения отличаются: перебор username возможен') + + # --- X-User-Id не даёт доступ в lab2 --- + c.call('GET', '/api/v1/users/me', 401, + headers={'X-User-Id': session['user']['id']}) + + # --- Basic на бизнес-endpoint не проходит --- + good = base64.b64encode(f'{username}:{password}'.encode()).decode() + c.call('GET', '/api/v1/users/me', 401, + headers={'Authorization': 'Basic ' + good}) + + print('PASS: logout, wrong password, X-User-Id и Basic на бизнес-endpoint') + + +if __name__ == '__main__': + run(main) \ No newline at end of file diff --git a/student-tests/test_cases.py b/student-tests/test_cases.py new file mode 100644 index 0000000..e939d66 --- /dev/null +++ b/student-tests/test_cases.py @@ -0,0 +1,112 @@ +#!/usr/bin/env python3 +import sys +import uuid +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / 'tests')) + +from client import Client, LAB, Failure, arguments, check, run # noqa: E402 + + +def main(): + args = arguments('Собственные тесты негативных сценариев') + c = Client(args.base_url, args.ca_file) + alice, bob, eve, chat = c.bootstrap() + path = '/api/v1/chats/' + chat['id'] + + # --- некорректный JSON --- + malformed = b'{"username":"alice","display_name":"A"' + c.call('POST', '/api/v1/users', 400, raw=malformed, + headers={'Content-Type': 'application/json'}) + + # --- лишнее поле --- + c.call('POST', '/api/v1/users', 400, + body={'username': 'u_' + uuid.uuid4().hex[:8], + 'display_name': 'X', 'extra': 'мусор'}) + + # --- неверный тип поля --- + c.call('POST', '/api/v1/users', 400, + body={'username': 123, 'display_name': 'X'}) + + # --- пустой display_name --- + c.call('POST', '/api/v1/users', 400, + body={'username': 'u_' + uuid.uuid4().hex[:8], 'display_name': ''}) + + # --- display_name только из пробелов --- + c.call('POST', '/api/v1/users', 400, + body={'username': 'u_' + uuid.uuid4().hex[:8], 'display_name': ' '}) + + # --- заглавные в username --- + c.call('POST', '/api/v1/users', 400, + body={'username': 'UPPERCASE', 'display_name': 'X'}) + + # --- дубликат username --- + c.call('POST', '/api/v1/users', 409, body=alice['registration']) + + # --- пустое сообщение --- + c.call('POST', path + '/messages', 400, actor=alice, body={'text': ''}) + + # --- сообщение только из пробелов --- + c.call('POST', path + '/messages', 400, actor=alice, body={'text': ' '}) + + # --- чужой чат --- + c.call('GET', path, 404, actor=eve) + c.call('GET', path + '/messages', 404, actor=eve) + c.call('POST', path + '/messages', 404, actor=eve, body={'text': 'чужое'}) + + # --- чат без создателя в member_ids --- + c.call('POST', '/api/v1/chats', 400, actor=alice, + body={'title': 'Без меня', 'member_ids': [bob['id']]}) + + # --- чат с неизвестным участником --- + c.call('POST', '/api/v1/chats', 400, actor=alice, + body={'title': 'С фантомом', + 'member_ids': [alice['id'], '00000000-0000-4000-8000-000000000000']}) + + # --- чат с дубликатами --- + c.call('POST', '/api/v1/chats', 400, actor=alice, + body={'title': 'Дубликаты', 'member_ids': [alice['id'], alice['id']]}) + + # --- обход нескольких страниц --- + for i in range(5): + c.message(alice, chat, 'page-test-%d' % i) + + seen = [] + cursor = None + for _ in range(20): + query = path + '/messages?limit=2' + if cursor: + from urllib.parse import quote + query += '&cursor=' + quote(cursor, safe='') + page = c.call('GET', query, actor=alice, schema='MessagePage')['json'] + seen.extend(x['id'] for x in page['items']) + cursor = page['next_cursor'] + if cursor is None: + break + check(len(seen) == len(set(seen)), 'пагинация вернула дубликаты') + check(len(seen) >= 5, 'пагинация потеряла сообщения') + + # --- cursor от другого чата --- + other_chat = c.call('POST', '/api/v1/chats', 201, actor=alice, + body={'title': 'Другой чат', + 'member_ids': [alice['id'], bob['id']]}, + schema='Chat')['json'] + other_path = '/api/v1/chats/' + other_chat['id'] + c.message(alice, other_chat, 'other-1') + c.message(alice, other_chat, 'other-2') + + other_page = c.call('GET', other_path + '/messages?limit=1', actor=alice, + schema='MessagePage')['json'] + other_cursor = other_page['next_cursor'] + check(other_cursor is not None, 'ожидался cursor от другого чата, но получен null') + + from urllib.parse import quote + c.call('GET', path + '/messages?limit=2&cursor=' + quote(other_cursor, safe=''), + 400, actor=alice) + + print('PASS: негативные сценарии прошли') + + +if __name__ == '__main__': + run(main) \ No newline at end of file diff --git a/student-tests/test_concurrency.py b/student-tests/test_concurrency.py new file mode 100644 index 0000000..05fd018 --- /dev/null +++ b/student-tests/test_concurrency.py @@ -0,0 +1,81 @@ +#!/usr/bin/env python3 +import threading +import uuid +from concurrent.futures import ThreadPoolExecutor + +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / 'tests')) + +from client import Client, LAB, Failure, arguments, check, run # noqa: E402 + + +def main(): + args = arguments('Собственные тесты конкурентности') + c = Client(args.base_url, args.ca_file) + alice, bob, eve, chat = c.bootstrap() + path = '/api/v1/chats/' + chat['id'] + + # --- 100 сообщений от 10 потоков --- + workers = 10 + per_worker = 10 + expected_total = workers * per_worker + barrier = threading.Barrier(workers) + + def writer(worker_id): + local = Client(args.base_url, args.ca_file, timeout=10) + barrier.wait() + for i in range(per_worker): + local.message(alice, chat, 'c-%d-%d' % (worker_id, i)) + + with ThreadPoolExecutor(max_workers=workers) as pool: + list(pool.map(writer, range(workers))) + + seen = [] + cursor = None + while True: + q = path + '/messages?limit=100' + if cursor: + from urllib.parse import quote + q += '&cursor=' + quote(cursor, safe='') + page = c.call('GET', q, actor=alice, schema='MessagePage')['json'] + seen.extend(x['id'] for x in page['items']) + cursor = page['next_cursor'] + if cursor is None: + break + + check(len(seen) == len(set(seen)), 'после параллельной записи обнаружены дубликаты id сообщений') + check(len(seen) == expected_total, + 'ожидалось ровно %d сообщений, получено %d' % (expected_total, len(seen))) + + # --- гонка за username --- + username = 'race_' + uuid.uuid4().hex[:8] + password = 'T3st-' + uuid.uuid4().hex + body = {'username': username, 'display_name': 'Race', 'password': password} + barrier2 = threading.Barrier(workers) + + def register(_): + local = Client(args.base_url, args.ca_file, timeout=10) + barrier2.wait() + try: + local.call('POST', '/api/v1/users', 201, body=body) + return 'ok' + except Failure: + return 'conflict' + + with ThreadPoolExecutor(max_workers=workers) as pool: + results = list(pool.map(register, range(workers))) + + ok_count = results.count('ok') + conflict_count = results.count('conflict') + check(ok_count == 1, 'ожидалась ровно одна успешная регистрация, получено %d' % ok_count) + check(conflict_count == workers - 1, + 'ожидалось %d конфликтов, получено %d' % (workers - 1, conflict_count)) + + print('PASS: конкурентность (100 сообщений, 1 победитель в гонке за username)') + + +if __name__ == '__main__': + run(main) \ No newline at end of file diff --git a/student-tests/test_expiry.py b/student-tests/test_expiry.py new file mode 100644 index 0000000..b79aa2a --- /dev/null +++ b/student-tests/test_expiry.py @@ -0,0 +1,46 @@ +#!/usr/bin/env python3 +import base64 +import time +import uuid +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / 'tests')) + +from client import Client, arguments, check, run # noqa: E402 + + +def main(): + args = arguments('Истечение сессии. Требует SESSION_TTL_SECONDS=2') + c = Client(args.base_url, args.ca_file) + + username = 'exp_' + uuid.uuid4().hex[:10] + password = 'T3st-' + uuid.uuid4().hex + c.call('POST', '/api/v1/users', 201, body={ + 'username': username, 'display_name': 'Exp', 'password': password}) + + cred = base64.b64encode(f'{username}:{password}'.encode()).decode() + s = c.call('POST', '/api/v1/auth/sessions', 201, + headers={'Authorization': 'Basic ' + cred}, schema='Session')['json'] + actor = {'id': s['user']['id'], 'token': s['token']} + + # сразу после логина — работает + c.call('GET', '/api/v1/users/me', actor=actor, schema='User') + + # ждём больше TTL. Если TTL не 2, тест упадёт с понятным сообщением + # (см. проверку ниже по факту отказа). + time.sleep(3.5) + + # ожидаем 401 с Bearer challenge + r = c.call('GET', '/api/v1/users/me', 401, actor=actor) + challenge = r['headers'].get('WWW-Authenticate', '') + check(challenge.lower().startswith('bearer'), + f'ожидался WWW-Authenticate: Bearer, получено {challenge!r}') + + # и сразу проверяем, что до истечения он работал — уже сделано выше + print('PASS: сессия истекла после TTL и вернула 401 Bearer') + + +if __name__ == '__main__': + run(main) \ No newline at end of file diff --git a/student-tests/test_resilience.py b/student-tests/test_resilience.py new file mode 100644 index 0000000..5f1b0f5 --- /dev/null +++ b/student-tests/test_resilience.py @@ -0,0 +1,89 @@ +#!/usr/bin/env python3 +import argparse +import subprocess +import time +import uuid +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / 'tests')) + +from client import Client, check, run # noqa: E402 + +REPO_ROOT = ROOT + + +def compose(*args, timeout=90): + return subprocess.run( + ['docker', 'compose', '--env-file', '.env', *args], + cwd=REPO_ROOT, capture_output=True, text=True, timeout=timeout, + ) + + +def make_user(c): + username = 'rs_' + uuid.uuid4().hex[:10] + password = 'T3st-' + uuid.uuid4().hex + c.call('POST', '/api/v1/users', 201, body={ + 'username': username, 'display_name': 'Res', 'password': password}) + import base64 + cred = base64.b64encode(f'{username}:{password}'.encode()).decode() + s = c.call('POST', '/api/v1/auth/sessions', 201, + headers={'Authorization': 'Basic ' + cred}, schema='Session')['json'] + return {'id': s['user']['id'], 'token': s['token']} + + +def wait_ready(c, seconds=90): + deadline = time.monotonic() + seconds + while time.monotonic() < deadline: + try: + c.call('GET', '/health/ready', schema='Health') + return + except Exception: + time.sleep(1) + raise RuntimeError('health/ready не восстановился за %d секунд' % seconds) + + +def main(): + p = argparse.ArgumentParser() + p.add_argument('--service', choices=['redis', 'postgres'], required=True) + p.add_argument('--base-url', default=None) + args = p.parse_args() + + c = Client(args.base_url) + alice = make_user(c) + c.call('GET', '/api/v1/users/me', actor=alice, schema='User') + + print(f'[{args.service}] останавливаем сервис') + r = compose('stop', args.service) + check(r.returncode == 0, f'docker compose stop: {r.stderr.strip()}') + + try: + time.sleep(2) + + # Защищённый endpoint должен вернуть 503 unavailable. + resp = c.call('GET', '/api/v1/users/me', 503, actor=alice) + code = resp['json']['error']['code'] + check(code == 'unavailable', + f'ожидался код unavailable, получено {code!r}') + + # Сообщение не должно раскрывать детали про Redis/Postgres/сеть. + msg = resp['json']['error']['message'].lower() + for bad in ('redis', 'postgres', 'sql', 'connection', 'refused', 'dial'): + check(bad not in msg, f'сообщение раскрывает "{bad}": {msg}') + + # Здоровье тоже должно репортить 503. + c.call('GET', '/health/ready', 503) + finally: + print(f'[{args.service}] запускаем сервис обратно') + r = compose('start', args.service) + check(r.returncode == 0, f'docker compose start: {r.stderr.strip()}') + wait_ready(c) + + # Токен alice всё ещё валиден после возврата сервиса. + c.call('GET', '/api/v1/users/me', actor=alice, schema='User') + print(f'PASS: {args.service} недоступен → 503 unavailable без утечек; восстановление OK') + + +if __name__ == '__main__': + run(main) \ No newline at end of file