From 083d0d80cc15e795b8cf7e4608ddc37e5ba54560 Mon Sep 17 00:00:00 2001 From: myDan Date: Fri, 20 Nov 2026 03:05:34 +0300 Subject: [PATCH] chore(solution): port lab3 sources --- .dockerignore | 11 + Dockerfile | 19 + Makefile | 20 +- cmd/server/main.go | 103 ++++++ compose.yaml | 136 ++++++++ go.mod | 21 ++ go.sum | 43 +++ infra/haproxy/haproxy.cfg | 30 ++ internal/config/config.go | 60 ++++ internal/domain/domain.go | 61 ++++ internal/domain/errors.go | 11 + internal/handler/auth.go | 53 +++ internal/handler/auth_test.go | 102 ++++++ internal/handler/chats.go | 104 ++++++ internal/handler/cursor.go | 34 ++ internal/handler/dto.go | 128 +++++++ internal/handler/errors.go | 55 +++ internal/handler/handler.go | 39 +++ internal/handler/handler_test.go | 324 ++++++++++++++++++ internal/handler/health.go | 32 ++ internal/handler/json.go | 86 +++++ internal/handler/messages.go | 57 +++ internal/handler/middleware.go | 122 +++++++ internal/handler/users.go | 25 ++ .../postgres/migrations/000001_init.down.sql | 4 + .../postgres/migrations/000001_init.up.sql | 32 ++ .../000002_message_idempotency.down.sql | 1 + .../000002_message_idempotency.up.sql | 9 + internal/repository/postgres/postgres_test.go | 103 ++++++ internal/repository/postgres/store.go | 275 +++++++++++++++ internal/repository/redis/sessions.go | 71 ++++ internal/router/router.go | 37 ++ internal/service/auth.go | 74 ++++ internal/service/chats.go | 81 +++++ internal/service/messages.go | 65 ++++ internal/service/password.go | 60 ++++ internal/service/ports.go | 36 ++ internal/service/users.go | 59 ++++ internal/service/validate.go | 31 ++ scripts/idempotency-race.py | 56 +++ scripts/init-secrets.sh | 18 + scripts/restart.sh | 8 + scripts/rolling-update.sh | 37 ++ scripts/stop-one.sh | 13 + 44 files changed, 2745 insertions(+), 1 deletion(-) create mode 100644 Dockerfile create mode 100644 cmd/server/main.go create mode 100644 compose.yaml create mode 100644 go.mod create mode 100644 go.sum create mode 100644 infra/haproxy/haproxy.cfg create mode 100644 internal/config/config.go create mode 100644 internal/domain/domain.go create mode 100644 internal/domain/errors.go create mode 100644 internal/handler/auth.go create mode 100644 internal/handler/auth_test.go create mode 100644 internal/handler/chats.go create mode 100644 internal/handler/cursor.go create mode 100644 internal/handler/dto.go create mode 100644 internal/handler/errors.go create mode 100644 internal/handler/handler.go create mode 100644 internal/handler/handler_test.go create mode 100644 internal/handler/health.go create mode 100644 internal/handler/json.go create mode 100644 internal/handler/messages.go create mode 100644 internal/handler/middleware.go create mode 100644 internal/handler/users.go create mode 100644 internal/repository/postgres/migrations/000001_init.down.sql create mode 100644 internal/repository/postgres/migrations/000001_init.up.sql create mode 100644 internal/repository/postgres/migrations/000002_message_idempotency.down.sql create mode 100644 internal/repository/postgres/migrations/000002_message_idempotency.up.sql create mode 100644 internal/repository/postgres/postgres_test.go create mode 100644 internal/repository/postgres/store.go create mode 100644 internal/repository/redis/sessions.go create mode 100644 internal/router/router.go create mode 100644 internal/service/auth.go create mode 100644 internal/service/chats.go create mode 100644 internal/service/messages.go create mode 100644 internal/service/password.go create mode 100644 internal/service/ports.go create mode 100644 internal/service/users.go create mode 100644 internal/service/validate.go create mode 100755 scripts/idempotency-race.py create mode 100755 scripts/init-secrets.sh create mode 100755 scripts/restart.sh create mode 100755 scripts/rolling-update.sh create mode 100755 scripts/stop-one.sh diff --git a/.dockerignore b/.dockerignore index bc16e55..11aa449 100644 --- a/.dockerignore +++ b/.dockerignore @@ -18,3 +18,14 @@ __pycache__ node_modules evidence .DS_Store +assets +contracts +examples +scripts +tests +*.md +Makefile +lab.json +requirements-dev.txt +Dockerfile* +.dockerignore diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..6de4dda --- /dev/null +++ b/Dockerfile @@ -0,0 +1,19 @@ +FROM golang:1.27.1-alpine3.24 AS build +WORKDIR /src +COPY go.mod go.sum ./ +RUN go mod download +COPY cmd ./cmd +COPY internal ./internal +RUN CGO_ENABLED=0 go build -trimpath -o /out/server ./cmd/server + +FROM alpine:3.24.1 +ARG BUILD_ID=dev +LABEL org.opencontainers.image.revision=$BUILD_ID +RUN adduser -D -H -u 10001 app +COPY --from=build /out/server /usr/local/bin/server +USER app +ENV APP_HOST=0.0.0.0 APP_PORT=8080 +EXPOSE 8080 +HEALTHCHECK --interval=10s --timeout=3s --start-period=5s --retries=3 \ + CMD wget -q -O /dev/null "http://127.0.0.1:${APP_PORT}/health/ready" || exit 1 +ENTRYPOINT ["/usr/local/bin/server"] diff --git a/Makefile b/Makefile index 5d86d17..1a60e77 100644 --- a/Makefile +++ b/Makefile @@ -2,12 +2,23 @@ PYTHON ?= python3 BASE_URL ?= http://localhost:8080 CA_FILE ?= ACTION_SCRIPT ?= +ENGINE ?= $(shell command -v podman >/dev/null 2>&1 && echo podman || echo docker) +COMPOSE ?= $(if $(filter podman,$(ENGINE)),podman-compose,docker compose) +TEST_DATABASE_URL ?= $(shell sed 's/@postgres:5432/@127.0.0.1:55432/' secrets/database_url 2>/dev/null) +TEST_REDIS_URL ?= redis://127.0.0.1:56379/0 TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",) -.PHONY: help check validate test load test-persistence test-failover +.PHONY: help up down check validate test load test-persistence test-failover test-idempotency test-go help: @echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes" + @echo "up/down: start/stop the stand, volumes kept; test-idempotency: one key in parallel via LB; test-go: Go tests against the running stand" + +up: + $(COMPOSE) up -d --build + +down: + $(COMPOSE) down check: $(PYTHON) scripts/check_contract.py @@ -28,3 +39,10 @@ test-persistence: test-failover: @test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable stop-one hook"; exit 2) $(PYTHON) tests/resilience.py --mode failover --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS) + +test-idempotency: + BASE_URL="$(BASE_URL)" $(PYTHON) scripts/idempotency-race.py + +test-go: + @TEST_DATABASE_URL="$(TEST_DATABASE_URL)" TEST_REDIS_URL="$(TEST_REDIS_URL)" go test -count=1 -v ./... + diff --git a/cmd/server/main.go b/cmd/server/main.go new file mode 100644 index 0000000..676f857 --- /dev/null +++ b/cmd/server/main.go @@ -0,0 +1,103 @@ +package main + +import ( + "context" + "errors" + "log/slog" + "net/http" + "os" + "os/signal" + "syscall" + "time" + + "messenger/internal/config" + "messenger/internal/handler" + "messenger/internal/repository/postgres" + "messenger/internal/repository/redis" + "messenger/internal/router" + "messenger/internal/service" +) + +const ( + drainDelay = 3 * time.Second + shutdownTimeout = 5 * time.Second +) + +func main() { + log := slog.New(slog.NewJSONHandler(os.Stdout, nil)) + if err := run(log); err != nil { + log.Error("server failed", "err", err) + os.Exit(1) + } +} + +func run(log *slog.Logger) error { + cfg, err := config.Load() + if err != nil { + return err + } + + instanceID, err := os.Hostname() + if err != nil { + return err + } + + pool, err := postgres.NewPool(context.Background(), cfg.DatabaseURL) + if err != nil { + return err + } + defer pool.Close() + store := postgres.New(pool) + + redisClient, err := redis.NewClient(cfg.CacheURL) + if err != nil { + return err + } + defer redisClient.Close() + sessions := redis.NewSessionStore(redisClient) + + users := service.NewUserService(store) + auth := service.NewAuthService(store, sessions, cfg.SessionTTL) + chats := service.NewChatService(store) + messages := service.NewMessageService(chats, store) + deps := []handler.Pinger{store.Ping, sessions.Ping} + + h := handler.New(users, auth, chats, messages, deps, log) + srv := &http.Server{ + Addr: cfg.Addr(), + Handler: router.New(h, instanceID), + ReadHeaderTimeout: 5 * time.Second, + ReadTimeout: 15 * time.Second, + WriteTimeout: 15 * time.Second, + IdleTimeout: 60 * time.Second, + } + + ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, os.Interrupt) + defer stop() + + errCh := make(chan error, 1) + go func() { + log.Info("starting server", "addr", srv.Addr, "instance_id", instanceID, "env", cfg.Env, "session_ttl", cfg.SessionTTL.String()) + if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) { + errCh <- err + } + }() + + select { + case err := <-errCh: + return err + case <-ctx.Done(): + } + log.Info("shutdown signal received, draining", "drain", drainDelay.String(), "timeout", shutdownTimeout.String()) + h.StartDraining() + srv.SetKeepAlivesEnabled(false) + time.Sleep(drainDelay) + + shutdownCtx, cancel := context.WithTimeout(context.Background(), shutdownTimeout) + defer cancel() + if err := srv.Shutdown(shutdownCtx); err != nil { + return err + } + log.Info("server stopped") + return nil +} diff --git a/compose.yaml b/compose.yaml new file mode 100644 index 0000000..95ece40 --- /dev/null +++ b/compose.yaml @@ -0,0 +1,136 @@ +name: messenger-lab3 + +services: + postgres: + image: docker.io/library/postgres:18.6-alpine3.24 + environment: + POSTGRES_USER: messenger + POSTGRES_DB: messenger + POSTGRES_PASSWORD_FILE: /run/secrets/postgres_password + secrets: + - postgres_password + volumes: + - pgdata:/var/lib/postgresql + networks: + - backend + ports: + - "127.0.0.1:55432:5432" + healthcheck: + test: ["CMD-SHELL", "pg_isready -U messenger -d messenger"] + interval: 2s + timeout: 3s + retries: 30 + deploy: + resources: + limits: + cpus: "1.0" + memory: 512M + restart: unless-stopped + + redis: + image: docker.io/library/redis:8.10.3-alpine3.23 + command: ["redis-server", "--appendonly", "yes", "--appendfsync", "everysec"] + volumes: + - redisdata:/data + networks: + - backend + ports: + - "127.0.0.1:56379:6379" + healthcheck: + test: ["CMD", "redis-cli", "ping"] + interval: 2s + timeout: 3s + retries: 30 + deploy: + resources: + limits: + cpus: "0.5" + memory: 128M + restart: unless-stopped + + migrate: + image: docker.io/migrate/migrate:v4.20.1 + entrypoint: ["/bin/sh", "-c"] + command: ['migrate -path /migrations -database "$$(cat /run/secrets/database_url)" up'] + secrets: + - database_url + volumes: + - ./internal/repository/postgres/migrations:/migrations:ro + networks: + - backend + depends_on: + postgres: + condition: service_healthy + deploy: + resources: + limits: + cpus: "0.5" + memory: 64M + restart: "no" + + api: + build: . + image: localhost/messenger-api:lab3 + environment: + APP_HOST: 0.0.0.0 + APP_PORT: "8080" + APP_ENV: ${APP_ENV:-lab} + SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600} + DATABASE_URL_FILE: /run/secrets/database_url + CACHE_URL_FILE: /run/secrets/cache_url + secrets: + - database_url + - cache_url + networks: + - edge + - backend + healthcheck: + test: ["CMD", "wget", "-q", "-O", "/dev/null", "http://127.0.0.1:8080/health/ready"] + interval: 5s + timeout: 2s + retries: 3 + start_period: 5s + stop_grace_period: 10s + scale: ${API_REPLICAS:-2} + deploy: + resources: + limits: + cpus: "1.0" + memory: 256M + depends_on: + migrate: + condition: service_completed_successfully + redis: + condition: service_healthy + restart: unless-stopped + + lb: + image: docker.io/library/haproxy:3.4.7-alpine + volumes: + - ./infra/haproxy/haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro + networks: + - edge + ports: + - "8080:8080" + deploy: + resources: + limits: + cpus: "0.5" + memory: 64M + restart: unless-stopped + +networks: + edge: + backend: + +secrets: + postgres_password: + file: ./secrets/postgres_password + database_url: + file: ./secrets/database_url + cache_url: + file: ./secrets/cache_url + +volumes: + pgdata: + redisdata: diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..2236f1b --- /dev/null +++ b/go.mod @@ -0,0 +1,21 @@ +module messenger + +go 1.27.1 + +require ( + github.com/go-chi/chi/v5 v5.3.2 + github.com/jackc/pgx/v5 v5.11.0 + github.com/redis/go-redis/v9 v9.23.0 + golang.org/x/crypto v0.58.0 +) + +require ( + github.com/cespare/xxhash/v2 v2.3.0 // indirect + github.com/jackc/pgpassfile v1.0.0 // indirect + github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect + github.com/jackc/puddle/v2 v2.2.2 // indirect + go.uber.org/atomic v1.12.0 // indirect + golang.org/x/sync v0.24.0 // indirect + golang.org/x/sys v0.49.0 // indirect + golang.org/x/text v0.43.0 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..0255591 --- /dev/null +++ b/go.sum @@ -0,0 +1,43 @@ +github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs= +github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c= +github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA= +github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0= +github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= +github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/go-chi/chi/v5 v5.3.2 h1:5YQkICvTCSZ25hoRsyJazN0scjzKGiu4VAUc7H1o1nY= +github.com/go-chi/chi/v5 v5.3.2/go.mod h1:R+tYY2hNuVUUjxoPtqUdgBqevM9s9njzkTLutVsOCto= +github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= +github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg= +github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo= +github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM= +github.com/jackc/pgx/v5 v5.11.0 h1:IzBBtyK9AHqf98cctWFifYSci2hgQR/cd56wB4p+ogg= +github.com/jackc/pgx/v5 v5.11.0/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4= +github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo= +github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= +github.com/klauspost/cpuid/v2 v2.4.0 h1:S6Hrbc7+ywsr0r+RLapfGBHfyefhCTwEh3A0tV913Dw= +github.com/klauspost/cpuid/v2 v2.4.0/go.mod h1:19jmZ9mjzoF//ddRSUsv0zfBTJWh3QJh9FNxZTMrGxU= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/redis/go-redis/v9 v9.23.0 h1:/TTVdJa8BRNsybwwGGnmiYktHNlUXtbOQxlWpHBPL3s= +github.com/redis/go-redis/v9 v9.23.0/go.mod h1:EWP2UUk+XDaI1s5nQB5mablZN6vccXlmBQTyfnF87D0= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE= +github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg= +github.com/zeebo/xxh3 v1.1.0 h1:s7DLGDK45Dyfg7++yxI0khrfwq9661w9EN78eP/UZVs= +github.com/zeebo/xxh3 v1.1.0/go.mod h1:IisAie1LELR4xhVinxWS5+zf1lA4p0MW4T+w+W07F5s= +go.uber.org/atomic v1.12.0 h1:BvcXdFKuviU4fTL/f+SxdQ5qJX/Jix8pAkgdUcb3XOE= +go.uber.org/atomic v1.12.0/go.mod h1:I6c4cg+6HCxRjfjSsYtApoFILnpc0CGUdGkXVqbYVNk= +go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw= +go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg= +golang.org/x/crypto v0.58.0 h1:COkYLr4k7nDI4r6QtMML2AfzeIswWHAJthLS6K/M/54= +golang.org/x/crypto v0.58.0/go.mod h1:Xh+kl5A+M0gMiWDytH2Hhr5Z7WbNCpv/eB/EFgfSk+w= +golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA= +golang.org/x/sync v0.24.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= +golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA= +golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= +golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc= +golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/infra/haproxy/haproxy.cfg b/infra/haproxy/haproxy.cfg new file mode 100644 index 0000000..d31efa8 --- /dev/null +++ b/infra/haproxy/haproxy.cfg @@ -0,0 +1,30 @@ +global + log stdout format raw local0 info + maxconn 2000 + +defaults + mode http + log global + option httplog + timeout connect 2s + timeout client 30s + timeout server 20s + timeout http-request 10s + timeout check 1s + retries 3 + option redispatch + +resolvers dns + parse-resolv-conf + hold valid 1s + +frontend public + bind :8080 + default_backend api + +backend api + balance roundrobin + option httpchk GET /health/ready + http-check expect status 200 + default-server check inter 1s fall 2 rise 2 resolvers dns init-addr none + server-template api 4 api:8080 diff --git a/internal/config/config.go b/internal/config/config.go new file mode 100644 index 0000000..29a8b74 --- /dev/null +++ b/internal/config/config.go @@ -0,0 +1,60 @@ +package config + +import ( + "fmt" + "net" + "os" + "strconv" + "strings" + "time" +) + +type Config struct { + Host string + Port string + Env string + SessionTTL time.Duration + DatabaseURL string + CacheURL string +} + +func Load() (Config, error) { + ttl, err := strconv.Atoi(getenv("SESSION_TTL_SECONDS", "3600")) + if err != nil || ttl <= 0 { + return Config{}, fmt.Errorf("SESSION_TTL_SECONDS must be a positive integer") + } + databaseURL, err := readSecret("DATABASE_URL_FILE", "/run/secrets/database_url") + if err != nil { + return Config{}, err + } + cacheURL, err := readSecret("CACHE_URL_FILE", "/run/secrets/cache_url") + if err != nil { + return Config{}, err + } + return Config{ + Host: getenv("APP_HOST", "0.0.0.0"), + Port: getenv("APP_PORT", "8080"), + Env: getenv("APP_ENV", "lab"), + SessionTTL: time.Duration(ttl) * time.Second, + DatabaseURL: databaseURL, + CacheURL: cacheURL, + }, nil +} + +func (c Config) Addr() string { return net.JoinHostPort(c.Host, c.Port) } + +func readSecret(key, def string) (string, error) { + path := getenv(key, def) + b, err := os.ReadFile(path) + if err != nil { + return "", fmt.Errorf("%s: cannot read %s", key, path) + } + return strings.TrimSpace(string(b)), nil +} + +func getenv(key, def string) string { + if v := os.Getenv(key); v != "" { + return v + } + return def +} diff --git a/internal/domain/domain.go b/internal/domain/domain.go new file mode 100644 index 0000000..f1036b7 --- /dev/null +++ b/internal/domain/domain.go @@ -0,0 +1,61 @@ +package domain + +import ( + "time" + "uuid" +) + +type User struct { + ID uuid.UUID + Username string + DisplayName string + CreatedAt time.Time +} + +type Chat struct { + ID uuid.UUID + Title string + MemberIDs []uuid.UUID + CreatedAt time.Time +} + +func (c Chat) HasMember(userID uuid.UUID) bool { + for _, id := range c.MemberIDs { + if id == userID { + return true + } + } + return false +} + +type Message struct { + ID uuid.UUID + ChatID uuid.UUID + SenderID uuid.UUID + Text string + CreatedAt time.Time +} + +type Session struct { + Token string + ExpiresAt time.Time + User User +} + +type Cursor struct { + Scope uuid.UUID + CreatedAt time.Time + ID uuid.UUID +} + +func CompareKey(aTime time.Time, aID uuid.UUID, bTime time.Time, bID uuid.UUID) int { + if c := aTime.Compare(bTime); c != 0 { + return c + } + return aID.Compare(bID) +} + +type Page[T any] struct { + Items []T + Next *Cursor +} diff --git a/internal/domain/errors.go b/internal/domain/errors.go new file mode 100644 index 0000000..b4adb60 --- /dev/null +++ b/internal/domain/errors.go @@ -0,0 +1,11 @@ +package domain + +import "errors" + +var ( + ErrInvalidInput = errors.New("invalid input") + ErrUnauthorized = errors.New("unauthorized") + ErrNotFound = errors.New("not found") + ErrConflict = errors.New("conflict") + ErrUnavailable = errors.New("dependency unavailable") +) diff --git a/internal/handler/auth.go b/internal/handler/auth.go new file mode 100644 index 0000000..cea44f6 --- /dev/null +++ b/internal/handler/auth.go @@ -0,0 +1,53 @@ +package handler + +import ( + "encoding/base64" + "errors" + "net/http" + "strings" + "unicode/utf8" + + "messenger/internal/domain" +) + +func (h *Handler) CreateSession(w http.ResponseWriter, r *http.Request) { + username, password, ok := basicCredentials(r) + if !ok { + h.failLogin(w, r, domain.ErrUnauthorized) + return + } + session, err := h.auth.Login(r.Context(), username, password) + if err != nil { + h.failLogin(w, r, err) + return + } + writeJSON(w, http.StatusCreated, toSessionResponse(session)) +} + +func (h *Handler) failLogin(w http.ResponseWriter, r *http.Request, err error) { + if errors.Is(err, domain.ErrUnauthorized) { + w.Header().Set(headerWWWAuthenticate, basicChallenge) + } + h.fail(w, r, err) +} + +func (h *Handler) DeleteSession(w http.ResponseWriter, r *http.Request) { + if err := h.auth.Logout(r.Context(), current(r).token); err != nil { + h.fail(w, r, err) + return + } + w.WriteHeader(http.StatusNoContent) +} + +func basicCredentials(r *http.Request) (string, string, bool) { + encoded, ok := authCredentials(r, "Basic") + if !ok { + return "", "", false + } + raw, err := base64.StdEncoding.DecodeString(encoded) + if err != nil || !utf8.Valid(raw) { + return "", "", false + } + username, password, ok := strings.Cut(string(raw), ":") + return username, password, ok +} diff --git a/internal/handler/auth_test.go b/internal/handler/auth_test.go new file mode 100644 index 0000000..9fb027b --- /dev/null +++ b/internal/handler/auth_test.go @@ -0,0 +1,102 @@ +package handler_test + +import ( + "net/http" + "strings" + "testing" + "time" +) + +const ( + deadDatabaseURL = "postgres://messenger:x@127.0.0.1:1/messenger?sslmode=disable" + deadRedisURL = "redis://127.0.0.1:1/0" +) + +func TestSessionExpiry(t *testing.T) { + dbURL, redisURL := testURLs(t) + srv := newStack(t, dbURL, redisURL, 2*time.Second) + alice := createUser(t, srv, "alice") + + if status, _ := do(t, srv, http.MethodGet, "/api/v1/users/me", alice.Token, ""); status != http.StatusOK { + t.Fatalf("fresh session: got %d, want 200", status) + } + time.Sleep(3 * time.Second) + resp := request(t, srv, http.MethodGet, "/api/v1/users/me", alice.Token, "") + resp.Body.Close() + if resp.StatusCode != http.StatusUnauthorized { + t.Fatalf("expired session: got %d, want 401", resp.StatusCode) + } + if got := resp.Header.Get("WWW-Authenticate"); !strings.HasPrefix(got, "Bearer") { + t.Errorf("WWW-Authenticate = %q, want Bearer challenge", got) + } +} + +func TestLogout(t *testing.T) { + srv := newServer(t) + alice := createUser(t, srv, "alice") + + resp := request(t, srv, http.MethodDelete, "/api/v1/auth/sessions/current", alice.Token, "") + resp.Body.Close() + if resp.StatusCode != http.StatusNoContent { + t.Fatalf("logout: got %d, want 204", resp.StatusCode) + } + if status, _ := do(t, srv, http.MethodGet, "/api/v1/users/me", alice.Token, ""); status != http.StatusUnauthorized { + t.Errorf("revoked token on /users/me: got %d, want 401", status) + } + if status, _ := do(t, srv, http.MethodDelete, "/api/v1/auth/sessions/current", alice.Token, ""); status != http.StatusUnauthorized { + t.Errorf("repeated logout: got %d, want 401", status) + } +} + +func TestWrongPassword(t *testing.T) { + srv := newServer(t) + alice := createUser(t, srv, "alice") + + for name, password := range map[string]string{"wrong password": "Wrong-password-123", "unknown user": alice.Password} { + username := alice.Username + if name == "unknown user" { + username = "nobody_" + alice.Username[:10] + } + resp := login(t, srv, username, password) + resp.Body.Close() + if resp.StatusCode != http.StatusUnauthorized { + t.Errorf("%s: got %d, want 401", name, resp.StatusCode) + } + if got := resp.Header.Get("WWW-Authenticate"); got != `Basic realm="messenger", charset="UTF-8"` { + t.Errorf("%s: WWW-Authenticate = %q", name, got) + } + } +} + +func TestRedisUnavailable(t *testing.T) { + dbURL, _ := testURLs(t) + srv := newStack(t, dbURL, deadRedisURL, time.Hour) + + if status, body := do(t, srv, http.MethodGet, "/api/v1/users/me", "some-token-from-before-the-outage", ""); status != http.StatusServiceUnavailable || errorCode(body) != "unavailable" { + t.Errorf("bearer request: got %d %q, want 503 unavailable", status, errorCode(body)) + } + if status, _ := do(t, srv, http.MethodGet, "/api/v1/users/me", "", ""); status != http.StatusUnauthorized { + t.Errorf("anonymous request: got %d, want 401", status) + } + if status, _ := do(t, srv, http.MethodGet, "/health/ready", "", ""); status != http.StatusServiceUnavailable { + t.Errorf("ready: got %d, want 503", status) + } +} + +func TestDatabaseUnavailable(t *testing.T) { + dbURL, redisURL := testURLs(t) + healthy := newStack(t, dbURL, redisURL, time.Hour) + alice := createUser(t, healthy, "alice") + + srv := newStack(t, deadDatabaseURL, redisURL, time.Hour) + if status, body := do(t, srv, http.MethodGet, "/api/v1/users/me", alice.Token, ""); status != http.StatusServiceUnavailable || errorCode(body) != "unavailable" { + t.Errorf("valid session: got %d %q, want 503 unavailable", status, errorCode(body)) + } + if status, _ := do(t, srv, http.MethodPost, "/api/v1/users", "", + `{"username":"db_down_user","display_name":"X","password":"long-enough-pass"}`); status != http.StatusServiceUnavailable { + t.Errorf("register: got %d, want 503", status) + } + if status, _ := do(t, srv, http.MethodGet, "/health/ready", "", ""); status != http.StatusServiceUnavailable { + t.Errorf("ready: got %d, want 503", status) + } +} diff --git a/internal/handler/chats.go b/internal/handler/chats.go new file mode 100644 index 0000000..c655ab0 --- /dev/null +++ b/internal/handler/chats.go @@ -0,0 +1,104 @@ +package handler + +import ( + "net/http" + "strconv" + "uuid" + + "github.com/go-chi/chi/v5" + + "messenger/internal/domain" + "messenger/internal/service" +) + +func (h *Handler) CreateChat(w http.ResponseWriter, r *http.Request) { + var req createChatRequest + if err := decodeJSON(w, r, &req); err != nil { + h.fail(w, r, err) + return + } + if req.Title == nil || req.MemberIDs == nil { + h.fail(w, r, badRequest("title and member_ids are required")) + return + } + memberIDs := make([]uuid.UUID, len(*req.MemberIDs)) + for i, s := range *req.MemberIDs { + id, ok := parseUUID(s) + if !ok { + h.fail(w, r, badRequest("member_ids must contain UUIDs")) + return + } + memberIDs[i] = id + } + chat, err := h.chats.Create(r.Context(), actor(r), *req.Title, memberIDs) + if err != nil { + h.fail(w, r, err) + return + } + writeJSON(w, http.StatusCreated, toChatResponse(chat)) +} + +func (h *Handler) ListChats(w http.ResponseWriter, r *http.Request) { + limit, cursor, err := pageParams(r) + if err != nil { + h.fail(w, r, err) + return + } + page, err := h.chats.List(r.Context(), actor(r), cursor, limit) + if err != nil { + h.fail(w, r, err) + return + } + writeJSON(w, http.StatusOK, toPageResponse(page, toChatResponse)) +} + +func (h *Handler) GetChat(w http.ResponseWriter, r *http.Request) { + chatID, err := chatIDParam(r) + if err != nil { + h.fail(w, r, err) + return + } + chat, err := h.chats.Get(r.Context(), actor(r), chatID) + if err != nil { + h.fail(w, r, err) + return + } + writeJSON(w, http.StatusOK, toChatResponse(chat)) +} + +func chatIDParam(r *http.Request) (uuid.UUID, error) { + id, ok := parseUUID(chi.URLParam(r, "chat_id")) + if !ok { + return uuid.UUID{}, badRequest("chat_id must be a UUID") + } + return id, nil +} + +func parseUUID(s string) (uuid.UUID, bool) { + if len(s) != 36 { + return uuid.UUID{}, false + } + id, err := uuid.Parse(s) + return id, err == nil +} + +func pageParams(r *http.Request) (int, *domain.Cursor, error) { + q := r.URL.Query() + limit := service.DefaultLimit + if q.Has("limit") { + n, err := strconv.Atoi(q.Get("limit")) + if err != nil { + return 0, nil, badRequest("limit must be an integer") + } + limit = n + } + var cursor *domain.Cursor + if q.Has("cursor") { + c, ok := decodeCursor(q.Get("cursor")) + if !ok { + return 0, nil, badRequest("invalid cursor") + } + cursor = &c + } + return limit, cursor, nil +} diff --git a/internal/handler/cursor.go b/internal/handler/cursor.go new file mode 100644 index 0000000..94c3f7f --- /dev/null +++ b/internal/handler/cursor.go @@ -0,0 +1,34 @@ +package handler + +import ( + "encoding/base64" + "strconv" + "strings" + "time" + "uuid" + + "messenger/internal/domain" +) + +func encodeCursor(c domain.Cursor) string { + raw := c.Scope.String() + "." + strconv.FormatInt(c.CreatedAt.UnixMicro(), 10) + "." + c.ID.String() + return base64.RawURLEncoding.EncodeToString([]byte(raw)) +} + +func decodeCursor(s string) (domain.Cursor, bool) { + raw, err := base64.RawURLEncoding.DecodeString(s) + if err != nil { + return domain.Cursor{}, false + } + parts := strings.Split(string(raw), ".") + if len(parts) != 3 { + return domain.Cursor{}, false + } + scope, err1 := uuid.Parse(parts[0]) + micros, err2 := strconv.ParseInt(parts[1], 10, 64) + id, err3 := uuid.Parse(parts[2]) + if err1 != nil || err2 != nil || err3 != nil { + return domain.Cursor{}, false + } + return domain.Cursor{Scope: scope, CreatedAt: time.UnixMicro(micros).UTC(), ID: id}, true +} diff --git a/internal/handler/dto.go b/internal/handler/dto.go new file mode 100644 index 0000000..2bacc08 --- /dev/null +++ b/internal/handler/dto.go @@ -0,0 +1,128 @@ +package handler + +import ( + "time" + + "messenger/internal/domain" +) + +type createUserRequest struct { + Username *string `json:"username"` + DisplayName *string `json:"display_name"` + Password *string `json:"password"` +} + +type createChatRequest struct { + Title *string `json:"title"` + MemberIDs *[]string `json:"member_ids"` +} + +type createMessageRequest struct { + Text *string `json:"text"` +} + +type userResponse struct { + ID string `json:"id"` + Username string `json:"username"` + DisplayName string `json:"display_name"` + CreatedAt string `json:"created_at"` +} + +type chatResponse struct { + ID string `json:"id"` + Title string `json:"title"` + MemberIDs []string `json:"member_ids"` + CreatedAt string `json:"created_at"` +} + +type messageResponse struct { + ID string `json:"id"` + ChatID string `json:"chat_id"` + SenderID string `json:"sender_id"` + Text string `json:"text"` + CreatedAt string `json:"created_at"` +} + +type pageResponse[T any] struct { + Items []T `json:"items"` + NextCursor *string `json:"next_cursor"` +} + +type sessionResponse struct { + Token string `json:"token"` + TokenType string `json:"token_type"` + ExpiresAt string `json:"expires_at"` + User userResponse `json:"user"` +} + +type healthResponse struct { + Status string `json:"status"` +} + +type errorBody struct { + Error errorDetails `json:"error"` +} + +type errorDetails struct { + Code string `json:"code"` + Message string `json:"message"` + RequestID string `json:"request_id"` +} + +const timeLayout = "2006-01-02T15:04:05.000000Z" + +func formatTime(t time.Time) string { return t.UTC().Format(timeLayout) } + +func toUserResponse(u domain.User) userResponse { + return userResponse{ + ID: u.ID.String(), + Username: u.Username, + DisplayName: u.DisplayName, + CreatedAt: formatTime(u.CreatedAt), + } +} + +func toSessionResponse(s domain.Session) sessionResponse { + return sessionResponse{ + Token: s.Token, + TokenType: "Bearer", + ExpiresAt: formatTime(s.ExpiresAt), + User: toUserResponse(s.User), + } +} + +func toChatResponse(c domain.Chat) chatResponse { + members := make([]string, len(c.MemberIDs)) + for i, id := range c.MemberIDs { + members[i] = id.String() + } + return chatResponse{ + ID: c.ID.String(), + Title: c.Title, + MemberIDs: members, + CreatedAt: formatTime(c.CreatedAt), + } +} + +func toMessageResponse(m domain.Message) messageResponse { + return messageResponse{ + ID: m.ID.String(), + ChatID: m.ChatID.String(), + SenderID: m.SenderID.String(), + Text: m.Text, + CreatedAt: formatTime(m.CreatedAt), + } +} + +func toPageResponse[D, R any](p domain.Page[D], conv func(D) R) pageResponse[R] { + items := make([]R, len(p.Items)) + for i, it := range p.Items { + items[i] = conv(it) + } + resp := pageResponse[R]{Items: items} + if p.Next != nil { + s := encodeCursor(*p.Next) + resp.NextCursor = &s + } + return resp +} diff --git a/internal/handler/errors.go b/internal/handler/errors.go new file mode 100644 index 0000000..ca7e45b --- /dev/null +++ b/internal/handler/errors.go @@ -0,0 +1,55 @@ +package handler + +import ( + "errors" + "net/http" + + "messenger/internal/domain" +) + +type apiError struct { + status int + code string + message string +} + +func (e *apiError) Error() string { return e.message } + +func badRequest(msg string) *apiError { + return &apiError{http.StatusBadRequest, "invalid_request", msg} +} + +func writeError(w http.ResponseWriter, status int, code, message string) { + writeJSON(w, status, errorBody{Error: errorDetails{ + Code: code, + Message: message, + RequestID: w.Header().Get(headerRequestID), + }}) +} + +func (h *Handler) fail(w http.ResponseWriter, r *http.Request, err error) { + var ae *apiError + switch { + case errors.As(err, &ae): + writeError(w, ae.status, ae.code, ae.message) + case errors.Is(err, domain.ErrInvalidInput): + writeError(w, http.StatusBadRequest, "invalid_request", err.Error()) + case errors.Is(err, domain.ErrUnauthorized): + if w.Header().Get(headerWWWAuthenticate) == "" { + w.Header().Set(headerWWWAuthenticate, bearerChallenge) + } + writeError(w, http.StatusUnauthorized, "unauthorized", "valid authentication is required") + case errors.Is(err, domain.ErrNotFound): + writeError(w, http.StatusNotFound, "not_found", "resource not found") + case errors.Is(err, domain.ErrConflict): + writeError(w, http.StatusConflict, "conflict", err.Error()) + case errors.Is(err, domain.ErrUnavailable): + h.log.Error("dependency unavailable", "request_id", w.Header().Get(headerRequestID), + "method", r.Method, "path", r.URL.Path, "err", err) + writeError(w, http.StatusServiceUnavailable, "unavailable", "service temporarily unavailable") + default: + h.log.Error("unexpected error", "request_id", w.Header().Get(headerRequestID), + "method", r.Method, "path", r.URL.Path, "err", err) + writeError(w, http.StatusInternalServerError, "internal_error", "internal server error") + } +} diff --git a/internal/handler/handler.go b/internal/handler/handler.go new file mode 100644 index 0000000..818d35c --- /dev/null +++ b/internal/handler/handler.go @@ -0,0 +1,39 @@ +package handler + +import ( + "context" + "log/slog" + "net/http" + "sync/atomic" + + "messenger/internal/service" +) + +type Pinger func(ctx context.Context) error + +type Handler struct { + users *service.UserService + auth *service.AuthService + chats *service.ChatService + messages *service.MessageService + deps []Pinger + log *slog.Logger + draining atomic.Bool +} + +func New(users *service.UserService, auth *service.AuthService, chats *service.ChatService, + messages *service.MessageService, deps []Pinger, log *slog.Logger) *Handler { + return &Handler{users: users, auth: auth, chats: chats, messages: messages, deps: deps, log: log} +} + +func (h *Handler) StartDraining() { + h.draining.Store(true) +} + +func (h *Handler) NotFound(w http.ResponseWriter, _ *http.Request) { + writeError(w, http.StatusNotFound, "not_found", "resource not found") +} + +func (h *Handler) MethodNotAllowed(w http.ResponseWriter, _ *http.Request) { + writeError(w, http.StatusMethodNotAllowed, "invalid_request", "method not allowed") +} diff --git a/internal/handler/handler_test.go b/internal/handler/handler_test.go new file mode 100644 index 0000000..2d378ee --- /dev/null +++ b/internal/handler/handler_test.go @@ -0,0 +1,324 @@ +package handler_test + +import ( + "context" + "encoding/base64" + "encoding/json" + "fmt" + "log/slog" + "net/http" + "net/http/httptest" + "os" + "strings" + "sync" + "testing" + "time" + "uuid" + + "messenger/internal/handler" + "messenger/internal/repository/postgres" + "messenger/internal/repository/redis" + "messenger/internal/router" + "messenger/internal/service" +) + +func testURLs(t *testing.T) (string, string) { + t.Helper() + dbURL, redisURL := os.Getenv("TEST_DATABASE_URL"), os.Getenv("TEST_REDIS_URL") + if dbURL == "" || redisURL == "" { + t.Skip("TEST_DATABASE_URL and TEST_REDIS_URL are required") + } + return dbURL, redisURL +} + +func newServer(t *testing.T) *httptest.Server { + t.Helper() + dbURL, redisURL := testURLs(t) + return newStack(t, dbURL, redisURL, time.Hour) +} + +func newStack(t *testing.T, dbURL, redisURL string, ttl time.Duration) *httptest.Server { + t.Helper() + pool, err := postgres.NewPool(context.Background(), dbURL) + if err != nil { + t.Fatal(err) + } + t.Cleanup(pool.Close) + store := postgres.New(pool) + client, err := redis.NewClient(redisURL) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { client.Close() }) + sessions := redis.NewSessionStore(client) + + users := service.NewUserService(store) + auth := service.NewAuthService(store, sessions, ttl) + chats := service.NewChatService(store) + messages := service.NewMessageService(chats, store) + h := handler.New(users, auth, chats, messages, []handler.Pinger{store.Ping, sessions.Ping}, slog.New(slog.DiscardHandler)) + srv := httptest.NewServer(router.New(h, "test")) + t.Cleanup(srv.Close) + return srv +} + +type testUser struct { + ID string + Username string + Password string + Token string +} + +func request(t *testing.T, srv *httptest.Server, method, path, token, body string) *http.Response { + t.Helper() + req, err := http.NewRequest(method, srv.URL+path, strings.NewReader(body)) + if err != nil { + t.Fatal(err) + } + if body != "" { + req.Header.Set("Content-Type", "application/json") + } + if token != "" { + req.Header.Set("Authorization", "Bearer "+token) + } + if method == http.MethodPost && strings.HasSuffix(path, "/messages") { + req.Header.Set("Idempotency-Key", uuid.New().String()) + } + resp, err := srv.Client().Do(req) + if err != nil { + t.Fatal(err) + } + return resp +} + +func do(t *testing.T, srv *httptest.Server, method, path, token, body string) (int, map[string]any) { + t.Helper() + resp := request(t, srv, method, path, token, body) + defer resp.Body.Close() + var out map[string]any + if err := json.NewDecoder(resp.Body).Decode(&out); err != nil { + t.Fatalf("%s %s: invalid JSON response: %v", method, path, err) + } + return resp.StatusCode, out +} + +func errorCode(body map[string]any) string { + e, _ := body["error"].(map[string]any) + code, _ := e["code"].(string) + return code +} + +func basic(username, password string) string { + return "Basic " + base64.StdEncoding.EncodeToString([]byte(username+":"+password)) +} + +func login(t *testing.T, srv *httptest.Server, username, password string) *http.Response { + t.Helper() + req, err := http.NewRequest(http.MethodPost, srv.URL+"/api/v1/auth/sessions", nil) + if err != nil { + t.Fatal(err) + } + req.Header.Set("Authorization", basic(username, password)) + resp, err := srv.Client().Do(req) + if err != nil { + t.Fatal(err) + } + return resp +} + +func createUser(t *testing.T, srv *httptest.Server, label string) testUser { + t.Helper() + u := testUser{ + Username: label + "_" + strings.ReplaceAll(uuid.New().String(), "-", "")[:12], + Password: "Test-password-" + label, + } + status, body := do(t, srv, http.MethodPost, "/api/v1/users", "", + fmt.Sprintf(`{"username":%q,"display_name":"Test","password":%q}`, u.Username, u.Password)) + if status != http.StatusCreated { + t.Fatalf("create user %s: status %d", u.Username, status) + } + u.ID = body["id"].(string) + + resp := login(t, srv, u.Username, u.Password) + defer resp.Body.Close() + var session map[string]any + if err := json.NewDecoder(resp.Body).Decode(&session); err != nil || resp.StatusCode != http.StatusCreated { + t.Fatalf("login %s: status %d", u.Username, resp.StatusCode) + } + u.Token = session["token"].(string) + return u +} + +func createChat(t *testing.T, srv *httptest.Server, owner testUser, members ...testUser) string { + t.Helper() + ids := make([]string, len(members)) + for i, m := range members { + ids[i] = m.ID + } + raw, _ := json.Marshal(ids) + status, body := do(t, srv, http.MethodPost, "/api/v1/chats", owner.Token, + fmt.Sprintf(`{"title":"Test","member_ids":%s}`, raw)) + if status != http.StatusCreated { + t.Fatalf("create chat: status %d", status) + } + return body["id"].(string) +} + +func TestInvalidJSON(t *testing.T) { + srv := newServer(t) + for _, body := range []string{`{"username":`, `not json`, `{"username":5,"display_name":"x","password":"long-enough-pass"}`} { + status, resp := do(t, srv, http.MethodPost, "/api/v1/users", "", body) + if status != http.StatusBadRequest || errorCode(resp) != "invalid_request" { + t.Errorf("body %q: got %d %q, want 400 invalid_request", body, status, errorCode(resp)) + } + } +} + +func TestForeignChat(t *testing.T) { + srv := newServer(t) + alice := createUser(t, srv, "alice") + bob := createUser(t, srv, "bob") + eve := createUser(t, srv, "eve") + chat := createChat(t, srv, alice, alice, bob) + + cases := []struct{ method, path, body string }{ + {http.MethodGet, "/api/v1/chats/" + chat, ""}, + {http.MethodGet, "/api/v1/chats/" + chat + "/messages", ""}, + {http.MethodPost, "/api/v1/chats/" + chat + "/messages", `{"text":"hi"}`}, + } + for _, c := range cases { + status, resp := do(t, srv, c.method, c.path, eve.Token, c.body) + if status != http.StatusNotFound || errorCode(resp) != "not_found" { + t.Errorf("%s %s by outsider: got %d, want 404", c.method, c.path, status) + } + } + + status, resp := do(t, srv, http.MethodGet, "/api/v1/chats", eve.Token, "") + if status != http.StatusOK || len(resp["items"].([]any)) != 0 { + t.Errorf("outsider chat list: got %d %v, want 200 with no items", status, resp["items"]) + } +} + +func TestEmptyMessage(t *testing.T) { + srv := newServer(t) + alice := createUser(t, srv, "alice") + chat := createChat(t, srv, alice, alice) + + for _, text := range []string{"", " ", "\n\t"} { + body, _ := json.Marshal(map[string]string{"text": text}) + status, resp := do(t, srv, http.MethodPost, "/api/v1/chats/"+chat+"/messages", alice.Token, string(body)) + if status != http.StatusBadRequest || errorCode(resp) != "invalid_request" { + t.Errorf("text %q: got %d, want 400", text, status) + } + } +} + +func TestDuplicateUsername(t *testing.T) { + srv := newServer(t) + alice := createUser(t, srv, "alice") + status, resp := do(t, srv, http.MethodPost, "/api/v1/users", "", + fmt.Sprintf(`{"username":%q,"display_name":"Other","password":"another-password"}`, alice.Username)) + if status != http.StatusConflict || errorCode(resp) != "conflict" { + t.Errorf("got %d %q, want 409 conflict", status, errorCode(resp)) + } +} + +func TestPaginationMultiplePages(t *testing.T) { + srv := newServer(t) + alice := createUser(t, srv, "alice") + chat := createChat(t, srv, alice, alice) + + const total, limit = 7, 3 + for i := range total { + status, _ := do(t, srv, http.MethodPost, "/api/v1/chats/"+chat+"/messages", alice.Token, fmt.Sprintf(`{"text":"msg %d"}`, i)) + if status != http.StatusCreated { + t.Fatalf("send message %d: status %d", i, status) + } + } + + seen := map[string]bool{} + pages := 0 + prevCreatedAt := "" + cursor := "" + for { + path := fmt.Sprintf("/api/v1/chats/%s/messages?limit=%d", chat, limit) + if cursor != "" { + path += "&cursor=" + cursor + } + status, resp := do(t, srv, http.MethodGet, path, alice.Token, "") + if status != http.StatusOK { + t.Fatalf("page %d: status %d", pages+1, status) + } + pages++ + for _, it := range resp["items"].([]any) { + m := it.(map[string]any) + id, createdAt := m["id"].(string), m["created_at"].(string) + if seen[id] { + t.Errorf("message %s returned twice", id) + } + if createdAt < prevCreatedAt { + t.Errorf("messages out of order: %s after %s", createdAt, prevCreatedAt) + } + seen[id] = true + prevCreatedAt = createdAt + } + next, ok := resp["next_cursor"].(string) + if !ok { + break + } + cursor = next + } + + if len(seen) != total { + t.Errorf("got %d messages, want %d", len(seen), total) + } + if want := (total + limit - 1) / limit; pages != want { + t.Errorf("got %d pages, want %d", pages, want) + } +} + +func TestConcurrentMessages(t *testing.T) { + srv := newServer(t) + const clients, perClient = 10, 10 + + users := make([]testUser, clients) + for i := range users { + users[i] = createUser(t, srv, fmt.Sprintf("client_%d", i)) + } + chat := createChat(t, srv, users[0], users...) + + var wg sync.WaitGroup + errs := make(chan error, clients*perClient) + for c, user := range users { + wg.Go(func() { + for i := range perClient { + status, _ := do(t, srv, http.MethodPost, "/api/v1/chats/"+chat+"/messages", user.Token, + fmt.Sprintf(`{"text":"client %d msg %d"}`, c, i)) + if status != http.StatusCreated { + errs <- fmt.Errorf("client %d msg %d: status %d", c, i, status) + } + } + }) + } + wg.Wait() + close(errs) + for err := range errs { + t.Error(err) + } + + status, resp := do(t, srv, http.MethodGet, "/api/v1/chats/"+chat+"/messages?limit=100", users[0].Token, "") + if status != http.StatusOK { + t.Fatalf("read history: status %d", status) + } + items := resp["items"].([]any) + ids := map[string]bool{} + for _, it := range items { + ids[it.(map[string]any)["id"].(string)] = true + } + if len(items) != clients*perClient || len(ids) != clients*perClient { + t.Errorf("got %d messages (%d unique), want %d", len(items), len(ids), clients*perClient) + } + if resp["next_cursor"] != nil { + t.Errorf("next_cursor = %v, want null", resp["next_cursor"]) + } +} diff --git a/internal/handler/health.go b/internal/handler/health.go new file mode 100644 index 0000000..375ee0b --- /dev/null +++ b/internal/handler/health.go @@ -0,0 +1,32 @@ +package handler + +import ( + "context" + "fmt" + "net/http" + "time" + + "messenger/internal/domain" +) + +const readyTimeout = time.Second + +func (h *Handler) Live(w http.ResponseWriter, _ *http.Request) { + writeJSON(w, http.StatusOK, healthResponse{Status: "ok"}) +} + +func (h *Handler) Ready(w http.ResponseWriter, r *http.Request) { + if h.draining.Load() { + h.fail(w, r, fmt.Errorf("%w: draining", domain.ErrUnavailable)) + return + } + ctx, cancel := context.WithTimeout(r.Context(), readyTimeout) + defer cancel() + for _, dep := range h.deps { + if err := dep(ctx); err != nil { + h.fail(w, r, fmt.Errorf("%w: %v", domain.ErrUnavailable, err)) + return + } + } + writeJSON(w, http.StatusOK, healthResponse{Status: "ok"}) +} diff --git a/internal/handler/json.go b/internal/handler/json.go new file mode 100644 index 0000000..54674c2 --- /dev/null +++ b/internal/handler/json.go @@ -0,0 +1,86 @@ +package handler + +import ( + "bytes" + "encoding/json" + "errors" + "io" + "mime" + "net/http" + "reflect" + "strings" + "unicode/utf8" +) + +const maxBodyBytes = 1 << 20 + +func writeJSON(w http.ResponseWriter, status int, v any) { + w.Header().Set("Content-Type", "application/json; charset=utf-8") + w.WriteHeader(status) + _ = json.NewEncoder(w).Encode(v) +} + +func decodeJSON(w http.ResponseWriter, r *http.Request, dst any) error { + mt, _, err := mime.ParseMediaType(r.Header.Get("Content-Type")) + if err != nil || mt != "application/json" { + return &apiError{http.StatusUnsupportedMediaType, "unsupported_media_type", "Content-Type must be application/json"} + } + + raw, err := io.ReadAll(http.MaxBytesReader(w, r.Body, maxBodyBytes)) + if err != nil { + var tooLarge *http.MaxBytesError + if errors.As(err, &tooLarge) { + return &apiError{http.StatusRequestEntityTooLarge, "payload_too_large", "request body is too large"} + } + return badRequest("failed to read request body") + } + if !utf8.Valid(raw) { + return badRequest("request body must be valid UTF-8") + } + if err := checkKeys(raw, dst); err != nil { + return err + } + + dec := json.NewDecoder(bytes.NewReader(raw)) + dec.DisallowUnknownFields() + if err := dec.Decode(dst); err != nil { + return badRequest("request body must be a valid JSON object matching the schema") + } + if err := dec.Decode(&struct{}{}); !errors.Is(err, io.EOF) { + return badRequest("request body must contain a single JSON object") + } + return nil +} + +func checkKeys(raw []byte, dst any) error { + allowed := jsonFields(dst) + dec := json.NewDecoder(bytes.NewReader(raw)) + if tok, err := dec.Token(); err != nil || tok != json.Delim('{') { + return badRequest("request body must be a JSON object") + } + for dec.More() { + tok, err := dec.Token() + if err != nil { + return badRequest("request body must be a valid JSON object matching the schema") + } + key, _ := tok.(string) + if !allowed[key] { + return badRequest("request body contains unknown field") + } + var value json.RawMessage + if err := dec.Decode(&value); err != nil { + return badRequest("request body must be a valid JSON object matching the schema") + } + } + return nil +} + +func jsonFields(dst any) map[string]bool { + t := reflect.TypeOf(dst).Elem() + fields := make(map[string]bool, t.NumField()) + for i := range t.NumField() { + name, _, _ := strings.Cut(t.Field(i).Tag.Get("json"), ",") + fields[name] = true + } + return fields +} diff --git a/internal/handler/messages.go b/internal/handler/messages.go new file mode 100644 index 0000000..7469f3a --- /dev/null +++ b/internal/handler/messages.go @@ -0,0 +1,57 @@ +package handler + +import ( + "net/http" + "regexp" +) + +const headerIdempotencyKey = "Idempotency-Key" + +var idempotencyKeyRe = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`) + +func (h *Handler) SendMessage(w http.ResponseWriter, r *http.Request) { + chatID, err := chatIDParam(r) + if err != nil { + h.fail(w, r, err) + return + } + key := r.Header.Get(headerIdempotencyKey) + if !idempotencyKeyRe.MatchString(key) { + h.fail(w, r, badRequest("Idempotency-Key header must match [A-Za-z0-9._:-]{1,128}")) + return + } + var req createMessageRequest + if err := decodeJSON(w, r, &req); err != nil { + h.fail(w, r, err) + return + } + if req.Text == nil { + h.fail(w, r, badRequest("text is required")) + return + } + msg, err := h.messages.Send(r.Context(), actor(r), chatID, key, *req.Text) + if err != nil { + h.fail(w, r, err) + return + } + writeJSON(w, http.StatusCreated, toMessageResponse(msg)) +} + +func (h *Handler) ListMessages(w http.ResponseWriter, r *http.Request) { + chatID, err := chatIDParam(r) + if err != nil { + h.fail(w, r, err) + return + } + limit, cursor, err := pageParams(r) + if err != nil { + h.fail(w, r, err) + return + } + page, err := h.messages.History(r.Context(), actor(r), chatID, cursor, limit) + if err != nil { + h.fail(w, r, err) + return + } + writeJSON(w, http.StatusOK, toPageResponse(page, toMessageResponse)) +} diff --git a/internal/handler/middleware.go b/internal/handler/middleware.go new file mode 100644 index 0000000..1deafcc --- /dev/null +++ b/internal/handler/middleware.go @@ -0,0 +1,122 @@ +package handler + +import ( + "context" + "errors" + "net/http" + "runtime/debug" + "strings" + "time" + "uuid" + + "github.com/go-chi/chi/v5" + "github.com/go-chi/chi/v5/middleware" + + "messenger/internal/domain" +) + +const ( + headerRequestID = "X-Request-Id" + headerInstanceID = "X-Instance-Id" + headerWWWAuthenticate = "WWW-Authenticate" + bearerChallenge = `Bearer realm="messenger"` + basicChallenge = `Basic realm="messenger", charset="UTF-8"` +) + +func InstanceID(id string) func(http.Handler) http.Handler { + return func(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set(headerInstanceID, id) + next.ServeHTTP(w, r) + }) + } +} + +func RequestID(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set(headerRequestID, uuid.New().String()) + next.ServeHTTP(w, r) + }) +} + +func (h *Handler) AccessLog(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + start := time.Now() + ww := middleware.NewWrapResponseWriter(w, r.ProtoMajor) + next.ServeHTTP(ww, r) + + route := r.URL.Path + if rc := chi.RouteContext(r.Context()); rc != nil && rc.RoutePattern() != "" { + route = rc.RoutePattern() + } + h.log.Info("request", + "request_id", w.Header().Get(headerRequestID), + "method", r.Method, + "route", route, + "status", ww.Status(), + "duration_ms", time.Since(start).Milliseconds(), + ) + }) +} + +func (h *Handler) Recoverer(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + defer func() { + rec := recover() + if rec == nil { + return + } + if rec == http.ErrAbortHandler { + panic(rec) + } + h.log.Error("panic", "request_id", w.Header().Get(headerRequestID), + "method", r.Method, "path", r.URL.Path, "panic", rec, "stack", string(debug.Stack())) + writeError(w, http.StatusInternalServerError, "internal_error", "internal server error") + }() + next.ServeHTTP(w, r) + }) +} + +type ctxKey struct{} + +type principal struct { + user domain.User + token string +} + +func (h *Handler) Authenticate(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + token, ok := authCredentials(r, "Bearer") + if !ok || token == "" { + h.fail(w, r, domain.ErrUnauthorized) + return + } + user, err := h.auth.Authenticate(r.Context(), token) + if err != nil { + h.fail(w, r, err) + return + } + ctx := context.WithValue(r.Context(), ctxKey{}, principal{user: user, token: token}) + next.ServeHTTP(w, r.WithContext(ctx)) + }) +} + +func authCredentials(r *http.Request, scheme string) (string, bool) { + gotScheme, credentials, ok := strings.Cut(r.Header.Get("Authorization"), " ") + if !ok || !strings.EqualFold(gotScheme, scheme) { + return "", false + } + return credentials, true +} + +func current(r *http.Request) principal { + p, ok := r.Context().Value(ctxKey{}).(principal) + if !ok { + panic(errors.New("handler: actor requested on unauthenticated route")) + } + return p +} + +func actor(r *http.Request) domain.User { + return current(r).user +} diff --git a/internal/handler/users.go b/internal/handler/users.go new file mode 100644 index 0000000..c427ca4 --- /dev/null +++ b/internal/handler/users.go @@ -0,0 +1,25 @@ +package handler + +import "net/http" + +func (h *Handler) RegisterUser(w http.ResponseWriter, r *http.Request) { + var req createUserRequest + if err := decodeJSON(w, r, &req); err != nil { + h.fail(w, r, err) + return + } + if req.Username == nil || req.DisplayName == nil || req.Password == nil { + h.fail(w, r, badRequest("username, display_name and password are required strings")) + return + } + user, err := h.users.Register(r.Context(), *req.Username, *req.DisplayName, *req.Password) + if err != nil { + h.fail(w, r, err) + return + } + writeJSON(w, http.StatusCreated, toUserResponse(user)) +} + +func (h *Handler) CurrentUser(w http.ResponseWriter, r *http.Request) { + writeJSON(w, http.StatusOK, toUserResponse(actor(r))) +} diff --git a/internal/repository/postgres/migrations/000001_init.down.sql b/internal/repository/postgres/migrations/000001_init.down.sql new file mode 100644 index 0000000..1ba630f --- /dev/null +++ b/internal/repository/postgres/migrations/000001_init.down.sql @@ -0,0 +1,4 @@ +DROP TABLE IF EXISTS messages; +DROP TABLE IF EXISTS chat_members; +DROP TABLE IF EXISTS chats; +DROP TABLE IF EXISTS users; diff --git a/internal/repository/postgres/migrations/000001_init.up.sql b/internal/repository/postgres/migrations/000001_init.up.sql new file mode 100644 index 0000000..694ae23 --- /dev/null +++ b/internal/repository/postgres/migrations/000001_init.up.sql @@ -0,0 +1,32 @@ +CREATE TABLE users ( + id uuid PRIMARY KEY, + username text NOT NULL UNIQUE, + display_name text NOT NULL, + password_hash text NOT NULL, + created_at timestamptz NOT NULL +); + +CREATE TABLE chats ( + id uuid PRIMARY KEY, + title text NOT NULL, + created_at timestamptz NOT NULL +); + +CREATE TABLE chat_members ( + chat_id uuid NOT NULL REFERENCES chats (id) ON DELETE CASCADE, + user_id uuid NOT NULL REFERENCES users (id), + position int NOT NULL, + PRIMARY KEY (chat_id, user_id) +); + +CREATE INDEX chat_members_user_id_idx ON chat_members (user_id); + +CREATE TABLE messages ( + id uuid PRIMARY KEY, + chat_id uuid NOT NULL REFERENCES chats (id) ON DELETE CASCADE, + sender_id uuid NOT NULL REFERENCES users (id), + text text NOT NULL, + created_at timestamptz NOT NULL +); + +CREATE INDEX messages_chat_created_id_idx ON messages (chat_id, created_at, id); diff --git a/internal/repository/postgres/migrations/000002_message_idempotency.down.sql b/internal/repository/postgres/migrations/000002_message_idempotency.down.sql new file mode 100644 index 0000000..64acde8 --- /dev/null +++ b/internal/repository/postgres/migrations/000002_message_idempotency.down.sql @@ -0,0 +1 @@ +DROP TABLE message_idempotency; diff --git a/internal/repository/postgres/migrations/000002_message_idempotency.up.sql b/internal/repository/postgres/migrations/000002_message_idempotency.up.sql new file mode 100644 index 0000000..d10b7a9 --- /dev/null +++ b/internal/repository/postgres/migrations/000002_message_idempotency.up.sql @@ -0,0 +1,9 @@ +CREATE TABLE message_idempotency ( + user_id uuid NOT NULL REFERENCES users (id), + 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, + PRIMARY KEY (user_id, chat_id, key) +); diff --git a/internal/repository/postgres/postgres_test.go b/internal/repository/postgres/postgres_test.go new file mode 100644 index 0000000..412fb9d --- /dev/null +++ b/internal/repository/postgres/postgres_test.go @@ -0,0 +1,103 @@ +package postgres_test + +import ( + "context" + "errors" + "os" + "sync" + "testing" + "time" + "uuid" + + "github.com/jackc/pgx/v5/pgxpool" + + "messenger/internal/domain" + "messenger/internal/repository/postgres" +) + +func newStore(t *testing.T) (*postgres.Store, *pgxpool.Pool) { + t.Helper() + dbURL := os.Getenv("TEST_DATABASE_URL") + if dbURL == "" { + t.Skip("TEST_DATABASE_URL is required") + } + pool, err := postgres.NewPool(context.Background(), dbURL) + if err != nil { + t.Fatal(err) + } + t.Cleanup(pool.Close) + return postgres.New(pool), pool +} + +func newUser(username string) domain.User { + return domain.User{ID: uuid.New(), Username: username, DisplayName: "Test", CreatedAt: time.Now().UTC()} +} + +func TestRegisterUsernameRace(t *testing.T) { + store, pool := newStore(t) + ctx := context.Background() + username := "race_" + uuid.New().String()[:8] + + const workers = 20 + var wg sync.WaitGroup + errs := make([]error, workers) + start := make(chan struct{}) + for i := range workers { + wg.Go(func() { + <-start + errs[i] = store.CreateUser(ctx, newUser(username), "hash") + }) + } + close(start) + wg.Wait() + + created := 0 + for _, err := range errs { + switch { + case err == nil: + created++ + case !errors.Is(err, domain.ErrConflict): + t.Errorf("unexpected error: %v", err) + } + } + if created != 1 { + t.Errorf("created %d users, want exactly 1", created) + } + var rows int + if err := pool.QueryRow(ctx, `SELECT count(*) FROM users WHERE username = $1`, username).Scan(&rows); err != nil { + t.Fatal(err) + } + if rows != 1 { + t.Errorf("users rows = %d, want 1", rows) + } +} + +func TestCreateChatRollback(t *testing.T) { + store, pool := newStore(t) + ctx := context.Background() + alice := newUser("rb_" + uuid.New().String()[:8]) + if err := store.CreateUser(ctx, alice, "hash"); err != nil { + t.Fatal(err) + } + + chat := domain.Chat{ + ID: uuid.New(), + Title: "rollback", + MemberIDs: []uuid.UUID{alice.ID, uuid.New()}, + CreatedAt: time.Now().UTC(), + } + if err := store.CreateChat(ctx, chat); !errors.Is(err, domain.ErrNotFound) { + t.Fatalf("CreateChat with unknown member: got %v, want ErrNotFound", err) + } + + var chats, members int + if err := pool.QueryRow(ctx, `SELECT count(*) FROM chats WHERE id = $1`, chat.ID).Scan(&chats); err != nil { + t.Fatal(err) + } + if err := pool.QueryRow(ctx, `SELECT count(*) FROM chat_members WHERE chat_id = $1`, chat.ID).Scan(&members); err != nil { + t.Fatal(err) + } + if chats != 0 || members != 0 { + t.Errorf("after rollback: chats=%d chat_members=%d, want 0 and 0", chats, members) + } +} diff --git a/internal/repository/postgres/store.go b/internal/repository/postgres/store.go new file mode 100644 index 0000000..0a3be5f --- /dev/null +++ b/internal/repository/postgres/store.go @@ -0,0 +1,275 @@ +package postgres + +import ( + "context" + "errors" + "fmt" + "time" + "uuid" + + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgconn" + "github.com/jackc/pgx/v5/pgxpool" + + "messenger/internal/domain" +) + +const ( + maxConns = 10 + connectTimeout = 3 * time.Second + statementTimeout = "5000" +) + +type Store struct { + pool *pgxpool.Pool +} + +func NewPool(ctx context.Context, databaseURL string) (*pgxpool.Pool, error) { + cfg, err := pgxpool.ParseConfig(databaseURL) + if err != nil { + return nil, err + } + cfg.MaxConns = maxConns + cfg.ConnConfig.ConnectTimeout = connectTimeout + cfg.ConnConfig.RuntimeParams["statement_timeout"] = statementTimeout + return pgxpool.NewWithConfig(ctx, cfg) +} + +func New(pool *pgxpool.Pool) *Store { + return &Store{pool: pool} +} + +func (s *Store) Ping(ctx context.Context) error { + return dbErr(s.pool.Ping(ctx)) +} + +func (s *Store) CreateUser(ctx context.Context, u domain.User, passwordHash string) error { + _, err := s.pool.Exec(ctx, + `INSERT INTO users (id, username, display_name, password_hash, created_at) VALUES ($1, $2, $3, $4, $5)`, + u.ID, u.Username, u.DisplayName, passwordHash, u.CreatedAt) + return dbErr(err) +} + +func (s *Store) GetUser(ctx context.Context, id uuid.UUID) (domain.User, error) { + var u domain.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) + return u, dbErr(err) +} + +func (s *Store) GetUserByUsername(ctx context.Context, username string) (domain.User, string, error) { + var u domain.User + var hash string + err := s.pool.QueryRow(ctx, + `SELECT id, username, display_name, created_at, password_hash FROM users WHERE username = $1`, username, + ).Scan(&u.ID, &u.Username, &u.DisplayName, &u.CreatedAt, &hash) + return u, hash, dbErr(err) +} + +func (s *Store) CreateChat(ctx context.Context, c domain.Chat) error { + tx, err := s.pool.Begin(ctx) + if err != nil { + return dbErr(err) + } + defer tx.Rollback(ctx) + + if _, err := tx.Exec(ctx, `INSERT INTO chats (id, title, created_at) VALUES ($1, $2, $3)`, + c.ID, c.Title, c.CreatedAt); err != nil { + return dbErr(err) + } + for i, userID := range c.MemberIDs { + if _, err := tx.Exec(ctx, `INSERT INTO chat_members (chat_id, user_id, position) VALUES ($1, $2, $3)`, + c.ID, userID, i); err != nil { + return dbErr(err) + } + } + return dbErr(tx.Commit(ctx)) +} + +func (s *Store) GetChat(ctx context.Context, id uuid.UUID) (domain.Chat, error) { + var c domain.Chat + err := s.pool.QueryRow(ctx, `SELECT id, title, created_at FROM chats WHERE id = $1`, id). + Scan(&c.ID, &c.Title, &c.CreatedAt) + if err != nil { + return domain.Chat{}, dbErr(err) + } + chats := []domain.Chat{c} + if err := s.loadMembers(ctx, chats); err != nil { + return domain.Chat{}, err + } + return chats[0], nil +} + +func (s *Store) ListUserChats(ctx context.Context, userID uuid.UUID, after *domain.Cursor, limit int) ([]domain.Chat, bool, error) { + var rows pgx.Rows + var err error + if after == nil { + rows, err = s.pool.Query(ctx, ` + SELECT c.id, c.title, c.created_at + FROM chats c + JOIN chat_members m ON m.chat_id = c.id + WHERE m.user_id = $1 + ORDER BY c.created_at, c.id + LIMIT $2`, userID, limit+1) + } else { + rows, err = s.pool.Query(ctx, ` + SELECT c.id, c.title, c.created_at + FROM chats c + JOIN chat_members m ON m.chat_id = c.id + WHERE m.user_id = $1 AND (c.created_at, c.id) > ($2, $3) + ORDER BY c.created_at, c.id + LIMIT $4`, userID, after.CreatedAt, after.ID, limit+1) + } + if err != nil { + return nil, false, dbErr(err) + } + chats, err := pgx.CollectRows(rows, func(row pgx.CollectableRow) (domain.Chat, error) { + var c domain.Chat + err := row.Scan(&c.ID, &c.Title, &c.CreatedAt) + return c, err + }) + if err != nil { + return nil, false, dbErr(err) + } + more := len(chats) > limit + if more { + chats = chats[:limit] + } + if err := s.loadMembers(ctx, chats); err != nil { + return nil, false, err + } + return chats, more, nil +} + +func (s *Store) loadMembers(ctx context.Context, chats []domain.Chat) error { + if len(chats) == 0 { + return nil + } + ids := make([]uuid.UUID, len(chats)) + index := make(map[uuid.UUID]int, len(chats)) + for i, c := range chats { + ids[i] = c.ID + index[c.ID] = i + } + rows, err := s.pool.Query(ctx, + `SELECT chat_id, user_id FROM chat_members WHERE chat_id = ANY($1) ORDER BY chat_id, position`, ids) + if err != nil { + return dbErr(err) + } + defer rows.Close() + for rows.Next() { + var chatID, userID uuid.UUID + if err := rows.Scan(&chatID, &userID); err != nil { + return dbErr(err) + } + i := index[chatID] + chats[i].MemberIDs = append(chats[i].MemberIDs, userID) + } + return dbErr(rows.Err()) +} + +func (s *Store) CreateMessageIdempotent(ctx context.Context, m domain.Message, key, requestHash string) (domain.Message, error) { + tx, err := s.pool.Begin(ctx) + if err != nil { + return domain.Message{}, dbErr(err) + } + defer tx.Rollback(ctx) + + tag, err := tx.Exec(ctx, ` + INSERT INTO message_idempotency (user_id, chat_id, key, request_hash, message_id, created_at) + VALUES ($1, $2, $3, $4, $5, $6) + ON CONFLICT DO NOTHING`, + m.SenderID, m.ChatID, key, requestHash, m.ID, m.CreatedAt) + if err != nil { + return domain.Message{}, dbErr(err) + } + if tag.RowsAffected() == 0 { + var storedHash string + var stored domain.Message + err := tx.QueryRow(ctx, ` + SELECT k.request_hash, m.id, m.chat_id, m.sender_id, m.text, m.created_at + FROM message_idempotency k + JOIN messages m ON m.id = k.message_id + WHERE k.user_id = $1 AND k.chat_id = $2 AND k.key = $3`, + m.SenderID, m.ChatID, key, + ).Scan(&storedHash, &stored.ID, &stored.ChatID, &stored.SenderID, &stored.Text, &stored.CreatedAt) + if err != nil { + return domain.Message{}, dbErr(err) + } + if storedHash != requestHash { + return domain.Message{}, domain.ErrConflict + } + return stored, nil + } + + if _, err := tx.Exec(ctx, + `INSERT INTO messages (id, chat_id, sender_id, text, created_at) VALUES ($1, $2, $3, $4, $5)`, + m.ID, m.ChatID, m.SenderID, m.Text, m.CreatedAt); err != nil { + return domain.Message{}, dbErr(err) + } + if err := tx.Commit(ctx); err != nil { + return domain.Message{}, dbErr(err) + } + return m, nil +} + +func (s *Store) ListMessages(ctx context.Context, chatID uuid.UUID, after *domain.Cursor, limit int) ([]domain.Message, bool, error) { + var rows pgx.Rows + var err error + if after == nil { + rows, err = s.pool.Query(ctx, ` + SELECT id, chat_id, sender_id, text, created_at + FROM messages + WHERE chat_id = $1 + ORDER BY created_at, id + LIMIT $2`, chatID, limit+1) + } else { + rows, err = s.pool.Query(ctx, ` + SELECT id, chat_id, sender_id, text, created_at + FROM messages + WHERE chat_id = $1 AND (created_at, id) > ($2, $3) + ORDER BY created_at, id + LIMIT $4`, chatID, after.CreatedAt, after.ID, limit+1) + } + if err != nil { + return nil, false, dbErr(err) + } + msgs, err := pgx.CollectRows(rows, func(row pgx.CollectableRow) (domain.Message, error) { + var m domain.Message + err := row.Scan(&m.ID, &m.ChatID, &m.SenderID, &m.Text, &m.CreatedAt) + return m, err + }) + if err != nil { + return nil, false, dbErr(err) + } + more := len(msgs) > limit + if more { + msgs = msgs[:limit] + } + return msgs, more, nil +} + +func dbErr(err error) error { + if err == nil { + return nil + } + if errors.Is(err, pgx.ErrNoRows) { + return domain.ErrNotFound + } + var pgErr *pgconn.PgError + if errors.As(err, &pgErr) { + switch pgErr.Code { + case "23505": + return domain.ErrConflict + case "23503": + return domain.ErrNotFound + } + switch pgErr.Code[:2] { + case "08", "53", "57": + return fmt.Errorf("%w: %v", domain.ErrUnavailable, err) + } + return err + } + return fmt.Errorf("%w: %v", domain.ErrUnavailable, err) +} diff --git a/internal/repository/redis/sessions.go b/internal/repository/redis/sessions.go new file mode 100644 index 0000000..1c054ca --- /dev/null +++ b/internal/repository/redis/sessions.go @@ -0,0 +1,71 @@ +package redis + +import ( + "context" + "errors" + "fmt" + "time" + "uuid" + + goredis "github.com/redis/go-redis/v9" + + "messenger/internal/domain" +) + +const keyPrefix = "session:" + +type SessionStore struct { + client *goredis.Client +} + +func NewClient(url string) (*goredis.Client, error) { + opts, err := goredis.ParseURL(url) + if err != nil { + return nil, err + } + opts.PoolSize = 10 + opts.DialTimeout = 2 * time.Second + opts.ReadTimeout = time.Second + opts.WriteTimeout = time.Second + opts.MaxRetries = 0 + return goredis.NewClient(opts), nil +} + +func NewSessionStore(client *goredis.Client) *SessionStore { + return &SessionStore{client: client} +} + +func (s *SessionStore) Ping(ctx context.Context) error { + return cacheErr(s.client.Ping(ctx).Err()) +} + +func (s *SessionStore) Create(ctx context.Context, tokenHash string, userID uuid.UUID, expiresAt time.Time) error { + return cacheErr(s.client.SetArgs(ctx, keyPrefix+tokenHash, userID.String(), + goredis.SetArgs{ExpireAt: expiresAt}).Err()) +} + +func (s *SessionStore) Get(ctx context.Context, tokenHash string) (uuid.UUID, error) { + v, err := s.client.Get(ctx, keyPrefix+tokenHash).Result() + if errors.Is(err, goredis.Nil) { + return uuid.UUID{}, domain.ErrUnauthorized + } + if err != nil { + return uuid.UUID{}, cacheErr(err) + } + id, err := uuid.Parse(v) + if err != nil { + return uuid.UUID{}, domain.ErrUnauthorized + } + return id, nil +} + +func (s *SessionStore) Delete(ctx context.Context, tokenHash string) error { + return cacheErr(s.client.Del(ctx, keyPrefix+tokenHash).Err()) +} + +func cacheErr(err error) error { + if err == nil { + return nil + } + return fmt.Errorf("%w: %v", domain.ErrUnavailable, err) +} diff --git a/internal/router/router.go b/internal/router/router.go new file mode 100644 index 0000000..dec80b2 --- /dev/null +++ b/internal/router/router.go @@ -0,0 +1,37 @@ +package router + +import ( + "net/http" + + "github.com/go-chi/chi/v5" + + "messenger/internal/handler" +) + +func New(h *handler.Handler, instanceID string) http.Handler { + r := chi.NewRouter() + r.Use(handler.InstanceID(instanceID), handler.RequestID, h.AccessLog, h.Recoverer) + + r.NotFound(h.NotFound) + r.MethodNotAllowed(h.MethodNotAllowed) + + r.Get("/health/live", h.Live) + r.Get("/health/ready", h.Ready) + + r.Route("/api/v1", func(r chi.Router) { + r.Post("/users", h.RegisterUser) + r.Post("/auth/sessions", h.CreateSession) + + r.Group(func(r chi.Router) { + r.Use(h.Authenticate) + r.Delete("/auth/sessions/current", h.DeleteSession) + r.Get("/users/me", h.CurrentUser) + r.Post("/chats", h.CreateChat) + r.Get("/chats", h.ListChats) + r.Get("/chats/{chat_id}", h.GetChat) + r.Post("/chats/{chat_id}/messages", h.SendMessage) + r.Get("/chats/{chat_id}/messages", h.ListMessages) + }) + }) + return r +} diff --git a/internal/service/auth.go b/internal/service/auth.go new file mode 100644 index 0000000..698058a --- /dev/null +++ b/internal/service/auth.go @@ -0,0 +1,74 @@ +package service + +import ( + "context" + "crypto/rand" + "crypto/sha256" + "encoding/base64" + "encoding/hex" + "errors" + "time" + + "messenger/internal/domain" +) + +const tokenBytes = 32 + +type AuthService struct { + users UserRepository + sessions SessionStore + ttl time.Duration +} + +func NewAuthService(users UserRepository, sessions SessionStore, ttl time.Duration) *AuthService { + return &AuthService{users: users, sessions: sessions, ttl: ttl} +} + +func (s *AuthService) Login(ctx context.Context, username, password string) (domain.Session, error) { + user, hash, err := s.users.GetUserByUsername(ctx, username) + if errors.Is(err, domain.ErrNotFound) { + return domain.Session{}, domain.ErrUnauthorized + } + if err != nil { + return domain.Session{}, err + } + ok, err := verifyPassword(password, hash) + if err != nil { + return domain.Session{}, err + } + if !ok { + return domain.Session{}, domain.ErrUnauthorized + } + + raw := make([]byte, tokenBytes) + if _, err := rand.Read(raw); err != nil { + return domain.Session{}, err + } + token := base64.RawURLEncoding.EncodeToString(raw) + expiresAt := now().Add(s.ttl) + if err := s.sessions.Create(ctx, HashToken(token), user.ID, expiresAt); err != nil { + return domain.Session{}, err + } + return domain.Session{Token: token, ExpiresAt: expiresAt, User: user}, nil +} + +func (s *AuthService) Authenticate(ctx context.Context, token string) (domain.User, error) { + userID, err := s.sessions.Get(ctx, HashToken(token)) + if err != nil { + return domain.User{}, err + } + u, err := s.users.GetUser(ctx, userID) + if errors.Is(err, domain.ErrNotFound) { + return domain.User{}, domain.ErrUnauthorized + } + return u, err +} + +func (s *AuthService) Logout(ctx context.Context, token string) error { + return s.sessions.Delete(ctx, HashToken(token)) +} + +func HashToken(token string) string { + sum := sha256.Sum256([]byte(token)) + return hex.EncodeToString(sum[:]) +} diff --git a/internal/service/chats.go b/internal/service/chats.go new file mode 100644 index 0000000..aafa7c5 --- /dev/null +++ b/internal/service/chats.go @@ -0,0 +1,81 @@ +package service + +import ( + "context" + "errors" + "fmt" + "uuid" + + "messenger/internal/domain" +) + +type ChatService struct { + repo ChatRepository +} + +func NewChatService(repo ChatRepository) *ChatService { + return &ChatService{repo: repo} +} + +func (s *ChatService) Create(ctx context.Context, actor domain.User, title string, memberIDs []uuid.UUID) (domain.Chat, error) { + if err := checkText("title", title, 100); err != nil { + return domain.Chat{}, err + } + if len(memberIDs) < 1 || len(memberIDs) > 100 { + return domain.Chat{}, fmt.Errorf("%w: member_ids must contain 1 to 100 users", domain.ErrInvalidInput) + } + seen := make(map[uuid.UUID]struct{}, len(memberIDs)) + for _, id := range memberIDs { + if _, dup := seen[id]; dup { + return domain.Chat{}, fmt.Errorf("%w: member_ids must not contain duplicates", domain.ErrInvalidInput) + } + seen[id] = struct{}{} + } + if _, ok := seen[actor.ID]; !ok { + return domain.Chat{}, fmt.Errorf("%w: member_ids must include the current user", domain.ErrInvalidInput) + } + + c := domain.Chat{ + ID: uuid.New(), + Title: title, + MemberIDs: memberIDs, + CreatedAt: now(), + } + if err := s.repo.CreateChat(ctx, c); err != nil { + if errors.Is(err, domain.ErrNotFound) { + return domain.Chat{}, fmt.Errorf("%w: member_ids contains unknown user", domain.ErrInvalidInput) + } + return domain.Chat{}, err + } + return c, nil +} + +func (s *ChatService) Get(ctx context.Context, actor domain.User, chatID uuid.UUID) (domain.Chat, error) { + c, err := s.repo.GetChat(ctx, chatID) + if err != nil { + return domain.Chat{}, err + } + if !c.HasMember(actor.ID) { + return domain.Chat{}, domain.ErrNotFound + } + return c, nil +} + +func (s *ChatService) List(ctx context.Context, actor domain.User, after *domain.Cursor, limit int) (domain.Page[domain.Chat], error) { + if err := checkLimit(limit); err != nil { + return domain.Page[domain.Chat]{}, err + } + if after != nil && after.Scope != actor.ID { + return domain.Page[domain.Chat]{}, fmt.Errorf("%w: cursor does not belong to this request", domain.ErrInvalidInput) + } + items, more, err := s.repo.ListUserChats(ctx, actor.ID, after, limit) + if err != nil { + return domain.Page[domain.Chat]{}, err + } + page := domain.Page[domain.Chat]{Items: items} + if more { + last := items[len(items)-1] + page.Next = &domain.Cursor{Scope: actor.ID, CreatedAt: last.CreatedAt, ID: last.ID} + } + return page, nil +} diff --git a/internal/service/messages.go b/internal/service/messages.go new file mode 100644 index 0000000..e20f5f4 --- /dev/null +++ b/internal/service/messages.go @@ -0,0 +1,65 @@ +package service + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "errors" + "fmt" + "uuid" + + "messenger/internal/domain" +) + +type MessageService struct { + chats *ChatService + messages MessageRepository +} + +func NewMessageService(chats *ChatService, messages MessageRepository) *MessageService { + return &MessageService{chats: chats, messages: messages} +} + +func (s *MessageService) Send(ctx context.Context, actor domain.User, chatID uuid.UUID, key, text string) (domain.Message, error) { + if _, err := s.chats.Get(ctx, actor, chatID); err != nil { + return domain.Message{}, err + } + if err := checkText("text", text, 4000); err != nil { + return domain.Message{}, err + } + m := domain.Message{ + ID: uuid.New(), + ChatID: chatID, + SenderID: actor.ID, + Text: text, + CreatedAt: now(), + } + sum := sha256.Sum256([]byte(text)) + stored, err := s.messages.CreateMessageIdempotent(ctx, m, key, hex.EncodeToString(sum[:])) + if errors.Is(err, domain.ErrConflict) { + return domain.Message{}, fmt.Errorf("%w: Idempotency-Key was already used with a different body", domain.ErrConflict) + } + return stored, err +} + +func (s *MessageService) History(ctx context.Context, actor domain.User, chatID uuid.UUID, after *domain.Cursor, limit int) (domain.Page[domain.Message], error) { + if _, err := s.chats.Get(ctx, actor, chatID); err != nil { + return domain.Page[domain.Message]{}, err + } + if err := checkLimit(limit); err != nil { + return domain.Page[domain.Message]{}, err + } + if after != nil && after.Scope != chatID { + return domain.Page[domain.Message]{}, fmt.Errorf("%w: cursor belongs to another chat", domain.ErrInvalidInput) + } + items, more, err := s.messages.ListMessages(ctx, chatID, after, limit) + if err != nil { + return domain.Page[domain.Message]{}, err + } + page := domain.Page[domain.Message]{Items: items} + if more { + last := items[len(items)-1] + page.Next = &domain.Cursor{Scope: chatID, CreatedAt: last.CreatedAt, ID: last.ID} + } + return page, nil +} diff --git a/internal/service/password.go b/internal/service/password.go new file mode 100644 index 0000000..a52c470 --- /dev/null +++ b/internal/service/password.go @@ -0,0 +1,60 @@ +package service + +import ( + "crypto/rand" + "crypto/subtle" + "encoding/base64" + "errors" + "fmt" + "strings" + + "golang.org/x/crypto/argon2" +) + +const ( + argonMemory = 19 * 1024 + argonTime = 2 + argonThreads = 1 + argonSaltLen = 16 + argonKeyLen = 32 +) + +var errBadHash = errors.New("malformed password hash") + +func hashPassword(password string) (string, error) { + salt := make([]byte, argonSaltLen) + if _, err := rand.Read(salt); err != nil { + return "", err + } + key := argon2.IDKey([]byte(password), salt, argonTime, argonMemory, argonThreads, argonKeyLen) + b64 := base64.RawStdEncoding + return fmt.Sprintf("$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s", + argon2.Version, argonMemory, argonTime, argonThreads, b64.EncodeToString(salt), b64.EncodeToString(key)), nil +} + +func verifyPassword(password, encoded string) (bool, error) { + parts := strings.Split(encoded, "$") + if len(parts) != 6 || parts[1] != "argon2id" { + return false, errBadHash + } + var version int + var memory, time uint32 + var threads uint8 + if _, err := fmt.Sscanf(parts[2], "v=%d", &version); err != nil || version != argon2.Version { + return false, errBadHash + } + if _, err := fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d", &memory, &time, &threads); err != nil { + return false, errBadHash + } + b64 := base64.RawStdEncoding + salt, err := b64.DecodeString(parts[4]) + if err != nil { + return false, errBadHash + } + want, err := b64.DecodeString(parts[5]) + if err != nil { + return false, errBadHash + } + got := argon2.IDKey([]byte(password), salt, time, memory, threads, uint32(len(want))) + return subtle.ConstantTimeCompare(got, want) == 1, nil +} diff --git a/internal/service/ports.go b/internal/service/ports.go new file mode 100644 index 0000000..758bf87 --- /dev/null +++ b/internal/service/ports.go @@ -0,0 +1,36 @@ +package service + +import ( + "context" + "time" + "uuid" + + "messenger/internal/domain" +) + +type UserRepository interface { + CreateUser(ctx context.Context, u domain.User, passwordHash string) error + GetUser(ctx context.Context, id uuid.UUID) (domain.User, error) + GetUserByUsername(ctx context.Context, username string) (domain.User, string, error) +} + +type ChatRepository interface { + CreateChat(ctx context.Context, c domain.Chat) error + GetChat(ctx context.Context, id uuid.UUID) (domain.Chat, error) + ListUserChats(ctx context.Context, userID uuid.UUID, after *domain.Cursor, limit int) ([]domain.Chat, bool, error) +} + +type MessageRepository interface { + CreateMessageIdempotent(ctx context.Context, m domain.Message, key, requestHash string) (domain.Message, error) + ListMessages(ctx context.Context, chatID uuid.UUID, after *domain.Cursor, limit int) ([]domain.Message, bool, error) +} + +type SessionStore interface { + Create(ctx context.Context, tokenHash string, userID uuid.UUID, expiresAt time.Time) error + Get(ctx context.Context, tokenHash string) (uuid.UUID, error) + Delete(ctx context.Context, tokenHash string) error +} + +func now() time.Time { + return time.Now().UTC().Truncate(time.Microsecond) +} diff --git a/internal/service/users.go b/internal/service/users.go new file mode 100644 index 0000000..9b387b4 --- /dev/null +++ b/internal/service/users.go @@ -0,0 +1,59 @@ +package service + +import ( + "context" + "errors" + "fmt" + "regexp" + "unicode/utf8" + "uuid" + + "messenger/internal/domain" +) + +var usernameRe = regexp.MustCompile(`^[a-z0-9_]{3,32}$`) + +const ( + minPasswordLen = 12 + maxPasswordLen = 128 +) + +type UserService struct { + repo UserRepository +} + +func NewUserService(repo UserRepository) *UserService { + return &UserService{repo: repo} +} + +func (s *UserService) Register(ctx context.Context, username, displayName, password string) (domain.User, error) { + if !usernameRe.MatchString(username) { + return domain.User{}, fmt.Errorf("%w: username must match [a-z0-9_]{3,32}", domain.ErrInvalidInput) + } + if err := checkText("display_name", displayName, 100); err != nil { + return domain.User{}, err + } + if err := checkText("password", password, maxPasswordLen); err != nil { + return domain.User{}, err + } + if utf8.RuneCountInString(password) < minPasswordLen { + return domain.User{}, fmt.Errorf("%w: password must be at least %d characters", domain.ErrInvalidInput, minPasswordLen) + } + hash, err := hashPassword(password) + if err != nil { + return domain.User{}, err + } + u := domain.User{ + ID: uuid.New(), + Username: username, + DisplayName: displayName, + CreatedAt: now(), + } + if err := s.repo.CreateUser(ctx, u, hash); err != nil { + if errors.Is(err, domain.ErrConflict) { + return domain.User{}, fmt.Errorf("%w: username is already taken", domain.ErrConflict) + } + return domain.User{}, err + } + return u, nil +} diff --git a/internal/service/validate.go b/internal/service/validate.go new file mode 100644 index 0000000..68540bc --- /dev/null +++ b/internal/service/validate.go @@ -0,0 +1,31 @@ +package service + +import ( + "fmt" + "strings" + "unicode/utf8" + + "messenger/internal/domain" +) + +const ( + DefaultLimit = 50 + MaxLimit = 100 +) + +func checkText(field, value string, maxRunes int) error { + if strings.TrimSpace(value) == "" { + return fmt.Errorf("%w: %s must not be empty", domain.ErrInvalidInput, field) + } + if n := utf8.RuneCountInString(value); n > maxRunes { + return fmt.Errorf("%w: %s must be at most %d characters", domain.ErrInvalidInput, field, maxRunes) + } + return nil +} + +func checkLimit(limit int) error { + if limit < 1 || limit > MaxLimit { + return fmt.Errorf("%w: limit must be between 1 and %d", domain.ErrInvalidInput, MaxLimit) + } + return nil +} diff --git a/scripts/idempotency-race.py b/scripts/idempotency-race.py new file mode 100755 index 0000000..d33fa90 --- /dev/null +++ b/scripts/idempotency-race.py @@ -0,0 +1,56 @@ +#!/usr/bin/env python3 +import sys +import threading +import uuid +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests')) +from client import Client, check + +WORKERS = 20 + + +def main(): + c = Client() + alice, _, _, chat = c.bootstrap() + key = uuid.uuid4().hex + text = 'Одновременный повтор ' + key + barrier = threading.Barrier(WORKERS) + results, errors = [], [] + lock = threading.Lock() + + def send(): + barrier.wait() + try: + r = c.message(alice, chat, text, key=key) + with lock: + results.append((r['json'], r['headers']['X-Instance-Id'])) + except AssertionError as exc: + with lock: + errors.append(str(exc)) + + threads = [threading.Thread(target=send) for _ in range(WORKERS)] + for t in threads: + t.start() + for t in threads: + t.join() + + history = c.call('GET', '/api/v1/chats/' + chat['id'] + '/messages?limit=100', actor=alice, schema='MessagePage')['json']['items'] + stored = [m for m in history if m['text'] == text] + instances = sorted({i for _, i in results}) + ids = {m['id'] for m, _ in results} + print('parallel requests with one key:', WORKERS) + print('successful responses (201):', len(results)) + print('failed requests:', len(errors), errors[:3]) + print('distinct message ids in responses:', len(ids)) + print('messages stored in history:', len(stored)) + print('instances that served requests:', instances) + check(not errors, 'some requests failed') + check(len(ids) == 1 and len(stored) == 1, 'duplicate message created') + check(all(m == results[0][0] for m, _ in results), 'replayed responses differ') + check(len(instances) >= 2, 'requests were not spread across replicas') + print('OK: exactly one message created') + + +if __name__ == '__main__': + main() diff --git a/scripts/init-secrets.sh b/scripts/init-secrets.sh new file mode 100755 index 0000000..11e9661 --- /dev/null +++ b/scripts/init-secrets.sh @@ -0,0 +1,18 @@ +#!/bin/sh +set -eu +cd "$(dirname "$0")/.." +mkdir -p secrets +chmod 700 secrets + +if [ ! -f secrets/postgres_password ]; then + head -c 24 /dev/urandom | od -An -tx1 | tr -d ' \n' > secrets/postgres_password +fi +password=$(cat secrets/postgres_password) + +[ -f secrets/database_url ] || + printf 'postgres://messenger:%s@postgres:5432/messenger?sslmode=disable\n' "$password" > secrets/database_url +[ -f secrets/cache_url ] || + printf 'redis://redis:6379/0\n' > secrets/cache_url + +chmod 644 secrets/postgres_password secrets/database_url secrets/cache_url +echo "secrets ready in ./secrets" diff --git a/scripts/restart.sh b/scripts/restart.sh new file mode 100755 index 0000000..d644401 --- /dev/null +++ b/scripts/restart.sh @@ -0,0 +1,8 @@ +#!/bin/sh +set -eu +cd "$(dirname "$0")/.." +ENGINE=${ENGINE:-$(command -v podman >/dev/null 2>&1 && echo podman || echo docker)} +COMPOSE=${COMPOSE:-$([ "$ENGINE" = podman ] && echo podman-compose || echo "docker compose")} + +$COMPOSE stop lb api redis postgres +$COMPOSE start postgres redis api lb diff --git a/scripts/rolling-update.sh b/scripts/rolling-update.sh new file mode 100755 index 0000000..7865588 --- /dev/null +++ b/scripts/rolling-update.sh @@ -0,0 +1,37 @@ +#!/bin/sh +set -eu +cd "$(dirname "$0")/.." +ENGINE=${ENGINE:-$(command -v podman >/dev/null 2>&1 && echo podman || echo docker)} +COMPOSE=${COMPOSE:-$([ "$ENGINE" = podman ] && echo podman-compose || echo "docker compose")} +PROJECT=${PROJECT:-messenger-lab3} + +replicas() { + $ENGINE ps -aq --no-trunc --filter "label=com.docker.compose.project=$PROJECT" --filter "label=com.docker.compose.service=api" | sort +} + +wait_healthy() { + for _ in $(seq 1 60); do + if [ "$($ENGINE inspect -f '{{.State.Health.Status}}' "$1" 2>/dev/null)" = "healthy" ]; then + return 0 + fi + sleep 1 + done + echo "replica $1 did not become healthy" >&2 + exit 1 +} + +$ENGINE build --build-arg "BUILD_ID=${BUILD_ID:-$(date +%s)}" -t localhost/messenger-api:lab3 . +$COMPOSE run --rm migrate + +for old in $(replicas); do + before=$(replicas) + $ENGINE stop -t 10 "$old" + $ENGINE rm "$old" + $COMPOSE up -d --no-deps --no-recreate api + for id in $(replicas); do + if ! echo "$before" | grep -q "$id"; then + wait_healthy "$id" + fi + done + sleep 2 +done diff --git a/scripts/stop-one.sh b/scripts/stop-one.sh new file mode 100755 index 0000000..96d49fa --- /dev/null +++ b/scripts/stop-one.sh @@ -0,0 +1,13 @@ +#!/bin/sh +set -eu +ENGINE=${ENGINE:-$(command -v podman >/dev/null 2>&1 && echo podman || echo docker)} +PROJECT=${PROJECT:-messenger-lab3} +: "${TARGET_INSTANCE_ID:?TARGET_INSTANCE_ID is required}" + +for id in $($ENGINE ps -q --filter "label=com.docker.compose.project=$PROJECT" --filter "label=com.docker.compose.service=api"); do + if [ "$($ENGINE inspect -f '{{.Config.Hostname}}' "$id")" = "$TARGET_INSTANCE_ID" ]; then + $ENGINE stop -t 10 "$id" >/dev/null + exit 0 + fi +done +exit 1