From 2f279a1715f13d8ad8ff7d13686ca66c0dea2d8a Mon Sep 17 00:00:00 2001 From: kk10 Date: Fri, 2 Oct 2026 11:45:26 +0300 Subject: [PATCH 01/40] chore: port lab 1 solution --- .env.example | 5 + Dockerfile | 21 +++ Makefile | 2 + cmd/server/main.go | 18 +++ docker-compose.yml | 12 ++ go.mod | 9 ++ go.sum | 6 + internal/app/app.go | 75 +++++++++ internal/app/healthcheck.go | 46 ++++++ internal/app/router.go | 53 +++++++ internal/config/config.go | 80 ++++++++++ internal/dto/chat.go | 49 ++++++ internal/dto/error.go | 25 +++ internal/dto/health.go | 5 + internal/dto/message.go | 46 ++++++ internal/dto/user.go | 37 +++++ internal/handler/chat.go | 168 ++++++++++++++++++++ internal/handler/error.go | 27 ++++ internal/handler/health.go | 17 +++ internal/handler/message.go | 142 +++++++++++++++++ internal/handler/user.go | 102 +++++++++++++ internal/httpx/pagination.go | 34 +++++ internal/httpx/request.go | 29 ++++ internal/httpx/response.go | 24 +++ internal/logger/logger.go | 14 ++ internal/middleware/auth.go | 65 ++++++++ internal/middleware/concurrency.go | 41 +++++ internal/middleware/logging.go | 49 ++++++ internal/middleware/request_id.go | 30 ++++ internal/model/chat.go | 14 ++ internal/model/message.go | 15 ++ internal/model/user.go | 14 ++ internal/service/chat.go | 109 +++++++++++++ internal/service/cursor.go | 40 +++++ internal/service/message.go | 87 +++++++++++ internal/service/user.go | 47 ++++++ internal/store/memory.go | 236 +++++++++++++++++++++++++++++ student-tests/contract_test.go | 135 +++++++++++++++++ student-tests/helpers_test.go | 198 ++++++++++++++++++++++++ student-tests/load_test.go | 138 +++++++++++++++++ student-tests/race_test.go | 100 ++++++++++++ student.mk | 17 +++ web/swagger/index.html | 21 +++ 43 files changed, 2402 insertions(+) create mode 100644 Dockerfile create mode 100644 cmd/server/main.go create mode 100644 docker-compose.yml create mode 100644 go.mod create mode 100644 go.sum create mode 100644 internal/app/app.go create mode 100644 internal/app/healthcheck.go create mode 100644 internal/app/router.go create mode 100644 internal/config/config.go create mode 100644 internal/dto/chat.go create mode 100644 internal/dto/error.go create mode 100644 internal/dto/health.go create mode 100644 internal/dto/message.go create mode 100644 internal/dto/user.go create mode 100644 internal/handler/chat.go create mode 100644 internal/handler/error.go create mode 100644 internal/handler/health.go create mode 100644 internal/handler/message.go create mode 100644 internal/handler/user.go create mode 100644 internal/httpx/pagination.go create mode 100644 internal/httpx/request.go create mode 100644 internal/httpx/response.go create mode 100644 internal/logger/logger.go create mode 100644 internal/middleware/auth.go create mode 100644 internal/middleware/concurrency.go create mode 100644 internal/middleware/logging.go create mode 100644 internal/middleware/request_id.go create mode 100644 internal/model/chat.go create mode 100644 internal/model/message.go create mode 100644 internal/model/user.go create mode 100644 internal/service/chat.go create mode 100644 internal/service/cursor.go create mode 100644 internal/service/message.go create mode 100644 internal/service/user.go create mode 100644 internal/store/memory.go create mode 100644 student-tests/contract_test.go create mode 100644 student-tests/helpers_test.go create mode 100644 student-tests/load_test.go create mode 100644 student-tests/race_test.go create mode 100644 student.mk create mode 100644 web/swagger/index.html diff --git a/.env.example b/.env.example index 714c8076..32b5e232 100644 --- a/.env.example +++ b/.env.example @@ -3,6 +3,11 @@ APP_HOST=0.0.0.0 APP_PORT=8080 APP_ENV=lab + +MAX_INFLIGHT_REQUESTS=0 + +LOG_LEVEL=INFO + SESSION_TTL_SECONDS=3600 # Choose credentials locally. File paths contain no secret values. DATABASE_URL_FILE=/run/secrets/database_url diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 00000000..d44495b6 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,21 @@ +FROM golang:1.25.0 AS build +WORKDIR /src + +COPY go.mod go.sum ./ +RUN go mod download + +COPY . . +RUN CGO_ENABLED=0 GOOS=linux go build -o /out/server ./cmd/server + +FROM gcr.io/distroless/static-debian12:nonroot +WORKDIR /app +COPY --from=build /out/server . +COPY contracts ./contracts +COPY web/swagger ./web/swagger + +EXPOSE 8080 + +HEALTHCHECK --interval=10s --timeout=3s --start-period=5s --retries=3 \ + CMD ["/app/server", "healthcheck"] + +ENTRYPOINT ["/app/server"] diff --git a/Makefile b/Makefile index 9ecb223e..93b05a5b 100644 --- a/Makefile +++ b/Makefile @@ -24,3 +24,5 @@ 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) + +-include student.mk diff --git a/cmd/server/main.go b/cmd/server/main.go new file mode 100644 index 00000000..e4032d40 --- /dev/null +++ b/cmd/server/main.go @@ -0,0 +1,18 @@ +package main + +import ( + "log" + "os" + + "mtusi2026-messenger/internal/app" +) + +func main() { + if len(os.Args) > 1 && os.Args[1] == "healthcheck" { + os.Exit(app.Healthcheck()) + } + + if err := app.Run(); err != nil { + log.Fatal(err) + } +} diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 00000000..08adff47 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,12 @@ +services: + messenger: + build: + context: . + dockerfile: Dockerfile + image: mtusi-messenger:lab1 + container_name: mtusi-messenger-lab1 + ports: + - "127.0.0.1:8080:${APP_PORT}" + env_file: + - .env + restart: unless-stopped diff --git a/go.mod b/go.mod new file mode 100644 index 00000000..1930f284 --- /dev/null +++ b/go.mod @@ -0,0 +1,9 @@ +module mtusi2026-messenger + +go 1.25.0 + +require ( + github.com/go-chi/chi/v5 v5.3.2 + github.com/google/uuid v1.6.0 + github.com/joho/godotenv v1.5.1 +) diff --git a/go.sum b/go.sum new file mode 100644 index 00000000..02c75233 --- /dev/null +++ b/go.sum @@ -0,0 +1,6 @@ +github.com/go-chi/chi/v5 v5.3.2 h1:5YQkICvTCSZ25hoRsyJazN0scjzKGiu4VAUc7H1o1nY= +github.com/go-chi/chi/v5 v5.3.2/go.mod h1:R+tYY2hNuVUUjxoPtqUdgBqevM9s9njzkTLutVsOCto= +github.com/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/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0= +github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4= diff --git a/internal/app/app.go b/internal/app/app.go new file mode 100644 index 00000000..0fdbc87a --- /dev/null +++ b/internal/app/app.go @@ -0,0 +1,75 @@ +package app + +import ( + "context" + "net/http" + "os" + "os/signal" + "syscall" + "time" + + "github.com/joho/godotenv" + + "mtusi2026-messenger/internal/config" + "mtusi2026-messenger/internal/logger" + "mtusi2026-messenger/internal/service" + "mtusi2026-messenger/internal/store" +) + +func Run() error { + if err := godotenv.Load(); err != nil && !os.IsNotExist(err) { + return err + } + + cfg := config.Load() + + log := logger.New(cfg.Logging.Level) + + memory := store.New() + + userService := service.NewUserService(memory) + chatService := service.NewChatService(memory) + messageService := service.NewMessageService(memory) + + router := NewRouter(log, cfg.Server.MaxInflightRequests, userService, chatService, messageService) + + server := &http.Server{ + Addr: cfg.Server.Host + ":" + cfg.Server.Port, + Handler: router, + } + + serverErrors := make(chan error, 1) + + go func() { + log.Info("server starting", "addr", server.Addr) + serverErrors <- server.ListenAndServe() + }() + + signalCh := make(chan os.Signal, 1) + signal.Notify(signalCh, syscall.SIGINT, syscall.SIGTERM) + defer signal.Stop(signalCh) + + select { + case err := <-serverErrors: + if err == http.ErrServerClosed { + return nil + } + + log.Error("server failed", "error", err) + return err + + case sig := <-signalCh: + log.Info("shutdown signal received", "signal", sig.String()) + + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + + if err := server.Shutdown(ctx); err != nil { + log.Error("server shutdown failed", "error", err) + return err + } + + log.Info("server stopped") + return nil + } +} diff --git a/internal/app/healthcheck.go b/internal/app/healthcheck.go new file mode 100644 index 00000000..6cab9274 --- /dev/null +++ b/internal/app/healthcheck.go @@ -0,0 +1,46 @@ +package app + +import ( + "context" + "fmt" + "net/http" + "os" + "time" + + "mtusi2026-messenger/internal/config" + + "github.com/joho/godotenv" +) + +func Healthcheck() int { + if err := godotenv.Load(); err != nil && !os.IsNotExist(err) { + fmt.Fprintln(os.Stderr, "healthcheck: load env:", err) + return 1 + } + + cfg := config.Load() + url := fmt.Sprintf("http://localhost:%s/health/ready", cfg.Server.Port) + + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + + req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) + if err != nil { + fmt.Fprintln(os.Stderr, "healthcheck: build request:", err) + return 1 + } + + resp, err := http.DefaultClient.Do(req) + if err != nil { + fmt.Fprintln(os.Stderr, "healthcheck: request failed:", err) + return 1 + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + fmt.Fprintln(os.Stderr, "healthcheck: unexpected status", resp.StatusCode) + return 1 + } + + return 0 +} diff --git a/internal/app/router.go b/internal/app/router.go new file mode 100644 index 00000000..0120396a --- /dev/null +++ b/internal/app/router.go @@ -0,0 +1,53 @@ +package app + +import ( + "log/slog" + "net/http" + + "github.com/go-chi/chi/v5" + + "mtusi2026-messenger/internal/handler" + "mtusi2026-messenger/internal/middleware" + "mtusi2026-messenger/internal/service" +) + +func NewRouter( + log *slog.Logger, + maxInflightRequests int, + userService *service.UserService, + chatService *service.ChatService, + messageService *service.MessageService, +) http.Handler { + router := chi.NewRouter() + + userHandler := handler.NewUserHandler(userService) + chatHandler := handler.NewChatHandler(chatService) + messageHandler := handler.NewMessageHandler(messageService) + + router.Use(middleware.RequestID) + router.Use(middleware.Logging(log)) + router.Use(middleware.ConcurrencyLimit(maxInflightRequests)) + + router.Get("/health/live", handler.Health) + router.Get("/health/ready", handler.Health) + + router.Post("/api/v1/users", userHandler.Create) + + router.Group(func(r chi.Router) { + r.Use(middleware.Auth(userService)) + + r.Get("/api/v1/users/me", userHandler.Me) + + r.Post("/api/v1/chats", chatHandler.Create) + r.Get("/api/v1/chats", chatHandler.List) + r.Get("/api/v1/chats/{chat_id}", chatHandler.Get) + + r.Post("/api/v1/chats/{chat_id}/messages", messageHandler.Create) + r.Get("/api/v1/chats/{chat_id}/messages", messageHandler.List) + }) + + router.Handle("/swagger/*", http.StripPrefix("/swagger/", http.FileServer(http.Dir("web/swagger")))) + router.Handle("/contracts/*", http.StripPrefix("/contracts/", http.FileServer(http.Dir("contracts")))) + + return router +} diff --git a/internal/config/config.go b/internal/config/config.go new file mode 100644 index 00000000..710eb9bd --- /dev/null +++ b/internal/config/config.go @@ -0,0 +1,80 @@ +package config + +import ( + "log" + "log/slog" + "os" + "strconv" +) + +type Config struct { + Server ServerConfig + Logging LoggingConfig +} + +type ServerConfig struct { + Host string + Port string + MaxInflightRequests int +} + +type LoggingConfig struct { + Level slog.Level +} + +func Load() Config { + return Config{ + Server: ServerConfig{ + Host: getEnv("APP_HOST", "0.0.0.0"), + Port: getEnv("APP_PORT", "8080"), + MaxInflightRequests: getEnvNonNegativeInt("MAX_INFLIGHT_REQUESTS", 0), + }, + + Logging: LoggingConfig{ + Level: getEnvLogLevel("LOG_LEVEL", slog.LevelInfo), + }, + } +} +func getEnv(key, def string) string { + value := os.Getenv(key) + if value == "" { + return def + } + + return value +} + +func getEnvNonNegativeInt(key string, def int) int { + v := os.Getenv(key) + if v == "" { + return def + } + + value, err := strconv.Atoi(v) + if err != nil || value < 0 { + log.Printf("invalid non-negative int for %s=%q, using default %d", key, v, def) + return def + } + + return value +} + +func getEnvLogLevel(key string, def slog.Level) slog.Level { + v := os.Getenv(key) + + switch v { + case "DEBUG": + return slog.LevelDebug + case "INFO": + return slog.LevelInfo + case "WARN": + return slog.LevelWarn + case "ERROR": + return slog.LevelError + case "": + return def + default: + log.Printf("invalid log level for %s=%q, using default %s", key, v, def) + return def + } +} diff --git a/internal/dto/chat.go b/internal/dto/chat.go new file mode 100644 index 00000000..904b7de0 --- /dev/null +++ b/internal/dto/chat.go @@ -0,0 +1,49 @@ +package dto + +import ( + "mtusi2026-messenger/internal/model" + "strings" + "time" + "unicode/utf8" + + "github.com/google/uuid" +) + +type CreateChatRequest struct { + Title string `json:"title"` + MemberIDs []uuid.UUID `json:"member_ids"` +} + +type ChatResponse struct { + ID uuid.UUID `json:"id"` + Title string `json:"title"` + MemberIDs []uuid.UUID `json:"member_ids"` + CreatedAt time.Time `json:"created_at"` +} + +type ChatPageResponse struct { + Items []ChatResponse `json:"items"` + NextCursor *string `json:"next_cursor"` +} + +func (r CreateChatRequest) Validate() bool { + titleLen := utf8.RuneCountInString(r.Title) + if strings.TrimSpace(r.Title) == "" || titleLen > 100 { + return false + } + + if len(r.MemberIDs) < 1 || len(r.MemberIDs) > 100 { + return false + } + + return true +} + +func ToChatResponse(c model.Chat) ChatResponse { + return ChatResponse{ + ID: c.ID, + Title: c.Title, + MemberIDs: c.MemberIDs, + CreatedAt: c.CreatedAt, + } +} diff --git a/internal/dto/error.go b/internal/dto/error.go new file mode 100644 index 00000000..3a46305e --- /dev/null +++ b/internal/dto/error.go @@ -0,0 +1,25 @@ +package dto + +type ErrorCode string + +const ( + ErrorCodeInvalidRequest ErrorCode = "invalid_request" + ErrorCodeUnauthorized ErrorCode = "unauthorized" + ErrorCodeNotFound ErrorCode = "not_found" + ErrorCodeConflict ErrorCode = "conflict" + ErrorCodePayloadTooLarge ErrorCode = "payload_too_large" + ErrorCodeUnsupportedMediaType ErrorCode = "unsupported_media_type" + ErrorCodeRateLimited ErrorCode = "rate_limited" + ErrorCodeUnavailable ErrorCode = "unavailable" + ErrorCodeInternalError ErrorCode = "internal_error" +) + +type ErrorResponse struct { + Error Error `json:"error"` +} + +type Error struct { + Code ErrorCode `json:"code"` + Message string `json:"message"` + RequestID string `json:"request_id"` +} diff --git a/internal/dto/health.go b/internal/dto/health.go new file mode 100644 index 00000000..8bb35034 --- /dev/null +++ b/internal/dto/health.go @@ -0,0 +1,5 @@ +package dto + +type HealthResponse struct { + Status string `json:"status"` +} diff --git a/internal/dto/message.go b/internal/dto/message.go new file mode 100644 index 00000000..0997a292 --- /dev/null +++ b/internal/dto/message.go @@ -0,0 +1,46 @@ +package dto + +import ( + "mtusi2026-messenger/internal/model" + "strings" + "time" + "unicode/utf8" + + "github.com/google/uuid" +) + +type CreateMessageRequest struct { + Text string `json:"text"` +} + +type MessageResponse struct { + ID uuid.UUID `json:"id"` + ChatID uuid.UUID `json:"chat_id"` + SenderID uuid.UUID `json:"sender_id"` + Text string `json:"text"` + CreatedAt time.Time `json:"created_at"` +} + +type MessagePageResponse struct { + Items []MessageResponse `json:"items"` + NextCursor *string `json:"next_cursor"` +} + +func (r CreateMessageRequest) Validate() bool { + textLen := utf8.RuneCountInString(r.Text) + if strings.TrimSpace(r.Text) == "" || textLen > 4000 { + return false + } + + return true +} + +func ToMessageResponse(m model.Message) MessageResponse { + return MessageResponse{ + ID: m.ID, + ChatID: m.ChatID, + SenderID: m.SenderID, + Text: m.Text, + CreatedAt: m.CreatedAt, + } +} diff --git a/internal/dto/user.go b/internal/dto/user.go new file mode 100644 index 00000000..dfe826b5 --- /dev/null +++ b/internal/dto/user.go @@ -0,0 +1,37 @@ +package dto + +import ( + "regexp" + "strings" + "time" + "unicode/utf8" + + "github.com/google/uuid" +) + +var usernamePattern = regexp.MustCompile(`^[a-z0-9_]{3,32}$`) + +type CreateUserRequest struct { + Username string `json:"username"` + DisplayName string `json:"display_name"` +} + +type UserResponse struct { + ID uuid.UUID `json:"id"` + Username string `json:"username"` + DisplayName string `json:"display_name"` + CreatedAt time.Time `json:"created_at"` +} + +func (r CreateUserRequest) Validate() bool { + if !usernamePattern.MatchString(r.Username) { + return false + } + + displayNameLength := utf8.RuneCountInString(r.DisplayName) + if strings.TrimSpace(r.DisplayName) == "" || displayNameLength > 100 { + return false + } + + return true +} diff --git a/internal/handler/chat.go b/internal/handler/chat.go new file mode 100644 index 00000000..24a91788 --- /dev/null +++ b/internal/handler/chat.go @@ -0,0 +1,168 @@ +package handler + +import ( + "errors" + "net/http" + + "github.com/go-chi/chi/v5" + "github.com/google/uuid" + + "mtusi2026-messenger/internal/dto" + "mtusi2026-messenger/internal/httpx" + "mtusi2026-messenger/internal/middleware" + "mtusi2026-messenger/internal/service" +) + +type ChatHandler struct { + service *service.ChatService +} + +func NewChatHandler(service *service.ChatService) *ChatHandler { + return &ChatHandler{service: service} +} + +func (h *ChatHandler) Create(w http.ResponseWriter, r *http.Request) { + requestID := middleware.GetRequestID(r.Context()) + userID := middleware.GetUserID(r.Context()) + + var req dto.CreateChatRequest + if !httpx.DecodeJSONBody(w, r, requestID, &req) { + return + } + + if !req.Validate() { + httpx.WriteError( + w, + http.StatusBadRequest, + dto.ErrorCodeInvalidRequest, + "invalid request body", + requestID, + ) + return + } + + chat, err := h.service.Create(userID, req.Title, req.MemberIDs) + switch { + case errors.Is(err, service.ErrNotChatMember): + httpx.WriteError( + w, + http.StatusBadRequest, + dto.ErrorCodeInvalidRequest, + "caller must be a member of member_ids", + requestID, + ) + return + case errors.Is(err, service.ErrDuplicateMember): + httpx.WriteError( + w, + http.StatusBadRequest, + dto.ErrorCodeInvalidRequest, + "member_ids contains duplicates", + requestID, + ) + return + case errors.Is(err, service.ErrUnknownMember): + httpx.WriteError( + w, + http.StatusBadRequest, + dto.ErrorCodeInvalidRequest, + "member_ids contains unknown user", + requestID, + ) + return + case err != nil: + httpx.WriteError( + w, + http.StatusInternalServerError, + dto.ErrorCodeInternalError, + "internal server error", + requestID, + ) + return + } + + httpx.WriteJSON(w, http.StatusCreated, dto.ToChatResponse(chat)) +} + +func (h *ChatHandler) Get(w http.ResponseWriter, r *http.Request) { + requestID := middleware.GetRequestID(r.Context()) + userID := middleware.GetUserID(r.Context()) + + chatID, err := uuid.Parse(chi.URLParam(r, "chat_id")) + if err != nil { + httpx.WriteError( + w, + http.StatusBadRequest, + dto.ErrorCodeInvalidRequest, + "invalid chat_id", + requestID, + ) + return + } + + chat, err := h.service.Get(userID, chatID) + switch { + case errors.Is(err, service.ErrChatNotFound): + httpx.WriteError( + w, + http.StatusNotFound, + dto.ErrorCodeNotFound, + "chat not found", + requestID, + ) + return + case err != nil: + httpx.WriteError( + w, + http.StatusInternalServerError, + dto.ErrorCodeInternalError, + "internal server error", + requestID, + ) + return + } + + httpx.WriteJSON(w, http.StatusOK, dto.ToChatResponse(chat)) +} + +func (h *ChatHandler) List(w http.ResponseWriter, r *http.Request) { + requestID := middleware.GetRequestID(r.Context()) + userID := middleware.GetUserID(r.Context()) + + limit, cursor, ok := httpx.ParsePagination(w, r, requestID) + if !ok { + return + } + + chats, nextCursor, err := h.service.List(userID, limit, cursor) + switch { + case errors.Is(err, service.ErrInvalidCursor): + httpx.WriteError( + w, + http.StatusBadRequest, + dto.ErrorCodeInvalidRequest, + "invalid cursor", + requestID, + ) + return + case err != nil: + httpx.WriteError( + w, + http.StatusInternalServerError, + dto.ErrorCodeInternalError, + "internal server error", + requestID, + ) + return + } + + items := make([]dto.ChatResponse, 0, len(chats)) + for _, c := range chats { + items = append(items, dto.ToChatResponse(c)) + } + + httpx.WriteJSON(w, http.StatusOK, dto.ChatPageResponse{ + Items: items, + NextCursor: nextCursor, + }) +} diff --git a/internal/handler/error.go b/internal/handler/error.go new file mode 100644 index 00000000..34bb0bb0 --- /dev/null +++ b/internal/handler/error.go @@ -0,0 +1,27 @@ +package handler + +import ( + "encoding/json" + "net/http" + + "mtusi2026-messenger/internal/dto" +) + +func WriteError( + w http.ResponseWriter, + status int, + code dto.ErrorCode, + message string, + requestID string, +) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(status) + + _ = json.NewEncoder(w).Encode(dto.ErrorResponse{ + Error: dto.Error{ + Code: code, + Message: message, + RequestID: requestID, + }, + }) +} diff --git a/internal/handler/health.go b/internal/handler/health.go new file mode 100644 index 00000000..b6e08120 --- /dev/null +++ b/internal/handler/health.go @@ -0,0 +1,17 @@ +package handler + +import ( + "encoding/json" + "net/http" + + "mtusi2026-messenger/internal/dto" +) + +func Health(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + + _ = json.NewEncoder(w).Encode(dto.HealthResponse{ + Status: "ok", + }) +} diff --git a/internal/handler/message.go b/internal/handler/message.go new file mode 100644 index 00000000..191590e1 --- /dev/null +++ b/internal/handler/message.go @@ -0,0 +1,142 @@ +package handler + +import ( + "errors" + "net/http" + + "github.com/go-chi/chi/v5" + "github.com/google/uuid" + + "mtusi2026-messenger/internal/dto" + "mtusi2026-messenger/internal/httpx" + "mtusi2026-messenger/internal/middleware" + "mtusi2026-messenger/internal/service" +) + +type MessageHandler struct { + service *service.MessageService +} + +func NewMessageHandler(service *service.MessageService) *MessageHandler { + return &MessageHandler{service: service} +} + +func (h *MessageHandler) Create(w http.ResponseWriter, r *http.Request) { + requestID := middleware.GetRequestID(r.Context()) + userID := middleware.GetUserID(r.Context()) + + chatID, err := uuid.Parse(chi.URLParam(r, "chat_id")) + if err != nil { + httpx.WriteError( + w, + http.StatusBadRequest, + dto.ErrorCodeInvalidRequest, + "invalid chat_id", + requestID, + ) + return + } + + var req dto.CreateMessageRequest + if !httpx.DecodeJSONBody(w, r, requestID, &req) { + return + } + + if !req.Validate() { + httpx.WriteError( + w, + http.StatusBadRequest, + dto.ErrorCodeInvalidRequest, + "invalid request body", + requestID, + ) + return + } + + message, err := h.service.Create(userID, chatID, req.Text) + switch { + case errors.Is(err, service.ErrMessageChatNotFound): + httpx.WriteError( + w, + http.StatusNotFound, + dto.ErrorCodeNotFound, + "chat not found", + requestID, + ) + return + case err != nil: + httpx.WriteError( + w, + http.StatusInternalServerError, + dto.ErrorCodeInternalError, + "internal server error", + requestID, + ) + return + } + + httpx.WriteJSON(w, http.StatusCreated, dto.ToMessageResponse(message)) +} + +func (h *MessageHandler) List(w http.ResponseWriter, r *http.Request) { + requestID := middleware.GetRequestID(r.Context()) + userID := middleware.GetUserID(r.Context()) + + chatID, err := uuid.Parse(chi.URLParam(r, "chat_id")) + if err != nil { + httpx.WriteError( + w, + http.StatusBadRequest, + dto.ErrorCodeInvalidRequest, + "invalid chat_id", + requestID, + ) + return + } + + limit, cursor, ok := httpx.ParsePagination(w, r, requestID) + if !ok { + return + } + + messages, nextCursor, err := h.service.List(userID, chatID, limit, cursor) + switch { + case errors.Is(err, service.ErrMessageChatNotFound): + httpx.WriteError( + w, + http.StatusNotFound, + dto.ErrorCodeNotFound, + "chat not found", + requestID, + ) + return + case errors.Is(err, service.ErrInvalidCursor): + httpx.WriteError( + w, + http.StatusBadRequest, + dto.ErrorCodeInvalidRequest, + "invalid cursor", + requestID, + ) + return + case err != nil: + httpx.WriteError( + w, + http.StatusInternalServerError, + dto.ErrorCodeInternalError, + "internal server error", + requestID, + ) + return + } + + items := make([]dto.MessageResponse, 0, len(messages)) + for _, m := range messages { + items = append(items, dto.ToMessageResponse(m)) + } + + httpx.WriteJSON(w, http.StatusOK, dto.MessagePageResponse{ + Items: items, + NextCursor: nextCursor, + }) +} diff --git a/internal/handler/user.go b/internal/handler/user.go new file mode 100644 index 00000000..0a163090 --- /dev/null +++ b/internal/handler/user.go @@ -0,0 +1,102 @@ +package handler + +import ( + "errors" + "net/http" + + "mtusi2026-messenger/internal/dto" + "mtusi2026-messenger/internal/httpx" + "mtusi2026-messenger/internal/middleware" + "mtusi2026-messenger/internal/service" +) + +type UserHandler struct { + service *service.UserService +} + +func NewUserHandler(service *service.UserService) *UserHandler { + return &UserHandler{service: service} +} + +func (h *UserHandler) Create(w http.ResponseWriter, r *http.Request) { + requestID := middleware.GetRequestID(r.Context()) + + var req dto.CreateUserRequest + if !httpx.DecodeJSONBody(w, r, requestID, &req) { + return + } + + if !req.Validate() { + httpx.WriteError( + w, + http.StatusBadRequest, + dto.ErrorCodeInvalidRequest, + "invalid request body", + requestID, + ) + return + } + + user, err := h.service.Create(req.Username, req.DisplayName) + if errors.Is(err, service.ErrUsernameTaken) { + httpx.WriteError( + w, + http.StatusConflict, + dto.ErrorCodeConflict, + "username already taken", + requestID, + ) + return + } + if err != nil { + httpx.WriteError( + w, + http.StatusInternalServerError, + dto.ErrorCodeInternalError, + "internal server error", + requestID, + ) + return + } + + httpx.WriteJSON(w, http.StatusCreated, dto.UserResponse{ + ID: user.ID, + Username: user.Username, + DisplayName: user.DisplayName, + CreatedAt: user.CreatedAt, + }) +} + +func (h *UserHandler) Me(w http.ResponseWriter, r *http.Request) { + requestID := middleware.GetRequestID(r.Context()) + userID := middleware.GetUserID(r.Context()) + + user, err := h.service.GetByID(userID) + if errors.Is(err, service.ErrUserNotFound) { + httpx.WriteError( + w, + http.StatusNotFound, + dto.ErrorCodeNotFound, + "user not found", + requestID, + ) + return + } + if err != nil { + httpx.WriteError( + w, + http.StatusInternalServerError, + dto.ErrorCodeInternalError, + "internal server error", + requestID, + ) + return + } + + httpx.WriteJSON(w, http.StatusOK, dto.UserResponse{ + ID: user.ID, + Username: user.Username, + DisplayName: user.DisplayName, + CreatedAt: user.CreatedAt, + }) +} diff --git a/internal/httpx/pagination.go b/internal/httpx/pagination.go new file mode 100644 index 00000000..2e7e0222 --- /dev/null +++ b/internal/httpx/pagination.go @@ -0,0 +1,34 @@ +package httpx + +import ( + "net/http" + "strconv" + + "mtusi2026-messenger/internal/dto" +) + +func ParsePagination(w http.ResponseWriter, r *http.Request, requestID string) (limit int, cursor *string, ok bool) { + q := r.URL.Query() + + limit = 50 + if raw := q.Get("limit"); raw != "" { + v, err := strconv.Atoi(raw) + if err != nil || v < 1 || v > 100 { + WriteError( + w, + http.StatusBadRequest, + dto.ErrorCodeInvalidRequest, + "limit must be an integer between 1 and 100", + requestID, + ) + return 0, nil, false + } + limit = v + } + + if raw := q.Get("cursor"); raw != "" { + cursor = &raw + } + + return limit, cursor, true +} diff --git a/internal/httpx/request.go b/internal/httpx/request.go new file mode 100644 index 00000000..7a376e40 --- /dev/null +++ b/internal/httpx/request.go @@ -0,0 +1,29 @@ +package httpx + +import ( + "encoding/json" + "mime" + "net/http" + + "mtusi2026-messenger/internal/dto" +) + +func DecodeJSONBody(w http.ResponseWriter, r *http.Request, requestID string, dst any) bool { + if ct := r.Header.Get("Content-Type"); ct != "" { + mt, _, err := mime.ParseMediaType(ct) + if err != nil || mt != "application/json" { + WriteError(w, http.StatusUnsupportedMediaType, dto.ErrorCodeUnsupportedMediaType, "expected application/json", requestID) + return false + } + } + + decoder := json.NewDecoder(r.Body) + decoder.DisallowUnknownFields() + + if err := decoder.Decode(dst); err != nil { + WriteError(w, http.StatusBadRequest, dto.ErrorCodeInvalidRequest, "invalid request body", requestID) + return false + } + + return true +} diff --git a/internal/httpx/response.go b/internal/httpx/response.go new file mode 100644 index 00000000..9a12f0ba --- /dev/null +++ b/internal/httpx/response.go @@ -0,0 +1,24 @@ +package httpx + +import ( + "encoding/json" + "net/http" + + "mtusi2026-messenger/internal/dto" +) + +func WriteJSON(w http.ResponseWriter, status int, body any) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(status) + _ = json.NewEncoder(w).Encode(body) +} + +func WriteError(w http.ResponseWriter, status int, code dto.ErrorCode, message, requestID string) { + WriteJSON(w, status, dto.ErrorResponse{ + Error: dto.Error{ + Code: code, + Message: message, + RequestID: requestID, + }, + }) +} diff --git a/internal/logger/logger.go b/internal/logger/logger.go new file mode 100644 index 00000000..89ce6002 --- /dev/null +++ b/internal/logger/logger.go @@ -0,0 +1,14 @@ +package logger + +import ( + "log/slog" + "os" +) + +func New(level slog.Level) *slog.Logger { + return slog.New( + slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{ + Level: level, + }), + ) +} diff --git a/internal/middleware/auth.go b/internal/middleware/auth.go new file mode 100644 index 00000000..38cc7da3 --- /dev/null +++ b/internal/middleware/auth.go @@ -0,0 +1,65 @@ +package middleware + +import ( + "context" + "net/http" + + "github.com/google/uuid" + + "mtusi2026-messenger/internal/dto" + "mtusi2026-messenger/internal/httpx" + "mtusi2026-messenger/internal/service" +) + +type userIDContextKey struct{} + +func Auth(userService *service.UserService) func(http.Handler) http.Handler { + return func(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requestID := GetRequestID(r.Context()) + + raw := r.Header.Get("X-User-Id") + if raw == "" { + httpx.WriteError( + w, + http.StatusUnauthorized, + dto.ErrorCodeUnauthorized, + "missing X-User-Id header", + requestID, + ) + return + } + + userID, err := uuid.Parse(raw) + if err != nil { + httpx.WriteError( + w, + http.StatusUnauthorized, + dto.ErrorCodeUnauthorized, + "invalid X-User-Id header", + requestID, + ) + return + } + + if _, err := userService.GetByID(userID); err != nil { + httpx.WriteError( + w, + http.StatusUnauthorized, + dto.ErrorCodeUnauthorized, + "unknown user", + requestID, + ) + return + } + + ctx := context.WithValue(r.Context(), userIDContextKey{}, userID) + next.ServeHTTP(w, r.WithContext(ctx)) + }) + } +} + +func GetUserID(ctx context.Context) uuid.UUID { + id, _ := ctx.Value(userIDContextKey{}).(uuid.UUID) + return id +} diff --git a/internal/middleware/concurrency.go b/internal/middleware/concurrency.go new file mode 100644 index 00000000..631f4bce --- /dev/null +++ b/internal/middleware/concurrency.go @@ -0,0 +1,41 @@ +package middleware + +import ( + "net/http" + + "mtusi2026-messenger/internal/dto" + "mtusi2026-messenger/internal/httpx" +) + +func ConcurrencyLimit(max int) func(http.Handler) http.Handler { + if max <= 0 { + return func(next http.Handler) http.Handler { + return next + } + } + + slots := make(chan struct{}, max) + + return func(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + select { + case slots <- struct{}{}: + defer func() { + <-slots + }() + + next.ServeHTTP(w, r) + + default: + w.Header().Set("Retry-After", "1") + httpx.WriteError( + w, + http.StatusTooManyRequests, + dto.ErrorCodeRateLimited, + "too many requests", + GetRequestID(r.Context()), + ) + } + }) + } +} diff --git a/internal/middleware/logging.go b/internal/middleware/logging.go new file mode 100644 index 00000000..ab28a612 --- /dev/null +++ b/internal/middleware/logging.go @@ -0,0 +1,49 @@ +package middleware + +import ( + "log/slog" + "net/http" + "time" +) + +type responseWriter struct { + http.ResponseWriter + status int +} + +func (w *responseWriter) WriteHeader(status int) { + w.status = status + w.ResponseWriter.WriteHeader(status) +} + +func Logging(log *slog.Logger) func(http.Handler) http.Handler { + return func(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + start := time.Now() + + writer := &responseWriter{ + ResponseWriter: w, + status: http.StatusOK, + } + + next.ServeHTTP(writer, r) + + level := slog.LevelInfo + + switch { + case writer.status >= 500: + level = slog.LevelError + case writer.status >= 400: + level = slog.LevelWarn + } + + log.Log(r.Context(), level, "http request", + "request_id", GetRequestID(r.Context()), + "method", r.Method, + "path", r.URL.Path, + "status", writer.status, + "duration_ms", time.Since(start).Milliseconds(), + ) + }) + } +} diff --git a/internal/middleware/request_id.go b/internal/middleware/request_id.go new file mode 100644 index 00000000..d62808b0 --- /dev/null +++ b/internal/middleware/request_id.go @@ -0,0 +1,30 @@ +package middleware + +import ( + "context" + "net/http" + + "github.com/google/uuid" +) + +type requestIDContextKey struct{} + +func RequestID(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requestID := r.Header.Get("X-Request-Id") + + if requestID == "" { + requestID = uuid.NewString() + } + + w.Header().Set("X-Request-Id", requestID) + + ctx := context.WithValue(r.Context(), requestIDContextKey{}, requestID) + next.ServeHTTP(w, r.WithContext(ctx)) + }) +} + +func GetRequestID(ctx context.Context) string { + id, _ := ctx.Value(requestIDContextKey{}).(string) + return id +} diff --git a/internal/model/chat.go b/internal/model/chat.go new file mode 100644 index 00000000..2c47c490 --- /dev/null +++ b/internal/model/chat.go @@ -0,0 +1,14 @@ +package model + +import ( + "time" + + "github.com/google/uuid" +) + +type Chat struct { + ID uuid.UUID + Title string + MemberIDs []uuid.UUID + CreatedAt time.Time +} diff --git a/internal/model/message.go b/internal/model/message.go new file mode 100644 index 00000000..5c2cf5fd --- /dev/null +++ b/internal/model/message.go @@ -0,0 +1,15 @@ +package model + +import ( + "time" + + "github.com/google/uuid" +) + +type Message struct { + ID uuid.UUID + ChatID uuid.UUID + SenderID uuid.UUID + Text string + CreatedAt time.Time +} diff --git a/internal/model/user.go b/internal/model/user.go new file mode 100644 index 00000000..dc7eff16 --- /dev/null +++ b/internal/model/user.go @@ -0,0 +1,14 @@ +package model + +import ( + "time" + + "github.com/google/uuid" +) + +type User struct { + ID uuid.UUID + Username string + DisplayName string + CreatedAt time.Time +} diff --git a/internal/service/chat.go b/internal/service/chat.go new file mode 100644 index 00000000..a6f20ba2 --- /dev/null +++ b/internal/service/chat.go @@ -0,0 +1,109 @@ +package service + +import ( + "errors" + "slices" + "time" + + "github.com/google/uuid" + + "mtusi2026-messenger/internal/model" + "mtusi2026-messenger/internal/store" +) + +var ( + ErrChatNotFound = errors.New("chat not found") + ErrNotChatMember = errors.New("caller must be a member of member_ids") + ErrDuplicateMember = errors.New("member_ids contains duplicates") + ErrUnknownMember = errors.New("member_ids contains unknown user") +) + +type ChatService struct { + store *store.Memory +} + +func NewChatService(store *store.Memory) *ChatService { + return &ChatService{store: store} +} + +func (s *ChatService) Create( + userID uuid.UUID, + title string, + memberIDs []uuid.UUID, +) (model.Chat, error) { + if !slices.Contains(memberIDs, userID) { + return model.Chat{}, ErrNotChatMember + } + + chat, err := s.store.CreateChat(title, memberIDs) + switch { + case errors.Is(err, store.ErrDuplicateMember): + return model.Chat{}, ErrDuplicateMember + case errors.Is(err, store.ErrUnknownMember): + return model.Chat{}, ErrUnknownMember + case err != nil: + return model.Chat{}, err + } + + return chat, nil +} + +func (s *ChatService) Get( + userID uuid.UUID, + chatID uuid.UUID, +) (model.Chat, error) { + chat, err := s.store.GetChat(chatID, userID) + if errors.Is(err, store.ErrNotFound) { + return model.Chat{}, ErrChatNotFound + } + if err != nil { + return model.Chat{}, err + } + + return chat, nil +} + +func (s *ChatService) List( + userID uuid.UUID, + limit int, + cursor *string, +) ([]model.Chat, *string, error) { + var afterCreatedAt *time.Time + var afterID *uuid.UUID + + if cursor != nil { + decoded, err := decodeCursor(*cursor) + if err != nil { + return nil, nil, ErrInvalidCursor + } + + afterCreatedAt = &decoded.CreatedAt + afterID = &decoded.ID + } + + chats, hasMore, err := s.store.ListChats( + userID, + afterCreatedAt, + afterID, + limit, + ) + if errors.Is(err, store.ErrInvalidCursor) { + return nil, nil, ErrInvalidCursor + } + if err != nil { + return nil, nil, err + } + + var next *string + if hasMore && len(chats) > 0 { + last := chats[len(chats)-1] + + c := encodeCursor(Cursor{ + CreatedAt: last.CreatedAt, + ID: last.ID, + }) + next = &c + } + + return chats, next, nil +} diff --git a/internal/service/cursor.go b/internal/service/cursor.go new file mode 100644 index 00000000..b727bd1e --- /dev/null +++ b/internal/service/cursor.go @@ -0,0 +1,40 @@ +package service + +import ( + "encoding/base64" + "encoding/json" + "errors" + "time" + + "github.com/google/uuid" +) + +var ErrInvalidCursor = errors.New("invalid cursor") + +type Cursor struct { + CreatedAt time.Time `json:"created_at"` + ID uuid.UUID `json:"id"` +} + +func encodeCursor(cursor Cursor) string { + data, _ := json.Marshal(cursor) + return base64.RawURLEncoding.EncodeToString(data) +} + +func decodeCursor(raw string) (Cursor, error) { + data, err := base64.RawURLEncoding.DecodeString(raw) + if err != nil { + return Cursor{}, ErrInvalidCursor + } + + var cursor Cursor + if err := json.Unmarshal(data, &cursor); err != nil { + return Cursor{}, ErrInvalidCursor + } + + if cursor.ID == uuid.Nil || cursor.CreatedAt.IsZero() { + return Cursor{}, ErrInvalidCursor + } + + return cursor, nil +} diff --git a/internal/service/message.go b/internal/service/message.go new file mode 100644 index 00000000..93cb2f7a --- /dev/null +++ b/internal/service/message.go @@ -0,0 +1,87 @@ +package service + +import ( + "errors" + "time" + + "github.com/google/uuid" + + "mtusi2026-messenger/internal/model" + "mtusi2026-messenger/internal/store" +) + +var ErrMessageChatNotFound = errors.New("chat not found") + +type MessageService struct { + store *store.Memory +} + +func NewMessageService(store *store.Memory) *MessageService { + return &MessageService{store: store} +} + +func (s *MessageService) Create( + userID uuid.UUID, + chatID uuid.UUID, + text string, +) (model.Message, error) { + message, err := s.store.CreateMessage(chatID, userID, text) + if errors.Is(err, store.ErrNotFound) { + return model.Message{}, ErrMessageChatNotFound + } + if err != nil { + return model.Message{}, err + } + + return message, nil +} + +func (s *MessageService) List( + userID uuid.UUID, + chatID uuid.UUID, + limit int, + cursor *string, +) ([]model.Message, *string, error) { + var afterCreatedAt *time.Time + var afterID *uuid.UUID + + if cursor != nil { + decoded, err := decodeCursor(*cursor) + if err != nil { + return nil, nil, ErrInvalidCursor + } + + afterCreatedAt = &decoded.CreatedAt + afterID = &decoded.ID + } + + messages, hasMore, err := s.store.ListMessages( + chatID, + userID, + afterCreatedAt, + afterID, + limit, + ) + if errors.Is(err, store.ErrNotFound) { + return nil, nil, ErrMessageChatNotFound + } + if errors.Is(err, store.ErrInvalidCursor) { + return nil, nil, ErrInvalidCursor + } + if err != nil { + return nil, nil, err + } + + var next *string + if hasMore && len(messages) > 0 { + last := messages[len(messages)-1] + + c := encodeCursor(Cursor{ + CreatedAt: last.CreatedAt, + ID: last.ID, + }) + next = &c + } + + return messages, next, nil +} diff --git a/internal/service/user.go b/internal/service/user.go new file mode 100644 index 00000000..140d4cc9 --- /dev/null +++ b/internal/service/user.go @@ -0,0 +1,47 @@ +package service + +import ( + "errors" + + "github.com/google/uuid" + + "mtusi2026-messenger/internal/model" + "mtusi2026-messenger/internal/store" +) + +var ( + ErrUserNotFound = errors.New("user not found") + ErrUsernameTaken = errors.New("username already taken") +) + +type UserService struct { + store *store.Memory +} + +func NewUserService(store *store.Memory) *UserService { + return &UserService{store: store} +} + +func (s *UserService) Create(username, displayName string) (model.User, error) { + user, err := s.store.CreateUser(username, displayName) + if errors.Is(err, store.ErrConflict) { + return model.User{}, ErrUsernameTaken + } + if err != nil { + return model.User{}, err + } + + return user, nil +} + +func (s *UserService) GetByID(id uuid.UUID) (model.User, error) { + user, err := s.store.GetUser(id) + if errors.Is(err, store.ErrNotFound) { + return model.User{}, ErrUserNotFound + } + if err != nil { + return model.User{}, err + } + + return user, nil +} diff --git a/internal/store/memory.go b/internal/store/memory.go new file mode 100644 index 00000000..8783c0ee --- /dev/null +++ b/internal/store/memory.go @@ -0,0 +1,236 @@ +package store + +import ( + "errors" + "slices" + "sort" + "sync" + "time" + + "github.com/google/uuid" + + "mtusi2026-messenger/internal/model" +) + +var ( + ErrNotFound = errors.New("not found") + ErrConflict = errors.New("conflict") + ErrDuplicateMember = errors.New("duplicate member id") + ErrUnknownMember = errors.New("unknown member id") + ErrInvalidCursor = errors.New("invalid cursor") +) + +type Memory struct { + mu sync.RWMutex + + users map[uuid.UUID]model.User + usersByUsername map[string]uuid.UUID + chats map[uuid.UUID]model.Chat + messages map[uuid.UUID]model.Message + chatMessages map[uuid.UUID][]uuid.UUID +} + +func New() *Memory { + return &Memory{ + users: make(map[uuid.UUID]model.User), + usersByUsername: make(map[string]uuid.UUID), + chats: make(map[uuid.UUID]model.Chat), + messages: make(map[uuid.UUID]model.Message), + chatMessages: make(map[uuid.UUID][]uuid.UUID), + } +} + +func (m *Memory) CreateUser(username, displayName string) (model.User, error) { + m.mu.Lock() + defer m.mu.Unlock() + + if _, exists := m.usersByUsername[username]; exists { + return model.User{}, ErrConflict + } + + user := model.User{ + ID: uuid.New(), + Username: username, + DisplayName: displayName, + CreatedAt: time.Now().UTC(), + } + + m.users[user.ID] = user + m.usersByUsername[user.Username] = user.ID + + return user, nil +} + +func (m *Memory) GetUser(id uuid.UUID) (model.User, error) { + m.mu.RLock() + defer m.mu.RUnlock() + + user, exists := m.users[id] + if !exists { + return model.User{}, ErrNotFound + } + + return user, nil +} + +func (m *Memory) CreateChat(title string, memberIDs []uuid.UUID) (model.Chat, error) { + m.mu.Lock() + defer m.mu.Unlock() + + seen := make(map[uuid.UUID]struct{}, len(memberIDs)) + for _, id := range memberIDs { + if _, dup := seen[id]; dup { + return model.Chat{}, ErrDuplicateMember + } + seen[id] = struct{}{} + + if _, exists := m.users[id]; !exists { + return model.Chat{}, ErrUnknownMember + } + } + + chat := model.Chat{ + ID: uuid.New(), + Title: title, + MemberIDs: append([]uuid.UUID(nil), memberIDs...), + CreatedAt: time.Now().UTC(), + } + + m.chats[chat.ID] = chat + + return chat, nil +} + +func (m *Memory) GetChat(id uuid.UUID, userID uuid.UUID) (model.Chat, error) { + m.mu.RLock() + defer m.mu.RUnlock() + + chat, exists := m.chats[id] + if !exists || !slices.Contains(chat.MemberIDs, userID) { + return model.Chat{}, ErrNotFound + } + + chat.MemberIDs = append([]uuid.UUID(nil), chat.MemberIDs...) + + return chat, nil +} + +func (m *Memory) ListChats( + userID uuid.UUID, + afterCreatedAt *time.Time, + afterID *uuid.UUID, + limit int, +) ([]model.Chat, bool, error) { + m.mu.RLock() + defer m.mu.RUnlock() + + chats := make([]model.Chat, 0) + for _, c := range m.chats { + if slices.Contains(c.MemberIDs, userID) { + c.MemberIDs = append([]uuid.UUID(nil), c.MemberIDs...) + chats = append(chats, c) + } + } + + sort.Slice(chats, func(i, j int) bool { + if !chats[i].CreatedAt.Equal(chats[j].CreatedAt) { + return chats[i].CreatedAt.Before(chats[j].CreatedAt) + } + return chats[i].ID.String() < chats[j].ID.String() + }) + + start := 0 + if afterCreatedAt != nil && afterID != nil { + start = sort.Search(len(chats), func(i int) bool { + chat := chats[i] + + return chat.CreatedAt.After(*afterCreatedAt) || + (chat.CreatedAt.Equal(*afterCreatedAt) && + chat.ID.String() > afterID.String()) + }) + } + + end := start + limit + hasMore := end < len(chats) + if end > len(chats) { + end = len(chats) + } + + return chats[start:end], hasMore, nil +} + +func (m *Memory) CreateMessage( + chatID uuid.UUID, + senderID uuid.UUID, + text string, +) (model.Message, error) { + m.mu.Lock() + defer m.mu.Unlock() + + chat, exists := m.chats[chatID] + if !exists || !slices.Contains(chat.MemberIDs, senderID) { + return model.Message{}, ErrNotFound + } + + message := model.Message{ + ID: uuid.New(), + ChatID: chatID, + SenderID: senderID, + Text: text, + CreatedAt: time.Now().UTC(), + } + + m.messages[message.ID] = message + m.chatMessages[chatID] = append(m.chatMessages[chatID], message.ID) + + return message, nil +} + +func (m *Memory) ListMessages( + chatID uuid.UUID, + userID uuid.UUID, + afterCreatedAt *time.Time, + afterID *uuid.UUID, + limit int, +) ([]model.Message, bool, error) { + m.mu.RLock() + defer m.mu.RUnlock() + + chat, exists := m.chats[chatID] + if !exists || !slices.Contains(chat.MemberIDs, userID) { + return nil, false, ErrNotFound + } + + ids := m.chatMessages[chatID] + messages := make([]model.Message, 0, len(ids)) + + for _, id := range ids { + messages = append(messages, m.messages[id]) + } + + sort.Slice(messages, func(i, j int) bool { + if !messages[i].CreatedAt.Equal(messages[j].CreatedAt) { + return messages[i].CreatedAt.Before(messages[j].CreatedAt) + } + return messages[i].ID.String() < messages[j].ID.String() + }) + + start := 0 + if afterCreatedAt != nil && afterID != nil { + start = sort.Search(len(messages), func(i int) bool { + msg := messages[i] + + return msg.CreatedAt.After(*afterCreatedAt) || + (msg.CreatedAt.Equal(*afterCreatedAt) && + msg.ID.String() > afterID.String()) + }) + } + + end := start + limit + hasMore := end < len(messages) + if end > len(messages) { + end = len(messages) + } + + return messages[start:end], hasMore, nil +} diff --git a/student-tests/contract_test.go b/student-tests/contract_test.go new file mode 100644 index 00000000..08535e8a --- /dev/null +++ b/student-tests/contract_test.go @@ -0,0 +1,135 @@ +//go:build contract + +package studenttests_test + +import ( + "encoding/json" + "net/http" + "net/url" + "strconv" + "testing" + + "github.com/google/uuid" + + "mtusi2026-messenger/internal/dto" +) + +func TestInvalidJSON(t *testing.T) { + resp := doRequest(t, http.MethodPost, "/api/v1/users", uuid.Nil, []byte(`{"username": "broken",`)) + requireStatus(t, resp, http.StatusBadRequest) + + var apiErr dto.ErrorResponse + mustDecode(t, resp, &apiErr) + + if apiErr.Error.Code != dto.ErrorCodeInvalidRequest { + t.Errorf("expected code %q, got %q", dto.ErrorCodeInvalidRequest, apiErr.Error.Code) + } +} + +func TestForeignChat(t *testing.T) { + user1 := createUser(t) + user2 := createUser(t) + user3 := createUser(t) + + chat := createChat(t, user1, user1.ID, user2.ID) + + resp := doRequest(t, http.MethodGet, "/api/v1/chats/"+chat.ID.String(), user3.ID, nil) + requireStatus(t, resp, http.StatusNotFound) + + resp = sendMessage(t, user3, chat.ID, "should not land") + requireStatus(t, resp, http.StatusNotFound) +} + +func TestEmptyMessage(t *testing.T) { + user := createUser(t) + chat := createChat(t, user, user.ID) + + for _, text := range []string{"", " ", "\t\n"} { + resp := sendMessage(t, user, chat.ID, text) + requireStatus(t, resp, http.StatusBadRequest) + } +} + +func TestDuplicateUsername(t *testing.T) { + user := createUser(t) + + body, err := json.Marshal(map[string]string{ + "username": user.Username, + "display_name": "Someone else", + }) + if err != nil { + t.Fatalf("marshal body: %v", err) + } + + resp := doRequest(t, http.MethodPost, "/api/v1/users", uuid.Nil, body) + requireStatus(t, resp, http.StatusConflict) + + var apiErr dto.ErrorResponse + mustDecode(t, resp, &apiErr) + + if apiErr.Error.Code != dto.ErrorCodeConflict { + t.Errorf("expected code %q, got %q", dto.ErrorCodeConflict, apiErr.Error.Code) + } +} + +func TestPagination(t *testing.T) { + user := createUser(t) + chat := createChat(t, user, user.ID) + + const total = 25 + const pageSize = 4 + + sent := make(map[string]bool, total) + for i := 0; i < total; i++ { + resp := sendMessage(t, user, chat.ID, "msg") + requireStatus(t, resp, http.StatusCreated) + + var msg dto.MessageResponse + mustDecode(t, resp, &msg) + sent[msg.ID.String()] = true + } + + seen := make(map[string]bool, total) + cursor := "" + pages := 0 + + for { + path := "/api/v1/chats/" + chat.ID.String() + "/messages?limit=" + strconv.Itoa(pageSize) + if cursor != "" { + path += "&cursor=" + url.QueryEscape(cursor) + } + + resp := doRequest(t, http.MethodGet, path, user.ID, nil) + requireStatus(t, resp, http.StatusOK) + + var page dto.MessagePageResponse + mustDecode(t, resp, &page) + pages++ + + for _, msg := range page.Items { + id := msg.ID.String() + if seen[id] { + t.Fatalf("duplicate message id across pages: %s", id) + } + seen[id] = true + } + + if page.NextCursor == nil { + break + } + cursor = *page.NextCursor + + if pages > total { + t.Fatalf("too many pages: got %d, expected at most %d", pages, total) + } + } + + if len(seen) != total { + t.Fatalf("expected %d unique messages across all pages, got %d", total, len(seen)) + } + for id := range sent { + if !seen[id] { + t.Fatalf("message %s sent but never seen while paginating", id) + } + } +} diff --git a/student-tests/helpers_test.go b/student-tests/helpers_test.go new file mode 100644 index 00000000..4e32c05c --- /dev/null +++ b/student-tests/helpers_test.go @@ -0,0 +1,198 @@ +package studenttests_test + +import ( + "bytes" + "encoding/json" + "flag" + "fmt" + "io" + "net/http" + "strings" + "testing" + "time" + + "github.com/google/uuid" + + "mtusi2026-messenger/internal/dto" +) + +var baseURL = flag.String("base-url", "http://127.0.0.1:8080", "base URL of the running server") + +var httpClient = &http.Client{ + Timeout: 10 * time.Second, + Transport: &http.Transport{ + MaxIdleConns: 200, + IdleConnTimeout: 30 * time.Second, + MaxIdleConnsPerHost: 200, + MaxConnsPerHost: 200, + }, +} + +func doRequest(t *testing.T, method, path string, actorID uuid.UUID, body []byte) *http.Response { + t.Helper() + + req, err := http.NewRequest(method, *baseURL+path, bytes.NewReader(body)) + if err != nil { + t.Fatalf("build request: %v", err) + } + + if body != nil { + req.Header.Set("Content-Type", "application/json") + } + + if actorID != uuid.Nil { + req.Header.Set("X-User-Id", actorID.String()) + } + + resp, err := httpClient.Do(req) + if err != nil { + t.Fatalf("%s %s: request failed: %v", method, path, err) + } + + return resp +} + +func mustDecode(t *testing.T, resp *http.Response, dst any) { + t.Helper() + defer resp.Body.Close() + + data, err := io.ReadAll(resp.Body) + if err != nil { + t.Fatalf("read body: %v", err) + } + + if err := json.Unmarshal(data, dst); err != nil { + t.Fatalf("decode body %q: %v", data, err) + } +} + +func requireStatus(t *testing.T, resp *http.Response, expected int) { + t.Helper() + + if resp.StatusCode != expected { + data, _ := io.ReadAll(resp.Body) + resp.Body.Close() + + t.Fatalf( + "expected status %d, got %d, body: %s", + expected, + resp.StatusCode, + data, + ) + } + + if resp.Header.Get("X-Request-Id") == "" { + t.Errorf("missing X-Request-Id header") + } +} + +func createUser(t *testing.T) dto.UserResponse { + t.Helper() + + username := "u_" + strings.ReplaceAll(uuid.NewString(), "-", "")[:12] + + body, err := json.Marshal(map[string]string{ + "username": username, + "display_name": "Test " + username, + }) + if err != nil { + t.Fatalf("marshal user: %v", err) + } + + resp := doRequest( + t, + http.MethodPost, + "/api/v1/users", + uuid.Nil, + body, + ) + + requireStatus(t, resp, http.StatusCreated) + + var u dto.UserResponse + mustDecode(t, resp, &u) + + return u +} + +func createChat( + t *testing.T, + creator dto.UserResponse, + memberIDs ...uuid.UUID, +) dto.ChatResponse { + t.Helper() + + body, err := json.Marshal(map[string]any{ + "title": "Test chat " + uuid.NewString()[:8], + "member_ids": memberIDs, + }) + if err != nil { + t.Fatalf("marshal chat: %v", err) + } + + resp := doRequest( + t, + http.MethodPost, + "/api/v1/chats", + creator.ID, + body, + ) + + requireStatus(t, resp, http.StatusCreated) + + var c dto.ChatResponse + mustDecode(t, resp, &c) + + return c +} + +func sendMessage( + t *testing.T, + actor dto.UserResponse, + chatID uuid.UUID, + text string, +) *http.Response { + t.Helper() + + body, err := json.Marshal(map[string]string{ + "text": text, + }) + if err != nil { + t.Fatalf("marshal message: %v", err) + } + + return doRequest( + t, + http.MethodPost, + fmt.Sprintf("/api/v1/chats/%v/messages", chatID.String()), + actor.ID, + body, + ) +} + +func sendLoadMessage( + actor dto.UserResponse, + chatID uuid.UUID, + text string, +) (*http.Response, error) { + body, err := json.Marshal(map[string]string{ + "text": text, + }) + if err != nil { + return nil, err + } + + req, err := http.NewRequest( + http.MethodPost, + *baseURL+"/api/v1/chats/"+chatID.String()+"/messages", + bytes.NewReader(body), + ) + if err != nil { + return nil, err + } + + req.Header.Set("Content-Type", "application/json") + req.Header.Set("X-User-Id", actor.ID.String()) + + return httpClient.Do(req) +} diff --git a/student-tests/load_test.go b/student-tests/load_test.go new file mode 100644 index 00000000..f7b09041 --- /dev/null +++ b/student-tests/load_test.go @@ -0,0 +1,138 @@ +//go:build load + +package studenttests_test + +import ( + "flag" + "io" + "net/http" + "sort" + "sync" + "sync/atomic" + "testing" + "time" +) + +var ( + workers = flag.Int("workers", 20, "number of concurrent workers") + duration = flag.Duration("duration", 5*time.Second, "test duration") + rate = flag.Int("rate", 20, "maximum requests per second per worker") +) + +func TestLoad(t *testing.T) { + var ( + statuses = make(map[int]int64) + requestErrors int64 + latencies []time.Duration + statusMu sync.Mutex + latencyMu sync.Mutex + wg sync.WaitGroup + ) + + user1 := createUser(t) + user2 := createUser(t) + chat := createChat(t, user1, user1.ID, user2.ID) + + start := time.Now() + deadline := start.Add(*duration) + + interval := time.Second / time.Duration(*rate) + + for worker := 0; worker < *workers; worker++ { + wg.Add(1) + + go func(workerID int) { + defer wg.Done() + + actor := user1 + if workerID%2 == 1 { + actor = user2 + } + + ticker := time.NewTicker(interval) + defer ticker.Stop() + + for time.Now().Before(deadline) { + <-ticker.C + + if time.Now().After(deadline) { + return + } + + requestStart := time.Now() + + resp, err := sendLoadMessage( + actor, + chat.ID, + "load-msg", + ) + + latency := time.Since(requestStart) + + if err != nil { + if atomic.CompareAndSwapInt64(&requestErrors, 0, 1) { + t.Logf("first transport error: %v", err) + } + atomic.AddInt64(&requestErrors, 1) + continue + } + + statusMu.Lock() + statuses[resp.StatusCode]++ + statusMu.Unlock() + + if resp.StatusCode == http.StatusCreated { + latencyMu.Lock() + latencies = append(latencies, latency) + latencyMu.Unlock() + } + + io.Copy(io.Discard, resp.Body) + resp.Body.Close() + } + }(worker) + } + + wg.Wait() + + elapsed := time.Since(start) + + var total int64 + for _, count := range statuses { + total += count + } + total += requestErrors + + t.Logf("duration: %.3fs", elapsed.Seconds()) + t.Logf("workers: %d", *workers) + t.Logf("rate per worker: %d req/s", *rate) + t.Logf("target rate: %d req/s", *workers**rate) + t.Logf("total requests: %d", total) + + for status, count := range statuses { + t.Logf("HTTP %d: %d", status, count) + } + + t.Logf("request errors: %d", requestErrors) + + successful := statuses[http.StatusCreated] + + t.Logf("successful RPS: %.2f", + float64(successful)/elapsed.Seconds(), + ) + + if len(latencies) > 0 { + sort.Slice(latencies, func(i, j int) bool { + return latencies[i] < latencies[j] + }) + + t.Logf("successful latency p50: %s", percentile(latencies, 0.50)) + t.Logf("successful latency p95: %s", percentile(latencies, 0.95)) + t.Logf("successful latency p99: %s", percentile(latencies, 0.99)) + } +} + +func percentile(values []time.Duration, p float64) time.Duration { + index := int(float64(len(values)-1) * p) + return values[index] +} diff --git a/student-tests/race_test.go b/student-tests/race_test.go new file mode 100644 index 00000000..67d17689 --- /dev/null +++ b/student-tests/race_test.go @@ -0,0 +1,100 @@ +//go:build race + +package studenttests_test + +import ( + "net/http" + "sync" + "testing" + + "mtusi2026-messenger/internal/dto" +) + +func TestConcurrentMessages(t *testing.T) { + const clients = 10 + const messagesPerClient = 10 + const total = clients * messagesPerClient + + user1 := createUser(t) + user2 := createUser(t) + chat := createChat(t, user1, user1.ID, user2.ID) + + var wg sync.WaitGroup + var mu sync.Mutex + sentIDs := make(map[string]bool, total) + + start := make(chan struct{}) + + for worker := 0; worker < clients; worker++ { + wg.Add(1) + + go func(workerID int) { + defer wg.Done() + + actor := user1 + if workerID%2 == 1 { + actor = user2 + } + + <-start + + for i := 0; i < messagesPerClient; i++ { + resp := sendMessage(t, actor, chat.ID, "race-msg") + if resp.StatusCode != http.StatusCreated { + t.Errorf("worker %d msg %d: expected 201, got %d", workerID, i, resp.StatusCode) + resp.Body.Close() + continue + } + + var m dto.MessageResponse + mustDecode(t, resp, &m) + + mu.Lock() + sentIDs[m.ID.String()] = true + mu.Unlock() + } + }(worker) + } + + close(start) + wg.Wait() + + if t.Failed() { + t.Fatal("one or more send requests failed, see errors above") + } + + if len(sentIDs) != total { + t.Fatalf("expected %d successful sends, got %d unique ids", total, len(sentIDs)) + } + + seen := make(map[string]bool, total) + + path := "/api/v1/chats/" + chat.ID.String() + "/messages?limit=100" + resp := doRequest(t, http.MethodGet, path, user1.ID, nil) + requireStatus(t, resp, http.StatusOK) + + var page dto.MessagePageResponse + mustDecode(t, resp, &page) + + if page.NextCursor != nil { + t.Fatalf("expected next_cursor to be nil, history may contain more than %d messages", total) + } + + for _, msg := range page.Items { + id := msg.ID.String() + if seen[id] { + t.Fatalf("duplicate message id in history: %s", id) + } + if !sentIDs[id] { + t.Fatalf("message %s in history was never sent by this test", id) + } + seen[id] = true + } + + if len(seen) != total { + t.Fatalf("expected exactly %d unique messages in history, got %d", total, len(seen)) + } + + t.Logf("PASS: %d concurrent clients sent %d messages, exactly %d unique messages persisted", + clients, total, len(seen)) +} diff --git a/student.mk b/student.mk new file mode 100644 index 00000000..8de59f03 --- /dev/null +++ b/student.mk @@ -0,0 +1,17 @@ +LOAD_ARGS = $(if $(LOAD_WORKERS),-workers=$(LOAD_WORKERS),) \ + $(if $(LOAD_DURATION),-duration=$(LOAD_DURATION),) \ + $(if $(LOAD_RATE),-rate=$(LOAD_RATE),) + +.PHONY: help-go contract-go race-go load-go + +help-go: + @echo "contract-go: student contract tests; race-go: concurrency test with -race; load-go: Go load test" + +contract-go: + go test -tags=contract ./student-tests/... -v -args -base-url=$(BASE_URL) + +race-go: + go test -tags=race ./student-tests/... -race -v -args -base-url=$(BASE_URL) + +load-go: + go test -tags=load ./student-tests/... -v -args -base-url=$(BASE_URL) $(LOAD_ARGS) diff --git a/web/swagger/index.html b/web/swagger/index.html new file mode 100644 index 00000000..c498b1bf --- /dev/null +++ b/web/swagger/index.html @@ -0,0 +1,21 @@ + + + + + MTUSI Messenger API + + + +
+ + + + + \ No newline at end of file -- 2.54.0 From 4c1d08f8a8727a1de03dfd78c0bcfae4a5d13a07 Mon Sep 17 00:00:00 2001 From: kk10 Date: Sat, 3 Oct 2026 11:40:26 +0300 Subject: [PATCH 02/40] feat(db): add postgres, goose migrations and initial schema --- Dockerfile.migrate | 8 ++++++ docker-compose.yml | 47 +++++++++++++++++++++++++++++++++--- migrations/00001_init.sql | 51 +++++++++++++++++++++++++++++++++++++++ 3 files changed, 103 insertions(+), 3 deletions(-) create mode 100644 Dockerfile.migrate create mode 100644 migrations/00001_init.sql diff --git a/Dockerfile.migrate b/Dockerfile.migrate new file mode 100644 index 00000000..8bcb4171 --- /dev/null +++ b/Dockerfile.migrate @@ -0,0 +1,8 @@ +FROM golang:1.27.1-alpine3.24 AS build +ENV CGO_ENABLED=0 +RUN go install github.com/pressly/goose/v3/cmd/goose@v3.28.0 + +FROM alpine:3.24 +COPY --from=build /go/bin/goose /usr/local/bin/goose +COPY migrations /migrations +ENTRYPOINT ["sh", "-c", "goose -dir /migrations postgres \"$(cat /run/secrets/database_url)\" up"] diff --git a/docker-compose.yml b/docker-compose.yml index 08adff47..02e19ac0 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,12 +1,53 @@ services: - messenger: + backend: build: context: . dockerfile: Dockerfile - image: mtusi-messenger:lab1 - container_name: mtusi-messenger-lab1 + image: mtusi-messenger:lab2 ports: - "127.0.0.1:8080:${APP_PORT}" env_file: - .env + secrets: + - database_url + depends_on: + migrate: + condition: service_completed_successfully restart: unless-stopped + + postgres: + image: postgres:18.6 + environment: + POSTGRES_USER: messenger + POSTGRES_DB: messenger + POSTGRES_PASSWORD_FILE: /run/secrets/postgres_password + secrets: + - postgres_password + volumes: + - pgdata:/var/lib/postgresql + healthcheck: + test: ["CMD-SHELL", "pg_isready -h 127.0.0.1 -U $${POSTGRES_USER} -d $${POSTGRES_DB}"] + interval: 5s + timeout: 3s + retries: 10 + restart: unless-stopped + + migrate: + build: + context: . + dockerfile: Dockerfile.migrate + secrets: + - database_url + depends_on: + postgres: + condition: service_healthy + restart: "no" + +secrets: + postgres_password: + file: ./secrets/postgres_password.txt + database_url: + file: ./secrets/database_url.txt + +volumes: + pgdata: diff --git a/migrations/00001_init.sql b/migrations/00001_init.sql new file mode 100644 index 00000000..ae4b6415 --- /dev/null +++ b/migrations/00001_init.sql @@ -0,0 +1,51 @@ +-- +goose Up +CREATE TABLE users ( + id uuid PRIMARY KEY, + username text NOT NULL UNIQUE + CONSTRAINT users_username_format CHECK (username ~ '^[a-z0-9_]{3,32}$'), + display_name text NOT NULL + CONSTRAINT users_display_name_not_blank CHECK (display_name ~ '\S'), + password_hash text NOT NULL, + created_at timestamptz NOT NULL DEFAULT now() +); + +CREATE TABLE sessions ( + token_hash text PRIMARY KEY, + user_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE, + created_at timestamptz NOT NULL DEFAULT now(), + expires_at timestamptz NOT NULL +); + +CREATE INDEX idx_sessions_expires_at ON sessions (expires_at); + +CREATE TABLE chats ( + id uuid PRIMARY KEY, + title text NOT NULL + CONSTRAINT chats_title_not_blank CHECK (title ~ '\S'), + created_at timestamptz NOT NULL DEFAULT now() +); + +CREATE TABLE chat_members ( + chat_id uuid NOT NULL REFERENCES chats (id) ON DELETE CASCADE, + user_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE, + PRIMARY KEY (chat_id, user_id) +); + +CREATE INDEX idx_chat_members_user_id ON chat_members (user_id); + +CREATE TABLE messages ( + id uuid PRIMARY KEY, + chat_id uuid NOT NULL REFERENCES chats (id) ON DELETE CASCADE, + sender_id uuid NOT NULL REFERENCES users (id) ON DELETE RESTRICT, + text text NOT NULL, + created_at timestamptz NOT NULL DEFAULT now() +); + +CREATE INDEX idx_messages_chat_history ON messages (chat_id, created_at, id); + +-- +goose Down +DROP TABLE messages; +DROP TABLE chat_members; +DROP TABLE chats; +DROP TABLE sessions; +DROP TABLE users; -- 2.54.0 From 60fad0fca7b087eeae33594593d3d0b5c9a2704d Mon Sep 17 00:00:00 2001 From: kk10 Date: Sat, 3 Oct 2026 12:32:09 +0300 Subject: [PATCH 03/40] feat(config): add database secret file and session TTL settings --- .env.example | 7 +----- internal/config/config.go | 52 +++++++++++++++++++++++++++++++++++++-- 2 files changed, 51 insertions(+), 8 deletions(-) diff --git a/.env.example b/.env.example index 32b5e232..25f9cfdb 100644 --- a/.env.example +++ b/.env.example @@ -1,15 +1,10 @@ -# Copy to .env for your LOCAL synthetic test environment; never commit .env. -# These are logical interface suggestions; map actual framework names in REPORT.md. APP_HOST=0.0.0.0 APP_PORT=8080 -APP_ENV=lab - MAX_INFLIGHT_REQUESTS=0 +SESSION_TTL_SECONDS=3600 LOG_LEVEL=INFO -SESSION_TTL_SECONDS=3600 -# Choose credentials locally. File paths contain no secret values. DATABASE_URL_FILE=/run/secrets/database_url # Optional on 3, required use on 4 in lab2; Redis OR Valkey: SESSION_STORE=postgres diff --git a/internal/config/config.go b/internal/config/config.go index 710eb9bd..2c0d222c 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -1,40 +1,59 @@ package config import ( + "fmt" "log" "log/slog" "os" "strconv" + "strings" + "time" ) type Config struct { - Server ServerConfig - Logging LoggingConfig + Server ServerConfig + Logging LoggingConfig + Database DatabaseConfig } type ServerConfig struct { Host string Port string MaxInflightRequests int + SessionTTL time.Duration } type LoggingConfig struct { Level slog.Level } +type DatabaseConfig struct { + URLFile string +} + +func (c DatabaseConfig) URL() (string, error) { + return readSecretFile(c.URLFile) +} + func Load() Config { return Config{ Server: ServerConfig{ Host: getEnv("APP_HOST", "0.0.0.0"), Port: getEnv("APP_PORT", "8080"), MaxInflightRequests: getEnvNonNegativeInt("MAX_INFLIGHT_REQUESTS", 0), + SessionTTL: time.Duration(getEnvPositiveInt("SESSION_TTL_SECONDS", 3600)) * time.Second, }, Logging: LoggingConfig{ Level: getEnvLogLevel("LOG_LEVEL", slog.LevelInfo), }, + + Database: DatabaseConfig{ + URLFile: getEnv("DATABASE_URL_FILE", "/run/secrets/database_url"), + }, } } + func getEnv(key, def string) string { value := os.Getenv(key) if value == "" { @@ -59,6 +78,21 @@ func getEnvNonNegativeInt(key string, def int) int { return value } +func getEnvPositiveInt(key string, def int) int { + v := os.Getenv(key) + if v == "" { + return def + } + + value, err := strconv.Atoi(v) + if err != nil || value <= 0 { + log.Printf("invalid positive int for %s=%q, using default %d", key, v, def) + return def + } + + return value +} + func getEnvLogLevel(key string, def slog.Level) slog.Level { v := os.Getenv(key) @@ -78,3 +112,17 @@ func getEnvLogLevel(key string, def slog.Level) slog.Level { return def } } + +func readSecretFile(path string) (string, error) { + b, err := os.ReadFile(path) + if err != nil { + return "", fmt.Errorf("read secret file %s: %w", path, err) + } + + value := strings.TrimSpace(string(b)) + if value == "" { + return "", fmt.Errorf("secret file %s is empty", path) + } + + return value, nil +} -- 2.54.0 From 492e0be15cf102e1bafc879dfc4e5da2629ee9dc Mon Sep 17 00:00:00 2001 From: kk10 Date: Sat, 3 Oct 2026 12:36:05 +0300 Subject: [PATCH 04/40] feat(db): connect to PostgreSQL and check it in /health/ready --- go.mod | 9 ++++++++ go.sum | 26 ++++++++++++++++++++++ internal/app/app.go | 23 +++++++++++++++++++- internal/app/router.go | 6 ++++-- internal/db/db.go | 34 +++++++++++++++++++++++++++++ internal/handler/health.go | 44 +++++++++++++++++++++++++++++++++++++- 6 files changed, 138 insertions(+), 4 deletions(-) create mode 100644 internal/db/db.go diff --git a/go.mod b/go.mod index 1930f284..0273f917 100644 --- a/go.mod +++ b/go.mod @@ -5,5 +5,14 @@ go 1.25.0 require ( github.com/go-chi/chi/v5 v5.3.2 github.com/google/uuid v1.6.0 + github.com/jackc/pgx/v5 v5.11.0 github.com/joho/godotenv v1.5.1 ) + +require ( + github.com/jackc/pgpassfile v1.0.0 // indirect + github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect + github.com/jackc/puddle/v2 v2.2.2 // indirect + golang.org/x/sync v0.17.0 // indirect + golang.org/x/text v0.29.0 // indirect +) diff --git a/go.sum b/go.sum index 02c75233..a9f25227 100644 --- a/go.sum +++ b/go.sum @@ -1,6 +1,32 @@ +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/go-chi/chi/v5 v5.3.2 h1:5YQkICvTCSZ25hoRsyJazN0scjzKGiu4VAUc7H1o1nY= github.com/go-chi/chi/v5 v5.3.2/go.mod h1:R+tYY2hNuVUUjxoPtqUdgBqevM9s9njzkTLutVsOCto= github.com/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/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= +github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg= +github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo= +github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM= +github.com/jackc/pgx/v5 v5.11.0 h1:IzBBtyK9AHqf98cctWFifYSci2hgQR/cd56wB4p+ogg= +github.com/jackc/pgx/v5 v5.11.0/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4= +github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo= +github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0= github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4= +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/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/sync v0.17.0 h1:l60nONMj9l5drqw6jlhIELNv9I0A4OFgRsG9k2oT9Ug= +golang.org/x/sync v0.17.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI= +golang.org/x/text v0.29.0 h1:1neNs90w9YzJ9BocxfsQNHKuAT4pkghyXc4nhZ6sJvk= +golang.org/x/text v0.29.0/go.mod h1:7MhJOA9CD2qZyOKYazxdYMF85OwPdEr9jTtBpO7ydH4= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/internal/app/app.go b/internal/app/app.go index 0fdbc87a..cc86e32e 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -11,6 +11,7 @@ import ( "github.com/joho/godotenv" "mtusi2026-messenger/internal/config" + "mtusi2026-messenger/internal/db" "mtusi2026-messenger/internal/logger" "mtusi2026-messenger/internal/service" "mtusi2026-messenger/internal/store" @@ -25,13 +26,33 @@ func Run() error { log := logger.New(cfg.Logging.Level) + dbURL, err := cfg.Database.URL() + if err != nil { + log.Error("read database url", "error", err) + return err + } + + pool, err := db.New(context.Background(), dbURL) + if err != nil { + log.Error("connect to database", "error", err) + return err + } + defer pool.Close() + memory := store.New() userService := service.NewUserService(memory) chatService := service.NewChatService(memory) messageService := service.NewMessageService(memory) - router := NewRouter(log, cfg.Server.MaxInflightRequests, userService, chatService, messageService) + router := NewRouter( + log, + cfg.Server.MaxInflightRequests, + pool, + userService, + chatService, + messageService, + ) server := &http.Server{ Addr: cfg.Server.Host + ":" + cfg.Server.Port, diff --git a/internal/app/router.go b/internal/app/router.go index 0120396a..07c81925 100644 --- a/internal/app/router.go +++ b/internal/app/router.go @@ -14,12 +14,14 @@ import ( func NewRouter( log *slog.Logger, maxInflightRequests int, + db handler.Pinger, userService *service.UserService, chatService *service.ChatService, messageService *service.MessageService, ) http.Handler { router := chi.NewRouter() + healthHandler := handler.NewHealthHandler(log, db) userHandler := handler.NewUserHandler(userService) chatHandler := handler.NewChatHandler(chatService) messageHandler := handler.NewMessageHandler(messageService) @@ -28,8 +30,8 @@ func NewRouter( router.Use(middleware.Logging(log)) router.Use(middleware.ConcurrencyLimit(maxInflightRequests)) - router.Get("/health/live", handler.Health) - router.Get("/health/ready", handler.Health) + router.Get("/health/live", healthHandler.Live) + router.Get("/health/ready", healthHandler.Ready) router.Post("/api/v1/users", userHandler.Create) diff --git a/internal/db/db.go b/internal/db/db.go new file mode 100644 index 00000000..64aabc9d --- /dev/null +++ b/internal/db/db.go @@ -0,0 +1,34 @@ +package db + +import ( + "context" + "fmt" + "time" + + "github.com/jackc/pgx/v5/pgxpool" +) + +func New(ctx context.Context, url string) (*pgxpool.Pool, error) { + cfg, err := pgxpool.ParseConfig(url) + if err != nil { + return nil, fmt.Errorf("parse database url: %w", err) + } + + cfg.MaxConns = 10 + cfg.ConnConfig.ConnectTimeout = 5 * time.Second + cfg.ConnConfig.RuntimeParams["statement_timeout"] = "5000" + + pool, err := pgxpool.NewWithConfig(ctx, cfg) + if err != nil { + return nil, fmt.Errorf("create pool: %w", err) + } + + pingCtx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + if err := pool.Ping(pingCtx); err != nil { + pool.Close() + return nil, fmt.Errorf("ping database: %w", err) + } + + return pool, nil +} diff --git a/internal/handler/health.go b/internal/handler/health.go index b6e08120..00c6cc25 100644 --- a/internal/handler/health.go +++ b/internal/handler/health.go @@ -1,13 +1,55 @@ package handler import ( + "context" "encoding/json" + "log/slog" "net/http" + "time" "mtusi2026-messenger/internal/dto" ) -func Health(w http.ResponseWriter, r *http.Request) { +const readyPingTimeout = 2 * time.Second + +type Pinger interface { + Ping(ctx context.Context) error +} + +type HealthHandler struct { + log *slog.Logger + db Pinger +} + +func NewHealthHandler(log *slog.Logger, db Pinger) *HealthHandler { + return &HealthHandler{log: log, db: db} +} + +func (h *HealthHandler) Live(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + + _ = json.NewEncoder(w).Encode(dto.HealthResponse{ + Status: "ok", + }) +} + +func (h *HealthHandler) Ready(w http.ResponseWriter, r *http.Request) { + ctx, cancel := context.WithTimeout(r.Context(), readyPingTimeout) + defer cancel() + + if err := h.db.Ping(ctx); err != nil { + h.log.ErrorContext(r.Context(), "readiness check failed", "error", err) + WriteError( + w, + http.StatusServiceUnavailable, + dto.ErrorCodeUnavailable, + "service unavailable", + w.Header().Get("X-Request-Id"), + ) + return + } + w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) -- 2.54.0 From e1f2cb01e0093e68771acc6b28e88c50602ade84 Mon Sep 17 00:00:00 2001 From: kk10 Date: Sun, 4 Oct 2026 21:25:07 +0300 Subject: [PATCH 05/40] feat(db): add schema, sqlc queries and generated code --- Dockerfile.migrate | 2 +- {migrations => db/migrations}/00001_init.sql | 0 db/queries/chats.sql | 62 +++++++ db/queries/messages.sql | 31 ++++ db/queries/sessions.sql | 24 +++ db/queries/users.sql | 21 +++ internal/db/chats.sql.go | 183 +++++++++++++++++++ internal/db/db.go | 42 ++--- internal/db/messages.sql.go | 110 +++++++++++ internal/db/models.go | 45 +++++ internal/db/querier.go | 30 +++ internal/db/sessions.sql.go | 85 +++++++++ internal/db/users.sql.go | 101 ++++++++++ sqlc.yaml | 31 ++++ 14 files changed, 744 insertions(+), 23 deletions(-) rename {migrations => db/migrations}/00001_init.sql (100%) create mode 100644 db/queries/chats.sql create mode 100644 db/queries/messages.sql create mode 100644 db/queries/sessions.sql create mode 100644 db/queries/users.sql create mode 100644 internal/db/chats.sql.go create mode 100644 internal/db/messages.sql.go create mode 100644 internal/db/models.go create mode 100644 internal/db/querier.go create mode 100644 internal/db/sessions.sql.go create mode 100644 internal/db/users.sql.go create mode 100644 sqlc.yaml diff --git a/Dockerfile.migrate b/Dockerfile.migrate index 8bcb4171..48e8f7ae 100644 --- a/Dockerfile.migrate +++ b/Dockerfile.migrate @@ -4,5 +4,5 @@ RUN go install github.com/pressly/goose/v3/cmd/goose@v3.28.0 FROM alpine:3.24 COPY --from=build /go/bin/goose /usr/local/bin/goose -COPY migrations /migrations +COPY db/migrations /migrations ENTRYPOINT ["sh", "-c", "goose -dir /migrations postgres \"$(cat /run/secrets/database_url)\" up"] diff --git a/migrations/00001_init.sql b/db/migrations/00001_init.sql similarity index 100% rename from migrations/00001_init.sql rename to db/migrations/00001_init.sql diff --git a/db/queries/chats.sql b/db/queries/chats.sql new file mode 100644 index 00000000..5609c446 --- /dev/null +++ b/db/queries/chats.sql @@ -0,0 +1,62 @@ +-- name: CreateChat :one +INSERT INTO chats ( + id, + title +) VALUES ( + sqlc.arg(id), + sqlc.arg(title) +) +RETURNING *; + +-- name: AddChatMembers :exec +INSERT INTO chat_members ( + chat_id, + user_id +) +SELECT + sqlc.arg(chat_id)::uuid, + unnest(sqlc.arg(user_ids)::uuid[]); + +-- name: IsChatMember :one +SELECT EXISTS ( + SELECT 1 FROM chat_members + WHERE chat_id = sqlc.arg(chat_id) + AND user_id = sqlc.arg(user_id) +); + +-- name: GetChat :one +SELECT + c.*, + ARRAY( + SELECT cm.user_id FROM chat_members cm + WHERE cm.chat_id = c.id + ORDER BY cm.user_id + )::uuid[] AS member_ids +FROM chats c +WHERE c.id = sqlc.arg(id) + AND EXISTS ( + SELECT 1 FROM chat_members m + WHERE m.chat_id = c.id + AND m.user_id = sqlc.arg(user_id) + ); + +-- name: ListChats :many +SELECT + c.*, + ARRAY( + SELECT cm.user_id FROM chat_members cm + WHERE cm.chat_id = c.id + ORDER BY cm.user_id + )::uuid[] AS member_ids +FROM chats c +JOIN chat_members m ON m.chat_id = c.id +WHERE m.user_id = sqlc.arg(user_id) + AND ( + sqlc.narg(after_created_at)::timestamptz IS NULL + OR (c.created_at, c.id) > ( + sqlc.narg(after_created_at)::timestamptz, + sqlc.narg(after_id)::uuid + ) + ) +ORDER BY c.created_at, c.id +LIMIT sqlc.arg(lim); diff --git a/db/queries/messages.sql b/db/queries/messages.sql new file mode 100644 index 00000000..adb03546 --- /dev/null +++ b/db/queries/messages.sql @@ -0,0 +1,31 @@ +-- name: CreateMessage :one +INSERT INTO messages ( + id, + chat_id, + sender_id, + text +) +SELECT + sqlc.arg(id)::uuid, + sqlc.arg(chat_id)::uuid, + sqlc.arg(sender_id)::uuid, + sqlc.arg(text)::text +WHERE EXISTS ( + SELECT 1 FROM chat_members + WHERE chat_id = sqlc.arg(chat_id) + AND user_id = sqlc.arg(sender_id) +) +RETURNING *; + +-- name: ListMessages :many +SELECT * FROM messages +WHERE chat_id = sqlc.arg(chat_id) + AND ( + sqlc.narg(after_created_at)::timestamptz IS NULL + OR (created_at, id) > ( + sqlc.narg(after_created_at)::timestamptz, + sqlc.narg(after_id)::uuid + ) + ) +ORDER BY created_at, id +LIMIT sqlc.arg(lim); diff --git a/db/queries/sessions.sql b/db/queries/sessions.sql new file mode 100644 index 00000000..64a0bfa4 --- /dev/null +++ b/db/queries/sessions.sql @@ -0,0 +1,24 @@ +-- name: CreateSession :exec +INSERT INTO sessions ( + token_hash, + user_id, + expires_at +) VALUES ( + sqlc.arg(token_hash), + sqlc.arg(user_id), + sqlc.arg(expires_at) +); + +-- name: GetSessionUser :one +SELECT u.id, u.username, u.display_name, u.created_at FROM sessions s +JOIN users u ON u.id = s.user_id +WHERE s.token_hash = sqlc.arg(token_hash) + AND s.expires_at > now(); + +-- name: DeleteSession :exec +DELETE FROM sessions +WHERE token_hash = sqlc.arg(token_hash); + +-- name: DeleteExpiredSessions :execrows +DELETE FROM sessions +WHERE expires_at <= now(); diff --git a/db/queries/users.sql b/db/queries/users.sql new file mode 100644 index 00000000..d6e9c030 --- /dev/null +++ b/db/queries/users.sql @@ -0,0 +1,21 @@ +-- name: CreateUser :one +INSERT INTO users ( + id, + username, + display_name, + password_hash +) VALUES ( + sqlc.arg(id), + sqlc.arg(username), + sqlc.arg(display_name), + sqlc.arg(password_hash) +) +RETURNING id, username, display_name, created_at; + +-- name: GetUser :one +SELECT id, username, display_name, created_at FROM users +WHERE id = sqlc.arg(id); + +-- name: GetUserByUsername :one +SELECT * FROM users +WHERE username = sqlc.arg(username); diff --git a/internal/db/chats.sql.go b/internal/db/chats.sql.go new file mode 100644 index 00000000..cf3dc388 --- /dev/null +++ b/internal/db/chats.sql.go @@ -0,0 +1,183 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 +// source: chats.sql + +package db + +import ( + "context" + "time" + + "github.com/google/uuid" +) + +const addChatMembers = `-- name: AddChatMembers :exec +INSERT INTO chat_members ( + chat_id, + user_id +) +SELECT + $1::uuid, + unnest($2::uuid[]) +` + +type AddChatMembersParams struct { + ChatID uuid.UUID + UserIds []uuid.UUID +} + +func (q *Queries) AddChatMembers(ctx context.Context, arg AddChatMembersParams) error { + _, err := q.db.Exec(ctx, addChatMembers, arg.ChatID, arg.UserIds) + return err +} + +const createChat = `-- name: CreateChat :one +INSERT INTO chats ( + id, + title +) VALUES ( + $1, + $2 +) +RETURNING id, title, created_at +` + +type CreateChatParams struct { + ID uuid.UUID + Title string +} + +func (q *Queries) CreateChat(ctx context.Context, arg CreateChatParams) (Chat, error) { + row := q.db.QueryRow(ctx, createChat, arg.ID, arg.Title) + var i Chat + err := row.Scan(&i.ID, &i.Title, &i.CreatedAt) + return i, err +} + +const getChat = `-- name: GetChat :one +SELECT + c.id, c.title, c.created_at, + ARRAY( + SELECT cm.user_id FROM chat_members cm + WHERE cm.chat_id = c.id + ORDER BY cm.user_id + )::uuid[] AS member_ids +FROM chats c +WHERE c.id = $1 + AND EXISTS ( + SELECT 1 FROM chat_members m + WHERE m.chat_id = c.id + AND m.user_id = $2 + ) +` + +type GetChatParams struct { + ID uuid.UUID + UserID uuid.UUID +} + +type GetChatRow struct { + ID uuid.UUID + Title string + CreatedAt time.Time + MemberIds []uuid.UUID +} + +func (q *Queries) GetChat(ctx context.Context, arg GetChatParams) (GetChatRow, error) { + row := q.db.QueryRow(ctx, getChat, arg.ID, arg.UserID) + var i GetChatRow + err := row.Scan( + &i.ID, + &i.Title, + &i.CreatedAt, + &i.MemberIds, + ) + return i, err +} + +const isChatMember = `-- name: IsChatMember :one +SELECT EXISTS ( + SELECT 1 FROM chat_members + WHERE chat_id = $1 + AND user_id = $2 +) +` + +type IsChatMemberParams struct { + ChatID uuid.UUID + UserID uuid.UUID +} + +func (q *Queries) IsChatMember(ctx context.Context, arg IsChatMemberParams) (bool, error) { + row := q.db.QueryRow(ctx, isChatMember, arg.ChatID, arg.UserID) + var exists bool + err := row.Scan(&exists) + return exists, err +} + +const listChats = `-- name: ListChats :many +SELECT + c.id, c.title, c.created_at, + ARRAY( + SELECT cm.user_id FROM chat_members cm + WHERE cm.chat_id = c.id + ORDER BY cm.user_id + )::uuid[] AS member_ids +FROM chats c +JOIN chat_members m ON m.chat_id = c.id +WHERE m.user_id = $1 + AND ( + $2::timestamptz IS NULL + OR (c.created_at, c.id) > ( + $2::timestamptz, + $3::uuid + ) + ) +ORDER BY c.created_at, c.id +LIMIT $4 +` + +type ListChatsParams struct { + UserID uuid.UUID + AfterCreatedAt *time.Time + AfterID *uuid.UUID + Lim int32 +} + +type ListChatsRow struct { + ID uuid.UUID + Title string + CreatedAt time.Time + MemberIds []uuid.UUID +} + +func (q *Queries) ListChats(ctx context.Context, arg ListChatsParams) ([]ListChatsRow, error) { + rows, err := q.db.Query(ctx, listChats, + arg.UserID, + arg.AfterCreatedAt, + arg.AfterID, + arg.Lim, + ) + if err != nil { + return nil, err + } + defer rows.Close() + items := []ListChatsRow{} + for rows.Next() { + var i ListChatsRow + if err := rows.Scan( + &i.ID, + &i.Title, + &i.CreatedAt, + &i.MemberIds, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} diff --git a/internal/db/db.go b/internal/db/db.go index 64aabc9d..468d1fa3 100644 --- a/internal/db/db.go +++ b/internal/db/db.go @@ -1,34 +1,32 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 + package db import ( "context" - "fmt" - "time" - "github.com/jackc/pgx/v5/pgxpool" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgconn" ) -func New(ctx context.Context, url string) (*pgxpool.Pool, error) { - cfg, err := pgxpool.ParseConfig(url) - if err != nil { - return nil, fmt.Errorf("parse database url: %w", err) - } +type DBTX interface { + Exec(context.Context, string, ...interface{}) (pgconn.CommandTag, error) + Query(context.Context, string, ...interface{}) (pgx.Rows, error) + QueryRow(context.Context, string, ...interface{}) pgx.Row +} - cfg.MaxConns = 10 - cfg.ConnConfig.ConnectTimeout = 5 * time.Second - cfg.ConnConfig.RuntimeParams["statement_timeout"] = "5000" +func New(db DBTX) *Queries { + return &Queries{db: db} +} - pool, err := pgxpool.NewWithConfig(ctx, cfg) - if err != nil { - return nil, fmt.Errorf("create pool: %w", err) - } +type Queries struct { + db DBTX +} - pingCtx, cancel := context.WithTimeout(ctx, 5*time.Second) - defer cancel() - if err := pool.Ping(pingCtx); err != nil { - pool.Close() - return nil, fmt.Errorf("ping database: %w", err) +func (q *Queries) WithTx(tx pgx.Tx) *Queries { + return &Queries{ + db: tx, } - - return pool, nil } diff --git a/internal/db/messages.sql.go b/internal/db/messages.sql.go new file mode 100644 index 00000000..babd80ad --- /dev/null +++ b/internal/db/messages.sql.go @@ -0,0 +1,110 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 +// source: messages.sql + +package db + +import ( + "context" + "time" + + "github.com/google/uuid" +) + +const createMessage = `-- name: CreateMessage :one +INSERT INTO messages ( + id, + chat_id, + sender_id, + text +) +SELECT + $1::uuid, + $2::uuid, + $3::uuid, + $4::text +WHERE EXISTS ( + SELECT 1 FROM chat_members + WHERE chat_id = $2 + AND user_id = $3 +) +RETURNING id, chat_id, sender_id, text, created_at +` + +type CreateMessageParams struct { + ID uuid.UUID + ChatID uuid.UUID + SenderID uuid.UUID + Text string +} + +func (q *Queries) CreateMessage(ctx context.Context, arg CreateMessageParams) (Message, error) { + row := q.db.QueryRow(ctx, createMessage, + arg.ID, + arg.ChatID, + arg.SenderID, + arg.Text, + ) + var i Message + err := row.Scan( + &i.ID, + &i.ChatID, + &i.SenderID, + &i.Text, + &i.CreatedAt, + ) + return i, err +} + +const listMessages = `-- name: ListMessages :many +SELECT id, chat_id, sender_id, text, created_at FROM messages +WHERE chat_id = $1 + AND ( + $2::timestamptz IS NULL + OR (created_at, id) > ( + $2::timestamptz, + $3::uuid + ) + ) +ORDER BY created_at, id +LIMIT $4 +` + +type ListMessagesParams struct { + ChatID uuid.UUID + AfterCreatedAt *time.Time + AfterID *uuid.UUID + Lim int32 +} + +func (q *Queries) ListMessages(ctx context.Context, arg ListMessagesParams) ([]Message, error) { + rows, err := q.db.Query(ctx, listMessages, + arg.ChatID, + arg.AfterCreatedAt, + arg.AfterID, + arg.Lim, + ) + if err != nil { + return nil, err + } + defer rows.Close() + items := []Message{} + for rows.Next() { + var i Message + if err := rows.Scan( + &i.ID, + &i.ChatID, + &i.SenderID, + &i.Text, + &i.CreatedAt, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} diff --git a/internal/db/models.go b/internal/db/models.go new file mode 100644 index 00000000..c9a085e4 --- /dev/null +++ b/internal/db/models.go @@ -0,0 +1,45 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 + +package db + +import ( + "time" + + "github.com/google/uuid" +) + +type Chat struct { + ID uuid.UUID + Title string + CreatedAt time.Time +} + +type ChatMember struct { + ChatID uuid.UUID + UserID uuid.UUID +} + +type Message struct { + ID uuid.UUID + ChatID uuid.UUID + SenderID uuid.UUID + Text string + CreatedAt time.Time +} + +type Session struct { + TokenHash string + UserID uuid.UUID + CreatedAt time.Time + ExpiresAt time.Time +} + +type User struct { + ID uuid.UUID + Username string + DisplayName string + PasswordHash string + CreatedAt time.Time +} diff --git a/internal/db/querier.go b/internal/db/querier.go new file mode 100644 index 00000000..0d5993a2 --- /dev/null +++ b/internal/db/querier.go @@ -0,0 +1,30 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 + +package db + +import ( + "context" + + "github.com/google/uuid" +) + +type Querier interface { + AddChatMembers(ctx context.Context, arg AddChatMembersParams) error + CreateChat(ctx context.Context, arg CreateChatParams) (Chat, error) + CreateMessage(ctx context.Context, arg CreateMessageParams) (Message, error) + CreateSession(ctx context.Context, arg CreateSessionParams) error + CreateUser(ctx context.Context, arg CreateUserParams) (CreateUserRow, error) + DeleteExpiredSessions(ctx context.Context) (int64, error) + DeleteSession(ctx context.Context, tokenHash string) error + GetChat(ctx context.Context, arg GetChatParams) (GetChatRow, error) + GetSessionUser(ctx context.Context, tokenHash string) (GetSessionUserRow, error) + GetUser(ctx context.Context, id uuid.UUID) (GetUserRow, error) + GetUserByUsername(ctx context.Context, username string) (User, error) + IsChatMember(ctx context.Context, arg IsChatMemberParams) (bool, error) + ListChats(ctx context.Context, arg ListChatsParams) ([]ListChatsRow, error) + ListMessages(ctx context.Context, arg ListMessagesParams) ([]Message, error) +} + +var _ Querier = (*Queries)(nil) diff --git a/internal/db/sessions.sql.go b/internal/db/sessions.sql.go new file mode 100644 index 00000000..5567e1be --- /dev/null +++ b/internal/db/sessions.sql.go @@ -0,0 +1,85 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 +// source: sessions.sql + +package db + +import ( + "context" + "time" + + "github.com/google/uuid" +) + +const createSession = `-- name: CreateSession :exec +INSERT INTO sessions ( + token_hash, + user_id, + expires_at +) VALUES ( + $1, + $2, + $3 +) +` + +type CreateSessionParams struct { + TokenHash string + UserID uuid.UUID + ExpiresAt time.Time +} + +func (q *Queries) CreateSession(ctx context.Context, arg CreateSessionParams) error { + _, err := q.db.Exec(ctx, createSession, arg.TokenHash, arg.UserID, arg.ExpiresAt) + return err +} + +const deleteExpiredSessions = `-- name: DeleteExpiredSessions :execrows +DELETE FROM sessions +WHERE expires_at <= now() +` + +func (q *Queries) DeleteExpiredSessions(ctx context.Context) (int64, error) { + result, err := q.db.Exec(ctx, deleteExpiredSessions) + if err != nil { + return 0, err + } + return result.RowsAffected(), nil +} + +const deleteSession = `-- name: DeleteSession :exec +DELETE FROM sessions +WHERE token_hash = $1 +` + +func (q *Queries) DeleteSession(ctx context.Context, tokenHash string) error { + _, err := q.db.Exec(ctx, deleteSession, tokenHash) + return err +} + +const getSessionUser = `-- name: GetSessionUser :one +SELECT u.id, u.username, u.display_name, u.created_at FROM sessions s +JOIN users u ON u.id = s.user_id +WHERE s.token_hash = $1 + AND s.expires_at > now() +` + +type GetSessionUserRow struct { + ID uuid.UUID + Username string + DisplayName string + CreatedAt time.Time +} + +func (q *Queries) GetSessionUser(ctx context.Context, tokenHash string) (GetSessionUserRow, error) { + row := q.db.QueryRow(ctx, getSessionUser, tokenHash) + var i GetSessionUserRow + err := row.Scan( + &i.ID, + &i.Username, + &i.DisplayName, + &i.CreatedAt, + ) + return i, err +} diff --git a/internal/db/users.sql.go b/internal/db/users.sql.go new file mode 100644 index 00000000..ec8a97f9 --- /dev/null +++ b/internal/db/users.sql.go @@ -0,0 +1,101 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 +// source: users.sql + +package db + +import ( + "context" + "time" + + "github.com/google/uuid" +) + +const createUser = `-- name: CreateUser :one +INSERT INTO users ( + id, + username, + display_name, + password_hash +) VALUES ( + $1, + $2, + $3, + $4 +) +RETURNING id, username, display_name, created_at +` + +type CreateUserParams struct { + ID uuid.UUID + Username string + DisplayName string + PasswordHash string +} + +type CreateUserRow struct { + ID uuid.UUID + Username string + DisplayName string + CreatedAt time.Time +} + +func (q *Queries) CreateUser(ctx context.Context, arg CreateUserParams) (CreateUserRow, error) { + row := q.db.QueryRow(ctx, createUser, + arg.ID, + arg.Username, + arg.DisplayName, + arg.PasswordHash, + ) + var i CreateUserRow + err := row.Scan( + &i.ID, + &i.Username, + &i.DisplayName, + &i.CreatedAt, + ) + return i, err +} + +const getUser = `-- name: GetUser :one +SELECT id, username, display_name, created_at FROM users +WHERE id = $1 +` + +type GetUserRow struct { + ID uuid.UUID + Username string + DisplayName string + CreatedAt time.Time +} + +func (q *Queries) GetUser(ctx context.Context, id uuid.UUID) (GetUserRow, error) { + row := q.db.QueryRow(ctx, getUser, id) + var i GetUserRow + err := row.Scan( + &i.ID, + &i.Username, + &i.DisplayName, + &i.CreatedAt, + ) + return i, err +} + +const getUserByUsername = `-- name: GetUserByUsername :one +SELECT id, username, display_name, password_hash, created_at FROM users +WHERE username = $1 +` + +func (q *Queries) GetUserByUsername(ctx context.Context, username string) (User, error) { + row := q.db.QueryRow(ctx, getUserByUsername, username) + var i User + err := row.Scan( + &i.ID, + &i.Username, + &i.DisplayName, + &i.PasswordHash, + &i.CreatedAt, + ) + return i, err +} diff --git a/sqlc.yaml b/sqlc.yaml new file mode 100644 index 00000000..85494b59 --- /dev/null +++ b/sqlc.yaml @@ -0,0 +1,31 @@ +version: "2" +sql: + - engine: "postgresql" + queries: "db/queries" + schema: "db/migrations" + gen: + go: + package: "db" + out: "internal/db" + sql_package: "pgx/v5" + emit_interface: true + emit_empty_slices: true + emit_pointers_for_null_types: true + overrides: + - db_type: "uuid" + go_type: "github.com/google/uuid.UUID" + - db_type: "uuid" + nullable: true + go_type: + import: "github.com/google/uuid" + type: "UUID" + pointer: true + + - db_type: "timestamptz" + go_type: "time.Time" + - db_type: "timestamptz" + nullable: true + go_type: + import: "time" + type: "Time" + pointer: true -- 2.54.0 From 862d22c2283126ce8a196987650cc2080f47b23d Mon Sep 17 00:00:00 2001 From: kk10 Date: Sun, 4 Oct 2026 21:41:39 +0300 Subject: [PATCH 06/40] feat(postgres): add pool and error code helpers --- internal/postgres/errors.go | 25 +++++++++++++++++++++++++ internal/postgres/pool.go | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 59 insertions(+) create mode 100644 internal/postgres/errors.go create mode 100644 internal/postgres/pool.go diff --git a/internal/postgres/errors.go b/internal/postgres/errors.go new file mode 100644 index 00000000..961f069e --- /dev/null +++ b/internal/postgres/errors.go @@ -0,0 +1,25 @@ +package postgres + +import ( + "errors" + + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgconn" +) + +const ( + CodeUniqueViolation = "23505" + CodeForeignKeyViolation = "23503" + CodeCheckViolation = "23514" +) + +func ErrCode(err error) string { + if pgErr, ok := errors.AsType[*pgconn.PgError](err); ok { + return pgErr.Code + } + return "" +} + +func IsNotFound(err error) bool { + return errors.Is(err, pgx.ErrNoRows) +} diff --git a/internal/postgres/pool.go b/internal/postgres/pool.go new file mode 100644 index 00000000..4a1361aa --- /dev/null +++ b/internal/postgres/pool.go @@ -0,0 +1,34 @@ +package postgres + +import ( + "context" + "fmt" + "time" + + "github.com/jackc/pgx/v5/pgxpool" +) + +func New(ctx context.Context, url string) (*pgxpool.Pool, error) { + cfg, err := pgxpool.ParseConfig(url) + if err != nil { + return nil, fmt.Errorf("parse database url: %w", err) + } + + cfg.MaxConns = 10 + cfg.ConnConfig.ConnectTimeout = 5 * time.Second + cfg.ConnConfig.RuntimeParams["statement_timeout"] = "5000" + + pool, err := pgxpool.NewWithConfig(ctx, cfg) + if err != nil { + return nil, fmt.Errorf("create pool: %w", err) + } + + pingCtx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + if err := pool.Ping(pingCtx); err != nil { + pool.Close() + return nil, fmt.Errorf("ping database: %w", err) + } + + return pool, nil +} -- 2.54.0 From 01a9cc3398ab80709eb26a12a53d9c2fec4726f3 Mon Sep 17 00:00:00 2001 From: kk10 Date: Sun, 4 Oct 2026 22:04:47 +0300 Subject: [PATCH 07/40] feat(credentials): add password hashing and token helpers --- go.mod | 7 ++-- go.sum | 10 +++--- internal/credentials/credentials.go | 51 +++++++++++++++++++++++++++++ 3 files changed, 61 insertions(+), 7 deletions(-) create mode 100644 internal/credentials/credentials.go diff --git a/go.mod b/go.mod index 0273f917..658d8f9d 100644 --- a/go.mod +++ b/go.mod @@ -1,18 +1,19 @@ module mtusi2026-messenger -go 1.25.0 +go 1.26.0 require ( github.com/go-chi/chi/v5 v5.3.2 github.com/google/uuid v1.6.0 github.com/jackc/pgx/v5 v5.11.0 github.com/joho/godotenv v1.5.1 + golang.org/x/crypto v0.57.0 ) require ( github.com/jackc/pgpassfile v1.0.0 // indirect github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect github.com/jackc/puddle/v2 v2.2.2 // indirect - golang.org/x/sync v0.17.0 // indirect - golang.org/x/text v0.29.0 // indirect + golang.org/x/sync v0.23.0 // indirect + golang.org/x/text v0.42.0 // indirect ) diff --git a/go.sum b/go.sum index a9f25227..1c8ee76a 100644 --- a/go.sum +++ b/go.sum @@ -22,10 +22,12 @@ github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UV github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= -golang.org/x/sync v0.17.0 h1:l60nONMj9l5drqw6jlhIELNv9I0A4OFgRsG9k2oT9Ug= -golang.org/x/sync v0.17.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI= -golang.org/x/text v0.29.0 h1:1neNs90w9YzJ9BocxfsQNHKuAT4pkghyXc4nhZ6sJvk= -golang.org/x/text v0.29.0/go.mod h1:7MhJOA9CD2qZyOKYazxdYMF85OwPdEr9jTtBpO7ydH4= +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/sync v0.23.0 h1:KameEIfc1IkluZyXWLn39Wd4tURc6GbCiISGiZm2bQk= +golang.org/x/sync v0.23.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= +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/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= diff --git a/internal/credentials/credentials.go b/internal/credentials/credentials.go new file mode 100644 index 00000000..7120a961 --- /dev/null +++ b/internal/credentials/credentials.go @@ -0,0 +1,51 @@ +package credentials + +import ( + "crypto/rand" + "crypto/sha256" + "encoding/base64" + "encoding/hex" + "errors" + + "golang.org/x/crypto/bcrypt" +) + +const tokenSize = 32 + +var ErrPasswordMismatch = errors.New("password mismatch") + +func prehash(plain string) []byte { + sum := sha256.Sum256([]byte(plain)) + return []byte(base64.StdEncoding.EncodeToString(sum[:])) +} + +func HashPassword(plain string) (string, error) { + hash, err := bcrypt.GenerateFromPassword(prehash(plain), bcrypt.DefaultCost) + if err != nil { + return "", err + } + + return string(hash), nil +} + +func VerifyPassword(hash, plain string) error { + err := bcrypt.CompareHashAndPassword([]byte(hash), prehash(plain)) + if errors.Is(err, bcrypt.ErrMismatchedHashAndPassword) { + return ErrPasswordMismatch + } + + return err +} + +func NewToken() string { + raw := make([]byte, tokenSize) + _, _ = rand.Read(raw) // never returns an error since Go 1.24 + + return base64.RawURLEncoding.EncodeToString(raw) +} + +func HashToken(token string) string { + sum := sha256.Sum256([]byte(token)) + + return hex.EncodeToString(sum[:]) +} -- 2.54.0 From bbcde1e95e207e5110181ff54e135ead32d6f35e Mon Sep 17 00:00:00 2001 From: kk10 Date: Sun, 4 Oct 2026 22:07:21 +0300 Subject: [PATCH 08/40] build(docker): bump Go image to 1.27.1 --- Dockerfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dockerfile b/Dockerfile index d44495b6..ed559f5f 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,4 +1,4 @@ -FROM golang:1.25.0 AS build +FROM golang:1.27.1 AS build WORKDIR /src COPY go.mod go.sum ./ -- 2.54.0 From 527c1748f8b9416bfe22d9311834d4a929b246cf Mon Sep 17 00:00:00 2001 From: kk10 Date: Sun, 4 Oct 2026 22:49:42 +0300 Subject: [PATCH 09/40] feat(user): store users in Postgres with password hashes --- internal/app/app.go | 6 ++-- internal/dto/user.go | 9 +++++- internal/handler/user.go | 9 ++++-- internal/service/user.go | 66 +++++++++++++++++++++++++++++++--------- 4 files changed, 70 insertions(+), 20 deletions(-) diff --git a/internal/app/app.go b/internal/app/app.go index cc86e32e..dcf6fbc1 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -13,6 +13,7 @@ import ( "mtusi2026-messenger/internal/config" "mtusi2026-messenger/internal/db" "mtusi2026-messenger/internal/logger" + "mtusi2026-messenger/internal/postgres" "mtusi2026-messenger/internal/service" "mtusi2026-messenger/internal/store" ) @@ -32,16 +33,17 @@ func Run() error { return err } - pool, err := db.New(context.Background(), dbURL) + pool, err := postgres.New(context.Background(), dbURL) if err != nil { log.Error("connect to database", "error", err) return err } defer pool.Close() + queries := db.New(pool) memory := store.New() - userService := service.NewUserService(memory) + userService := service.NewUserService(queries) chatService := service.NewChatService(memory) messageService := service.NewMessageService(memory) diff --git a/internal/dto/user.go b/internal/dto/user.go index dfe826b5..27973e1d 100644 --- a/internal/dto/user.go +++ b/internal/dto/user.go @@ -14,6 +14,7 @@ var usernamePattern = regexp.MustCompile(`^[a-z0-9_]{3,32}$`) type CreateUserRequest struct { Username string `json:"username"` DisplayName string `json:"display_name"` + Password string `json:"password"` } type UserResponse struct { @@ -29,7 +30,13 @@ func (r CreateUserRequest) Validate() bool { } displayNameLength := utf8.RuneCountInString(r.DisplayName) - if strings.TrimSpace(r.DisplayName) == "" || displayNameLength > 100 { + if strings.TrimSpace(r.DisplayName) == "" || + displayNameLength > 100 || + strings.ContainsRune(r.DisplayName, 0) { + return false + } + + if n := utf8.RuneCountInString(r.Password); n < 12 || n > 128 { return false } diff --git a/internal/handler/user.go b/internal/handler/user.go index 0a163090..5356546d 100644 --- a/internal/handler/user.go +++ b/internal/handler/user.go @@ -37,7 +37,12 @@ func (h *UserHandler) Create(w http.ResponseWriter, r *http.Request) { return } - user, err := h.service.Create(req.Username, req.DisplayName) + user, err := h.service.Create( + r.Context(), + req.Username, + req.DisplayName, + req.Password, + ) if errors.Is(err, service.ErrUsernameTaken) { httpx.WriteError( w, @@ -71,7 +76,7 @@ func (h *UserHandler) Me(w http.ResponseWriter, r *http.Request) { requestID := middleware.GetRequestID(r.Context()) userID := middleware.GetUserID(r.Context()) - user, err := h.service.GetByID(userID) + user, err := h.service.GetByID(r.Context(), userID) if errors.Is(err, service.ErrUserNotFound) { httpx.WriteError( w, diff --git a/internal/service/user.go b/internal/service/user.go index 140d4cc9..555b8b09 100644 --- a/internal/service/user.go +++ b/internal/service/user.go @@ -1,47 +1,83 @@ package service import ( + "context" "errors" "github.com/google/uuid" + "mtusi2026-messenger/internal/credentials" + "mtusi2026-messenger/internal/db" "mtusi2026-messenger/internal/model" - "mtusi2026-messenger/internal/store" + "mtusi2026-messenger/internal/postgres" ) var ( - ErrUserNotFound = errors.New("user not found") ErrUsernameTaken = errors.New("username already taken") + ErrUserNotFound = errors.New("user not found") ) +type userQueries interface { + CreateUser(ctx context.Context, arg db.CreateUserParams) (db.CreateUserRow, error) + GetUser(ctx context.Context, id uuid.UUID) (db.GetUserRow, error) +} + type UserService struct { - store *store.Memory + q userQueries } -func NewUserService(store *store.Memory) *UserService { - return &UserService{store: store} +func NewUserService(q userQueries) *UserService { + return &UserService{q: q} } -func (s *UserService) Create(username, displayName string) (model.User, error) { - user, err := s.store.CreateUser(username, displayName) - if errors.Is(err, store.ErrConflict) { - return model.User{}, ErrUsernameTaken - } +func (s *UserService) Create( + ctx context.Context, + username, displayName, plain string, +) (model.User, error) { + hash, err := credentials.HashPassword(plain) if err != nil { return model.User{}, err } - return user, nil + id, err := uuid.NewV7() + if err != nil { + return model.User{}, err + } + + row, err := s.q.CreateUser(ctx, db.CreateUserParams{ + ID: id, + Username: username, + DisplayName: displayName, + PasswordHash: hash, + }) + if err != nil { + if postgres.ErrCode(err) == postgres.CodeUniqueViolation { + return model.User{}, ErrUsernameTaken + } + return model.User{}, err + } + + return model.User{ + ID: row.ID, + Username: row.Username, + DisplayName: row.DisplayName, + CreatedAt: row.CreatedAt.UTC(), + }, nil } -func (s *UserService) GetByID(id uuid.UUID) (model.User, error) { - user, err := s.store.GetUser(id) - if errors.Is(err, store.ErrNotFound) { +func (s *UserService) GetByID(ctx context.Context, id uuid.UUID) (model.User, error) { + row, err := s.q.GetUser(ctx, id) + if postgres.IsNotFound(err) { return model.User{}, ErrUserNotFound } if err != nil { return model.User{}, err } - return user, nil + return model.User{ + ID: row.ID, + Username: row.Username, + DisplayName: row.DisplayName, + CreatedAt: row.CreatedAt.UTC(), + }, nil } -- 2.54.0 From 5d6f5a397f9134437f7f932e4759e2515b0a7a72 Mon Sep 17 00:00:00 2001 From: kk10 Date: Sun, 4 Oct 2026 23:08:11 +0300 Subject: [PATCH 10/40] refactor(db): drop Querier and select only user id for session lookup --- db/queries/sessions.sql | 9 ++++----- internal/db/querier.go | 30 ------------------------------ internal/db/sessions.sql.go | 31 +++++++++---------------------- sqlc.yaml | 1 - 4 files changed, 13 insertions(+), 58 deletions(-) delete mode 100644 internal/db/querier.go diff --git a/db/queries/sessions.sql b/db/queries/sessions.sql index 64a0bfa4..65970af5 100644 --- a/db/queries/sessions.sql +++ b/db/queries/sessions.sql @@ -9,11 +9,10 @@ INSERT INTO sessions ( sqlc.arg(expires_at) ); --- name: GetSessionUser :one -SELECT u.id, u.username, u.display_name, u.created_at FROM sessions s -JOIN users u ON u.id = s.user_id -WHERE s.token_hash = sqlc.arg(token_hash) - AND s.expires_at > now(); +-- name: GetSessionUserID :one +SELECT user_id FROM sessions +WHERE token_hash = sqlc.arg(token_hash) + AND expires_at > now(); -- name: DeleteSession :exec DELETE FROM sessions diff --git a/internal/db/querier.go b/internal/db/querier.go deleted file mode 100644 index 0d5993a2..00000000 --- a/internal/db/querier.go +++ /dev/null @@ -1,30 +0,0 @@ -// Code generated by sqlc. DO NOT EDIT. -// versions: -// sqlc v1.31.1 - -package db - -import ( - "context" - - "github.com/google/uuid" -) - -type Querier interface { - AddChatMembers(ctx context.Context, arg AddChatMembersParams) error - CreateChat(ctx context.Context, arg CreateChatParams) (Chat, error) - CreateMessage(ctx context.Context, arg CreateMessageParams) (Message, error) - CreateSession(ctx context.Context, arg CreateSessionParams) error - CreateUser(ctx context.Context, arg CreateUserParams) (CreateUserRow, error) - DeleteExpiredSessions(ctx context.Context) (int64, error) - DeleteSession(ctx context.Context, tokenHash string) error - GetChat(ctx context.Context, arg GetChatParams) (GetChatRow, error) - GetSessionUser(ctx context.Context, tokenHash string) (GetSessionUserRow, error) - GetUser(ctx context.Context, id uuid.UUID) (GetUserRow, error) - GetUserByUsername(ctx context.Context, username string) (User, error) - IsChatMember(ctx context.Context, arg IsChatMemberParams) (bool, error) - ListChats(ctx context.Context, arg ListChatsParams) ([]ListChatsRow, error) - ListMessages(ctx context.Context, arg ListMessagesParams) ([]Message, error) -} - -var _ Querier = (*Queries)(nil) diff --git a/internal/db/sessions.sql.go b/internal/db/sessions.sql.go index 5567e1be..3438166b 100644 --- a/internal/db/sessions.sql.go +++ b/internal/db/sessions.sql.go @@ -58,28 +58,15 @@ func (q *Queries) DeleteSession(ctx context.Context, tokenHash string) error { return err } -const getSessionUser = `-- name: GetSessionUser :one -SELECT u.id, u.username, u.display_name, u.created_at FROM sessions s -JOIN users u ON u.id = s.user_id -WHERE s.token_hash = $1 - AND s.expires_at > now() +const getSessionUserID = `-- name: GetSessionUserID :one +SELECT user_id FROM sessions +WHERE token_hash = $1 + AND expires_at > now() ` -type GetSessionUserRow struct { - ID uuid.UUID - Username string - DisplayName string - CreatedAt time.Time -} - -func (q *Queries) GetSessionUser(ctx context.Context, tokenHash string) (GetSessionUserRow, error) { - row := q.db.QueryRow(ctx, getSessionUser, tokenHash) - var i GetSessionUserRow - err := row.Scan( - &i.ID, - &i.Username, - &i.DisplayName, - &i.CreatedAt, - ) - return i, err +func (q *Queries) GetSessionUserID(ctx context.Context, tokenHash string) (uuid.UUID, error) { + row := q.db.QueryRow(ctx, getSessionUserID, tokenHash) + var user_id uuid.UUID + err := row.Scan(&user_id) + return user_id, err } diff --git a/sqlc.yaml b/sqlc.yaml index 85494b59..0e834114 100644 --- a/sqlc.yaml +++ b/sqlc.yaml @@ -8,7 +8,6 @@ sql: package: "db" out: "internal/db" sql_package: "pgx/v5" - emit_interface: true emit_empty_slices: true emit_pointers_for_null_types: true overrides: -- 2.54.0 From b94e7813ee70445977a9f383aa30e20592a3d649 Mon Sep 17 00:00:00 2001 From: kk10 Date: Mon, 5 Oct 2026 11:41:34 +0300 Subject: [PATCH 11/40] refactor(httpx): drop duplicate WriteError, add WriteInternal --- internal/handler/chat.go | 24 +++--------------------- internal/handler/error.go | 27 --------------------------- internal/handler/health.go | 3 ++- internal/handler/message.go | 16 ++-------------- internal/handler/user.go | 16 ++-------------- internal/httpx/response.go | 10 ++++++++++ 6 files changed, 19 insertions(+), 77 deletions(-) delete mode 100644 internal/handler/error.go diff --git a/internal/handler/chat.go b/internal/handler/chat.go index 24a91788..8b6b23d5 100644 --- a/internal/handler/chat.go +++ b/internal/handler/chat.go @@ -71,13 +71,7 @@ func (h *ChatHandler) Create(w http.ResponseWriter, r *http.Request) { ) return case err != nil: - httpx.WriteError( - w, - http.StatusInternalServerError, - dto.ErrorCodeInternalError, - "internal server error", - requestID, - ) + httpx.WriteInternal(w, requestID) return } @@ -112,13 +106,7 @@ func (h *ChatHandler) Get(w http.ResponseWriter, r *http.Request) { ) return case err != nil: - httpx.WriteError( - w, - http.StatusInternalServerError, - dto.ErrorCodeInternalError, - "internal server error", - requestID, - ) + httpx.WriteInternal(w, requestID) return } @@ -146,13 +134,7 @@ func (h *ChatHandler) List(w http.ResponseWriter, r *http.Request) { ) return case err != nil: - httpx.WriteError( - w, - http.StatusInternalServerError, - dto.ErrorCodeInternalError, - "internal server error", - requestID, - ) + httpx.WriteInternal(w, requestID) return } diff --git a/internal/handler/error.go b/internal/handler/error.go deleted file mode 100644 index 34bb0bb0..00000000 --- a/internal/handler/error.go +++ /dev/null @@ -1,27 +0,0 @@ -package handler - -import ( - "encoding/json" - "net/http" - - "mtusi2026-messenger/internal/dto" -) - -func WriteError( - w http.ResponseWriter, - status int, - code dto.ErrorCode, - message string, - requestID string, -) { - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(status) - - _ = json.NewEncoder(w).Encode(dto.ErrorResponse{ - Error: dto.Error{ - Code: code, - Message: message, - RequestID: requestID, - }, - }) -} diff --git a/internal/handler/health.go b/internal/handler/health.go index 00c6cc25..ee8a2b30 100644 --- a/internal/handler/health.go +++ b/internal/handler/health.go @@ -8,6 +8,7 @@ import ( "time" "mtusi2026-messenger/internal/dto" + "mtusi2026-messenger/internal/httpx" ) const readyPingTimeout = 2 * time.Second @@ -40,7 +41,7 @@ func (h *HealthHandler) Ready(w http.ResponseWriter, r *http.Request) { if err := h.db.Ping(ctx); err != nil { h.log.ErrorContext(r.Context(), "readiness check failed", "error", err) - WriteError( + httpx.WriteError( w, http.StatusServiceUnavailable, dto.ErrorCodeUnavailable, diff --git a/internal/handler/message.go b/internal/handler/message.go index 191590e1..85814865 100644 --- a/internal/handler/message.go +++ b/internal/handler/message.go @@ -65,13 +65,7 @@ func (h *MessageHandler) Create(w http.ResponseWriter, r *http.Request) { ) return case err != nil: - httpx.WriteError( - w, - http.StatusInternalServerError, - dto.ErrorCodeInternalError, - "internal server error", - requestID, - ) + httpx.WriteInternal(w, requestID) return } @@ -120,13 +114,7 @@ func (h *MessageHandler) List(w http.ResponseWriter, r *http.Request) { ) return case err != nil: - httpx.WriteError( - w, - http.StatusInternalServerError, - dto.ErrorCodeInternalError, - "internal server error", - requestID, - ) + httpx.WriteInternal(w, requestID) return } diff --git a/internal/handler/user.go b/internal/handler/user.go index 5356546d..40d6086b 100644 --- a/internal/handler/user.go +++ b/internal/handler/user.go @@ -54,13 +54,7 @@ func (h *UserHandler) Create(w http.ResponseWriter, r *http.Request) { return } if err != nil { - httpx.WriteError( - w, - http.StatusInternalServerError, - dto.ErrorCodeInternalError, - "internal server error", - requestID, - ) + httpx.WriteInternal(w, requestID) return } @@ -88,13 +82,7 @@ func (h *UserHandler) Me(w http.ResponseWriter, r *http.Request) { return } if err != nil { - httpx.WriteError( - w, - http.StatusInternalServerError, - dto.ErrorCodeInternalError, - "internal server error", - requestID, - ) + httpx.WriteInternal(w, requestID) return } diff --git a/internal/httpx/response.go b/internal/httpx/response.go index 9a12f0ba..51e240b5 100644 --- a/internal/httpx/response.go +++ b/internal/httpx/response.go @@ -22,3 +22,13 @@ func WriteError(w http.ResponseWriter, status int, code dto.ErrorCode, message, }, }) } + +func WriteInternal(w http.ResponseWriter, requestID string) { + WriteError( + w, + http.StatusInternalServerError, + dto.ErrorCodeInternalError, + "internal server error", + requestID, + ) +} -- 2.54.0 From a8525778a38bfa759b75f3e8928685ff2e5a1c7b Mon Sep 17 00:00:00 2001 From: kk10 Date: Mon, 5 Oct 2026 11:54:36 +0300 Subject: [PATCH 12/40] feat(auth): add session login, logout and bearer middleware --- db/queries/sessions.sql | 5 +- internal/app/app.go | 2 + internal/app/router.go | 7 ++- internal/db/sessions.sql.go | 12 +++-- internal/dto/session.go | 10 ++++ internal/handler/auth.go | 73 +++++++++++++++++++++++++ internal/httpx/auth.go | 37 +++++++++++++ internal/middleware/auth.go | 45 ++++++---------- internal/model/session.go | 9 ++++ internal/service/auth.go | 105 ++++++++++++++++++++++++++++++++++++ 10 files changed, 268 insertions(+), 37 deletions(-) create mode 100644 internal/dto/session.go create mode 100644 internal/handler/auth.go create mode 100644 internal/httpx/auth.go create mode 100644 internal/model/session.go create mode 100644 internal/service/auth.go diff --git a/db/queries/sessions.sql b/db/queries/sessions.sql index 65970af5..4f1decde 100644 --- a/db/queries/sessions.sql +++ b/db/queries/sessions.sql @@ -14,9 +14,10 @@ SELECT user_id FROM sessions WHERE token_hash = sqlc.arg(token_hash) AND expires_at > now(); --- name: DeleteSession :exec +-- name: DeleteSession :execrows DELETE FROM sessions -WHERE token_hash = sqlc.arg(token_hash); +WHERE token_hash = sqlc.arg(token_hash) + AND expires_at > now(); -- name: DeleteExpiredSessions :execrows DELETE FROM sessions diff --git a/internal/app/app.go b/internal/app/app.go index dcf6fbc1..3372947b 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -43,6 +43,7 @@ func Run() error { queries := db.New(pool) memory := store.New() + authService := service.NewAuthService(queries, cfg.Server.SessionTTL) userService := service.NewUserService(queries) chatService := service.NewChatService(memory) messageService := service.NewMessageService(memory) @@ -51,6 +52,7 @@ func Run() error { log, cfg.Server.MaxInflightRequests, pool, + authService, userService, chatService, messageService, diff --git a/internal/app/router.go b/internal/app/router.go index 07c81925..32fb089c 100644 --- a/internal/app/router.go +++ b/internal/app/router.go @@ -15,6 +15,7 @@ func NewRouter( log *slog.Logger, maxInflightRequests int, db handler.Pinger, + authService *service.AuthService, userService *service.UserService, chatService *service.ChatService, messageService *service.MessageService, @@ -22,6 +23,7 @@ func NewRouter( router := chi.NewRouter() healthHandler := handler.NewHealthHandler(log, db) + authHandler := handler.NewAuthHandler(authService) userHandler := handler.NewUserHandler(userService) chatHandler := handler.NewChatHandler(chatService) messageHandler := handler.NewMessageHandler(messageService) @@ -35,8 +37,11 @@ func NewRouter( router.Post("/api/v1/users", userHandler.Create) + router.Post("/api/v1/auth/sessions", authHandler.CreateSession) + router.Delete("/api/v1/auth/sessions/current", authHandler.RevokeSession) + router.Group(func(r chi.Router) { - r.Use(middleware.Auth(userService)) + r.Use(middleware.Auth(authService)) r.Get("/api/v1/users/me", userHandler.Me) diff --git a/internal/db/sessions.sql.go b/internal/db/sessions.sql.go index 3438166b..3d2e9de2 100644 --- a/internal/db/sessions.sql.go +++ b/internal/db/sessions.sql.go @@ -48,14 +48,18 @@ func (q *Queries) DeleteExpiredSessions(ctx context.Context) (int64, error) { return result.RowsAffected(), nil } -const deleteSession = `-- name: DeleteSession :exec +const deleteSession = `-- name: DeleteSession :execrows DELETE FROM sessions WHERE token_hash = $1 + AND expires_at > now() ` -func (q *Queries) DeleteSession(ctx context.Context, tokenHash string) error { - _, err := q.db.Exec(ctx, deleteSession, tokenHash) - return err +func (q *Queries) DeleteSession(ctx context.Context, tokenHash string) (int64, error) { + result, err := q.db.Exec(ctx, deleteSession, tokenHash) + if err != nil { + return 0, err + } + return result.RowsAffected(), nil } const getSessionUserID = `-- name: GetSessionUserID :one diff --git a/internal/dto/session.go b/internal/dto/session.go new file mode 100644 index 00000000..f8d1ccf2 --- /dev/null +++ b/internal/dto/session.go @@ -0,0 +1,10 @@ +package dto + +import "time" + +type SessionResponse struct { + Token string `json:"token"` + TokenType string `json:"token_type"` + ExpiresAt time.Time `json:"expires_at"` + User UserResponse `json:"user"` +} diff --git a/internal/handler/auth.go b/internal/handler/auth.go new file mode 100644 index 00000000..ae422c2c --- /dev/null +++ b/internal/handler/auth.go @@ -0,0 +1,73 @@ +package handler + +import ( + "errors" + "net/http" + + "mtusi2026-messenger/internal/dto" + "mtusi2026-messenger/internal/httpx" + "mtusi2026-messenger/internal/middleware" + "mtusi2026-messenger/internal/service" +) + +type AuthHandler struct { + service *service.AuthService +} + +func NewAuthHandler(s *service.AuthService) *AuthHandler { + return &AuthHandler{service: s} +} + +func (h *AuthHandler) CreateSession(w http.ResponseWriter, r *http.Request) { + requestID := middleware.GetRequestID(r.Context()) + + username, plain, ok := r.BasicAuth() + if !ok { + httpx.WriteUnauthorized(w, httpx.BasicChallenge, requestID) + return + } + + session, err := h.service.Login(r.Context(), username, plain) + if errors.Is(err, service.ErrInvalidCredentials) { + httpx.WriteUnauthorized(w, httpx.BasicChallenge, requestID) + return + } + if err != nil { + httpx.WriteInternal(w, requestID) + return + } + + httpx.WriteJSON(w, http.StatusCreated, dto.SessionResponse{ + Token: session.Token, + TokenType: "Bearer", + ExpiresAt: session.ExpiresAt, + User: dto.UserResponse{ + ID: session.User.ID, + Username: session.User.Username, + DisplayName: session.User.DisplayName, + CreatedAt: session.User.CreatedAt, + }, + }) +} + +func (h *AuthHandler) RevokeSession(w http.ResponseWriter, r *http.Request) { + requestID := middleware.GetRequestID(r.Context()) + + token, ok := httpx.BearerToken(r) + if !ok { + httpx.WriteUnauthorized(w, httpx.BearerChallenge, requestID) + return + } + + err := h.service.Logout(r.Context(), token) + if errors.Is(err, service.ErrUnauthorized) { + httpx.WriteUnauthorized(w, httpx.BearerChallenge, requestID) + return + } + if err != nil { + httpx.WriteInternal(w, requestID) + return + } + + w.WriteHeader(http.StatusNoContent) +} diff --git a/internal/httpx/auth.go b/internal/httpx/auth.go new file mode 100644 index 00000000..b2fb421c --- /dev/null +++ b/internal/httpx/auth.go @@ -0,0 +1,37 @@ +package httpx + +import ( + "net/http" + "strings" + + "mtusi2026-messenger/internal/dto" +) + +const ( + BasicChallenge = `Basic realm="messenger", charset="UTF-8"` + BearerChallenge = `Bearer realm="messenger"` +) + +func BearerToken(r *http.Request) (string, bool) { + const prefix = "Bearer " + + header := r.Header.Get("Authorization") + if len(header) <= len(prefix) || !strings.EqualFold(header[:len(prefix)], prefix) { + return "", false + } + + token := strings.TrimSpace(header[len(prefix):]) + + return token, token != "" +} + +func WriteUnauthorized(w http.ResponseWriter, challenge, requestID string) { + w.Header().Set("WWW-Authenticate", challenge) + WriteError( + w, + http.StatusUnauthorized, + dto.ErrorCodeUnauthorized, + "unauthorized", + requestID, + ) +} diff --git a/internal/middleware/auth.go b/internal/middleware/auth.go index 38cc7da3..ad78688c 100644 --- a/internal/middleware/auth.go +++ b/internal/middleware/auth.go @@ -2,54 +2,39 @@ package middleware import ( "context" + "errors" "net/http" "github.com/google/uuid" - "mtusi2026-messenger/internal/dto" "mtusi2026-messenger/internal/httpx" "mtusi2026-messenger/internal/service" ) type userIDContextKey struct{} -func Auth(userService *service.UserService) func(http.Handler) http.Handler { +type authenticator interface { + Authenticate(ctx context.Context, token string) (uuid.UUID, error) +} + +func Auth(auth authenticator) func(http.Handler) http.Handler { return func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { requestID := GetRequestID(r.Context()) - raw := r.Header.Get("X-User-Id") - if raw == "" { - httpx.WriteError( - w, - http.StatusUnauthorized, - dto.ErrorCodeUnauthorized, - "missing X-User-Id header", - requestID, - ) + token, ok := httpx.BearerToken(r) + if !ok { + httpx.WriteUnauthorized(w, httpx.BearerChallenge, requestID) return } - userID, err := uuid.Parse(raw) + userID, err := auth.Authenticate(r.Context(), token) + if errors.Is(err, service.ErrUnauthorized) { + httpx.WriteUnauthorized(w, httpx.BearerChallenge, requestID) + return + } if err != nil { - httpx.WriteError( - w, - http.StatusUnauthorized, - dto.ErrorCodeUnauthorized, - "invalid X-User-Id header", - requestID, - ) - return - } - - if _, err := userService.GetByID(userID); err != nil { - httpx.WriteError( - w, - http.StatusUnauthorized, - dto.ErrorCodeUnauthorized, - "unknown user", - requestID, - ) + httpx.WriteInternal(w, requestID) return } diff --git a/internal/model/session.go b/internal/model/session.go new file mode 100644 index 00000000..4129b793 --- /dev/null +++ b/internal/model/session.go @@ -0,0 +1,9 @@ +package model + +import "time" + +type Session struct { + Token string + ExpiresAt time.Time + User User +} diff --git a/internal/service/auth.go b/internal/service/auth.go new file mode 100644 index 00000000..84a29445 --- /dev/null +++ b/internal/service/auth.go @@ -0,0 +1,105 @@ +package service + +import ( + "context" + "errors" + "time" + + "mtusi2026-messenger/internal/credentials" + "mtusi2026-messenger/internal/db" + "mtusi2026-messenger/internal/model" + "mtusi2026-messenger/internal/postgres" + + "github.com/google/uuid" +) + +var ( + ErrInvalidCredentials = errors.New("invalid credentials") + ErrUnauthorized = errors.New("unauthorized") +) + +type authQueries interface { + CreateSession(ctx context.Context, arg db.CreateSessionParams) error + DeleteSession(ctx context.Context, tokenHash string) (int64, error) + GetSessionUserID(ctx context.Context, tokenHash string) (uuid.UUID, error) + GetUserByUsername(ctx context.Context, username string) (db.User, error) +} + +type AuthService struct { + q authQueries + sessionTTL time.Duration +} + +func NewAuthService(q authQueries, sessionTTL time.Duration) *AuthService { + return &AuthService{ + q: q, + sessionTTL: sessionTTL, + } +} + +var dummyHash, _ = credentials.HashPassword("dummy-password-for-timing") + +func (s *AuthService) Login(ctx context.Context, username, plain string) (model.Session, error) { + user, err := s.q.GetUserByUsername(ctx, username) + if postgres.IsNotFound(err) { + _ = credentials.VerifyPassword(dummyHash, plain) + return model.Session{}, ErrInvalidCredentials + } + if err != nil { + return model.Session{}, err + } + + if err := credentials.VerifyPassword(user.PasswordHash, plain); err != nil { + if errors.Is(err, credentials.ErrPasswordMismatch) { + return model.Session{}, ErrInvalidCredentials + } + return model.Session{}, err + } + + token := credentials.NewToken() + expiresAt := time.Now().UTC().Add(s.sessionTTL) + + err = s.q.CreateSession(ctx, db.CreateSessionParams{ + TokenHash: credentials.HashToken(token), + UserID: user.ID, + ExpiresAt: expiresAt, + }) + if err != nil { + return model.Session{}, err + } + + return model.Session{ + Token: token, + ExpiresAt: expiresAt, + User: model.User{ + ID: user.ID, + Username: user.Username, + DisplayName: user.DisplayName, + CreatedAt: user.CreatedAt.UTC(), + }, + }, nil +} + +func (s *AuthService) Authenticate(ctx context.Context, token string) (uuid.UUID, error) { + userID, err := s.q.GetSessionUserID(ctx, credentials.HashToken(token)) + if postgres.IsNotFound(err) { + return uuid.Nil, ErrUnauthorized + } + if err != nil { + return uuid.Nil, err + } + + return userID, nil +} + +func (s *AuthService) Logout(ctx context.Context, token string) error { + n, err := s.q.DeleteSession(ctx, credentials.HashToken(token)) + if err != nil { + return err + } + if n == 0 { + return ErrUnauthorized + } + + return nil +} -- 2.54.0 From 86f4aadead851b8acec12ea711b00a665bd5bcf7 Mon Sep 17 00:00:00 2001 From: kk10 Date: Mon, 5 Oct 2026 11:57:31 +0300 Subject: [PATCH 13/40] refactor(httpx): rename WriteInternal to WriteInternalError --- internal/handler/auth.go | 4 ++-- internal/handler/chat.go | 6 +++--- internal/handler/message.go | 4 ++-- internal/handler/user.go | 4 ++-- internal/middleware/auth.go | 2 +- 5 files changed, 10 insertions(+), 10 deletions(-) diff --git a/internal/handler/auth.go b/internal/handler/auth.go index ae422c2c..0a64acb4 100644 --- a/internal/handler/auth.go +++ b/internal/handler/auth.go @@ -33,7 +33,7 @@ func (h *AuthHandler) CreateSession(w http.ResponseWriter, r *http.Request) { return } if err != nil { - httpx.WriteInternal(w, requestID) + httpx.WriteInternalError(w, requestID) return } @@ -65,7 +65,7 @@ func (h *AuthHandler) RevokeSession(w http.ResponseWriter, r *http.Request) { return } if err != nil { - httpx.WriteInternal(w, requestID) + httpx.WriteInternalError(w, requestID) return } diff --git a/internal/handler/chat.go b/internal/handler/chat.go index 8b6b23d5..1f8fc6da 100644 --- a/internal/handler/chat.go +++ b/internal/handler/chat.go @@ -71,7 +71,7 @@ func (h *ChatHandler) Create(w http.ResponseWriter, r *http.Request) { ) return case err != nil: - httpx.WriteInternal(w, requestID) + httpx.WriteInternalError(w, requestID) return } @@ -106,7 +106,7 @@ func (h *ChatHandler) Get(w http.ResponseWriter, r *http.Request) { ) return case err != nil: - httpx.WriteInternal(w, requestID) + httpx.WriteInternalError(w, requestID) return } @@ -134,7 +134,7 @@ func (h *ChatHandler) List(w http.ResponseWriter, r *http.Request) { ) return case err != nil: - httpx.WriteInternal(w, requestID) + httpx.WriteInternalError(w, requestID) return } diff --git a/internal/handler/message.go b/internal/handler/message.go index 85814865..954c4752 100644 --- a/internal/handler/message.go +++ b/internal/handler/message.go @@ -65,7 +65,7 @@ func (h *MessageHandler) Create(w http.ResponseWriter, r *http.Request) { ) return case err != nil: - httpx.WriteInternal(w, requestID) + httpx.WriteInternalError(w, requestID) return } @@ -114,7 +114,7 @@ func (h *MessageHandler) List(w http.ResponseWriter, r *http.Request) { ) return case err != nil: - httpx.WriteInternal(w, requestID) + httpx.WriteInternalError(w, requestID) return } diff --git a/internal/handler/user.go b/internal/handler/user.go index 40d6086b..4990f4be 100644 --- a/internal/handler/user.go +++ b/internal/handler/user.go @@ -54,7 +54,7 @@ func (h *UserHandler) Create(w http.ResponseWriter, r *http.Request) { return } if err != nil { - httpx.WriteInternal(w, requestID) + httpx.WriteInternalError(w, requestID) return } @@ -82,7 +82,7 @@ func (h *UserHandler) Me(w http.ResponseWriter, r *http.Request) { return } if err != nil { - httpx.WriteInternal(w, requestID) + httpx.WriteInternalError(w, requestID) return } diff --git a/internal/middleware/auth.go b/internal/middleware/auth.go index ad78688c..d34071f3 100644 --- a/internal/middleware/auth.go +++ b/internal/middleware/auth.go @@ -34,7 +34,7 @@ func Auth(auth authenticator) func(http.Handler) http.Handler { return } if err != nil { - httpx.WriteInternal(w, requestID) + httpx.WriteInternalError(w, requestID) return } -- 2.54.0 From c99f6f02c5f66a8fcb7963feff3b2924039b35be Mon Sep 17 00:00:00 2001 From: kk10 Date: Mon, 5 Oct 2026 12:47:41 +0300 Subject: [PATCH 14/40] refactor(httpx): rename WriteInternal to WriteInternalError --- internal/httpx/response.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/internal/httpx/response.go b/internal/httpx/response.go index 51e240b5..34f910f1 100644 --- a/internal/httpx/response.go +++ b/internal/httpx/response.go @@ -23,7 +23,7 @@ func WriteError(w http.ResponseWriter, status int, code dto.ErrorCode, message, }) } -func WriteInternal(w http.ResponseWriter, requestID string) { +func WriteInternalError(w http.ResponseWriter, requestID string) { WriteError( w, http.StatusInternalServerError, -- 2.54.0 From 04f7c046b6fea6a00b5ec43334f963942a9b0a1b Mon Sep 17 00:00:00 2001 From: kk10 Date: Mon, 5 Oct 2026 12:54:51 +0300 Subject: [PATCH 15/40] feat(chat): store chats in Postgres --- internal/app/app.go | 2 +- internal/dto/chat.go | 5 +- internal/handler/chat.go | 6 +- internal/service/chat.go | 135 +++++++++++++++++++++++++++++++-------- 4 files changed, 116 insertions(+), 32 deletions(-) diff --git a/internal/app/app.go b/internal/app/app.go index 3372947b..b448398b 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -45,7 +45,7 @@ func Run() error { authService := service.NewAuthService(queries, cfg.Server.SessionTTL) userService := service.NewUserService(queries) - chatService := service.NewChatService(memory) + chatService := service.NewChatService(pool, queries) messageService := service.NewMessageService(memory) router := NewRouter( diff --git a/internal/dto/chat.go b/internal/dto/chat.go index 904b7de0..f8c2cca0 100644 --- a/internal/dto/chat.go +++ b/internal/dto/chat.go @@ -27,8 +27,9 @@ type ChatPageResponse struct { } func (r CreateChatRequest) Validate() bool { - titleLen := utf8.RuneCountInString(r.Title) - if strings.TrimSpace(r.Title) == "" || titleLen > 100 { + if strings.TrimSpace(r.Title) == "" || + strings.ContainsRune(r.Title, 0) || + utf8.RuneCountInString(r.Title) > 100 { return false } diff --git a/internal/handler/chat.go b/internal/handler/chat.go index 1f8fc6da..f69e727f 100644 --- a/internal/handler/chat.go +++ b/internal/handler/chat.go @@ -41,7 +41,7 @@ func (h *ChatHandler) Create(w http.ResponseWriter, r *http.Request) { return } - chat, err := h.service.Create(userID, req.Title, req.MemberIDs) + chat, err := h.service.Create(r.Context(), userID, req.Title, req.MemberIDs) switch { case errors.Is(err, service.ErrNotChatMember): httpx.WriteError( @@ -94,7 +94,7 @@ func (h *ChatHandler) Get(w http.ResponseWriter, r *http.Request) { return } - chat, err := h.service.Get(userID, chatID) + chat, err := h.service.Get(r.Context(), userID, chatID) switch { case errors.Is(err, service.ErrChatNotFound): httpx.WriteError( @@ -122,7 +122,7 @@ func (h *ChatHandler) List(w http.ResponseWriter, r *http.Request) { return } - chats, nextCursor, err := h.service.List(userID, limit, cursor) + chats, nextCursor, err := h.service.List(r.Context(), userID, limit, cursor) switch { case errors.Is(err, service.ErrInvalidCursor): httpx.WriteError( diff --git a/internal/service/chat.go b/internal/service/chat.go index a6f20ba2..ab0325a1 100644 --- a/internal/service/chat.go +++ b/internal/service/chat.go @@ -1,14 +1,19 @@ package service import ( + "bytes" + "context" "errors" "slices" "time" "github.com/google/uuid" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgxpool" + "mtusi2026-messenger/internal/db" "mtusi2026-messenger/internal/model" - "mtusi2026-messenger/internal/store" + "mtusi2026-messenger/internal/postgres" ) var ( @@ -18,15 +23,35 @@ var ( ErrUnknownMember = errors.New("member_ids contains unknown user") ) -type ChatService struct { - store *store.Memory +type chatQueries interface { + CreateChat(ctx context.Context, arg db.CreateChatParams) (db.Chat, error) + AddChatMembers(ctx context.Context, arg db.AddChatMembersParams) error + GetChat(ctx context.Context, arg db.GetChatParams) (db.GetChatRow, error) + ListChats(ctx context.Context, arg db.ListChatsParams) ([]db.ListChatsRow, error) } -func NewChatService(store *store.Memory) *ChatService { - return &ChatService{store: store} +type txBeginner interface { + Begin(ctx context.Context) (pgx.Tx, error) +} + +type ChatService struct { + pool txBeginner + q chatQueries + withTx func(pgx.Tx) chatQueries +} + +func NewChatService(pool *pgxpool.Pool, q *db.Queries) *ChatService { + return &ChatService{ + pool: pool, + q: q, + withTx: func(tx pgx.Tx) chatQueries { + return q.WithTx(tx) + }, + } } func (s *ChatService) Create( + ctx context.Context, userID uuid.UUID, title string, memberIDs []uuid.UUID, @@ -35,35 +60,81 @@ func (s *ChatService) Create( return model.Chat{}, ErrNotChatMember } - chat, err := s.store.CreateChat(title, memberIDs) - switch { - case errors.Is(err, store.ErrDuplicateMember): - return model.Chat{}, ErrDuplicateMember - case errors.Is(err, store.ErrUnknownMember): - return model.Chat{}, ErrUnknownMember - case err != nil: + tx, err := s.pool.Begin(ctx) + if err != nil { + return model.Chat{}, err + } + defer tx.Rollback(ctx) + + q := s.withTx(tx) + + id, err := uuid.NewV7() + if err != nil { return model.Chat{}, err } - return chat, nil + row, err := q.CreateChat(ctx, db.CreateChatParams{ + ID: id, + Title: title, + }) + + err = q.AddChatMembers(ctx, db.AddChatMembersParams{ + ChatID: row.ID, + UserIds: memberIDs, + }) + switch postgres.ErrCode(err) { + case postgres.CodeUniqueViolation: + return model.Chat{}, ErrDuplicateMember + case postgres.CodeForeignKeyViolation: + return model.Chat{}, ErrUnknownMember + } + if err != nil { + return model.Chat{}, err + } + + if err := tx.Commit(ctx); err != nil { + return model.Chat{}, err + } + + ids := slices.Clone(memberIDs) + slices.SortFunc(ids, func(a, b uuid.UUID) int { + return bytes.Compare(a[:], b[:]) + }) + + return model.Chat{ + ID: row.ID, + Title: row.Title, + CreatedAt: row.CreatedAt, + MemberIDs: ids, + }, nil } func (s *ChatService) Get( + ctx context.Context, userID uuid.UUID, chatID uuid.UUID, ) (model.Chat, error) { - chat, err := s.store.GetChat(chatID, userID) - if errors.Is(err, store.ErrNotFound) { + row, err := s.q.GetChat(ctx, db.GetChatParams{ + ID: chatID, + UserID: userID, + }) + if postgres.IsNotFound(err) { return model.Chat{}, ErrChatNotFound } if err != nil { return model.Chat{}, err } - return chat, nil + return model.Chat{ + ID: row.ID, + Title: row.Title, + CreatedAt: row.CreatedAt, + MemberIDs: row.MemberIds, + }, nil } func (s *ChatService) List( + ctx context.Context, userID uuid.UUID, limit int, cursor *string, @@ -81,21 +152,33 @@ func (s *ChatService) List( afterID = &decoded.ID } - chats, hasMore, err := s.store.ListChats( - userID, - afterCreatedAt, - afterID, - limit, - ) - if errors.Is(err, store.ErrInvalidCursor) { - return nil, nil, ErrInvalidCursor - } + rows, err := s.q.ListChats(ctx, db.ListChatsParams{ + UserID: userID, + AfterCreatedAt: afterCreatedAt, + AfterID: afterID, + Lim: int32(limit + 1), + }) if err != nil { return nil, nil, err } + hasMore := len(rows) > limit + if hasMore { + rows = rows[:limit] + } + + chats := make([]model.Chat, 0, len(rows)) + for _, r := range rows { + chats = append(chats, model.Chat{ + ID: r.ID, + Title: r.Title, + CreatedAt: r.CreatedAt, + MemberIDs: r.MemberIds, + }) + } + var next *string - if hasMore && len(chats) > 0 { + if hasMore { last := chats[len(chats)-1] c := encodeCursor(Cursor{ -- 2.54.0 From 385a8c03125e228b1c9c3a8e49358ca25f345e96 Mon Sep 17 00:00:00 2001 From: kk10 Date: Mon, 5 Oct 2026 13:26:21 +0300 Subject: [PATCH 16/40] feat(message): store messages in Postgres --- internal/app/app.go | 4 +- internal/dto/message.go | 5 +- internal/handler/message.go | 4 +- internal/service/chat.go | 4 +- internal/service/cursor.go | 5 +- internal/service/message.go | 96 +++++++++++++++++++++++++++---------- 6 files changed, 82 insertions(+), 36 deletions(-) diff --git a/internal/app/app.go b/internal/app/app.go index b448398b..c936a17f 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -15,7 +15,6 @@ import ( "mtusi2026-messenger/internal/logger" "mtusi2026-messenger/internal/postgres" "mtusi2026-messenger/internal/service" - "mtusi2026-messenger/internal/store" ) func Run() error { @@ -41,12 +40,11 @@ func Run() error { defer pool.Close() queries := db.New(pool) - memory := store.New() authService := service.NewAuthService(queries, cfg.Server.SessionTTL) userService := service.NewUserService(queries) chatService := service.NewChatService(pool, queries) - messageService := service.NewMessageService(memory) + messageService := service.NewMessageService(queries) router := NewRouter( log, diff --git a/internal/dto/message.go b/internal/dto/message.go index 0997a292..32658c56 100644 --- a/internal/dto/message.go +++ b/internal/dto/message.go @@ -27,8 +27,9 @@ type MessagePageResponse struct { } func (r CreateMessageRequest) Validate() bool { - textLen := utf8.RuneCountInString(r.Text) - if strings.TrimSpace(r.Text) == "" || textLen > 4000 { + if strings.TrimSpace(r.Text) == "" || + strings.ContainsRune(r.Text, 0) || + utf8.RuneCountInString(r.Text) > 4000 { return false } diff --git a/internal/handler/message.go b/internal/handler/message.go index 954c4752..9d16b66c 100644 --- a/internal/handler/message.go +++ b/internal/handler/message.go @@ -53,7 +53,7 @@ func (h *MessageHandler) Create(w http.ResponseWriter, r *http.Request) { return } - message, err := h.service.Create(userID, chatID, req.Text) + message, err := h.service.Create(r.Context(), userID, chatID, req.Text) switch { case errors.Is(err, service.ErrMessageChatNotFound): httpx.WriteError( @@ -93,7 +93,7 @@ func (h *MessageHandler) List(w http.ResponseWriter, r *http.Request) { return } - messages, nextCursor, err := h.service.List(userID, chatID, limit, cursor) + messages, nextCursor, err := h.service.List(r.Context(), userID, chatID, limit, cursor) switch { case errors.Is(err, service.ErrMessageChatNotFound): httpx.WriteError( diff --git a/internal/service/chat.go b/internal/service/chat.go index ab0325a1..5489a2ee 100644 --- a/internal/service/chat.go +++ b/internal/service/chat.go @@ -24,8 +24,8 @@ var ( ) type chatQueries interface { - CreateChat(ctx context.Context, arg db.CreateChatParams) (db.Chat, error) AddChatMembers(ctx context.Context, arg db.AddChatMembersParams) error + CreateChat(ctx context.Context, arg db.CreateChatParams) (db.Chat, error) GetChat(ctx context.Context, arg db.GetChatParams) (db.GetChatRow, error) ListChats(ctx context.Context, arg db.ListChatsParams) ([]db.ListChatsRow, error) } @@ -143,7 +143,7 @@ func (s *ChatService) List( var afterID *uuid.UUID if cursor != nil { - decoded, err := decodeCursor(*cursor) + decoded, err := decodeCursor(*cursor, uuid.Nil) if err != nil { return nil, nil, ErrInvalidCursor } diff --git a/internal/service/cursor.go b/internal/service/cursor.go index b727bd1e..4709543f 100644 --- a/internal/service/cursor.go +++ b/internal/service/cursor.go @@ -12,6 +12,7 @@ import ( var ErrInvalidCursor = errors.New("invalid cursor") type Cursor struct { + ChatID uuid.UUID `json:"chat_id"` CreatedAt time.Time `json:"created_at"` ID uuid.UUID `json:"id"` } @@ -21,7 +22,7 @@ func encodeCursor(cursor Cursor) string { return base64.RawURLEncoding.EncodeToString(data) } -func decodeCursor(raw string) (Cursor, error) { +func decodeCursor(raw string, chatID uuid.UUID) (Cursor, error) { data, err := base64.RawURLEncoding.DecodeString(raw) if err != nil { return Cursor{}, ErrInvalidCursor @@ -32,7 +33,7 @@ func decodeCursor(raw string) (Cursor, error) { return Cursor{}, ErrInvalidCursor } - if cursor.ID == uuid.Nil || cursor.CreatedAt.IsZero() { + if cursor.ID == uuid.Nil || cursor.CreatedAt.IsZero() || cursor.ChatID != chatID { return Cursor{}, ErrInvalidCursor } diff --git a/internal/service/message.go b/internal/service/message.go index 93cb2f7a..78667489 100644 --- a/internal/service/message.go +++ b/internal/service/message.go @@ -1,52 +1,89 @@ package service import ( + "context" "errors" "time" "github.com/google/uuid" + "mtusi2026-messenger/internal/db" "mtusi2026-messenger/internal/model" - "mtusi2026-messenger/internal/store" + "mtusi2026-messenger/internal/postgres" ) var ErrMessageChatNotFound = errors.New("chat not found") -type MessageService struct { - store *store.Memory +type messageQueries interface { + CreateMessage(ctx context.Context, arg db.CreateMessageParams) (db.Message, error) + IsChatMember(ctx context.Context, arg db.IsChatMemberParams) (bool, error) + ListMessages(ctx context.Context, arg db.ListMessagesParams) ([]db.Message, error) } -func NewMessageService(store *store.Memory) *MessageService { - return &MessageService{store: store} +type MessageService struct { + q messageQueries +} + +func NewMessageService(q *db.Queries) *MessageService { + return &MessageService{q: q} } func (s *MessageService) Create( + ctx context.Context, userID uuid.UUID, chatID uuid.UUID, text string, ) (model.Message, error) { - message, err := s.store.CreateMessage(chatID, userID, text) - if errors.Is(err, store.ErrNotFound) { + id, err := uuid.NewV7() + if err != nil { + return model.Message{}, err + } + + row, err := s.q.CreateMessage(ctx, db.CreateMessageParams{ + ID: id, + ChatID: chatID, + SenderID: userID, + Text: text, + }) + if postgres.IsNotFound(err) { return model.Message{}, ErrMessageChatNotFound } if err != nil { return model.Message{}, err } - return message, nil + return model.Message{ + ID: row.ID, + ChatID: row.ChatID, + SenderID: row.SenderID, + Text: row.Text, + CreatedAt: row.CreatedAt, + }, nil } func (s *MessageService) List( + ctx context.Context, userID uuid.UUID, chatID uuid.UUID, limit int, cursor *string, ) ([]model.Message, *string, error) { + isMember, err := s.q.IsChatMember(ctx, db.IsChatMemberParams{ + ChatID: chatID, + UserID: userID, + }) + if err != nil { + return nil, nil, err + } + if !isMember { + return nil, nil, ErrMessageChatNotFound + } + var afterCreatedAt *time.Time var afterID *uuid.UUID if cursor != nil { - decoded, err := decodeCursor(*cursor) + decoded, err := decodeCursor(*cursor, chatID) if err != nil { return nil, nil, ErrInvalidCursor } @@ -55,28 +92,37 @@ func (s *MessageService) List( afterID = &decoded.ID } - messages, hasMore, err := s.store.ListMessages( - chatID, - userID, - afterCreatedAt, - afterID, - limit, - ) - if errors.Is(err, store.ErrNotFound) { - return nil, nil, ErrMessageChatNotFound - } - if errors.Is(err, store.ErrInvalidCursor) { - return nil, nil, ErrInvalidCursor - } + rows, err := s.q.ListMessages(ctx, db.ListMessagesParams{ + ChatID: chatID, + AfterCreatedAt: afterCreatedAt, + AfterID: afterID, + Lim: int32(limit + 1), + }) if err != nil { return nil, nil, err } - var next *string - if hasMore && len(messages) > 0 { - last := messages[len(messages)-1] + hasMore := len(rows) > limit + if hasMore { + rows = rows[:limit] + } + messages := make([]model.Message, 0, len(rows)) + for _, r := range rows { + messages = append(messages, model.Message{ + ID: r.ID, + ChatID: r.ChatID, + SenderID: r.SenderID, + Text: r.Text, + CreatedAt: r.CreatedAt, + }) + } + + var next *string + if hasMore { + last := messages[len(messages)-1] c := encodeCursor(Cursor{ + ChatID: chatID, CreatedAt: last.CreatedAt, ID: last.ID, }) -- 2.54.0 From 79036b0f18109583b0378c313f653936731093e0 Mon Sep 17 00:00:00 2001 From: kk10 Date: Mon, 5 Oct 2026 13:42:00 +0300 Subject: [PATCH 17/40] test: authenticate student tests with session tokens --- student-tests/contract_test.go | 11 +++---- student-tests/helpers_test.go | 58 +++++++++++++++++++++++----------- student-tests/race_test.go | 2 +- 3 files changed, 45 insertions(+), 26 deletions(-) diff --git a/student-tests/contract_test.go b/student-tests/contract_test.go index 08535e8a..2aea9f28 100644 --- a/student-tests/contract_test.go +++ b/student-tests/contract_test.go @@ -9,13 +9,11 @@ import ( "strconv" "testing" - "github.com/google/uuid" - "mtusi2026-messenger/internal/dto" ) func TestInvalidJSON(t *testing.T) { - resp := doRequest(t, http.MethodPost, "/api/v1/users", uuid.Nil, []byte(`{"username": "broken",`)) + resp := doRequest(t, http.MethodPost, "/api/v1/users", "", []byte(`{"username": "broken",`)) requireStatus(t, resp, http.StatusBadRequest) var apiErr dto.ErrorResponse @@ -33,7 +31,7 @@ func TestForeignChat(t *testing.T) { chat := createChat(t, user1, user1.ID, user2.ID) - resp := doRequest(t, http.MethodGet, "/api/v1/chats/"+chat.ID.String(), user3.ID, nil) + resp := doRequest(t, http.MethodGet, "/api/v1/chats/"+chat.ID.String(), user3.Token, nil) requireStatus(t, resp, http.StatusNotFound) resp = sendMessage(t, user3, chat.ID, "should not land") @@ -56,12 +54,13 @@ func TestDuplicateUsername(t *testing.T) { body, err := json.Marshal(map[string]string{ "username": user.Username, "display_name": "Someone else", + "password": testPassword, }) if err != nil { t.Fatalf("marshal body: %v", err) } - resp := doRequest(t, http.MethodPost, "/api/v1/users", uuid.Nil, body) + resp := doRequest(t, http.MethodPost, "/api/v1/users", "", body) requireStatus(t, resp, http.StatusConflict) var apiErr dto.ErrorResponse @@ -99,7 +98,7 @@ func TestPagination(t *testing.T) { path += "&cursor=" + url.QueryEscape(cursor) } - resp := doRequest(t, http.MethodGet, path, user.ID, nil) + resp := doRequest(t, http.MethodGet, path, user.Token, nil) requireStatus(t, resp, http.StatusOK) var page dto.MessagePageResponse diff --git a/student-tests/helpers_test.go b/student-tests/helpers_test.go index 4e32c05c..b97f4d5d 100644 --- a/student-tests/helpers_test.go +++ b/student-tests/helpers_test.go @@ -28,7 +28,14 @@ var httpClient = &http.Client{ }, } -func doRequest(t *testing.T, method, path string, actorID uuid.UUID, body []byte) *http.Response { +type testUser struct { + dto.UserResponse + Token string +} + +const testPassword = "correct-horse-battery" + +func doRequest(t *testing.T, method, path, token string, body []byte) *http.Response { t.Helper() req, err := http.NewRequest(method, *baseURL+path, bytes.NewReader(body)) @@ -40,8 +47,8 @@ func doRequest(t *testing.T, method, path string, actorID uuid.UUID, body []byte req.Header.Set("Content-Type", "application/json") } - if actorID != uuid.Nil { - req.Header.Set("X-User-Id", actorID.String()) + if token != "" { + req.Header.Set("Authorization", "Bearer "+token) } resp, err := httpClient.Do(req) @@ -86,7 +93,7 @@ func requireStatus(t *testing.T, resp *http.Response, expected int) { } } -func createUser(t *testing.T) dto.UserResponse { +func createUser(t *testing.T) testUser { t.Helper() username := "u_" + strings.ReplaceAll(uuid.NewString(), "-", "")[:12] @@ -94,30 +101,43 @@ func createUser(t *testing.T) dto.UserResponse { body, err := json.Marshal(map[string]string{ "username": username, "display_name": "Test " + username, + "password": testPassword, }) if err != nil { t.Fatalf("marshal user: %v", err) } - resp := doRequest( - t, - http.MethodPost, - "/api/v1/users", - uuid.Nil, - body, - ) - + resp := doRequest(t, http.MethodPost, "/api/v1/users", "", body) requireStatus(t, resp, http.StatusCreated) var u dto.UserResponse mustDecode(t, resp, &u) - return u + req, err := http.NewRequest( + http.MethodPost, + *baseURL+"/api/v1/auth/sessions", + nil, + ) + if err != nil { + t.Fatalf("build login request: %v", err) + } + req.SetBasicAuth(username, testPassword) + + resp, err = httpClient.Do(req) + if err != nil { + t.Fatalf("login request failed: %v", err) + } + requireStatus(t, resp, http.StatusCreated) + + var session dto.SessionResponse + mustDecode(t, resp, &session) + + return testUser{UserResponse: u, Token: session.Token} } func createChat( t *testing.T, - creator dto.UserResponse, + creator testUser, memberIDs ...uuid.UUID, ) dto.ChatResponse { t.Helper() @@ -134,7 +154,7 @@ func createChat( t, http.MethodPost, "/api/v1/chats", - creator.ID, + creator.Token, body, ) @@ -148,7 +168,7 @@ func createChat( func sendMessage( t *testing.T, - actor dto.UserResponse, + actor testUser, chatID uuid.UUID, text string, ) *http.Response { @@ -165,13 +185,13 @@ func sendMessage( t, http.MethodPost, fmt.Sprintf("/api/v1/chats/%v/messages", chatID.String()), - actor.ID, + actor.Token, body, ) } func sendLoadMessage( - actor dto.UserResponse, + actor testUser, chatID uuid.UUID, text string, ) (*http.Response, error) { @@ -192,7 +212,7 @@ func sendLoadMessage( } req.Header.Set("Content-Type", "application/json") - req.Header.Set("X-User-Id", actor.ID.String()) + req.Header.Set("Authorization", "Bearer "+actor.Token) return httpClient.Do(req) } diff --git a/student-tests/race_test.go b/student-tests/race_test.go index 67d17689..3a4384dc 100644 --- a/student-tests/race_test.go +++ b/student-tests/race_test.go @@ -70,7 +70,7 @@ func TestConcurrentMessages(t *testing.T) { seen := make(map[string]bool, total) path := "/api/v1/chats/" + chat.ID.String() + "/messages?limit=100" - resp := doRequest(t, http.MethodGet, path, user1.ID, nil) + resp := doRequest(t, http.MethodGet, path, user1.Token, nil) requireStatus(t, resp, http.StatusOK) var page dto.MessagePageResponse -- 2.54.0 From 7b92ca2366cc738f3e2cd4bcfc64cf135ccd6a50 Mon Sep 17 00:00:00 2001 From: kk10 Date: Mon, 5 Oct 2026 15:11:24 +0300 Subject: [PATCH 18/40] feat(auth): delete expired sessions hourly --- internal/app/app.go | 11 +++++++++++ internal/app/cleanup.go | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+) create mode 100644 internal/app/cleanup.go diff --git a/internal/app/app.go b/internal/app/app.go index c936a17f..dfa8d02c 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -41,6 +41,17 @@ func Run() error { queries := db.New(pool) + cleanupCtx, stopCleanup := context.WithCancel(context.Background()) + cleanupDone := make(chan struct{}) + go func() { + defer close(cleanupDone) + runSessionCleanup(cleanupCtx, log, queries, sessionCleanupInterval) + }() + defer func() { + stopCleanup() + <-cleanupDone + }() + authService := service.NewAuthService(queries, cfg.Server.SessionTTL) userService := service.NewUserService(queries) chatService := service.NewChatService(pool, queries) diff --git a/internal/app/cleanup.go b/internal/app/cleanup.go new file mode 100644 index 00000000..11913643 --- /dev/null +++ b/internal/app/cleanup.go @@ -0,0 +1,36 @@ +package app + +import ( + "context" + "log/slog" + "time" +) + +const sessionCleanupInterval = time.Hour + +type sessionCleaner interface { + DeleteExpiredSessions(ctx context.Context) (int64, error) +} + +func runSessionCleanup(ctx context.Context, log *slog.Logger, q sessionCleaner, interval time.Duration) { + ticker := time.NewTicker(interval) + defer ticker.Stop() + + for { + select { + case <-ctx.Done(): + return + case <-ticker.C: + n, err := q.DeleteExpiredSessions(ctx) + if err != nil { + if ctx.Err() == nil { + log.Error("delete expired sessions", "error", err) + } + continue + } + if n > 0 { + log.Info("expired sessions deleted", "count", n) + } + } + } +} -- 2.54.0 From 62412bd465dfe4f4b69ef738ac22a0f78bea4dfb Mon Sep 17 00:00:00 2001 From: kk10 Date: Mon, 5 Oct 2026 22:18:52 +0300 Subject: [PATCH 19/40] test: add restart hook for persistence test --- scripts/restart.sh | 4 ++++ 1 file changed, 4 insertions(+) create mode 100644 scripts/restart.sh diff --git a/scripts/restart.sh b/scripts/restart.sh new file mode 100644 index 00000000..35118db2 --- /dev/null +++ b/scripts/restart.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu + +docker compose restart postgres backend -- 2.54.0 From 2d413ab7048bf4c379783fcfb84a8dbdd4258b85 Mon Sep 17 00:00:00 2001 From: kk10 Date: Mon, 5 Oct 2026 22:29:18 +0300 Subject: [PATCH 20/40] feat(middleware): add request timeout --- internal/app/router.go | 2 ++ internal/middleware/timeout.go | 17 +++++++++++++++++ 2 files changed, 19 insertions(+) create mode 100644 internal/middleware/timeout.go diff --git a/internal/app/router.go b/internal/app/router.go index 32fb089c..f30293a6 100644 --- a/internal/app/router.go +++ b/internal/app/router.go @@ -3,6 +3,7 @@ package app import ( "log/slog" "net/http" + "time" "github.com/go-chi/chi/v5" @@ -28,6 +29,7 @@ func NewRouter( chatHandler := handler.NewChatHandler(chatService) messageHandler := handler.NewMessageHandler(messageService) + router.Use(middleware.RequestTimeout(5 * time.Second)) router.Use(middleware.RequestID) router.Use(middleware.Logging(log)) router.Use(middleware.ConcurrencyLimit(maxInflightRequests)) diff --git a/internal/middleware/timeout.go b/internal/middleware/timeout.go new file mode 100644 index 00000000..9486fa30 --- /dev/null +++ b/internal/middleware/timeout.go @@ -0,0 +1,17 @@ +package middleware + +import ( + "context" + "net/http" + "time" +) + +func RequestTimeout(d time.Duration) func(http.Handler) http.Handler { + return func(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + ctx, cancel := context.WithTimeout(r.Context(), d) + defer cancel() + next.ServeHTTP(w, r.WithContext(ctx)) + }) + } +} -- 2.54.0 From 66808c6c8046ea987efc8e968536ba857c0fdc3c Mon Sep 17 00:00:00 2001 From: kk10 Date: Mon, 5 Oct 2026 22:43:09 +0300 Subject: [PATCH 21/40] test(auth): add concurrent registration race test --- student-tests/registration_race_test.go | 77 +++++++++++++++++++++++++ 1 file changed, 77 insertions(+) create mode 100644 student-tests/registration_race_test.go diff --git a/student-tests/registration_race_test.go b/student-tests/registration_race_test.go new file mode 100644 index 00000000..1f49203f --- /dev/null +++ b/student-tests/registration_race_test.go @@ -0,0 +1,77 @@ +//go:build race + +package studenttests_test + +import ( + "bytes" + "encoding/json" + "net/http" + "strings" + "sync" + "testing" + + "github.com/google/uuid" +) + +func TestConcurrentRegistration(t *testing.T) { + const workers = 20 + + username := "u_" + strings.ReplaceAll(uuid.NewString(), "-", "")[:12] + + body, err := json.Marshal(map[string]string{ + "username": username, + "display_name": "Racer", + "password": testPassword, + }) + if err != nil { + t.Fatalf("marshal body: %v", err) + } + + start := make(chan struct{}) + statuses := make(chan int, workers) + + var wg sync.WaitGroup + for i := 0; i < workers; i++ { + wg.Add(1) + go func() { + defer wg.Done() + <-start + + req, err := http.NewRequest(http.MethodPost, *baseURL+"/api/v1/users", bytes.NewReader(body)) + if err != nil { + t.Errorf("build request: %v", err) + return + } + req.Header.Set("Content-Type", "application/json") + + resp, err := httpClient.Do(req) + if err != nil { + t.Errorf("request failed: %v", err) + return + } + defer resp.Body.Close() + + statuses <- resp.StatusCode + }() + } + + close(start) + wg.Wait() + close(statuses) + + created, conflict := 0, 0 + for s := range statuses { + switch s { + case http.StatusCreated: + created++ + case http.StatusConflict: + conflict++ + default: + t.Errorf("unexpected status %d", s) + } + } + + if created != 1 || conflict != workers-1 { + t.Fatalf("expected 1 created and %d conflict, got %d created and %d conflict", workers-1, created, conflict) + } +} -- 2.54.0 From 81cea31c810a13226ee4c56e64939052c7a207c0 Mon Sep 17 00:00:00 2001 From: kk10 Date: Mon, 5 Oct 2026 23:06:18 +0300 Subject: [PATCH 22/40] test(chat): add create chat rollback test --- internal/service/chat.go | 3 ++ student-tests/chat_rollback_test.go | 55 +++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+) create mode 100644 student-tests/chat_rollback_test.go diff --git a/internal/service/chat.go b/internal/service/chat.go index 5489a2ee..d17fd976 100644 --- a/internal/service/chat.go +++ b/internal/service/chat.go @@ -77,6 +77,9 @@ func (s *ChatService) Create( ID: id, Title: title, }) + if err != nil { + return model.Chat{}, err + } err = q.AddChatMembers(ctx, db.AddChatMembersParams{ ChatID: row.ID, diff --git a/student-tests/chat_rollback_test.go b/student-tests/chat_rollback_test.go new file mode 100644 index 00000000..76cfb8d6 --- /dev/null +++ b/student-tests/chat_rollback_test.go @@ -0,0 +1,55 @@ +//go:build contract + +package studenttests_test + +import ( + "context" + "encoding/json" + "net/http" + "os" + "strings" + "testing" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5" +) + +func TestCreateChatRollback(t *testing.T) { + data, err := os.ReadFile("../secrets/test_database_url.txt") + if err != nil { + t.Fatalf("read secrets/test_database_url: %v", err) + } + + ctx := context.Background() + conn, err := pgx.Connect(ctx, strings.TrimSpace(string(data))) + if err != nil { + t.Fatalf("connect to database: %v", err) + } + defer conn.Close(ctx) + + creator := createUser(t) + title := "rollback-" + uuid.NewString() + + body, err := json.Marshal(map[string]any{ + "title": title, + "member_ids": []uuid.UUID{creator.ID, uuid.New()}, + }) + if err != nil { + t.Fatalf("marshal body: %v", err) + } + + resp := doRequest(t, http.MethodPost, "/api/v1/chats", creator.Token, body) + resp.Body.Close() + if resp.StatusCode < 400 || resp.StatusCode >= 500 { + t.Fatalf("expected 4xx, got %d", resp.StatusCode) + } + + var n int + err = conn.QueryRow(ctx, "SELECT count(*) FROM chats WHERE title = $1", title).Scan(&n) + if err != nil { + t.Fatalf("count chats: %v", err) + } + if n != 0 { + t.Fatalf("expected no chat rows after failed creation, found %d", n) + } +} -- 2.54.0 From 58177470b70eb67a465ccd30481d1d45e9a1c53f Mon Sep 17 00:00:00 2001 From: kk10 Date: Mon, 5 Oct 2026 23:55:12 +0300 Subject: [PATCH 23/40] chore(compose): publish postgres port on localhost --- docker-compose.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docker-compose.yml b/docker-compose.yml index 02e19ac0..abd7538b 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -17,6 +17,8 @@ services: postgres: image: postgres:18.6 + ports: + - "127.0.0.1:5432:5432" environment: POSTGRES_USER: messenger POSTGRES_DB: messenger -- 2.54.0 From ffe842f31282c833a6d9a9ad16293149ab387f4a Mon Sep 17 00:00:00 2001 From: kk10 Date: Mon, 5 Oct 2026 23:55:20 +0300 Subject: [PATCH 24/40] docs: add explain analyze results for message history --- evidence/explain-history.txt | 90 ++++++++++++++++++++++++++++++++++++ 1 file changed, 90 insertions(+) create mode 100644 evidence/explain-history.txt diff --git a/evidence/explain-history.txt b/evidence/explain-history.txt new file mode 100644 index 00000000..421cafd0 --- /dev/null +++ b/evidence/explain-history.txt @@ -0,0 +1,90 @@ +> docker compose exec postgres psql -U messenger -d messenger +psql (18.6 (Debian 18.6-1.pgdg13+2)) +Type "help" for help. + +messenger=# INSERT INTO users (id, username, display_name, password_hash) +VALUES ('00000000-0000-0000-0000-0000000000a1', 'explain_user', 'Explain', 'x'); +INSERT 0 1 +messenger=# INSERT INTO chats (id, title) +VALUES ('00000000-0000-0000-0000-0000000000b1', 'explain chat'); +INSERT 0 1 +messenger=# INSERT INTO messages (id, chat_id, sender_id, text, created_at) +SELECT gen_random_uuid(), '00000000-0000-0000-0000-0000000000b1', + '00000000-0000-0000-0000-0000000000a1', 'msg ' || g, + now() - (g || ' seconds')::interval +FROM generate_series(1, 20000) g; +INSERT 0 20000 +messenger=# ANALYZE messages; +ANALYZE + +messenger=# BEGIN; +BEGIN +messenger=*# DROP INDEX idx_messages_chat_history; +DROP INDEX +messenger=*# EXPLAIN (ANALYZE, BUFFERS) +SELECT * FROM messages +WHERE chat_id = '00000000-0000-0000-0000-0000000000b1' +ORDER BY created_at, id LIMIT 50; + QUERY PLAN +---------------------------------------------------------------------------------------------------------------------------- + Limit (cost=1405.39..1405.51 rows=50 width=65) (actual time=4.083..4.088 rows=50.00 loops=1) + Buffers: shared hit=491 + -> Sort (cost=1405.39..1455.39 rows=20000 width=65) (actual time=4.082..4.084 rows=50.00 loops=1) + Sort Key: created_at, id + Sort Method: top-N heapsort Memory: 38kB + Buffers: shared hit=491 + -> Seq Scan on messages (cost=0.00..741.00 rows=20000 width=65) (actual time=0.154..1.624 rows=20000.00 loops=1) + Filter: (chat_id = '00000000-0000-0000-0000-0000000000b1'::uuid) + Buffers: shared hit=491 + Planning: + Buffers: shared hit=30 + Planning Time: 0.218 ms + Execution Time: 4.102 ms +(13 rows) + +messenger=*# ROLLBACK; +ROLLBACK + + +messenger=# EXPLAIN (ANALYZE, BUFFERS) +SELECT * FROM messages +WHERE chat_id = '00000000-0000-0000-0000-0000000000b1' +ORDER BY created_at, id LIMIT 50; + QUERY PLAN +------------------------------------------------------------------------------------------------------------------------------------------------------ + Limit (cost=0.41..10.76 rows=50 width=65) (actual time=0.008..0.018 rows=50.00 loops=1) + Buffers: shared hit=6 + -> Index Scan using idx_messages_chat_history on messages (cost=0.41..4139.54 rows=20000 width=65) (actual time=0.006..0.014 rows=50.00 loops=1) + Index Cond: (chat_id = '00000000-0000-0000-0000-0000000000b1'::uuid) + Index Searches: 1 + Buffers: shared hit=6 + Planning: + Buffers: shared hit=22 + Planning Time: 0.141 ms + Execution Time: 0.029 ms +(10 rows) + + +messenger=# SELECT created_at AS cur_ts, id AS cur_id FROM messages +WHERE chat_id = '00000000-0000-0000-0000-0000000000b1' +ORDER BY created_at, id OFFSET 15000 LIMIT 1 \gset + +EXPLAIN (ANALYZE, BUFFERS) +SELECT * FROM messages +WHERE chat_id = '00000000-0000-0000-0000-0000000000b1' + AND (created_at, id) > (:'cur_ts', :'cur_id') +ORDER BY created_at, id LIMIT 50; + + QUERY PLAN +----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + Limit (cost=0.41..17.36 rows=50 width=65) (actual time=0.018..0.031 rows=50.00 loops=1) + Buffers: shared hit=5 + -> Index Scan using idx_messages_chat_history on messages (cost=0.41..1694.52 rows=4999 width=65) (actual time=0.017..0.026 rows=50.00 loops=1) + Index Cond: ((chat_id = '00000000-0000-0000-0000-0000000000b1'::uuid) AND (ROW(created_at, id) > ROW('2026-10-05 19:13:13.4346+00'::timestamp with time zone, '9bb7f5ae-1191-44f9-aaa9-fb1ebf4cc701'::uuid))) + Index Searches: 1 + Buffers: shared hit=5 + Planning Time: 0.071 ms + Execution Time: 0.044 ms +(8 rows) + +messenger=# -- 2.54.0 From 6469ed475b9522378a3e06d55bf19fef436207d2 Mon Sep 17 00:00:00 2001 From: kk10 Date: Tue, 6 Oct 2026 13:05:16 +0300 Subject: [PATCH 25/40] refactor(compose): rename backend service to api --- docker-compose.yml | 2 +- scripts/restart.sh | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docker-compose.yml b/docker-compose.yml index abd7538b..78c94463 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,5 +1,5 @@ services: - backend: + api: build: context: . dockerfile: Dockerfile diff --git a/scripts/restart.sh b/scripts/restart.sh index 35118db2..5a124d24 100644 --- a/scripts/restart.sh +++ b/scripts/restart.sh @@ -1,4 +1,4 @@ #!/bin/sh set -eu -docker compose restart postgres backend +docker compose restart postgres api -- 2.54.0 From 06e9af1ba6f9fa2a9185628a76ede45ef550d233 Mon Sep 17 00:00:00 2001 From: kk10 Date: Tue, 6 Oct 2026 13:09:00 +0300 Subject: [PATCH 26/40] feat(compose): add redis service --- docker-compose.yml | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/docker-compose.yml b/docker-compose.yml index 78c94463..85f2f1fc 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -13,6 +13,8 @@ services: depends_on: migrate: condition: service_completed_successfully + redis: + condition: service_healthy restart: unless-stopped postgres: @@ -45,6 +47,16 @@ services: condition: service_healthy restart: "no" + redis: + image: redis:8.8.3-alpine3.23 + command: ["redis-server", "--save", "", "--appendonly", "no"] + healthcheck: + test: ["CMD", "redis-cli", "ping"] + interval: 5s + timeout: 3s + retries: 10 + restart: unless-stopped + secrets: postgres_password: file: ./secrets/postgres_password.txt -- 2.54.0 From f7e1866d4e76ddb65759b8408f9d8b8070b5313b Mon Sep 17 00:00:00 2001 From: kk10 Date: Tue, 6 Oct 2026 13:18:46 +0300 Subject: [PATCH 27/40] feat(config): add redis url secret --- .env.example | 3 +-- docker-compose.yml | 3 +++ internal/config/config.go | 13 +++++++++++++ internal/redis/client.go | 1 + 4 files changed, 18 insertions(+), 2 deletions(-) create mode 100644 internal/redis/client.go diff --git a/.env.example b/.env.example index 25f9cfdb..5bbc5ebe 100644 --- a/.env.example +++ b/.env.example @@ -6,6 +6,5 @@ SESSION_TTL_SECONDS=3600 LOG_LEVEL=INFO DATABASE_URL_FILE=/run/secrets/database_url -# Optional on 3, required use on 4 in lab2; Redis OR Valkey: -SESSION_STORE=postgres + CACHE_URL_FILE=/run/secrets/cache_url diff --git a/docker-compose.yml b/docker-compose.yml index 85f2f1fc..eaa1e10f 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -10,6 +10,7 @@ services: - .env secrets: - database_url + - cache_url depends_on: migrate: condition: service_completed_successfully @@ -62,6 +63,8 @@ secrets: file: ./secrets/postgres_password.txt database_url: file: ./secrets/database_url.txt + cache_url: + file: ./secrets/cache_url.txt volumes: pgdata: diff --git a/internal/config/config.go b/internal/config/config.go index 2c0d222c..ccffe790 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -14,6 +14,7 @@ type Config struct { Server ServerConfig Logging LoggingConfig Database DatabaseConfig + Redis RedisConfig } type ServerConfig struct { @@ -35,6 +36,14 @@ func (c DatabaseConfig) URL() (string, error) { return readSecretFile(c.URLFile) } +type RedisConfig struct { + URLFile string +} + +func (c RedisConfig) URL() (string, error) { + return readSecretFile(c.URLFile) +} + func Load() Config { return Config{ Server: ServerConfig{ @@ -51,6 +60,10 @@ func Load() Config { Database: DatabaseConfig{ URLFile: getEnv("DATABASE_URL_FILE", "/run/secrets/database_url"), }, + + Redis: RedisConfig{ + URLFile: getEnv("CACHE_URL_FILE", "/run/secrets/cache_url"), + }, } } diff --git a/internal/redis/client.go b/internal/redis/client.go new file mode 100644 index 00000000..65a229e1 --- /dev/null +++ b/internal/redis/client.go @@ -0,0 +1 @@ +package redis -- 2.54.0 From 5bd210b59d98c6384ffb6034d21ac4da44d83e04 Mon Sep 17 00:00:00 2001 From: kk10 Date: Tue, 6 Oct 2026 15:36:52 +0300 Subject: [PATCH 28/40] feat(auth): cache sessions in redis with postgres fallback --- docker-compose.yml | 2 -- go.mod | 4 +++ go.sum | 27 +++++++++++++----- internal/app/app.go | 16 ++++++++++- internal/redis/client.go | 31 +++++++++++++++++++++ internal/service/auth.go | 59 +++++++++++++++++++++++++++++++++++++--- scripts/restart.sh | 2 +- 7 files changed, 126 insertions(+), 15 deletions(-) diff --git a/docker-compose.yml b/docker-compose.yml index eaa1e10f..caf3650c 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -14,8 +14,6 @@ services: depends_on: migrate: condition: service_completed_successfully - redis: - condition: service_healthy restart: unless-stopped postgres: diff --git a/go.mod b/go.mod index 658d8f9d..a1de767d 100644 --- a/go.mod +++ b/go.mod @@ -7,13 +7,17 @@ require ( github.com/google/uuid v1.6.0 github.com/jackc/pgx/v5 v5.11.0 github.com/joho/godotenv v1.5.1 + github.com/redis/go-redis/v9 v9.23.0 golang.org/x/crypto v0.57.0 ) require ( + github.com/cespare/xxhash/v2 v2.3.0 // indirect github.com/jackc/pgpassfile v1.0.0 // indirect github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect github.com/jackc/puddle/v2 v2.2.2 // indirect + go.uber.org/atomic v1.12.0 // indirect golang.org/x/sync v0.23.0 // indirect + golang.org/x/sys v0.48.0 // indirect golang.org/x/text v0.42.0 // indirect ) diff --git a/go.sum b/go.sum index 1c8ee76a..8e78d734 100644 --- a/go.sum +++ b/go.sum @@ -1,6 +1,10 @@ +github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs= +github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c= +github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA= +github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0= +github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= +github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/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/go-chi/chi/v5 v5.3.2 h1:5YQkICvTCSZ25hoRsyJazN0scjzKGiu4VAUc7H1o1nY= github.com/go-chi/chi/v5 v5.3.2/go.mod h1:R+tYY2hNuVUUjxoPtqUdgBqevM9s9njzkTLutVsOCto= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= @@ -15,20 +19,29 @@ github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0= github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4= -github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/klauspost/cpuid/v2 v2.4.0 h1:S6Hrbc7+ywsr0r+RLapfGBHfyefhCTwEh3A0tV913Dw= +github.com/klauspost/cpuid/v2 v2.4.0/go.mod h1:19jmZ9mjzoF//ddRSUsv0zfBTJWh3QJh9FNxZTMrGxU= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/redis/go-redis/v9 v9.23.0 h1:/TTVdJa8BRNsybwwGGnmiYktHNlUXtbOQxlWpHBPL3s= +github.com/redis/go-redis/v9 v9.23.0/go.mod h1:EWP2UUk+XDaI1s5nQB5mablZN6vccXlmBQTyfnF87D0= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= -github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE= +github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg= +github.com/zeebo/xxh3 v1.1.0 h1:s7DLGDK45Dyfg7++yxI0khrfwq9661w9EN78eP/UZVs= +github.com/zeebo/xxh3 v1.1.0/go.mod h1:IisAie1LELR4xhVinxWS5+zf1lA4p0MW4T+w+W07F5s= +go.uber.org/atomic v1.12.0 h1:BvcXdFKuviU4fTL/f+SxdQ5qJX/Jix8pAkgdUcb3XOE= +go.uber.org/atomic v1.12.0/go.mod h1:I6c4cg+6HCxRjfjSsYtApoFILnpc0CGUdGkXVqbYVNk= +go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw= +go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg= golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M= golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA= golang.org/x/sync v0.23.0 h1:KameEIfc1IkluZyXWLn39Wd4tURc6GbCiISGiZm2bQk= golang.org/x/sync v0.23.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= +golang.org/x/sys v0.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/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= -gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/internal/app/app.go b/internal/app/app.go index dfa8d02c..e4e9224b 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -14,6 +14,7 @@ import ( "mtusi2026-messenger/internal/db" "mtusi2026-messenger/internal/logger" "mtusi2026-messenger/internal/postgres" + "mtusi2026-messenger/internal/redis" "mtusi2026-messenger/internal/service" ) @@ -41,6 +42,19 @@ func Run() error { queries := db.New(pool) + cacheURL, err := cfg.Redis.URL() + if err != nil { + log.Error("read redis url", "error", err) + return err + } + + rdb, err := redis.New(context.Background(), log, cacheURL) + if err != nil { + log.Error("create redis client", "error", err) + return err + } + defer rdb.Close() + cleanupCtx, stopCleanup := context.WithCancel(context.Background()) cleanupDone := make(chan struct{}) go func() { @@ -52,7 +66,7 @@ func Run() error { <-cleanupDone }() - authService := service.NewAuthService(queries, cfg.Server.SessionTTL) + authService := service.NewAuthService(queries, rdb, cfg.Server.SessionTTL, log) userService := service.NewUserService(queries) chatService := service.NewChatService(pool, queries) messageService := service.NewMessageService(queries) diff --git a/internal/redis/client.go b/internal/redis/client.go index 65a229e1..65ccd3a2 100644 --- a/internal/redis/client.go +++ b/internal/redis/client.go @@ -1 +1,32 @@ package redis + +import ( + "context" + "fmt" + "log/slog" + "time" + + goredis "github.com/redis/go-redis/v9" +) + +func New(ctx context.Context, log *slog.Logger, url string) (*goredis.Client, error) { + opts, err := goredis.ParseURL(url) + if err != nil { + return nil, fmt.Errorf("parse redis url: %w", err) + } + + opts.DialTimeout = 1 * time.Second + opts.ReadTimeout = 200 * time.Millisecond + opts.WriteTimeout = 200 * time.Millisecond + opts.MaxRetries = -1 + + client := goredis.NewClient(opts) + + pingCtx, cancel := context.WithTimeout(ctx, 2*time.Second) + defer cancel() + if err := client.Ping(pingCtx).Err(); err != nil { + log.Warn("redis unavailable, running without cache", "error", err) + } + + return client, nil +} diff --git a/internal/service/auth.go b/internal/service/auth.go index 84a29445..e15cc649 100644 --- a/internal/service/auth.go +++ b/internal/service/auth.go @@ -3,6 +3,7 @@ package service import ( "context" "errors" + "log/slog" "time" "mtusi2026-messenger/internal/credentials" @@ -11,8 +12,12 @@ import ( "mtusi2026-messenger/internal/postgres" "github.com/google/uuid" + goredis "github.com/redis/go-redis/v9" ) +const sessionCacheTTL = 60 * time.Second +const cacheOpTimeout = 300 * time.Millisecond + var ( ErrInvalidCredentials = errors.New("invalid credentials") ErrUnauthorized = errors.New("unauthorized") @@ -27,13 +32,17 @@ type authQueries interface { type AuthService struct { q authQueries + cache *goredis.Client sessionTTL time.Duration + log *slog.Logger } -func NewAuthService(q authQueries, sessionTTL time.Duration) *AuthService { +func NewAuthService(q authQueries, cache *goredis.Client, sessionTTL time.Duration, log *slog.Logger) *AuthService { return &AuthService{ q: q, + cache: cache, sessionTTL: sessionTTL, + log: log, } } @@ -81,7 +90,24 @@ func (s *AuthService) Login(ctx context.Context, username, plain string) (model. } func (s *AuthService) Authenticate(ctx context.Context, token string) (uuid.UUID, error) { - userID, err := s.q.GetSessionUserID(ctx, credentials.HashToken(token)) + tokenHash := credentials.HashToken(token) + key := cacheKey(tokenHash) + + cctx, cancel := context.WithTimeout(ctx, cacheOpTimeout) + val, err := s.cache.Get(cctx, key).Result() + cancel() + + if err == nil { + id, perr := uuid.Parse(val) + if perr == nil { + return id, nil + } + s.log.Warn("session cache value is not a uuid", "error", perr) + } else if !errors.Is(err, goredis.Nil) { + s.log.Warn("session cache get failed, falling back to database", "error", err) + } + + userID, err := s.q.GetSessionUserID(ctx, tokenHash) if postgres.IsNotFound(err) { return uuid.Nil, ErrUnauthorized } @@ -89,17 +115,42 @@ func (s *AuthService) Authenticate(ctx context.Context, token string) (uuid.UUID return uuid.Nil, err } + cctx, cancel = context.WithTimeout(ctx, cacheOpTimeout) + if err := s.cache.Set(cctx, key, userID.String(), s.cacheTTL()).Err(); err != nil { + s.log.Warn("session cache set failed", "error", err) + } + cancel() + return userID, nil } func (s *AuthService) Logout(ctx context.Context, token string) error { - n, err := s.q.DeleteSession(ctx, credentials.HashToken(token)) + tokenHash := credentials.HashToken(token) + + n, err := s.q.DeleteSession(ctx, tokenHash) if err != nil { return err } + + cctx, cancel := context.WithTimeout(ctx, cacheOpTimeout) + defer cancel() + if err := s.cache.Del(cctx, cacheKey(tokenHash)).Err(); err != nil { + s.log.Warn("session cache delete failed", "error", err) + } + if n == 0 { return ErrUnauthorized } - return nil } + +func cacheKey(tokenHash string) string { + return "session:" + tokenHash +} + +func (s *AuthService) cacheTTL() time.Duration { + if s.sessionTTL < sessionCacheTTL { + return s.sessionTTL + } + return sessionCacheTTL +} diff --git a/scripts/restart.sh b/scripts/restart.sh index 5a124d24..8b313750 100644 --- a/scripts/restart.sh +++ b/scripts/restart.sh @@ -1,4 +1,4 @@ #!/bin/sh set -eu -docker compose restart postgres api +docker compose restart postgres redis api -- 2.54.0 From b540577cf94d7dcfc11a90727ec49e71c0e52682 Mon Sep 17 00:00:00 2001 From: kk10 Date: Tue, 6 Oct 2026 18:33:56 +0300 Subject: [PATCH 29/40] test(auth): add wrong password and logout tests --- student-tests/session_test.go | 58 +++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 student-tests/session_test.go diff --git a/student-tests/session_test.go b/student-tests/session_test.go new file mode 100644 index 00000000..d72097ef --- /dev/null +++ b/student-tests/session_test.go @@ -0,0 +1,58 @@ +//go:build contract + +package studenttests_test + +import ( + "net/http" + "testing" +) + +func basicLogin(t *testing.T, username, password string) *http.Response { + t.Helper() + + req, err := http.NewRequest(http.MethodPost, *baseURL+"/api/v1/auth/sessions", nil) + if err != nil { + t.Fatalf("build login request: %v", err) + } + req.SetBasicAuth(username, password) + + resp, err := httpClient.Do(req) + if err != nil { + t.Fatalf("login request failed: %v", err) + } + return resp +} + +func TestLoginWrongPassword(t *testing.T) { + user := createUser(t) + + resp := basicLogin(t, user.Username, "wrong-"+testPassword) + requireStatus(t, resp, http.StatusUnauthorized) + resp.Body.Close() + + resp = basicLogin(t, "no_such_user_"+user.Username, testPassword) + requireStatus(t, resp, http.StatusUnauthorized) + resp.Body.Close() +} + +func TestLogout(t *testing.T) { + user := createUser(t) + + resp := doRequest(t, http.MethodGet, "/api/v1/users/me", user.Token, nil) + requireStatus(t, resp, http.StatusOK) + resp.Body.Close() + + resp = doRequest(t, http.MethodDelete, "/api/v1/auth/sessions/current", user.Token, nil) + if resp.StatusCode >= 300 { + t.Fatalf("logout: unexpected status %d", resp.StatusCode) + } + resp.Body.Close() + + resp = doRequest(t, http.MethodGet, "/api/v1/users/me", user.Token, nil) + requireStatus(t, resp, http.StatusUnauthorized) + resp.Body.Close() + + resp = doRequest(t, http.MethodDelete, "/api/v1/auth/sessions/current", user.Token, nil) + requireStatus(t, resp, http.StatusUnauthorized) + resp.Body.Close() +} -- 2.54.0 From d7002b4dfee60e54a91dc8cc69f1fb53584c4d97 Mon Sep 17 00:00:00 2001 From: kk10 Date: Tue, 6 Oct 2026 18:45:31 +0300 Subject: [PATCH 30/40] feat(httpx): return 503 when a dependency is unavailable --- internal/handler/auth.go | 4 ++-- internal/handler/chat.go | 6 +++--- internal/handler/message.go | 4 ++-- internal/handler/user.go | 4 ++-- internal/httpx/response.go | 35 ++++++++++++++++++++++++++++++++++- internal/middleware/auth.go | 2 +- 6 files changed, 44 insertions(+), 11 deletions(-) diff --git a/internal/handler/auth.go b/internal/handler/auth.go index 0a64acb4..07e2d683 100644 --- a/internal/handler/auth.go +++ b/internal/handler/auth.go @@ -33,7 +33,7 @@ func (h *AuthHandler) CreateSession(w http.ResponseWriter, r *http.Request) { return } if err != nil { - httpx.WriteInternalError(w, requestID) + httpx.WriteInternalError(w, requestID, err) return } @@ -65,7 +65,7 @@ func (h *AuthHandler) RevokeSession(w http.ResponseWriter, r *http.Request) { return } if err != nil { - httpx.WriteInternalError(w, requestID) + httpx.WriteInternalError(w, requestID, err) return } diff --git a/internal/handler/chat.go b/internal/handler/chat.go index f69e727f..e5f9c1e6 100644 --- a/internal/handler/chat.go +++ b/internal/handler/chat.go @@ -71,7 +71,7 @@ func (h *ChatHandler) Create(w http.ResponseWriter, r *http.Request) { ) return case err != nil: - httpx.WriteInternalError(w, requestID) + httpx.WriteInternalError(w, requestID, err) return } @@ -106,7 +106,7 @@ func (h *ChatHandler) Get(w http.ResponseWriter, r *http.Request) { ) return case err != nil: - httpx.WriteInternalError(w, requestID) + httpx.WriteInternalError(w, requestID, err) return } @@ -134,7 +134,7 @@ func (h *ChatHandler) List(w http.ResponseWriter, r *http.Request) { ) return case err != nil: - httpx.WriteInternalError(w, requestID) + httpx.WriteInternalError(w, requestID, err) return } diff --git a/internal/handler/message.go b/internal/handler/message.go index 9d16b66c..d181fa14 100644 --- a/internal/handler/message.go +++ b/internal/handler/message.go @@ -65,7 +65,7 @@ func (h *MessageHandler) Create(w http.ResponseWriter, r *http.Request) { ) return case err != nil: - httpx.WriteInternalError(w, requestID) + httpx.WriteInternalError(w, requestID, err) return } @@ -114,7 +114,7 @@ func (h *MessageHandler) List(w http.ResponseWriter, r *http.Request) { ) return case err != nil: - httpx.WriteInternalError(w, requestID) + httpx.WriteInternalError(w, requestID, err) return } diff --git a/internal/handler/user.go b/internal/handler/user.go index 4990f4be..66cc985a 100644 --- a/internal/handler/user.go +++ b/internal/handler/user.go @@ -54,7 +54,7 @@ func (h *UserHandler) Create(w http.ResponseWriter, r *http.Request) { return } if err != nil { - httpx.WriteInternalError(w, requestID) + httpx.WriteInternalError(w, requestID, err) return } @@ -82,7 +82,7 @@ func (h *UserHandler) Me(w http.ResponseWriter, r *http.Request) { return } if err != nil { - httpx.WriteInternalError(w, requestID) + httpx.WriteInternalError(w, requestID, err) return } diff --git a/internal/httpx/response.go b/internal/httpx/response.go index 34f910f1..f2eac202 100644 --- a/internal/httpx/response.go +++ b/internal/httpx/response.go @@ -1,8 +1,14 @@ package httpx import ( + "context" "encoding/json" + "errors" + "net" "net/http" + "strings" + + "github.com/jackc/pgx/v5/pgconn" "mtusi2026-messenger/internal/dto" ) @@ -23,7 +29,18 @@ func WriteError(w http.ResponseWriter, status int, code dto.ErrorCode, message, }) } -func WriteInternalError(w http.ResponseWriter, requestID string) { +func WriteInternalError(w http.ResponseWriter, requestID string, err error) { + if isUnavailable(err) { + WriteError( + w, + http.StatusServiceUnavailable, + dto.ErrorCodeUnavailable, + "dependency unavailable", + requestID, + ) + return + } + WriteError( w, http.StatusInternalServerError, @@ -32,3 +49,19 @@ func WriteInternalError(w http.ResponseWriter, requestID string) { requestID, ) } + +func isUnavailable(err error) bool { + if errors.Is(err, context.DeadlineExceeded) { + return true + } + + if _, ok := errors.AsType[net.Error](err); ok { + return true + } + + if pgErr, ok := errors.AsType[*pgconn.PgError](err); ok { + return strings.HasPrefix(pgErr.Code, "08") || pgErr.Code == "57P01" + } + + return false +} diff --git a/internal/middleware/auth.go b/internal/middleware/auth.go index d34071f3..5ade80c3 100644 --- a/internal/middleware/auth.go +++ b/internal/middleware/auth.go @@ -34,7 +34,7 @@ func Auth(auth authenticator) func(http.Handler) http.Handler { return } if err != nil { - httpx.WriteInternalError(w, requestID) + httpx.WriteInternalError(w, requestID, err) return } -- 2.54.0 From fff2cb5b37383f2d8dc5ebd718749c2f8e5ca69d Mon Sep 17 00:00:00 2001 From: kk10 Date: Wed, 7 Oct 2026 17:07:05 +0300 Subject: [PATCH 31/40] test(auth): add redis and database failure tests --- student-tests/dependency_failure_test.go | 89 ++++++++++++++++++++++++ student.mk | 10 ++- 2 files changed, 97 insertions(+), 2 deletions(-) create mode 100644 student-tests/dependency_failure_test.go diff --git a/student-tests/dependency_failure_test.go b/student-tests/dependency_failure_test.go new file mode 100644 index 00000000..b0f23638 --- /dev/null +++ b/student-tests/dependency_failure_test.go @@ -0,0 +1,89 @@ +//go:build failure + +package studenttests_test + +import ( + "net/http" + "os/exec" + "testing" + "time" +) + +func compose(t *testing.T, args ...string) { + t.Helper() + + cmd := exec.Command("docker", append([]string{"compose"}, args...)...) + cmd.Dir = ".." + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("docker compose %v: %v\n%s", args, err, out) + } +} + +func stopService(t *testing.T, name string) { + t.Helper() + + compose(t, "stop", name) + t.Cleanup(func() { + compose(t, "start", name) + waitReady(t) + }) +} + +func waitReady(t *testing.T) { + t.Helper() + + deadline := time.Now().Add(60 * time.Second) + for time.Now().Before(deadline) { + resp, err := httpClient.Get(*baseURL + "/health/ready") + if err == nil { + resp.Body.Close() + if resp.StatusCode == http.StatusOK { + return + } + } + time.Sleep(500 * time.Millisecond) + } + t.Fatal("service did not become ready in 60s") +} + +func TestRedisDown(t *testing.T) { + user := createUser(t) + + stopService(t, "redis") + + // настоящий токен + resp := doRequest(t, http.MethodGet, "/api/v1/users/me", user.Token, nil) + requireStatus(t, resp, http.StatusOK) + resp.Body.Close() + + // выдуманный токен + resp = doRequest(t, http.MethodGet, "/api/v1/users/me", "forged-"+user.Token, nil) + requireStatus(t, resp, http.StatusUnauthorized) + resp.Body.Close() + + // без токена + resp = doRequest(t, http.MethodGet, "/api/v1/users/me", "", nil) + requireStatus(t, resp, http.StatusUnauthorized) + resp.Body.Close() +} + +func TestDatabaseDown(t *testing.T) { + user := createUser(t) // токен ещё не использован, ключа в Redis нет + + stopService(t, "postgres") + + // ключа в кэше нет, проверить сессию негде + resp := doRequest(t, http.MethodGet, "/api/v1/users/me", user.Token, nil) + requireStatus(t, resp, http.StatusServiceUnavailable) + resp.Body.Close() + + // выдуманный токен + resp = doRequest(t, http.MethodGet, "/api/v1/users/me", "forged-"+user.Token, nil) + requireStatus(t, resp, http.StatusServiceUnavailable) + resp.Body.Close() + + // без токена + resp = doRequest(t, http.MethodGet, "/api/v1/users/me", "", nil) + requireStatus(t, resp, http.StatusUnauthorized) + resp.Body.Close() +} diff --git a/student.mk b/student.mk index 8de59f03..012aef3c 100644 --- a/student.mk +++ b/student.mk @@ -2,10 +2,13 @@ LOAD_ARGS = $(if $(LOAD_WORKERS),-workers=$(LOAD_WORKERS),) \ $(if $(LOAD_DURATION),-duration=$(LOAD_DURATION),) \ $(if $(LOAD_RATE),-rate=$(LOAD_RATE),) -.PHONY: help-go contract-go race-go load-go +.PHONY: help-go contract-go race-go load-go failure-go help-go: - @echo "contract-go: student contract tests; race-go: concurrency test with -race; load-go: Go load test" + @echo "contract-go: contract tests" + @echo "race-go: concurrency tests (-race)" + @echo "load-go: load test" + @echo "failure-go: dependency failure tests (stops redis/postgres containers)" contract-go: go test -tags=contract ./student-tests/... -v -args -base-url=$(BASE_URL) @@ -15,3 +18,6 @@ race-go: load-go: go test -tags=load ./student-tests/... -v -args -base-url=$(BASE_URL) $(LOAD_ARGS) + +failure-go: + go test -tags=failure ./student-tests/... -v -args -base-url=$(BASE_URL) -- 2.54.0 From 0e62ba9660f274c52ccbc17c1ffc624cb8073777 Mon Sep 17 00:00:00 2001 From: kk10 Date: Wed, 7 Oct 2026 17:13:09 +0300 Subject: [PATCH 32/40] test(auth): add session expiry test with short ttl --- student-tests/session_expiry_test.go | 42 ++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 student-tests/session_expiry_test.go diff --git a/student-tests/session_expiry_test.go b/student-tests/session_expiry_test.go new file mode 100644 index 00000000..99eb098c --- /dev/null +++ b/student-tests/session_expiry_test.go @@ -0,0 +1,42 @@ +//go:build failure + +package studenttests_test + +import ( + "net/http" + "os/exec" + "testing" + "time" +) + +const shortTTLContainer = "api-short-ttl" +const shortTTLURL = "http://localhost:8081" + +func TestSessionExpiry(t *testing.T) { + _ = exec.Command("docker", "rm", "-f", shortTTLContainer).Run() + + compose(t, "run", "-d", "--no-deps", "--name", shortTTLContainer, + "-e", "SESSION_TTL_SECONDS=3", + "-p", "127.0.0.1:8081:8080", "api") + t.Cleanup(func() { + _ = exec.Command("docker", "rm", "-f", shortTTLContainer).Run() + }) + + old := *baseURL + *baseURL = shortTTLURL + t.Cleanup(func() { *baseURL = old }) + + waitReady(t) + + user := createUser(t) + + resp := doRequest(t, http.MethodGet, "/api/v1/users/me", user.Token, nil) + requireStatus(t, resp, http.StatusOK) + resp.Body.Close() + + time.Sleep(4 * time.Second) + + resp = doRequest(t, http.MethodGet, "/api/v1/users/me", user.Token, nil) + requireStatus(t, resp, http.StatusUnauthorized) + resp.Body.Close() +} -- 2.54.0 From 497f677453051753aae6d96e9bc1a76a83d4293c Mon Sep 17 00:00:00 2001 From: kk10 Date: Wed, 7 Oct 2026 23:48:38 +0300 Subject: [PATCH 33/40] docs: add track 2 and test evidence --- evidence/make-contract-go.txt | Bin 0 -> 1370 bytes evidence/make-failure-go.txt | 9 + evidence/make-race-go.txt | 9 + evidence/make-test-persistence.txt | 4 + evidence/make-test.txt | 3 + evidence/migrate-repeat.txt | 4 + evidence/track2-backup-restore.txt | 70 +++++++ evidence/track2-explain.txt | 297 +++++++++++++++++++++++++++++ evidence/track2-insert-cost.txt | 168 ++++++++++++++++ 9 files changed, 564 insertions(+) create mode 100644 evidence/make-contract-go.txt create mode 100644 evidence/make-failure-go.txt create mode 100644 evidence/make-race-go.txt create mode 100644 evidence/make-test-persistence.txt create mode 100644 evidence/make-test.txt create mode 100644 evidence/migrate-repeat.txt create mode 100644 evidence/track2-backup-restore.txt create mode 100644 evidence/track2-explain.txt create mode 100644 evidence/track2-insert-cost.txt diff --git a/evidence/make-contract-go.txt b/evidence/make-contract-go.txt new file mode 100644 index 0000000000000000000000000000000000000000..1216af47dab26c1fd94f0c8b04d5918923d5c0a0 GIT binary patch literal 1370 zcmbW1TT22#7>3_lgZ{%_)`jaSDg=YDf}(?1(zWTbO6rQc8vXg|`Np<_tes+5XPlk) zFyCQcUyc-Ls=gi-u^K4ROqmw!44BJ`+1b{Xn*(+trThlG$v6}9uk{TTC{)FrTWScx z814KToANGn!&p|1tB;~_+0FyJDQC-CvO9r)1UA!LO^_9K5)}K)BUa|7sY6xWV@_Lc z1nR1%YZz_Zy=%8&jKG?gHh5cgVVN*YcR(DBqwGeYj*fN9X#SBS&<>75)o_(+*Kz*l z>zo*^+?~cm>;lCbycapyjLNmEIPlRv%W>uvA6E4@Uso|x6LXFMI{n%BMRYeb6L_B6VnR+-WX881U;N_{~VlZ|NGMrgQ z7R6%|CfBX2?xlN)QjFeA_uSu9W9r{}G1Zf+kzt_^ACCX|O2|~^slPs(>(sv7KksLY tXF{*rx1mIyGuTt^UZ-d3)Na}3-fnJRFRRGKuV1thogQirtmW9)-vHNJ(;EN) literal 0 HcmV?d00001 diff --git a/evidence/make-failure-go.txt b/evidence/make-failure-go.txt new file mode 100644 index 00000000..1e8071c9 --- /dev/null +++ b/evidence/make-failure-go.txt @@ -0,0 +1,9 @@ +> make failure-go +go test -tags=failure ./student-tests/... -v -args -base-url=http://localhost:8080 +=== RUN TestRedisDown +--- PASS: TestRedisDown (2.12s) +=== RUN --- PASS: TestDatabaseDown (10.90s) +=== RUN TestSessionExpiry +--- PASS: TestSessionExpiry (5.77s) +PASS +ok mtusi2026-messenger/student-tests 18.803s diff --git a/evidence/make-race-go.txt b/evidence/make-race-go.txt new file mode 100644 index 00000000..6cadf697 --- /dev/null +++ b/evidence/make-race-go.txt @@ -0,0 +1,9 @@ +> make race-go +go test -tags=race ./student-tests/... -race -v -args -base-url=http://localhost:8080 +=== RUN TestConcurrentMessages + race_test.go:98: PASS: 10 concurrent clients sent 100 messages, exactly 100 unique messages persisted +--- PASS: TestConcurrentMessages (0.31s) +=== RUN TestConcurrentRegistration +--- PASS: TestConcurrentRegistration (0.12s) +PASS +ok mtusi2026-messenger/student-tests 1.443s diff --git a/evidence/make-test-persistence.txt b/evidence/make-test-persistence.txt new file mode 100644 index 00000000..b20f0a29 --- /dev/null +++ b/evidence/make-test-persistence.txt @@ -0,0 +1,4 @@ +> make test-persistence ACTION_SCRIPT=scripts/restart.sh +python3 tests/resilience.py --mode persistence --action-script "scripts/restart.sh" --base-url "http://localhost:8080" +Executing explicit persistence hook; hook output suppressed to avoid leaking secrets. +PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence. diff --git a/evidence/make-test.txt b/evidence/make-test.txt new file mode 100644 index 00000000..74f1b6c0 --- /dev/null +++ b/evidence/make-test.txt @@ -0,0 +1,3 @@ +> make test +python3 tests/smoke.py --base-url "http://localhost:8080" +PASS: lab2 public API scenario; infrastructure and grading evidence remain separate. diff --git a/evidence/migrate-repeat.txt b/evidence/migrate-repeat.txt new file mode 100644 index 00000000..a201a7c5 --- /dev/null +++ b/evidence/migrate-repeat.txt @@ -0,0 +1,4 @@ +> docker compose run --rm --no-deps migrate + Container mtusi2026lab2-migrate-run-481a17e62bda Creating + Container mtusi2026lab2-migrate-run-481a17e62bda Created +2026/10/07 20:39:09 goose: no migrations to run. current version: 1 diff --git a/evidence/track2-backup-restore.txt b/evidence/track2-backup-restore.txt new file mode 100644 index 00000000..17196aee --- /dev/null +++ b/evidence/track2-backup-restore.txt @@ -0,0 +1,70 @@ +research=# DROP TABLE messages_seed; +DROP TABLE +Time: 4.369 ms +research=# CREATE INDEX idx_messages_chat_history ON messages (chat_id, created_at, id); +CREATE INDEX +Time: 75.459 ms +research=# ANALYZE messages; +ANALYZE +Time: 92.896 ms +research=# SELECT count(*) FROM messages; + count +-------- + 100000 +(1 row) + +Time: 7.997 ms +research=# SELECT md5(string_agg(id::text || chat_id::text || created_at::text || text, '' ORDER BY id)) AS full_hash FROM messages; + full_hash +---------------------------------- + 3b0b6c7f0769218c3d3d1a7b660f521c +(1 row) + +Time: 74.820 ms +research=# SELECT md5(string_agg(id::text || text, '' ORDER BY created_at, id)) AS page_hash FROM (SELECT * FROM messages WHERE chat_id = (SELECT id FROM chats WHERE title = 'big') AND (created_at, id) > ('2026-01-15 00:00+00', '00000000-0000-0000-0000-000000000000') ORDER BY created_at, id LIMIT 50) p; + page_hash +---------------------------------- + 1b111bf87f61b52ef916f31037c4acb5 +(1 row) + +Time: 0.736 ms +research=# \q + +> Measure-Command { docker compose exec postgres pg_dump -U messenger -d research -Fc -f /tmp/research.dump } | Select-Object TotalSeconds + +TotalSeconds +------------ + 0,6917214 +> docker compose exec postgres psql -U messenger -d postgres -c "CREATE DATABASE research_restore;" +CREATE DATABASE +> Measure-Command { docker compose exec postgres pg_restore -U messenger -d research_restore /tmp/research.dump } | Select-Object TotalSeconds + +TotalSeconds +------------ + 0,5392463 +> docker compose exec postgres ls -lh /tmp/research.dump +-rw-r--r-- 1 root root 4.1M Oct 7 19:48 /tmp/research.dump +> docker compose exec postgres psql -U messenger -d research_restore +psql (18.6 (Debian 18.6-1.pgdg13+2)) +Type "help" for help. + +research_restore=# SELECT count(*) FROM messages; + count +-------- + 100000 +(1 row) + +research_restore=# SELECT md5(string_agg(id::text || chat_id::text || created_at::text || text, '' ORDER BY id)) AS full_hash FROM messages; + full_hash +---------------------------------- + 3b0b6c7f0769218c3d3d1a7b660f521c +(1 row) + +research_restore=# SELECT md5(string_agg(id::text || text, '' ORDER BY created_at, id)) AS page_hash FROM (SELECT * FROM messages WHERE chat_id = (SELECT id FROM chats WHERE title = 'big') AND (created_at, id) > ('2026-01-15 00:00+00', '00000000-0000-0000-0000-000000000000') ORDER BY created_at, id LIMIT 50) p; + page_hash +---------------------------------- + 1b111bf87f61b52ef916f31037c4acb5 +(1 row) + +research_restore=# \q +> docker compose exec postgres rm /tmp/research.dump diff --git a/evidence/track2-explain.txt b/evidence/track2-explain.txt new file mode 100644 index 00000000..7c57f99b --- /dev/null +++ b/evidence/track2-explain.txt @@ -0,0 +1,297 @@ +C. (chat_id, id) +research=# EXPLAIN (ANALYZE, BUFFERS) SELECT * FROM messages WHERE chat_id = (SELECT id FROM chats WHERE title = 'big') AND (created_at, id) > ('2026-01-15 00:00+00', '00000000-0000-0000-0000-000000000000') ORDER BY created_at, id LIMIT 50; + QUERY PLAN +-------------------------------------------------------------------------------------------------------------------------------------------------------- + Limit (cost=810.77..810.89 rows=50 width=151) (actual time=11.161..11.167 rows=50.00 loops=1) + Buffers: shared hit=1730 + InitPlan 1 + -> Seq Scan on chats (cost=0.00..4.58 rows=1 width=16) (actual time=0.012..0.024 rows=1.00 loops=1) + Filter: (title = 'big'::text) + Rows Removed by Filter: 205 + Buffers: shared hit=2 + -> Sort (cost=806.19..806.68 rows=193 width=151) (actual time=11.159..11.162 rows=50.00 loops=1) + Sort Key: messages.created_at, messages.id + Sort Method: top-N heapsort Memory: 36kB + Buffers: shared hit=1730 + -> Index Scan using idx_messages_chat_id on messages (cost=0.42..799.78 rows=193 width=151) (actual time=2.648..8.533 rows=39841.00 loops=1) + Index Cond: (chat_id = (InitPlan 1).col1) + Filter: (ROW(created_at, id) > ROW('2026-01-15 00:00:00+00'::timestamp with time zone, '00000000-0000-0000-0000-000000000000'::uuid)) + Rows Removed by Filter: 20159 + Index Searches: 1 + Buffers: shared hit=1730 + Planning Time: 0.115 ms + Execution Time: 11.189 ms +(19 rows) + +Time: 11.614 ms +research=# EXPLAIN (ANALYZE, BUFFERS) SELECT * FROM messages WHERE chat_id = (SELECT id FROM chats WHERE title = 'big') AND (created_at, id) > ('2026-01-15 00:00+00', '00000000-0000-0000-0000-000000000000') ORDER BY created_at, id LIMIT 50; + QUERY PLAN +--------------------------------------------------------------------------------------------------------------------------------------------------------- + Limit (cost=810.77..810.89 rows=50 width=151) (actual time=13.602..13.609 rows=50.00 loops=1) + Buffers: shared hit=1730 + InitPlan 1 + -> Seq Scan on chats (cost=0.00..4.58 rows=1 width=16) (actual time=0.034..0.044 rows=1.00 loops=1) + Filter: (title = 'big'::text) + Rows Removed by Filter: 205 + Buffers: shared hit=2 + -> Sort (cost=806.19..806.68 rows=193 width=151) (actual time=13.601..13.604 rows=50.00 loops=1) + Sort Key: messages.created_at, messages.id + Sort Method: top-N heapsort Memory: 36kB + Buffers: shared hit=1730 + -> Index Scan using idx_messages_chat_id on messages (cost=0.42..799.78 rows=193 width=151) (actual time=3.012..10.954 rows=39841.00 loops=1) + Index Cond: (chat_id = (InitPlan 1).col1) + Filter: (ROW(created_at, id) > ROW('2026-01-15 00:00:00+00'::timestamp with time zone, '00000000-0000-0000-0000-000000000000'::uuid)) + Rows Removed by Filter: 20159 + Index Searches: 1 + Buffers: shared hit=1730 + Planning Time: 0.207 ms + Execution Time: 13.645 ms +(19 rows) + +Time: 14.423 ms +research=# EXPLAIN (ANALYZE, BUFFERS) SELECT * FROM messages WHERE chat_id = (SELECT id FROM chats WHERE title = 'small-1') AND (created_at, id) > ('2026-01-01 00:30+00', '00000000-0000-0000-0000-000000000000') ORDER BY created_at, id LIMIT 50; + QUERY PLAN +----------------------------------------------------------------------------------------------------------------------------------------------------- + Limit (cost=819.50..819.63 rows=50 width=151) (actual time=0.140..0.148 rows=46.00 loops=1) + Buffers: shared hit=10 + InitPlan 1 + -> Seq Scan on chats (cost=0.00..4.58 rows=1 width=16) (actual time=0.011..0.020 rows=1.00 loops=1) + Filter: (title = 'small-1'::text) + Rows Removed by Filter: 205 + Buffers: shared hit=2 + -> Sort (cost=814.93..816.07 rows=456 width=151) (actual time=0.139..0.142 rows=46.00 loops=1) + Sort Key: messages.created_at, messages.id + Sort Method: quicksort Memory: 35kB + Buffers: shared hit=10 + -> Index Scan using idx_messages_chat_id on messages (cost=0.42..799.78 rows=456 width=151) (actual time=0.039..0.047 rows=46.00 loops=1) + Index Cond: (chat_id = (InitPlan 1).col1) + Filter: (ROW(created_at, id) > ROW('2026-01-01 00:30:00+00'::timestamp with time zone, '00000000-0000-0000-0000-000000000000'::uuid)) + Rows Removed by Filter: 29 + Index Searches: 1 + Buffers: shared hit=10 + Planning Time: 0.084 ms + Execution Time: 0.167 ms +(19 rows) + +Time: 0.532 ms +research=# EXPLAIN (ANALYZE, BUFFERS) SELECT * FROM messages WHERE chat_id = (SELECT id FROM chats WHERE title = 'small-1') AND (created_at, id) > ('2026-01-01 00:30+00', '00000000-0000-0000-0000-000000000000') ORDER BY created_at, id LIMIT 50; + QUERY PLAN +----------------------------------------------------------------------------------------------------------------------------------------------------- + Limit (cost=819.50..819.63 rows=50 width=151) (actual time=0.126..0.131 rows=46.00 loops=1) + Buffers: shared hit=10 + InitPlan 1 + -> Seq Scan on chats (cost=0.00..4.58 rows=1 width=16) (actual time=0.032..0.042 rows=1.00 loops=1) + Filter: (title = 'small-1'::text) + Rows Removed by Filter: 205 + Buffers: shared hit=2 + -> Sort (cost=814.93..816.07 rows=456 width=151) (actual time=0.125..0.127 rows=46.00 loops=1) + Sort Key: messages.created_at, messages.id + Sort Method: quicksort Memory: 35kB + Buffers: shared hit=10 + -> Index Scan using idx_messages_chat_id on messages (cost=0.42..799.78 rows=456 width=151) (actual time=0.075..0.086 rows=46.00 loops=1) + Index Cond: (chat_id = (InitPlan 1).col1) + Filter: (ROW(created_at, id) > ROW('2026-01-01 00:30:00+00'::timestamp with time zone, '00000000-0000-0000-0000-000000000000'::uuid)) + Rows Removed by Filter: 29 + Index Searches: 1 + Buffers: shared hit=10 + Planning Time: 0.250 ms + Execution Time: 0.166 ms +(19 rows) + +Time: 1.156 ms + + +B. (chat_id, created_at, id) +research=# DROP INDEX IF EXISTS idx_messages_chat_id; +DROP INDEX +Time: 3.644 ms +research=# CREATE INDEX idx_messages_chat_history ON messages (chat_id, created_at, id); +CREATE INDEX +Time: 69.022 ms +research=# ANALYZE messages; +ANALYZE +Time: 103.435 ms +research=# EXPLAIN (ANALYZE, BUFFERS) SELECT * FROM messages WHERE chat_id = (SELECT id FROM chats WHERE title = 'big') AND (created_at, id) > ('2026-01-15 00:00+00', '00000000-0000-0000-0000-000000000000') ORDER BY created_at, id LIMIT 50; + QUERY PLAN +--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + Limit (cost=4.99..93.65 rows=50 width=151) (actual time=0.055..0.069 rows=50.00 loops=1) + Buffers: shared hit=4 read=4 + InitPlan 1 + -> Seq Scan on chats (cost=0.00..4.58 rows=1 width=16) (actual time=0.009..0.019 rows=1.00 loops=1) + Filter: (title = 'big'::text) + Rows Removed by Filter: 205 + Buffers: shared hit=2 + -> Index Scan using idx_messages_chat_history on messages (cost=0.42..340.85 rows=192 width=151) (actual time=0.054..0.065 rows=50.00 loops=1) + Index Cond: ((chat_id = (InitPlan 1).col1) AND (ROW(created_at, id) > ROW('2026-01-15 00:00:00+00'::timestamp with time zone, '00000000-0000-0000-0000-000000000000'::uuid))) + Index Searches: 1 + Buffers: shared hit=4 read=4 + Planning: + Buffers: shared hit=21 read=1 + Planning Time: 0.333 ms + Execution Time: 0.092 ms +(15 rows) + +Time: 1.018 ms +research=# EXPLAIN (ANALYZE, BUFFERS) SELECT * FROM messages WHERE chat_id = (SELECT id FROM chats WHERE title = 'big') AND (created_at, id) > ('2026-01-15 00:00+00', '00000000-0000-0000-0000-000000000000') ORDER BY created_at, id LIMIT 50; + QUERY PLAN +--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + Limit (cost=4.99..93.65 rows=50 width=151) (actual time=0.033..0.045 rows=50.00 loops=1) + Buffers: shared hit=8 + InitPlan 1 + -> Seq Scan on chats (cost=0.00..4.58 rows=1 width=16) (actual time=0.011..0.020 rows=1.00 loops=1) + Filter: (title = 'big'::text) + Rows Removed by Filter: 205 + Buffers: shared hit=2 + -> Index Scan using idx_messages_chat_history on messages (cost=0.42..340.85 rows=192 width=151) (actual time=0.032..0.041 rows=50.00 loops=1) + Index Cond: ((chat_id = (InitPlan 1).col1) AND (ROW(created_at, id) > ROW('2026-01-15 00:00:00+00'::timestamp with time zone, '00000000-0000-0000-0000-000000000000'::uuid))) + Index Searches: 1 + Buffers: shared hit=8 + Planning Time: 0.106 ms + Execution Time: 0.061 ms +(13 rows) + +Time: 0.464 ms +research=# EXPLAIN (ANALYZE, BUFFERS) SELECT * FROM messages WHERE chat_id = (SELECT id FROM chats WHERE title = 'small-1') AND (created_at, id) > ('2026-01-01 00:30+00', '00000000-0000-0000-0000-000000000000') ORDER BY created_at, id LIMIT 50; + QUERY PLAN +--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + Limit (cost=4.99..88.31 rows=50 width=151) (actual time=0.139..0.152 rows=46.00 loops=1) + Buffers: shared hit=7 read=2 + InitPlan 1 + -> Seq Scan on chats (cost=0.00..4.58 rows=1 width=16) (actual time=0.015..0.026 rows=1.00 loops=1) + Filter: (title = 'small-1'::text) + Rows Removed by Filter: 205 + Buffers: shared hit=2 + -> Index Scan using idx_messages_chat_history on messages (cost=0.42..758.65 rows=455 width=151) (actual time=0.137..0.147 rows=46.00 loops=1) + Index Cond: ((chat_id = (InitPlan 1).col1) AND (ROW(created_at, id) > ROW('2026-01-01 00:30:00+00'::timestamp with time zone, '00000000-0000-0000-0000-000000000000'::uuid))) + Index Searches: 1 + Buffers: shared hit=7 read=2 + Planning Time: 0.130 ms + Execution Time: 0.174 ms +(13 rows) + +Time: 0.581 ms +research=# EXPLAIN (ANALYZE, BUFFERS) SELECT * FROM messages WHERE chat_id = (SELECT id FROM chats WHERE title = 'small-1') AND (created_at, id) > ('2026-01-01 00:30+00', '00000000-0000-0000-0000-000000000000') ORDER BY created_at, id LIMIT 50; + QUERY PLAN +--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + Limit (cost=4.99..88.31 rows=50 width=151) (actual time=0.064..0.073 rows=46.00 loops=1) + Buffers: shared hit=9 + InitPlan 1 + -> Seq Scan on chats (cost=0.00..4.58 rows=1 width=16) (actual time=0.030..0.039 rows=1.00 loops=1) + Filter: (title = 'small-1'::text) + Rows Removed by Filter: 205 + Buffers: shared hit=2 + -> Index Scan using idx_messages_chat_history on messages (cost=0.42..758.65 rows=455 width=151) (actual time=0.063..0.069 rows=46.00 loops=1) + Index Cond: ((chat_id = (InitPlan 1).col1) AND (ROW(created_at, id) > ROW('2026-01-01 00:30:00+00'::timestamp with time zone, '00000000-0000-0000-0000-000000000000'::uuid))) + Index Searches: 1 + Buffers: shared hit=9 + Planning Time: 0.208 ms + Execution Time: 0.100 ms +(13 rows) + +Time: 0.808 ms + +A. Only PK +research=# DROP INDEX IF EXISTS idx_messages_chat_history; +DROP INDEX +Time: 5.715 ms +research=# DROP INDEX IF EXISTS idx_messages_chat_id; +NOTICE: index "idx_messages_chat_id" does not exist, skipping +DROP INDEX +Time: 0.228 ms +research=# ANALYZE messages; +ANALYZE +Time: 102.311 ms +research=# EXPLAIN (ANALYZE, BUFFERS) SELECT * FROM messages WHERE chat_id = (SELECT id FROM chats WHERE title = 'big') AND (created_at, id) > ('2026-01-15 00:00+00', '00000000-0000-0000-0000-000000000000') ORDER BY created_at, id LIMIT 50; + QUERY PLAN +----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + Limit (cost=4022.99..4023.11 rows=50 width=150) (actual time=10.619..10.625 rows=50.00 loops=1) + Buffers: shared hit=2264 + InitPlan 1 + -> Seq Scan on chats (cost=0.00..4.58 rows=1 width=16) (actual time=0.007..0.019 rows=1.00 loops=1) + Filter: (title = 'big'::text) + Rows Removed by Filter: 205 + Buffers: shared hit=2 + -> Sort (cost=4018.41..4018.89 rows=193 width=150) (actual time=10.616..10.619 rows=50.00 loops=1) + Sort Key: messages.created_at, messages.id + Sort Method: top-N heapsort Memory: 36kB + Buffers: shared hit=2264 + -> Seq Scan on messages (cost=0.00..4012.00 rows=193 width=150) (actual time=1.644..8.293 rows=39841.00 loops=1) + Filter: ((chat_id = (InitPlan 1).col1) AND (ROW(created_at, id) > ROW('2026-01-15 00:00:00+00'::timestamp with time zone, '00000000-0000-0000-0000-000000000000'::uuid))) + Rows Removed by Filter: 60159 + Buffers: shared hit=2264 + Planning: + Buffers: shared hit=20 + Planning Time: 0.264 ms + Execution Time: 10.659 ms +(19 rows) + +Time: 11.410 ms +research=# EXPLAIN (ANALYZE, BUFFERS) SELECT * FROM messages WHERE chat_id = (SELECT id FROM chats WHERE title = 'big') AND (created_at, id) > ('2026-01-15 00:00+00', '00000000-0000-0000-0000-000000000000') ORDER BY created_at, id LIMIT 50; + QUERY PLAN +----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + Limit (cost=4022.99..4023.11 rows=50 width=150) (actual time=10.266..10.274 rows=50.00 loops=1) + Buffers: shared hit=2264 + InitPlan 1 + -> Seq Scan on chats (cost=0.00..4.58 rows=1 width=16) (actual time=0.006..0.016 rows=1.00 loops=1) + Filter: (title = 'big'::text) + Rows Removed by Filter: 205 + Buffers: shared hit=2 + -> Sort (cost=4018.41..4018.89 rows=193 width=150) (actual time=10.265..10.269 rows=50.00 loops=1) + Sort Key: messages.created_at, messages.id + Sort Method: top-N heapsort Memory: 36kB + Buffers: shared hit=2264 + -> Seq Scan on messages (cost=0.00..4012.00 rows=193 width=150) (actual time=1.597..8.150 rows=39841.00 loops=1) + Filter: ((chat_id = (InitPlan 1).col1) AND (ROW(created_at, id) > ROW('2026-01-15 00:00:00+00'::timestamp with time zone, '00000000-0000-0000-0000-000000000000'::uuid))) + Rows Removed by Filter: 60159 + Buffers: shared hit=2264 + Planning Time: 0.082 ms + Execution Time: 10.300 ms +(17 rows) + +Time: 11.458 ms +research=# EXPLAIN (ANALYZE, BUFFERS) SELECT * FROM messages WHERE chat_id = (SELECT id FROM chats WHERE title = 'small-1') AND (created_at, id) > ('2026-01-01 00:30+00', '00000000-0000-0000-0000-000000000000') ORDER BY created_at, id LIMIT 50; + QUERY PLAN +----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + Limit (cost=4031.69..4031.81 rows=50 width=150) (actual time=6.337..6.344 rows=46.00 loops=1) + Buffers: shared hit=2264 + InitPlan 1 + -> Seq Scan on chats (cost=0.00..4.58 rows=1 width=16) (actual time=0.007..0.019 rows=1.00 loops=1) + Filter: (title = 'small-1'::text) + Rows Removed by Filter: 205 + Buffers: shared hit=2 + -> Sort (cost=4027.11..4028.25 rows=455 width=150) (actual time=6.335..6.339 rows=46.00 loops=1) + Sort Key: messages.created_at, messages.id + Sort Method: quicksort Memory: 35kB + Buffers: shared hit=2264 + -> Seq Scan on messages (cost=0.00..4012.00 rows=455 width=150) (actual time=4.345..6.255 rows=46.00 loops=1) + Filter: ((chat_id = (InitPlan 1).col1) AND (ROW(created_at, id) > ROW('2026-01-01 00:30:00+00'::timestamp with time zone, '00000000-0000-0000-0000-000000000000'::uuid))) + Rows Removed by Filter: 99954 + Buffers: shared hit=2264 + Planning Time: 0.105 ms + Execution Time: 6.366 ms +(17 rows) + +Time: 6.763 ms +research=# EXPLAIN (ANALYZE, BUFFERS) SELECT * FROM messages WHERE chat_id = (SELECT id FROM chats WHERE title = 'small-1') AND (created_at, id) > ('2026-01-01 00:30+00', '00000000-0000-0000-0000-000000000000') ORDER BY created_at, id LIMIT 50; + QUERY PLAN +----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + Limit (cost=4031.69..4031.81 rows=50 width=150) (actual time=6.219..6.227 rows=46.00 loops=1) + Buffers: shared hit=2264 + InitPlan 1 + -> Seq Scan on chats (cost=0.00..4.58 rows=1 width=16) (actual time=0.009..0.021 rows=1.00 loops=1) + Filter: (title = 'small-1'::text) + Rows Removed by Filter: 205 + Buffers: shared hit=2 + -> Sort (cost=4027.11..4028.25 rows=455 width=150) (actual time=6.217..6.221 rows=46.00 loops=1) + Sort Key: messages.created_at, messages.id + Sort Method: quicksort Memory: 35kB + Buffers: shared hit=2264 + -> Seq Scan on messages (cost=0.00..4012.00 rows=455 width=150) (actual time=4.517..6.205 rows=46.00 loops=1) + Filter: ((chat_id = (InitPlan 1).col1) AND (ROW(created_at, id) > ROW('2026-01-01 00:30:00+00'::timestamp with time zone, '00000000-0000-0000-0000-000000000000'::uuid))) + Rows Removed by Filter: 99954 + Buffers: shared hit=2264 + Planning Time: 0.110 ms + Execution Time: 6.248 ms +(17 rows) + +Time: 6.727 ms diff --git a/evidence/track2-insert-cost.txt b/evidence/track2-insert-cost.txt new file mode 100644 index 00000000..175c5964 --- /dev/null +++ b/evidence/track2-insert-cost.txt @@ -0,0 +1,168 @@ +> docker compose exec postgres psql -U messenger -d postgres -c "CREATE DATABASE research;" +CREATE DATABASE +> docker compose run --rm --no-deps --entrypoint sh migrate -c 'URL=$(sed s,/messenger?,/research?, /run/secrets/database_url); goose -dir /migrations postgres $URL up' +Container mtusi2026lab2-migrate-run-37c6222942bf Creating +Container mtusi2026lab2-migrate-run-37c6222942bf Created +2026/10/07 19:30:06 OK 00001_init.sql (10.96ms) +2026/10/07 19:30:06 goose: successfully migrated database to version: 1 +> docker compose exec postgres psql -U messenger -d research +psql (18.6 (Debian 18.6-1.pgdg13+2)) +Type "help" for help. + +research=# INSERT INTO users (id, username, display_name, password_hash) VALUES (uuidv7(), 'research_user', 'Research User', 'x'); +INSERT 0 1 +research=# INSERT INTO chats (id, title) SELECT uuidv7(), 'big'; +INSERT 0 1 +research=# INSERT INTO chats (id, title) SELECT uuidv7(), 'mid-' || g FROM generate_series(1, 5) g; +INSERT 0 5 +research=# INSERT INTO chats (id, title) SELECT uuidv7(), 'small-' || g FROM generate_series(1, 200) g; +INSERT 0 200 +research=# CREATE TABLE messages_seed AS +SELECT uuidv7() AS id, + c.id AS chat_id, + (SELECT id FROM users WHERE username = 'research_user') AS sender_id, + 'message ' || n || ' ' || repeat(md5(random()::text), 1 + (n % 4)) AS text, + timestamptz '2026-01-01 00:00:00+00' + n * interval '1 minute' AS created_at +FROM chats c +CROSS JOIN LATERAL generate_series(1, CASE split_part(c.title, '-', 1) + WHEN 'big' THEN 60000 WHEN 'mid' THEN 5000 ELSE 75 END) AS n; +SELECT 100000 + +A. Only PK +research=# SELECT 'VARIANT A' AS variant; +DROP INDEX IF EXISTS idx_messages_chat_history; +DROP INDEX IF EXISTS idx_messages_chat_id; + +TRUNCATE messages; +INSERT INTO messages SELECT id, chat_id, sender_id, text, created_at FROM messages_seed; +TRUNCATE messages; +INSERT INTO messages SELECT id, chat_id, sender_id, text, created_at FROM messages_seed; +TRUNCATE messages; +INSERT INTO messages SELECT id, chat_id, sender_id, text, created_at FROM messages_seed; + +ANALYZE messages; +SELECT pg_size_pretty(pg_relation_size('messages')) AS table, indexrelid::regclass AS idx, pg_size_pretty(pg_relation_size(indexrelid)) AS size FROM pg_index WHERE indrelid = 'messages'::regclass; + variant +----------- + VARIANT A +(1 row) + +Time: 0.345 ms +DROP INDEX +Time: 5.736 ms +NOTICE: index "idx_messages_chat_id" does not exist, skipping +DROP INDEX +Time: 0.153 ms +TRUNCATE TABLE +Time: 3.614 ms +INSERT 0 100000 +Time: 989.859 ms +TRUNCATE TABLE +Time: 6.348 ms +INSERT 0 100000 +Time: 976.844 ms +TRUNCATE TABLE +Time: 6.268 ms +INSERT 0 100000 +Time: 977.896 ms +ANALYZE +Time: 103.989 ms + table | idx | size +-------+---------------+--------- + 18 MB | messages_pkey | 3104 kB +(1 row) + +Time: 0.765 ms + +B. (chat_id, created_at, id) +research=# SELECT 'VARIANT B' AS variant; +DROP INDEX IF EXISTS idx_messages_chat_id; +CREATE INDEX idx_messages_chat_history ON messages (chat_id, created_at, id); + +TRUNCATE messages; +INSERT INTO messages SELECT id, chat_id, sender_id, text, created_at FROM messages_seed; +TRUNCATE messages; +INSERT INTO messages SELECT id, chat_id, sender_id, text, created_at FROM messages_seed; +TRUNCATE messages; +INSERT INTO messages SELECT id, chat_id, sender_id, text, created_at FROM messages_seed; + +ANALYZE messages; +SELECT pg_size_pretty(pg_relation_size('messages')) AS table, indexrelid::regclass AS idx, pg_size_pretty(pg_relation_size(indexrelid)) AS size FROM pg_index WHERE indrelid = 'messages'::regclass; + variant +----------- + VARIANT B +(1 row) + +Time: 0.411 ms +NOTICE: index "idx_messages_chat_id" does not exist, skipping +DROP INDEX +Time: 0.144 ms +CREATE INDEX +Time: 165.646 ms +TRUNCATE TABLE +Time: 9.681 ms +INSERT 0 100000 +Time: 1655.348 ms (00:01.655) +TRUNCATE TABLE +Time: 6.620 ms +INSERT 0 100000 +Time: 1640.366 ms (00:01.640) +TRUNCATE TABLE +Time: 7.094 ms +INSERT 0 100000 +Time: 1156.808 ms (00:01.157) +ANALYZE +Time: 92.376 ms + table | idx | size +-------+---------------------------+--------- + 18 MB | messages_pkey | 3104 kB + 18 MB | idx_messages_chat_history | 5776 kB +(2 rows) + +Time: 0.560 ms + +C. (chat_id, id) +research=# SELECT 'VARIANT C' AS variant; +DROP INDEX IF EXISTS idx_messages_chat_history; +CREATE INDEX idx_messages_chat_id ON messages (chat_id, id); + +TRUNCATE messages; +INSERT INTO messages SELECT id, chat_id, sender_id, text, created_at FROM messages_seed; +TRUNCATE messages; +INSERT INTO messages SELECT id, chat_id, sender_id, text, created_at FROM messages_seed; +TRUNCATE messages; +INSERT INTO messages SELECT id, chat_id, sender_id, text, created_at FROM messages_seed; + +ANALYZE messages; +SELECT pg_size_pretty(pg_relation_size('messages')) AS table, indexrelid::regclass AS idx, pg_size_pretty(pg_relation_size(indexrelid)) AS size FROM pg_index WHERE indrelid = 'messages'::regclass; + variant +----------- + VARIANT C +(1 row) + +Time: 0.362 ms +DROP INDEX +Time: 4.459 ms +CREATE INDEX +Time: 61.503 ms +TRUNCATE TABLE +Time: 6.046 ms +INSERT 0 100000 +Time: 1222.658 ms (00:01.223) +TRUNCATE TABLE +Time: 6.482 ms +INSERT 0 100000 +Time: 1181.280 ms (00:01.181) +TRUNCATE TABLE +Time: 6.286 ms +INSERT 0 100000 +Time: 1185.066 ms (00:01.185) +ANALYZE +Time: 98.084 ms + table | idx | size +-------+----------------------+--------- + 18 MB | messages_pkey | 3104 kB + 18 MB | idx_messages_chat_id | 4880 kB +(2 rows) + +Time: 0.490 ms -- 2.54.0 From f86d79a584789c60484830dc02e227e9fadf99e2 Mon Sep 17 00:00:00 2001 From: kk10 Date: Thu, 8 Oct 2026 00:00:04 +0300 Subject: [PATCH 34/40] refactor: remove unused in-memory store --- internal/store/memory.go | 236 --------------------------------------- 1 file changed, 236 deletions(-) delete mode 100644 internal/store/memory.go diff --git a/internal/store/memory.go b/internal/store/memory.go deleted file mode 100644 index 8783c0ee..00000000 --- a/internal/store/memory.go +++ /dev/null @@ -1,236 +0,0 @@ -package store - -import ( - "errors" - "slices" - "sort" - "sync" - "time" - - "github.com/google/uuid" - - "mtusi2026-messenger/internal/model" -) - -var ( - ErrNotFound = errors.New("not found") - ErrConflict = errors.New("conflict") - ErrDuplicateMember = errors.New("duplicate member id") - ErrUnknownMember = errors.New("unknown member id") - ErrInvalidCursor = errors.New("invalid cursor") -) - -type Memory struct { - mu sync.RWMutex - - users map[uuid.UUID]model.User - usersByUsername map[string]uuid.UUID - chats map[uuid.UUID]model.Chat - messages map[uuid.UUID]model.Message - chatMessages map[uuid.UUID][]uuid.UUID -} - -func New() *Memory { - return &Memory{ - users: make(map[uuid.UUID]model.User), - usersByUsername: make(map[string]uuid.UUID), - chats: make(map[uuid.UUID]model.Chat), - messages: make(map[uuid.UUID]model.Message), - chatMessages: make(map[uuid.UUID][]uuid.UUID), - } -} - -func (m *Memory) CreateUser(username, displayName string) (model.User, error) { - m.mu.Lock() - defer m.mu.Unlock() - - if _, exists := m.usersByUsername[username]; exists { - return model.User{}, ErrConflict - } - - user := model.User{ - ID: uuid.New(), - Username: username, - DisplayName: displayName, - CreatedAt: time.Now().UTC(), - } - - m.users[user.ID] = user - m.usersByUsername[user.Username] = user.ID - - return user, nil -} - -func (m *Memory) GetUser(id uuid.UUID) (model.User, error) { - m.mu.RLock() - defer m.mu.RUnlock() - - user, exists := m.users[id] - if !exists { - return model.User{}, ErrNotFound - } - - return user, nil -} - -func (m *Memory) CreateChat(title string, memberIDs []uuid.UUID) (model.Chat, error) { - m.mu.Lock() - defer m.mu.Unlock() - - seen := make(map[uuid.UUID]struct{}, len(memberIDs)) - for _, id := range memberIDs { - if _, dup := seen[id]; dup { - return model.Chat{}, ErrDuplicateMember - } - seen[id] = struct{}{} - - if _, exists := m.users[id]; !exists { - return model.Chat{}, ErrUnknownMember - } - } - - chat := model.Chat{ - ID: uuid.New(), - Title: title, - MemberIDs: append([]uuid.UUID(nil), memberIDs...), - CreatedAt: time.Now().UTC(), - } - - m.chats[chat.ID] = chat - - return chat, nil -} - -func (m *Memory) GetChat(id uuid.UUID, userID uuid.UUID) (model.Chat, error) { - m.mu.RLock() - defer m.mu.RUnlock() - - chat, exists := m.chats[id] - if !exists || !slices.Contains(chat.MemberIDs, userID) { - return model.Chat{}, ErrNotFound - } - - chat.MemberIDs = append([]uuid.UUID(nil), chat.MemberIDs...) - - return chat, nil -} - -func (m *Memory) ListChats( - userID uuid.UUID, - afterCreatedAt *time.Time, - afterID *uuid.UUID, - limit int, -) ([]model.Chat, bool, error) { - m.mu.RLock() - defer m.mu.RUnlock() - - chats := make([]model.Chat, 0) - for _, c := range m.chats { - if slices.Contains(c.MemberIDs, userID) { - c.MemberIDs = append([]uuid.UUID(nil), c.MemberIDs...) - chats = append(chats, c) - } - } - - sort.Slice(chats, func(i, j int) bool { - if !chats[i].CreatedAt.Equal(chats[j].CreatedAt) { - return chats[i].CreatedAt.Before(chats[j].CreatedAt) - } - return chats[i].ID.String() < chats[j].ID.String() - }) - - start := 0 - if afterCreatedAt != nil && afterID != nil { - start = sort.Search(len(chats), func(i int) bool { - chat := chats[i] - - return chat.CreatedAt.After(*afterCreatedAt) || - (chat.CreatedAt.Equal(*afterCreatedAt) && - chat.ID.String() > afterID.String()) - }) - } - - end := start + limit - hasMore := end < len(chats) - if end > len(chats) { - end = len(chats) - } - - return chats[start:end], hasMore, nil -} - -func (m *Memory) CreateMessage( - chatID uuid.UUID, - senderID uuid.UUID, - text string, -) (model.Message, error) { - m.mu.Lock() - defer m.mu.Unlock() - - chat, exists := m.chats[chatID] - if !exists || !slices.Contains(chat.MemberIDs, senderID) { - return model.Message{}, ErrNotFound - } - - message := model.Message{ - ID: uuid.New(), - ChatID: chatID, - SenderID: senderID, - Text: text, - CreatedAt: time.Now().UTC(), - } - - m.messages[message.ID] = message - m.chatMessages[chatID] = append(m.chatMessages[chatID], message.ID) - - return message, nil -} - -func (m *Memory) ListMessages( - chatID uuid.UUID, - userID uuid.UUID, - afterCreatedAt *time.Time, - afterID *uuid.UUID, - limit int, -) ([]model.Message, bool, error) { - m.mu.RLock() - defer m.mu.RUnlock() - - chat, exists := m.chats[chatID] - if !exists || !slices.Contains(chat.MemberIDs, userID) { - return nil, false, ErrNotFound - } - - ids := m.chatMessages[chatID] - messages := make([]model.Message, 0, len(ids)) - - for _, id := range ids { - messages = append(messages, m.messages[id]) - } - - sort.Slice(messages, func(i, j int) bool { - if !messages[i].CreatedAt.Equal(messages[j].CreatedAt) { - return messages[i].CreatedAt.Before(messages[j].CreatedAt) - } - return messages[i].ID.String() < messages[j].ID.String() - }) - - start := 0 - if afterCreatedAt != nil && afterID != nil { - start = sort.Search(len(messages), func(i int) bool { - msg := messages[i] - - return msg.CreatedAt.After(*afterCreatedAt) || - (msg.CreatedAt.Equal(*afterCreatedAt) && - msg.ID.String() > afterID.String()) - }) - } - - end := start + limit - hasMore := end < len(messages) - if end > len(messages) { - end = len(messages) - } - - return messages[start:end], hasMore, nil -} -- 2.54.0 From 9ec1eae7b8a4d1295f92a8683c7ecba85df1c7ee Mon Sep 17 00:00:00 2001 From: kk10 Date: Thu, 8 Oct 2026 15:21:18 +0300 Subject: [PATCH 35/40] docs: write lab 2 report --- REPORT.md | 143 ++++++++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 129 insertions(+), 14 deletions(-) diff --git a/REPORT.md b/REPORT.md index e42f2b05..17d08f4d 100644 --- a/REPORT.md +++ b/REPORT.md @@ -1,37 +1,152 @@ # Отчёт — лабораторная 2 -- Автор, группа: TODO -- Целевая оценка; выбранный трек 5, если нужен: TODO +- Автор, группа: Каменски Лин, БПИ2301 +- Целевая оценка; выбранный трек 5, если нужен: 5; трек 2 - Commit/PR: TODO после публикации -- Использованные источники, библиотеки и помощь ИИ: TODO +- Использованные источники, библиотеки и помощь ИИ: материалы лабораторной; Go, chi, pgx v5, sqlc, goose, PostgreSQL 18.6, Redis 8.8.3; Claude, ChatGPT - для ускорения работы и оформления отчёта ## Запуск из чистого clone -TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных. +Требуются Go 1.26+ и Docker с Compose. Образы: PostgreSQL 18.6, Redis 8.8.3. + +Создать локальные secrets - файлы в `secrets/`, в каждый записать значение без лишних символов: +- `database_url.txt` - URL PostgreSQL для API; +- `cache_url.txt` - URL Redis; +- `postgres_password.txt` - пароль пользователя `messenger`; +- `test_database_url.txt` - URL БД для тестов. + +Пример (значения заменить своими): +```bash +mkdir -p secrets +printf '%s' 'CHANGE_ME' > secrets/postgres_password.txt +printf '%s' 'postgres://messenger:CHANGE_ME@postgres:5432/messenger?sslmode=disable' > secrets/database_url.txt +printf '%s' 'redis://redis:6379/0' > secrets/cache_url.txt +printf '%s' 'postgres://messenger:CHANGE_ME@127.0.0.1:5432/messenger?sslmode=disable' > secrets/test_database_url.txt +``` + +Скопировать шаблон переменных окружения: +```bash +cp .env.example .env +``` + +Сборка и запуск (сервис `migrate` применяет миграции goose автоматически): +```bash +docker compose up --build -d +``` + +Готовность API проверяется запросом к `/health/ready`; после этого API доступен на http://localhost:8080. + +Тесты: +```bash +make test +make test-persistence ACTION_SCRIPT=scripts/restart.sh +make contract-go +make race-go +make failure-go +``` + +Безопасная остановка (данные в volume `pgdata` сохраняются): +```bash +docker compose down +``` + +Намеренное удаление учебных данных: +```bash +docker compose down -v +``` ## Архитектура и решения -TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab1, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации. +Процессы/хранилища: `api` (Go), `postgres`, `redis`, одноразовый `migrate` (goose). Источник истины - PostgreSQL. Redis хранит только кэш сессий: TTL записи = min(60 с, `SESSION_TTL_SECONDS`); при logout запись удаляется сначала из PostgreSQL, затем из Redis. При недоступности Redis API обходит кэш и читает сессию из PostgreSQL; при недоступности PostgreSQL API отвечает `503`. Создание чата выполняется в одной транзакции (откат проверяется `TestCreateChatRollback`). + +Пароли хешируются bcrypt; перед этим пароль проходит через SHA-256, чтобы обойти ограничение bcrypt в 72 байта. + +Из lab1 перенесены слои `handler` (HTTP) и `service` (бизнес-логика). Хранилище в памяти (`store`) заменено кодом доступа к PostgreSQL (sqlc, pgxpool) и удалено; `X-User-Id` заменён на Bearer-сессии. + +Переменные `.env.example`: `APP_HOST`, `APP_PORT` - адрес и порт API; `MAX_INFLIGHT_REQUESTS` - ограничитель запросов из lab1 (0 - выключен); `SESSION_TTL_SECONDS` - срок жизни сессии; `LOG_LEVEL` - уровень логов; `DATABASE_URL_FILE`, `CACHE_URL_FILE` - пути к secrets с URL PostgreSQL и Redis. ## Доказательства критериев | Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства | | --- | --- | --- | --- | -| Публичный smoke | make test | TODO | TODO | -| Остальные пункты уровня 3 | TODO | TODO | TODO | -| Все пункты уровня 4, если заявлен | TODO | TODO | TODO | -| Выбранный трек 5, если заявлен | TODO | TODO | TODO | - -TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены. +| Публичный smoke | `make test` | `PASS` | `evidence/make-test.txt` | +| Уровень 3 | +| Сохранность данных и сессии после рестарта | `make test-persistence ACTION_SCRIPT=scripts/restart.sh`; скрипт выполняет `docker compose restart postgres redis api`, volumes сохраняются | `PASS`: данные и существующая сессия сохранены | `evidence/make-test-persistence.txt` | +| Повторный запуск миграций без дублирования данных | повторный запуск сервиса `migrate` | `no migrations to run` | `evidence/migrate-repeat.txt` | +| Уникальность username | `make contract-go` (`TestDuplicateUsername`) | `PASS` | `evidence/make-contract-go.txt` | +| Срок жизни сессии | `make failure-go` (`TestSessionExpiry`) | `PASS` | `evidence/make-failure-go.txt` | +| Уровень 4 | +| Гонка регистрации одного username | `make race-go` (`TestConcurrentRegistration`) | `PASS` | `evidence/make-race-go.txt` | +| Rollback составной операции | `make contract-go` (`TestCreateChatRollback`) | `PASS` | `evidence/make-contract-go.txt` | +| Индекс истории, пагинация без полного scan | `EXPLAIN (ANALYZE, BUFFERS)`, 20 000 сообщений | Seq Scan + Sort 5,2 мс, 507 буферов → Index Scan 0,03 мс, 4 буфера | `evidence/explain-history.txt` | +| Logout, неверный пароль | `make contract-go` (`TestLogout`, `TestLoginWrongPassword`) | `PASS` | `evidence/make-contract-go.txt` | +| Недоступность Redis и БД | `make failure-go` (`TestRedisDown`, `TestDatabaseDown`) | `PASS` | `evidence/make-failure-go.txt` | +| Уровень 5 | +| Трек 2: стоимость записи | вставка 100 000 сообщений (чаты 60 000 / 5×5 000 / 200×75) для вариантов A, B, C | B и C медленнее A; дополнительные индексы занимают 4880–5776 КБ | `evidence/track2-insert-cost.txt` | +| Трек 2: план запроса | `EXPLAIN (ANALYZE, BUFFERS)` для A, B, C на чатах `big` и `small-1` | A: Seq Scan, 2264 буфера; B: Index Scan, 8-9 буферов; C: Index Scan + Sort, 1730 буферов на `big` | `evidence/track2-explain.txt` | +| Трек 2: backup → restore | `pg_dump -Fc` → `pg_restore` в `research_restore` | `count` = 100 000, хеш таблицы и хеш выбранной страницы совпали | `evidence/track2-backup-restore.txt` | ## Эксперименты и отказы -TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения. +Для сравнения использовались три варианта индексации таблицы `messages`: +- A - только первичный ключ `(PK)`, без дополнительного индекса; +- B - индекс `(chat_id, created_at, id)`; +- C - индекс `(chat_id, id)`. + +Для каждого варианта выполнялись эксперименты с записью и чтением. Дополнительно проверялись резервное копирование и восстановление данных. + +**Гипотезы**: +1. Индекс `(chat_id, created_at, id)` (B) позволит получить страницу из 50 сообщений за сопоставимое время и с сопоставимым числом обращений к данным в малом и большом чате; +2. Индекс `(chat_id, id)` (C) хуже индекса `(chat_id, created_at, id)` (B), поскольку может потребоваться дополнительная сортировка по `created_at, id`; +3. Каждый индекс замедляет вставку и занимает место. + +**Методика**: + +Эксперимент проводился в Docker Desktop с доступными 12 ядрами процессора и примерно 7,7 ГБ оперативной памяти. PostgreSQL 18.6, отдельная БД `research`, 100 000 сообщений: 1 чат на 60 000, 5 по 5 000, 200 по 75. Данные синтетические, сгенерированы один раз во вспомогательной таблице `messages_seed`. + +Запись: для каждого варианта выполнено по 3 измерения времени вставки 100 000 одинаковых строк; перед каждым измерением таблица очищалась через TRUNCATE. Для вариантов B и C индекс создавался до начала измерений. + +Чтение: для каждого варианта выполнено чтение страницы из 50 сообщений после курсора из середины истории, `EXPLAIN (ANALYZE, BUFFERS)`, чаты `big` и `small-1`, 2 измерения (каждый запрос выполнялся дважды, в таблице приведено второе измерение, когда данные уже в кэше). + +Backup сделан при индексе B. Проверка: `count(*)`, `md5` по всем строкам таблицы и `md5` по странице из 50 сообщений чата `big` (тот же курсор, что в `EXPLAIN`); значения хэша в `research` и `research_restore` совпали. + +Выполненные команды видны в выводе сессий psql в `evidence/track2-*.txt`. + +**Результаты экспериментов**: + +Запись: + +| Вариант | Измерения, мс | Размер PK/индексов, КБ | +| --- | --- | --- | +| A | 990, 977, 978 | 3104 | +| B | 1655, 1640, 1157 | 8880 | +| C | 1223, 1181, 1185 | 7984 | + +Чтение: + +| Вариант | `big` (60 000) | `small-1` (75) | +| --- | --- | --- | +| A | 2264 / 10,3 мс | 2264 / 6,2 мс | +| B | 8 / 0,06 мс | 9 / 0,10 мс | +| C | 1730 / 13,6 мс | 10 / 0,17 мс | | Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных | | --- | --- | --- | --- | -| TODO | TODO | TODO | TODO | +| Вставка 100 000 сообщений без индекса (A) | минимальная стоимость записи | 977–990 мс | - | +| Вставка 100 000 сообщений с индексом `(chat_id, created_at, id)` (B) | вставка медленнее | 1157–1655 мс; индекс 5776 КБ | - | +| Вставка 100 000 сообщений с индексом `(chat_id, id)` (C) | вставка медленнее | 1181–1223 мс; индекс 4880 КБ | - | +| Запрос страницы без индекса (A) | стоимость зависит от размера таблицы | `Seq Scan`, 2264 буфера | - | +| Запрос страницы с индексом `(chat_id, created_at, id)` (B) | стоимость слабо зависит от размера чата | `Index Scan`, 8–9 буферов, без `Sort` | - | +| Запрос страницы с индексом `(chat_id, id)` (C) | хуже B на большом чате | `Index Scan` + `Sort`, 1730 буферов на `big` | - | +| `pg_dump -Fc` → `pg_restore` | полное восстановление данных | 4,1 МБ; backup 0,69 с; restore 0,54 с; хэши совпали | 0,54 с; потеря - изменения после последнего backup | + +**Вывод**: Гипотеза 1 подтверждена: с индексом B страница читается за 8-9 буферов и 0,06-0,10 мс и в большом, и в малом чате. Гипотеза 2 подтверждена: на большом чате с индексом C читается 1730 буферов за 13,6 мс против 8 буферов и 0,06 мс с индексом B, потому что условие курсора не входит в индекс и нужна сортировка. Гипотеза 3 подтверждена: оба индекса замедляют вставку (977-990 мс без индекса, 1157-1655 мс с B, 1181-1223 мс с C) и занимают место (дополнительно 5776 КБ у B и 4880 КБ у C). Backup и restore восстановили 100 000 сообщений без потери проверенных данных; для истории сообщений выбран индекс B. ## Ограничения и следующие шаги -TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза. +- Сервер и volume общие для `messenger`, `research` и `research_restore`: эксперимент подтверждает корректность дампа, но не сохранность данных при отказе диска, так как копия лежит на том же носителе. +- Данные синтетические; размеры индексов и степень сжатия дампа на реальных данных будут другими. +- Один курсор из середины истории; каждый запрос выполнялся дважды, в результатах приведён второй прогон при заполненном кэше. +- Время backup и restore включает накладные расходы `docker compose exec`; параллельной записи во время backup не было, консистентность дампа под нагрузкой не проверялась. +- Redis в backup не входит: это кэш, источник истины PostgreSQL. +- После logout при недоступном Redis токен может приниматься до истечения кэш-TTL (до 60 с). -- 2.54.0 From af88065a1c96e43c3a24e7a8f864891807efd100 Mon Sep 17 00:00:00 2001 From: kk10 Date: Thu, 8 Oct 2026 15:44:14 +0300 Subject: [PATCH 36/40] docs: add PR link to report --- REPORT.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/REPORT.md b/REPORT.md index 17d08f4d..f563e4a3 100644 --- a/REPORT.md +++ b/REPORT.md @@ -2,7 +2,7 @@ - Автор, группа: Каменски Лин, БПИ2301 - Целевая оценка; выбранный трек 5, если нужен: 5; трек 2 -- Commit/PR: TODO после публикации +- Commit/PR: [Pull Request 20](https://gitea.privcloud.tech/mtusi2026/mtusi2026lab2/pulls/20) - Использованные источники, библиотеки и помощь ИИ: материалы лабораторной; Go, chi, pgx v5, sqlc, goose, PostgreSQL 18.6, Redis 8.8.3; Claude, ChatGPT - для ускорения работы и оформления отчёта ## Запуск из чистого clone -- 2.54.0 From d25054843caafc63ffb4a82abb78fb31c1d9129f Mon Sep 17 00:00:00 2001 From: kk10 Date: Sat, 10 Oct 2026 10:38:55 +0300 Subject: [PATCH 37/40] fix(auth): cap session cache TTL by remaining session lifetime --- db/queries/sessions.sql | 4 ++-- internal/db/sessions.sql.go | 19 ++++++++++++------- internal/service/auth.go | 24 ++++++++++-------------- 3 files changed, 24 insertions(+), 23 deletions(-) diff --git a/db/queries/sessions.sql b/db/queries/sessions.sql index 4f1decde..065907f2 100644 --- a/db/queries/sessions.sql +++ b/db/queries/sessions.sql @@ -9,8 +9,8 @@ INSERT INTO sessions ( sqlc.arg(expires_at) ); --- name: GetSessionUserID :one -SELECT user_id FROM sessions +-- name: GetActiveSession :one +SELECT user_id, expires_at FROM sessions WHERE token_hash = sqlc.arg(token_hash) AND expires_at > now(); diff --git a/internal/db/sessions.sql.go b/internal/db/sessions.sql.go index 3d2e9de2..fa6abddb 100644 --- a/internal/db/sessions.sql.go +++ b/internal/db/sessions.sql.go @@ -62,15 +62,20 @@ func (q *Queries) DeleteSession(ctx context.Context, tokenHash string) (int64, e return result.RowsAffected(), nil } -const getSessionUserID = `-- name: GetSessionUserID :one -SELECT user_id FROM sessions +const getActiveSession = `-- name: GetActiveSession :one +SELECT user_id, expires_at FROM sessions WHERE token_hash = $1 AND expires_at > now() ` -func (q *Queries) GetSessionUserID(ctx context.Context, tokenHash string) (uuid.UUID, error) { - row := q.db.QueryRow(ctx, getSessionUserID, tokenHash) - var user_id uuid.UUID - err := row.Scan(&user_id) - return user_id, err +type GetActiveSessionRow struct { + UserID uuid.UUID + ExpiresAt time.Time +} + +func (q *Queries) GetActiveSession(ctx context.Context, tokenHash string) (GetActiveSessionRow, error) { + row := q.db.QueryRow(ctx, getActiveSession, tokenHash) + var i GetActiveSessionRow + err := row.Scan(&i.UserID, &i.ExpiresAt) + return i, err } diff --git a/internal/service/auth.go b/internal/service/auth.go index e15cc649..97eb5bef 100644 --- a/internal/service/auth.go +++ b/internal/service/auth.go @@ -26,7 +26,7 @@ var ( type authQueries interface { CreateSession(ctx context.Context, arg db.CreateSessionParams) error DeleteSession(ctx context.Context, tokenHash string) (int64, error) - GetSessionUserID(ctx context.Context, tokenHash string) (uuid.UUID, error) + GetActiveSession(ctx context.Context, tokenHash string) (db.GetActiveSessionRow, error) GetUserByUsername(ctx context.Context, username string) (db.User, error) } @@ -107,7 +107,7 @@ func (s *AuthService) Authenticate(ctx context.Context, token string) (uuid.UUID s.log.Warn("session cache get failed, falling back to database", "error", err) } - userID, err := s.q.GetSessionUserID(ctx, tokenHash) + row, err := s.q.GetActiveSession(ctx, tokenHash) if postgres.IsNotFound(err) { return uuid.Nil, ErrUnauthorized } @@ -115,13 +115,16 @@ func (s *AuthService) Authenticate(ctx context.Context, token string) (uuid.UUID return uuid.Nil, err } - cctx, cancel = context.WithTimeout(ctx, cacheOpTimeout) - if err := s.cache.Set(cctx, key, userID.String(), s.cacheTTL()).Err(); err != nil { - s.log.Warn("session cache set failed", "error", err) + ttl := min(time.Until(row.ExpiresAt), sessionCacheTTL) + if ttl > 0 { + cctx, cancel = context.WithTimeout(ctx, cacheOpTimeout) + if err := s.cache.Set(cctx, key, row.UserID.String(), ttl).Err(); err != nil { + s.log.Warn("session cache set failed", "error", err) + } + cancel() } - cancel() - return userID, nil + return row.UserID, nil } func (s *AuthService) Logout(ctx context.Context, token string) error { @@ -147,10 +150,3 @@ func (s *AuthService) Logout(ctx context.Context, token string) error { func cacheKey(tokenHash string) string { return "session:" + tokenHash } - -func (s *AuthService) cacheTTL() time.Duration { - if s.sessionTTL < sessionCacheTTL { - return s.sessionTTL - } - return sessionCacheTTL -} -- 2.54.0 From a288193cda769772dca472642e750e777279b30c Mon Sep 17 00:00:00 2001 From: kk10 Date: Sat, 10 Oct 2026 10:41:58 +0300 Subject: [PATCH 38/40] fix(httpx): reject request bodies with trailing data after JSON --- internal/httpx/request.go | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/internal/httpx/request.go b/internal/httpx/request.go index 7a376e40..58f32b82 100644 --- a/internal/httpx/request.go +++ b/internal/httpx/request.go @@ -2,6 +2,8 @@ package httpx import ( "encoding/json" + "errors" + "io" "mime" "net/http" @@ -25,5 +27,10 @@ func DecodeJSONBody(w http.ResponseWriter, r *http.Request, requestID string, ds return false } + if err := decoder.Decode(&struct{}{}); !errors.Is(err, io.EOF) { + WriteError(w, http.StatusBadRequest, dto.ErrorCodeInvalidRequest, "invalid request body", requestID) + return false + } + return true } -- 2.54.0 From c8470beeeebd3d8bef9be4a3c403c8b5279b6bc3 Mon Sep 17 00:00:00 2001 From: kk10 Date: Sat, 10 Oct 2026 10:51:50 +0300 Subject: [PATCH 39/40] perf(pagination): split list queries into first-page and after-cursor variants --- db/queries/chats.sql | 25 ++++++++---- db/queries/messages.sql | 17 ++++---- internal/db/chats.sql.go | 79 ++++++++++++++++++++++++++++++------- internal/db/messages.sql.go | 59 +++++++++++++++++++++------ internal/service/chat.go | 79 +++++++++++++++++++++---------------- internal/service/message.go | 33 ++++++++-------- 6 files changed, 202 insertions(+), 90 deletions(-) diff --git a/db/queries/chats.sql b/db/queries/chats.sql index 5609c446..80d2ba3e 100644 --- a/db/queries/chats.sql +++ b/db/queries/chats.sql @@ -40,7 +40,7 @@ WHERE c.id = sqlc.arg(id) AND m.user_id = sqlc.arg(user_id) ); --- name: ListChats :many +-- name: ListChatsFirstPage :many SELECT c.*, ARRAY( @@ -51,12 +51,23 @@ SELECT FROM chats c JOIN chat_members m ON m.chat_id = c.id WHERE m.user_id = sqlc.arg(user_id) - AND ( - sqlc.narg(after_created_at)::timestamptz IS NULL - OR (c.created_at, c.id) > ( - sqlc.narg(after_created_at)::timestamptz, - sqlc.narg(after_id)::uuid - ) +ORDER BY c.created_at, c.id +LIMIT sqlc.arg(lim); + +-- name: ListChatsAfter :many +SELECT + c.*, + ARRAY( + SELECT cm.user_id FROM chat_members cm + WHERE cm.chat_id = c.id + ORDER BY cm.user_id + )::uuid[] AS member_ids +FROM chats c +JOIN chat_members m ON m.chat_id = c.id +WHERE m.user_id = sqlc.arg(user_id) + AND (c.created_at, c.id) > ( + sqlc.arg(after_created_at)::timestamptz, + sqlc.arg(after_id)::uuid ) ORDER BY c.created_at, c.id LIMIT sqlc.arg(lim); diff --git a/db/queries/messages.sql b/db/queries/messages.sql index adb03546..69635c4f 100644 --- a/db/queries/messages.sql +++ b/db/queries/messages.sql @@ -17,15 +17,18 @@ WHERE EXISTS ( ) RETURNING *; --- name: ListMessages :many +-- name: ListMessagesFirstPage :many SELECT * FROM messages WHERE chat_id = sqlc.arg(chat_id) - AND ( - sqlc.narg(after_created_at)::timestamptz IS NULL - OR (created_at, id) > ( - sqlc.narg(after_created_at)::timestamptz, - sqlc.narg(after_id)::uuid - ) +ORDER BY created_at, id +LIMIT sqlc.arg(lim); + +-- name: ListMessagesAfter :many +SELECT * FROM messages +WHERE chat_id = sqlc.arg(chat_id) + AND (created_at, id) > ( + sqlc.arg(after_created_at)::timestamptz, + sqlc.arg(after_id)::uuid ) ORDER BY created_at, id LIMIT sqlc.arg(lim); diff --git a/internal/db/chats.sql.go b/internal/db/chats.sql.go index cf3dc388..c061eafb 100644 --- a/internal/db/chats.sql.go +++ b/internal/db/chats.sql.go @@ -116,7 +116,7 @@ func (q *Queries) IsChatMember(ctx context.Context, arg IsChatMemberParams) (boo return exists, err } -const listChats = `-- name: ListChats :many +const listChatsAfter = `-- name: ListChatsAfter :many SELECT c.id, c.title, c.created_at, ARRAY( @@ -127,33 +127,30 @@ SELECT FROM chats c JOIN chat_members m ON m.chat_id = c.id WHERE m.user_id = $1 - AND ( - $2::timestamptz IS NULL - OR (c.created_at, c.id) > ( - $2::timestamptz, - $3::uuid - ) + AND (c.created_at, c.id) > ( + $2::timestamptz, + $3::uuid ) ORDER BY c.created_at, c.id LIMIT $4 ` -type ListChatsParams struct { +type ListChatsAfterParams struct { UserID uuid.UUID - AfterCreatedAt *time.Time - AfterID *uuid.UUID + AfterCreatedAt time.Time + AfterID uuid.UUID Lim int32 } -type ListChatsRow struct { +type ListChatsAfterRow struct { ID uuid.UUID Title string CreatedAt time.Time MemberIds []uuid.UUID } -func (q *Queries) ListChats(ctx context.Context, arg ListChatsParams) ([]ListChatsRow, error) { - rows, err := q.db.Query(ctx, listChats, +func (q *Queries) ListChatsAfter(ctx context.Context, arg ListChatsAfterParams) ([]ListChatsAfterRow, error) { + rows, err := q.db.Query(ctx, listChatsAfter, arg.UserID, arg.AfterCreatedAt, arg.AfterID, @@ -163,9 +160,61 @@ func (q *Queries) ListChats(ctx context.Context, arg ListChatsParams) ([]ListCha return nil, err } defer rows.Close() - items := []ListChatsRow{} + items := []ListChatsAfterRow{} for rows.Next() { - var i ListChatsRow + var i ListChatsAfterRow + if err := rows.Scan( + &i.ID, + &i.Title, + &i.CreatedAt, + &i.MemberIds, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const listChatsFirstPage = `-- name: ListChatsFirstPage :many +SELECT + c.id, c.title, c.created_at, + ARRAY( + SELECT cm.user_id FROM chat_members cm + WHERE cm.chat_id = c.id + ORDER BY cm.user_id + )::uuid[] AS member_ids +FROM chats c +JOIN chat_members m ON m.chat_id = c.id +WHERE m.user_id = $1 +ORDER BY c.created_at, c.id +LIMIT $2 +` + +type ListChatsFirstPageParams struct { + UserID uuid.UUID + Lim int32 +} + +type ListChatsFirstPageRow struct { + ID uuid.UUID + Title string + CreatedAt time.Time + MemberIds []uuid.UUID +} + +func (q *Queries) ListChatsFirstPage(ctx context.Context, arg ListChatsFirstPageParams) ([]ListChatsFirstPageRow, error) { + rows, err := q.db.Query(ctx, listChatsFirstPage, arg.UserID, arg.Lim) + if err != nil { + return nil, err + } + defer rows.Close() + items := []ListChatsFirstPageRow{} + for rows.Next() { + var i ListChatsFirstPageRow if err := rows.Scan( &i.ID, &i.Title, diff --git a/internal/db/messages.sql.go b/internal/db/messages.sql.go index babd80ad..c599fb09 100644 --- a/internal/db/messages.sql.go +++ b/internal/db/messages.sql.go @@ -57,29 +57,26 @@ func (q *Queries) CreateMessage(ctx context.Context, arg CreateMessageParams) (M return i, err } -const listMessages = `-- name: ListMessages :many +const listMessagesAfter = `-- name: ListMessagesAfter :many SELECT id, chat_id, sender_id, text, created_at FROM messages WHERE chat_id = $1 - AND ( - $2::timestamptz IS NULL - OR (created_at, id) > ( - $2::timestamptz, - $3::uuid - ) + AND (created_at, id) > ( + $2::timestamptz, + $3::uuid ) ORDER BY created_at, id LIMIT $4 ` -type ListMessagesParams struct { +type ListMessagesAfterParams struct { ChatID uuid.UUID - AfterCreatedAt *time.Time - AfterID *uuid.UUID + AfterCreatedAt time.Time + AfterID uuid.UUID Lim int32 } -func (q *Queries) ListMessages(ctx context.Context, arg ListMessagesParams) ([]Message, error) { - rows, err := q.db.Query(ctx, listMessages, +func (q *Queries) ListMessagesAfter(ctx context.Context, arg ListMessagesAfterParams) ([]Message, error) { + rows, err := q.db.Query(ctx, listMessagesAfter, arg.ChatID, arg.AfterCreatedAt, arg.AfterID, @@ -108,3 +105,41 @@ func (q *Queries) ListMessages(ctx context.Context, arg ListMessagesParams) ([]M } return items, nil } + +const listMessagesFirstPage = `-- name: ListMessagesFirstPage :many +SELECT id, chat_id, sender_id, text, created_at FROM messages +WHERE chat_id = $1 +ORDER BY created_at, id +LIMIT $2 +` + +type ListMessagesFirstPageParams struct { + ChatID uuid.UUID + Lim int32 +} + +func (q *Queries) ListMessagesFirstPage(ctx context.Context, arg ListMessagesFirstPageParams) ([]Message, error) { + rows, err := q.db.Query(ctx, listMessagesFirstPage, arg.ChatID, arg.Lim) + if err != nil { + return nil, err + } + defer rows.Close() + items := []Message{} + for rows.Next() { + var i Message + if err := rows.Scan( + &i.ID, + &i.ChatID, + &i.SenderID, + &i.Text, + &i.CreatedAt, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} diff --git a/internal/service/chat.go b/internal/service/chat.go index d17fd976..d1ada3e6 100644 --- a/internal/service/chat.go +++ b/internal/service/chat.go @@ -5,7 +5,6 @@ import ( "context" "errors" "slices" - "time" "github.com/google/uuid" "github.com/jackc/pgx/v5" @@ -27,7 +26,8 @@ type chatQueries interface { AddChatMembers(ctx context.Context, arg db.AddChatMembersParams) error CreateChat(ctx context.Context, arg db.CreateChatParams) (db.Chat, error) GetChat(ctx context.Context, arg db.GetChatParams) (db.GetChatRow, error) - ListChats(ctx context.Context, arg db.ListChatsParams) ([]db.ListChatsRow, error) + ListChatsAfter(ctx context.Context, arg db.ListChatsAfterParams) ([]db.ListChatsAfterRow, error) + ListChatsFirstPage(ctx context.Context, arg db.ListChatsFirstPageParams) ([]db.ListChatsFirstPageRow, error) } type txBeginner interface { @@ -142,48 +142,61 @@ func (s *ChatService) List( limit int, cursor *string, ) ([]model.Chat, *string, error) { - var afterCreatedAt *time.Time - var afterID *uuid.UUID + var chats []model.Chat - if cursor != nil { - decoded, err := decodeCursor(*cursor, uuid.Nil) + if cursor == nil { + rows, err := s.q.ListChatsFirstPage(ctx, db.ListChatsFirstPageParams{ + UserID: userID, + Lim: int32(limit + 1), + }) if err != nil { + return nil, nil, err + } + + chats = make([]model.Chat, 0, len(rows)) + for _, r := range rows { + chats = append(chats, model.Chat{ + ID: r.ID, + Title: r.Title, + CreatedAt: r.CreatedAt, + MemberIDs: r.MemberIds, + }) + } + } else { + decoded, derr := decodeCursor(*cursor, uuid.Nil) + if derr != nil { return nil, nil, ErrInvalidCursor } - afterCreatedAt = &decoded.CreatedAt - afterID = &decoded.ID - } - - rows, err := s.q.ListChats(ctx, db.ListChatsParams{ - UserID: userID, - AfterCreatedAt: afterCreatedAt, - AfterID: afterID, - Lim: int32(limit + 1), - }) - if err != nil { - return nil, nil, err - } - - hasMore := len(rows) > limit - if hasMore { - rows = rows[:limit] - } - - chats := make([]model.Chat, 0, len(rows)) - for _, r := range rows { - chats = append(chats, model.Chat{ - ID: r.ID, - Title: r.Title, - CreatedAt: r.CreatedAt, - MemberIDs: r.MemberIds, + rows, err := s.q.ListChatsAfter(ctx, db.ListChatsAfterParams{ + UserID: userID, + AfterCreatedAt: decoded.CreatedAt, + AfterID: decoded.ID, + Lim: int32(limit + 1), }) + if err != nil { + return nil, nil, err + } + + chats = make([]model.Chat, 0, len(rows)) + for _, r := range rows { + chats = append(chats, model.Chat{ + ID: r.ID, + Title: r.Title, + CreatedAt: r.CreatedAt, + MemberIDs: r.MemberIds, + }) + } + } + + hasMore := len(chats) > limit + if hasMore { + chats = chats[:limit] } var next *string if hasMore { last := chats[len(chats)-1] - c := encodeCursor(Cursor{ CreatedAt: last.CreatedAt, ID: last.ID, diff --git a/internal/service/message.go b/internal/service/message.go index 78667489..4c3ef6e7 100644 --- a/internal/service/message.go +++ b/internal/service/message.go @@ -3,7 +3,6 @@ package service import ( "context" "errors" - "time" "github.com/google/uuid" @@ -17,7 +16,8 @@ var ErrMessageChatNotFound = errors.New("chat not found") type messageQueries interface { CreateMessage(ctx context.Context, arg db.CreateMessageParams) (db.Message, error) IsChatMember(ctx context.Context, arg db.IsChatMemberParams) (bool, error) - ListMessages(ctx context.Context, arg db.ListMessagesParams) ([]db.Message, error) + ListMessagesAfter(ctx context.Context, arg db.ListMessagesAfterParams) ([]db.Message, error) + ListMessagesFirstPage(ctx context.Context, arg db.ListMessagesFirstPageParams) ([]db.Message, error) } type MessageService struct { @@ -79,25 +79,26 @@ func (s *MessageService) List( return nil, nil, ErrMessageChatNotFound } - var afterCreatedAt *time.Time - var afterID *uuid.UUID + var rows []db.Message - if cursor != nil { - decoded, err := decodeCursor(*cursor, chatID) - if err != nil { + if cursor == nil { + rows, err = s.q.ListMessagesFirstPage(ctx, db.ListMessagesFirstPageParams{ + ChatID: chatID, + Lim: int32(limit + 1), + }) + } else { + decoded, derr := decodeCursor(*cursor, chatID) + if derr != nil { return nil, nil, ErrInvalidCursor } - afterCreatedAt = &decoded.CreatedAt - afterID = &decoded.ID + rows, err = s.q.ListMessagesAfter(ctx, db.ListMessagesAfterParams{ + ChatID: chatID, + AfterCreatedAt: decoded.CreatedAt, + AfterID: decoded.ID, + Lim: int32(limit + 1), + }) } - - rows, err := s.q.ListMessages(ctx, db.ListMessagesParams{ - ChatID: chatID, - AfterCreatedAt: afterCreatedAt, - AfterID: afterID, - Lim: int32(limit + 1), - }) if err != nil { return nil, nil, err } -- 2.54.0 From 15492d7894d5fcc31bfa96c182a9c7da56a1d8d4 Mon Sep 17 00:00:00 2001 From: kk10 Date: Sat, 10 Oct 2026 11:02:29 +0300 Subject: [PATCH 40/40] docs(report): update session cache TTL description --- REPORT.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/REPORT.md b/REPORT.md index f563e4a3..9796e2ce 100644 --- a/REPORT.md +++ b/REPORT.md @@ -57,7 +57,7 @@ docker compose down -v ## Архитектура и решения -Процессы/хранилища: `api` (Go), `postgres`, `redis`, одноразовый `migrate` (goose). Источник истины - PostgreSQL. Redis хранит только кэш сессий: TTL записи = min(60 с, `SESSION_TTL_SECONDS`); при logout запись удаляется сначала из PostgreSQL, затем из Redis. При недоступности Redis API обходит кэш и читает сессию из PostgreSQL; при недоступности PostgreSQL API отвечает `503`. Создание чата выполняется в одной транзакции (откат проверяется `TestCreateChatRollback`). +Процессы/хранилища: `api` (Go), `postgres`, `redis`, одноразовый `migrate` (goose). Источник истины - PostgreSQL. Redis хранит только кэш сессий: TTL записи = min(60 с, оставшийся срок сессии до `expires_at`); при logout запись удаляется сначала из PostgreSQL, затем из Redis. При недоступности Redis API обходит кэш и читает сессию из PostgreSQL; при недоступности PostgreSQL API отвечает `503`. Создание чата выполняется в одной транзакции (откат проверяется `TestCreateChatRollback`). Пароли хешируются bcrypt; перед этим пароль проходит через SHA-256, чтобы обойти ограничение bcrypt в 72 байта. -- 2.54.0