From 14166003b827e2ce52e6aea45df86f4ef0c64393 Mon Sep 17 00:00:00 2001 From: morodik Date: Wed, 28 Oct 2026 14:12:41 +0300 Subject: [PATCH] =?UTF-8?q?=D0=BA=D0=BE=D0=B4=20=D0=B8=D0=B7=20lab3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 1 + Dockerfile | 24 + cmd/api/main.go | 115 +++ compose.yml | 121 +++ docs/architecture.png | Bin 0 -> 24037 bytes docs/architecture.puml | 24 + docs/track-5-report-md | 52 ++ go.mod | 226 ++++++ go.sum | 862 ++++++++++++++++++++++ infra/haproxy.cfg | 31 + internal/auth/password.go | 76 ++ internal/auth/session.go | 15 + internal/cache/cache.go | 67 ++ internal/config/config.go | 37 + internal/cursor/cursor.go | 45 ++ internal/db/db.go | 42 ++ internal/httpapi/api_test.go | 983 +++++++++++++++++++++++++ internal/httpapi/auth.go | 110 +++ internal/httpapi/chats.go | 131 ++++ internal/httpapi/health.go | 39 + internal/httpapi/httpx.go | 98 +++ internal/httpapi/idempotency_test.go | 184 +++++ internal/httpapi/messages.go | 80 ++ internal/httpapi/middleware.go | 41 ++ internal/httpapi/race_test.go | 163 ++++ internal/httpapi/router.go | 84 +++ internal/httpapi/sessionstore_test.go | 73 ++ internal/httpapi/testmain_test.go | 145 ++++ internal/httpapi/transaction_test.go | 63 ++ internal/httpapi/users.go | 117 +++ internal/httpapi/validate.go | 45 ++ internal/idgen/uuid.go | 23 + internal/model/model.go | 65 ++ internal/sessionstore/redis.go | 73 ++ internal/sessionstore/sessionstore.go | 18 + internal/store/limits.go | 51 ++ internal/store/store.go | 436 +++++++++++ migrations/000001_init_schema.down.sql | 7 + migrations/000001_init_schema.up.sql | 49 ++ migrations/000002_idempotency.up.sql | 11 + scripts/check_edge.py | 51 ++ scripts/check_lb.py | 65 ++ scripts/explain_messages.sql | 69 ++ scripts/failover-under-load.sh | 20 + scripts/measure_failover.py | 91 +++ scripts/restart.sh | 4 + scripts/rolling-under-load.sh | 16 + scripts/rolling-update.sh | 18 + scripts/stop-one.sh | 13 + 49 files changed, 5174 insertions(+) create mode 100644 Dockerfile create mode 100644 cmd/api/main.go create mode 100644 compose.yml create mode 100644 docs/architecture.png create mode 100644 docs/architecture.puml create mode 100644 docs/track-5-report-md create mode 100644 go.mod create mode 100644 go.sum create mode 100644 infra/haproxy.cfg create mode 100644 internal/auth/password.go create mode 100644 internal/auth/session.go create mode 100644 internal/cache/cache.go create mode 100644 internal/config/config.go create mode 100644 internal/cursor/cursor.go create mode 100644 internal/db/db.go create mode 100644 internal/httpapi/api_test.go create mode 100644 internal/httpapi/auth.go create mode 100644 internal/httpapi/chats.go create mode 100644 internal/httpapi/health.go create mode 100644 internal/httpapi/httpx.go create mode 100644 internal/httpapi/idempotency_test.go create mode 100644 internal/httpapi/messages.go create mode 100644 internal/httpapi/middleware.go create mode 100644 internal/httpapi/race_test.go create mode 100644 internal/httpapi/router.go create mode 100644 internal/httpapi/sessionstore_test.go create mode 100644 internal/httpapi/testmain_test.go create mode 100644 internal/httpapi/transaction_test.go create mode 100644 internal/httpapi/users.go create mode 100644 internal/httpapi/validate.go create mode 100644 internal/idgen/uuid.go create mode 100644 internal/model/model.go create mode 100644 internal/sessionstore/redis.go create mode 100644 internal/sessionstore/sessionstore.go create mode 100644 internal/store/limits.go create mode 100644 internal/store/store.go create mode 100644 migrations/000001_init_schema.down.sql create mode 100644 migrations/000001_init_schema.up.sql create mode 100644 migrations/000002_idempotency.up.sql create mode 100644 scripts/check_edge.py create mode 100644 scripts/check_lb.py create mode 100644 scripts/explain_messages.sql create mode 100755 scripts/failover-under-load.sh create mode 100644 scripts/measure_failover.py create mode 100755 scripts/restart.sh create mode 100755 scripts/rolling-under-load.sh create mode 100755 scripts/rolling-update.sh create mode 100755 scripts/stop-one.sh diff --git a/.gitignore b/.gitignore index b5a7189..e723c13 100644 --- a/.gitignore +++ b/.gitignore @@ -30,3 +30,4 @@ coverage/ .vscode/ # Keep small, sanitized evidence summaries in evidence/ under version control. # Inspect git diff --cached: ignore rules are not a secret scanner. +secrets/ \ No newline at end of file diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..e9e5507 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,24 @@ +FROM golang:1.27-alpine AS builder + +WORKDIR /app +COPY go.mod go.sum ./ +RUN go mod download + +COPY . . +RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -o /out/api ./cmd/api + +FROM alpine:3.20 + +RUN apk add --no-cache ca-certificates wget \ + && addgroup -S app && adduser -S app -G app + +WORKDIR /app +COPY --from=builder /out/api . + +USER app +EXPOSE 8080 + +HEALTHCHECK --interval=10s --timeout=3s --start-period=5s --retries=3 \ + CMD wget -qO- http://127.0.0.1:8080/health/ready || exit 1 + +CMD ["./api"] \ No newline at end of file diff --git a/cmd/api/main.go b/cmd/api/main.go new file mode 100644 index 0000000..10c70ed --- /dev/null +++ b/cmd/api/main.go @@ -0,0 +1,115 @@ +package main + +import ( + "context" + "log" + "net/http" + "os" + "os/signal" + "sync/atomic" + "syscall" + "time" + + "mtusi2026/internal/cache" + "mtusi2026/internal/config" + "mtusi2026/internal/db" + "mtusi2026/internal/httpapi" + "mtusi2026/internal/sessionstore" + "mtusi2026/internal/store" + + "github.com/redis/go-redis/v9" +) + +func main() { + ctx := context.Background() + + dbCfg := db.Config{ + DSN: config.GetEnv("DATABASE_URL", ""), + MaxConns: int32(config.ParseIntEnv("DB_MAX_CONNS", 10)), + MinConns: int32(config.ParseIntEnv("DB_MIN_CONNS", 2)), + ConnMaxLifetime: config.ParseDurationSecondsEnv("DB_CONN_MAX_LIFETIME_SECONDS", 3600), + ConnTimeout: config.ParseDurationSecondsEnv("DB_CONN_TIMEOUT_SECONDS", 5), + } + if dbCfg.DSN == "" { + log.Fatal("DATABASE_URL is required") + } + + pool, err := db.Connect(ctx, dbCfg) + if err != nil { + log.Fatalf("db connect: %v", err) + } + defer pool.Close() + + maxMessages := int64(config.ParseIntEnv("MAX_MESSAGES", 10000)) + maxConcurrent := config.ParseIntEnv("MAX_CONCURRENT_REQUESTS", 50) + + limiter := store.NewLimiter(maxMessages, maxConcurrent) + + cacheURL := config.GetEnv("CACHE_URL", "") + if cacheURL == "" { + log.Fatal("CACHE_URL is required") + } + + redisOpts, err := redis.ParseURL(cacheURL) + if err != nil { + log.Fatalf("redis config: %v", err) + } + + redisClient := redis.NewClient(redisOpts) + defer redisClient.Close() + + if err := redisClient.Ping(ctx).Err(); err != nil { + log.Fatalf("redis connect: %v", err) + } + + sessionStore := sessionstore.NewRedis(redisClient) + + chatCacheTTL := config.ParseDurationSecondsEnv("CHAT_CACHE_TTL_SECONDS", 30) + chatCache := cache.New(redisClient, chatCacheTTL) + + s := store.New(pool, limiter) + + instanceID := config.GetEnv("INSTANCE_ID", "") + if instanceID == "" { + instanceID, _ = os.Hostname() + } + var draining atomic.Bool + + mux := httpapi.NewRouterWithCache(s, pool, sessionStore, chatCache, httpapi.Options{ + InstanceID: instanceID, + Redis: redisClient, + Draining: &draining, + }) + + port := config.GetEnv("PORT", "8080") + srv := &http.Server{ + Addr: ":" + port, + Handler: mux, + ReadHeaderTimeout: 5 * time.Second, + ReadTimeout: 15 * time.Second, + WriteTimeout: 15 * time.Second, + IdleTimeout: 60 * time.Second, + } + + ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, syscall.SIGINT) + defer stop() + + go func() { + log.Printf("запуск на :%s instance=%s", port, instanceID) + if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed { + log.Fatalf("сервер упал: %v", err) + } + }() + + <-ctx.Done() + log.Println("Получен сигнал остановки: readiness -> 503, жду LB...") + draining.Store(true) + time.Sleep(time.Duration(config.ParseIntEnv("DRAIN_SECONDS", 4)) * time.Second) + + shutdownCtx, cancel := context.WithTimeout(context.Background(), 12*time.Second) + defer cancel() + if err := srv.Shutdown(shutdownCtx); err != nil { + log.Printf("принудительное завершение: %v", err) + } + log.Println("Остановлен") +} diff --git a/compose.yml b/compose.yml new file mode 100644 index 0000000..0683f03 --- /dev/null +++ b/compose.yml @@ -0,0 +1,121 @@ +services: + postgres: + image: postgres:16.4-alpine + environment: + POSTGRES_USER: ${POSTGRES_USER} + POSTGRES_DB: ${POSTGRES_DB} + POSTGRES_PASSWORD_FILE: /run/secrets/postgres_password + secrets: + - postgres_password + volumes: + - postgres-data:/var/lib/postgresql/data + healthcheck: + test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER} -d ${POSTGRES_DB}"] + interval: 5s + timeout: 3s + retries: 10 + start_period: 5s + networks: [data] + deploy: + resources: + limits: { cpus: "1.0", memory: 512M } + + redis: + image: redis:7.4-alpine + command: ["redis-server", "--appendonly", "yes"] + volumes: + - redis-data:/data + healthcheck: + test: ["CMD", "redis-cli", "ping"] + interval: 5s + timeout: 3s + retries: 10 + start_period: 5s + networks: [data] + deploy: + resources: + limits: { cpus: "0.25", memory: 128M } + + migrate: + image: migrate/migrate:v4.17.1 + depends_on: + postgres: + condition: service_healthy + volumes: + - ./migrations:/migrations + command: + - "-path=/migrations" + - "-database=postgres://${POSTGRES_USER}:${POSTGRES_PASSWORD}@postgres:5432/${POSTGRES_DB}?sslmode=disable" + - "up" + restart: "no" + networks: [data] + deploy: + resources: + limits: { cpus: "0.25", memory: 128M } + + api: + build: + context: . + dockerfile: Dockerfile + depends_on: + postgres: + condition: service_healthy + migrate: + condition: service_completed_successfully + redis: + condition: service_healthy + environment: + PORT: ${PORT} + DATABASE_URL_FILE: /run/secrets/database_url + SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS} + MAX_CONCURRENT_REQUESTS: ${MAX_CONCURRENT_REQUESTS} + DB_MAX_CONNS: ${DB_MAX_CONNS} + DB_MIN_CONNS: ${DB_MIN_CONNS} + DB_CONN_TIMEOUT_SECONDS: ${DB_CONN_TIMEOUT_SECONDS} + CACHE_URL: ${CACHE_URL} + CHAT_CACHE_TTL_SECONDS: 30 + DRAIN_SECONDS: 4 + GOMEMLIMIT: 200MiB + APP_VERSION: ${APP_VERSION:-dev} + secrets: + - database_url + stop_grace_period: 20s + healthcheck: + test: ["CMD", "wget", "-qO-", "http://127.0.0.1:8080/health/ready"] + interval: 3s + timeout: 2s + retries: 3 + start_period: 5s + networks: [edge, data] + deploy: + replicas: 2 + resources: + limits: { cpus: "0.5", memory: 256M } + + lb: + image: haproxy:3.0-alpine + depends_on: + api: + condition: service_healthy + volumes: + - ./infra/haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro + ports: + - "127.0.0.1:8080:8080" + networks: [edge] + deploy: + resources: + limits: { cpus: "0.25", memory: 128M } + +networks: + edge: + data: + +secrets: + database_url: + file: ./secrets/database_url.txt + postgres_password: + file: ./secrets/postgres_password.txt + +volumes: + postgres-data: + redis-data: \ No newline at end of file diff --git a/docs/architecture.png b/docs/architecture.png new file mode 100644 index 0000000000000000000000000000000000000000..8af3b50d601a725a3ecacb0f5c4976de9beb185a GIT binary patch literal 24037 zcmbTdbyQrzmN(i+aCdhN8axo(rE&KJcY?dSOK=Fm-Q6{~ySrQCjq`EuyEE^8Gqc{T z^=h3zx=z*k)joB0)!zHJtHTxLC6N&b5C8xGvb2<#G5`QE3jjcl!a;r9Ndl(cepCw5Qw2jt#KgpeEE7d+)5YvFghEDz!zV?f=OyD7q@<)|oPGmc|0uZS z$otny#m)f}7ZrXjX=rGuy8l-5&R32eRE(QY`8BJUw4|20Y+zuZYGPqy7+h)+USXCw`6FY-Fni57XU*K)+}hsRCaTOPw#GKD#yor8E_dD{ zf5WbL)5XQ*XF{E8R`1XJ1^a>}*WyL{;!UTrEq8Z!w_i1GsZCxPEp8{`0&>FMd7 zT<@LQ7?|DaTRiPsI{UkJJv1~lvamb0v^TK{8d|@Z*uI_qD60qao5u@V$J4uaYiny8 z2j@$N_iHEMjnjw2!^5q^i|r%OAqcz=dOWy%ytueH1>Ig;-=ADR-QC??gI~Z;ukY{g z?qtw5AKLKQNnF#($j;u~+QifeAZcQ2;_%(c#F*@dJDItYlf5G^3yZ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icp333Y$!Dfxyv&-v*-#pIS9UF?P}?lXROj|3UKjk|G^WX5!Fj_?3aBl zAol5l&y|m**W!MXdXiK}3tsW1{Ff#! z_rRVc4v$aNlgjv?dTKq6)i(K c.ID + } + return false +} diff --git a/internal/db/db.go b/internal/db/db.go new file mode 100644 index 0000000..7fcca45 --- /dev/null +++ b/internal/db/db.go @@ -0,0 +1,42 @@ +package db + +import ( + "context" + "fmt" + "time" + + "github.com/jackc/pgx/v5/pgxpool" +) + +type Config struct { + DSN string + MaxConns int32 + MinConns int32 + ConnMaxLifetime time.Duration + ConnTimeout time.Duration +} + +func Connect(ctx context.Context, cfg Config) (*pgxpool.Pool, error) { + poolCfg, err := pgxpool.ParseConfig(cfg.DSN) + if err != nil { + return nil, fmt.Errorf("parse dsn: %w", err) + } + poolCfg.MaxConns = cfg.MaxConns + poolCfg.MinConns = cfg.MinConns + poolCfg.MaxConnLifetime = cfg.ConnMaxLifetime + + connCtx, cancel := context.WithTimeout(ctx, cfg.ConnTimeout) + defer cancel() + pool, err := pgxpool.NewWithConfig(connCtx, poolCfg) + if err != nil { + return nil, fmt.Errorf("create pool: %w", err) + } + + pingCtx, cancel2 := context.WithTimeout(ctx, cfg.ConnTimeout) + defer cancel2() + if err := pool.Ping(pingCtx); err != nil { + pool.Close() + return nil, fmt.Errorf("ping db: %w", err) + } + return pool, nil +} diff --git a/internal/httpapi/api_test.go b/internal/httpapi/api_test.go new file mode 100644 index 0000000..7438fad --- /dev/null +++ b/internal/httpapi/api_test.go @@ -0,0 +1,983 @@ +package httpapi + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "mtusi2026/internal/cache" + "mtusi2026/internal/idgen" + "mtusi2026/internal/model" + "mtusi2026/internal/sessionstore" + "mtusi2026/internal/store" + + "github.com/redis/go-redis/v9" +) + +//вспомогательные функции + +func newKey() string { return idgen.GenerateUUIDv4() } + +func doMessage(srv *httptest.Server, chatID, token, key string, body any) (*http.Response, error) { + var buf bytes.Buffer + if s, ok := body.(string); ok { + buf.WriteString(s) + } else if err := json.NewEncoder(&buf).Encode(body); err != nil { + return nil, err + } + req, err := http.NewRequest(http.MethodPost, + fmt.Sprintf("%s/api/v1/chats/%s/messages", srv.URL, chatID), &buf) + if err != nil { + return nil, err + } + req.Header.Set("Content-Type", "application/json") + if token != "" { + req.Header.Set("Authorization", "Bearer "+token) + } + if key != "" { + req.Header.Set("Idempotency-Key", key) + } + return srv.Client().Do(req) +} + +func postMessage(t *testing.T, srv *httptest.Server, chatID, token, key string, body any) *http.Response { + t.Helper() + resp, err := doMessage(srv, chatID, token, key, body) + if err != nil { + t.Fatalf("do request: %v", err) + } + return resp +} + +func newUnlimitedLimiter() *store.Limiter { + return store.NewLimiter(1_000_000, 1000) +} + +func newTestServer(t *testing.T) *httptest.Server { + t.Helper() + srv, _ := newTestServerWithStore(t) + return srv +} + +func newTestServerWithStore(t *testing.T) (*httptest.Server, *store.Store) { + t.Helper() + truncateAll(t) + + s := store.New(testPool, newUnlimitedLimiter()) + ss := newMemorySessionStore() + + return httptest.NewServer(NewRouter(s, testPool, ss)), s +} + +func newRedisTestServer(t *testing.T) *httptest.Server { + t.Helper() + srv, _ := newRedisTestServerWithStore(t) + return srv +} + +func newRedisTestServerWithStore(t *testing.T) (*httptest.Server, *store.Store) { + t.Helper() + truncateAll(t) + + if err := testRedis.FlushDB(context.Background()).Err(); err != nil { + t.Fatalf("flush redis: %v", err) + } + + s := store.New(testPool, newUnlimitedLimiter()) + ss := sessionstore.NewRedis(testRedis) + + return httptest.NewServer(NewRouter(s, testPool, ss)), s +} + +func newCachedRedisTestServer(t *testing.T) (*httptest.Server, *store.Store) { + t.Helper() + truncateAll(t) + + if err := testRedis.FlushDB(context.Background()).Err(); err != nil { + t.Fatalf("flush redis: %v", err) + } + + s := store.New(testPool, newUnlimitedLimiter()) + ss := sessionstore.NewRedis(testRedis) + chatCache := cache.New(testRedis, 30*time.Second) + + srv := httptest.NewServer( + NewRouterWithCache(s, testPool, ss, chatCache), + ) + + return srv, s +} + +type testUser struct { + model.User + Token string +} + +func postJSON(t *testing.T, srv *httptest.Server, path string, token string, body any) *http.Response { + t.Helper() + var buf bytes.Buffer + if s, ok := body.(string); ok { + buf.WriteString(s) + } else if err := json.NewEncoder(&buf).Encode(body); err != nil { + t.Fatalf("encode request body: %v", err) + } + req, err := http.NewRequest(http.MethodPost, srv.URL+path, &buf) + if err != nil { + t.Fatalf("build request: %v", err) + } + req.Header.Set("Content-Type", "application/json") + if token != "" { + req.Header.Set("Authorization", "Bearer "+token) + } + resp, err := srv.Client().Do(req) + if err != nil { + t.Fatalf("do request: %v", err) + } + return resp +} + +func getJSON(t *testing.T, srv *httptest.Server, path string, token string) *http.Response { + t.Helper() + req, err := http.NewRequest(http.MethodGet, srv.URL+path, nil) + if err != nil { + t.Fatalf("build request: %v", err) + } + if token != "" { + req.Header.Set("Authorization", "Bearer "+token) + } + resp, err := srv.Client().Do(req) + if err != nil { + t.Fatalf("do request: %v", err) + } + return resp +} + +func decodeBody[T any](t *testing.T, resp *http.Response) T { + t.Helper() + defer resp.Body.Close() + var v T + if err := json.NewDecoder(resp.Body).Decode(&v); err != nil { + t.Fatalf("decode response body: %v", err) + } + return v +} + +func mustLogin(t *testing.T, srv *httptest.Server, username, password string) string { + t.Helper() + req, err := http.NewRequest(http.MethodPost, srv.URL+"/api/v1/auth/sessions", nil) + if err != nil { + t.Fatalf("build login request: %v", err) + } + req.SetBasicAuth(username, password) + + resp, err := srv.Client().Do(req) + if err != nil { + t.Fatalf("do login request: %v", err) + } + if resp.StatusCode != http.StatusCreated { + t.Fatalf("login %s: expected 201, got %d", username, resp.StatusCode) + } + session := decodeBody[model.Session](t, resp) + return session.Token +} + +func mustRegisterUser(t *testing.T, srv *httptest.Server, username string) testUser { + t.Helper() + const password = "correct-horse-battery-staple" + + resp := postJSON(t, srv, "/api/v1/users", "", model.CreateUserRequest{ + Username: username, + DisplayName: "Test " + username, + Password: password, + }) + if resp.StatusCode != http.StatusCreated { + t.Fatalf("register %s: expected 201, got %d", username, resp.StatusCode) + } + u := decodeBody[model.User](t, resp) + + token := mustLogin(t, srv, username, password) + return testUser{User: u, Token: token} +} + +func mustCreateChat(t *testing.T, srv *httptest.Server, caller testUser, title string, memberIDs []string) model.Chat { + t.Helper() + resp := postJSON(t, srv, "/api/v1/chats", caller.Token, model.CreateChatRequest{ + Title: title, + MemberIDs: memberIDs, + }) + if resp.StatusCode != http.StatusCreated { + t.Fatalf("create chat: expected 201, got %d", resp.StatusCode) + } + return decodeBody[model.Chat](t, resp) +} + +// тесты пользователи + +func TestRegisterUser_DuplicateUsername_Returns409(t *testing.T) { + srv := newTestServer(t) + defer srv.Close() + + mustRegisterUser(t, srv, "alice") + + resp := postJSON(t, srv, "/api/v1/users", "", model.CreateUserRequest{ + Username: "alice", + DisplayName: "Другая Алиса", + Password: "correct-horse-battery-staple", + }) + if resp.StatusCode != http.StatusConflict { + t.Fatalf("expected 409, got %d", resp.StatusCode) + } + errBody := decodeBody[model.ErrorEnvelope](t, resp) + if errBody.Error.Code != "conflict" { + t.Fatalf("expected error code 'conflict', got %q", errBody.Error.Code) + } + if errBody.Error.RequestID == "" { + t.Fatal("expected non-empty request_id") + } +} + +func TestRegisterUser_InvalidPasswordLength_Returns400(t *testing.T) { + srv := newTestServer(t) + defer srv.Close() + + cases := []string{"short", strings.Repeat("a", 129)} + for _, password := range cases { + resp := postJSON(t, srv, "/api/v1/users", "", model.CreateUserRequest{ + Username: "alice", + DisplayName: "Алиса", + Password: password, + }) + if resp.StatusCode != http.StatusBadRequest { + t.Errorf("password len %d: expected 400, got %d", len(password), resp.StatusCode) + } + } +} + +func TestRegisterUser_InvalidJSON_Returns400(t *testing.T) { + srv := newTestServer(t) + defer srv.Close() + + resp := postJSON(t, srv, "/api/v1/users", "", `{"username":`) + if resp.StatusCode != http.StatusBadRequest { + t.Fatalf("expected 400, got %d", resp.StatusCode) + } +} + +func TestRegisterUser_UnknownField_Returns400(t *testing.T) { + srv := newTestServer(t) + defer srv.Close() + + resp := postJSON(t, srv, "/api/v1/users", "", `{"username":"bob","display_name":"Боб","password":"correct-horse-battery-staple","extra":"whatever"}`) + if resp.StatusCode != http.StatusBadRequest { + t.Fatalf("expected 400 on unknown field, got %d", resp.StatusCode) + } +} + +func TestRegisterUser_InvalidUsernamePattern_Returns400(t *testing.T) { + srv := newTestServer(t) + defer srv.Close() + + cases := []string{"AB", "ab", "Has-Dash", "こんにちは"} + for _, username := range cases { + resp := postJSON(t, srv, "/api/v1/users", "", model.CreateUserRequest{ + Username: username, + DisplayName: "Тест", + Password: "correct-horse-battery-staple", + }) + if resp.StatusCode != http.StatusBadRequest { + t.Errorf("username %q: expected 400, got %d", username, resp.StatusCode) + } + } +} + +func TestCurrentUser_MissingHeader_Returns401(t *testing.T) { + srv := newTestServer(t) + defer srv.Close() + + resp := getJSON(t, srv, "/api/v1/users/me", "") + if resp.StatusCode != http.StatusUnauthorized { + t.Fatalf("expected 401, got %d", resp.StatusCode) + } +} + +func TestCurrentUser_UnknownToken_Returns401(t *testing.T) { + srv := newTestServer(t) + defer srv.Close() + + resp := getJSON(t, srv, "/api/v1/users/me", "totally-made-up-token") + if resp.StatusCode != http.StatusUnauthorized { + t.Fatalf("expected 401, got %d", resp.StatusCode) + } +} + +//тесты вход и сессии + +func TestCreateSession_WrongPassword_Returns401(t *testing.T) { + srv := newTestServer(t) + defer srv.Close() + + mustRegisterUser(t, srv, "alice") + + req, _ := http.NewRequest(http.MethodPost, srv.URL+"/api/v1/auth/sessions", nil) + req.SetBasicAuth("alice", "totally-wrong-password") + resp, err := srv.Client().Do(req) + if err != nil { + t.Fatalf("do request: %v", err) + } + if resp.StatusCode != http.StatusUnauthorized { + t.Fatalf("expected 401, got %d", resp.StatusCode) + } + if resp.Header.Get("WWW-Authenticate") == "" { + t.Error("expected WWW-Authenticate header on failed login") + } +} + +func TestCreateSession_UnknownUsername_Returns401(t *testing.T) { + srv := newTestServer(t) + defer srv.Close() + + req, _ := http.NewRequest(http.MethodPost, srv.URL+"/api/v1/auth/sessions", nil) + req.SetBasicAuth("nobody_here", "whatever-password-12") + resp, err := srv.Client().Do(req) + if err != nil { + t.Fatalf("do request: %v", err) + } + if resp.StatusCode != http.StatusUnauthorized { + t.Fatalf("expected 401, got %d", resp.StatusCode) + } +} + +func TestDeleteSession_ThenReuse_Returns401(t *testing.T) { + srv := newTestServer(t) + defer srv.Close() + + alice := mustRegisterUser(t, srv, "alice") + + req, _ := http.NewRequest(http.MethodDelete, srv.URL+"/api/v1/auth/sessions/current", nil) + req.Header.Set("Authorization", "Bearer "+alice.Token) + resp, err := srv.Client().Do(req) + if err != nil { + t.Fatalf("do logout request: %v", err) + } + if resp.StatusCode != http.StatusNoContent { + t.Fatalf("expected 204, got %d", resp.StatusCode) + } + + // повторное использование отозванного токена -401 + resp2 := getJSON(t, srv, "/api/v1/users/me", alice.Token) + if resp2.StatusCode != http.StatusUnauthorized { + t.Fatalf("expected 401 after logout, got %d", resp2.StatusCode) + } +} + +//тесты чаты и membership + +func TestCreateChat_CallerNotInMembers_Returns400(t *testing.T) { + srv := newTestServer(t) + defer srv.Close() + + alice := mustRegisterUser(t, srv, "alice") + bob := mustRegisterUser(t, srv, "bob") + + resp := postJSON(t, srv, "/api/v1/chats", alice.Token, model.CreateChatRequest{ + Title: "Без себя", + MemberIDs: []string{bob.ID}, + }) + if resp.StatusCode != http.StatusBadRequest { + t.Fatalf("expected 400, got %d", resp.StatusCode) + } +} + +func TestCreateChat_DuplicateMemberIDs_Returns400(t *testing.T) { + srv := newTestServer(t) + defer srv.Close() + + alice := mustRegisterUser(t, srv, "alice") + + resp := postJSON(t, srv, "/api/v1/chats", alice.Token, model.CreateChatRequest{ + Title: "Дубли", + MemberIDs: []string{alice.ID, alice.ID}, + }) + if resp.StatusCode != http.StatusBadRequest { + t.Fatalf("expected 400, got %d", resp.StatusCode) + } +} + +func TestGetChat_NotMember_Returns404NotForbidden(t *testing.T) { + srv := newTestServer(t) + defer srv.Close() + + alice := mustRegisterUser(t, srv, "alice") + bob := mustRegisterUser(t, srv, "bob") + carol := mustRegisterUser(t, srv, "carol") + + chat := mustCreateChat(t, srv, alice, "Приватный", []string{alice.ID, bob.ID}) + + resp := getJSON(t, srv, "/api/v1/chats/"+chat.ID, carol.Token) + if resp.StatusCode != http.StatusNotFound { + t.Fatalf("expected 404 for non-member (never 403), got %d", resp.StatusCode) + } +} + +func TestGetChat_UnknownChatID_Returns404(t *testing.T) { + srv := newTestServer(t) + defer srv.Close() + + alice := mustRegisterUser(t, srv, "alice") + + resp := getJSON(t, srv, "/api/v1/chats/11111111-1111-4111-8111-111111111111", alice.Token) + if resp.StatusCode != http.StatusNotFound { + t.Fatalf("expected 404, got %d", resp.StatusCode) + } +} + +// тесты: сообщения + +func TestCreateMessage_EmptyText_Returns400(t *testing.T) { + srv := newTestServer(t) + defer srv.Close() + + alice := mustRegisterUser(t, srv, "alice") + chat := mustCreateChat(t, srv, alice, "Чат", []string{alice.ID}) + + resp := postMessage(t, srv, chat.ID, alice.Token, newKey(), model.CreateMessageRequest{Text: ""}) + + if resp.StatusCode != http.StatusBadRequest { + t.Fatalf("expected 400 for empty text, got %d", resp.StatusCode) + } +} + +func TestCreateMessage_WhitespaceOnlyText_Returns400(t *testing.T) { + srv := newTestServer(t) + defer srv.Close() + + alice := mustRegisterUser(t, srv, "alice") + chat := mustCreateChat(t, srv, alice, "Чат", []string{alice.ID}) + + resp := postMessage(t, srv, chat.ID, alice.Token, newKey(), model.CreateMessageRequest{Text: " \t\n "}) + + if resp.StatusCode != http.StatusBadRequest { + t.Fatalf("expected 400 for whitespace-only text, got %d", resp.StatusCode) + } +} + +func TestCreateMessage_ForeignChat_Returns404(t *testing.T) { + srv := newTestServer(t) + defer srv.Close() + + alice := mustRegisterUser(t, srv, "alice") + bob := mustRegisterUser(t, srv, "bob") + carol := mustRegisterUser(t, srv, "carol") + + chat := mustCreateChat(t, srv, alice, "Приватный", []string{alice.ID, bob.ID}) + + resp := postMessage(t, srv, chat.ID, carol.Token, newKey(), model.CreateMessageRequest{Text: "Я тут чужая"}) + + if resp.StatusCode != http.StatusNotFound { + t.Fatalf("expected 404 for foreign chat, got %d", resp.StatusCode) + } +} + +func TestCreateMessage_SenderIDIgnoredFromRequestBody(t *testing.T) { + srv := newTestServer(t) + defer srv.Close() + + alice := mustRegisterUser(t, srv, "alice") + bob := mustRegisterUser(t, srv, "bob") + chat := mustCreateChat(t, srv, alice, "Чат", []string{alice.ID, bob.ID}) + + raw := fmt.Sprintf(`{"text":"Привет","sender_id":%q}`, bob.ID) + resp := postMessage(t, srv, chat.ID, alice.Token, newKey(), raw) + if resp.StatusCode != http.StatusBadRequest { + t.Fatalf("expected 400 (unknown field sender_id), got %d", resp.StatusCode) + } +} + +// тесты пагинация + +func TestListMessages_PaginationAcrossMultiplePages(t *testing.T) { + srv := newTestServer(t) + defer srv.Close() + + alice := mustRegisterUser(t, srv, "alice") + chat := mustCreateChat(t, srv, alice, "Чат", []string{alice.ID}) + + const total = 5 + for i := 0; i < total; i++ { + resp := postMessage(t, srv, chat.ID, alice.Token, newKey(), model.CreateMessageRequest{ + Text: fmt.Sprintf("сообщение %d", i), + }) + if resp.StatusCode != http.StatusCreated { + t.Fatalf("create message %d: expected 201, got %d", i, resp.StatusCode) + } + resp.Body.Close() + } + + seen := make(map[string]bool) + cursor := "" + pages := 0 + for { + path := fmt.Sprintf("/api/v1/chats/%s/messages?limit=2", chat.ID) + if cursor != "" { + path += "&cursor=" + cursor + } + resp := getJSON(t, srv, path, alice.Token) + if resp.StatusCode != http.StatusOK { + t.Fatalf("list messages: expected 200, got %d", resp.StatusCode) + } + page := decodeBody[model.MessagePage](t, resp) + pages++ + + for _, m := range page.Items { + if seen[m.ID] { + t.Fatalf("duplicate message across pages: %s", m.ID) + } + seen[m.ID] = true + } + + if page.NextCursor == nil { + break + } + cursor = *page.NextCursor + + if pages > total { + t.Fatal("too many pages — possible cursor bug (infinite loop)") + } + } + + if len(seen) != total { + t.Fatalf("expected %d unique messages across all pages, got %d", total, len(seen)) + } + if pages < 2 { + t.Fatalf("expected pagination to span multiple pages, got %d page(s)", pages) + } +} + +func TestListMessages_CursorFromDifferentChat_Returns400(t *testing.T) { + srv := newTestServer(t) + defer srv.Close() + + alice := mustRegisterUser(t, srv, "alice") + chatA := mustCreateChat(t, srv, alice, "Чат A", []string{alice.ID}) + chatB := mustCreateChat(t, srv, alice, "Чат B", []string{alice.ID}) + + postMessage(t, srv, chatA.ID, alice.Token, newKey(), model.CreateMessageRequest{Text: "первое"}).Body.Close() + postMessage(t, srv, chatA.ID, alice.Token, newKey(), model.CreateMessageRequest{Text: "второе"}).Body.Close() + + respA := getJSON(t, srv, fmt.Sprintf("/api/v1/chats/%s/messages?limit=1", chatA.ID), alice.Token) + pageA := decodeBody[model.MessagePage](t, respA) + if pageA.NextCursor == nil { + t.Fatal("expected next_cursor to be present after inserting 2 messages with limit=1") + } + + resp := getJSON(t, srv, fmt.Sprintf("/api/v1/chats/%s/messages?cursor=%s", chatB.ID, *pageA.NextCursor), alice.Token) + if resp.StatusCode != http.StatusBadRequest { + t.Fatalf("expected 400 for cross-chat cursor, got %d", resp.StatusCode) + } +} + +func TestCreateSession_RedisTTLExpires(t *testing.T) { + srv := newRedisTestServer(t) + defer srv.Close() + + mustRegisterUser(t, srv, "alice") + + t.Setenv("SESSION_TTL_SECONDS", "1") + + token := mustLogin(t, srv, "alice", "correct-horse-battery-staple") + + resp := getJSON(t, srv, "/api/v1/users/me", token) + if resp.StatusCode != http.StatusOK { + t.Fatalf("expected 200 immediately after login, got %d", resp.StatusCode) + } + resp.Body.Close() + + time.Sleep(1500 * time.Millisecond) + + resp = getJSON(t, srv, "/api/v1/users/me", token) + if resp.StatusCode != http.StatusUnauthorized { + t.Fatalf("expected 401 after session TTL expiration, got %d", resp.StatusCode) + } + resp.Body.Close() +} + +func TestCurrentUser_RedisUnavailable_Returns503(t *testing.T) { + srv, s := newRedisTestServerWithStore(t) + defer srv.Close() + + alice := mustRegisterUser(t, srv, "alice") + + resp := getJSON(t, srv, "/api/v1/users/me", alice.Token) + if resp.StatusCode != http.StatusOK { + t.Fatalf("expected 200 before redis failure, got %d", resp.StatusCode) + } + resp.Body.Close() + + redisDownClient := redis.NewClient(&redis.Options{ + Addr: "127.0.0.1:1", + }) + defer redisDownClient.Close() + + redisDownSessionStore := sessionstore.NewRedis(redisDownClient) + + downSrv := httptest.NewServer( + NewRouter(s, testPool, redisDownSessionStore), + ) + defer downSrv.Close() + + resp = getJSON(t, downSrv, "/api/v1/users/me", alice.Token) + if resp.StatusCode != http.StatusServiceUnavailable { + t.Fatalf( + "expected 503 when redis is unavailable, got %d", + resp.StatusCode, + ) + } + resp.Body.Close() + +} + +func TestChatCache_ConcurrentRequests(t *testing.T) { + const concurrentRequests = 50 + + baselineSrv, baselineStore := newTestServerWithStore(t) + defer baselineSrv.Close() + + baselineUser := mustRegisterUser(t, baselineSrv, "cachebaseline") + baselineChat := mustCreateChat( + t, + baselineSrv, + baselineUser, + "Cache baseline", + []string{baselineUser.ID}, + ) + + baselineStore.ResetChatSQLQueries() + + start := make(chan struct{}) + errCh := make(chan error, concurrentRequests) + + baselineStart := time.Now() + + for i := 0; i < concurrentRequests; i++ { + go func() { + <-start + + _, err := baselineStore.GetChat( + context.Background(), + baselineChat.ID, + baselineUser.ID, + ) + errCh <- err + }() + } + + close(start) + + for i := 0; i < concurrentRequests; i++ { + if err := <-errCh; err != nil { + t.Fatal(err) + } + } + + baselineLatency := time.Since(baselineStart) + baselineQueries := baselineStore.ChatSQLQueries() + + cachedSrv, cachedStore := newCachedRedisTestServer(t) + defer cachedSrv.Close() + + cachedUser := mustRegisterUser(t, cachedSrv, "cacheprotected") + cachedChat := mustCreateChat( + t, + cachedSrv, + cachedUser, + "Cache protected", + []string{cachedUser.ID}, + ) + + cacheKey := "chat:" + cachedUser.ID + ":" + cachedChat.ID + + if err := testRedis.Del(context.Background(), cacheKey).Err(); err != nil { + t.Fatalf("delete cache key: %v", err) + } + + cachedStore.ResetChatSQLQueries() + + start = make(chan struct{}) + errCh = make(chan error, concurrentRequests) + + cachedStart := time.Now() + + for i := 0; i < concurrentRequests; i++ { + go func() { + <-start + + resp := getJSON( + t, + cachedSrv, + "/api/v1/chats/"+cachedChat.ID, + cachedUser.Token, + ) + defer resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + errCh <- fmt.Errorf("unexpected status: %d", resp.StatusCode) + return + } + + errCh <- nil + }() + } + + close(start) + + for i := 0; i < concurrentRequests; i++ { + if err := <-errCh; err != nil { + t.Fatal(err) + } + } + + cachedLatency := time.Since(cachedStart) + cachedQueries := cachedStore.ChatSQLQueries() + + t.Logf( + "baseline: requests=%d sql_queries=%d latency=%s", + concurrentRequests, + baselineQueries, + baselineLatency, + ) + + t.Logf( + "cold cache + singleflight: requests=%d sql_queries=%d latency=%s", + concurrentRequests, + cachedQueries, + cachedLatency, + ) + + expectedBaselineQueries := int64(concurrentRequests * 2) + + if baselineQueries != expectedBaselineQueries { + t.Errorf( + "baseline: expected %d SQL queries, got %d", + expectedBaselineQueries, + baselineQueries, + ) + } + + if cachedQueries > 2 { + t.Errorf( + "cold cache + singleflight: expected <=2 SQL queries, got %d", + cachedQueries, + ) + } +} + +func TestChatCache_WarmCache(t *testing.T) { + const concurrentRequests = 50 + + srv, s := newCachedRedisTestServer(t) + defer srv.Close() + + user := mustRegisterUser(t, srv, "cachewarm") + chat := mustCreateChat( + t, + srv, + user, + "Warm cache", + []string{user.ID}, + ) + + // Первый GET прогревает cache + resp := getJSON( + t, + srv, + "/api/v1/chats/"+chat.ID, + user.Token, + ) + resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + t.Fatalf("warm-up GET: unexpected status %d", resp.StatusCode) + } + + s.ResetChatSQLQueries() + + start := make(chan struct{}) + errCh := make(chan error, concurrentRequests) + + startedAt := time.Now() + + for i := 0; i < concurrentRequests; i++ { + go func() { + <-start + + resp := getJSON( + t, + srv, + "/api/v1/chats/"+chat.ID, + user.Token, + ) + defer resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + errCh <- fmt.Errorf( + "unexpected status: %d", + resp.StatusCode, + ) + return + } + + errCh <- nil + }() + } + + close(start) + + for i := 0; i < concurrentRequests; i++ { + if err := <-errCh; err != nil { + t.Fatal(err) + } + } + + latency := time.Since(startedAt) + queries := s.ChatSQLQueries() + + t.Logf( + "warm cache: requests=%d sql_queries=%d latency=%s", + concurrentRequests, + queries, + latency, + ) + + if queries != 0 { + t.Errorf( + "warm cache: expected 0 SQL queries, got %d", + queries, + ) + } +} + +func TestChatCache_ReadAfterWriteAndRecovery(t *testing.T) { + srv, s := newCachedRedisTestServer(t) + defer srv.Close() + + user := mustRegisterUser(t, srv, "cacherecovery") + + chat := mustCreateChat( + t, + srv, + user, + "Read after write", + []string{user.ID}, + ) + + s.ResetChatSQLQueries() + + resp := getJSON( + t, + srv, + "/api/v1/chats/"+chat.ID, + user.Token, + ) + defer resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + t.Fatalf("read-after-write: unexpected status %d", resp.StatusCode) + } + + got := decodeBody[model.Chat](t, resp) + + if got.ID != chat.ID { + t.Fatalf( + "read-after-write: expected chat %s, got %s", + chat.ID, + got.ID, + ) + } + + if got.Title != "Read after write" { + t.Fatalf( + "read-after-write: expected title %q, got %q", + "Read after write", + got.Title, + ) + } + + if queries := s.ChatSQLQueries(); queries != 2 { + t.Fatalf( + "read-after-write: expected 2 SQL queries on cache miss, got %d", + queries, + ) + } + + cacheKey := "chat:" + user.ID + ":" + chat.ID + + exists, err := testRedis.Exists(context.Background(), cacheKey).Result() + if err != nil { + t.Fatalf("check cache: %v", err) + } + + if exists != 1 { + t.Fatalf("expected chat to be present in cache") + } + + if err := testRedis.Del(context.Background(), cacheKey).Err(); err != nil { + t.Fatalf("delete cache: %v", err) + } + + s.ResetChatSQLQueries() + + resp2 := getJSON( + t, + srv, + "/api/v1/chats/"+chat.ID, + user.Token, + ) + defer resp2.Body.Close() + + if resp2.StatusCode != http.StatusOK { + t.Fatalf( + "recovery after cache loss: unexpected status %d", + resp2.StatusCode, + ) + } + + recovered := decodeBody[model.Chat](t, resp2) + + if recovered.ID != chat.ID { + t.Fatalf( + "recovery: expected chat %s, got %s", + chat.ID, + recovered.ID, + ) + } + + if recovered.Title != chat.Title { + t.Fatalf( + "recovery: expected title %q, got %q", + chat.Title, + recovered.Title, + ) + } + + if queries := s.ChatSQLQueries(); queries != 2 { + t.Fatalf( + "recovery: expected 2 SQL queries after cache loss, got %d", + queries, + ) + } + + exists, err = testRedis.Exists(context.Background(), cacheKey).Result() + if err != nil { + t.Fatalf("check recovered cache: %v", err) + } + + if exists != 1 { + t.Fatalf("expected cache to be restored after database read") + } +} diff --git a/internal/httpapi/auth.go b/internal/httpapi/auth.go new file mode 100644 index 0000000..85a2bc2 --- /dev/null +++ b/internal/httpapi/auth.go @@ -0,0 +1,110 @@ +package httpapi + +import ( + "errors" + "net/http" + "strings" + + "mtusi2026/internal/auth" + "mtusi2026/internal/config" + "mtusi2026/internal/model" + "mtusi2026/internal/store" +) + +const sessionTTLEnvKey = "SESSION_TTL_SECONDS" + +var dummyPasswordHash = func() string { + h, err := auth.HashPassword("timing-equalizer-password") + if err != nil { + panic(err) + } + return h +}() + +func (a *api) handleCreateSession(w http.ResponseWriter, r *http.Request) { + requestID := newRequestID() + + username, password, ok := r.BasicAuth() + if !ok { + w.Header().Set("WWW-Authenticate", `Basic realm="messenger", charset="UTF-8"`) + writeError(w, http.StatusUnauthorized, requestID, codeUnauthorized, "missing or malformed Basic credentials") + return + } + + u, passwordHash, err := a.store.GetUserByUsername(r.Context(), username) + if err != nil { + if !errors.Is(err, store.ErrUsernameNotFound) { + writeError(w, http.StatusServiceUnavailable, requestID, codeUnavailable, "database unavailable") + return + } + _, _ = auth.VerifyPassword(password, dummyPasswordHash) + w.Header().Set("WWW-Authenticate", `Basic realm="messenger", charset="UTF-8"`) + writeError(w, http.StatusUnauthorized, requestID, codeUnauthorized, "invalid username or password") + return + } + + valid, err := auth.VerifyPassword(password, passwordHash) + if err != nil || !valid { + w.Header().Set("WWW-Authenticate", `Basic realm="messenger", charset="UTF-8"`) + writeError(w, http.StatusUnauthorized, requestID, codeUnauthorized, "invalid username or password") + return + } + + token, err := auth.GenerateSessionToken() + if err != nil { + writeError(w, http.StatusInternalServerError, requestID, codeInternal, "internal error") + return + } + + ttl := config.ParseDurationSecondsEnv(sessionTTLEnvKey, 3600) + expiresAt, err := a.sessionStore.Create(r.Context(), token, u.ID, ttl) + if err != nil { + writeError(w, http.StatusServiceUnavailable, requestID, codeInternal, "session service unavailable") + return + } + + writeJSON(w, http.StatusCreated, requestID, model.Session{ + Token: token, + TokenType: "Bearer", + ExpiresAt: expiresAt, + User: u, + }) +} + +func (a *api) handleDeleteSession(w http.ResponseWriter, r *http.Request) { + requestID := newRequestID() + + token, ok := bearerToken(r) + if !ok { + w.Header().Set("WWW-Authenticate", `Bearer realm="messenger"`) + writeError(w, http.StatusUnauthorized, requestID, codeUnauthorized, "missing or malformed Bearer token") + return + } + + deleted, err := a.sessionStore.Delete(r.Context(), token) + if err != nil { + writeError(w, http.StatusServiceUnavailable, requestID, codeInternal, "session service unavailable") + return + } + if !deleted { + w.Header().Set("WWW-Authenticate", `Bearer realm="messenger"`) + writeError(w, http.StatusUnauthorized, requestID, codeUnauthorized, "unknown or already revoked token") + return + } + + w.Header().Set("X-Request-Id", requestID) + w.WriteHeader(http.StatusNoContent) +} + +func bearerToken(r *http.Request) (string, bool) { + h := r.Header.Get("Authorization") + const prefix = "Bearer " + if !strings.HasPrefix(h, prefix) { + return "", false + } + token := strings.TrimPrefix(h, prefix) + if token == "" { + return "", false + } + return token, true +} diff --git a/internal/httpapi/chats.go b/internal/httpapi/chats.go new file mode 100644 index 0000000..5211564 --- /dev/null +++ b/internal/httpapi/chats.go @@ -0,0 +1,131 @@ +package httpapi + +import ( + "context" + "errors" + "net/http" + "strconv" + "strings" + "time" + + "mtusi2026/internal/idgen" + "mtusi2026/internal/model" + "mtusi2026/internal/store" +) + +func parseLimit(r *http.Request) (int, bool) { + q := r.URL.Query() + if !q.Has("limit") { + return 50, true + } + raw := q.Get("limit") + n, err := strconv.Atoi(raw) + if err != nil || n < 1 || n > 100 || raw != strconv.Itoa(n) { + return 0, false + } + return n, true +} + +func (a *api) handleCreateChat(w http.ResponseWriter, r *http.Request, u model.User, requestID string) { + var req model.CreateChatRequest + if err := decodeJSONStrict(r, &req); err != nil { + writeError(w, http.StatusBadRequest, requestID, codeInvalidRequest, "malformed request body") + return + } + if !validText(req.Title, 100) || len(req.MemberIDs) == 0 { + writeError(w, http.StatusBadRequest, requestID, codeInvalidRequest, "invalid title or member_ids") + return + } + for i, id := range req.MemberIDs { + if !idgen.IsValidUUID(id) { + writeError(w, http.StatusBadRequest, requestID, codeInvalidRequest, "invalid title or member_ids") + return + } + req.MemberIDs[i] = strings.ToLower(id) + } + + c, err := a.store.CreateChat(r.Context(), u.ID, req.Title, req.MemberIDs) + if err != nil { + if errors.Is(err, store.ErrValidation) { + writeError(w, http.StatusBadRequest, requestID, codeInvalidRequest, "invalid title or member_ids") + return + } + writeError(w, http.StatusInternalServerError, requestID, codeInternal, "internal error") + return + } + writeJSON(w, http.StatusCreated, requestID, c) +} + +func (a *api) handleListChats(w http.ResponseWriter, r *http.Request, u model.User, requestID string) { + limit, ok := parseLimit(r) + if !ok { + writeError(w, http.StatusBadRequest, requestID, codeInvalidRequest, "invalid limit") + return + } + cursorStr, ok := parseCursor(r) + if !ok { + writeError(w, http.StatusBadRequest, requestID, codeInvalidRequest, "invalid cursor") + return + } + + items, next, err := a.store.ListChatsForUser(r.Context(), u.ID, cursorStr, limit) + if err != nil { + if errors.Is(err, store.ErrValidation) { + writeError(w, http.StatusBadRequest, requestID, codeInvalidRequest, "invalid cursor") + return + } + writeError(w, http.StatusInternalServerError, requestID, codeInternal, "internal error") + return + } + if items == nil { + items = []model.Chat{} + } + writeJSON(w, http.StatusOK, requestID, model.ChatPage{Items: items, NextCursor: next}) +} + +func (a *api) handleGetChat(w http.ResponseWriter, r *http.Request, u model.User, requestID string) { + chatID, ok := chatIDParam(w, r, requestID) + if !ok { + return + } + + if a.chatCache != nil { + if c, hit, err := a.chatCache.Get(r.Context(), u.ID, chatID); err == nil && hit { + writeJSON(w, http.StatusOK, requestID, c) + return + } + } + + result, err, _ := a.chatFlight.Do(u.ID+":"+chatID, func() (any, error) { + ctx, cancel := context.WithTimeout(context.WithoutCancel(r.Context()), 5*time.Second) + defer cancel() + + if a.chatCache != nil { + if c, hit, err := a.chatCache.Get(ctx, u.ID, chatID); err == nil && hit { + return c, nil + } + } + c, err := a.store.GetChat(ctx, chatID, u.ID) + if err != nil { + return model.Chat{}, err + } + if a.chatCache != nil { + _ = a.chatCache.Set(ctx, u.ID, chatID, c) + } + return c, nil + }) + if err != nil { + if errors.Is(err, store.ErrChatNotFound) { + writeError(w, http.StatusNotFound, requestID, codeNotFound, "chat not found") + } else { + writeError(w, http.StatusServiceUnavailable, requestID, codeUnavailable, "database unavailable") + } + return + } + c, ok := result.(model.Chat) + if !ok { + writeError(w, http.StatusInternalServerError, requestID, codeInternal, "internal error") + return + } + writeJSON(w, http.StatusOK, requestID, c) +} diff --git a/internal/httpapi/health.go b/internal/httpapi/health.go new file mode 100644 index 0000000..8df2046 --- /dev/null +++ b/internal/httpapi/health.go @@ -0,0 +1,39 @@ +package httpapi + +import ( + "context" + "net/http" + "sync/atomic" + "time" + + "github.com/jackc/pgx/v5/pgxpool" + "github.com/redis/go-redis/v9" +) + +func handleHealthLive(w http.ResponseWriter, r *http.Request) { + writeJSON(w, http.StatusOK, newRequestID(), map[string]string{"status": "ok"}) +} + +func handleHealthReady(pool *pgxpool.Pool, rdb *redis.Client, draining *atomic.Bool) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + requestID := newRequestID() + if draining.Load() { + writeError(w, http.StatusServiceUnavailable, requestID, codeUnavailable, "shutting down") + return + } + ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second) + defer cancel() + + if err := pool.Ping(ctx); err != nil { + writeError(w, http.StatusServiceUnavailable, requestID, codeUnavailable, "database unavailable") + return + } + if rdb != nil { + if err := rdb.Ping(ctx).Err(); err != nil { + writeError(w, http.StatusServiceUnavailable, requestID, codeUnavailable, "session store unavailable") + return + } + } + writeJSON(w, http.StatusOK, requestID, map[string]string{"status": "ok"}) + } +} diff --git a/internal/httpapi/httpx.go b/internal/httpapi/httpx.go new file mode 100644 index 0000000..c628611 --- /dev/null +++ b/internal/httpapi/httpx.go @@ -0,0 +1,98 @@ +package httpapi + +import ( + "bytes" + "crypto/rand" + "encoding/json" + "fmt" + "io" + "mime" + "net/http" + "reflect" + "strings" +) + +type errorCode string + +const ( + codeInvalidRequest errorCode = "invalid_request" + codeUnauthorized errorCode = "unauthorized" + codeNotFound errorCode = "not_found" + codeConflict errorCode = "conflict" + codeUnavailable errorCode = "unavailable" + codeInternal errorCode = "internal_error" +) + +func newRequestID() string { + b := make([]byte, 12) + _, _ = rand.Read(b) + return fmt.Sprintf("%x", b) +} + +func writeJSON(w http.ResponseWriter, status int, requestID string, payload any) { + w.Header().Set("Content-Type", "application/json") + w.Header().Set("X-Request-Id", requestID) + w.WriteHeader(status) + if payload != nil { + _ = json.NewEncoder(w).Encode(payload) + } +} + +func writeError(w http.ResponseWriter, status int, requestID string, code errorCode, message string) { + writeJSON(w, status, requestID, map[string]any{ + "error": map[string]any{ + "code": code, + "message": message, + "request_id": requestID, + }, + }) +} + +func jsonFieldNames(dst any) map[string]bool { + names := map[string]bool{} + t := reflect.TypeOf(dst) + for t.Kind() == reflect.Ptr { + t = t.Elem() + } + for i := 0; i < t.NumField(); i++ { + tag := strings.Split(t.Field(i).Tag.Get("json"), ",")[0] + if tag != "" && tag != "-" { + names[tag] = true + } + } + return names +} +func decodeJSONStrict(r *http.Request, dst any) error { + contentType := r.Header.Get("Content-Type") + mediaType, _, err := mime.ParseMediaType(contentType) + if err != nil || mediaType != "application/json" { + return fmt.Errorf("unsupported Content-Type") + } + + raw, err := io.ReadAll(io.LimitReader(r.Body, 1<<20)) + if err != nil { + return err + } + if len(bytes.TrimSpace(raw)) == 0 { + return fmt.Errorf("empty body") + } + var probe map[string]json.RawMessage + if err := json.Unmarshal(raw, &probe); err != nil { + return err + } + allowed := jsonFieldNames(dst) + for k := range probe { + if !allowed[k] { + return fmt.Errorf("unknown field %q", k) + } + } + dec := json.NewDecoder(bytes.NewReader(raw)) + dec.DisallowUnknownFields() + if err := dec.Decode(dst); err != nil { + return err + } + if dec.More() { + return fmt.Errorf("trailing data after JSON body") + } + return nil +} diff --git a/internal/httpapi/idempotency_test.go b/internal/httpapi/idempotency_test.go new file mode 100644 index 0000000..bdb5362 --- /dev/null +++ b/internal/httpapi/idempotency_test.go @@ -0,0 +1,184 @@ +package httpapi + +import ( + "fmt" + "net/http" + "strings" + "sync" + "testing" + + "mtusi2026/internal/model" +) + +func TestIdempotency_RepeatReturnsSameMessage(t *testing.T) { + srv := newTestServer(t) + defer srv.Close() + alice := mustRegisterUser(t, srv, "alice") + chat := mustCreateChat(t, srv, alice, "Чат", []string{alice.ID}) + + key := newKey() + body := model.CreateMessageRequest{Text: "привет"} + + r1 := postMessage(t, srv, chat.ID, alice.Token, key, body) + if r1.StatusCode != http.StatusCreated { + t.Fatalf("first: expected 201, got %d", r1.StatusCode) + } + m1 := decodeBody[model.Message](t, r1) + + r2 := postMessage(t, srv, chat.ID, alice.Token, key, body) + if r2.StatusCode != http.StatusCreated { + t.Fatalf("repeat: expected 201, got %d", r2.StatusCode) + } + m2 := decodeBody[model.Message](t, r2) + + if m1.ID != m2.ID || !m1.CreatedAt.Equal(m2.CreatedAt) { + t.Fatalf("repeat returned a different message: %+v vs %+v", m1, m2) + } + + page := decodeBody[model.MessagePage](t, + getJSON(t, srv, fmt.Sprintf("/api/v1/chats/%s/messages", chat.ID), alice.Token)) + if len(page.Items) != 1 { + t.Fatalf("expected 1 message in history, got %d", len(page.Items)) + } +} + +func TestIdempotency_DifferentBodySameKey_Returns409(t *testing.T) { + srv := newTestServer(t) + defer srv.Close() + alice := mustRegisterUser(t, srv, "alice") + chat := mustCreateChat(t, srv, alice, "Чат", []string{alice.ID}) + + key := newKey() + postMessage(t, srv, chat.ID, alice.Token, key, model.CreateMessageRequest{Text: "один"}).Body.Close() + + resp := postMessage(t, srv, chat.ID, alice.Token, key, model.CreateMessageRequest{Text: "два"}) + defer resp.Body.Close() + if resp.StatusCode != http.StatusConflict { + t.Fatalf("expected 409, got %d", resp.StatusCode) + } +} + +func TestIdempotency_MissingOrInvalidKey_Returns400(t *testing.T) { + srv := newTestServer(t) + defer srv.Close() + alice := mustRegisterUser(t, srv, "alice") + chat := mustCreateChat(t, srv, alice, "Чат", []string{alice.ID}) + + keys := map[string]string{ + "missing": "", + "space": "bad key", + "too long": strings.Repeat("a", 129), + "cyrillic": "ключ", + } + for name, key := range keys { + resp := postMessage(t, srv, chat.ID, alice.Token, key, model.CreateMessageRequest{Text: "x"}) + resp.Body.Close() + if resp.StatusCode != http.StatusBadRequest { + t.Errorf("%s: expected 400, got %d", name, resp.StatusCode) + } + } +} + +func TestIdempotency_ConcurrentSameKey_OneMessage(t *testing.T) { + srv := newTestServer(t) + defer srv.Close() + alice := mustRegisterUser(t, srv, "alice") + chat := mustCreateChat(t, srv, alice, "Чат", []string{alice.ID}) + + const workers = 20 + key := newKey() + start := make(chan struct{}) + type result struct { + status int + id string + err error + } + results := make(chan result, workers) + + var wg sync.WaitGroup + for i := 0; i < workers; i++ { + wg.Add(1) + go func() { + defer wg.Done() + <-start + resp, err := doMessage(srv, chat.ID, alice.Token, key, model.CreateMessageRequest{Text: "гонка"}) + if err != nil { + results <- result{err: err} + return + } + defer resp.Body.Close() + var m model.Message + _ = t.Fatal + results <- result{status: resp.StatusCode, id: m.ID} + }() + } + close(start) + wg.Wait() + close(results) + + ids := map[string]bool{} + for r := range results { + if r.err != nil { + t.Errorf("request error: %v", r.err) + continue + } + if r.status != http.StatusCreated { + t.Errorf("expected 201, got %d", r.status) + } + ids[r.id] = true + } + if len(ids) != 1 { + t.Fatalf("expected one distinct message id, got %d", len(ids)) + } + + page := decodeBody[model.MessagePage](t, + getJSON(t, srv, fmt.Sprintf("/api/v1/chats/%s/messages", chat.ID), alice.Token)) + if len(page.Items) != 1 { + t.Fatalf("expected exactly 1 message stored, got %d", len(page.Items)) + } +} + +func TestIdempotency_ScopeIsPerUserAndChat(t *testing.T) { + srv := newTestServer(t) + defer srv.Close() + alice := mustRegisterUser(t, srv, "alice") + bob := mustRegisterUser(t, srv, "bob") + chatA := mustCreateChat(t, srv, alice, "A", []string{alice.ID, bob.ID}) + chatB := mustCreateChat(t, srv, alice, "B", []string{alice.ID, bob.ID}) + + key := newKey() + body := model.CreateMessageRequest{Text: "то же самое"} + ids := map[string]bool{} + for _, c := range []struct { + chat string + token string + }{ + {chatA.ID, alice.Token}, {chatB.ID, alice.Token}, {chatA.ID, bob.Token}, + } { + resp := postMessage(t, srv, c.chat, c.token, key, body) + if resp.StatusCode != http.StatusCreated { + t.Fatalf("expected 201, got %d", resp.StatusCode) + } + ids[decodeBody[model.Message](t, resp).ID] = true + } + if len(ids) != 3 { + t.Fatalf("same key in different scopes must create 3 messages, got %d", len(ids)) + } +} + +func TestIdempotency_ForeignChatRepeat_Returns404(t *testing.T) { + srv := newTestServer(t) + defer srv.Close() + alice := mustRegisterUser(t, srv, "alice") + carol := mustRegisterUser(t, srv, "carol") + chat := mustCreateChat(t, srv, alice, "Приватный", []string{alice.ID}) + + key := newKey() + for i := 0; i < 2; i++ { + resp := postMessage(t, srv, chat.ID, carol.Token, key, model.CreateMessageRequest{Text: "чужой"}) + resp.Body.Close() + if resp.StatusCode != http.StatusNotFound { + t.Fatalf("attempt %d: expected 404, got %d", i, resp.StatusCode) + } + } +} diff --git a/internal/httpapi/messages.go b/internal/httpapi/messages.go new file mode 100644 index 0000000..dd1a2af --- /dev/null +++ b/internal/httpapi/messages.go @@ -0,0 +1,80 @@ +package httpapi + +import ( + "errors" + "net/http" + "regexp" + + "mtusi2026/internal/model" + "mtusi2026/internal/store" +) + +var idemKeyRe = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`) + +func (a *api) handleCreateMessage(w http.ResponseWriter, r *http.Request, u model.User, requestID string) { + chatID, ok := chatIDParam(w, r, requestID) + if !ok { + return + } + key := r.Header.Get("Idempotency-Key") + if !idemKeyRe.MatchString(key) { + writeError(w, http.StatusBadRequest, requestID, codeInvalidRequest, "missing or invalid Idempotency-Key") + return + } + + var req model.CreateMessageRequest + if err := decodeJSONStrict(r, &req); err != nil { + writeError(w, http.StatusBadRequest, requestID, codeInvalidRequest, "malformed request body") + return + } + + m, err := a.store.CreateMessage(r.Context(), chatID, u.ID, key, req.Text) + if err != nil { + switch { + case errors.Is(err, store.ErrChatNotFound): + writeError(w, http.StatusNotFound, requestID, codeNotFound, "chat not found") + case errors.Is(err, store.ErrIdempotencyConflict): + writeError(w, http.StatusConflict, requestID, codeConflict, "Idempotency-Key was used with a different request body") + case errors.Is(err, store.ErrValidation): + writeError(w, http.StatusBadRequest, requestID, codeInvalidRequest, "invalid text") + default: + writeError(w, http.StatusInternalServerError, requestID, codeInternal, "internal error") + } + return + } + writeJSON(w, http.StatusCreated, requestID, m) +} + +func (a *api) handleListMessages(w http.ResponseWriter, r *http.Request, u model.User, requestID string) { + chatID, ok := chatIDParam(w, r, requestID) + if !ok { + return + } + limit, ok := parseLimit(r) + if !ok { + writeError(w, http.StatusBadRequest, requestID, codeInvalidRequest, "invalid limit") + return + } + cursorStr, ok := parseCursor(r) + if !ok { + writeError(w, http.StatusBadRequest, requestID, codeInvalidRequest, "invalid cursor") + return + } + + items, next, err := a.store.ListMessages(r.Context(), chatID, u.ID, cursorStr, limit) + if err != nil { + switch { + case errors.Is(err, store.ErrChatNotFound): + writeError(w, http.StatusNotFound, requestID, codeNotFound, "chat not found") + case errors.Is(err, store.ErrValidation): + writeError(w, http.StatusBadRequest, requestID, codeInvalidRequest, "invalid cursor") + default: + writeError(w, http.StatusInternalServerError, requestID, codeInternal, "internal error") + } + return + } + if items == nil { + items = []model.Message{} + } + writeJSON(w, http.StatusOK, requestID, model.MessagePage{Items: items, NextCursor: next}) +} diff --git a/internal/httpapi/middleware.go b/internal/httpapi/middleware.go new file mode 100644 index 0000000..14d7bff --- /dev/null +++ b/internal/httpapi/middleware.go @@ -0,0 +1,41 @@ +package httpapi + +import ( + "log" + "net/http" + "time" + + "mtusi2026/internal/store" +) + +type statusRecorder struct { + http.ResponseWriter + status int +} + +func (r *statusRecorder) WriteHeader(status int) { + r.status = status + r.ResponseWriter.WriteHeader(status) +} + +func loggingMiddleware(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + start := time.Now() + rec := &statusRecorder{ResponseWriter: w, status: http.StatusOK} + next.ServeHTTP(rec, r) + log.Printf("method=%s path=%s status=%d duration=%s", + r.Method, r.URL.Path, rec.status, time.Since(start)) + }) +} + +func concurrencyMiddleware(limiter *store.Limiter, next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if !limiter.TryAcquire() { + requestID := newRequestID() + writeError(w, http.StatusServiceUnavailable, requestID, codeUnavailable, "сервер перегружен, попробуйте позже") + return + } + defer limiter.Release() + next.ServeHTTP(w, r) + }) +} diff --git a/internal/httpapi/race_test.go b/internal/httpapi/race_test.go new file mode 100644 index 0000000..a7f1ec6 --- /dev/null +++ b/internal/httpapi/race_test.go @@ -0,0 +1,163 @@ +package httpapi + +import ( + "bytes" + "encoding/json" + "fmt" + "net/http" + "strings" + "sync" + "testing" + + "mtusi2026/internal/model" +) + +func TestConcurrentMessages_NoLostOrDuplicated(t *testing.T) { + srv := newTestServer(t) + defer srv.Close() + + alice := mustRegisterUser(t, srv, "alice") + chat := mustCreateChat(t, srv, alice, "нагрузочный чат", []string{alice.ID}) + const clients = 10 + const perClients = 10 + const total = clients * perClients + + var wg sync.WaitGroup + errCh := make(chan error, total) + client := srv.Client() + + for c := 0; c < clients; c++ { + wg.Add(1) + go func(clientNum int) { + defer wg.Done() + for i := 0; i < perClients; i++ { + text := fmt.Sprintf("client-%d-msg-%d", clientNum, i) + body, _ := json.Marshal(model.CreateMessageRequest{Text: text}) + req, err := http.NewRequest( + http.MethodPost, + fmt.Sprintf("%s/api/v1/chats/%s/messages", srv.URL, chat.ID), + bytes.NewReader(body), + ) + if err != nil { + errCh <- fmt.Errorf("client %d: build request: %w", clientNum, err) + continue + } + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Authorization", "Bearer "+alice.Token) + req.Header.Set("Idempotency-Key", fmt.Sprintf("race-%d-%d", clientNum, i)) + resp, err := client.Do(req) + if err != nil { + errCh <- fmt.Errorf("client %d: do request: %w", clientNum, err) + continue + } + if resp.StatusCode != http.StatusCreated { + errCh <- fmt.Errorf("client %d msg %d: expected 201, got %d", clientNum, i, resp.StatusCode) + } + resp.Body.Close() + } + }(c) + } + wg.Wait() + close(errCh) + + for err := range errCh { + t.Error(err) + } + if t.Failed() { + t.Fatal("прекращение из-за ошбок запросов") + } + + resp := getJSON(t, srv, fmt.Sprintf("/api/v1/chats/%s/messages?limit=100", chat.ID), alice.Token) + if resp.StatusCode != http.StatusOK { + t.Fatalf("list messages: expected 200, got %d", resp.StatusCode) + } + page := decodeBody[model.MessagePage](t, resp) + + if page.NextCursor != nil { + t.Fatalf("expected all %d messages to fit on one page with limit=100, got next_cursor", total) + } + if len(page.Items) != total { + t.Fatalf("expected exactly %d messages, got %d", total, len(page.Items)) + } + + seen := make(map[string]bool, total) + for _, m := range page.Items { + if seen[m.ID] { + t.Fatalf("duplicate message ID found: %s", m.ID) + } + seen[m.ID] = true + if m.SenderID != alice.ID { + t.Fatalf("unexpected sender_id: %s", m.SenderID) + } + } +} + +func TestRegisterUser_ConcurrentDuplicateUsername_OnlyOneSucceeds(t *testing.T) { + srv := newTestServer(t) + defer srv.Close() + + const workers = 20 + + statuses := make(chan int, workers) + + var wg sync.WaitGroup + wg.Add(workers) + + for i := 0; i < workers; i++ { + go func() { + defer wg.Done() + + body := `{ + "username": "raceuser", + "display_name": "Race User", + "password": "correct-horse-battery-staple" + }` + + req, err := http.NewRequest( + http.MethodPost, + srv.URL+"/api/v1/users", + strings.NewReader(body), + ) + if err != nil { + statuses <- -1 + return + } + + req.Header.Set("Content-Type", "application/json") + + resp, err := srv.Client().Do(req) + if err != nil { + statuses <- -1 + return + } + + statuses <- resp.StatusCode + resp.Body.Close() + }() + } + + wg.Wait() + close(statuses) + + created := 0 + conflicts := 0 + + for status := range statuses { + switch status { + case http.StatusCreated: + created++ + case http.StatusConflict: + conflicts++ + default: + t.Errorf("unexpected status code: %d", status) + } + } + + if created != 1 { + t.Fatalf("ожидалась одна успешная регистрация, got %d", created) + } + + if conflicts != workers-1 { + t.Fatalf("expected %d conflicts, got %d", workers-1, conflicts) + } +} diff --git a/internal/httpapi/router.go b/internal/httpapi/router.go new file mode 100644 index 0000000..b9479e9 --- /dev/null +++ b/internal/httpapi/router.go @@ -0,0 +1,84 @@ +package httpapi + +import ( + "net/http" + "sync/atomic" + + "github.com/jackc/pgx/v5/pgxpool" + "github.com/redis/go-redis/v9" + + "mtusi2026/internal/cache" + "mtusi2026/internal/model" + "mtusi2026/internal/sessionstore" + "mtusi2026/internal/store" +) + +type Options struct { + InstanceID string + Redis *redis.Client + Draining *atomic.Bool +} + +func NewRouter(s *store.Store, pool *pgxpool.Pool, sessionStores ...sessionstore.Store) http.Handler { + var ss sessionstore.Store + if len(sessionStores) > 0 { + ss = sessionStores[0] + } + return NewRouterWithCache(s, pool, ss, nil) +} + +func NewRouterWithCache( + s *store.Store, + pool *pgxpool.Pool, + sessionStore sessionstore.Store, + chatCache *cache.Cache, + opts ...Options, +) http.Handler { + var o Options + if len(opts) > 0 { + o = opts[0] + } + if o.InstanceID == "" { + o.InstanceID = "local" + } + if o.Draining == nil { + o.Draining = new(atomic.Bool) + } + + a := &api{ + store: s, + sessionStore: sessionStore, + chatCache: chatCache, + } + + apiMux := http.NewServeMux() + apiMux.HandleFunc("POST /api/v1/users", a.handleRegisterUser) + apiMux.HandleFunc("GET /api/v1/users/me", a.authMiddleware(a.handleCurrentUser)) + apiMux.HandleFunc("POST /api/v1/chats", a.authMiddleware(a.handleCreateChat)) + apiMux.HandleFunc("GET /api/v1/chats", a.authMiddleware(a.handleListChats)) + apiMux.HandleFunc("GET /api/v1/chats/{chat_id}", a.authMiddleware(a.handleGetChat)) + apiMux.HandleFunc("POST /api/v1/chats/{chat_id}/messages", a.authMiddleware(a.handleCreateMessage)) + apiMux.HandleFunc("GET /api/v1/chats/{chat_id}/messages", a.authMiddleware(a.handleListMessages)) + apiMux.HandleFunc("POST /api/v1/auth/sessions", a.handleCreateSession) + apiMux.HandleFunc("DELETE /api/v1/auth/sessions/current", a.authMiddleware( + func(w http.ResponseWriter, r *http.Request, u model.User, requestID string) { + a.handleDeleteSession(w, r) + })) + + root := http.NewServeMux() + root.HandleFunc("GET /health/live", handleHealthLive) + root.HandleFunc("GET /health/ready", handleHealthReady(pool, o.Redis, o.Draining)) + root.Handle("/", concurrencyMiddleware(s.Limiter, apiMux)) + + var h http.Handler = root + h = loggingMiddleware(h) + h = instanceMiddleware(o.InstanceID, h) + return h +} + +func instanceMiddleware(id string, next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("X-Instance-Id", id) + next.ServeHTTP(w, r) + }) +} diff --git a/internal/httpapi/sessionstore_test.go b/internal/httpapi/sessionstore_test.go new file mode 100644 index 0000000..72936c5 --- /dev/null +++ b/internal/httpapi/sessionstore_test.go @@ -0,0 +1,73 @@ +package httpapi + +import ( + "context" + "sync" + "time" + + "mtusi2026/internal/sessionstore" +) + +type memorySession struct { + userID string + expiresAt time.Time +} + +type memorySessionStore struct { + mu sync.Mutex + sessions map[string]memorySession +} + +func newMemorySessionStore() *memorySessionStore { + return &memorySessionStore{ + sessions: make(map[string]memorySession), + } +} + +func (s *memorySessionStore) Create( + _ context.Context, + token string, + userID string, + ttl time.Duration, +) (time.Time, error) { + s.mu.Lock() + defer s.mu.Unlock() + + expiresAt := time.Now().UTC().Add(ttl) + s.sessions[token] = memorySession{ + userID: userID, + expiresAt: expiresAt, + } + return expiresAt, nil +} + +func (s *memorySessionStore) GetUserID( + _ context.Context, + token string, +) (string, error) { + s.mu.Lock() + defer s.mu.Unlock() + + session, ok := s.sessions[token] + if !ok || !time.Now().UTC().Before(session.expiresAt) { + delete(s.sessions, token) + return "", sessionstore.ErrNotFound + } + + return session.userID, nil +} + +func (s *memorySessionStore) Delete( + _ context.Context, + token string, +) (bool, error) { + s.mu.Lock() + defer s.mu.Unlock() + + if _, ok := s.sessions[token]; !ok { + return false, nil + } + + delete(s.sessions, token) + return true, nil +} diff --git a/internal/httpapi/testmain_test.go b/internal/httpapi/testmain_test.go new file mode 100644 index 0000000..a8bfef4 --- /dev/null +++ b/internal/httpapi/testmain_test.go @@ -0,0 +1,145 @@ +package httpapi + +import ( + "context" + "fmt" + "log" + "net/url" + "os" + "path/filepath" + "testing" + "time" + + "github.com/golang-migrate/migrate/v4" + _ "github.com/golang-migrate/migrate/v4/database/pgx/v5" + _ "github.com/golang-migrate/migrate/v4/source/file" + "github.com/jackc/pgx/v5/pgxpool" + "github.com/redis/go-redis/v9" + "github.com/testcontainers/testcontainers-go" + tcpostgres "github.com/testcontainers/testcontainers-go/modules/postgres" + tcredis "github.com/testcontainers/testcontainers-go/modules/redis" + "github.com/testcontainers/testcontainers-go/wait" +) + +var testPool *pgxpool.Pool +var testRedis *redis.Client + +// поднимает эфемерный Postgres в Docker применяет миграции даёт testPool +// всем тестам пакета и гарантированно убивает контейнер в конце прогона :) +func TestMain(m *testing.M) { + ctx := context.Background() + + pgContainer, err := tcpostgres.Run(ctx, + "postgres:16.4-alpine", + tcpostgres.WithDatabase("messenger_test"), + tcpostgres.WithUsername("messenger_test"), + tcpostgres.WithPassword("messenger_test"), + testcontainers.WithWaitStrategy( + wait.ForLog("database system is ready to accept connections"). + WithOccurrence(2). + WithStartupTimeout(30*time.Second), + ), + ) + if err != nil { + log.Fatalf("start postgres container: %v", err) + } + defer func() { + if err := pgContainer.Terminate(ctx); err != nil { + log.Printf("terminate postgres container: %v", err) + } + }() + + dsn, err := pgContainer.ConnectionString(ctx, "sslmode=disable") + if err != nil { + log.Fatalf("get connection string: %v", err) + } + + if err := applyMigrations(dsn); err != nil { + log.Fatalf("apply migrations: %v", err) + } + + poolCfg, err := pgxpool.ParseConfig(dsn) + if err != nil { + log.Fatalf("parse pool config: %v", err) + } + testPool, err = pgxpool.NewWithConfig(ctx, poolCfg) + if err != nil { + log.Fatalf("create pool: %v", err) + } + defer testPool.Close() + + if err := testPool.Ping(ctx); err != nil { + log.Fatalf("ping test db: %v", err) + } + + redisContainer, err := tcredis.Run(ctx, "redis:7.4-alpine") + if err != nil { + log.Fatalf("start redis container: %v", err) + } + defer func() { + if err := testcontainers.TerminateContainer(redisContainer); err != nil { + log.Printf("terminate redis container: %v", err) + } + }() + + redisURL, err := redisContainer.ConnectionString(ctx) + if err != nil { + log.Fatalf("get redis connection string: %v", err) + } + + redisOpts, err := redis.ParseURL(redisURL) + if err != nil { + log.Fatalf("parse redis url: %v", err) + } + + testRedis = redis.NewClient(redisOpts) + defer testRedis.Close() + + if err := testRedis.Ping(ctx).Err(); err != nil { + log.Fatalf("ping test redis: %v", err) + } + + os.Exit(m.Run()) +} + +// тесты запускаются из internal/httpapi/ поэтому путь на три уровня вверх +// и прогоняет все .up.sql через golang-migrate +func applyMigrations(dsn string) error { + migrationsPath, err := filepath.Abs(filepath.Join("..", "..", "migrations")) + if err != nil { + return err + } + + u, err := url.Parse(dsn) + if err != nil { + return fmt.Errorf("parse dsn: %w", err) + } + u.Scheme = "pgx5" + + m, err := migrate.New( + fmt.Sprintf("file://%s", migrationsPath), + u.String(), + ) + if err != nil { + return fmt.Errorf("migrate.New: %w", err) + } + defer m.Close() + + if err := m.Up(); err != nil && err != migrate.ErrNoChange { + return fmt.Errorf("migrate.Up: %w", err) + } + return nil +} + +// truncateAll очищает все таблицы между тестами сохраняя схему +// быстрее чем пересоздавать контейнер на каждый тест +func truncateAll(t *testing.T) { + t.Helper() + ctx := context.Background() + _, err := testPool.Exec(ctx, + `TRUNCATE TABLE messages, chat_members, chats, sessions, users RESTART IDENTITY CASCADE`, + ) + if err != nil { + t.Fatalf("truncate tables: %v", err) + } +} diff --git a/internal/httpapi/transaction_test.go b/internal/httpapi/transaction_test.go new file mode 100644 index 0000000..f1702a2 --- /dev/null +++ b/internal/httpapi/transaction_test.go @@ -0,0 +1,63 @@ +package httpapi + +import ( + "context" + "errors" + "testing" + + "mtusi2026/internal/store" +) + +func TestCreateChat_RollsBackOnMemberInsertFailure(t *testing.T) { + srv := newTestServer(t) + defer srv.Close() + + alice := mustRegisterUser(t, srv, "rollback_alice") + + ctx := context.Background() + s := store.New(testPool, newUnlimitedLimiter()) + + missingUserID := "00000000-0000-0000-0000-000000000000" + + _, err := s.CreateChat( + ctx, + alice.ID, + "rollback-test", + []string{alice.ID, missingUserID}, + ) + + if !errors.Is(err, store.ErrValidation) { + t.Fatalf("expected ErrValidation, got %v", err) + } + + var chatCount int + err = testPool.QueryRow( + ctx, + `SELECT COUNT(*) FROM chats WHERE title = $1`, + "rollback-test", + ).Scan(&chatCount) + if err != nil { + t.Fatalf("check chats after rollback: %v", err) + } + + if chatCount != 0 { + t.Fatalf("expected 0 chats after rollback, got %d", chatCount) + } + + var membershipCount int + err = testPool.QueryRow( + ctx, + `SELECT COUNT(*) + FROM chat_members cm + JOIN chats c ON c.id = cm.chat_id + WHERE c.title = $1`, + "rollback-test", + ).Scan(&membershipCount) + if err != nil { + t.Fatalf("check chat_members after rollback: %v", err) + } + + if membershipCount != 0 { + t.Fatalf("expected 0 chat members after rollback, got %d", membershipCount) + } +} diff --git a/internal/httpapi/users.go b/internal/httpapi/users.go new file mode 100644 index 0000000..939ad09 --- /dev/null +++ b/internal/httpapi/users.go @@ -0,0 +1,117 @@ +package httpapi + +import ( + "errors" + "net/http" + "regexp" + "unicode/utf8" + + "golang.org/x/sync/singleflight" + + "mtusi2026/internal/auth" + "mtusi2026/internal/cache" + "mtusi2026/internal/model" + "mtusi2026/internal/sessionstore" + "mtusi2026/internal/store" +) + +var usernameRe = regexp.MustCompile(`^[a-z0-9_]{3,32}$`) + +type api struct { + store *store.Store + sessionStore sessionstore.Store + chatCache *cache.Cache + chatFlight singleflight.Group +} + +func (a *api) authMiddleware(next func(w http.ResponseWriter, r *http.Request, u model.User, requestID string)) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + requestID := newRequestID() + + token, ok := bearerToken(r) + if !ok { + w.Header().Set("WWW-Authenticate", `Bearer realm="messenger"`) + writeError(w, http.StatusUnauthorized, requestID, codeUnauthorized, "missing or malformed Bearer token") + return + } + + userID, err := a.sessionStore.GetUserID(r.Context(), token) + if err != nil { + if errors.Is(err, sessionstore.ErrNotFound) { + w.Header().Set("WWW-Authenticate", `Bearer realm="messenger"`) + writeError(w, http.StatusUnauthorized, requestID, codeUnauthorized, "invalid, expired or revoked token") + return + } + + writeError(w, http.StatusServiceUnavailable, requestID, codeInternal, "session service unavailable") + return + } + + u, ok, err := a.store.GetUserByID(r.Context(), userID) + if err != nil { + writeError(w, http.StatusServiceUnavailable, requestID, codeInternal, "database unavailable") + return + } + if !ok { + w.Header().Set("WWW-Authenticate", `Bearer realm="messenger"`) + writeError(w, http.StatusUnauthorized, requestID, codeUnauthorized, "invalid session user") + return + } + + next(w, r, u, requestID) + } +} + +func validDisplayName(s string) bool { + return validText(s, 100) +} + +func validPassword(s string) bool { + n := utf8.RuneCountInString(s) + return n >= 12 && n <= 128 +} + +func (a *api) handleRegisterUser(w http.ResponseWriter, r *http.Request) { + requestID := newRequestID() + + var req model.CreateUserRequest + if err := decodeJSONStrict(r, &req); err != nil { + writeError(w, http.StatusBadRequest, requestID, codeInvalidRequest, "malformed request body") + return + } + + if !usernameRe.MatchString(req.Username) { + writeError(w, http.StatusBadRequest, requestID, codeInvalidRequest, "username must match ^[a-z0-9_]{3,32}$") + return + } + if !validDisplayName(req.DisplayName) { + writeError(w, http.StatusBadRequest, requestID, codeInvalidRequest, "display_name must be 1-100 non-blank code points") + return + } + if !validPassword(req.Password) { + writeError(w, http.StatusBadRequest, requestID, codeInvalidRequest, "password must be 12-128 code points") + return + } + + passwordHash, err := auth.HashPassword(req.Password) + if err != nil { + writeError(w, http.StatusInternalServerError, requestID, codeInternal, "internal error") + return + } + + u, err := a.store.CreateUser(r.Context(), req.Username, req.DisplayName, passwordHash) + if err != nil { + if err == store.ErrUsernameTaken { + writeError(w, http.StatusConflict, requestID, codeConflict, "username already taken") + return + } + writeError(w, http.StatusInternalServerError, requestID, codeInternal, "internal error") + return + } + + writeJSON(w, http.StatusCreated, requestID, u) +} + +func (a *api) handleCurrentUser(w http.ResponseWriter, r *http.Request, u model.User, requestID string) { + writeJSON(w, http.StatusOK, requestID, u) +} diff --git a/internal/httpapi/validate.go b/internal/httpapi/validate.go new file mode 100644 index 0000000..11da225 --- /dev/null +++ b/internal/httpapi/validate.go @@ -0,0 +1,45 @@ +package httpapi + +import ( + "net/http" + "strings" + "unicode" + "unicode/utf8" + + "mtusi2026/internal/idgen" +) + +func validText(s string, max int) bool { + n := utf8.RuneCountInString(s) + if n < 1 || n > max { + return false + } + hasContent := false + for _, r := range s { + if r == 0 { + return false + } + if !unicode.IsSpace(r) { + hasContent = true + } + } + return hasContent +} + +func parseCursor(r *http.Request) (string, bool) { + q := r.URL.Query() + if !q.Has("cursor") { + return "", true + } + c := q.Get("cursor") + return c, c != "" +} + +func chatIDParam(w http.ResponseWriter, r *http.Request, requestID string) (string, bool) { + id := r.PathValue("chat_id") + if !idgen.IsValidUUID(id) { + writeError(w, http.StatusBadRequest, requestID, codeInvalidRequest, "invalid chat_id") + return "", false + } + return strings.ToLower(id), true +} diff --git a/internal/idgen/uuid.go b/internal/idgen/uuid.go new file mode 100644 index 0000000..50b9c6c --- /dev/null +++ b/internal/idgen/uuid.go @@ -0,0 +1,23 @@ +package idgen + +import ( + "crypto/rand" + "fmt" + "regexp" +) + +var uuidRe = regexp.MustCompile(`^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$`) + +func IsValidUUID(s string) bool { + return uuidRe.MatchString(s) +} + +func GenerateUUIDv4() string { + b := make([]byte, 16) + if _, err := rand.Read(b); err != nil { + panic(err) + } + b[6] = (b[6] & 0x0f) | 0x40 + b[8] = (b[8] & 0x3f) | 0x80 + return fmt.Sprintf("%x-%x-%x-%x-%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:16]) +} diff --git a/internal/model/model.go b/internal/model/model.go new file mode 100644 index 0000000..e468a34 --- /dev/null +++ b/internal/model/model.go @@ -0,0 +1,65 @@ +package model + +import "time" + +type User struct { + ID string `json:"id"` + Username string `json:"username"` + DisplayName string `json:"display_name"` + CreatedAt time.Time `json:"created_at"` +} + +type CreateUserRequest struct { + Username string `json:"username"` + DisplayName string `json:"display_name"` + Password string `json:"password"` +} + +type Chat struct { + ID string `json:"id"` + Title string `json:"title"` + MemberIDs []string `json:"member_ids"` + CreatedAt time.Time `json:"created_at"` +} + +type CreateChatRequest struct { + Title string `json:"title"` + MemberIDs []string `json:"member_ids"` +} + +type ChatPage struct { + Items []Chat `json:"items"` + NextCursor *string `json:"next_cursor"` +} + +type Message struct { + ID string `json:"id"` + ChatID string `json:"chat_id"` + SenderID string `json:"sender_id"` + Text string `json:"text"` + CreatedAt time.Time `json:"created_at"` +} + +type CreateMessageRequest struct { + Text string `json:"text"` +} + +type MessagePage struct { + Items []Message `json:"items"` + NextCursor *string `json:"next_cursor"` +} + +type ErrorEnvelope struct { + Error struct { + Code string `json:"code"` + Message string `json:"message"` + RequestID string `json:"request_id"` + } `json:"error"` +} + +type Session struct { + Token string `json:"token"` + TokenType string `json:"token_type"` + ExpiresAt time.Time `json:"expires_at"` + User User `json:"user"` +} diff --git a/internal/sessionstore/redis.go b/internal/sessionstore/redis.go new file mode 100644 index 0000000..2aadedb --- /dev/null +++ b/internal/sessionstore/redis.go @@ -0,0 +1,73 @@ +package sessionstore + +import ( + "context" + "errors" + "fmt" + "time" + + "github.com/redis/go-redis/v9" +) + +type RedisStore struct { + client *redis.Client +} + +func NewRedis(client *redis.Client) *RedisStore { + return &RedisStore{client: client} +} + +func NewRedisClient(ctx context.Context, addr string) (*redis.Client, error) { + client := redis.NewClient(&redis.Options{ + Addr: addr, + }) + + if err := client.Ping(ctx).Err(); err != nil { + _ = client.Close() + return nil, fmt.Errorf("%w: redis ping: %v", ErrUnavailable, err) + } + + return client, nil +} + +func sessionKey(token string) string { + return "session:" + token +} + +func (s *RedisStore) Create( + ctx context.Context, + token string, + userID string, + ttl time.Duration, +) (time.Time, error) { + if ttl <= 0 { + return time.Time{}, fmt.Errorf("invalid session ttl: %s", ttl) + } + + if err := s.client.Set(ctx, sessionKey(token), userID, ttl).Err(); err != nil { + return time.Time{}, fmt.Errorf("%w: create session: %v", ErrUnavailable, err) + } + + return time.Now().UTC().Add(ttl), nil +} + +func (s *RedisStore) GetUserID(ctx context.Context, token string) (string, error) { + userID, err := s.client.Get(ctx, sessionKey(token)).Result() + if errors.Is(err, redis.Nil) { + return "", ErrNotFound + } + if err != nil { + return "", fmt.Errorf("%w: get session: %v", ErrUnavailable, err) + } + + return userID, nil +} + +func (s *RedisStore) Delete(ctx context.Context, token string) (bool, error) { + n, err := s.client.Del(ctx, sessionKey(token)).Result() + if err != nil { + return false, fmt.Errorf("%w: delete session: %v", ErrUnavailable, err) + } + + return n > 0, nil +} diff --git a/internal/sessionstore/sessionstore.go b/internal/sessionstore/sessionstore.go new file mode 100644 index 0000000..506982e --- /dev/null +++ b/internal/sessionstore/sessionstore.go @@ -0,0 +1,18 @@ +package sessionstore + +import ( + "context" + "errors" + "time" +) + +var ( + ErrNotFound = errors.New("session not found or expired") + ErrUnavailable = errors.New("session store unavailable") +) + +type Store interface { + Create(ctx context.Context, token, userID string, ttl time.Duration) (time.Time, error) + GetUserID(ctx context.Context, token string) (string, error) + Delete(ctx context.Context, token string) (bool, error) +} diff --git a/internal/store/limits.go b/internal/store/limits.go new file mode 100644 index 0000000..37630f0 --- /dev/null +++ b/internal/store/limits.go @@ -0,0 +1,51 @@ +package store + +import "sync/atomic" + +type Limiter struct { + maxMessages int64 + messageCount int64 + maxConcurrent int + inFlight chan struct{} +} + +func NewLimiter(maxMessages int64, maxConcurrent int) *Limiter { + return &Limiter{ + maxMessages: maxMessages, + maxConcurrent: maxConcurrent, + inFlight: make(chan struct{}, maxConcurrent), + } +} + +func (l *Limiter) TryReserveMessage() bool { + for { + cur := atomic.LoadInt64(&l.messageCount) + if cur >= l.maxMessages { + return false + } + if atomic.CompareAndSwapInt64(&l.messageCount, cur, cur+1) { + return true + } + } +} + +func (l *Limiter) ReleaseMessage() { + atomic.AddInt64(&l.messageCount, -1) +} + +func (l *Limiter) CurrentMessageCount() int64 { + return atomic.LoadInt64(&l.messageCount) +} + +func (l *Limiter) TryAcquire() bool { + select { + case l.inFlight <- struct{}{}: + return true + default: + return false + } +} + +func (l *Limiter) Release() { + <-l.inFlight +} diff --git a/internal/store/store.go b/internal/store/store.go new file mode 100644 index 0000000..13ec038 --- /dev/null +++ b/internal/store/store.go @@ -0,0 +1,436 @@ +package store + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "errors" + "fmt" + "strconv" + "sync/atomic" + "unicode" + "unicode/utf8" + + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgconn" + "github.com/jackc/pgx/v5/pgxpool" + + "mtusi2026/internal/cursor" + "mtusi2026/internal/idgen" + "mtusi2026/internal/model" +) + +var ( + ErrUsernameTaken = errors.New("username taken") + ErrChatNotFound = errors.New("chat not found or not accessible") + ErrValidation = errors.New("validation failed") + ErrCapacityExceeded = errors.New("message capacity exceeded") +) + +type Store struct { + pool *pgxpool.Pool + Limiter *Limiter + chatSQLQueries atomic.Int64 +} + +func New(pool *pgxpool.Pool, limiter *Limiter) *Store { + return &Store{pool: pool, Limiter: limiter} +} + +func (s *Store) CreateUser(ctx context.Context, username, displayName, passwordHash string) (model.User, error) { + var u model.User + err := s.pool.QueryRow(ctx, + `INSERT INTO users (username, display_name, password_hash) + VALUES ($1, $2, $3) + RETURNING id, username, display_name, created_at`, + username, displayName, passwordHash, + ).Scan(&u.ID, &u.Username, &u.DisplayName, &u.CreatedAt) + + if err != nil { + if isUniqueViolation(err) { + return model.User{}, ErrUsernameTaken + } + return model.User{}, err + } + return u, nil +} + +func (s *Store) GetUserByID(ctx context.Context, id string) (model.User, bool, error) { + var u model.User + err := s.pool.QueryRow(ctx, + `SELECT id, username, display_name, created_at FROM users WHERE id = $1`, + id, + ).Scan(&u.ID, &u.Username, &u.DisplayName, &u.CreatedAt) + + if errors.Is(err, pgx.ErrNoRows) { + return model.User{}, false, nil + } + if err != nil { + return model.User{}, false, err + } + + return u, true, nil +} + +func (s *Store) CreateChat(ctx context.Context, callerID, title string, memberIDs []string) (model.Chat, error) { + if len(memberIDs) == 0 || len(memberIDs) > 100 { + return model.Chat{}, ErrValidation + } + + seen := make(map[string]bool, len(memberIDs)) + callerIncluded := false + for _, id := range memberIDs { + if seen[id] { + return model.Chat{}, ErrValidation + } + seen[id] = true + if id == callerID { + callerIncluded = true + } + } + if !callerIncluded { + return model.Chat{}, ErrValidation + } + + tx, err := s.pool.Begin(ctx) + if err != nil { + return model.Chat{}, err + } + defer tx.Rollback(ctx) + + var c model.Chat + err = tx.QueryRow(ctx, + `INSERT INTO chats (title) VALUES ($1) RETURNING id, title, created_at`, + title, + ).Scan(&c.ID, &c.Title, &c.CreatedAt) + if err != nil { + return model.Chat{}, err + } + + for _, memberID := range memberIDs { + _, err = tx.Exec(ctx, + `INSERT INTO chat_members (chat_id, user_id) VALUES ($1, $2)`, + c.ID, memberID, + ) + if err != nil { + if isForeignKeyViolation(err) { + return model.Chat{}, ErrValidation + } + return model.Chat{}, err + } + } + + if err := tx.Commit(ctx); err != nil { + return model.Chat{}, err + } + + c.MemberIDs = append([]string{}, memberIDs...) + return c, nil +} + +func (s *Store) GetChat(ctx context.Context, chatID, userID string) (model.Chat, error) { + var c model.Chat + s.chatSQLQueries.Add(1) + + err := s.pool.QueryRow(ctx, + `SELECT c.id, c.title, c.created_at + FROM chats c + JOIN chat_members cm ON cm.chat_id = c.id AND cm.user_id = $2 + WHERE c.id = $1`, + chatID, userID, + ).Scan(&c.ID, &c.Title, &c.CreatedAt) + + if err != nil { + if errors.Is(err, pgx.ErrNoRows) { + return model.Chat{}, ErrChatNotFound + } + return model.Chat{}, fmt.Errorf("get chat: %w", err) + } + + memberIDs, err := s.listChatMemberIDs(ctx, c.ID) + if err != nil { + return model.Chat{}, err + } + c.MemberIDs = memberIDs + return c, nil +} + +func (s *Store) listChatMemberIDs(ctx context.Context, chatID string) ([]string, error) { + s.chatSQLQueries.Add(1) + + rows, err := s.pool.Query(ctx, `SELECT user_id FROM chat_members WHERE chat_id = $1`, chatID) + if err != nil { + return nil, err + } + defer rows.Close() + + var ids []string + for rows.Next() { + var id string + if err := rows.Scan(&id); err != nil { + return nil, err + } + ids = append(ids, id) + } + return ids, rows.Err() +} + +func (s *Store) ListChatsForUser(ctx context.Context, userID, cursorStr string, limit int) ([]model.Chat, *string, error) { + var after *cursor.Cursor + if cursorStr != "" { + c, err := cursor.Decode(cursorStr) + if err != nil || c.Scope != "chats:"+userID { + return nil, nil, ErrValidation + } + after = &c + } + + query := ` + SELECT c.id, c.title, c.created_at + FROM chats c + JOIN chat_members cm ON cm.chat_id = c.id + WHERE cm.user_id = $1` + args := []any{userID} + + if after != nil { + query += ` AND (c.created_at, c.id) > ($2, $3)` + args = append(args, after.CreatedAt, after.ID) + } + query += ` ORDER BY c.created_at ASC, c.id ASC LIMIT $` + strconv.Itoa(len(args)+1) + args = append(args, limit+1) + + rows, err := s.pool.Query(ctx, query, args...) + if err != nil { + return nil, nil, err + } + defer rows.Close() + + var page []model.Chat + for rows.Next() { + var c model.Chat + if err := rows.Scan(&c.ID, &c.Title, &c.CreatedAt); err != nil { + return nil, nil, err + } + page = append(page, c) + } + if err := rows.Err(); err != nil { + return nil, nil, err + } + + var next *string + if len(page) > limit { + last := page[limit-1] + nc := cursor.Encode(cursor.Cursor{Scope: "chats:" + userID, CreatedAt: last.CreatedAt, ID: last.ID}) + next = &nc + page = page[:limit] + } + + for i := range page { + memberIDs, err := s.listChatMemberIDs(ctx, page[i].ID) + if err != nil { + return nil, nil, err + } + page[i].MemberIDs = memberIDs + } + + return page, next, nil +} + +var ErrIdempotencyConflict = errors.New("idempotency key reused with different body") + +func (s *Store) CreateMessage(ctx context.Context, chatID, senderID, idemKey, text string) (model.Message, error) { + if !validMessageText(text) { + return model.Message{}, ErrValidation + } + sum := sha256.Sum256([]byte(text)) + hash := hex.EncodeToString(sum[:]) + + tx, err := s.pool.Begin(ctx) + if err != nil { + return model.Message{}, err + } + defer tx.Rollback(ctx) + + var isMember bool + if err := tx.QueryRow(ctx, + `SELECT EXISTS(SELECT 1 FROM chat_members WHERE chat_id=$1 AND user_id=$2)`, + chatID, senderID).Scan(&isMember); err != nil { + return model.Message{}, err + } + if !isMember { + return model.Message{}, ErrChatNotFound + } + + msgID := idgen.GenerateUUIDv4() + tag, err := tx.Exec(ctx, + `INSERT INTO idempotency_keys (user_id, chat_id, key, request_hash, message_id) + VALUES ($1,$2,$3,$4,$5) + ON CONFLICT (user_id, chat_id, key) DO NOTHING`, + senderID, chatID, idemKey, hash, msgID) + if err != nil { + return model.Message{}, err + } + + if tag.RowsAffected() == 0 { + var storedHash string + var m model.Message + err := tx.QueryRow(ctx, + `SELECT k.request_hash, m.id, m.chat_id, m.sender_id, m.text, m.created_at + FROM idempotency_keys k JOIN messages m ON m.id = k.message_id + WHERE k.user_id=$1 AND k.chat_id=$2 AND k.key=$3`, + senderID, chatID, idemKey, + ).Scan(&storedHash, &m.ID, &m.ChatID, &m.SenderID, &m.Text, &m.CreatedAt) + if err != nil { + return model.Message{}, err + } + if storedHash != hash { + return model.Message{}, ErrIdempotencyConflict + } + return m, nil + } + + var m model.Message + err = tx.QueryRow(ctx, + `INSERT INTO messages (id, chat_id, sender_id, text, created_at) + VALUES ($1,$2,$3,$4, clock_timestamp()) + RETURNING id, chat_id, sender_id, text, created_at`, + msgID, chatID, senderID, text, + ).Scan(&m.ID, &m.ChatID, &m.SenderID, &m.Text, &m.CreatedAt) + if err != nil { + if isCheckViolation(err) { + return model.Message{}, ErrValidation + } + return model.Message{}, err + } + if err := tx.Commit(ctx); err != nil { + return model.Message{}, err + } + return m, nil +} + +func (s *Store) ListMessages(ctx context.Context, chatID, userID, cursorStr string, limit int) ([]model.Message, *string, error) { + var isMember bool + err := s.pool.QueryRow(ctx, + `SELECT EXISTS(SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2)`, + chatID, userID, + ).Scan(&isMember) + if err != nil { + return nil, nil, err + } + if !isMember { + return nil, nil, ErrChatNotFound + } + + var after *cursor.Cursor + if cursorStr != "" { + dc, err := cursor.Decode(cursorStr) + if err != nil || dc.Scope != "messages:"+chatID { + return nil, nil, ErrValidation + } + after = &dc + } + + query := ` + SELECT id, chat_id, sender_id, text, created_at + FROM messages + WHERE chat_id = $1` + args := []any{chatID} + + if after != nil { + query += ` AND (created_at, id) > ($2, $3)` + args = append(args, after.CreatedAt, after.ID) + } + query += ` ORDER BY created_at ASC, id ASC LIMIT $` + strconv.Itoa(len(args)+1) + args = append(args, limit+1) + + rows, err := s.pool.Query(ctx, query, args...) + if err != nil { + return nil, nil, err + } + defer rows.Close() + + var page []model.Message + for rows.Next() { + var m model.Message + if err := rows.Scan(&m.ID, &m.ChatID, &m.SenderID, &m.Text, &m.CreatedAt); err != nil { + return nil, nil, err + } + page = append(page, m) + } + if err := rows.Err(); err != nil { + return nil, nil, err + } + + var next *string + if len(page) > limit { + last := page[limit-1] + nc := cursor.Encode(cursor.Cursor{Scope: "messages:" + chatID, CreatedAt: last.CreatedAt, ID: last.ID}) + next = &nc + page = page[:limit] + } + return page, next, nil +} + +func isUniqueViolation(err error) bool { + var pgErr *pgconn.PgError + return errors.As(err, &pgErr) && pgErr.Code == "23505" +} + +func isForeignKeyViolation(err error) bool { + var pgErr *pgconn.PgError + return errors.As(err, &pgErr) && pgErr.Code == "23503" +} + +func isCheckViolation(err error) bool { + var pgErr *pgconn.PgError + return errors.As(err, &pgErr) && pgErr.Code == "23514" +} + +func validMessageText(s string) bool { + n := utf8.RuneCountInString(s) + if n == 0 || n > 4000 { + return false + } + hasContent := false + for _, r := range s { + if r == 0 { + return false + } + if !unicode.IsSpace(r) { + hasContent = true + } + } + return hasContent +} + +var ErrSessionNotFound = errors.New("session not found or expired") + +func (s *Store) GetUserByUsername(ctx context.Context, username string) (model.User, string, error) { + var u model.User + var passwordHash string + + err := s.pool.QueryRow(ctx, + `SELECT id, username, display_name, created_at, password_hash + FROM users WHERE username = $1`, + username, + ).Scan(&u.ID, &u.Username, &u.DisplayName, &u.CreatedAt, &passwordHash) + + if errors.Is(err, pgx.ErrNoRows) { + return model.User{}, "", ErrUsernameNotFound + } + if err != nil { + return model.User{}, "", err + } + + return u, passwordHash, nil +} + +var ErrUsernameNotFound = errors.New("username not found") + +func (s *Store) ResetChatSQLQueries() { + s.chatSQLQueries.Store(0) +} + +func (s *Store) ChatSQLQueries() int64 { + return s.chatSQLQueries.Load() +} diff --git a/migrations/000001_init_schema.down.sql b/migrations/000001_init_schema.down.sql new file mode 100644 index 0000000..6ec50ce --- /dev/null +++ b/migrations/000001_init_schema.down.sql @@ -0,0 +1,7 @@ +-- 000001_init_schema.down.sql + +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; \ No newline at end of file diff --git a/migrations/000001_init_schema.up.sql b/migrations/000001_init_schema.up.sql new file mode 100644 index 0000000..c8e2068 --- /dev/null +++ b/migrations/000001_init_schema.up.sql @@ -0,0 +1,49 @@ +-- 000001_init_schema.up.sql + +CREATE EXTENSION IF NOT EXISTS pgcrypto; + +CREATE TABLE users ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + username TEXT NOT NULL UNIQUE, + display_name TEXT NOT NULL, + password_hash TEXT NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + CONSTRAINT username_format CHECK (username ~ '^[a-z0-9_]{3,32}$'), + CONSTRAINT display_name_length CHECK (char_length(trim(display_name)) BETWEEN 1 AND 100) +); + +CREATE TABLE chats ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + title TEXT NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + CONSTRAINT title_length CHECK (char_length(title) BETWEEN 1 AND 100) +); + + +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 CASCADE, + PRIMARY KEY (chat_id, user_id) +); + +CREATE TABLE messages ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + chat_id UUID NOT NULL REFERENCES chats(id) ON DELETE CASCADE, + sender_id UUID NOT NULL REFERENCES users(id), + text TEXT NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + CONSTRAINT text_length CHECK (char_length(text) BETWEEN 1 AND 4000) +); + + +CREATE INDEX idx_messages_chat_created_id ON messages (chat_id, created_at, id); + +CREATE TABLE sessions ( + token TEXT 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() +); + +CREATE INDEX idx_sessions_expires_at ON sessions (expires_at); +CREATE INDEX idx_sessions_user_id ON sessions (user_id); \ No newline at end of file diff --git a/migrations/000002_idempotency.up.sql b/migrations/000002_idempotency.up.sql new file mode 100644 index 0000000..4657fa3 --- /dev/null +++ b/migrations/000002_idempotency.up.sql @@ -0,0 +1,11 @@ +CREATE TABLE idempotency_keys ( + user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, + chat_id UUID NOT NULL REFERENCES chats(id) ON DELETE CASCADE, + key TEXT NOT NULL, + request_hash TEXT NOT NULL, + message_id UUID NOT NULL REFERENCES messages(id) ON DELETE CASCADE + DEFERRABLE INITIALLY DEFERRED, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + PRIMARY KEY (user_id, chat_id, key) +); +CREATE INDEX idx_idempotency_created_at ON idempotency_keys (created_at); \ No newline at end of file diff --git a/scripts/check_edge.py b/scripts/check_edge.py new file mode 100644 index 0000000..61f8a1b --- /dev/null +++ b/scripts/check_edge.py @@ -0,0 +1,51 @@ +import base64, json, sys, time, urllib.request, urllib.error, uuid + +BASE = sys.argv[1] if len(sys.argv) > 1 else "http://localhost:8080" +PWD = "correct-horse-battery-staple" + + +def call(method, path, body=None, token=None, basic=None, key=None): + data = json.dumps(body).encode() if body is not None else None + r = urllib.request.Request(BASE + path, data=data, method=method) + if data is not None: r.add_header("Content-Type", "application/json") + if token: r.add_header("Authorization", "Bearer " + token) + if basic: r.add_header("Authorization", "Basic " + base64.b64encode(basic.encode()).decode()) + if key: r.add_header("Idempotency-Key", key) + try: + with urllib.request.urlopen(r, timeout=10) as resp: + return resp.status, json.loads(resp.read() or b"null") + except urllib.error.HTTPError as e: + return e.code, None + + +name = "edge_" + uuid.uuid4().hex[:8] +_, u = call("POST", "/api/v1/users", {"username": name, "display_name": "e", "password": PWD}) +_, s = call("POST", "/api/v1/auth/sessions", basic=f"{name}:{PWD}") +t = s["token"] +_, c = call("POST", "/api/v1/chats", {"title": "t", "member_ids": [u["id"]]}, token=t) +m = f"/api/v1/chats/{c['id']}/messages" +k = lambda: uuid.uuid4().hex + +cases = [ + ("поле Text (другой регистр)", call("POST", m, {"Text": "x"}, token=t, key=k())[0], {400}), + ("текст из NBSP/U+3000", call("POST", m, {"text": "\u00a0\u3000"}, token=t, key=k())[0], {400}), + ("текст с NUL", call("POST", m, {"text": "a\u0000b"}, token=t, key=k())[0], {400}), + ("limit= пустой", call("GET", "/api/v1/chats?limit=", token=t)[0], {400}), + ("cursor= пустой", call("GET", m + "?cursor=", token=t)[0], {400}), + ("chat_id не UUID", call("GET", "/api/v1/chats/not-a-uuid/messages", token=t)[0], {400}), + ("member_ids не UUID", call("POST", "/api/v1/chats", {"title": "t", "member_ids": [u["id"], "not-a-uuid"]}, token=t)[0], {400}), + ("название из пробелов", call("POST", "/api/v1/chats", {"title": " ", "member_ids": [u["id"]]}, token=t)[0], {400}), + ("название 101 символ", call("POST", "/api/v1/chats", {"title": "a" * 101, "member_ids": [u["id"]]}, token=t)[0], {400}), +] +for label, got, ok in cases: + print("PASS" if got in ok else "FAIL", label, "->", got) + + +def login_ms(basic): + t0 = time.time(); call("POST", "/api/v1/auth/sessions", basic=basic) + return (time.time() - t0) * 1000 + +ms_unknown = sorted(login_ms("nobody_" + uuid.uuid4().hex[:6] + ":" + PWD) for _ in range(5))[2] +ms_wrong = sorted(login_ms(name + ":wrong-password-123") for _ in range(5))[2] +print("PASS" if abs(ms_unknown - ms_wrong) < 0.5 * ms_wrong else "FAIL", + f"тайминг входа: неизвестный {ms_unknown:.1f} мс, неверный пароль {ms_wrong:.1f} мс") \ No newline at end of file diff --git a/scripts/check_lb.py b/scripts/check_lb.py new file mode 100644 index 0000000..db2ea63 --- /dev/null +++ b/scripts/check_lb.py @@ -0,0 +1,65 @@ +import base64, json, sys, urllib.error, urllib.request, uuid +from concurrent.futures import ThreadPoolExecutor + +BASE = sys.argv[1] if len(sys.argv) > 1 else "http://localhost:8080" +PWD = "correct-horse-battery-staple" + + +def call(method, path, body=None, token=None, basic=None, key=None): + data = json.dumps(body).encode() if body is not None else None + req = urllib.request.Request(BASE + path, data=data, method=method) + if body is not None: + req.add_header("Content-Type", "application/json") + if token: + req.add_header("Authorization", "Bearer " + token) + if basic: + req.add_header("Authorization", "Basic " + base64.b64encode(basic.encode()).decode()) + if key: + req.add_header("Idempotency-Key", key) + try: + with urllib.request.urlopen(req, timeout=10) as r: + raw = r.read() + return r.status, r.headers.get("X-Instance-Id"), json.loads(raw) if raw else None + except urllib.error.HTTPError as e: + return e.code, e.headers.get("X-Instance-Id"), None + + +ok = True +def check(name, cond, info=""): + global ok + ok &= bool(cond) + print(("PASS" if cond else "FAIL"), name, info) + + +name = "lb_" + uuid.uuid4().hex[:10] +s, _, user = call("POST", "/api/v1/users", {"username": name, "display_name": "LB check", "password": PWD}) +s, _, sess = call("POST", "/api/v1/auth/sessions", basic=f"{name}:{PWD}") +token = sess["token"] + +# один токен разные реплики +inst = {call("GET", "/api/v1/users/me", token=token)[1] for _ in range(12)} +check("one token served by >=2 replicas", len(inst) >= 2, sorted(inst)) + +s, _, chat = call("POST", "/api/v1/chats", {"title": "lb", "member_ids": [user["id"]]}, token=token) +path = f"/api/v1/chats/{chat['id']}/messages" + +# конкурентные повторы с одним ключом через lb +key = "conc-" + uuid.uuid4().hex +with ThreadPoolExecutor(30) as ex: + res = list(ex.map(lambda _: call("POST", path, {"text": "race"}, token=token, key=key), range(30))) +ids = {r[2]["id"] for r in res if r[2]} +check("concurrent same key: all 201", all(r[0] == 201 for r in res), sorted({r[0] for r in res})) +check("concurrent same key: one message id", len(ids) == 1, len(ids)) +check("concurrent requests hit >=2 replicas", len({r[1] for r in res}) >= 2, sorted({r[1] for r in res})) + +# последовательный повтор на разных репликах +key2 = "seq-" + uuid.uuid4().hex +seq = [call("POST", path, {"text": "seq"}, token=token, key=key2) for _ in range(6)] +check("sequential repeat: same id", len({r[2]["id"] for r in seq}) == 1) +check("sequential repeat: >=2 replicas", len({r[1] for r in seq}) >= 2, sorted({r[1] for r in seq})) +check("different body, same key -> 409", call("POST", path, {"text": "other"}, token=token, key=key2)[0] == 409) + +s, _, page = call("GET", path + "?limit=100", token=token) +check("history has exactly 2 messages", len(page["items"]) == 2, len(page["items"])) + +sys.exit(0 if ok else 1) \ No newline at end of file diff --git a/scripts/explain_messages.sql b/scripts/explain_messages.sql new file mode 100644 index 0000000..d53eeed --- /dev/null +++ b/scripts/explain_messages.sql @@ -0,0 +1,69 @@ +BEGIN; + +CREATE TEMP TABLE explain_ctx ( + user_id UUID, + chat_id UUID +); + +WITH u AS ( + INSERT INTO users (username, display_name, password_hash) + VALUES ( + 'explain_' || substr(gen_random_uuid()::text, 1, 8), + 'Explain Test', + 'test-hash' + ) + RETURNING id +), +c AS ( + INSERT INTO chats (title) + VALUES ('explain-10000') + RETURNING id +) +INSERT INTO explain_ctx (user_id, chat_id) +SELECT u.id, c.id +FROM u CROSS JOIN c; + +INSERT INTO chat_members (chat_id, user_id) +SELECT chat_id, user_id +FROM explain_ctx; + +INSERT INTO messages (chat_id, sender_id, text, created_at) +SELECT + chat_id, + user_id, + 'message ' || gs, + TIMESTAMPTZ '2026-01-01 00:00:00+00' + gs * INTERVAL '1 second' +FROM explain_ctx +CROSS JOIN generate_series(1, 10000) AS gs; + +ANALYZE messages; + +\echo '=== FIRST PAGE ===' + +EXPLAIN (ANALYZE, BUFFERS) +SELECT id, chat_id, sender_id, text, created_at +FROM messages +WHERE chat_id = (SELECT chat_id FROM explain_ctx) +ORDER BY created_at ASC, id ASC +LIMIT 20; + +\echo '=== DEEP PAGE ===' + +EXPLAIN (ANALYZE, BUFFERS) +SELECT id, chat_id, sender_id, text, created_at +FROM messages +WHERE chat_id = (SELECT chat_id FROM explain_ctx) + AND (created_at, id) > ( + TIMESTAMPTZ '2026-01-01 02:00:00+00', + ( + SELECT id + FROM messages + WHERE chat_id = (SELECT chat_id FROM explain_ctx) + AND created_at = TIMESTAMPTZ '2026-01-01 02:00:00+00' + LIMIT 1 + ) + ) +ORDER BY created_at ASC, id ASC +LIMIT 20; + +ROLLBACK; diff --git a/scripts/failover-under-load.sh b/scripts/failover-under-load.sh new file mode 100755 index 0000000..7f4ebe8 --- /dev/null +++ b/scripts/failover-under-load.sh @@ -0,0 +1,20 @@ +#!/bin/sh +set -eu +mkdir -p evidence + +python3 tests/load.py --duration 30 --concurrency 4 \ + --output evidence/load-stop-api2.json > evidence/load-stop-api2.txt & +LOAD_PID=$! + +sleep 8 +date '+%T stop api-2' +docker stop -t 8 mtusi2026lab4-api-2 >/dev/null +docker compose ps > evidence/ps-during-failover.txt + +sleep 10 +date '+%T start api-2' +docker start mtusi2026lab4-api-2 >/dev/null + +wait "$LOAD_PID" +docker compose logs lb --since 3m > evidence/lb-failover.log +cat evidence/load-stop-api2.txt diff --git a/scripts/measure_failover.py b/scripts/measure_failover.py new file mode 100644 index 0000000..3658d6f --- /dev/null +++ b/scripts/measure_failover.py @@ -0,0 +1,91 @@ +import base64, json, subprocess, sys, threading, time, urllib.request, uuid +import os +BASE = os.environ.get("BASE", "http://localhost:8080"); PWD = "correct-horse-battery-staple" +WORKERS, DURATION, STOP_AT, START_AT = 4, 35, 8, 22 + + +def req(method, path, body=None, token=None, basic=None, key=None): + r = urllib.request.Request(BASE + path, method=method, + data=json.dumps(body).encode() if body is not None else None) + if body is not None: r.add_header("Content-Type", "application/json") + if token: r.add_header("Authorization", "Bearer " + token) + if basic: r.add_header("Authorization", "Basic " + base64.b64encode(basic.encode()).decode()) + if key: r.add_header("Idempotency-Key", key) + with urllib.request.urlopen(r, timeout=3) as resp: + return resp.status, resp.headers.get("X-Instance-Id"), json.loads(resp.read() or b"null") + + +def sh(*a): return subprocess.run(a, capture_output=True, text=True).stdout.split() +arg = sys.argv[1] +names = sorted(sh("docker", "ps", "--filter", "label=com.docker.compose.service=api", + "--format", "{{.Names}}")) +container = names[int(arg) - 1] if arg.isdigit() else arg +stopped_id = subprocess.run(["docker", "inspect", "-f", "{{.Config.Hostname}}", container], + capture_output=True, text=True).stdout.strip() +assert stopped_id, "container not found" +name = "fo_" + uuid.uuid4().hex[:10] +_, _, u = req("POST", "/api/v1/users", {"username": name, "display_name": "fo", "password": PWD}) +_, _, s = req("POST", "/api/v1/auth/sessions", basic=f"{name}:{PWD}") +tok = s["token"] +_, _, c = req("POST", "/api/v1/chats", {"title": "fo", "member_ids": [u["id"]]}, token=tok) +path = f"/api/v1/chats/{c['id']}/messages" + +t0 = time.time() +attempts, confirmed, unconfirmed = [], set(), 0 +lock = threading.Lock() + + +def action(): + time.sleep(STOP_AT) + subprocess.run(["docker", "stop", "-t", "8", container], capture_output=True) + time.sleep(max(0, START_AT - (time.time() - t0))) + subprocess.run(["docker", "start", container], capture_output=True) + + +def worker(): + global unconfirmed + while time.time() - t0 < DURATION: + key = uuid.uuid4().hex + done = False + for n in range(3): + ts = time.time() - t0 + try: + _, inst, m = req("POST", path, {"text": "x"}, token=tok, key=key) + with lock: + attempts.append((ts, True, inst, n)); confirmed.add(m["id"]) + done = True + break + except Exception: + with lock: attempts.append((ts, False, None, n)) + time.sleep(0.2) + if not done: + with lock: unconfirmed += 1 + + +threads = [threading.Thread(target=action)] + [threading.Thread(target=worker) for _ in range(WORKERS)] +[t.start() for t in threads]; [t.join() for t in threads] + +stored, cur = set(), None +while True: + _, _, page = req("GET", path + "?limit=100" + (f"&cursor={cur}" if cur else ""), token=tok) + stored |= {m["id"] for m in page["items"]} + cur = page["next_cursor"] + if not cur: break + +oks = sorted(a[0] for a in attempts if a[1]) +gap = max((b - a for a, b in zip(oks, oks[1:])), default=0) +first_fail = [a[0] - STOP_AT for a in attempts if not a[1] and a[3] == 0 and a[0] >= STOP_AT] +pre_stop_errors = sum(1 for a in attempts if not a[1] and a[3] == 0 and a[0] < STOP_AT) +rps = lambda a, b: round(sum(a <= t < b for t in oks) / (b - a), 1) +late = {a[2] for a in attempts if a[1] and STOP_AT + 6 < a[0] < START_AT} +print(json.dumps({ + "container": container, "stopped_instance": stopped_id, + "rps_before": rps(0, STOP_AT), "rps_during": rps(STOP_AT, START_AT), "rps_after": rps(START_AT, DURATION), + "first_attempt_errors": len(first_fail), + "error_window_s_after_stop": [round(min(first_fail), 2), round(max(first_fail), 2)] if first_fail else None, + "longest_gap_without_success_s": round(gap, 2), + "stopped_instance_seen_while_down": stopped_id in late, + "confirmed": len(confirmed), "unconfirmed_keys": unconfirmed, "stored": len(stored), + "lost_confirmed": len(confirmed - stored), + "stored_minus_confirmed": len(stored) - len(confirmed), +}, indent=2)) \ No newline at end of file diff --git a/scripts/restart.sh b/scripts/restart.sh new file mode 100755 index 0000000..ef623f1 --- /dev/null +++ b/scripts/restart.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +docker compose restart postgres redis +docker compose restart api lb \ No newline at end of file diff --git a/scripts/rolling-under-load.sh b/scripts/rolling-under-load.sh new file mode 100755 index 0000000..76988a5 --- /dev/null +++ b/scripts/rolling-under-load.sh @@ -0,0 +1,16 @@ +#!/bin/sh +set -eu +mkdir -p evidence +docker run --rm --network mtusi2026lab4_edge -v "$PWD":/w python:3.13-alpine \ + python /w/tests/load.py --base-url http://lb:8080 --duration 80 --concurrency 4 \ + --output /w/evidence/load-rolling.json > evidence/load-rolling.txt & +LOAD=$! +sleep 8 +date '+%T rolling start' +./scripts/rolling-update.sh +date '+%T rolling end' +wait "$LOAD" +docker compose ps > evidence/ps-after-rolling.txt +docker compose logs lb --since 4m > evidence/lb-rolling.log +for c in $(docker compose ps -q api); do docker exec "$c" printenv APP_VERSION; done +cat evidence/load-rolling.txt diff --git a/scripts/rolling-update.sh b/scripts/rolling-update.sh new file mode 100755 index 0000000..91d24bc --- /dev/null +++ b/scripts/rolling-update.sh @@ -0,0 +1,18 @@ +#!/bin/sh +set -eu +N=2 +export APP_VERSION="${APP_VERSION:-v$(date +%s)}" +wait_healthy() { + until [ "$(docker compose ps -q api | xargs docker inspect -f '{{.State.Health.Status}}' | grep -c '^healthy$')" = "$1" ]; do sleep 1; done +} +docker compose build api +for old in $(docker compose ps -q api); do + docker compose up -d --no-deps --no-recreate --scale api=$((N+1)) api + wait_healthy $((N+1)) + sleep 5 # LB: rise 2 + обновление DNS + echo "$(date +%T) replacing $(docker inspect -f '{{.Name}}' "$old")" + docker stop -t 20 "$old" >/dev/null + docker rm "$old" >/dev/null +done +wait_healthy $N +echo "$(date +%T) done, APP_VERSION=$APP_VERSION" diff --git a/scripts/stop-one.sh b/scripts/stop-one.sh new file mode 100755 index 0000000..daa80f1 --- /dev/null +++ b/scripts/stop-one.sh @@ -0,0 +1,13 @@ +#!/bin/sh +set -eu +: "${TARGET_INSTANCE_ID:?test provides target API instance alias}" + +cid="" +for id in $(docker compose ps -q api); do + host=$(docker inspect -f '{{.Config.Hostname}}' "$id") + if [ "$host" = "$TARGET_INSTANCE_ID" ]; then cid="$id"; break; fi +done +[ -n "$cid" ] || { echo "container for instance $TARGET_INSTANCE_ID not found" >&2; exit 1; } + +docker stop -t 8 "$cid" >/dev/null +echo "stopped $cid" >&2