From 4455850c6a72777eba3e59c5f3f6228cc66b7654 Mon Sep 17 00:00:00 2001 From: d1frend Date: Tue, 6 Oct 2026 21:26:18 +0300 Subject: [PATCH] =?UTF-8?q?=D0=9F=D0=B5=D1=80=D0=B5=D0=BD=D0=B5=D1=81?= =?UTF-8?q?=D0=B5=D0=BD=D0=B0=20=D0=9B=D0=A01?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Dockerfile | 34 ++ cmd/server/main.go | 95 +++++ go.mod | 5 + go.sum | 2 + internal/domain/models.go | 155 +++++++ internal/store/memory.go | 287 +++++++++++++ internal/transport/http/handlers/chats.go | 105 +++++ internal/transport/http/handlers/handler.go | 44 ++ internal/transport/http/handlers/health.go | 20 + internal/transport/http/handlers/messages.go | 100 +++++ internal/transport/http/handlers/users.go | 59 +++ internal/transport/http/middleware/auth.go | 43 ++ internal/transport/http/middleware/logger.go | 44 ++ .../transport/http/middleware/recovery.go | 28 ++ .../transport/http/middleware/request_id.go | 35 ++ internal/transport/http/response/response.go | 60 +++ student_tests/cursor_concurrency_test.go | 401 ++++++++++++++++++ student_tests/messenger_test.go | 367 ++++++++++++++++ 18 files changed, 1884 insertions(+) create mode 100644 Dockerfile create mode 100644 cmd/server/main.go create mode 100644 go.mod create mode 100644 go.sum create mode 100644 internal/domain/models.go create mode 100644 internal/store/memory.go create mode 100644 internal/transport/http/handlers/chats.go create mode 100644 internal/transport/http/handlers/handler.go create mode 100644 internal/transport/http/handlers/health.go create mode 100644 internal/transport/http/handlers/messages.go create mode 100644 internal/transport/http/handlers/users.go create mode 100644 internal/transport/http/middleware/auth.go create mode 100644 internal/transport/http/middleware/logger.go create mode 100644 internal/transport/http/middleware/recovery.go create mode 100644 internal/transport/http/middleware/request_id.go create mode 100644 internal/transport/http/response/response.go create mode 100644 student_tests/cursor_concurrency_test.go create mode 100644 student_tests/messenger_test.go diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..8223c15 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,34 @@ +FROM golang:1.27.1-alpine AS builder + +WORKDIR /build + +COPY go.mod go.sum ./ +RUN go mod download + +COPY cmd/ ./cmd/ +COPY internal/ ./internal/ + + +RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags="-w -s" -o /build/server ./cmd/server/main.go + +FROM alpine:3.24 + +RUN addgroup -g 1000 appgroup && \ + adduser -u 1000 -G appgroup -s /bin/sh -D appuser + +WORKDIR /app + +COPY --from=builder /build/server /app/server + +RUN chown -R appuser:appgroup /app + +USER appuser:appgroup + +EXPOSE 8080 + +# Проверка здоровья контейнера через /health/live и wget +HEALTHCHECK --interval=5s --timeout=3s --start-period=2s --retries=3 \ + CMD wget -qO- http://127.0.0.1:8080/health/live || exit 1 + + +ENTRYPOINT ["/app/server"] \ No newline at end of file diff --git a/cmd/server/main.go b/cmd/server/main.go new file mode 100644 index 0000000..eb7d7a4 --- /dev/null +++ b/cmd/server/main.go @@ -0,0 +1,95 @@ +package main + +import ( + "context" + "errors" + "log" + "net/http" + "os" + "os/signal" + "syscall" + "time" + + "mtusi2026lab2/internal/store" + "mtusi2026lab2/internal/transport/http/handlers" + "mtusi2026lab2/internal/transport/http/middleware" +) + +func main() { + addr := os.Getenv("HTTP_ADDR") + if addr == "" { + port := os.Getenv("PORT") + if port == "" { + port = "8080" + } + addr = "0.0.0.0:" + port + } + + memStore := store.NewMemoryStore() + h := handlers.NewHandler(memStore) + + mux := http.NewServeMux() + + //паблик систем ручки + mux.HandleFunc("GET /health/live", h.HealthLive) + mux.HandleFunc("GET /health/ready", h.HealthReady) + + // паблик рег юзера + mux.HandleFunc("POST /api/v1/users", h.CreateUser) + + //защищенные через мидлварьки + mux.HandleFunc("GET /api/v1/users/me", middleware.RequireAuth(memStore, h.GetMe)) + + mux.HandleFunc("POST /api/v1/chats", middleware.RequireAuth(memStore, h.CreateChat)) + mux.HandleFunc("GET /api/v1/chats", middleware.RequireAuth(memStore, h.ListChats)) + mux.HandleFunc("GET /api/v1/chats/{chat_id}", middleware.RequireAuth(memStore, h.GetChat)) + + mux.HandleFunc("POST /api/v1/chats/{chat_id}/messages", middleware.RequireAuth(memStore, h.CreateMessage)) + mux.HandleFunc("GET /api/v1/chats/{chat_id}/messages", middleware.RequireAuth(memStore, h.GetMessages)) + + //конвейер + var rootHandler http.Handler = mux + rootHandler = middleware.Recovery(rootHandler) + rootHandler = middleware.Logger(rootHandler) + rootHandler = middleware.RequestID(rootHandler) + + //конф сервака + server := &http.Server{ + Addr: addr, + Handler: rootHandler, + ReadTimeout: 15 * time.Second, + WriteTimeout: 15 * time.Second, + IdleTimeout: 60 * time.Second, + } + + //серв в рутине запущен + serverErrors := make(chan error, 1) + go func() { + log.Printf("[INFO] Server starting on %s", addr) + serverErrors <- server.ListenAndServe() + }() + + shutdown := make(chan os.Signal, 1) + signal.Notify(shutdown, os.Interrupt, syscall.SIGTERM) + + //падение/сигнал на выкл + select { + case err := <-serverErrors: + if !errors.Is(err, http.ErrServerClosed) { + log.Fatalf("[FATAL] Server crashed: %v", err) + } + + case sig := <-shutdown: + log.Printf("[INFO] Signal %v received. Starting graceful shutdown...", sig) + + // завершение не более чем за 10 секунд + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + if err := server.Shutdown(ctx); err != nil { + log.Printf("[WARN] Graceful shutdown failed: %v. Forcing close.", err) + _ = server.Close() + } + log.Println("[INFO] Server stopped gracefully.") + } +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..dccd666 --- /dev/null +++ b/go.mod @@ -0,0 +1,5 @@ +module mtusi2026lab2 + +go 1.27.1 + +require github.com/google/uuid v1.6.0 diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..7790d7c --- /dev/null +++ b/go.sum @@ -0,0 +1,2 @@ +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= diff --git a/internal/domain/models.go b/internal/domain/models.go new file mode 100644 index 0000000..b40edb2 --- /dev/null +++ b/internal/domain/models.go @@ -0,0 +1,155 @@ +package domain + +import ( + "encoding/base64" + "fmt" + "regexp" + "strings" + "time" + "unicode/utf8" + + "github.com/google/uuid" +) + +var ( + //регулярка по контракту + usernameRegex = regexp.MustCompile(`^[a-z0-9_]{3,32}$`) +) + +type User struct { + ID string `json:"id"` + Username string `json:"username"` + DisplayName string `json:"display_name"` + CreatedAt time.Time `json:"created_at"` +} + +type Chat struct { + ID string `json:"id"` + Title string `json:"title"` + MemberIDs []string `json:"member_ids"` + CreatedAt time.Time `json:"created_at"` +} + +type Message struct { + ID string `json:"id"` + ChatID string `json:"chat_id"` + SenderID string `json:"sender_id"` + Text string `json:"text"` + CreatedAt time.Time `json:"created_at"` +} + +// страница выдачи истории сообщений +type MessagePage struct { + Items []Message `json:"items"` + NextCursor *string `json:"next_cursor"` +} + +func (u *User) Validate() error { + if !usernameRegex.MatchString(u.Username) { + return fmt.Errorf("username must match [a-z0-9_]{3,32}") + } + + nameRunes := utf8.RuneCountInString(u.DisplayName) + if nameRunes < 1 || nameRunes > 100 { + return fmt.Errorf("display_name length must be between 1 and 100 code points") + } + + if strings.TrimSpace(u.DisplayName) == "" { + return fmt.Errorf("display_name cannot be only whitespace") + } + + return nil +} + +func ValidateChatInput(title string, memberIDs []string, callerID string) error { + titleRunes := utf8.RuneCountInString(title) + if titleRunes < 1 || titleRunes > 100 || strings.TrimSpace(title) == "" { + return fmt.Errorf("invalid chat title") + } + + if len(memberIDs) == 0 { + return fmt.Errorf("member_ids cannot be empty") + } + + hasCaller := false + seen := make(map[string]bool) + + for _, id := range memberIDs { + if _, err := uuid.Parse(id); err != nil { + return fmt.Errorf("invalid member uuid: %s", id) + } + if seen[id] { + return fmt.Errorf("duplicate member_id: %s", id) + } + seen[id] = true + + if id == callerID { + hasCaller = true + } + } + + if !hasCaller { + return fmt.Errorf("caller must be in member_ids") + } + + return nil +} + +func ValidateMessageText(text string) error { + textRunes := utf8.RuneCountInString(text) + if textRunes < 1 || textRunes > 4000 { + return fmt.Errorf("message text length must be between 1 and 4000 code points") + } + if strings.TrimSpace(text) == "" { + return fmt.Errorf("message text cannot be only whitespace") + } + return nil +} + +type CursorData struct { + CreatedAt time.Time + MessageID string + ChatID string +} + +// EncodeCursor превращает время, message_id и chat_id в непрозрачную base64 строку +func EncodeCursor(createdAt time.Time, messageID, chatID string) string { + raw := fmt.Sprintf("%s|%s|%s", createdAt.Format(time.RFC3339Nano), messageID, chatID) + return base64.StdEncoding.EncodeToString([]byte(raw)) +} + +// DecodeCursor декодирует строку курсора и проверяет, что он принадлежит именно этому чату +func DecodeCursor(cursorStr string, expectedChatID string) (*CursorData, error) { + bytes, err := base64.StdEncoding.DecodeString(cursorStr) + if err != nil { + return nil, fmt.Errorf("invalid base64 cursor") + } + + parts := strings.Split(string(bytes), "|") + if len(parts) != 3 { + return nil, fmt.Errorf("malformed cursor") + } + + t, err := time.Parse(time.RFC3339Nano, parts[0]) + if err != nil { + return nil, fmt.Errorf("invalid cursor timestamp") + } + + chatID := parts[2] + //защита из контракта: курсор от другого чата должен давать 400 + if chatID != expectedChatID { + return nil, fmt.Errorf("cursor belongs to another chat") + } + + return &CursorData{ + CreatedAt: t, + MessageID: parts[1], + ChatID: chatID, + }, nil +} + +// страница со списком чатов пользователя +type ChatPage struct { + Items []Chat `json:"items"` + NextCursor *string `json:"next_cursor"` +} diff --git a/internal/store/memory.go b/internal/store/memory.go new file mode 100644 index 0000000..3435c04 --- /dev/null +++ b/internal/store/memory.go @@ -0,0 +1,287 @@ +package store + +import ( + "fmt" + "sort" + "sync" + "time" + + "mtusi2026lab2/internal/domain" + + "github.com/google/uuid" +) + +var ( + ErrNotFound = fmt.Errorf("not found") + ErrConflict = fmt.Errorf("conflict") +) + +type MemoryStore struct { + mu sync.RWMutex + + usersByID map[string]domain.User //key = user UUID + usersByUsername map[string]string //key = username для быстрой проверки уникальности + + chatsByID map[string]domain.Chat //key = chat UUID + + messagesByChatID map[string][]domain.Message // key = chat UUID, value = слайс сообщений +} + +func NewMemoryStore() *MemoryStore { + return &MemoryStore{ + usersByID: make(map[string]domain.User), + usersByUsername: make(map[string]string), + chatsByID: make(map[string]domain.Chat), + messagesByChatID: make(map[string][]domain.Message), + } +} + +// ---пользователи--- + +func (s *MemoryStore) CreateUser(username, displayName string) (domain.User, error) { + s.mu.Lock() + defer s.mu.Unlock() + + // дубликат username -> 409 Conflict + if _, exists := s.usersByUsername[username]; exists { + return domain.User{}, ErrConflict + } + + user := domain.User{ + ID: uuid.NewString(), + Username: username, + DisplayName: displayName, + CreatedAt: time.Now().UTC(), + } + + s.usersByID[user.ID] = user + s.usersByUsername[user.Username] = user.ID + + return user, nil +} + +func (s *MemoryStore) GetUserByID(id string) (domain.User, error) { + s.mu.RLock() + defer s.mu.RUnlock() + + user, exists := s.usersByID[id] + if !exists { + return domain.User{}, ErrNotFound + } + return user, nil +} + +// ---чаты--- + +func (s *MemoryStore) CreateChat(title string, memberIDs []string) (domain.Chat, error) { + s.mu.Lock() + defer s.mu.Unlock() + + //все участники рил существуют + for _, memberID := range memberIDs { + if _, exists := s.usersByID[memberID]; !exists { + return domain.Chat{}, fmt.Errorf("member not found: %s", memberID) + } + } + + chat := domain.Chat{ + ID: uuid.NewString(), + Title: title, + MemberIDs: append([]string(nil), memberIDs...), //копирую слайс для изоляции + CreatedAt: time.Now().UTC(), + } + + s.chatsByID[chat.ID] = chat + s.messagesByChatID[chat.ID] = make([]domain.Message, 0) + + return chat, nil +} + +func (s *MemoryStore) GetChatByID(chatID, callerID string) (domain.Chat, error) { + s.mu.RLock() + defer s.mu.RUnlock() + + chat, exists := s.chatsByID[chatID] + if !exists { + return domain.Chat{}, ErrNotFound + } + + // Требование безопасности: посторонний получает 404, а не 403 + isMember := false + for _, m := range chat.MemberIDs { + if m == callerID { + isMember = true + break + } + } + + if !isMember { + return domain.Chat{}, ErrNotFound + } + + return chat, nil +} + +func (s *MemoryStore) GetChatsForUser(userID string, limit int) ([]domain.Chat, error) { + s.mu.RLock() + defer s.mu.RUnlock() + + var result []domain.Chat + for _, chat := range s.chatsByID { + for _, m := range chat.MemberIDs { + if m == userID { + result = append(result, chat) + break + } + } + } + + //по контракту: сортировка по created_at, id по возрастанию + sort.Slice(result, func(i, j int) bool { + if result[i].CreatedAt.Equal(result[j].CreatedAt) { + return result[i].ID < result[j].ID + } + return result[i].CreatedAt.Before(result[j].CreatedAt) + }) + + if limit > 0 && len(result) > limit { + result = result[:limit] + } + + return result, nil +} + +// ---Сообщения--- + +func (s *MemoryStore) CreateMessage( + chatID, senderID, text string, +) (domain.Message, error) { + messageID := uuid.NewString() + + s.mu.Lock() + defer s.mu.Unlock() + + chat, exists := s.chatsByID[chatID] + if !exists { + return domain.Message{}, ErrNotFound + } + + isMember := false + for _, memberID := range chat.MemberIDs { + if memberID == senderID { + isMember = true + break + } + } + if !isMember { + return domain.Message{}, ErrNotFound + } + + createdAt := time.Now().UTC() + + messages := s.messagesByChatID[chatID] + if len(messages) > 0 { + lastCreatedAt := messages[len(messages)-1].CreatedAt + + // Обеспечиваем строго возрастающее время внутри каждого чата. + if !createdAt.After(lastCreatedAt) { + createdAt = lastCreatedAt.Add(time.Nanosecond) + } + } + + message := domain.Message{ + ID: messageID, + ChatID: chatID, + SenderID: senderID, + Text: text, + CreatedAt: createdAt, + } + + s.messagesByChatID[chatID] = append(messages, message) + + return message, nil +} + +func (s *MemoryStore) GetMessages( + chatID, callerID string, + limit int, + cursorStr string, +) (domain.MessagePage, error) { + s.mu.RLock() + defer s.mu.RUnlock() + + chat, exists := s.chatsByID[chatID] + if !exists { + return domain.MessagePage{}, ErrNotFound + } + + isMember := false + for _, memberID := range chat.MemberIDs { + if memberID == callerID { + isMember = true + break + } + } + if !isMember { + return domain.MessagePage{}, ErrNotFound + } + + var cursorData *domain.CursorData + if cursorStr != "" { + decodedCursor, err := domain.DecodeCursor(cursorStr, chatID) + if err != nil { + return domain.MessagePage{}, + fmt.Errorf("invalid cursor: %w", err) + } + cursorData = decodedCursor + } + + messages := s.messagesByChatID[chatID] + + start := 0 + + if cursorData != nil { + // Срез уже упорядочен во время записи, поэтому вместо + // полного прохода используем бинарный поиск. + start = sort.Search(len(messages), func(index int) bool { + message := messages[index] + + if message.CreatedAt.After(cursorData.CreatedAt) { + return true + } + + return message.CreatedAt.Equal(cursorData.CreatedAt) && + message.ID > cursorData.MessageID + }) + } + + page := domain.MessagePage{ + Items: make([]domain.Message, 0), + NextCursor: nil, + } + + if start >= len(messages) { + return page, nil + } + + end := len(messages) + if limit > 0 && end-start > limit { + end = start + limit + } + + // копируем только возвращаемую страницу, а не всю историю, изменяя внутренний срез + page.Items = make([]domain.Message, end-start) + copy(page.Items, messages[start:end]) + + if end < len(messages) { + lastItem := page.Items[len(page.Items)-1] + nextCursor := domain.EncodeCursor( + lastItem.CreatedAt, + lastItem.ID, + chatID, + ) + page.NextCursor = &nextCursor + } + + return page, nil +} diff --git a/internal/transport/http/handlers/chats.go b/internal/transport/http/handlers/chats.go new file mode 100644 index 0000000..53f0b45 --- /dev/null +++ b/internal/transport/http/handlers/chats.go @@ -0,0 +1,105 @@ +package handlers + +import ( + "errors" + "net/http" + "strconv" + + "mtusi2026lab2/internal/domain" + "mtusi2026lab2/internal/store" + "mtusi2026lab2/internal/transport/http/middleware" + "mtusi2026lab2/internal/transport/http/response" + + "github.com/google/uuid" +) + +type CreateChatRequest struct { + Title string `json:"title"` + MemberIDs []string `json:"member_ids"` +} + +func (h *Handler) CreateChat(w http.ResponseWriter, r *http.Request) { + reqID := middleware.GetRequestID(r.Context()) + currentUser := middleware.GetCurrentUser(r.Context()) + + var req CreateChatRequest + if err := decodeJSON(r, &req); err != nil { + response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest, "invalid json: "+err.Error(), reqID) + return + } + + //вызывающий есть в списке, нет дубликатов, валидные UUID + if err := domain.ValidateChatInput(req.Title, req.MemberIDs, currentUser.ID); err != nil { + response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest, err.Error(), reqID) + return + } + + chat, err := h.store.CreateChat(req.Title, req.MemberIDs) + if err != nil { + //участник не существует -> 400 + response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest, err.Error(), reqID) + return + } + + response.WriteJSON(w, http.StatusCreated, chat, reqID) +} + +// инфа о чате +func (h *Handler) GetChat(w http.ResponseWriter, r *http.Request) { + reqID := middleware.GetRequestID(r.Context()) + currentUser := middleware.GetCurrentUser(r.Context()) + + chatID := r.PathValue("chat_id") + if _, err := uuid.Parse(chatID); err != nil { + response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest, "invalid chat_id uuid", reqID) + return + } + + chat, err := h.store.GetChatByID(chatID, currentUser.ID) + if err != nil { + if errors.Is(err, store.ErrNotFound) { + //посторонний или несуществующий чат -> 404 + response.WriteError(w, http.StatusNotFound, response.CodeNotFound, "chat not found", reqID) + return + } + response.WriteError(w, http.StatusInternalServerError, response.CodeInternalError, "internal error", reqID) + return + } + + response.WriteJSON(w, http.StatusOK, chat, reqID) +} + +// список всех чатов текущего пользователя +func (h *Handler) ListChats(w http.ResponseWriter, r *http.Request) { + reqID := middleware.GetRequestID(r.Context()) + currentUser := middleware.GetCurrentUser(r.Context()) + + limit := 50 + limitStr := r.URL.Query().Get("limit") + if limitStr != "" { + val, err := strconv.Atoi(limitStr) + if err != nil || val < 1 || val > 100 { + response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest, "limit must be an integer between 1 and 100", reqID) + return + } + limit = val + } + + chats, err := h.store.GetChatsForUser(currentUser.ID, limit) + if err != nil { + response.WriteError(w, http.StatusInternalServerError, response.CodeInternalError, "internal error", reqID) + return + } + + //если чатов нет, сериализую в пустой массив [], а не null + if chats == nil { + chats = make([]domain.Chat, 0) + } + + page := domain.ChatPage{ + Items: chats, + NextCursor: nil, + } + + response.WriteJSON(w, http.StatusOK, page, reqID) +} diff --git a/internal/transport/http/handlers/handler.go b/internal/transport/http/handlers/handler.go new file mode 100644 index 0000000..7e2269d --- /dev/null +++ b/internal/transport/http/handlers/handler.go @@ -0,0 +1,44 @@ +package handlers + +import ( + "encoding/json" + "errors" + "io" + "net/http" + + "mtusi2026lab2/internal/store" +) + +type Handler struct { + store *store.MemoryStore +} + +func NewHandler(st *store.MemoryStore) *Handler { + return &Handler{store: st} +} + +// декодирует тело запроса: +// Запрещает неизвестные/лишние поля (DisallowUnknownFields) -> 400 +// Ловит синтаксические ошибки JSON -> 400 +// Проверяет, что после валидного JSON нет мусора +func decodeJSON(r *http.Request, dst any) error { + if r.Body == nil { + return errors.New("request body is empty") + } + defer r.Body.Close() + + dec := json.NewDecoder(r.Body) + dec.DisallowUnknownFields() + + if err := dec.Decode(dst); err != nil { + return err + } + + // два JSON подряд или мусор в конце — ошибка + var extra json.RawMessage + if err := dec.Decode(&extra); !errors.Is(err, io.EOF) { + return errors.New("extra data after JSON") + } + + return nil +} diff --git a/internal/transport/http/handlers/health.go b/internal/transport/http/handlers/health.go new file mode 100644 index 0000000..c6c4ca0 --- /dev/null +++ b/internal/transport/http/handlers/health.go @@ -0,0 +1,20 @@ +package handlers + +import ( + "net/http" + + "mtusi2026lab2/internal/transport/http/middleware" + "mtusi2026lab2/internal/transport/http/response" +) + +// HealthLive проверяет, что процесс сервера запущен +func (h *Handler) HealthLive(w http.ResponseWriter, r *http.Request) { + reqID := middleware.GetRequestID(r.Context()) + response.WriteJSON(w, http.StatusOK, map[string]string{"status": "ok"}, reqID) +} + +// HealthReady проверяет, что сервер готов принимать входящие запросы +func (h *Handler) HealthReady(w http.ResponseWriter, r *http.Request) { + reqID := middleware.GetRequestID(r.Context()) + response.WriteJSON(w, http.StatusOK, map[string]string{"status": "ok"}, reqID) +} diff --git a/internal/transport/http/handlers/messages.go b/internal/transport/http/handlers/messages.go new file mode 100644 index 0000000..af42de2 --- /dev/null +++ b/internal/transport/http/handlers/messages.go @@ -0,0 +1,100 @@ +package handlers + +import ( + "errors" + "net/http" + "strconv" + + "mtusi2026lab2/internal/domain" + "mtusi2026lab2/internal/store" + "mtusi2026lab2/internal/transport/http/middleware" + "mtusi2026lab2/internal/transport/http/response" + + "github.com/google/uuid" +) + +type CreateMessageRequest struct { + Text string `json:"text"` +} + +// CreateMessage отправляет сообщение в чат +func (h *Handler) CreateMessage(w http.ResponseWriter, r *http.Request) { + reqID := middleware.GetRequestID(r.Context()) + currentUser := middleware.GetCurrentUser(r.Context()) + + chatID := r.PathValue("chat_id") + if _, err := uuid.Parse(chatID); err != nil { + response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest, "invalid chat_id uuid", reqID) + return + } + + var req CreateMessageRequest + if err := decodeJSON(r, &req); err != nil { + response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest, "invalid json: "+err.Error(), reqID) + return + } + + //не пустой, не только пробелы, до 4000 рун + if err := domain.ValidateMessageText(req.Text); err != nil { + response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest, err.Error(), reqID) + return + } + + //автор сообщения строго выводится из сессии (currentUser.ID) + msg, err := h.store.CreateMessage(chatID, currentUser.ID, req.Text) + if err != nil { + if errors.Is(err, store.ErrNotFound) { + // чата нет/пользователь не участник -> 404 + response.WriteError(w, http.StatusNotFound, response.CodeNotFound, "chat not found", reqID) + return + } + response.WriteError(w, http.StatusInternalServerError, response.CodeInternalError, "internal error", reqID) + return + } + + response.WriteJSON(w, http.StatusCreated, msg, reqID) +} + +// GetMessages возвращает историю сообщений чата с пагинацией по курсору +func (h *Handler) GetMessages(w http.ResponseWriter, r *http.Request) { + reqID := middleware.GetRequestID(r.Context()) + currentUser := middleware.GetCurrentUser(r.Context()) + + chatID := r.PathValue("chat_id") + if _, err := uuid.Parse(chatID); err != nil { + response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest, "invalid chat_id uuid", reqID) + return + } + + limit := 50 + limitStr := r.URL.Query().Get("limit") + if limitStr != "" { + val, err := strconv.Atoi(limitStr) + // Если передан limit=0 или >100 -> 400 invalid_request + if err != nil || val < 1 || val > 100 { + response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest, "limit must be an integer between 1 and 100", reqID) + return + } + limit = val + } + + cursor := r.URL.Query().Get("cursor") + + page, err := h.store.GetMessages(chatID, currentUser.ID, limit, cursor) + if err != nil { + if errors.Is(err, store.ErrNotFound) { + response.WriteError(w, http.StatusNotFound, response.CodeNotFound, "chat not found", reqID) + return + } + //если курсор кривой или от другого чата -> 400 invalid_request + response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest, err.Error(), reqID) + return + } + + // сообщений нет, [] вместо null + if page.Items == nil { + page.Items = make([]domain.Message, 0) + } + + response.WriteJSON(w, http.StatusOK, page, reqID) +} diff --git a/internal/transport/http/handlers/users.go b/internal/transport/http/handlers/users.go new file mode 100644 index 0000000..9a012bd --- /dev/null +++ b/internal/transport/http/handlers/users.go @@ -0,0 +1,59 @@ +package handlers + +import ( + "errors" + "net/http" + + "mtusi2026lab2/internal/domain" + "mtusi2026lab2/internal/store" + "mtusi2026lab2/internal/transport/http/middleware" + "mtusi2026lab2/internal/transport/http/response" +) + +type CreateUserRequest struct { + Username string `json:"username"` + DisplayName string `json:"display_name"` +} + +// CreateUser создает нового пользователя +func (h *Handler) CreateUser(w http.ResponseWriter, r *http.Request) { + reqID := middleware.GetRequestID(r.Context()) + + var req CreateUserRequest + if err := decodeJSON(r, &req); err != nil { + response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest, "malformed or invalid JSON: "+err.Error(), reqID) + return + } + + userCandidate := domain.User{ + Username: req.Username, + DisplayName: req.DisplayName, + } + + //правила Unicode, длину и пробелы из domain + if err := userCandidate.Validate(); err != nil { + response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest, err.Error(), reqID) + return + } + + createdUser, err := h.store.CreateUser(userCandidate.Username, userCandidate.DisplayName) + if err != nil { + // юзернейм занят — 409 + if errors.Is(err, store.ErrConflict) { + response.WriteError(w, http.StatusConflict, response.CodeConflict, "username already exists", reqID) + return + } + response.WriteError(w, http.StatusInternalServerError, response.CodeInternalError, "failed to create user", reqID) + return + } + + response.WriteJSON(w, http.StatusCreated, createdUser, reqID) +} + +// GetMe возвращает профиль текущего пользователя +func (h *Handler) GetMe(w http.ResponseWriter, r *http.Request) { + reqID := middleware.GetRequestID(r.Context()) + currentUser := middleware.GetCurrentUser(r.Context()) + + response.WriteJSON(w, http.StatusOK, currentUser, reqID) +} diff --git a/internal/transport/http/middleware/auth.go b/internal/transport/http/middleware/auth.go new file mode 100644 index 0000000..2174706 --- /dev/null +++ b/internal/transport/http/middleware/auth.go @@ -0,0 +1,43 @@ +package middleware + +import ( + "context" + "net/http" + + "mtusi2026lab2/internal/domain" + "mtusi2026lab2/internal/store" + "mtusi2026lab2/internal/transport/http/response" +) + +const UserContextKey contextKey = "current_user" + +// RequireAuth проверяет наличие и валидность X-User-Id +func RequireAuth(st *store.MemoryStore, next http.HandlerFunc) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + reqID := GetRequestID(r.Context()) + userID := r.Header.Get("X-User-Id") + + if userID == "" { + response.WriteError(w, http.StatusUnauthorized, response.CodeUnauthorized, "missing X-User-Id header", reqID) + return + } + + //существует ли чел + user, err := st.GetUserByID(userID) + if err != nil { + response.WriteError(w, http.StatusUnauthorized, response.CodeUnauthorized, "user not found", reqID) + return + } + + ctx := context.WithValue(r.Context(), UserContextKey, user) + next(w, r.WithContext(ctx)) + } +} + +// чисто чтоб зареганного получить из контекста +func GetCurrentUser(ctx context.Context) domain.User { + if val, ok := ctx.Value(UserContextKey).(domain.User); ok { + return val + } + return domain.User{} +} diff --git a/internal/transport/http/middleware/logger.go b/internal/transport/http/middleware/logger.go new file mode 100644 index 0000000..93c405b --- /dev/null +++ b/internal/transport/http/middleware/logger.go @@ -0,0 +1,44 @@ +package middleware + +import ( + "log" + "net/http" + "time" +) + +// responseWriterInterceptor перехватывает статус-код ответа для логов +type responseWriterInterceptor struct { + http.ResponseWriter + statusCode int +} + +func (w *responseWriterInterceptor) WriteHeader(code int) { + w.statusCode = code + w.ResponseWriter.WriteHeader(code) +} + +func Logger(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + start := time.Now() + + interceptor := &responseWriterInterceptor{ + ResponseWriter: w, + statusCode: http.StatusOK, // дефолтный статус если WriteHeader не вызывался + } + + next.ServeHTTP(interceptor, r) + + reqID := GetRequestID(r.Context()) + duration := time.Since(start) + + // метаданные без r.Body + log.Printf( + "[HTTP] %s %s | status: %d | duration: %v | request_id: %s", + r.Method, + r.URL.Path, + interceptor.statusCode, + duration, + reqID, + ) + }) +} diff --git a/internal/transport/http/middleware/recovery.go b/internal/transport/http/middleware/recovery.go new file mode 100644 index 0000000..5e56c26 --- /dev/null +++ b/internal/transport/http/middleware/recovery.go @@ -0,0 +1,28 @@ +package middleware + +import ( + "net/http" + + "mtusi2026lab2/internal/transport/http/response" +) + +// Recovery перехватывает панику и возвращает клиенту валидный JSON 500 +func Recovery(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + defer func() { + if err := recover(); err != nil { + reqID := GetRequestID(r.Context()) + //из контракта: не раскрывать stack trace и внутренности + response.WriteError( + w, + http.StatusInternalServerError, + response.CodeInternalError, + "internal server error", + reqID, + ) + } + }() + + next.ServeHTTP(w, r) + }) +} diff --git a/internal/transport/http/middleware/request_id.go b/internal/transport/http/middleware/request_id.go new file mode 100644 index 0000000..228a77a --- /dev/null +++ b/internal/transport/http/middleware/request_id.go @@ -0,0 +1,35 @@ +package middleware + +import ( + "context" + "net/http" + + "github.com/google/uuid" +) + +type contextKey string + +const RequestIDKey contextKey = "request_id" + +// RequestID извлекает или генерирует X-Request-Id и кладет его в контекст и заголовок ответа +func RequestID(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + reqID := r.Header.Get("X-Request-Id") + if reqID == "" { + reqID = uuid.NewString() + } + + w.Header().Set("X-Request-Id", reqID) + + ctx := context.WithValue(r.Context(), RequestIDKey, reqID) + next.ServeHTTP(w, r.WithContext(ctx)) + }) +} + +// GetRequestID достает ID запроса из контекста +func GetRequestID(ctx context.Context) string { + if val, ok := ctx.Value(RequestIDKey).(string); ok { + return val + } + return uuid.NewString() +} diff --git a/internal/transport/http/response/response.go b/internal/transport/http/response/response.go new file mode 100644 index 0000000..ec8adfc --- /dev/null +++ b/internal/transport/http/response/response.go @@ -0,0 +1,60 @@ +package response + +import ( + "encoding/json" + "net/http" +) + +// коды ошибок по контракту +const ( + CodeInvalidRequest = "invalid_request" + CodeUnauthorized = "unauthorized" + CodeNotFound = "not_found" + CodeConflict = "conflict" + CodeInternalError = "internal_error" +) + +type ErrorPayload struct { + Code string `json:"code"` + Message string `json:"message"` + RequestID string `json:"request_id"` +} + +// ErrorResponse — строгое тело ответа при любой ошибке +type ErrorResponse struct { + Error ErrorPayload `json:"error"` +} + +// WriteJSON отправляет любой успешный ответ с правильными заголовками +func WriteJSON(w http.ResponseWriter, statusCode int, data any, requestID string) { + w.Header().Set("Content-Type", "application/json; charset=utf-8") + if requestID != "" { + w.Header().Set("X-Request-Id", requestID) + } + + w.WriteHeader(statusCode) + + if data != nil { + _ = json.NewEncoder(w).Encode(data) + } +} + +// WriteError формирует стандартизированную ошибку с совпадением request_id в теле и заголовке +func WriteError(w http.ResponseWriter, statusCode int, code string, message string, requestID string) { + w.Header().Set("Content-Type", "application/json; charset=utf-8") + if requestID != "" { + w.Header().Set("X-Request-Id", requestID) + } + + w.WriteHeader(statusCode) + + resp := ErrorResponse{ + Error: ErrorPayload{ + Code: code, + Message: message, + RequestID: requestID, + }, + } + + _ = json.NewEncoder(w).Encode(resp) +} diff --git a/student_tests/cursor_concurrency_test.go b/student_tests/cursor_concurrency_test.go new file mode 100644 index 0000000..a67e7e1 --- /dev/null +++ b/student_tests/cursor_concurrency_test.go @@ -0,0 +1,401 @@ +package student_tests + +import ( + "encoding/json" + "fmt" + "io" + "net/http" + "net/url" + "runtime" + "sync" + "testing" + "time" + + "mtusi2026lab2/internal/domain" +) + +func fetchCursorPage( + t *testing.T, + baseURL, chatID, userID string, + limit int, + cursor string, +) domain.MessagePage { + t.Helper() + + endpoint := fmt.Sprintf( + "%s/api/v1/chats/%s/messages?limit=%d", + baseURL, + chatID, + limit, + ) + if cursor != "" { + endpoint += "&cursor=" + url.QueryEscape(cursor) + } + + req, err := http.NewRequest(http.MethodGet, endpoint, nil) + if err != nil { + t.Fatal(err) + } + req.Header.Set("X-User-Id", userID) + + res, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatal(err) + } + defer res.Body.Close() + + if res.StatusCode != http.StatusOK { + body, _ := io.ReadAll(res.Body) + t.Fatalf("expected 200, got %d: %s", res.StatusCode, body) + } + + var page domain.MessagePage + if err := json.NewDecoder(res.Body).Decode(&page); err != nil { + t.Fatalf("decode message page: %v", err) + } + return page +} + +func TestCursorTraversalAfterConcurrentWrites(t *testing.T) { + ts, st := setupTestServer() + defer ts.Close() + + const ( + clients = 10 + messagesPerClient = 100 + expectedMessages = clients * messagesPerClient + ) + + memberIDs := make([]string, 0, clients) + for client := 0; client < clients; client++ { + user, err := st.CreateUser( + fmt.Sprintf("cursor_client_%d", client), + fmt.Sprintf("Cursor client %d", client), + ) + if err != nil { + t.Fatal(err) + } + memberIDs = append(memberIDs, user.ID) + } + + chat, err := st.CreateChat("Concurrent cursor test", memberIDs) + if err != nil { + t.Fatal(err) + } + + start := make(chan struct{}) + var writers sync.WaitGroup + for client := 0; client < clients; client++ { + writers.Add(1) + go func(client int) { + defer writers.Done() + <-start + for message := 0; message < messagesPerClient; message++ { + _, err := st.CreateMessage( + chat.ID, + memberIDs[client], + fmt.Sprintf("client=%d message=%d", client, message), + ) + if err != nil { + t.Errorf("create message: %v", err) + return + } + } + }(client) + } + + close(start) + writers.Wait() + + seen := make(map[string]struct{}, expectedMessages) + duplicateCount := 0 + var previous *domain.Message + firstOrderingViolation := "" + cursor := "" + pageCount := 0 + + for { + pageCount++ + if pageCount > expectedMessages { + t.Fatal("pagination did not terminate") + } + + page := fetchCursorPage(t, ts.URL, chat.ID, memberIDs[0], 17, cursor) + for index := range page.Items { + message := page.Items[index] + if _, duplicate := seen[message.ID]; duplicate { + duplicateCount++ + } + seen[message.ID] = struct{}{} + + if previous != nil { + outOfOrder := message.CreatedAt.Before(previous.CreatedAt) || + (message.CreatedAt.Equal(previous.CreatedAt) && message.ID <= previous.ID) + if outOfOrder && firstOrderingViolation == "" { + firstOrderingViolation = fmt.Sprintf( + "previous=(%s,%s), current=(%s,%s)", + previous.CreatedAt.Format("15:04:05.999999999"), previous.ID, + message.CreatedAt.Format("15:04:05.999999999"), message.ID, + ) + } + } + + messageCopy := message + previous = &messageCopy + } + + if page.NextCursor == nil { + break + } + cursor = *page.NextCursor + } + + if len(seen) != expectedMessages || duplicateCount != 0 { + t.Fatalf( + "cursor traversal returned %d unique messages of %d and %d duplicates; first ordering violation: %s", + len(seen), expectedMessages, duplicateCount, firstOrderingViolation, + ) + } + if firstOrderingViolation != "" { + t.Fatalf("history is not ordered: %s", firstOrderingViolation) + } +} + +func TestCursorTraversalDuringConcurrentWrites(t *testing.T) { + ts, st := setupTestServer() + defer ts.Close() + + const ( + clients = 16 + messagesPerClient = 100 + seedMessages = 100 + pageLimit = 7 + expectedTotal = seedMessages + clients*messagesPerClient + ) + + memberIDs := make([]string, 0, clients) + for client := 0; client < clients; client++ { + user, err := st.CreateUser( + fmt.Sprintf("live_cursor_client_%d", client), + fmt.Sprintf("Live cursor client %d", client), + ) + if err != nil { + t.Fatalf("create user %d: %v", client, err) + } + memberIDs = append(memberIDs, user.ID) + } + + chat, err := st.CreateChat("Live concurrent cursor test", memberIDs) + if err != nil { + t.Fatalf("create chat: %v", err) + } + + // Начальные сообщения нужны, чтобы читатель сразу начал + // двигать курсор, пока остальные сообщения ещё записываются. + expectedIDs := make(map[string]struct{}, expectedTotal) + for index := 0; index < seedMessages; index++ { + message, err := st.CreateMessage( + chat.ID, + memberIDs[0], + fmt.Sprintf("seed message=%d", index), + ) + if err != nil { + t.Fatalf("create seed message %d: %v", index, err) + } + expectedIDs[message.ID] = struct{}{} + } + + var expectedMu sync.Mutex + var writers sync.WaitGroup + var ready sync.WaitGroup + + start := make(chan struct{}) + writerErrors := make(chan error, clients) + + for client := 0; client < clients; client++ { + writers.Add(1) + ready.Add(1) + + go func(client int) { + defer writers.Done() + + ready.Done() + <-start + + for index := 0; index < messagesPerClient; index++ { + // Отдаём планировщику возможность чаще переключать + // конкурентные горутины. + runtime.Gosched() + + message, err := st.CreateMessage( + chat.ID, + memberIDs[client], + fmt.Sprintf("client=%d message=%d", client, index), + ) + if err != nil { + writerErrors <- fmt.Errorf( + "client %d, message %d: %w", + client, + index, + err, + ) + return + } + + expectedMu.Lock() + expectedIDs[message.ID] = struct{}{} + expectedMu.Unlock() + + // Не даём всем писателям завершиться до того, + // как читатель успеет продвинуть курсор. + time.Sleep(50 * time.Microsecond) + } + }(client) + } + + // Сначала убеждаемся, что все горутины готовы, + // и только потом одновременно разрешаем запись. + ready.Wait() + + writersDone := make(chan struct{}) + go func() { + writers.Wait() + close(writersDone) + }() + + close(start) + + seen := make(map[string]struct{}, expectedTotal) + cursor := "" + var previous *domain.Message + + const maxPageRequests = expectedTotal * 4 + finished := false + + for requestNumber := 0; requestNumber < maxPageRequests; requestNumber++ { + page := fetchCursorPage( + t, + ts.URL, + chat.ID, + memberIDs[0], + pageLimit, + cursor, + ) + + for index := range page.Items { + message := page.Items[index] + + if _, duplicate := seen[message.ID]; duplicate { + t.Fatalf( + "message %s was returned more than once", + message.ID, + ) + } + + if previous != nil { + outOfOrder := + message.CreatedAt.Before(previous.CreatedAt) || + (message.CreatedAt.Equal(previous.CreatedAt) && + message.ID <= previous.ID) + + if outOfOrder { + t.Fatalf( + "messages are out of order: previous=(%s,%s), current=(%s,%s)", + previous.CreatedAt.Format(time.RFC3339Nano), + previous.ID, + message.CreatedAt.Format(time.RFC3339Nano), + message.ID, + ) + } + } + + seen[message.ID] = struct{}{} + messageCopy := message + previous = &messageCopy + } + + // Для продолжающегося чтения строим курсор по последнему + // фактически полученному сообщению. Это позволяет опрашивать + // историю, даже если в промежуточный момент сервер вернул + // NextCursor=nil. + if len(page.Items) > 0 { + last := page.Items[len(page.Items)-1] + cursor = domain.EncodeCursor( + last.CreatedAt, + last.ID, + chat.ID, + ) + } + + select { + case <-writersDone: + finished = true + default: + } + + // Все писатели завершились, а после текущего курсора + // больше ничего нет: обход закончен. + if finished && len(page.Items) == 0 { + break + } + + if len(page.Items) == 0 { + runtime.Gosched() + } + + if requestNumber == maxPageRequests-1 { + t.Fatalf( + "pagination did not terminate after %d requests", + maxPageRequests, + ) + } + } + + <-writersDone + close(writerErrors) + + for writerErr := range writerErrors { + t.Errorf("create message: %v", writerErr) + } + + expectedMu.Lock() + missingIDs := make([]string, 0) + for id := range expectedIDs { + if _, found := seen[id]; !found { + missingIDs = append(missingIDs, id) + } + } + expectedCount := len(expectedIDs) + expectedMu.Unlock() + + if expectedCount != expectedTotal { + t.Fatalf( + "writers confirmed %d messages, expected %d", + expectedCount, + expectedTotal, + ) + } + + if len(missingIDs) != 0 { + const displayedMissingIDs = 5 + if len(missingIDs) > displayedMissingIDs { + missingIDs = missingIDs[:displayedMissingIDs] + } + + t.Fatalf( + "cursor traversal returned %d of %d confirmed messages; "+ + "examples of missing IDs: %v", + len(seen), + expectedTotal, + missingIDs, + ) + } + + if len(seen) != expectedTotal { + t.Fatalf( + "cursor traversal returned %d messages, expected %d", + len(seen), + expectedTotal, + ) + } +} diff --git a/student_tests/messenger_test.go b/student_tests/messenger_test.go new file mode 100644 index 0000000..8036086 --- /dev/null +++ b/student_tests/messenger_test.go @@ -0,0 +1,367 @@ +package student_tests + +import ( + "bytes" + "encoding/json" + "fmt" + "io" + "net/http" + "net/http/httptest" + "sync" + "testing" + + "mtusi2026lab2/internal/domain" + "mtusi2026lab2/internal/store" + "mtusi2026lab2/internal/transport/http/handlers" + "mtusi2026lab2/internal/transport/http/middleware" +) + +// изолированный серв для тестов +func setupTestServer() (*httptest.Server, *store.MemoryStore) { + st := store.NewMemoryStore() + h := handlers.NewHandler(st) + + mux := http.NewServeMux() + mux.HandleFunc("POST /api/v1/users", h.CreateUser) + mux.HandleFunc("GET /api/v1/users/me", middleware.RequireAuth(st, h.GetMe)) + mux.HandleFunc("POST /api/v1/chats", middleware.RequireAuth(st, h.CreateChat)) + mux.HandleFunc("GET /api/v1/chats", middleware.RequireAuth(st, h.ListChats)) + mux.HandleFunc("GET /api/v1/chats/{chat_id}", middleware.RequireAuth(st, h.GetChat)) + mux.HandleFunc("POST /api/v1/chats/{chat_id}/messages", middleware.RequireAuth(st, h.CreateMessage)) + mux.HandleFunc("GET /api/v1/chats/{chat_id}/messages", middleware.RequireAuth(st, h.GetMessages)) + + var root http.Handler = mux + root = middleware.Recovery(root) + root = middleware.RequestID(root) + + return httptest.NewServer(root), st +} + +// 1 тест на дубликат username -> 409 Conflict +func TestDuplicateUsername(t *testing.T) { + ts, _ := setupTestServer() + defer ts.Close() + + body := `{"username":"bob_the_builder","display_name":"Боб"}` + + // Первый раз — 201 Created + res1, _ := http.Post(ts.URL+"/api/v1/users", "application/json", bytes.NewBufferString(body)) + if res1.StatusCode != http.StatusCreated { + t.Fatalf("expected 201, got %d", res1.StatusCode) + } + + // Второй раз тот же username — 409 Conflict + res2, _ := http.Post(ts.URL+"/api/v1/users", "application/json", bytes.NewBufferString(body)) + if res2.StatusCode != http.StatusConflict { + t.Fatalf("expected 409 Conflict for duplicate username, got %d", res2.StatusCode) + } +} + +// 2 тест на неверный JSON и лишние поля -> 400 Invalid Request +func TestInvalidAndExtraJSON(t *testing.T) { + ts, _ := setupTestServer() + defer ts.Close() + + // Кривой JSON (malformed) + res1, _ := http.Post(ts.URL+"/api/v1/users", "application/json", bytes.NewBufferString(`{"username": "bad"`)) + if res1.StatusCode != http.StatusBadRequest { + t.Fatalf("expected 400 for malformed json, got %d", res1.StatusCode) + } + + // Лишнее поле "age" (проверка DisallowUnknownFields) + res2, _ := http.Post(ts.URL+"/api/v1/users", "application/json", bytes.NewBufferString(`{"username":"valid_user","display_name":"User","age":25}`)) + if res2.StatusCode != http.StatusBadRequest { + t.Fatalf("expected 400 for extra fields, got %d", res2.StatusCode) + } +} + +// 3 тст на пустое сообщение и сообщение из одних пробелов -> 400 Invalid Request +func TestEmptyMessageValidation(t *testing.T) { + ts, st := setupTestServer() + defer ts.Close() + + u, _ := st.CreateUser("user_msg_test", "Tester") + chat, _ := st.CreateChat("Test Chat", []string{u.ID}) + + // Пустой текст + req, _ := http.NewRequest(http.MethodPost, fmt.Sprintf("%s/api/v1/chats/%s/messages", ts.URL, chat.ID), bytes.NewBufferString(`{"text":""}`)) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("X-User-Id", u.ID) + + res, _ := http.DefaultClient.Do(req) + if res.StatusCode != http.StatusBadRequest { + t.Fatalf("expected 400 for empty text, got %d", res.StatusCode) + } + + // Текст только из пробелов + reqSpaces, _ := http.NewRequest(http.MethodPost, fmt.Sprintf("%s/api/v1/chats/%s/messages", ts.URL, chat.ID), bytes.NewBufferString(`{"text":" "}`)) + reqSpaces.Header.Set("Content-Type", "application/json") + reqSpaces.Header.Set("X-User-Id", u.ID) + + resSpaces, _ := http.DefaultClient.Do(reqSpaces) + if resSpaces.StatusCode != http.StatusBadRequest { + t.Fatalf("expected 400 for whitespace-only text, got %d", resSpaces.StatusCode) + } +} + +// 4 тест: чужой чат для постороннего -> 404 Not Found (не 403!) +func TestOutsiderChatAccess(t *testing.T) { + ts, st := setupTestServer() + defer ts.Close() + + alice, _ := st.CreateUser("alice_secret", "Алиса") + eve, _ := st.CreateUser("eve_eavesdropper", "Ева") + + chat, _ := st.CreateChat("Секретный чат", []string{alice.ID}) + + // Ева пытается прочитать чат Алисы + req, _ := http.NewRequest(http.MethodGet, fmt.Sprintf("%s/api/v1/chats/%s", ts.URL, chat.ID), nil) + req.Header.Set("X-User-Id", eve.ID) + + res, _ := http.DefaultClient.Do(req) + if res.StatusCode != http.StatusNotFound { + t.Fatalf("expected 404 Not Found (no leak via 403), got %d", res.StatusCode) + } +} + +// 5 Тест: пагинация по нескольким страницам с курсором +func TestCursorPaginationMultiplePages(t *testing.T) { + ts, st := setupTestServer() + defer ts.Close() + + u, _ := st.CreateUser("paging_user", "Пейджер") + chat, _ := st.CreateChat("Чат пагинации", []string{u.ID}) + + // Отправляем 5 сообщений + for i := 1; i <= 5; i++ { + st.CreateMessage(chat.ID, u.ID, fmt.Sprintf("Message %d", i)) + } + + // Запрашиваем порциями по limit=2 + var allReceived []string + cursor := "" + + for { + url := fmt.Sprintf("%s/api/v1/chats/%s/messages?limit=2", ts.URL, chat.ID) + if cursor != "" { + url += "&cursor=" + cursor + } + + req, _ := http.NewRequest(http.MethodGet, url, nil) + req.Header.Set("X-User-Id", u.ID) + res, _ := http.DefaultClient.Do(req) + + var page domain.MessagePage + body, _ := io.ReadAll(res.Body) + json.Unmarshal(body, &page) + res.Body.Close() + + for _, m := range page.Items { + allReceived = append(allReceived, m.Text) + } + + if page.NextCursor == nil { + break + } + cursor = *page.NextCursor + } + + if len(allReceived) != 5 { + t.Fatalf("expected 5 messages total across pages, got %d", len(allReceived)) + } +} + +// 6 тест: 100 сообщений от 10 клиентов одновременно, защита от гонок +func TestConcurrent100MessagesFrom10Clients(t *testing.T) { + ts, st := setupTestServer() + defer ts.Close() + + // Создаем 10 пользователей + var memberIDs []string + for i := 0; i < 10; i++ { + u, _ := st.CreateUser(fmt.Sprintf("client_%d", i), fmt.Sprintf("Client %d", i)) + memberIDs = append(memberIDs, u.ID) + } + + chat, err := st.CreateChat("Highload Chat", memberIDs) + if err != nil { + t.Fatalf("failed to create chat: %v", err) + } + + var wg sync.WaitGroup + totalClients := 10 + messagesPerClient := 10 + + for i := 0; i < totalClients; i++ { + wg.Add(1) + clientID := memberIDs[i] + + go func(senderID string, clientIndex int) { + defer wg.Done() + + for m := 0; m < messagesPerClient; m++ { + text := fmt.Sprintf("Client %d - Message %d", clientIndex, m) + payload := fmt.Sprintf(`{"text":"%s"}`, text) + + req, _ := http.NewRequest( + http.MethodPost, + fmt.Sprintf("%s/api/v1/chats/%s/messages", ts.URL, chat.ID), + bytes.NewBufferString(payload), + ) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("X-User-Id", senderID) + + res, err := http.DefaultClient.Do(req) + if err != nil || res.StatusCode != http.StatusCreated { + t.Errorf("failed to send concurrent message: %v", err) + } + if res != nil { + res.Body.Close() + } + } + }(clientID, i) + } + + wg.Wait() + + // должно быть 100 сообщений в чате + page, err := st.GetMessages(chat.ID, memberIDs[0], 200, "") + if err != nil { + t.Fatalf("failed to get messages: %v", err) + } + + if len(page.Items) != 100 { + t.Fatalf("RACE CONDITION DETECTED: expected exactly 100 messages, got %d", len(page.Items)) + } + + // уникальность ID + seenIDs := make(map[string]bool) + for _, m := range page.Items { + if seenIDs[m.ID] { + t.Fatalf("duplicate message ID found: %s", m.ID) + } + seenIDs[m.ID] = true + } +} + +// 7 тест: защита от подделки курсора (чужой чат или битый Base64) -> 400 +func TestForeignAndMalformedCursor(t *testing.T) { + ts, st := setupTestServer() + defer ts.Close() + + u, _ := st.CreateUser("cursor_tester", "Tester") + chatA, _ := st.CreateChat("Chat A", []string{u.ID}) + chatB, _ := st.CreateChat("Chat B", []string{u.ID}) + + // В Чат А кладем несколько сообщений, чтобы при limit=1 появился NextCursor + st.CreateMessage(chatA.ID, u.ID, "Message 1 in A") + st.CreateMessage(chatA.ID, u.ID, "Message 2 in A") + st.CreateMessage(chatA.ID, u.ID, "Message 3 in A") + st.CreateMessage(chatA.ID, u.ID, "Message 4 in A") + st.CreateMessage(chatA.ID, u.ID, "Message 5 in A") + + st.CreateMessage(chatB.ID, u.ID, "Message 1 in B") + st.CreateMessage(chatB.ID, u.ID, "Message 2 in B") + + // Получаем валидный курсор из Чата А (запрашиваем 1 из 2) + pageA, err := st.GetMessages(chatA.ID, u.ID, 1, "") + if err != nil || pageA.NextCursor == nil { + t.Fatalf("expected next_cursor in Chat A, err: %v", err) + } + + // 1. Пытаемся применить курсор от Чата А к Чату Б -> строго 400! + urlForeign := fmt.Sprintf("%s/api/v1/chats/%s/messages?cursor=%s", ts.URL, chatB.ID, *pageA.NextCursor) + reqForeign, _ := http.NewRequest(http.MethodGet, urlForeign, nil) + reqForeign.Header.Set("X-User-Id", u.ID) + resForeign, _ := http.DefaultClient.Do(reqForeign) + + if resForeign.StatusCode != http.StatusBadRequest { + t.Fatalf("expected 400 for foreign chat cursor, got %d", resForeign.StatusCode) + } + + // 2. Битый (невалидный) Base64 -> 400 + urlBad := fmt.Sprintf("%s/api/v1/chats/%s/messages?cursor=not-a-valid-base64!@#", ts.URL, chatB.ID) + reqBad, _ := http.NewRequest(http.MethodGet, urlBad, nil) + reqBad.Header.Set("X-User-Id", u.ID) + resBad, _ := http.DefaultClient.Do(reqBad) + + if resBad.StatusCode != http.StatusBadRequest { + t.Fatalf("expected 400 for malformed cursor, got %d", resBad.StatusCode) + } +} + +// 8 тест валидации создания чата (создателя нет в списке / несуществующий юзер / дубликат) -> 400 +func TestChatCreationValidation(t *testing.T) { + ts, st := setupTestServer() + defer ts.Close() + + alice, _ := st.CreateUser("alice_chat_val", "Alice") + bob, _ := st.CreateUser("bob_chat_val", "Bob") + + // 1. Создатель (Alice) забыла добавить себя в member_ids + bodyNoCaller := fmt.Sprintf(`{"title":"No Caller Chat","member_ids":["%s"]}`, bob.ID) + req1, _ := http.NewRequest(http.MethodPost, ts.URL+"/api/v1/chats", bytes.NewBufferString(bodyNoCaller)) + req1.Header.Set("Content-Type", "application/json") + req1.Header.Set("X-User-Id", alice.ID) + res1, _ := http.DefaultClient.Do(req1) + if res1.StatusCode != http.StatusBadRequest { + t.Fatalf("expected 400 when caller is not in member_ids, got %d", res1.StatusCode) + } + + // 2. В участниках передан несуществующий UUID + bodyFakeUser := fmt.Sprintf(`{"title":"Fake User Chat","member_ids":["%s","00000000-0000-0000-0000-000000000000"]}`, alice.ID) + req2, _ := http.NewRequest(http.MethodPost, ts.URL+"/api/v1/chats", bytes.NewBufferString(bodyFakeUser)) + req2.Header.Set("Content-Type", "application/json") + req2.Header.Set("X-User-Id", alice.ID) + res2, _ := http.DefaultClient.Do(req2) + if res2.StatusCode != http.StatusBadRequest { + t.Fatalf("expected 400 for non-existent member_id, got %d", res2.StatusCode) + } + + // 3. Дубликат участника в списке + bodyDuplicate := fmt.Sprintf(`{"title":"Duplicate Member","member_ids":["%s","%s"]}`, alice.ID, alice.ID) + req3, _ := http.NewRequest(http.MethodPost, ts.URL+"/api/v1/chats", bytes.NewBufferString(bodyDuplicate)) + req3.Header.Set("Content-Type", "application/json") + req3.Header.Set("X-User-Id", alice.ID) + res3, _ := http.DefaultClient.Do(req3) + if res3.StatusCode != http.StatusBadRequest { + t.Fatalf("expected 400 for duplicate member_ids, got %d", res3.StatusCode) + } +} + +// 9 тест лимитов символов Unicode (длина до 4000 рун и отказ при >4000) +func TestUnicodeLimits(t *testing.T) { + ts, st := setupTestServer() + defer ts.Close() + + u, _ := st.CreateUser("unicode_master", "Иван 🚀") + chat, _ := st.CreateChat("Unicode Chat", []string{u.ID}) + + // Ровно 4000 смайликов (в байтах это 16000 байт, но в рунах — ровно 4000!) + validRunes := make([]rune, 4000) + for i := range validRunes { + validRunes[i] = '🔥' + } + bodyValid := fmt.Sprintf(`{"text":"%s"}`, string(validRunes)) + req1, _ := http.NewRequest(http.MethodPost, fmt.Sprintf("%s/api/v1/chats/%s/messages", ts.URL, chat.ID), bytes.NewBufferString(bodyValid)) + req1.Header.Set("Content-Type", "application/json") + req1.Header.Set("X-User-Id", u.ID) + res1, _ := http.DefaultClient.Do(req1) + if res1.StatusCode != http.StatusCreated { + t.Fatalf("expected 201 for 4000 unicode runes, got %d", res1.StatusCode) + } + + // 4001 символ -> строго 400 Invalid Request! + tooLongRunes := make([]rune, 4001) + for i := range tooLongRunes { + tooLongRunes[i] = 'a' + } + bodyTooLong := fmt.Sprintf(`{"text":"%s"}`, string(tooLongRunes)) + req2, _ := http.NewRequest(http.MethodPost, fmt.Sprintf("%s/api/v1/chats/%s/messages", ts.URL, chat.ID), bytes.NewBufferString(bodyTooLong)) + req2.Header.Set("Content-Type", "application/json") + req2.Header.Set("X-User-Id", u.ID) + res2, _ := http.DefaultClient.Do(req2) + if res2.StatusCode != http.StatusBadRequest { + t.Fatalf("expected 400 for 4001 runes, got %d", res2.StatusCode) + } +}