From 20f2f00a607f445a5256414f5e93891f38a29530 Mon Sep 17 00:00:00 2001 From: Grbisba Date: Fri, 30 Oct 2026 12:25:56 +0300 Subject: [PATCH] =?UTF-8?q?=D0=9D=D0=B0=D1=87=D0=B0=D0=BB=D0=BE=20=D1=80?= =?UTF-8?q?=D0=B5=D0=B0=D0=BB=D0=B8=D0=B7=D0=B0=D1=86=D0=B8=D0=B8=20=D1=81?= =?UTF-8?q?=D0=B5=D1=80=D0=B2=D0=B8=D1=81=D0=B0.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Dockerfile | 32 ++ Makefile | 29 +- docker-compose.yml | 16 + service/cmd/app/main.go | 69 ++++ service/cmd/benchmark/main.go | 386 ++++++++++++++++++ service/go.mod | 36 ++ service/go.sum | 80 ++++ .../adapter/controller/http/chatHandler.go | 164 ++++++++ .../adapter/controller/http/controller.go | 102 +++++ .../adapter/controller/http/handler.go | 220 ++++++++++ .../adapter/controller/http/healthHandler.go | 37 ++ .../adapter/controller/http/router.go | 50 +++ .../adapter/controller/http/userHandler.go | 66 +++ .../repository/cache/inmemory/cache.go | 107 +++++ .../adapter/repository/cache/inmemory/chat.go | 149 +++++++ .../repository/cache/inmemory/message.go | 114 ++++++ .../adapter/repository/cache/inmemory/page.go | 28 ++ .../adapter/repository/cache/inmemory/user.go | 101 +++++ service/internal/config/abstractions.go | 7 + service/internal/config/application.go | 63 +++ service/internal/config/config.go | 121 ++++++ service/internal/config/cookies.go | 65 +++ service/internal/config/jwt.go | 48 +++ service/internal/config/postgres.go | 94 +++++ service/internal/config/redis.go | 64 +++ service/internal/config/server.go | 96 +++++ service/internal/config/validation.go | 11 + service/internal/dto/auth.go | 144 +++++++ service/internal/dto/chat.go | 20 + service/internal/dto/message.go | 21 + service/internal/dto/page.go | 9 + service/internal/dto/user.go | 19 + service/internal/gen/contracts/types.gen.go | 127 ++++++ service/internal/pkg/apperr/error.go | 122 ++++++ service/internal/pkg/auth/provider/claims.go | 143 +++++++ service/internal/pkg/auth/provider/cookie.go | 84 ++++ service/internal/pkg/auth/provider/error.go | 18 + .../internal/pkg/auth/provider/interface.go | 26 ++ service/internal/pkg/auth/provider/manager.go | 199 +++++++++ .../internal/pkg/auth/provider/provider.go | 182 +++++++++ service/internal/pkg/auth/provider/readers.go | 35 ++ service/internal/pkg/authidentity/status.go | 79 ++++ service/internal/pkg/authprovider/provider.go | 82 ++++ .../internal/pkg/environment/environment.go | 77 ++++ service/internal/pkg/error.go | 25 ++ service/internal/pkg/role/role.go | 105 +++++ service/internal/pkg/validator/validator.go | 29 ++ service/migrations/001_create_users_table.sql | 14 + .../002_create_refresh_tokens_table.sql | 19 + .../003_create_auth_identities_table.sql | 17 + service/tests/api_test.go | 239 +++++++++++ service/tests/concurrency_test.go | 162 ++++++++ 52 files changed, 4351 insertions(+), 1 deletion(-) create mode 100644 Dockerfile create mode 100644 docker-compose.yml create mode 100644 service/cmd/app/main.go create mode 100644 service/cmd/benchmark/main.go create mode 100644 service/go.mod create mode 100644 service/go.sum create mode 100644 service/internal/adapter/controller/http/chatHandler.go create mode 100644 service/internal/adapter/controller/http/controller.go create mode 100644 service/internal/adapter/controller/http/handler.go create mode 100644 service/internal/adapter/controller/http/healthHandler.go create mode 100644 service/internal/adapter/controller/http/router.go create mode 100644 service/internal/adapter/controller/http/userHandler.go create mode 100644 service/internal/adapter/repository/cache/inmemory/cache.go create mode 100644 service/internal/adapter/repository/cache/inmemory/chat.go create mode 100644 service/internal/adapter/repository/cache/inmemory/message.go create mode 100644 service/internal/adapter/repository/cache/inmemory/page.go create mode 100644 service/internal/adapter/repository/cache/inmemory/user.go create mode 100644 service/internal/config/abstractions.go create mode 100644 service/internal/config/application.go create mode 100644 service/internal/config/config.go create mode 100644 service/internal/config/cookies.go create mode 100644 service/internal/config/jwt.go create mode 100644 service/internal/config/postgres.go create mode 100644 service/internal/config/redis.go create mode 100644 service/internal/config/server.go create mode 100644 service/internal/config/validation.go create mode 100644 service/internal/dto/auth.go create mode 100644 service/internal/dto/chat.go create mode 100644 service/internal/dto/message.go create mode 100644 service/internal/dto/page.go create mode 100644 service/internal/dto/user.go create mode 100644 service/internal/gen/contracts/types.gen.go create mode 100644 service/internal/pkg/apperr/error.go create mode 100644 service/internal/pkg/auth/provider/claims.go create mode 100644 service/internal/pkg/auth/provider/cookie.go create mode 100644 service/internal/pkg/auth/provider/error.go create mode 100644 service/internal/pkg/auth/provider/interface.go create mode 100644 service/internal/pkg/auth/provider/manager.go create mode 100644 service/internal/pkg/auth/provider/provider.go create mode 100644 service/internal/pkg/auth/provider/readers.go create mode 100644 service/internal/pkg/authidentity/status.go create mode 100644 service/internal/pkg/authprovider/provider.go create mode 100644 service/internal/pkg/environment/environment.go create mode 100644 service/internal/pkg/error.go create mode 100644 service/internal/pkg/role/role.go create mode 100644 service/internal/pkg/validator/validator.go create mode 100644 service/migrations/001_create_users_table.sql create mode 100644 service/migrations/002_create_refresh_tokens_table.sql create mode 100644 service/migrations/003_create_auth_identities_table.sql create mode 100644 service/tests/api_test.go create mode 100644 service/tests/concurrency_test.go diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..a256b35 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,32 @@ +# syntax=docker/dockerfile:1 + +FROM --platform=$BUILDPLATFORM golang:1.27.2-alpine3.23 AS build + +WORKDIR /src + +COPY service/go.mod service/go.sum ./ +RUN go mod download + +COPY service/ ./ + +ARG TARGETOS +ARG TARGETARCH +RUN CGO_ENABLED=0 GOOS=$TARGETOS GOARCH=$TARGETARCH \ + go build -mod=readonly -trimpath -ldflags="-s -w" -o /out/messenger ./cmd/app + +FROM alpine:3.23.6 + +COPY --from=build --chmod=0555 /out/messenger /usr/local/bin/messenger + +ENV APP_HOST=0.0.0.0 \ + APP_PORT=8080 \ + APP_SHUTDOWN_TIMEOUT=8s + +USER 65532:65532 +EXPOSE 8080 +STOPSIGNAL SIGTERM + +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/messenger"] diff --git a/Makefile b/Makefile index 9ecb223..16af552 100644 --- a/Makefile +++ b/Makefile @@ -3,8 +3,12 @@ BASE_URL ?= http://localhost:8080 CA_FILE ?= ACTION_SCRIPT ?= TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",) +OPENAPI_SPEC := contracts/openapi.json +GEN_OUTPUT := service/internal/gen/contracts/types.gen.go +GEN_PACKAGE := contracts +OAPI_CODEGEN ?= $(shell go env GOPATH)/bin/oapi-codegen -.PHONY: help check validate test load test-persistence +.PHONY: help check validate test load test-persistence openapi-generate certs key-gen help: @echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes" @@ -24,3 +28,26 @@ load: test-persistence: @test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable restart hook"; exit 2) $(PYTHON) tests/resilience.py --mode persistence --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS) + +openapi-generate: + @mkdir -p $(dir $(GEN_OUTPUT)) + @echo "Generating Go types from $(OPENAPI_SPEC)..." + @set -o pipefail; \ + jq '(.components.schemas.ChatPage.properties.next_cursor.type, .components.schemas.MessagePage.properties.next_cursor.type) |= "string" | (.components.schemas.ChatPage.properties.next_cursor.nullable, .components.schemas.MessagePage.properties.next_cursor.nullable) = true' $(OPENAPI_SPEC) | \ + $(OAPI_CODEGEN) -generate types -package $(GEN_PACKAGE) -o $(GEN_OUTPUT) /dev/stdin + +key-gen: create-dir gen-private-key gen-public-key + +create-dir: + @mkdir -p certs +gen-private-key: + @openssl genrsa -out certs/private_key.pem 2048 +gen-public-key: + @openssl rsa -in certs/private_key.pem -pubout -outform PEM -out certs/public_key.pem + +certs: gen-key gen-crt + +gen-key: + @openssl genrsa -out ./certs/server.key 2048 +gen-crt: + @openssl req -new -x509 -key ./certs/server.key -out ./certs/server.crt -days 365 diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..11a4c26 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,16 @@ +services: + api: + build: + context: . + dockerfile: Dockerfile + image: mtusi-messenger:lab2 + environment: + APP_HOST: 0.0.0.0 + APP_PORT: "8080" + APP_READ_TIMEOUT: ${APP_READ_TIMEOUT:-5s} + APP_WRITE_TIMEOUT: ${APP_WRITE_TIMEOUT:-10s} + APP_IDLE_TIMEOUT: ${APP_IDLE_TIMEOUT:-60s} + APP_SHUTDOWN_TIMEOUT: ${APP_SHUTDOWN_TIMEOUT:-8s} + ports: + - "127.0.0.1:${HOST_PORT:-8080}:8080" + stop_grace_period: 10s diff --git a/service/cmd/app/main.go b/service/cmd/app/main.go new file mode 100644 index 0000000..2fa791b --- /dev/null +++ b/service/cmd/app/main.go @@ -0,0 +1,69 @@ +package main + +import ( + "context" + "fmt" + "log/slog" + "os" + "os/signal" + "syscall" + + "gitea.privcloud.tech/mtusi2026/internal/adapter/controller/http" + inmemory2 "gitea.privcloud.tech/mtusi2026/internal/adapter/repository/cache/inmemory" + "gitea.privcloud.tech/mtusi2026/internal/config" +) + +func main() { + if err := run(); err != nil { + slog.Error("application stopped", "error", err) + os.Exit(1) + } +} + +func run() error { + cfg, err := config.LoadServer() + if err != nil { + return fmt.Errorf("load server config: %w", err) + } + + router := http.NewRouter() + + userCache := inmemory2.NewUserCache() + chatCache := inmemory2.NewChatCache(userCache) + messageCache := inmemory2.NewMessageCache(chatCache) + + server := http.New(cfg, router) + + baseHandler := http.NewBaseHandler(router) + healthHandler := http.NewHealthHandler(baseHandler, server) + chatHandler := http.NewChatHandler(baseHandler, userCache, chatCache, messageCache) + userHandler := http.NewUserHandler(baseHandler, userCache) + + registerRoutes( + healthHandler, + chatHandler, + userHandler, + ) + + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer stop() + + if err := server.Start(ctx); err != nil { + return fmt.Errorf("start HTTP server: %w", err) + } + slog.Info("HTTP server started", "address", cfg.BindAddress()) + + <-ctx.Done() + shutdownCtx, cancel := context.WithTimeout(context.Background(), cfg.ShutdownTimeout) + defer cancel() + if err := server.Stop(shutdownCtx); err != nil { + return fmt.Errorf("stop HTTP server: %w", err) + } + return nil +} + +func registerRoutes(handlers ...http.Handler) { + for _, handler := range handlers { + handler.RegisterRoutes() + } +} diff --git a/service/cmd/benchmark/main.go b/service/cmd/benchmark/main.go new file mode 100644 index 0000000..13f8f20 --- /dev/null +++ b/service/cmd/benchmark/main.go @@ -0,0 +1,386 @@ +// Command benchmark measures the lab1 HTTP API in fresh, resource-limited containers. +package main + +import ( + "bytes" + "encoding/json" + "errors" + "flag" + "fmt" + "io" + "math" + "net/http" + "os" + "os/exec" + "path/filepath" + "slices" + "strconv" + "strings" + "sync" + "time" +) + +const ( + container = "mtusi-inmemory-benchmark" + baseURL = "http://127.0.0.1:18093" +) + +type runResult struct { + History int `json:"history"` + Concurrency int `json:"concurrency"` + Repetition int `json:"repetition"` + ElapsedSeconds float64 `json:"elapsed_seconds"` + ReadSuccess int `json:"read_success"` + WriteSuccess int `json:"write_success"` + Errors int `json:"errors"` + SuccessfulRPS float64 `json:"successful_rps"` + LatencyMS map[string]float64 `json:"latency_ms"` + RSSBeforeKiB int `json:"rss_kib_before"` + RSSPeakKiB int `json:"rss_kib_peak"` +} + +type report struct { + Image string `json:"image"` + Method map[string]any `json:"method"` + Runs []runResult `json:"runs"` +} + +type workerResult struct { + reads int + writes int + errors int + latencies []float64 +} + +type memoryResult struct { + peak int + err error +} + +func docker(args ...string) (string, error) { + command := exec.Command("docker", args...) + output, err := command.CombinedOutput() + if err != nil { + return "", fmt.Errorf("docker %s: %w: %s", strings.Join(args, " "), err, strings.TrimSpace(string(output))) + } + return strings.TrimSpace(string(output)), nil +} + +func rssKiB() (int, error) { + status, err := docker("exec", container, "cat", "/proc/1/status") + if err != nil { + return 0, err + } + for line := range strings.SplitSeq(status, "\n") { + if strings.HasPrefix(line, "VmRSS:") { + fields := strings.Fields(line) + return strconv.Atoi(fields[1]) + } + } + return 0, errors.New("VmRSS is unavailable") +} + +func newClient(timeout time.Duration) *http.Client { + return &http.Client{ + Timeout: timeout, + Transport: &http.Transport{ + MaxConnsPerHost: 1, + MaxIdleConnsPerHost: 1, + IdleConnTimeout: 30 * time.Second, + }, + } +} + +func request(client *http.Client, method, path, user string, body any) (map[string]any, error) { + var data io.Reader + if body != nil { + encoded, err := json.Marshal(body) + if err != nil { + return nil, err + } + data = bytes.NewReader(encoded) + } + req, err := http.NewRequest(method, baseURL+path, data) + if err != nil { + return nil, err + } + req.Header.Set("Accept", "application/json") + if user != "" { + req.Header.Set("X-User-Id", user) + } + if body != nil { + req.Header.Set("Content-Type", "application/json") + } + response, err := client.Do(req) + if err != nil { + return nil, err + } + defer response.Body.Close() + content, err := io.ReadAll(io.LimitReader(response.Body, 1<<20)) + if err != nil { + return nil, err + } + if response.StatusCode != http.StatusOK && response.StatusCode != http.StatusCreated { + return nil, fmt.Errorf("%s %s: HTTP %d: %s", method, path, response.StatusCode, content) + } + var payload map[string]any + if err := json.Unmarshal(content, &payload); err != nil { + return nil, err + } + return payload, nil +} + +func stringField(payload map[string]any, key string) (string, error) { + value, ok := payload[key].(string) + if !ok || value == "" { + return "", fmt.Errorf("missing %s in API response", key) + } + return value, nil +} + +func percentile(sorted []float64, proportion float64) float64 { + if len(sorted) == 0 { + return 0 + } + index := int(math.Ceil(float64(len(sorted))*proportion)) - 1 + if index < 0 { + index = 0 + } + return round(sorted[index], 3) +} + +func round(value float64, places int) float64 { + shift := math.Pow10(places) + return math.Round(value*shift) / shift +} + +func sampleMemory(stop <-chan struct{}, initial int, result chan<- memoryResult) { + ticker := time.NewTicker(250 * time.Millisecond) + defer ticker.Stop() + peak := initial + for { + select { + case <-stop: + result <- memoryResult{peak: peak} + return + case <-ticker.C: + rss, err := rssKiB() + if err != nil { + result <- memoryResult{err: err} + return + } + peak = max(peak, rss) + } + } +} + +func runCase(image string, history, concurrency, repetition int, duration time.Duration) (runResult, error) { + row := runResult{History: history, Concurrency: concurrency, Repetition: repetition} + if _, err := docker("run", "-d", "--name", container, "--cpus=1", "--memory=512m", + "-p", "127.0.0.1:18093:8080", image); err != nil { + return row, err + } + defer func() { _, _ = docker("rm", "-f", container) }() + + setup := newClient(2 * time.Second) + defer setup.CloseIdleConnections() + readyDeadline := time.Now().Add(20 * time.Second) + for { + if _, err := request(setup, http.MethodGet, "/health/ready", "", nil); err == nil { + break + } else if time.Now().After(readyDeadline) { + return row, fmt.Errorf("server did not become ready: %w", err) + } + time.Sleep(100 * time.Millisecond) + } + userResponse, err := request(setup, http.MethodPost, "/api/v1/users", "", map[string]any{ + "username": fmt.Sprintf("bench_%d_%d_%d", time.Now().UnixNano(), history, repetition), + "display_name": "Benchmark", + }) + if err != nil { + return row, err + } + user, err := stringField(userResponse, "id") + if err != nil { + return row, err + } + chatResponse, err := request(setup, http.MethodPost, "/api/v1/chats", user, map[string]any{ + "title": "Benchmark", "member_ids": []string{user}, + }) + if err != nil { + return row, err + } + chat, err := stringField(chatResponse, "id") + if err != nil { + return row, err + } + path := "/api/v1/chats/" + chat + "/messages" + for index := range history { + if _, err := request(setup, http.MethodPost, path, user, map[string]string{ + "text": fmt.Sprintf("seed-%d", index), + }); err != nil { + return row, fmt.Errorf("seed message %d: %w", index, err) + } + } + row.RSSBeforeKiB, err = rssKiB() + if err != nil { + return row, err + } + + start := make(chan struct{}) + results := make(chan workerResult, concurrency) + stopSampling := make(chan struct{}) + memory := make(chan memoryResult, 1) + go sampleMemory(stopSampling, row.RSSBeforeKiB, memory) + var group sync.WaitGroup + group.Add(concurrency) + deadline := time.Now().Add(duration) + started := time.Now() + for workerID := range concurrency { + go func() { + defer group.Done() + local := newClient(5 * time.Second) + defer local.CloseIdleConnections() + result := workerResult{} + <-start + for index := 0; time.Now().Before(deadline); index++ { + began := time.Now() + var err error + if index%10 == 0 { + _, err = request(local, http.MethodPost, path, user, map[string]string{ + "text": fmt.Sprintf("load-%d-%d-%d", repetition, workerID, index), + }) + if err == nil { + result.writes++ + } + } else { + var page map[string]any + page, err = request(local, http.MethodGet, path+"?limit=50", user, nil) + if err == nil { + items, ok := page["items"].([]any) + if !ok || len(items) != 50 { + err = errors.New("short first page") + } else { + result.reads++ + } + } + } + if err != nil { + result.errors++ + } else { + result.latencies = append(result.latencies, float64(time.Since(began).Microseconds())/1000) + } + } + results <- result + }() + } + close(start) + group.Wait() + row.ElapsedSeconds = round(time.Since(started).Seconds(), 3) + close(stopSampling) + memorySample := <-memory + if memorySample.err != nil { + return row, memorySample.err + } + row.RSSPeakKiB = memorySample.peak + if finalRSS, err := rssKiB(); err == nil { + row.RSSPeakKiB = max(row.RSSPeakKiB, finalRSS) + } else { + return row, err + } + latencies := make([]float64, 0) + for range concurrency { + result := <-results + row.ReadSuccess += result.reads + row.WriteSuccess += result.writes + row.Errors += result.errors + latencies = append(latencies, result.latencies...) + } + if len(latencies) == 0 { + return row, errors.New("no successful requests") + } + slices.Sort(latencies) + row.SuccessfulRPS = round(float64(len(latencies))/row.ElapsedSeconds, 2) + row.LatencyMS = map[string]float64{ + "p95": percentile(latencies, 0.95), + "p99": percentile(latencies, 0.99), + } + return row, nil +} + +func parseValues(raw string, minimum int) ([]int, error) { + values := make([]int, 0) + for part := range strings.SplitSeq(raw, ",") { + value, err := strconv.Atoi(strings.TrimSpace(part)) + if err != nil || value < minimum { + return nil, fmt.Errorf("invalid value %q", part) + } + values = append(values, value) + } + return values, nil +} + +func save(path string, data report) error { + encoded, err := json.MarshalIndent(data, "", " ") + if err != nil { + return err + } + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + return err + } + return os.WriteFile(path, append(encoded, '\n'), 0o644) +} + +func main() { + image := flag.String("image", "", "Docker image to benchmark") + output := flag.String("output", "", "JSON output path") + historiesArg := flag.String("histories", "100,500,1500", "Comma-separated history sizes") + concurrenciesArg := flag.String("concurrencies", "1,4,10", "Comma-separated client counts") + repeats := flag.Int("repeats", 3, "Runs per combination") + duration := flag.Duration("duration", 5*time.Second, "Measured duration per run") + flag.Parse() + if *image == "" || *output == "" || *repeats < 1 || *duration <= 0 { + fmt.Fprintln(os.Stderr, "image, output, positive repeats and duration are required") + os.Exit(2) + } + histories, err := parseValues(*historiesArg, 50) + if err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(2) + } + concurrencies, err := parseValues(*concurrenciesArg, 1) + if err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(2) + } + data := report{ + Image: *image, + Method: map[string]any{ + "histories": histories, "concurrencies": concurrencies, + "repeats": *repeats, "duration_seconds": duration.Seconds(), + "mix": "90% first-page GET, 10% POST per client; persistent HTTP connections", + "limits": "1 CPU, 512 MiB; fresh container and history per case", + "rss": "VmRSS from /proc/1/status every 250 ms (sampled peak)", + "latency": "successful requests only; errors counted separately; closed-loop workload", + }, + Runs: make([]runResult, 0, len(histories)*len(concurrencies)*(*repeats)), + } + for _, history := range histories { + for _, concurrency := range concurrencies { + for repetition := 1; repetition <= *repeats; repetition++ { + row, err := runCase(*image, history, concurrency, repetition, *duration) + if err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(1) + } + data.Runs = append(data.Runs, row) + if err := save(*output, data); err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(1) + } + encoded, _ := json.Marshal(row) + fmt.Println(string(encoded)) + } + } + } +} diff --git a/service/go.mod b/service/go.mod new file mode 100644 index 0000000..375905b --- /dev/null +++ b/service/go.mod @@ -0,0 +1,36 @@ +module gitea.privcloud.tech/mtusi2026 + +go 1.27.0 + +require ( + github.com/go-chi/chi/v5 v5.5.0 + github.com/go-playground/validator/v10 v10.30.5 + github.com/google/uuid v1.6.0 + github.com/oapi-codegen/runtime v1.4.2 + github.com/spf13/viper v1.21.0 +) + +require ( + github.com/cespare/xxhash/v2 v2.3.0 // indirect + github.com/fsnotify/fsnotify v1.9.0 // indirect + github.com/gabriel-vasile/mimetype v1.4.15 // indirect + github.com/go-playground/locales v0.14.1 // indirect + github.com/go-playground/universal-translator v0.18.1 // indirect + github.com/go-viper/mapstructure/v2 v2.4.0 // indirect + github.com/golang-jwt/jwt/v5 v5.3.1 // indirect + github.com/leodido/go-urn v1.5.0 // indirect + github.com/pelletier/go-toml/v2 v2.4.3-0.20260624044523-35f78d5908f1 // indirect + github.com/redis/go-redis/v9 v9.23.0 // indirect + github.com/sagikazarmark/locafero v0.11.0 // indirect + github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 // indirect + github.com/spf13/afero v1.15.0 // indirect + github.com/spf13/cast v1.10.0 // indirect + github.com/spf13/pflag v1.0.10 // indirect + github.com/subosito/gotenv v1.6.0 // indirect + go.uber.org/atomic v1.12.0 // indirect + go.uber.org/multierr v1.11.0 // indirect + go.yaml.in/yaml/v3 v3.0.5 // indirect + golang.org/x/crypto v0.57.0 // indirect + golang.org/x/sys v0.48.0 // indirect + golang.org/x/text v0.42.0 // indirect +) diff --git a/service/go.sum b/service/go.sum new file mode 100644 index 0000000..191dbec --- /dev/null +++ b/service/go.sum @@ -0,0 +1,80 @@ +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.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8= +github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0= +github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k= +github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0= +github.com/gabriel-vasile/mimetype v1.4.15 h1:05iP/CYtZ/w455R/KZM6rZ5ieAdh99UPtd+d3YzLmaI= +github.com/gabriel-vasile/mimetype v1.4.15/go.mod h1:azpTcoLcDZRNgFou5j+APrqQx9HqVPWa6ijYQIIVswQ= +github.com/go-chi/chi/v5 v5.5.0 h1:xdKQ1dJmVJsmgahrXSKhUx8NyVPzpwdlyrrQFpMPJgg= +github.com/go-chi/chi/v5 v5.5.0/go.mod h1:d1IG7GtKPSjPyBP365PH8sAGVHk3qfB/IhjFNRH1wWM= +github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s= +github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= +github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA= +github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= +github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY= +github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY= +github.com/go-playground/validator/v10 v10.30.5 h1:YyCXvVShZbs2Sm3Mb53eNOlhRXctSOzW5QJAouCTZL4= +github.com/go-playground/validator/v10 v10.30.5/go.mod h1:wEqiaov48pXX1kjhc3Da8y0M0Dtg/BK7gurFBLgwFrQ= +github.com/go-viper/mapstructure/v2 v2.4.0 h1:EBsztssimR/CONLSZZ04E8qAkxNYq4Qp9LvH92wZUgs= +github.com/go-viper/mapstructure/v2 v2.4.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM= +github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY= +github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE= +github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= +github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/leodido/go-urn v1.5.0 h1:pLqT2kq1zpHW/1D18QMjMpdtX7cekxqtJJjg5ANyWw0= +github.com/leodido/go-urn v1.5.0/go.mod h1:9BORnCDhdPBJNDEX+w1bJisa8yOKYi116VeO96s4ifE= +github.com/oapi-codegen/runtime v1.4.2 h1:GMxFVYLzoYLua+/KvzgSphkyK1lLTReQI9Vf4hvATKE= +github.com/oapi-codegen/runtime v1.4.2/go.mod h1:GwV7hC2hviaMzj+ITfHVRESK5J2W/GefVwIND/bMGvU= +github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4= +github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY= +github.com/pelletier/go-toml/v2 v2.4.3-0.20260624044523-35f78d5908f1 h1:gIZQQ2+wbsdQGWLPDSdJFptR25tBCjSC0KbSIQZ1rgE= +github.com/pelletier/go-toml/v2 v2.4.3-0.20260624044523-35f78d5908f1/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/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/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8= +github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= +github.com/sagikazarmark/locafero v0.11.0 h1:1iurJgmM9G3PA/I+wWYIOw/5SyBtxapeHDcg+AAIFXc= +github.com/sagikazarmark/locafero v0.11.0/go.mod h1:nVIGvgyzw595SUSUE6tvCp3YYTeHs15MvlmU87WwIik= +github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 h1:+jumHNA0Wrelhe64i8F6HNlS8pkoyMv5sreGx2Ry5Rw= +github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8/go.mod h1:3n1Cwaq1E1/1lhQhtRK2ts/ZwZEhjcQeJQ1RuC6Q/8U= +github.com/spf13/afero v1.15.0 h1:b/YBCLWAJdFWJTN9cLhiXXcD7mzKn9Dm86dNnfyQw1I= +github.com/spf13/afero v1.15.0/go.mod h1:NC2ByUVxtQs4b3sIUphxK0NioZnmxgyCrfzeuq8lxMg= +github.com/spf13/cast v1.10.0 h1:h2x0u2shc1QuLHfxi+cTJvs30+ZAHOGRic8uyGTDWxY= +github.com/spf13/cast v1.10.0/go.mod h1:jNfB8QC9IA6ZuY2ZjDp0KtFO2LZZlg4S/7bzP6qqeHo= +github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk= +github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +github.com/spf13/viper v1.21.0 h1:x5S+0EU27Lbphp4UKm1C+1oQO+rKx36vfCoaVebLFSU= +github.com/spf13/viper v1.21.0/go.mod h1:P0lhsswPGWD/1lZJ9ny3fYnVqxiegrlNrEmgLjbTCAY= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8= +github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU= +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.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= +go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= +go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc= +go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= +go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg= +golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M= +golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA= +golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo= +golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= +golang.org/x/text v0.42.0 h1:JbOZXgfeCPU9gacVtYliJqOhD+zhrEqK4LfdpmlUZqI= +golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo= +gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/service/internal/adapter/controller/http/chatHandler.go b/service/internal/adapter/controller/http/chatHandler.go new file mode 100644 index 0000000..b97fe8d --- /dev/null +++ b/service/internal/adapter/controller/http/chatHandler.go @@ -0,0 +1,164 @@ +package http + +import ( + "net/http" + + "github.com/google/uuid" + + inmemory2 "gitea.privcloud.tech/mtusi2026/internal/adapter/repository/cache/inmemory" + "gitea.privcloud.tech/mtusi2026/internal/dto" + "gitea.privcloud.tech/mtusi2026/internal/gen/contracts" +) + +type ChatHandler struct { + *BaseHandler + users inmemory2.UserCache + chats inmemory2.ChatCache + messages inmemory2.MessageCache +} + +func NewChatHandler(base *BaseHandler, users inmemory2.UserCache, chats inmemory2.ChatCache, messages inmemory2.MessageCache) Handler { + return &ChatHandler{BaseHandler: base, users: users, chats: chats, messages: messages} +} + +func (h *ChatHandler) RegisterRoutes() { + h.router.Post("/api/v1/chats", h.Create) + h.router.Get("/api/v1/chats", h.Get) + h.router.Get("/api/v1/chats/{chat_id}", h.GetByID) + h.router.Post("/api/v1/chats/{chat_id}/messages", h.SendMessage) + h.router.Get("/api/v1/chats/{chat_id}/messages", h.GetMessages) +} + +func (h *ChatHandler) Create(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() + user, ok := h.authenticatedUser(w, r, h.users) + if !ok { + return + } + var req contracts.CreateChat + if !h.Decode(w, r, &req) || !h.Validate(w, r, &req) { + return + } + chat, err := h.chats.Create(ctx, dto.CreateChat{ + CreatorID: user.ID, + Title: req.Title, + MemberIDs: req.MemberIds, + }) + if err != nil { + h.JSONError(ctx, w, err) + return + } + h.JSONResponse(w, http.StatusCreated, contractChat(chat)) +} + +func (h *ChatHandler) Get(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() + user, ok := h.authenticatedUser(w, r, h.users) + if !ok { + return + } + limit, afterID, ok := h.pageParams(w, r) + if !ok { + return + } + page, err := h.chats.ListForMember(ctx, user.ID, limit, afterID) + if err != nil { + h.JSONError(ctx, w, err) + return + } + items := make([]contracts.Chat, 0, len(page.Items)) + for _, chat := range page.Items { + items = append(items, contractChat(chat)) + } + h.JSONResponse(w, http.StatusOK, contracts.ChatPage{Items: items, NextCursor: cursorString(page.NextCursorID)}) +} + +func (h *ChatHandler) GetByID(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() + user, ok := h.authenticatedUser(w, r, h.users) + if !ok { + return + } + chatID, err := h.ParseIDFromPathParam(ctx, w, r, "chat_id") + if err != nil { + return + } + chat, err := h.chats.GetForMember(ctx, chatID, user.ID) + if err != nil { + h.JSONError(ctx, w, err) + return + } + h.JSONResponse(w, http.StatusOK, contractChat(chat)) +} + +func (h *ChatHandler) SendMessage(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() + user, ok := h.authenticatedUser(w, r, h.users) + if !ok { + return + } + chatID, err := h.ParseIDFromPathParam(ctx, w, r, "chat_id") + if err != nil { + return + } + if _, err := h.chats.GetForMember(ctx, chatID, user.ID); err != nil { + h.JSONError(ctx, w, err) + return + } + var req contracts.CreateMessage + if !h.Decode(w, r, &req) || !h.Validate(w, r, &req) { + return + } + message, err := h.messages.Create(ctx, dto.CreateMessage{ChatID: chatID, SenderID: user.ID, Text: req.Text}) + if err != nil { + h.JSONError(ctx, w, err) + return + } + h.JSONResponse(w, http.StatusCreated, contractMessage(message)) +} + +func (h *ChatHandler) GetMessages(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() + user, ok := h.authenticatedUser(w, r, h.users) + if !ok { + return + } + chatID, err := h.ParseIDFromPathParam(ctx, w, r, "chat_id") + if err != nil { + return + } + if _, err := h.chats.GetForMember(ctx, chatID, user.ID); err != nil { + h.JSONError(ctx, w, err) + return + } + limit, afterID, ok := h.pageParams(w, r) + if !ok { + return + } + page, err := h.messages.ListForChat(ctx, chatID, user.ID, limit, afterID) + if err != nil { + h.JSONError(ctx, w, err) + return + } + items := make([]contracts.Message, 0, len(page.Items)) + for _, message := range page.Items { + items = append(items, contractMessage(message)) + } + h.JSONResponse(w, http.StatusOK, contracts.MessagePage{Items: items, NextCursor: cursorString(page.NextCursorID)}) +} + +func contractChat(chat dto.Chat) contracts.Chat { + return contracts.Chat{Id: chat.ID, Title: chat.Title, MemberIds: chat.MemberIDs, CreatedAt: chat.CreatedAt} +} + +func contractMessage(message dto.Message) contracts.Message { + return contracts.Message{Id: message.ID, ChatId: message.ChatID, SenderId: message.SenderID, Text: message.Text, CreatedAt: message.CreatedAt} +} + +func cursorString(id *uuid.UUID) *string { + if id == nil { + return nil + } + value := id.String() + return &value +} diff --git a/service/internal/adapter/controller/http/controller.go b/service/internal/adapter/controller/http/controller.go new file mode 100644 index 0000000..5b262d2 --- /dev/null +++ b/service/internal/adapter/controller/http/controller.go @@ -0,0 +1,102 @@ +package http + +import ( + "context" + "errors" + "log/slog" + "net" + "net/http" + "sync/atomic" + + "github.com/go-chi/chi/v5" + + "gitea.privcloud.tech/mtusi2026/internal/config" +) + +type Server interface { + ShouldBeRunning() bool + Ready() bool + Start(ctx context.Context) error + Stop(ctx context.Context) error +} + +type server struct { + server http.Server + cfg *config.Server + ready atomic.Bool +} + +func New(cfg *config.Server, router chi.Router) Server { + s := server{ + server: http.Server{ + Addr: cfg.BindAddress(), + Handler: router, + ReadTimeout: cfg.ReadTimeout, + WriteTimeout: cfg.WriteTimeout, + IdleTimeout: cfg.IdleTimeout, + }, + cfg: cfg, + ready: atomic.Bool{}, + } + + if err := s.validate(); err != nil { + panic(err) + } + + return &s +} + +func (s *server) Start(_ context.Context) error { + if !s.ShouldBeRunning() { + slog.Info("server should not be running: skip starting") + return nil + } + listener, err := net.Listen("tcp", s.server.Addr) + if err != nil { + return err + } + + s.ready.Store(true) + go func() { + defer s.ready.Store(false) + if err := s.server.Serve(listener); err != nil && + !errors.Is(err, http.ErrServerClosed) { + slog.Error("rest server failed", "error", err) + } + }() + return nil +} + +func (s *server) Stop(ctx context.Context) error { + if !s.ShouldBeRunning() { + slog.Info("server should not be running: skip stopping") + return nil + } + + slog.Info("shutting down rest server...", "address", s.server.Addr) + s.ready.Store(false) + if err := s.server.Shutdown(ctx); err != nil { + slog.Error("rest server shutdown failed", "error", err) + return err + } + slog.Info("rest server shutdown successfully") + return nil +} + +func (s *server) ShouldBeRunning() bool { + return s.cfg.Enabled +} + +func (s *server) Ready() bool { + return s.ready.Load() +} + +func (s *server) validate() error { + if s.cfg == nil { + slog.Error("failed to validate server: provided nil config") + return errors.New("failed to validate server: provided nil config") + } + + slog.Info("server successfully validated") + return nil +} diff --git a/service/internal/adapter/controller/http/handler.go b/service/internal/adapter/controller/http/handler.go new file mode 100644 index 0000000..edde89c --- /dev/null +++ b/service/internal/adapter/controller/http/handler.go @@ -0,0 +1,220 @@ +package http + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "log/slog" + "mime" + "net/http" + "strconv" + "strings" + + "github.com/go-chi/chi/v5" + v10 "github.com/go-playground/validator/v10" + "github.com/google/uuid" + + "gitea.privcloud.tech/mtusi2026/internal/adapter/repository/cache/inmemory" + "gitea.privcloud.tech/mtusi2026/internal/dto" + "gitea.privcloud.tech/mtusi2026/internal/gen/contracts" + "gitea.privcloud.tech/mtusi2026/internal/pkg/apperr" + "gitea.privcloud.tech/mtusi2026/internal/pkg/validator" +) + +const ( + HeaderContentType = "Content-Type" + HeaderRequestID = "X-Request-Id" + HeaderUserID = "X-User-Id" +) + +type Handler interface { + RegisterRoutes() +} + +type BaseHandler struct { + router chi.Router + validator *validator.ValidatorImpl +} + +func NewBaseHandler(r chi.Router) *BaseHandler { + return &BaseHandler{ + router: r, + validator: validator.NewValidatorImpl(), + } +} + +func (h *BaseHandler) validate(ctx context.Context, value any) error { + err := h.validator.ValidateCtx(ctx, value) + if err == nil { + return nil + } + var fieldErrors v10.ValidationErrors + if errors.As(err, &fieldErrors) { + return apperr.Wrap(err, apperr.CodeInvalidRequest, "invalid request fields") + } + return apperr.Wrap(err, apperr.CodeInternalError, "validation failed") +} + +func (h *BaseHandler) Validate(w http.ResponseWriter, r *http.Request, value any) bool { + if err := h.validate(r.Context(), value); err != nil { + h.JSONError(r.Context(), w, err) + return false + } + return true +} + +func (h *BaseHandler) JSONResponse(w http.ResponseWriter, status int, body any) { + w.Header().Set(HeaderContentType, "application/json") + w.WriteHeader(status) + + if status == http.StatusNoContent { + return + } + + if err := json.NewEncoder(w).Encode(body); err != nil { + wrapped := apperr.Wrap(err, apperr.CodeInternal, "failed json encode") + slog.Error("response", "error", wrapped) + } +} + +func (h *BaseHandler) JSONError(ctx context.Context, w http.ResponseWriter, err error) { + if err == nil { + return + } + + requestId, ok := ctx.Value(HeaderRequestID).(uuid.UUID) + if !ok { + requestId = uuid.New() + } + w.Header().Set(HeaderRequestID, requestId.String()) + + appErr, ok := apperr.As(err) + if !ok { + appErr = apperr.New(apperr.CodeInternalError, "internal server error") + } + slog.Error("response", "error", err, "status", appErr.Code().HTTPStatus(), "requestId", requestId.String()) + h.JSONResponse(w, appErr.Code().HTTPStatus(), contracts.Error{ + Error: struct { + Code contracts.ErrorErrorCode `json:"code"` + Message string `json:"message"` + RequestId string `json:"request_id"` + }{ + Code: contracts.ErrorErrorCode(appErr.Code()), + Message: apperr.PublicMessage(appErr), + RequestId: requestId.String(), + }, + }) +} + +func (h *BaseHandler) Decode(w http.ResponseWriter, r *http.Request, object any) bool { + mediaType, params, err := mime.ParseMediaType(r.Header.Get(HeaderContentType)) + if err != nil || mediaType != "application/json" || + (params["charset"] != "" && !strings.EqualFold(params["charset"], "utf-8")) { + h.JSONError(r.Context(), w, apperr.New(apperr.CodeUnsupportedMediaType, "expected application/json")) + return false + } + decoder := json.NewDecoder(r.Body) + decoder.DisallowUnknownFields() + if err := decoder.Decode(object); err != nil { + h.JSONError(r.Context(), w, apperr.Wrap(err, apperr.CodeBadRequest, "failed decode")) + return false + } + var trailing any + if err := decoder.Decode(&trailing); err != io.EOF { + h.JSONError(r.Context(), w, apperr.New(apperr.CodeBadRequest, "expected one JSON object")) + return false + } + return true +} + +func (h *BaseHandler) PathParam(r *http.Request, key string) string { + return chi.URLParam(r, key) +} + +func (h *BaseHandler) QueryParam(r *http.Request, key string) string { + return r.URL.Query().Get(key) +} + +func (h *BaseHandler) HeaderParam(r *http.Request, key string) string { + return r.Header.Get(key) +} + +func (h *BaseHandler) ParseIDFromPathParam(ctx context.Context, w http.ResponseWriter, r *http.Request, key string) (uuid.UUID, error) { + rawID := h.PathParam(r, key) + id, err := uuid.Parse(rawID) + if err != nil { + h.JSONError(ctx, w, apperr.New(apperr.CodeValidation, fmt.Sprintf("provided invalid %s", key))) + return uuid.Nil, err + } + return id, nil +} + +func (h *BaseHandler) ParseIDFromQueryParam(ctx context.Context, w http.ResponseWriter, r *http.Request, key string) (uuid.UUID, error) { + rawID := h.QueryParam(r, key) + id, err := uuid.Parse(rawID) + if err != nil { + h.JSONError(ctx, w, apperr.New(apperr.CodeValidation, fmt.Sprintf("provided invalid %s", key))) + return uuid.Nil, err + } + return id, nil +} + +func (h *BaseHandler) ParseIDFromHeaderParam(ctx context.Context, w http.ResponseWriter, r *http.Request, key string) (uuid.UUID, error) { + rawID := h.HeaderParam(r, key) + id, err := uuid.Parse(rawID) + if err != nil { + h.JSONError(ctx, w, apperr.New(apperr.CodeUnauthorized, "missing or invalid user ID")) + return uuid.Nil, err + } + return id, nil +} + +func (h *BaseHandler) authenticatedUser(w http.ResponseWriter, r *http.Request, users inmemory.UserCache) (dto.User, bool) { + id, err := h.ParseIDFromHeaderParam(r.Context(), w, r, HeaderUserID) + if err != nil { + return dto.User{}, false + } + user, err := users.GetByID(r.Context(), id) + if err != nil { + if appErr, ok := apperr.As(err); ok && appErr.Code() == apperr.CodeNotFound { + h.JSONError(r.Context(), w, apperr.New(apperr.CodeUnauthorized, "unknown user ID")) + } else { + h.JSONError(r.Context(), w, err) + } + return dto.User{}, false + } + return user, true +} + +func (h *BaseHandler) pageParams(w http.ResponseWriter, r *http.Request) (*int, *uuid.UUID, bool) { + query := r.URL.Query() + var limit *int + if values, exists := query["limit"]; exists { + if len(values) != 1 { + h.JSONError(r.Context(), w, apperr.New(apperr.CodeInvalidRequest, "invalid limit")) + return nil, nil, false + } + value, err := strconv.Atoi(values[0]) + if err != nil || value < 1 || value > 100 { + h.JSONError(r.Context(), w, apperr.New(apperr.CodeInvalidRequest, "invalid limit")) + return nil, nil, false + } + limit = &value + } + var afterID *uuid.UUID + if values, exists := query["cursor"]; exists { + if len(values) != 1 { + h.JSONError(r.Context(), w, apperr.New(apperr.CodeInvalidRequest, "invalid cursor")) + return nil, nil, false + } + id, err := uuid.Parse(values[0]) + if err != nil || id == uuid.Nil { + h.JSONError(r.Context(), w, apperr.New(apperr.CodeInvalidRequest, "invalid cursor")) + return nil, nil, false + } + afterID = &id + } + return limit, afterID, true +} diff --git a/service/internal/adapter/controller/http/healthHandler.go b/service/internal/adapter/controller/http/healthHandler.go new file mode 100644 index 0000000..7f271a4 --- /dev/null +++ b/service/internal/adapter/controller/http/healthHandler.go @@ -0,0 +1,37 @@ +package http + +import ( + "net/http" + + "gitea.privcloud.tech/mtusi2026/internal/gen/contracts" + "gitea.privcloud.tech/mtusi2026/internal/pkg/apperr" +) + +type HealthHandler struct { + *BaseHandler + server Server +} + +func NewHealthHandler(base *BaseHandler, server Server) Handler { + return &HealthHandler{ + BaseHandler: base, + server: server, + } +} + +func (h *HealthHandler) RegisterRoutes() { + h.router.Get("/health/ready", h.Ready) + h.router.Get("/health/live", h.Live) +} + +func (h *HealthHandler) Live(w http.ResponseWriter, _ *http.Request) { + h.JSONResponse(w, http.StatusOK, contracts.Health{Status: contracts.Ok}) +} + +func (h *HealthHandler) Ready(w http.ResponseWriter, r *http.Request) { + if !h.server.Ready() { + h.JSONError(r.Context(), w, apperr.New(apperr.CodeUnavailable, "server is not ready")) + return + } + h.JSONResponse(w, http.StatusOK, contracts.Health{Status: contracts.Ok}) +} diff --git a/service/internal/adapter/controller/http/router.go b/service/internal/adapter/controller/http/router.go new file mode 100644 index 0000000..dea6375 --- /dev/null +++ b/service/internal/adapter/controller/http/router.go @@ -0,0 +1,50 @@ +package http + +import ( + "context" + "log/slog" + "net/http" + "time" + + "github.com/go-chi/chi/v5" + "github.com/go-chi/chi/v5/middleware" + "github.com/google/uuid" +) + +func NewRouter() chi.Router { + r := chi.NewRouter() + r.Use(requestIdMiddleware, loggingMiddleware) + return r +} + +func requestIdMiddleware(next http.Handler) http.Handler { + fn := func(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() + requestID := uuid.New() + w.Header().Set(HeaderRequestID, requestID.String()) + ctx = context.WithValue(ctx, HeaderRequestID, requestID) + next.ServeHTTP(w, r.WithContext(ctx)) + } + return http.HandlerFunc(fn) +} + +func loggingMiddleware(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + started := time.Now() + wrapped := middleware.NewWrapResponseWriter(w, r.ProtoMajor) + next.ServeHTTP(wrapped, r) + + status := wrapped.Status() + if status == 0 { + status = http.StatusOK + } + slog.InfoContext(r.Context(), "http request", + "method", r.Method, + "path", r.URL.Path, + "status", status, + "duration", time.Since(started), + "bytes", wrapped.BytesWritten(), + "request_id", w.Header().Get(HeaderRequestID), + ) + }) +} diff --git a/service/internal/adapter/controller/http/userHandler.go b/service/internal/adapter/controller/http/userHandler.go new file mode 100644 index 0000000..c73bd3b --- /dev/null +++ b/service/internal/adapter/controller/http/userHandler.go @@ -0,0 +1,66 @@ +package http + +import ( + "net/http" + + "gitea.privcloud.tech/mtusi2026/internal/adapter/repository/cache/inmemory" + "gitea.privcloud.tech/mtusi2026/internal/dto" + "gitea.privcloud.tech/mtusi2026/internal/gen/contracts" +) + +type UserHandler struct { + *BaseHandler + + users inmemory.UserCache +} + +func NewUserHandler(base *BaseHandler, users inmemory.UserCache) Handler { + return &UserHandler{ + BaseHandler: base, + users: users, + } +} + +func (h *UserHandler) RegisterRoutes() { + h.router.Post("/api/v1/users", h.Create) + h.router.Get("/api/v1/users/me", h.GetMe) +} + +func (h *UserHandler) Create(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() + + var req contracts.CreateUser + if !h.Decode(w, r, &req) || !h.Validate(w, r, &req) { + return + } + + user, err := h.users.Create(ctx, dto.CreateUser{ + Username: req.Username, + DisplayName: req.DisplayName, + }) + if err != nil { + h.JSONError(ctx, w, err) + return + } + + h.JSONResponse(w, http.StatusCreated, contracts.User{ + CreatedAt: user.CreatedAt, + DisplayName: user.DisplayName, + Id: user.ID, + Username: user.Username, + }) +} + +func (h *UserHandler) GetMe(w http.ResponseWriter, r *http.Request) { + user, ok := h.authenticatedUser(w, r, h.users) + if !ok { + return + } + + h.JSONResponse(w, http.StatusOK, contracts.User{ + CreatedAt: user.CreatedAt, + DisplayName: user.DisplayName, + Id: user.ID, + Username: user.Username, + }) +} diff --git a/service/internal/adapter/repository/cache/inmemory/cache.go b/service/internal/adapter/repository/cache/inmemory/cache.go new file mode 100644 index 0000000..1a17183 --- /dev/null +++ b/service/internal/adapter/repository/cache/inmemory/cache.go @@ -0,0 +1,107 @@ +package inmemory + +import ( + "log/slog" + "sync/atomic" + "unsafe" +) + +type Cache[K comparable, V any] interface { + Name() string + GetAll() map[K]V + GetList() []V + Get(key K) (value V, ok bool) + Find(predicate func(K, V) bool) []V +} + +type CopyAndWriteCache[K comparable, V any] struct { + name string + data unsafe.Pointer +} + +func NewCopyAndWriteCache[K comparable, V any]( + name string, +) *CopyAndWriteCache[K, V] { + c := CopyAndWriteCache[K, V]{ + name: name, + } + + emptyMap := make(map[K]V) + atomic.StorePointer(&c.data, unsafe.Pointer(&emptyMap)) + + slog.Info("cache initialized", "name", name) + + return &c +} + +func (c *CopyAndWriteCache[K, V]) Name() string { + return c.name +} + +func (c *CopyAndWriteCache[K, V]) GetAll() map[K]V { + ptr := atomic.LoadPointer(&c.data) + if ptr == nil { + return make(map[K]V) + } + + m := *(*map[K]V)(ptr) + + out := make(map[K]V, len(m)) + for k, v := range m { + out[k] = v + } + return out +} + +func (c *CopyAndWriteCache[K, V]) GetList() []V { + records := c.GetAll() + out := make([]V, 0, len(records)) + for _, record := range records { + out = append(out, record) + } + + return out +} + +func (c *CopyAndWriteCache[K, V]) Get(key K) (value V, ok bool) { + ptr := atomic.LoadPointer(&c.data) + if ptr == nil { + var zero V + return zero, false + } + + m := *(*map[K]V)(ptr) + v, ok := m[key] + return v, ok +} + +func (c *CopyAndWriteCache[K, V]) Find(predicate func(K, V) bool) []V { + ptr := atomic.LoadPointer(&c.data) + if ptr == nil { + return []V{} + } + + m := *(*map[K]V)(ptr) + + var result []V + for key, value := range m { + if predicate(key, value) { + result = append(result, value) + } + } + + return result +} + +func (c *CopyAndWriteCache[K, V]) Store(key K, value V) bool { + ptr := atomic.LoadPointer(&c.data) + if ptr == nil { + return false + } + + m := *(*map[K]V)(ptr) + + m[key] = value + + return true +} diff --git a/service/internal/adapter/repository/cache/inmemory/chat.go b/service/internal/adapter/repository/cache/inmemory/chat.go new file mode 100644 index 0000000..2f77e54 --- /dev/null +++ b/service/internal/adapter/repository/cache/inmemory/chat.go @@ -0,0 +1,149 @@ +package inmemory + +import ( + "context" + "slices" + "sort" + "strings" + "sync" + "time" + "unicode/utf8" + + "github.com/google/uuid" + + "gitea.privcloud.tech/mtusi2026/internal/dto" + "gitea.privcloud.tech/mtusi2026/internal/pkg/apperr" +) + +const chatCacheName = "CHATS_CACHE" + +type ChatCache interface { + Create(ctx context.Context, input dto.CreateChat) (dto.Chat, error) + GetForMember(ctx context.Context, chatID, userID uuid.UUID) (dto.Chat, error) + ListForMember(ctx context.Context, userID uuid.UUID, limit *int, afterID *uuid.UUID) (dto.Page[dto.Chat], error) +} + +type chatCache struct { + mu sync.RWMutex + store *CopyAndWriteCache[uuid.UUID, dto.Chat] + users UserCache +} + +func NewChatCache(users UserCache) ChatCache { + if users == nil { + panic("chat cache requires a user repository") + } + return &chatCache{ + store: NewCopyAndWriteCache[uuid.UUID, dto.Chat](chatCacheName), + users: users, + } +} + +func (c *chatCache) Create(ctx context.Context, input dto.CreateChat) (dto.Chat, error) { + if err := ctx.Err(); err != nil { + return dto.Chat{}, err + } + if strings.TrimSpace(input.Title) == "" || utf8.RuneCountInString(input.Title) > 100 || + len(input.MemberIDs) < 1 || len(input.MemberIDs) > 100 { + return dto.Chat{}, apperr.New(apperr.CodeInvalidRequest, "invalid chat fields") + } + + seen := make(map[uuid.UUID]struct{}, len(input.MemberIDs)) + for _, memberID := range input.MemberIDs { + if memberID == uuid.Nil { + return dto.Chat{}, apperr.New(apperr.CodeInvalidRequest, "invalid chat member") + } + if _, duplicate := seen[memberID]; duplicate { + return dto.Chat{}, apperr.New(apperr.CodeInvalidRequest, "duplicate chat member") + } + seen[memberID] = struct{}{} + if _, err := c.users.GetByID(ctx, memberID); err != nil { + if appErr, ok := apperr.As(err); ok && appErr.Code() == apperr.CodeNotFound { + return dto.Chat{}, apperr.New(apperr.CodeInvalidRequest, "unknown chat member") + } + return dto.Chat{}, err + } + } + if _, included := seen[input.CreatorID]; !included { + return dto.Chat{}, apperr.New(apperr.CodeInvalidRequest, "creator must be a chat member") + } + + id, err := uuid.NewRandom() + if err != nil { + return dto.Chat{}, apperr.Wrap(err, apperr.CodeInternalError, "generate chat ID") + } + chat := dto.Chat{ + ID: id, + Title: input.Title, + MemberIDs: append([]uuid.UUID(nil), input.MemberIDs...), + CreatedAt: time.Now().UTC(), + } + c.mu.Lock() + defer c.mu.Unlock() + if !c.store.Store(chat.ID, chat) { + return dto.Chat{}, apperr.New(apperr.CodeInternalError, "store chat") + } + return cloneChat(chat), nil +} + +func (c *chatCache) GetForMember(ctx context.Context, chatID, userID uuid.UUID) (dto.Chat, error) { + if err := ctx.Err(); err != nil { + return dto.Chat{}, err + } + c.mu.RLock() + defer c.mu.RUnlock() + chat, ok := c.store.Get(chatID) + if !ok || !slices.Contains(chat.MemberIDs, userID) { + return dto.Chat{}, apperr.New(apperr.CodeNotFound, "chat not found") + } + return cloneChat(chat), nil +} + +func (c *chatCache) ListForMember(ctx context.Context, userID uuid.UUID, limit *int, afterID *uuid.UUID) (dto.Page[dto.Chat], error) { + if err := ctx.Err(); err != nil { + return dto.Page[dto.Chat]{}, err + } + pageSize, err := pageLimit(limit) + if err != nil { + return dto.Page[dto.Chat]{}, err + } + + c.mu.RLock() + all := c.store.GetList() + chats := make([]dto.Chat, 0, len(all)) + for _, chat := range all { + if slices.Contains(chat.MemberIDs, userID) { + chats = append(chats, cloneChat(chat)) + } + } + c.mu.RUnlock() + + sort.Slice(chats, func(i, j int) bool { + return lessKey(chats[i].CreatedAt, chats[i].ID, chats[j].CreatedAt, chats[j].ID) + }) + start := 0 + if afterID != nil { + start = -1 + for i, chat := range chats { + if chat.ID == *afterID { + start = i + 1 + break + } + } + if start < 0 { + return dto.Page[dto.Chat]{}, apperr.New(apperr.CodeInvalidRequest, "invalid cursor") + } + } + end := min(start+pageSize, len(chats)) + page := dto.Page[dto.Chat]{Items: chats[start:end]} + if end < len(chats) { + id := chats[end-1].ID + page.NextCursorID = &id + } + return page, nil +} + +func cloneChat(chat dto.Chat) dto.Chat { + chat.MemberIDs = append([]uuid.UUID(nil), chat.MemberIDs...) + return chat +} diff --git a/service/internal/adapter/repository/cache/inmemory/message.go b/service/internal/adapter/repository/cache/inmemory/message.go new file mode 100644 index 0000000..1166002 --- /dev/null +++ b/service/internal/adapter/repository/cache/inmemory/message.go @@ -0,0 +1,114 @@ +package inmemory + +import ( + "context" + "sort" + "strings" + "sync" + "time" + "unicode/utf8" + + "github.com/google/uuid" + + "gitea.privcloud.tech/mtusi2026/internal/dto" + "gitea.privcloud.tech/mtusi2026/internal/pkg/apperr" +) + +const MessageCacheName = "MESSAGE_CACHE" + +type MessageCache interface { + Create(ctx context.Context, input dto.CreateMessage) (dto.Message, error) + ListForChat(ctx context.Context, chatID, userID uuid.UUID, limit *int, afterID *uuid.UUID) (dto.Page[dto.Message], error) +} + +type messageCache struct { + mu sync.RWMutex + store *CopyAndWriteCache[uuid.UUID, dto.Message] + byChat map[uuid.UUID][]dto.Message + chats ChatCache +} + +func NewMessageCache(chats ChatCache) MessageCache { + if chats == nil { + panic("message cache requires a chat repository") + } + return &messageCache{ + store: NewCopyAndWriteCache[uuid.UUID, dto.Message](MessageCacheName), + byChat: make(map[uuid.UUID][]dto.Message), + chats: chats, + } +} + +func (c *messageCache) Create(ctx context.Context, input dto.CreateMessage) (dto.Message, error) { + if err := ctx.Err(); err != nil { + return dto.Message{}, err + } + if _, err := c.chats.GetForMember(ctx, input.ChatID, input.SenderID); err != nil { + return dto.Message{}, err + } + if strings.TrimSpace(input.Text) == "" || utf8.RuneCountInString(input.Text) > 4000 { + return dto.Message{}, apperr.New(apperr.CodeInvalidRequest, "invalid message text") + } + + id, err := uuid.NewRandom() + if err != nil { + return dto.Message{}, apperr.Wrap(err, apperr.CodeInternalError, "generate message ID") + } + c.mu.Lock() + defer c.mu.Unlock() + message := dto.Message{ + ID: id, + ChatID: input.ChatID, + SenderID: input.SenderID, + Text: input.Text, + CreatedAt: time.Now().UTC(), + } + if !c.store.Store(message.ID, message) { + return dto.Message{}, apperr.New(apperr.CodeInternalError, "store message") + } + messages := c.byChat[message.ChatID] + index := sort.Search(len(messages), func(i int) bool { + return !lessKey(messages[i].CreatedAt, messages[i].ID, message.CreatedAt, message.ID) + }) + messages = append(messages, dto.Message{}) + copy(messages[index+1:], messages[index:]) + messages[index] = message + c.byChat[message.ChatID] = messages + return message, nil +} + +func (c *messageCache) ListForChat(ctx context.Context, chatID, userID uuid.UUID, limit *int, afterID *uuid.UUID) (dto.Page[dto.Message], error) { + if err := ctx.Err(); err != nil { + return dto.Page[dto.Message]{}, err + } + if _, err := c.chats.GetForMember(ctx, chatID, userID); err != nil { + return dto.Page[dto.Message]{}, err + } + pageSize, err := pageLimit(limit) + if err != nil { + return dto.Page[dto.Message]{}, err + } + + c.mu.RLock() + defer c.mu.RUnlock() + messages := c.byChat[chatID] + start := 0 + if afterID != nil { + cursor, ok := c.store.Get(*afterID) + if !ok || cursor.ChatID != chatID { + return dto.Page[dto.Message]{}, apperr.New(apperr.CodeInvalidRequest, "invalid cursor") + } + start = sort.Search(len(messages), func(i int) bool { + return lessKey(cursor.CreatedAt, cursor.ID, messages[i].CreatedAt, messages[i].ID) + }) + } + end := min(start+pageSize, len(messages)) + items := make([]dto.Message, end-start) + copy(items, messages[start:end]) + page := dto.Page[dto.Message]{Items: items} + if end < len(messages) { + id := messages[end-1].ID + page.NextCursorID = &id + } + return page, nil +} diff --git a/service/internal/adapter/repository/cache/inmemory/page.go b/service/internal/adapter/repository/cache/inmemory/page.go new file mode 100644 index 0000000..2fd04e2 --- /dev/null +++ b/service/internal/adapter/repository/cache/inmemory/page.go @@ -0,0 +1,28 @@ +package inmemory + +import ( + "bytes" + "time" + + "github.com/google/uuid" + + "gitea.privcloud.tech/mtusi2026/internal/pkg/apperr" +) + +func pageLimit(rawLimit *int) (int, error) { + limit := 50 + if rawLimit != nil { + limit = *rawLimit + } + if limit < 1 || limit > 100 { + return 0, apperr.New(apperr.CodeInvalidRequest, "invalid limit") + } + return limit, nil +} + +func lessKey(leftTime time.Time, leftID uuid.UUID, rightTime time.Time, rightID uuid.UUID) bool { + if !leftTime.Equal(rightTime) { + return leftTime.Before(rightTime) + } + return bytes.Compare(leftID[:], rightID[:]) < 0 +} diff --git a/service/internal/adapter/repository/cache/inmemory/user.go b/service/internal/adapter/repository/cache/inmemory/user.go new file mode 100644 index 0000000..cfaaa48 --- /dev/null +++ b/service/internal/adapter/repository/cache/inmemory/user.go @@ -0,0 +1,101 @@ +package inmemory + +import ( + "context" + "regexp" + "strings" + "sync" + "time" + "unicode/utf8" + + "github.com/google/uuid" + + "gitea.privcloud.tech/mtusi2026/internal/dto" + "gitea.privcloud.tech/mtusi2026/internal/pkg/apperr" +) + +const UserCacheName = "USERS_CACHE" + +var usernamePattern = regexp.MustCompile(`^[a-z0-9_]{3,32}$`) + +type UserCache interface { + Create(ctx context.Context, input dto.CreateUser) (dto.User, error) + GetByID(ctx context.Context, id uuid.UUID) (dto.User, error) + GetByUsername(ctx context.Context, username string) (dto.User, error) +} + +type userCache struct { + mu sync.RWMutex + store *CopyAndWriteCache[uuid.UUID, dto.User] + byUsername map[string]uuid.UUID +} + +func NewUserCache() UserCache { + return &userCache{ + store: NewCopyAndWriteCache[uuid.UUID, dto.User](UserCacheName), + byUsername: make(map[string]uuid.UUID), + } +} + +func (c *userCache) Create(ctx context.Context, input dto.CreateUser) (dto.User, error) { + if err := ctx.Err(); err != nil { + return dto.User{}, err + } + if !usernamePattern.MatchString(input.Username) || + strings.TrimSpace(input.DisplayName) == "" || + utf8.RuneCountInString(input.DisplayName) > 100 { + return dto.User{}, apperr.New(apperr.CodeInvalidRequest, "invalid user fields") + } + + c.mu.Lock() + defer c.mu.Unlock() + if _, exists := c.byUsername[input.Username]; exists { + return dto.User{}, apperr.New(apperr.CodeConflict, "username already exists") + } + + id, err := uuid.NewRandom() + if err != nil { + return dto.User{}, apperr.Wrap(err, apperr.CodeInternalError, "generate user ID") + } + user := dto.User{ + ID: id, + Username: input.Username, + DisplayName: input.DisplayName, + CreatedAt: time.Now().UTC(), + } + if !c.store.Store(user.ID, user) { + return dto.User{}, apperr.New(apperr.CodeInternalError, "store user") + } + c.byUsername[user.Username] = user.ID + return user, nil +} + +func (c *userCache) GetByID(ctx context.Context, id uuid.UUID) (dto.User, error) { + if err := ctx.Err(); err != nil { + return dto.User{}, err + } + c.mu.RLock() + defer c.mu.RUnlock() + user, ok := c.store.Get(id) + if !ok { + return dto.User{}, apperr.New(apperr.CodeNotFound, "user not found") + } + return user, nil +} + +func (c *userCache) GetByUsername(ctx context.Context, username string) (dto.User, error) { + if err := ctx.Err(); err != nil { + return dto.User{}, err + } + c.mu.RLock() + defer c.mu.RUnlock() + id, ok := c.byUsername[username] + if !ok { + return dto.User{}, apperr.New(apperr.CodeNotFound, "user not found") + } + user, ok := c.store.Get(id) + if !ok { + return dto.User{}, apperr.New(apperr.CodeInternalError, "user index is inconsistent") + } + return user, nil +} diff --git a/service/internal/config/abstractions.go b/service/internal/config/abstractions.go new file mode 100644 index 0000000..2490832 --- /dev/null +++ b/service/internal/config/abstractions.go @@ -0,0 +1,7 @@ +package config + +import "github.com/spf13/viper" + +type Loader interface { + loadConfig(v *viper.Viper) error +} diff --git a/service/internal/config/application.go b/service/internal/config/application.go new file mode 100644 index 0000000..07cbd8c --- /dev/null +++ b/service/internal/config/application.go @@ -0,0 +1,63 @@ +package config + +import ( + "errors" + "time" + + "github.com/spf13/viper" + + "gitea.privcloud.tech/mtusi2026/internal/pkg/environment" +) + +type Application struct { + LogLevel string + ShutdownTimeout time.Duration + Environment environment.ApplicationEnvironment + RequestRateLimit float64 + BurstRateLimit int + RateLimitTTL time.Duration +} + +func (c *Application) Validate() error { + environmentErr := c.Environment.Validate() + + switch { + case c.LogLevel == "": + return wrapValidationError("application", errors.New("log_level cannot be empty in application config")) + case c.ShutdownTimeout == 0: + return wrapValidationError("application", errors.New("shutdown_timeout cannot be zero in application config")) + case environmentErr != nil: + return wrapValidationError("application", environmentErr) + //case c.RequestRateLimit == 0: + // return wrapValidationError("application", errors.New("request_rate_limit cannot be zero in application config")) + //case c.BurstRateLimit == 0: + // return wrapValidationError("application", errors.New("burst_rate_limit cannot be zero in application config")) + //case c.RateLimitTTL == 0: + // return wrapValidationError("application", errors.New("rate_limit_ttl cannot be zero in application config")) + default: + return nil + } +} + +func (c *Application) loadConfig(v *viper.Viper) error { + v.SetEnvPrefix("APPLICATION") + c.LogLevel = v.GetString("LOG_LEVEL") + c.ShutdownTimeout = v.GetDuration("SHUTDOWN_TIMEOUT") + c.Environment = environment.ParseEnvironment(v.GetString("ENVIRONMENT")) + // todo add cool value + c.RequestRateLimit = v.GetFloat64("REQUEST_RATE_LIMIT") + c.BurstRateLimit = v.GetInt("BURST_RATE_LIMIT") + c.RateLimitTTL = v.GetDuration("RATE_LIMIT_TTL") + return nil +} + +func (c *Application) copy() *Application { + return &Application{ + LogLevel: c.LogLevel, + ShutdownTimeout: c.ShutdownTimeout, + Environment: c.Environment, + RequestRateLimit: c.RequestRateLimit, + BurstRateLimit: c.BurstRateLimit, + RateLimitTTL: c.RateLimitTTL, + } +} diff --git a/service/internal/config/config.go b/service/internal/config/config.go new file mode 100644 index 0000000..a7ee1a8 --- /dev/null +++ b/service/internal/config/config.go @@ -0,0 +1,121 @@ +package config + +import ( + "net/http" + "strings" + "time" + + "github.com/spf13/viper" + "go.uber.org/multierr" + + "gitea.privcloud.tech/mtusi2026/internal/pkg/environment" +) + +var defaultConfig = &Config{ + Server: &Server{ + Host: "localhost", + Port: 8001, + ReadTimeout: 10 * time.Second, + WriteTimeout: 10 * time.Second, + IdleTimeout: 10 * time.Second, + ShutdownTimeout: 10 * time.Second, + Enabled: false, + }, + Postgres: &Postgres{ + Host: "localhost", + Port: 5432, + User: "postgres", + Password: "postgres", + Database: "postgres", + VersionTable: "versions", + RunMigrations: false, + MaxConnections: 10, + }, + Redis: &Redis{ + Host: "localhost", + Port: 6379, + Username: "", + Password: "", + DB: 0, + }, + JWT: &JWT{ + AccessTokenLifetime: 4 * time.Hour, + RefreshTokenLifetime: 24 * time.Hour, + PublicKeyPath: "certs/private.pem", + PrivateKeyPath: "certs/public.pem", + }, + Cookies: &Cookies{ + Enabled: true, + Domain: "", + Path: "/", + Secure: true, + SameSite: http.SameSiteStrictMode, + AllowedOrigins: []string{"http:localhost:8080"}, + }, + Application: &Application{ + LogLevel: "info", + ShutdownTimeout: 10 * time.Second, + Environment: environment.ApplicationEnvironmentDev, + RequestRateLimit: 100, + }, +} + +type Config struct { + Server *Server + Postgres *Postgres + Redis *Redis + JWT *JWT + Cookies *Cookies + Application *Application +} + +func New() (*Config, error) { + v := viper.New() + v.SetEnvKeyReplacer(strings.NewReplacer(".", "_")) + v.AutomaticEnv() + + cfg := defaultConfig.copy() + + if err := cfg.loadConfig(v); err != nil { + return nil, err + } + + if err := cfg.Validate(); err != nil { + return nil, err + } + + return cfg, nil +} + +func (c *Config) Validate() error { + return multierr.Combine( + c.Server.Validate(), + c.Postgres.Validate(), + c.JWT.Validate(), + c.Redis.Validate(), + c.Cookies.Validate(), + c.Application.Validate(), + ) +} + +func (c *Config) loadConfig(v *viper.Viper) error { + return multierr.Combine( + c.Postgres.loadConfig(v), + c.Server.loadConfig(v), + c.JWT.loadConfig(v), + c.Redis.loadConfig(v), + c.Cookies.loadConfig(v), + c.Application.loadConfig(v), + ) +} + +func (c *Config) copy() *Config { + return &Config{ + Server: c.Server.copy(), + Postgres: c.Postgres.copy(), + Redis: c.Redis.copy(), + JWT: c.JWT.copy(), + Cookies: c.Cookies.copy(), + Application: c.Application.copy(), + } +} diff --git a/service/internal/config/cookies.go b/service/internal/config/cookies.go new file mode 100644 index 0000000..b6f7d88 --- /dev/null +++ b/service/internal/config/cookies.go @@ -0,0 +1,65 @@ +package config + +import ( + "errors" + "net/http" + "strings" + + "github.com/spf13/viper" +) + +type Cookies struct { + Enabled bool + Domain string + Path string + Secure bool + SameSite http.SameSite + AllowedOrigins []string +} + +func (c *Cookies) Validate() error { + switch { + case c.Domain == "": + return wrapValidationError("cookies", errors.New("domain cannot be empty")) + case c.Path == "": + return wrapValidationError("cookies", errors.New("path cannot be empty")) + case c.SameSite == http.SameSiteDefaultMode: + return wrapValidationError("cookies", errors.New("same_site_set_to_none_mode cannot be empty")) + //case c.Enabled && !c.Secure: + // return wrapValidationError("cookies", errors.New("if cookies_enabled equals true then cookies_secure must be true")) + case c.AllowedOrigins == nil || len(c.AllowedOrigins) == 0: + return wrapValidationError("cookies", errors.New("allowed_origins cannot be empty")) + default: + return nil + } +} + +func (c *Cookies) loadConfig(v *viper.Viper) error { + v.SetEnvPrefix("COOKIES") + c.Enabled = v.GetBool("ENABLED") + c.Domain = v.GetString("DOMAIN") + c.Path = v.GetString("PATH") + c.Secure = v.GetBool("SECURE") + c.AllowedOrigins = v.GetStringSlice("ALLOWED_ORIGINS") + sameSite := v.GetString("SAME_SITE") + switch strings.ToLower(strings.TrimSpace(sameSite)) { + case "strict": + c.SameSite = http.SameSiteStrictMode + case "none": + c.SameSite = http.SameSiteNoneMode + default: + c.SameSite = http.SameSiteLaxMode + } + return nil +} + +func (c *Cookies) copy() *Cookies { + return &Cookies{ + Enabled: c.Enabled, + Domain: c.Domain, + Path: c.Path, + Secure: c.Secure, + SameSite: c.SameSite, + AllowedOrigins: c.AllowedOrigins, + } +} diff --git a/service/internal/config/jwt.go b/service/internal/config/jwt.go new file mode 100644 index 0000000..f04eb8f --- /dev/null +++ b/service/internal/config/jwt.go @@ -0,0 +1,48 @@ +package config + +import ( + "errors" + "time" + + "github.com/spf13/viper" +) + +type JWT struct { + AccessTokenLifetime time.Duration + RefreshTokenLifetime time.Duration + PublicKeyPath string + PrivateKeyPath string +} + +func (c *JWT) Validate() error { + switch { + case c.AccessTokenLifetime == 0: + return wrapValidationError("jwt", errors.New("access_token_lifetime cannot be empty")) + case c.RefreshTokenLifetime == 0: + return wrapValidationError("jwt", errors.New("refresh_token_lifetime cannot be empty")) + case c.PrivateKeyPath == "": + return wrapValidationError("jwt", errors.New("private_key_path cannot be empty")) + case c.PublicKeyPath == "": + return wrapValidationError("jwt", errors.New("public_key_path cannot be empty")) + default: + return nil + } +} + +func (c *JWT) loadConfig(v *viper.Viper) error { + v.SetEnvPrefix("JWT") + c.AccessTokenLifetime = v.GetDuration("ACCESS_TOKEN_LIFETIME") + c.RefreshTokenLifetime = v.GetDuration("REFRESH_TOKEN_LIFETIME") + c.PublicKeyPath = v.GetString("PUBLIC_KEY_PATH") + c.PrivateKeyPath = v.GetString("PRIVATE_KEY_PATH") + return nil +} + +func (c *JWT) copy() *JWT { + return &JWT{ + AccessTokenLifetime: c.AccessTokenLifetime, + RefreshTokenLifetime: c.RefreshTokenLifetime, + PublicKeyPath: c.PublicKeyPath, + PrivateKeyPath: c.PrivateKeyPath, + } +} diff --git a/service/internal/config/postgres.go b/service/internal/config/postgres.go new file mode 100644 index 0000000..4f104ed --- /dev/null +++ b/service/internal/config/postgres.go @@ -0,0 +1,94 @@ +package config + +import ( + "errors" + "fmt" + + "github.com/spf13/viper" +) + +const ( + uri = "postgres://%s:%s@%s:%d/%s?sslmode=disable" +) + +type Postgres struct { + Host string + Port int + User string + Password string + Database string + VersionTable string + RunMigrations bool + MaxConnections int +} + +func (c *Postgres) Validate() error { + switch { + case c.Host == "": + return wrapValidationError("postgres", errors.New("host cannot be empty")) + case c.Port == 0: + return wrapValidationError("postgres", errors.New("port cannot be empty")) + case c.User == "": + return wrapValidationError("postgres", errors.New("user cannot be empty")) + case c.Password == "": + return wrapValidationError("postgres", errors.New("password cannot be empty")) + case c.Database == "": + return wrapValidationError("postgres", errors.New("database cannot be empty")) + case c.VersionTable == "": + return wrapValidationError("postgres", errors.New("version_table name cannot be empty")) + case c.MaxConnections == 0: + return wrapValidationError("postgres", errors.New("max_connections cannot be empty")) + default: + return nil + } +} + +func (c *Postgres) GetVersionTableName() string { + if c == nil { + return "" + } + return c.VersionTable +} + +func (c *Postgres) GetURI() string { + if c == nil { + return "" + } + return fmt.Sprintf(uri, c.User, c.Password, c.Host, c.Port, c.Database) +} + +func (c *Postgres) GetRunMigrations() bool { + if c == nil { + return false + } + return c.RunMigrations +} + +func (c *Postgres) loadConfig(v *viper.Viper) error { + v.SetEnvPrefix("POSTGRES") + c.Host = v.GetString("HOST") + c.Port = v.GetInt("PORT") + c.User = v.GetString("USER") + c.Password = v.GetString("PASSWORD") + c.Database = v.GetString("DATABASE") + c.VersionTable = v.GetString("VERSION_TABLE") + c.RunMigrations = v.GetBool("RUN_MIGRATIONS") + c.MaxConnections = v.GetInt("MAX_CONNECTIONS") + return nil +} + +func (c *Postgres) copy() *Postgres { + if c == nil { + return nil + } + return &Postgres{ + Host: c.Host, + Port: c.Port, + User: c.User, + Password: c.Password, + Database: c.Database, + MaxConnections: c.MaxConnections, + RunMigrations: c.RunMigrations, + VersionTable: c.VersionTable, + } +} diff --git a/service/internal/config/redis.go b/service/internal/config/redis.go new file mode 100644 index 0000000..7d844c5 --- /dev/null +++ b/service/internal/config/redis.go @@ -0,0 +1,64 @@ +package config + +import ( + "errors" + "fmt" + "net" + + "github.com/redis/go-redis/v9" + "github.com/spf13/viper" +) + +type Redis struct { + Host string + Port int + Username string + Password string + DB int +} + +func (c *Redis) Validate() error { + switch { + case c.Host == "": + return wrapValidationError("redis", errors.New("host cannot be empty")) + case c.Port == 0: + return wrapValidationError("redis", errors.New("port cannot be empty")) + default: + return nil + } +} + +func (c *Redis) BuildRedisOptions() *redis.Options { + if c == nil { + return nil + } + return &redis.Options{ + Addr: net.JoinHostPort(c.Host, fmt.Sprintf("%d", c.Port)), + Username: c.Username, + Password: c.Password, + DB: c.DB, + } +} + +func (c *Redis) loadConfig(v *viper.Viper) error { + v.SetEnvPrefix("REDIS") + c.Host = v.GetString("HOST") + c.Port = v.GetInt("PORT") + c.DB = v.GetInt("DB") + c.Password = v.GetString("PASSWORD") + c.Username = v.GetString("USERNAME") + return nil +} + +func (c *Redis) copy() *Redis { + if c == nil { + return nil + } + return &Redis{ + Host: c.Host, + Port: c.Port, + Username: c.Username, + Password: c.Password, + DB: c.DB, + } +} diff --git a/service/internal/config/server.go b/service/internal/config/server.go new file mode 100644 index 0000000..1ef30ca --- /dev/null +++ b/service/internal/config/server.go @@ -0,0 +1,96 @@ +package config + +import ( + "errors" + "fmt" + "time" + + "github.com/spf13/viper" +) + +type Server struct { + Host string + Port int + ReadTimeout time.Duration + WriteTimeout time.Duration + IdleTimeout time.Duration + ShutdownTimeout time.Duration + Enabled bool +} + +// LoadServer reads settings from environment variables and applies lab1 defaults. +func LoadServer() (*Server, error) { + v := viper.New() + v.SetEnvPrefix("APP") + v.AutomaticEnv() + v.SetDefault("HOST", "0.0.0.0") + v.SetDefault("PORT", 8080) + v.SetDefault("READ_TIMEOUT", "5s") + v.SetDefault("WRITE_TIMEOUT", "10s") + v.SetDefault("IDLE_TIMEOUT", "60s") + v.SetDefault("SHUTDOWN_TIMEOUT", "10s") + v.SetDefault("ENABLED", true) + + if err := v.BindEnv("HOST", "APP_HOST", "SERVER_HOST"); err != nil { + return nil, err + } + if err := v.BindEnv("PORT", "APP_PORT", "SERVER_PORT"); err != nil { + return nil, err + } + + cfg := new(Server) + if err := cfg.loadConfig(v); err != nil { + return nil, err + } + return cfg, nil +} + +func (c *Server) Validate() error { + if !c.Enabled { + return nil + } + switch { + case c.Host == "": + return wrapValidationError("server", errors.New("host cannot be empty")) + case c.Port == 0: + return wrapValidationError("server", errors.New("port cannot be empty")) + case c.ReadTimeout == 0: + return wrapValidationError("server", errors.New("read_timeout cannot be empty")) + case c.WriteTimeout == 0: + return wrapValidationError("server", errors.New("write_timeout cannot be empty")) + case c.IdleTimeout == 0: + return wrapValidationError("server", errors.New("idle_timeout cannot be empty")) + case c.ShutdownTimeout == 0: + return wrapValidationError("server", errors.New("shutdown_timeout name cannot be empty")) + default: + return nil + } +} + +func (c *Server) loadConfig(v *viper.Viper) error { + v.SetEnvPrefix("APP") + c.Host = v.GetString("HOST") + c.Port = v.GetInt("PORT") + c.ReadTimeout = v.GetDuration("READ_TIMEOUT") + c.WriteTimeout = v.GetDuration("WRITE_TIMEOUT") + c.IdleTimeout = v.GetDuration("IDLE_TIMEOUT") + c.ShutdownTimeout = v.GetDuration("SHUTDOWN_TIMEOUT") + c.Enabled = v.GetBool("ENABLED") + return c.Validate() +} + +func (c *Server) BindAddress() string { + return fmt.Sprintf("%s:%d", c.Host, c.Port) +} + +func (c *Server) copy() *Server { + return &Server{ + Host: c.Host, + Port: c.Port, + ReadTimeout: c.ReadTimeout, + WriteTimeout: c.WriteTimeout, + IdleTimeout: c.IdleTimeout, + ShutdownTimeout: c.ShutdownTimeout, + Enabled: c.Enabled, + } +} diff --git a/service/internal/config/validation.go b/service/internal/config/validation.go new file mode 100644 index 0000000..aeb4502 --- /dev/null +++ b/service/internal/config/validation.go @@ -0,0 +1,11 @@ +package config + +import "fmt" + +func wrapValidationError(name string, err error) error { + if err == nil { + return nil + } + + return fmt.Errorf("%s validation error: %w", name, err) +} diff --git a/service/internal/dto/auth.go b/service/internal/dto/auth.go new file mode 100644 index 0000000..747145a --- /dev/null +++ b/service/internal/dto/auth.go @@ -0,0 +1,144 @@ +package dto + +import ( + "errors" + "net/netip" + "time" + + "github.com/google/uuid" + + "gitea.privcloud.tech/mtusi2026/internal/pkg/authidentity" + "gitea.privcloud.tech/mtusi2026/internal/pkg/authprovider" + "gitea.privcloud.tech/mtusi2026/internal/pkg/role" +) + +// ---- Tokens ---- + +type UserDataInToken struct { + TokenID uuid.UUID + UserID uuid.UUID + Role role.Role + IsAccess bool + + PhoneNumber *string + Email *string + + ExpiresAt time.Time + IssuedAt time.Time +} + +func (u UserDataInToken) Validate() error { + if u.TokenID == uuid.Nil { + return errors.New("invalid token id") + } + if u.UserID == uuid.Nil { + return errors.New("invalid user id") + } + if !u.Role.IsValid() { + return errors.New("invalid role") + } + if u.ExpiresAt.IsZero() { + return errors.New("invalid expiry") + } + if u.IssuedAt.IsZero() { + return errors.New("invalid issued") + } + return nil +} + +type Token struct { + Payload string +} + +type ( + AccessToken Token + RefreshToken Token +) + +type Tokens struct { + AccessToken AccessToken + RefreshToken RefreshToken +} + +func (t AccessToken) Token() *Token { + return new(Token(t)) +} + +func (t RefreshToken) Token() *Token { + return new(Token(t)) +} + +type StoredRefreshToken struct { + ID uuid.UUID + UserID uuid.UUID + TokenHash string + UserAgent string + IPAddress netip.Addr + Role role.Role + ExpiresAt time.Time + RevokedAt *time.Time + CreatedAt time.Time +} + +type RevokeRefreshToken struct { + ID uuid.UUID + RevokedAt time.Time +} + +type RevokeRefreshTokensByUserID struct { + UserID uuid.UUID + RevokedAt time.Time +} + +// ---- Auth ---- + +type Login struct { + Email string + Password string +} + +type Register struct { + Email string + Password string + RepeatPassword string +} + +// ---- Auth Identities ---- + +type AuthIdentity struct { + ID uuid.UUID + Role role.Role + UserID uuid.UUID + Provider authprovider.Type + Identifier string + PasswordHash *string + Status authidentity.Status + CreatedAt time.Time + UpdatedAt time.Time +} +type UpdateAuthIdentity struct { + ID uuid.UUID + Role *role.Role + Provider *authprovider.Type + Identifier *string + PasswordHash *string + Status *authidentity.Status + UpdatedAt time.Time +} + +type UpdateAuthIdentityPasswordHash struct { + ID uuid.UUID + PasswordHash string + UpdatedAt time.Time +} + +type UpdateAuthIdentityStatus struct { + ID uuid.UUID + Status authidentity.Status + UpdatedAt time.Time +} + +type GetAuthIdentityByRoleAndUserID struct { + Role role.Role + UserID uuid.UUID +} diff --git a/service/internal/dto/chat.go b/service/internal/dto/chat.go new file mode 100644 index 0000000..733e107 --- /dev/null +++ b/service/internal/dto/chat.go @@ -0,0 +1,20 @@ +package dto + +import ( + "time" + + "github.com/google/uuid" +) + +type Chat struct { + ID uuid.UUID + Title string + MemberIDs []uuid.UUID + CreatedAt time.Time +} + +type CreateChat struct { + CreatorID uuid.UUID + Title string + MemberIDs []uuid.UUID +} diff --git a/service/internal/dto/message.go b/service/internal/dto/message.go new file mode 100644 index 0000000..8e503e3 --- /dev/null +++ b/service/internal/dto/message.go @@ -0,0 +1,21 @@ +package dto + +import ( + "time" + + "github.com/google/uuid" +) + +type Message struct { + ID uuid.UUID + ChatID uuid.UUID + SenderID uuid.UUID + Text string + CreatedAt time.Time +} + +type CreateMessage struct { + ChatID uuid.UUID + SenderID uuid.UUID + Text string +} diff --git a/service/internal/dto/page.go b/service/internal/dto/page.go new file mode 100644 index 0000000..de8b7a5 --- /dev/null +++ b/service/internal/dto/page.go @@ -0,0 +1,9 @@ +package dto + +import "github.com/google/uuid" + +// Page is a page of records with the ID to use for the next page. +type Page[T any] struct { + Items []T + NextCursorID *uuid.UUID +} diff --git a/service/internal/dto/user.go b/service/internal/dto/user.go new file mode 100644 index 0000000..8321572 --- /dev/null +++ b/service/internal/dto/user.go @@ -0,0 +1,19 @@ +package dto + +import ( + "time" + + "github.com/google/uuid" +) + +type User struct { + ID uuid.UUID + Username string + DisplayName string + CreatedAt time.Time +} + +type CreateUser struct { + Username string + DisplayName string +} diff --git a/service/internal/gen/contracts/types.gen.go b/service/internal/gen/contracts/types.gen.go new file mode 100644 index 0000000..117542e --- /dev/null +++ b/service/internal/gen/contracts/types.gen.go @@ -0,0 +1,127 @@ +// Package contracts provides primitives to interact with the openapi HTTP API. +// +// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.5.1 DO NOT EDIT. +package contracts + +import ( + "time" + + openapi_types "github.com/oapi-codegen/runtime/types" +) + +const ( + DevUserScopes = "devUser.Scopes" +) + +// Defines values for ErrorErrorCode. +const ( + Conflict ErrorErrorCode = "conflict" + InternalError ErrorErrorCode = "internal_error" + InvalidRequest ErrorErrorCode = "invalid_request" + NotFound ErrorErrorCode = "not_found" + PayloadTooLarge ErrorErrorCode = "payload_too_large" + RateLimited ErrorErrorCode = "rate_limited" + Unauthorized ErrorErrorCode = "unauthorized" + Unavailable ErrorErrorCode = "unavailable" + UnsupportedMediaType ErrorErrorCode = "unsupported_media_type" +) + +// Defines values for HealthStatus. +const ( + Ok HealthStatus = "ok" +) + +// Chat defines model for Chat. +type Chat struct { + CreatedAt time.Time `json:"created_at"` + Id openapi_types.UUID `json:"id"` + MemberIds []openapi_types.UUID `json:"member_ids"` + Title string `json:"title"` +} + +// ChatPage defines model for ChatPage. +type ChatPage struct { + Items []Chat `json:"items"` + NextCursor *string `json:"next_cursor"` +} + +// CreateChat defines model for CreateChat. +type CreateChat struct { + MemberIds []openapi_types.UUID `json:"member_ids"` + Title string `json:"title"` +} + +// CreateMessage defines model for CreateMessage. +type CreateMessage struct { + Text string `json:"text"` +} + +// CreateUser defines model for CreateUser. +type CreateUser struct { + DisplayName string `json:"display_name"` + Username string `json:"username"` +} + +// Error defines model for Error. +type Error struct { + Error struct { + Code ErrorErrorCode `json:"code"` + Message string `json:"message"` + RequestId string `json:"request_id"` + } `json:"error"` +} + +// ErrorErrorCode defines model for Error.Error.Code. +type ErrorErrorCode string + +// Health defines model for Health. +type Health struct { + Status HealthStatus `json:"status"` +} + +// HealthStatus defines model for Health.Status. +type HealthStatus string + +// Message defines model for Message. +type Message struct { + ChatId openapi_types.UUID `json:"chat_id"` + CreatedAt time.Time `json:"created_at"` + Id openapi_types.UUID `json:"id"` + SenderId openapi_types.UUID `json:"sender_id"` + Text string `json:"text"` +} + +// MessagePage defines model for MessagePage. +type MessagePage struct { + Items []Message `json:"items"` + NextCursor *string `json:"next_cursor"` +} + +// User defines model for User. +type User struct { + CreatedAt time.Time `json:"created_at"` + DisplayName string `json:"display_name"` + Id openapi_types.UUID `json:"id"` + Username string `json:"username"` +} + +// ListChatsParams defines parameters for ListChats. +type ListChatsParams struct { + Limit *int `form:"limit,omitempty" json:"limit,omitempty"` + Cursor *string `form:"cursor,omitempty" json:"cursor,omitempty"` +} + +// ListMessagesParams defines parameters for ListMessages. +type ListMessagesParams struct { + Limit *int `form:"limit,omitempty" json:"limit,omitempty"` + Cursor *string `form:"cursor,omitempty" json:"cursor,omitempty"` +} + +// CreateChatJSONRequestBody defines body for CreateChat for application/json ContentType. +type CreateChatJSONRequestBody = CreateChat + +// CreateMessageJSONRequestBody defines body for CreateMessage for application/json ContentType. +type CreateMessageJSONRequestBody = CreateMessage + +// RegisterUserJSONRequestBody defines body for RegisterUser for application/json ContentType. +type RegisterUserJSONRequestBody = CreateUser diff --git a/service/internal/pkg/apperr/error.go b/service/internal/pkg/apperr/error.go new file mode 100644 index 0000000..d45f71a --- /dev/null +++ b/service/internal/pkg/apperr/error.go @@ -0,0 +1,122 @@ +package apperr + +import ( + "errors" + "net/http" +) + +// Code is the machine-readable error code used by the API contract. +type Code string + +const ( + CodeInvalidRequest Code = "invalid_request" + CodeUnauthorized Code = "unauthorized" + CodeNotFound Code = "not_found" + CodeConflict Code = "conflict" + CodePayloadTooLarge Code = "payload_too_large" + CodeUnsupportedMediaType Code = "unsupported_media_type" + CodeRateLimited Code = "rate_limited" + CodeUnavailable Code = "unavailable" + CodeInternalError Code = "internal_error" + + CodeValidation Code = CodeInvalidRequest + CodeBadRequest Code = CodeInvalidRequest + CodeInternal Code = CodeInternalError +) + +func (c Code) HTTPStatus() int { + switch c { + case CodeInvalidRequest: + return http.StatusBadRequest + case CodeUnauthorized: + return http.StatusUnauthorized + case CodeNotFound: + return http.StatusNotFound + case CodeConflict: + return http.StatusConflict + case CodePayloadTooLarge: + return http.StatusRequestEntityTooLarge + case CodeUnsupportedMediaType: + return http.StatusUnsupportedMediaType + case CodeRateLimited: + return http.StatusTooManyRequests + case CodeUnavailable: + return http.StatusServiceUnavailable + default: + return http.StatusInternalServerError + } +} + +// AppError adds a public message and API code to an optional underlying error. +type AppError struct { + code Code + message string + cause error +} + +func New(code Code, message string) *AppError { + return &AppError{code: code, message: message} +} + +// Wrap returns nil for a nil cause. +func Wrap(err error, code Code, message string) error { + if err == nil { + return nil + } + return &AppError{code: code, message: message, cause: err} +} + +func (e *AppError) Error() string { + if e == nil { + return "" + } + if e.cause != nil { + return e.message + ": " + e.cause.Error() + } + return e.message +} + +func (e *AppError) Unwrap() error { + if e == nil { + return nil + } + return e.cause +} + +func (e *AppError) Code() Code { + if e == nil { + return CodeInternalError + } + return e.code +} + +func (e *AppError) Message() string { + if e == nil { + return "" + } + return e.message +} + +// As finds an AppError even when it is wrapped with fmt.Errorf("...: %w", err). +func As(err error) (*AppError, bool) { + var appErr *AppError + if !errors.As(err, &appErr) || appErr == nil { + return nil, false + } + return appErr, true +} + +// Root is retained for existing HTTP handler call sites. +func Root(err error) *AppError { + appErr, _ := As(err) + return appErr +} + +// PublicMessage never exposes an unknown error or the cause of a server error. +func PublicMessage(err error) string { + appErr, ok := As(err) + if !ok || appErr.Code().HTTPStatus() >= http.StatusInternalServerError { + return "internal server error" + } + return appErr.Message() +} diff --git a/service/internal/pkg/auth/provider/claims.go b/service/internal/pkg/auth/provider/claims.go new file mode 100644 index 0000000..895692b --- /dev/null +++ b/service/internal/pkg/auth/provider/claims.go @@ -0,0 +1,143 @@ +package provider + +import ( + "fmt" + "log/slog" + "time" + + "github.com/golang-jwt/jwt/v5" + "github.com/google/uuid" + + "gitea.privcloud.tech/mtusi2026/internal/dto" + "gitea.privcloud.tech/mtusi2026/internal/pkg/role" +) + +var _ Claims = (*jwtClaims)(nil) + +type Claims interface { + GetTopTokenID() (uuid.UUID, bool) + GetTopUserID() (uuid.UUID, bool) + GetTopRole() (role.Role, bool) + GetTopIsAccess() (bool, bool) + GetTopExpiresAt() (time.Time, bool) + GetTopIssuedAt() (time.Time, bool) +} + +type claimsParseFunc func(token *dto.Token) (*jwtClaims, error) + +type jwtClaims struct { + jwt.RegisteredClaims + + IsAccess bool `json:"is_access"` + Role role.Role `json:"role"` +} + +func (claims *jwtClaims) GetTopTokenID() (uuid.UUID, bool) { + parsed, err := uuid.Parse(claims.ID) + if err != nil { + return uuid.Nil, false + } + return parsed, true +} + +func (claims *jwtClaims) GetTopUserID() (uuid.UUID, bool) { + parsed, err := uuid.Parse(claims.Subject) + if err != nil { + return uuid.Nil, false + } + return parsed, true +} + +func (claims *jwtClaims) GetTopRole() (role.Role, bool) { + return claims.Role, true +} + +func (claims *jwtClaims) GetTopIsAccess() (bool, bool) { + return claims.IsAccess, true +} + +func (claims *jwtClaims) GetTopExpiresAt() (time.Time, bool) { + if claims.ExpiresAt == nil { + return time.Time{}, false + } + return claims.ExpiresAt.Time, true +} + +func (claims *jwtClaims) GetTopIssuedAt() (time.Time, bool) { + if claims.IssuedAt == nil { + return time.Time{}, false + } + return claims.IssuedAt.Time, true +} + +func (claims *jwtClaims) userData() (*dto.UserDataInToken, error) { + var u dto.UserDataInToken + + tokenID, err := uuid.Parse(claims.ID) + if err != nil { + return nil, fmt.Errorf("failed to parse token id: %w", err) + } + u.TokenID = tokenID + + userID, err := uuid.Parse(claims.Subject) + if err != nil { + return nil, fmt.Errorf("failed to parse user id from token %q: %w", claims.Subject, err) + } + u.UserID = userID + + u.Role = claims.Role + u.IsAccess = claims.IsAccess + + if claims.ExpiresAt != nil { + u.ExpiresAt = claims.ExpiresAt.Time + } + + if claims.IssuedAt != nil { + u.IssuedAt = claims.IssuedAt.Time + } + + return &u, nil +} + +func (p *provider) parseClaimsFromProtectedJWT(token *dto.Token) (*jwtClaims, error) { + if token == nil { + return nil, ErrTokenIsMissing + } + + claims := &jwtClaims{} + + parsed, err := jwt.ParseWithClaims( + token.Payload, + claims, + p.readKeyFunc, + ) + if err != nil { + slog.Error("failed to parse token with claims", "error", err) + return nil, ErrInvalidToken + } + + // todo ADD VALIDATION + + if !parsed.Valid { + slog.Error("failed to parse token: provided invalid token", "valid", parsed.Valid) + return nil, ErrInvalidToken + } + + return claims, nil +} + +func (p *provider) parseClaimsFromExposedJWT(token *dto.Token) (*jwtClaims, error) { + if token == nil { + return nil, ErrTokenIsMissing + } + + claims := &jwtClaims{} + + _, _, err := new(jwt.Parser).ParseUnverified(token.Payload, claims) + if err != nil { + slog.Error("failed to parse token: provided invalid token") + return nil, ErrInvalidToken + } + + return claims, nil +} diff --git a/service/internal/pkg/auth/provider/cookie.go b/service/internal/pkg/auth/provider/cookie.go new file mode 100644 index 0000000..0f1e1bf --- /dev/null +++ b/service/internal/pkg/auth/provider/cookie.go @@ -0,0 +1,84 @@ +package provider + +import ( + "net/http" +) + +const ( + accessTokenCookieKey = "auth-access-token" + refreshTokenCookieKey = "auth-refresh-token" + expiresAtCookieKey = "auth-exp" +) + +type CookieBuilderFabric struct { + fabric func() http.Cookie +} + +func newCookieBuilder( + domain string, + path string, + secure bool, + sameSite http.SameSite, +) *CookieBuilderFabric { + return &CookieBuilderFabric{ + fabric: newCookieFabric(domain, path, secure, sameSite), + } +} + +func (b *CookieBuilderFabric) Builder() *CookieBuilder { + return &CookieBuilder{ + cookie: b.fabric(), + } +} + +func newCookieFabric( + _ string, + path string, + secure bool, + sameSite http.SameSite) func() http.Cookie { + return func() http.Cookie { + return http.Cookie{ + Path: path, + Secure: secure, + SameSite: sameSite, + } + } +} + +type CookieBuilder struct { + cookie http.Cookie +} + +func (b *CookieBuilder) AccessName() *CookieBuilder { + b.cookie.Name = accessTokenCookieKey + return b +} + +func (b *CookieBuilder) ExpiresName() *CookieBuilder { + b.cookie.Name = expiresAtCookieKey + return b +} + +func (b *CookieBuilder) RefreshName() *CookieBuilder { + b.cookie.Name = refreshTokenCookieKey + return b +} + +func (b *CookieBuilder) Value(value string) *CookieBuilder { + b.cookie.Value = value + return b +} + +func (b *CookieBuilder) HTTPOnly() *CookieBuilder { + b.cookie.HttpOnly = true + return b +} + +func (b *CookieBuilder) MaxAge(maxAge int) *CookieBuilder { + b.cookie.MaxAge = maxAge + return b +} + +func (b *CookieBuilder) Build() *http.Cookie { + return new(b.cookie) +} diff --git a/service/internal/pkg/auth/provider/error.go b/service/internal/pkg/auth/provider/error.go new file mode 100644 index 0000000..180f210 --- /dev/null +++ b/service/internal/pkg/auth/provider/error.go @@ -0,0 +1,18 @@ +package provider + +import ( + "errors" +) + +var ( + ErrDecode = errors.New("failed to decode argument") + ErrNotFound = errors.New("not found") + ErrUnexpectedAlgorithm = errors.New("unexpected signing algorithm") + ErrTokenIsMissing = errors.New("token is missing") + ErrInvalidToken = errors.New("provided invalid token") + ErrInvalidUserDataInToken = errors.New("invalid user data in token") + ErrInvalidTokenClaims = errors.New("provided invalid token claims") + ErrInvalidBirthDateFormat = errors.New("provided invalid birth date format") + ErrTokenExpired = errors.New("token is expired") + ErrFailedToSign = errors.New("failed to sign jwt") +) diff --git a/service/internal/pkg/auth/provider/interface.go b/service/internal/pkg/auth/provider/interface.go new file mode 100644 index 0000000..c131be2 --- /dev/null +++ b/service/internal/pkg/auth/provider/interface.go @@ -0,0 +1,26 @@ +package provider + +import ( + "net/http" + + "github.com/google/uuid" + + "gitea.privcloud.tech/mtusi2026/internal/dto" + "gitea.privcloud.tech/mtusi2026/internal/pkg/role" +) + +type Provider interface { + Parse(token *dto.Token) (*dto.UserDataInToken, error) + CreateRefreshAndAccessTokensForUser(userID uuid.UUID, role role.Role) (*dto.Tokens, error) + ParseVerified(token *dto.Token) (*dto.UserDataInToken, error) + ParseUnverified(token *dto.Token) (*dto.UserDataInToken, error) + ValidateUserDataInToken(u *dto.UserDataInToken) error +} + +type Cookie interface { + Enabled() bool + Set(w http.ResponseWriter, tokens *dto.Tokens) + Clear(w http.ResponseWriter) + AccessToken(r *http.Request) *dto.AccessToken + RefreshToken(r *http.Request) *dto.RefreshToken +} diff --git a/service/internal/pkg/auth/provider/manager.go b/service/internal/pkg/auth/provider/manager.go new file mode 100644 index 0000000..dcb0072 --- /dev/null +++ b/service/internal/pkg/auth/provider/manager.go @@ -0,0 +1,199 @@ +package provider + +import ( + "fmt" + "net/http" + "strconv" + "time" + + "gitea.privcloud.tech/mtusi2026/internal/config" + "gitea.privcloud.tech/mtusi2026/internal/dto" +) + +type manager struct { + enabled bool + cookieFabric *CookieBuilderFabric + prv Provider +} + +func NewCookieManager(cfg *config.Config, provider Provider) Cookie { + m := &manager{ + enabled: cfg.Cookies.Enabled, + cookieFabric: newCookieBuilder( + cfg.Cookies.Domain, + cfg.Cookies.Path, + cfg.Cookies.Secure, + cfg.Cookies.SameSite, + ), + prv: provider, + } + + if !m.enabled { + return m + } + + if err := m.cookieFabric. + Builder(). + AccessName(). + Value("test"). + HTTPOnly(). + MaxAge(0). + Build(). + Valid(); err != nil { + panic(fmt.Errorf("cookie validation failed: %w", err)) + } + + return m +} + +func (m *manager) Enabled() bool { + return m.enabled +} + +func (m *manager) Set(w http.ResponseWriter, tokens *dto.Tokens) { + if !m.enabled || tokens == nil { + return + } + + if tokens.AccessToken.Payload != "" { + m.setAccess(tokens.AccessToken, w) + } + + if tokens.RefreshToken.Payload != "" { + m.setRefresh(tokens.RefreshToken, w) + } +} + +func (m *manager) Clear(w http.ResponseWriter) { + if !m.enabled { + return + } + + for _, name := range []string{accessTokenCookieKey, refreshTokenCookieKey, expiresAtCookieKey} { + b := m.cookieFabric. + Builder(). + MaxAge(-1) + + switch name { + case expiresAtCookieKey: + b.ExpiresName() + case refreshTokenCookieKey: + b.RefreshName(). + HTTPOnly() + case accessTokenCookieKey: + b.AccessName(). + HTTPOnly() + } + http.SetCookie(w, b.Build()) + } +} + +func (m *manager) AccessToken(r *http.Request) *dto.AccessToken { + if !m.enabled { + return nil + } + + c, err := r.Cookie(accessTokenCookieKey) + if err != nil { + return nil + } + + return &dto.AccessToken{ + Payload: c.Value, + } +} + +func (m *manager) RefreshToken(r *http.Request) *dto.RefreshToken { + if !m.enabled { + return nil + } + + c, err := r.Cookie(refreshTokenCookieKey) + if err != nil { + return nil + } + + return &dto.RefreshToken{ + Payload: c.Value, + } +} + +func (m *manager) setAccess(token dto.AccessToken, w http.ResponseWriter) { + accessTTL := m.tokenTTL(token.Token()) + if accessTTL < 0 { + http.SetCookie(w, m.cookieFabric. + Builder(). + AccessName(). + HTTPOnly(). + MaxAge(-1). + Build(), + ) + http.SetCookie(w, m.cookieFabric. + Builder(). + ExpiresName(). + MaxAge(-1). + Build(), + ) + } else if tokenExpiresAt := m.tokenExpiry(token.Token()); !tokenExpiresAt.IsZero() { + http.SetCookie(w, m.cookieFabric. + Builder(). + AccessName(). + Value(token.Payload). + HTTPOnly(). + MaxAge(accessTTL). + Build(), + ) + http.SetCookie(w, m.cookieFabric. + Builder(). + ExpiresName(). + Value(strconv.FormatInt(tokenExpiresAt.Unix(), 10)). + MaxAge(accessTTL). + Build(), + ) + } +} + +func (m *manager) setRefresh(token dto.RefreshToken, w http.ResponseWriter) { + refreshTTL := m.tokenTTL(token.Token()) + if refreshTTL < 0 { + http.SetCookie(w, m.cookieFabric. + Builder(). + RefreshName(). + HTTPOnly(). + MaxAge(-1). + Build(), + ) + } else { + http.SetCookie(w, m.cookieFabric. + Builder(). + RefreshName(). + Value(token.Payload). + HTTPOnly(). + MaxAge(refreshTTL). + Build(), + ) + } +} + +func (m *manager) tokenTTL(token *dto.Token) int { + expiresAt := m.tokenExpiry(token) + + if expiresAt.IsZero() { + return -1 + } + + ttl := int(time.Until(expiresAt).Seconds()) + if ttl <= 0 { + return -1 + } + + return ttl +} + +func (m *manager) tokenExpiry(token *dto.Token) time.Time { + data, err := m.prv.ParseUnverified(token) + if err != nil { + return time.Time{} + } + return data.ExpiresAt +} diff --git a/service/internal/pkg/auth/provider/provider.go b/service/internal/pkg/auth/provider/provider.go new file mode 100644 index 0000000..87e74c2 --- /dev/null +++ b/service/internal/pkg/auth/provider/provider.go @@ -0,0 +1,182 @@ +package provider + +import ( + "crypto/rsa" + "fmt" + "log/slog" + "time" + + "github.com/golang-jwt/jwt/v5" + "github.com/google/uuid" + + "gitea.privcloud.tech/mtusi2026/internal/config" + "gitea.privcloud.tech/mtusi2026/internal/dto" + "gitea.privcloud.tech/mtusi2026/internal/pkg/environment" + "gitea.privcloud.tech/mtusi2026/internal/pkg/role" +) + +var ( + _ Provider = (*provider)(nil) +) + +type provider struct { + accessLifetime time.Duration + refreshLifetime time.Duration + publicKey *rsa.PublicKey + privateKey *rsa.PrivateKey + parseFunc claimsParseFunc +} + +func New(cfg *config.Config) Provider { + p := provider{ + accessLifetime: cfg.JWT.AccessTokenLifetime, + refreshLifetime: cfg.JWT.RefreshTokenLifetime, + } + p.parseFunc = p.parseClaimsFromProtectedJWT + + if cfg.Application.Environment == environment.ApplicationEnvironmentDev { + p.parseFunc = p.parseClaimsFromExposedJWT + } + + var err error + if p.publicKey, err = readPublicKeyFromFile(cfg.JWT.PublicKeyPath); err != nil { + slog.Error("failed to read public key", "error", err) + panic(fmt.Errorf("failed to read public key: %w", err)) + } + if p.privateKey, err = readPrivateKeyFromFile(cfg.JWT.PrivateKeyPath); err != nil { + slog.Error("failed to read private key", "error", err) + panic(fmt.Errorf("failed to read private key: %w", err)) + } + + return &p +} + +func (p *provider) Parse(token *dto.Token) (*dto.UserDataInToken, error) { + claims, err := p.parseFunc(token) + if err != nil { + return nil, err + } + return claims.userData() +} + +func (p *provider) ParseUnverified(t *dto.Token) (*dto.UserDataInToken, error) { + if t == nil { + return nil, ErrTokenIsMissing + } + + claims, err := p.parseClaimsFromExposedJWT(t) + if err != nil { + return nil, err + } + + return claims.userData() +} + +func (p *provider) ParseVerified(t *dto.Token) (*dto.UserDataInToken, error) { + if t == nil { + return nil, ErrTokenIsMissing + } + claims, err := p.parseFunc(t) + if err != nil { + return nil, fmt.Errorf("failed to parse token: %w", err) + } + + return claims.userData() +} + +func (p *provider) CreateAccessTokenForUser(userID uuid.UUID, role role.Role) (*dto.AccessToken, error) { + t, err := p.createTokenForUser(userID, true, role) + if err != nil { + return nil, err + } + return &dto.AccessToken{ + Payload: t.Payload, + }, nil +} + +func (p *provider) CreateRefreshTokenForUser(userID uuid.UUID, role role.Role) (*dto.RefreshToken, error) { + t, err := p.createTokenForUser(userID, false, role) + if err != nil { + return nil, err + } + return &dto.RefreshToken{ + Payload: t.Payload, + }, nil +} + +func (p *provider) CreateRefreshAndAccessTokensForUser(userID uuid.UUID, role role.Role) (*dto.Tokens, error) { + access, err := p.CreateAccessTokenForUser(userID, role) + if err != nil { + return nil, err + } + refresh, err := p.CreateRefreshTokenForUser(userID, role) + if err != nil { + return nil, err + } + return &dto.Tokens{ + AccessToken: *access, + RefreshToken: *refresh, + }, nil +} + +func (p *provider) createTokenForUser(userID uuid.UUID, isAccess bool, role role.Role) (*dto.Token, error) { + now := time.Now() + var tokenExpiresAt time.Time + if isAccess { + tokenExpiresAt = now.Add(p.accessLifetime) + } else { + tokenExpiresAt = now.Add(p.refreshLifetime) + } + claims := &jwtClaims{ + RegisteredClaims: jwt.RegisteredClaims{ + Subject: userID.String(), + ExpiresAt: jwt.NewNumericDate(tokenExpiresAt), + NotBefore: jwt.NewNumericDate(now), + IssuedAt: jwt.NewNumericDate(now), + ID: uuid.NewString(), + }, + IsAccess: isAccess, + Role: role, + } + t := jwt.NewWithClaims(jwt.SigningMethodRS256, claims) + + payload, err := t.SignedString(p.privateKey) + if err != nil { + slog.Error("failed to sign jwt", "error", err) + return nil, ErrFailedToSign + } + return &dto.Token{Payload: payload}, nil +} + +// TODO refactor maybe delete +func (p *provider) ValidateUserDataInToken(u *dto.UserDataInToken) error { + if u == nil { + return ErrInvalidUserDataInToken + } + + switch { + case u.TokenID == uuid.Nil: + return fmt.Errorf("%w: unexpected nil token id", ErrInvalidUserDataInToken) + case u.UserID == uuid.Nil: + return fmt.Errorf("%w: unexpected nil user id", ErrInvalidUserDataInToken) + case u.IssuedAt.IsZero(): + return fmt.Errorf("%w: unexpected zero issued at", ErrInvalidUserDataInToken) + case u.Email != nil && *u.Email == "": + return fmt.Errorf("%w: unexpected empty email", ErrInvalidUserDataInToken) + case u.PhoneNumber != nil && *u.PhoneNumber == "": + return fmt.Errorf("%w: unexpected empty phone number", ErrInvalidUserDataInToken) + case u.ExpiresAt.IsZero(): + return fmt.Errorf("%w: unexpected zero expires at", ErrInvalidUserDataInToken) + } + + return nil +} + +func (p *provider) readKeyFunc(token *jwt.Token) (interface{}, error) { + switch token.Method.(type) { + case *jwt.SigningMethodRSA: + return p.publicKey, nil + default: + return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"]) + } +} diff --git a/service/internal/pkg/auth/provider/readers.go b/service/internal/pkg/auth/provider/readers.go new file mode 100644 index 0000000..75456c2 --- /dev/null +++ b/service/internal/pkg/auth/provider/readers.go @@ -0,0 +1,35 @@ +package provider + +import ( + "crypto/rsa" + "fmt" + "os" + + "github.com/golang-jwt/jwt/v5" +) + +func readPrivateKeyFromFile(path string) (*rsa.PrivateKey, error) { + key, err := os.ReadFile(path) + if err != nil { + return nil, fmt.Errorf("failed to read public key: %w", err) + } + + privateKey, err := jwt.ParseRSAPrivateKeyFromPEM(key) + if err != nil { + return nil, fmt.Errorf("failed to parse private key: %w", err) + } + return privateKey, nil +} + +func readPublicKeyFromFile(path string) (*rsa.PublicKey, error) { + key, err := os.ReadFile(path) + if err != nil { + return nil, fmt.Errorf("failed to read public key: %w", err) + } + + privateKey, err := jwt.ParseRSAPublicKeyFromPEM(key) + if err != nil { + return nil, fmt.Errorf("failed to parse private key: %w", err) + } + return privateKey, nil +} diff --git a/service/internal/pkg/authidentity/status.go b/service/internal/pkg/authidentity/status.go new file mode 100644 index 0000000..c6a1708 --- /dev/null +++ b/service/internal/pkg/authidentity/status.go @@ -0,0 +1,79 @@ +package authidentity + +import ( + "encoding/json" + "strings" + + "git.dev.mamont-optics.ru/mamont-optics/backend/application/internal/pkg/types" +) + +type Status string + +const ( + StatusUndefined Status = "UNDEFINED" + StatusPending Status = "PENDING" + StatusActive Status = "ACTIVE" + StatusBlocked Status = "BLOCKED" +) + +var allowedStatuses = map[Status]struct{}{ + StatusUndefined: {}, + StatusPending: {}, + StatusActive: {}, + StatusBlocked: {}, +} + +func ParseStatus(status string) Status { + s := Status(strings.ToUpper(status)) + if !s.IsValid() { + return StatusUndefined + } + return s +} + +func ParseAndValidateStatus(status string) (Status, error) { + parsed := ParseStatus(status) + if _, ok := allowedStatuses[parsed]; ok { + return parsed, nil + } + return StatusUndefined, types.ErrUnsupportedAuthIdentityStatus +} + +func (t Status) String() string { + return string(t) +} + +func (t Status) Validate() error { + if _, ok := allowedStatuses[t]; ok { + return nil + } + return types.ErrUnsupportedAuthIdentityStatus +} + +func (t Status) IsValid() bool { + _, ok := allowedStatuses[t] + return ok +} + +func (t Status) MarshalJSON() ([]byte, error) { + if err := t.Validate(); err != nil { + return nil, err + } + return json.Marshal(t.String()) +} + +func (t *Status) UnmarshalJSON(data []byte) error { + if t == nil { + return types.ErrUnmarshalAuthIdentityStatusIntoNilPointer + } + var value string + if err := json.Unmarshal(data, &value); err != nil { + return err + } + parsed := ParseStatus(value) + if err := parsed.Validate(); err != nil { + return err + } + *t = parsed + return nil +} diff --git a/service/internal/pkg/authprovider/provider.go b/service/internal/pkg/authprovider/provider.go new file mode 100644 index 0000000..ebaa90a --- /dev/null +++ b/service/internal/pkg/authprovider/provider.go @@ -0,0 +1,82 @@ +package authprovider + +import ( + "encoding/json" + "strings" + + "git.dev.mamont-optics.ru/mamont-optics/backend/application/internal/pkg/types" +) + +type Type string + +const ( + TypeUndefined Type = "undefined" + TypePassword Type = "password" + TypeEmail Type = "email" + TypePhone Type = "phone" + TypeGoogle Type = "google" + TypeTelegram Type = "telegram" +) + +var allowedTypes = map[Type]struct{}{ + TypePassword: {}, + TypeEmail: {}, + TypePhone: {}, + TypeGoogle: {}, + TypeTelegram: {}, +} + +func ParseType(value string) Type { + t := Type(strings.ToLower(value)) + if !t.IsValid() { + return TypeUndefined + } + return t +} + +func ParseAndValidateType(value string) (Type, error) { + parsed := ParseType(value) + if _, ok := allowedTypes[parsed]; ok { + return parsed, nil + } + return TypeUndefined, types.ErrUnsupportedOTPStatus +} + +func (t Type) String() string { + return string(t) +} + +func (t Type) Validate() error { + if _, ok := allowedTypes[t]; ok { + return nil + } + return types.ErrUnsupportedAuthProviderType +} + +func (t Type) IsValid() bool { + _, ok := allowedTypes[t] + return ok +} + +func (t Type) MarshalJSON() ([]byte, error) { + if err := t.Validate(); err != nil { + return nil, err + } + return json.Marshal(t.String()) +} + +func (t *Type) UnmarshalJSON(data []byte) error { + if t == nil { + return types.ErrUnmarshalAuthProviderTypeIntoNilPointer + } + var value string + if err := json.Unmarshal(data, &value); err != nil { + return err + } + parsed := ParseType(value) + if err := parsed.Validate(); err != nil { + return err + } + *t = parsed + return nil +} diff --git a/service/internal/pkg/environment/environment.go b/service/internal/pkg/environment/environment.go new file mode 100644 index 0000000..345efe8 --- /dev/null +++ b/service/internal/pkg/environment/environment.go @@ -0,0 +1,77 @@ +package environment + +import ( + "encoding/json" + "strings" + + "git.dev.mamont-optics.ru/mamont-optics/backend/application/internal/pkg/types" +) + +type ApplicationEnvironment string + +const ( + ApplicationEnvironmentUndefined ApplicationEnvironment = "undefined" + ApplicationEnvironmentDev ApplicationEnvironment = "dev" + ApplicationEnvironmentProd ApplicationEnvironment = "prod" +) + +var allowedEnvironments = map[ApplicationEnvironment]struct{}{ + ApplicationEnvironmentUndefined: {}, + ApplicationEnvironmentDev: {}, + ApplicationEnvironmentProd: {}, +} + +func ParseEnvironment(value string) ApplicationEnvironment { + s := ApplicationEnvironment(strings.ToLower(value)) + if !s.IsValid() { + return ApplicationEnvironmentUndefined + } + return s +} + +func ParseAndValidateEnvironment(status string) (ApplicationEnvironment, error) { + parsed := ParseEnvironment(status) + if _, ok := allowedEnvironments[parsed]; ok { + return parsed, nil + } + return ApplicationEnvironmentUndefined, types.ErrUnsupportedApplicationEnvironment +} + +func (t ApplicationEnvironment) String() string { + return string(t) +} + +func (t ApplicationEnvironment) Validate() error { + if _, ok := allowedEnvironments[t]; ok { + return nil + } + return types.ErrUnsupportedApplicationEnvironment +} + +func (t ApplicationEnvironment) IsValid() bool { + _, ok := allowedEnvironments[t] + return ok +} + +func (t ApplicationEnvironment) MarshalJSON() ([]byte, error) { + if err := t.Validate(); err != nil { + return nil, err + } + return json.Marshal(t.String()) +} + +func (t *ApplicationEnvironment) UnmarshalJSON(data []byte) error { + if t == nil { + return types.ErrUnmarshalApplicationEnvironmentIntoNilPointer + } + var value string + if err := json.Unmarshal(data, &value); err != nil { + return err + } + parsed := ParseEnvironment(value) + if err := parsed.Validate(); err != nil { + return err + } + *t = parsed + return nil +} diff --git a/service/internal/pkg/error.go b/service/internal/pkg/error.go new file mode 100644 index 0000000..5f52357 --- /dev/null +++ b/service/internal/pkg/error.go @@ -0,0 +1,25 @@ +package types + +import "errors" + +var ( + ErrUnsupportedRole = errors.New("unsupported role") + ErrUnsupportedOTPType = errors.New("unsupported OTP type") + ErrUnsupportedAuthProviderType = errors.New("unsupported auth provider type") + ErrUnsupportedContactType = errors.New("unsupported contact type") + ErrUnsupportedOTPStatus = errors.New("unsupported OTP status") + ErrUnsupportedOTPResult = errors.New("unsupported OTP result") + ErrUnsupportedFormStatus = errors.New("unsupported form status") + ErrUnsupportedAuthIdentityStatus = errors.New("unsupported auth identity status") + ErrUnsupportedApplicationEnvironment = errors.New("unsupported application environment") + + ErrUnmarshalRoleIntoNilPointer = errors.New("unmarshal role into nil pointer") + ErrUnmarshalOTPTypeIntoNilPointer = errors.New("unmarshal OTP type into nil pointer") + ErrUnmarshalAuthProviderTypeIntoNilPointer = errors.New("unmarshal auth provider into nil pointer") + ErrUnmarshalContactTypeIntoNilPointer = errors.New("unmarshal contact into nil pointer") + ErrUnmarshalOTPStatusIntoNilPointer = errors.New("unmarshal OTP status into nil pointer") + ErrUnmarshalOTPResultIntoNilPointer = errors.New("unmarshal OTP result into nil pointer") + ErrUnmarshalFormStatusIntoNilPointer = errors.New("unmarshal form status into nil pointer") + ErrUnmarshalAuthIdentityStatusIntoNilPointer = errors.New("unmarshal auth identity status into nil pointer") + ErrUnmarshalApplicationEnvironmentIntoNilPointer = errors.New("unmarshal application environment into nil pointer") +) diff --git a/service/internal/pkg/role/role.go b/service/internal/pkg/role/role.go new file mode 100644 index 0000000..3c1f7c2 --- /dev/null +++ b/service/internal/pkg/role/role.go @@ -0,0 +1,105 @@ +package role + +import ( + "encoding/json" + "strings" + + "git.dev.mamont-optics.ru/mamont-optics/backend/application/internal/pkg/types" +) + +type Role string + +const ( + Undefined Role = "undefined" + User Role = "user" + Doctor Role = "doctor" + Manager Role = "manager" + Admin Role = "admin" +) + +var allowedRoles = map[Role]struct{}{ + User: {}, + Doctor: {}, + Manager: {}, + Admin: {}, +} + +func ParseRole(s string) Role { + r := Role(strings.ToLower(s)) + if !r.IsValid() { + return Undefined + } + return r +} + +func ParseAndValidateRole(s string) (Role, error) { + parsed := ParseRole(s) + if _, ok := allowedRoles[parsed]; ok { + return parsed, nil + } + return Undefined, types.ErrUnsupportedRole +} + +func (t Role) String() string { + return string(t) +} + +func (t Role) Validate() error { + if _, ok := allowedRoles[t]; ok { + return nil + } + return types.ErrUnsupportedRole +} + +func (t Role) IsValid() bool { + _, ok := allowedRoles[t] + return ok +} + +func (t Role) MarshalJSON() ([]byte, error) { + if err := t.Validate(); err != nil { + return nil, err + } + return json.Marshal(t.String()) +} + +func (t *Role) UnmarshalJSON(data []byte) error { + if t == nil { + return types.ErrUnmarshalRoleIntoNilPointer + } + var value string + if err := json.Unmarshal(data, &value); err != nil { + return err + } + parsed := ParseRole(value) + if err := parsed.Validate(); err != nil { + return err + } + *t = parsed + return nil +} + +func (t Role) IsAdmin() bool { + return t == Admin +} + +func (t Role) IsManager() bool { + return t == Manager +} + +func (t Role) IsDoctor() bool { + return t == Doctor +} + +func (t Role) IsUser() bool { + return t == User +} + +func (t Role) IsPrivileged() bool { + switch t { + case Doctor, Manager, Admin: + return true + default: + return false + } +} diff --git a/service/internal/pkg/validator/validator.go b/service/internal/pkg/validator/validator.go new file mode 100644 index 0000000..d4ab8aa --- /dev/null +++ b/service/internal/pkg/validator/validator.go @@ -0,0 +1,29 @@ +package validator + +import ( + "context" + + "github.com/go-playground/validator/v10" +) + +type TagKey string + +type ValidatorImpl struct { + validator *validator.Validate +} + +func NewValidatorImpl() *ValidatorImpl { + return &ValidatorImpl{validator: validator.New()} +} + +func (v *ValidatorImpl) Register(tag TagKey, fn validator.Func, callValidationEvenIfNull ...bool) error { + return v.validator.RegisterValidation(string(tag), fn, callValidationEvenIfNull...) +} + +func (v *ValidatorImpl) ValidateCtx(ctx context.Context, value any) error { + return v.validator.StructCtx(ctx, value) +} + +func (v *ValidatorImpl) Validate(value any) error { + return v.validator.Struct(value) +} diff --git a/service/migrations/001_create_users_table.sql b/service/migrations/001_create_users_table.sql new file mode 100644 index 0000000..676fdaa --- /dev/null +++ b/service/migrations/001_create_users_table.sql @@ -0,0 +1,14 @@ +CREATE TABLE IF NOT EXISTS users +( + id UUID PRIMARY KEY, + name VARCHAR(64), + surname VARCHAR(64), + patronymic VARCHAR(64), + birthdate DATE, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() +); + +---- create above / drop below ---- + +DROP TABLE IF EXISTS users; \ No newline at end of file diff --git a/service/migrations/002_create_refresh_tokens_table.sql b/service/migrations/002_create_refresh_tokens_table.sql new file mode 100644 index 0000000..cbc7308 --- /dev/null +++ b/service/migrations/002_create_refresh_tokens_table.sql @@ -0,0 +1,19 @@ +CREATE TABLE IF NOT EXISTS refresh_tokens +( + id UUID PRIMARY KEY, + user_id UUID NOT NULL REFERENCES users (id), + token_hash TEXT NOT NULL, + user_agent TEXT, + ip_address INET, + role VARCHAR(16) NOT NULL, + expires_at TIMESTAMPTZ NOT NULL, + revoked_at TIMESTAMPTZ, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() +); + +CREATE INDEX IF NOT EXISTS idx_refresh_user_id ON refresh_tokens (user_id); +CREATE INDEX IF NOT EXISTS idx_refresh_expires ON refresh_tokens (expires_at); + +---- create above / drop below ---- + +DROP TABLE IF EXISTS refresh_tokens; \ No newline at end of file diff --git a/service/migrations/003_create_auth_identities_table.sql b/service/migrations/003_create_auth_identities_table.sql new file mode 100644 index 0000000..615ffd7 --- /dev/null +++ b/service/migrations/003_create_auth_identities_table.sql @@ -0,0 +1,17 @@ +CREATE TABLE IF NOT EXISTS auth_identities +( + id UUID PRIMARY KEY, + role VARCHAR(12) NOT NULL, + user_id UUID NOT NULL, + provider TEXT NOT NULL, + identifier TEXT NOT NULL, + password_hash TEXT, + status VARCHAR(24) NOT NULL DEFAULT 'PENDING', + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + + CONSTRAINT fk_auth_identities_users FOREIGN KEY (user_id) REFERENCES users (id), + UNIQUE (provider, identifier) +); +---- create above / drop below ---- +DROP TABLE IF EXISTS auth_identities; \ No newline at end of file diff --git a/service/tests/api_test.go b/service/tests/api_test.go new file mode 100644 index 0000000..478cb04 --- /dev/null +++ b/service/tests/api_test.go @@ -0,0 +1,239 @@ +package tests + +import ( + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "testing" + + controller "gitea.privcloud.tech/mtusi2026/internal/adapter/controller/http" + inmemory2 "gitea.privcloud.tech/mtusi2026/internal/adapter/repository/cache/inmemory" +) + +type apiClient struct { + handler http.Handler +} + +type apiResponse struct { + status int + requestID string + body []byte +} + +func newAPI(t *testing.T) *apiClient { + t.Helper() + router := controller.NewRouter() + users := inmemory2.NewUserCache() + chats := inmemory2.NewChatCache(users) + messages := inmemory2.NewMessageCache(chats) + base := controller.NewBaseHandler(router) + controller.NewUserHandler(base, users).RegisterRoutes() + controller.NewChatHandler(base, users, chats, messages).RegisterRoutes() + + return &apiClient{handler: router} +} + +func (api *apiClient) request(t *testing.T, method, path, userID, body string) apiResponse { + t.Helper() + req := httptest.NewRequest(method, path, strings.NewReader(body)) + if body != "" { + req.Header.Set("Content-Type", "application/json") + } + if userID != "" { + req.Header.Set("X-User-Id", userID) + } + recorder := httptest.NewRecorder() + api.handler.ServeHTTP(recorder, req) + resp := recorder.Result() + defer resp.Body.Close() + requestID := resp.Header.Get("X-Request-Id") + if requestID == "" { + t.Fatalf("%s %s: missing X-Request-Id", method, path) + } + return apiResponse{status: resp.StatusCode, requestID: requestID, body: recorder.Body.Bytes()} +} + +func jsonString(t *testing.T, value any) string { + t.Helper() + data, err := json.Marshal(value) + if err != nil { + t.Fatalf("encode request: %v", err) + } + return string(data) +} + +func decodeOK(t *testing.T, resp apiResponse, wantStatus int, target any) { + t.Helper() + if resp.status != wantStatus { + t.Fatalf("status = %d, want %d; body: %s", resp.status, wantStatus, resp.body) + } + if err := json.Unmarshal(resp.body, target); err != nil { + t.Fatalf("decode response %s: %v", resp.body, err) + } +} + +func assertError(t *testing.T, resp apiResponse, wantStatus int, wantCode string) { + t.Helper() + if resp.status != wantStatus { + t.Fatalf("status = %d, want %d; body: %s", resp.status, wantStatus, resp.body) + } + var body struct { + Error struct { + Code string `json:"code"` + Message string `json:"message"` + RequestID string `json:"request_id"` + } `json:"error"` + } + if err := json.Unmarshal(resp.body, &body); err != nil { + t.Fatalf("decode error response %s: %v", resp.body, err) + } + if body.Error.Code != wantCode || body.Error.Message == "" || body.Error.RequestID != resp.requestID { + t.Fatalf("invalid error response: header request ID %q, body %s", resp.requestID, resp.body) + } +} + +func (api *apiClient) createUser(t *testing.T, username string) string { + t.Helper() + resp := api.request(t, http.MethodPost, "/api/v1/users", "", jsonString(t, map[string]string{ + "username": username, "display_name": username, + })) + var user struct { + ID string `json:"id"` + } + decodeOK(t, resp, http.StatusCreated, &user) + if user.ID == "" { + t.Fatal("created user has no ID") + } + return user.ID +} + +func (api *apiClient) createChat(t *testing.T, creatorID string, memberIDs ...string) string { + t.Helper() + resp := api.request(t, http.MethodPost, "/api/v1/chats", creatorID, jsonString(t, map[string]any{ + "title": "Test chat", "member_ids": memberIDs, + })) + var chat struct { + ID string `json:"id"` + } + decodeOK(t, resp, http.StatusCreated, &chat) + if chat.ID == "" { + t.Fatal("created chat has no ID") + } + return chat.ID +} + +func TestInvalidJSON(t *testing.T) { + api := newAPI(t) + for _, tc := range []struct { + name string + body string + }{ + {name: "malformed", body: `{"username":`}, + {name: "wrong type", body: `{"username":42,"display_name":"Alice"}`}, + {name: "unknown field", body: `{"username":"alice","display_name":"Alice","admin":true}`}, + } { + t.Run(tc.name, func(t *testing.T) { + resp := api.request(t, http.MethodPost, "/api/v1/users", "", tc.body) + assertError(t, resp, http.StatusBadRequest, "invalid_request") + }) + } +} + +func TestForeignChatIsHidden(t *testing.T) { + api := newAPI(t) + alice := api.createUser(t, "alice") + bob := api.createUser(t, "bob") + eve := api.createUser(t, "eve") + chatID := api.createChat(t, alice, alice, bob) + + for _, tc := range []struct { + method string + path string + body string + }{ + {method: http.MethodGet, path: "/api/v1/chats/" + chatID}, + {method: http.MethodGet, path: "/api/v1/chats/" + chatID + "/messages"}, + {method: http.MethodPost, path: "/api/v1/chats/" + chatID + "/messages", body: `{"text":"secret"}`}, + } { + resp := api.request(t, tc.method, tc.path, eve, tc.body) + assertError(t, resp, http.StatusNotFound, "not_found") + } +} + +func TestEmptyMessage(t *testing.T) { + api := newAPI(t) + alice := api.createUser(t, "alice") + chatID := api.createChat(t, alice, alice) + path := "/api/v1/chats/" + chatID + "/messages" + for _, body := range []string{`{"text":""}`, `{"text":" \t\n "}`} { + resp := api.request(t, http.MethodPost, path, alice, body) + assertError(t, resp, http.StatusBadRequest, "invalid_request") + } +} + +func TestDuplicateUsername(t *testing.T) { + api := newAPI(t) + api.createUser(t, "alice") + resp := api.request(t, http.MethodPost, "/api/v1/users", "", `{"username":"alice","display_name":"Another Alice"}`) + assertError(t, resp, http.StatusConflict, "conflict") +} + +func TestMessagePagination(t *testing.T) { + api := newAPI(t) + alice := api.createUser(t, "alice") + chatID := api.createChat(t, alice, alice) + wantIDs := make(map[string]bool) + for i := range 5 { + resp := api.request(t, http.MethodPost, "/api/v1/chats/"+chatID+"/messages", alice, + jsonString(t, map[string]string{"text": fmt.Sprintf("message %d", i)})) + var message struct { + ID string `json:"id"` + } + decodeOK(t, resp, http.StatusCreated, &message) + if message.ID == "" || wantIDs[message.ID] { + t.Fatalf("invalid or duplicate created message ID %q", message.ID) + } + wantIDs[message.ID] = true + } + + seen := make(map[string]bool) + cursor := "" + pages := 0 + for { + path := "/api/v1/chats/" + chatID + "/messages?limit=2" + if cursor != "" { + path += "&cursor=" + url.QueryEscape(cursor) + } + resp := api.request(t, http.MethodGet, path, alice, "") + var page struct { + Items []struct { + ID string `json:"id"` + } `json:"items"` + NextCursor *string `json:"next_cursor"` + } + decodeOK(t, resp, http.StatusOK, &page) + pages++ + if pages > 3 || len(page.Items) == 0 || len(page.Items) > 2 { + t.Fatalf("unexpected page %d: %s", pages, resp.body) + } + for _, message := range page.Items { + if !wantIDs[message.ID] || seen[message.ID] { + t.Fatalf("unexpected or repeated message ID %q on page %d", message.ID, pages) + } + seen[message.ID] = true + } + if page.NextCursor == nil { + break + } + if *page.NextCursor == "" || *page.NextCursor == cursor { + t.Fatalf("invalid next cursor on page %d: %s", pages, resp.body) + } + cursor = *page.NextCursor + } + if pages != 3 || len(seen) != len(wantIDs) { + t.Fatalf("got %d pages and %d unique messages, want 3 pages and %d messages", pages, len(seen), len(wantIDs)) + } +} diff --git a/service/tests/concurrency_test.go b/service/tests/concurrency_test.go new file mode 100644 index 0000000..694acc6 --- /dev/null +++ b/service/tests/concurrency_test.go @@ -0,0 +1,162 @@ +package tests + +import ( + "encoding/json" + "fmt" + "io" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "sync" + "testing" + "time" +) + +type createdMessage struct { + ID string `json:"id"` + SenderID string `json:"sender_id"` + Text string `json:"text"` +} + +func postMessage(client *http.Client, endpoint, userID, text string) (createdMessage, error) { + body, err := json.Marshal(struct { + Text string `json:"text"` + }{Text: text}) + if err != nil { + return createdMessage{}, err + } + req, err := http.NewRequest(http.MethodPost, endpoint, strings.NewReader(string(body))) + if err != nil { + return createdMessage{}, err + } + req.Header.Set("Content-Type", "application/json") + req.Header.Set("X-User-Id", userID) + resp, err := client.Do(req) + if err != nil { + return createdMessage{}, err + } + defer resp.Body.Close() + data, err := io.ReadAll(resp.Body) + if err != nil { + return createdMessage{}, err + } + if resp.StatusCode != http.StatusCreated { + return createdMessage{}, fmt.Errorf("POST status %d: %s", resp.StatusCode, data) + } + if resp.Header.Get("X-Request-Id") == "" { + return createdMessage{}, fmt.Errorf("POST response has no X-Request-Id") + } + var message createdMessage + if err := json.Unmarshal(data, &message); err != nil { + return createdMessage{}, fmt.Errorf("decode POST response: %w", err) + } + return message, nil +} + +func TestConcurrentMessages(t *testing.T) { + const clients = 10 + const messagesPerClient = 10 + const total = clients * messagesPerClient + + api := newAPI(t) + users := make([]string, clients) + for i := range users { + users[i] = api.createUser(t, fmt.Sprintf("user%02d", i)) + } + chatID := api.createChat(t, users[0], users...) + server := httptest.NewServer(api.handler) + t.Cleanup(server.Close) + endpoint := server.URL + "/api/v1/chats/" + chatID + "/messages" + + type result struct { + message createdMessage + wantSenderID string + wantText string + err error + } + results := make(chan result, total) + start := make(chan struct{}) + var ready sync.WaitGroup + var workers sync.WaitGroup + ready.Add(clients) + workers.Add(clients) + for i, userID := range users { + go func(workerID int, userID string) { + defer workers.Done() + client := &http.Client{Timeout: 5 * time.Second} + defer client.CloseIdleConnections() + ready.Done() + <-start + for j := range messagesPerClient { + text := fmt.Sprintf("client-%02d-message-%02d", workerID, j) + message, err := postMessage(client, endpoint, userID, text) + results <- result{message: message, wantSenderID: userID, wantText: text, err: err} + } + }(i, userID) + } + ready.Wait() + close(start) + workers.Wait() + close(results) + + created := make(map[string]createdMessage, total) + count := 0 + for item := range results { + count++ + if item.err != nil { + t.Errorf("send %q: %v", item.wantText, item.err) + continue + } + if item.message.ID == "" || item.message.SenderID != item.wantSenderID || item.message.Text != item.wantText { + t.Errorf("unexpected response for %q: %+v", item.wantText, item.message) + continue + } + if _, duplicate := created[item.message.ID]; duplicate { + t.Errorf("duplicate message ID %q", item.message.ID) + continue + } + created[item.message.ID] = item.message + } + if count != total || len(created) != total { + t.Fatalf("sent %d requests, created %d unique messages; want %d", count, len(created), total) + } + + seen := make(map[string]bool, total) + cursor := "" + pages := 0 + for { + path := "/api/v1/chats/" + chatID + "/messages?limit=17" + if cursor != "" { + path += "&cursor=" + url.QueryEscape(cursor) + } + resp := api.request(t, http.MethodGet, path, users[0], "") + var page struct { + Items []createdMessage `json:"items"` + NextCursor *string `json:"next_cursor"` + } + decodeOK(t, resp, http.StatusOK, &page) + pages++ + if pages > total || len(page.Items) == 0 || len(page.Items) > 17 { + t.Fatalf("unexpected page %d: %s", pages, resp.body) + } + for _, message := range page.Items { + want, exists := created[message.ID] + if !exists || seen[message.ID] || message != want { + t.Fatalf("unexpected or repeated message on page %d: %+v", pages, message) + } + seen[message.ID] = true + } + if page.NextCursor == nil { + break + } + if *page.NextCursor == "" || *page.NextCursor == cursor { + t.Fatalf("invalid cursor on page %d: %s", pages, resp.body) + } + cursor = *page.NextCursor + } + if len(seen) != total { + t.Fatalf("history has %d unique messages across %d pages; want %d", len(seen), pages, total) + } + t.Logf("%d clients sent %d messages; history contains %d unique messages across %d pages", clients, total, len(seen), pages) +}